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 System.Diagnostics;
using System.Runtime.InteropServices;
namespace tweetz5.Utilities.System
{
public static class NativeMethods
{
[DllImport("user32.dll")]
internal static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, IntPtr dwExtraInfo);
[StructLayout(LayoutKind.Sequential)]
internal struct OsVersioninfo
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szCSDVersion;
}
[DllImport("kernel32.Dll")]
internal static extern short GetVersionEx(ref OsVersioninfo o);
public static string GetServicePack()
{
try
{
var os = new OsVersioninfo {dwOSVersionInfoSize = Marshal.SizeOf(typeof (OsVersioninfo))};
GetVersionEx(ref os);
return (os.szCSDVersion == "") ? "No Service Pack detected" : os.szCSDVersion;
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
return "Service pack version unavailable";
}
}
}
} | 33.390244 | 107 | 0.580716 | [
"MIT"
] | mike-ward/tweetz-desktop | tweetz/tweetz5/Utilities/System/NativeMethods.cs | 1,371 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace F1toPCO.Util
{
public enum HttpRequestMethod {
GET,
POST,
PUT,
DELETE
}
} | 14.857143 | 33 | 0.634615 | [
"MIT"
] | jbenton4579/f1-pco | F1toPCO/Util/HttpRequestMethod.cs | 210 | C# |
using MathNet.Spatial.Euclidean;
using SynthesisAPI.EnvironmentManager.Components;
using System.Collections.Generic;
namespace SynthesisCore.Meshes
{
public static class Cube
{
public static Mesh Make(Mesh m)
{
if (m == null)
m = new Mesh();
m.Vertices = new List<Vector3D>()
{
new Vector3D(-0.5,-0.5,-0.5),
new Vector3D(0.5,-0.5,-0.5),
new Vector3D(0.5,0.5,-0.5),
new Vector3D(-0.5,0.5,-0.5),
new Vector3D(-0.5,0.5,0.5),
new Vector3D(0.5,0.5,0.5),
new Vector3D(0.5,-0.5,0.5),
new Vector3D(-0.5,-0.5,0.5)
};
m.Triangles = new List<int>()
{
0, 2, 1, //face front
0, 3, 2,
2, 3, 4, //face top3
2, 4, 5,
1, 2, 5, //face right
1, 5, 6,
0, 7, 4, //face left
0, 4, 3,
5, 4, 7, //face back
5, 7, 6,
0, 6, 7, //face bottom
0, 1, 6
};
return m;
}
}
}
| 26.311111 | 49 | 0.393581 | [
"Apache-2.0"
] | Autodesk/synthesis | modules/SynthesisCore/Meshes/Cube.cs | 1,186 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Compute.Fluent.Snapshot.Definition;
using Microsoft.Azure.Management.Compute.Fluent.Snapshot.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Rest;
internal partial class SnapshotImpl
{
/// <summary>
/// Specifies the operating system type.
/// </summary>
/// <param name="osType">Operating system type.</param>
/// <return>The next stage of the update.</return>
Snapshot.Update.IUpdate Snapshot.Update.IWithOSSettings.WithOSType(OperatingSystemTypes osType)
{
return this.WithOSType(osType);
}
/// <summary>
/// Specifies the source data managed snapshot.
/// </summary>
/// <param name="snapshotId">A snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithDataSnapshotFromSnapshot.WithDataFromSnapshot(string snapshotId)
{
return this.WithDataFromSnapshot(snapshotId);
}
/// <summary>
/// Specifies the source data managed snapshot.
/// </summary>
/// <param name="snapshot">A snapshot resource.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithDataSnapshotFromSnapshot.WithDataFromSnapshot(ISnapshot snapshot)
{
return this.WithDataFromSnapshot(snapshot);
}
/// <summary>
/// Specifies the source data VHD.
/// </summary>
/// <param name="vhdUrl">A source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithDataSnapshotFromVhd.WithDataFromVhd(string vhdUrl)
{
return this.WithDataFromVhd(vhdUrl);
}
/// <summary>
/// Gets the snapshot creation method.
/// </summary>
Models.DiskCreateOption Microsoft.Azure.Management.Compute.Fluent.ISnapshot.CreationMethod
{
get
{
return this.CreationMethod();
}
}
/// <summary>
/// Gets disk size in GB.
/// </summary>
int Microsoft.Azure.Management.Compute.Fluent.ISnapshot.SizeInGB
{
get
{
return this.SizeInGB();
}
}
/// <summary>
/// Gets the snapshot SKU type.
/// </summary>
Models.DiskSkuTypes Microsoft.Azure.Management.Compute.Fluent.ISnapshot.Sku
{
get
{
return this.Sku();
}
}
/// <summary>
/// Gets the details of the source from which snapshot is created.
/// </summary>
Models.CreationSource Microsoft.Azure.Management.Compute.Fluent.ISnapshot.Source
{
get
{
return this.Source();
}
}
/// <summary>
/// Revoke access granted to the snapshot.
/// </summary>
void Microsoft.Azure.Management.Compute.Fluent.ISnapshot.RevokeAccess()
{
this.RevokeAccess();
}
/// <summary>
/// Grants access to the snapshot.
/// </summary>
/// <param name="accessDurationInSeconds">The access duration in seconds.</param>
/// <return>The read-only SAS URI to the snapshot.</return>
string Microsoft.Azure.Management.Compute.Fluent.ISnapshot.GrantAccess(int accessDurationInSeconds)
{
return this.GrantAccess(accessDurationInSeconds);
}
/// <summary>
/// Revoke access granted to the snapshot asynchronously.
/// </summary>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Compute.Fluent.ISnapshot.RevokeAccessAsync(CancellationToken cancellationToken)
{
await this.RevokeAccessAsync(cancellationToken);
}
/// <summary>
/// Grants access to the snapshot asynchronously.
/// </summary>
/// <param name="accessDurationInSeconds">The access duration in seconds.</param>
/// <return>A representation of the deferred computation of this call returning a read-only SAS URI to the disk.</return>
async Task<string> Microsoft.Azure.Management.Compute.Fluent.ISnapshot.GrantAccessAsync(int accessDurationInSeconds, CancellationToken cancellationToken)
{
return await this.GrantAccessAsync(accessDurationInSeconds, cancellationToken);
}
/// <summary>
/// Gets the type of operating system in the snapshot.
/// </summary>
Models.OperatingSystemTypes? Microsoft.Azure.Management.Compute.Fluent.ISnapshot.OSType
{
get
{
return this.OSType();
}
}
/// <summary>
/// Specifies the ID of source data managed disk.
/// </summary>
/// <param name="managedDiskId">Source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithDataSnapshotFromDisk.WithDataFromDisk(string managedDiskId)
{
return this.WithDataFromDisk(managedDiskId);
}
/// <summary>
/// Specifies the source data managed disk.
/// </summary>
/// <param name="managedDisk">A source managed disk.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithDataSnapshotFromDisk.WithDataFromDisk(IDisk managedDisk)
{
return this.WithDataFromDisk(managedDisk);
}
/// <summary>
/// Specifies the SKU type.
/// </summary>
/// <param name="sku">SKU type.</param>
/// <return>The next stage of the update.</return>
[System.Obsolete("Update.IWithSku.WithSku(DiskSkuTypes) is deprecated use Update.IWithSku.WithSku(SnapshotSkuType) instead.")]
Snapshot.Update.IUpdate Snapshot.Update.IWithSku.WithSku(DiskSkuTypes sku)
{
return this.WithSku(sku);
}
/// <summary>
/// Specifies the SKU type.
/// </summary>
/// <param name="sku">SKU type.</param>
/// <return>The next stage of the update.</return>
Snapshot.Update.IUpdate Snapshot.Update.IWithSku.WithSku(SnapshotSkuType sku)
{
return this.WithSku(sku);
}
/// <summary>
/// Specifies the SKU type.
/// </summary>
/// <deprecated>Use WithSku.withSku(SnapshotSkuType) instead.</deprecated>
/// <param name="sku">SKU type.</param>
/// <return>The next stage of the definition.</return>
[System.Obsolete("Definition.IWithSku.WithSku(DiskSkuTypes) is deprecated use Definition.IWithSku.WithSku(SnapshotSkuType) instead.")]
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithSku.WithSku(DiskSkuTypes sku)
{
return this.WithSku(sku);
}
/// <summary>
/// Specifies the SKU type.
/// </summary>
/// <param name="sku">SKU type.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithSku.WithSku(SnapshotSkuType sku)
{
return this.WithSku(sku);
}
/// <summary>
/// Gets the snapshot SKU type.
/// </summary>
Microsoft.Azure.Management.Compute.Fluent.SnapshotSkuType Microsoft.Azure.Management.Compute.Fluent.ISnapshot.SkuType
{
get
{
return this.SkuType();
}
}
/// <summary>
/// Specifies the disk size.
/// </summary>
/// <param name="sizeInGB">The disk size in GB.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithSize.WithSizeInGB(int sizeInGB)
{
return this.WithSizeInGB(sizeInGB);
}
/// <summary>
/// Specifies the source Linux OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshotId">A snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithLinuxSnapshotSource.WithLinuxFromSnapshot(string sourceSnapshotId)
{
return this.WithLinuxFromSnapshot(sourceSnapshotId);
}
/// <summary>
/// Specifies the source Linux OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshot">A source snapshot.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithLinuxSnapshotSource.WithLinuxFromSnapshot(ISnapshot sourceSnapshot)
{
return this.WithLinuxFromSnapshot(sourceSnapshot);
}
/// <summary>
/// Specifies the source specialized or generalized Linux OS VHD.
/// </summary>
/// <param name="vhdUrl">The source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithLinuxSnapshotSource.WithLinuxFromVhd(string vhdUrl)
{
return this.WithLinuxFromVhd(vhdUrl);
}
/// <summary>
/// Specifies the source Linux OS managed disk.
/// </summary>
/// <param name="sourceDiskId">A source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithLinuxSnapshotSource.WithLinuxFromDisk(string sourceDiskId)
{
return this.WithLinuxFromDisk(sourceDiskId);
}
/// <summary>
/// Specifies the source Linux OS managed disk.
/// </summary>
/// <param name="sourceDisk">A source managed disk.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithLinuxSnapshotSource.WithLinuxFromDisk(IDisk sourceDisk)
{
return this.WithLinuxFromDisk(sourceDisk);
}
/// <summary>
/// Specifies the source specialized or generalized Windows OS VHD.
/// </summary>
/// <param name="vhdUrl">The source VHD URL.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithWindowsSnapshotSource.WithWindowsFromVhd(string vhdUrl)
{
return this.WithWindowsFromVhd(vhdUrl);
}
/// <summary>
/// Specifies the source Windows OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshotId">A snapshot resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithWindowsSnapshotSource.WithWindowsFromSnapshot(string sourceSnapshotId)
{
return this.WithWindowsFromSnapshot(sourceSnapshotId);
}
/// <summary>
/// Specifies the source Windows OS managed snapshot.
/// </summary>
/// <param name="sourceSnapshot">A source snapshot.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithWindowsSnapshotSource.WithWindowsFromSnapshot(ISnapshot sourceSnapshot)
{
return this.WithWindowsFromSnapshot(sourceSnapshot);
}
/// <summary>
/// Specifies the source Windows OS managed disk.
/// </summary>
/// <param name="sourceDiskId">A source managed disk resource ID.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithWindowsSnapshotSource.WithWindowsFromDisk(string sourceDiskId)
{
return this.WithWindowsFromDisk(sourceDiskId);
}
/// <summary>
/// Specifies the source Windows OS managed disk.
/// </summary>
/// <param name="sourceDisk">A source managed disk.</param>
/// <return>The next stage of the definition.</return>
Snapshot.Definition.IWithCreate Snapshot.Definition.IWithWindowsSnapshotSource.WithWindowsFromDisk(IDisk sourceDisk)
{
return this.WithWindowsFromDisk(sourceDisk);
}
}
} | 39.540541 | 161 | 0.619048 | [
"MIT"
] | shemseddine/azure-libraries-for-net | src/ResourceManagement/Compute/Domain/InterfaceImpl/SnapshotImpl.cs | 13,167 | C# |
// ReSharper disable UnusedMember.Global
#pragma warning disable 1591
namespace Bauland.Others
{
namespace Constants.MfRc522
{
/// <summary>
/// Address of register
/// </summary>
public enum Register
{
// Command and status
Command = 0x01 << 1,
ComIrq = 0x04 << 1,
DivIrq = 0x05 << 1,
Error = 0x06 << 1,
Status1 = 0x07 << 1,
Status2 = 0x08 << 1,
FifoData = 0x09 << 1,
FifoLevel = 0x0A << 1,
Control = 0x0C << 1,
BitFraming = 0x0D << 1,
Coll = 0x0E << 1,
Mode = 0x11 << 1,
TxMode = 0x12 << 1,
RxMode = 0x13 << 1,
TxControl = 0x14 << 1,
TxAsk = 0x15 << 1,
Version = 0x37 << 1,
CrcResultHigh = 0x21 << 1,
CrcResultLow = 0x22 << 1,
ModeWith = 0x24 << 1,
TimerMode = 0x2A << 1,
TimerPrescaler = 0x2B << 1,
TimerReloadHigh = 0x2C << 1,
TimerReloadLow = 0x2D << 1,
}
/// <summary>
/// Return code of some functions
/// </summary>
public enum StatusCode
{
Ok,
Collision,
Error,
Timeout,
NoRoom,
CrcError
}
/// <summary>
/// Command to send to picc (card)
/// </summary>
public enum PiccCommand
{
ReqA = 0x26,
MifareRead = 0x30,
HaltA = 0x50,
AuthenticateKeyA = 0x60,
AuthenticateKeyB = 0x61,
SelCl1 = 0x93,
SelCl2 = 0x95,
SelCl3 = 0x97,
}
/// <summary>
/// Command of reader
/// </summary>
public enum PcdCommand
{
Idle = 0x00,
CalculateCrc = 0x03,
Transceive = 0x0c,
MfAuthenticate = 0xe,
}
/// <summary>
/// Length of uid
/// </summary>
public enum UidType
{
T4 = 4,
T7 = 7,
T10 = 10
}
/// <summary>
/// Type of card
/// </summary>
public enum PiccType
{
Unknown,
Mifare1K,
MifareUltralight
}
/// <summary>
///
/// </summary>
public class Uid
{
/// <summary>
/// Lentgh of uid (can be 4, 7 or 10 bytes length)
/// </summary>
public UidType UidType { get; set; }
/// <summary>
/// Contain uid of card (can be 4, 7 or 10 bytes length)
/// </summary>
public byte[] UidBytes { get; set; }
/// <summary>
/// Sak which contains usefull informations
/// </summary>
public byte Sak { get; set; }
/// <summary>
/// Get type of card
/// </summary>
/// <returns>Type of card</returns>
public PiccType GetPiccType()
{
var sak = Sak & 0x7f;
switch (sak)
{
case 0x08:
return PiccType.Mifare1K;
case 0x00:
return PiccType.MifareUltralight;
default:
return PiccType.Unknown;
}
}
}
}
}
| 25.092199 | 68 | 0.399096 | [
"Apache-2.0",
"MIT"
] | bauland/TinyClrLib | Modules/Others/MfRc522/Constant.cs | 3,540 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AudioDuck
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 23.782609 | 66 | 0.59415 | [
"MIT"
] | TominoCZ/AudioDuck | AudioDuck/Program.cs | 549 | C# |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
namespace Prota.Animation
{
public class AnimTextureImporter : AssetPostprocessor
{
void OnPreprocessTexture()
{
if(!assetImporter.assetPath.Contains("/Animation/")) return;
var importer = assetImporter as TextureImporter;
importer.filterMode = FilterMode.Bilinear;
importer.textureCompression = TextureImporterCompression.Uncompressed;
importer.mipmapEnabled = true;
importer.textureType = TextureImporterType.Sprite;
importer.spriteImportMode = SpriteImportMode.Single;
importer.spritePixelsPerUnit = 128;
if(importer.assetPath.Contains("_Anchor_") || importer.assetPath.Contains("_anchor_"))
{
importer.isReadable = true;
}
}
}
} | 29.764706 | 99 | 0.582016 | [
"MIT"
] | DragoonKiller/ProtaFramework | SimpleAnimation/Editor/AnimTextureImporter.cs | 1,012 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Linq;
using ACTransit.Contracts.Data.CusRel.TicketContract;
using ACTransit.Contracts.Data.CusRel.UserContract;
using ACTransit.DataAccess.CustomerRelations;
using ACTransit.Entities.CustomerRelations;
using ACTransit.Framework.Extensions;
using ACTransit.Framework.Web.Helpers;
namespace ACTransit.CusRel.Repositories.Mapping
{
public class TicketEntities
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public tblContacts Contact { get; set; }
public List<tblAttachments> Attachments;
public List<tblContactHistory> ResponseHistory;
public List<tblResearchHistory> ResearchHistory;
public List<tblIncidentUpdateHistory> IncidentUpdateHistory;
public List<tblLinkedContacts> LinkedContacts;
public List<tblUpdateLog> ChangeHistory;
public ChangeTracking Changes = new ChangeTracking();
// -------------------------------------------------------------------
#region Static Conversions
public static tblAttachments ToAttachment(Attachment Attachment, Ticket Ticket)
{
return new tblAttachments
{
FileNum = Ticket.Id,
AttachmentNum = Attachment.Id,
FileName = Attachment.Filename,
FileSize = Attachment.IsNew && Attachment.ShouldDelete
? -2 // -2 = ignore
: (!Attachment.IsNew && Attachment.ShouldDelete
? -1 // -1 to mark for deletion?
: Attachment.Data.Length),
ContentType = MimeHelper.GetMimeType(Attachment.Filename),
BinaryData = Attachment.Data,
DateUploaded = Attachment.UploadedAt ?? DateTime.Now,
Description = Attachment.Description,
UploadedBy = Attachment.UploadedBy != null ? Attachment.UploadedBy.Id : (Ticket.UpdatedBy != null ? Ticket.UpdatedBy.Id : null)
};
}
public static Attachment FromAttachment(tblAttachments Attachment)
{
return new Attachment
{
Id = Attachment.AttachmentNum,
Filename = Attachment.FileName,
Data = Attachment.BinaryData,
UploadedAt = Attachment.DateUploaded,
UploadedBy = new User(Id: Attachment.UploadedBy),
Description = Attachment.Description
};
}
// -------------------------------------------------------------------
public static tblContactHistory ToContactHistory(ResponseHistory ResponseHistory, Ticket Ticket)
{
return new tblContactHistory
{
FileNum = Ticket.Id,
Id = ResponseHistory.Id,
UserId = ResponseHistory.ResponseBy.Id != null ? ResponseHistory.ResponseBy.Id.TrimEnd() : null,
ContactDateTime = ResponseHistory.ResponseAt,
Via = ResponseHistory.Via.ToString(),
Comment = ResponseHistory.Comment
};
}
public static ResponseHistory FromContactHistory(tblContactHistory ContactHistory, string contactStatus = null)
{
return new ResponseHistory
{
Id = ContactHistory.Id,
ResponseBy = new User(Id: ContactHistory.UserId != null ? ContactHistory.UserId.TrimEnd() : null),
ResponseAt = ContactHistory.ContactDateTime,
Via = ToResponseHistoryVia(ContactHistory.Via),
ViaAsString = !string.IsNullOrEmpty(contactStatus) ? contactStatus : ContactHistory.Via.Trim().PascalCaseToDescription(),
Comment = ContactHistory.Comment
};
}
public static ResponseHistoryVia ToResponseHistoryVia(string contactHistoryVia)
{
var via = contactHistoryVia.NullableTrim().EnumParse(ResponseHistoryVia.Unknown);
if (via != ResponseHistoryVia.Unknown)
return via;
switch (contactHistoryVia.NullableTrim())
{
case "":
return ResponseHistoryVia.NotApplicable;
case "None":
return ResponseHistoryVia.NotApplicable;
//case "Email":
// return ResponseHistoryVia.SentEmail;
//case "Letter":
// return ResponseHistoryVia.SentLetter;
//case "Phone":
// return ResponseHistoryVia.CalledLeftMessage;
}
return ResponseHistoryVia.Unknown;
}
// -------------------------------------------------------------------
public static tblResearchHistory ToResearchHistory(ResearchHistory ResearchHistory, Ticket Ticket)
{
return new tblResearchHistory
{
FileNum = Ticket.Id,
Id = ResearchHistory.Id,
UserId = ResearchHistory.ResearchedBy.Id != null ? ResearchHistory.ResearchedBy.Id.TrimEnd() : null,
EnteredDateTime = ResearchHistory.ResearchedAt,
Comment = ResearchHistory.Comment
};
}
public static ResearchHistory FromResearchHistory(tblResearchHistory ResearchHistory)
{
return new ResearchHistory
{
Id = ResearchHistory.Id,
ResearchedBy = new User(Id: ResearchHistory.UserId != null ? ResearchHistory.UserId.TrimEnd() : null),
ResearchedAt = ResearchHistory.EnteredDateTime,
Comment = ResearchHistory.Comment
};
}
// -------------------------------------------------------------------
public static tblLinkedContacts ToLinkedContact(Ticket ParentTicket, Ticket ChildTicket)
{
return new tblLinkedContacts
{
Id = ChildTicket.LinkedId ?? 0,
FileNum = ParentTicket.Id,
LinkedFileNum = ChildTicket.Id,
Active = !ChildTicket.ShouldUnlink
};
}
public static Ticket FromLinkedContact(tblLinkedContacts Contact)
{
return new Ticket
{
Id = Contact.LinkedFileNum, // LinkedFileNum is child's FileNum
ShouldUnlink = !Contact.Active,
LinkedId = Contact.Id
};
}
public static List<Ticket> FromLinkedContacts(List<tblLinkedContacts> ChildContacts, int Id)
{
return ChildContacts.Where(c => c.FileNum == Id).Select(FromLinkedContact).ToList();
}
// -------------------------------------------------------------------
public static tblUpdateLog ToChangeHistory(ChangeHistory ChangeHistory, Ticket Ticket)
{
return new tblUpdateLog
{
UserId = ChangeHistory.ChangeBy.Id.Trim(),
FileNum = Ticket.Id,
TableName = ChangeHistory.TableName,
UpdateAction = ChangeHistory.Action,
DateUpdated = ChangeHistory.ChangeAt,
Id = ChangeHistory.Id,
ColumnName = ChangeHistory.ColumnName,
OldValue = ChangeHistory.OldValue,
NewValue = ChangeHistory.NewValue
};
}
public static ChangeHistory FromChangeHistory(tblUpdateLog ChangeHistory)
{
return new ChangeHistory
{
Id = ChangeHistory.Id,
ChangeAt = ChangeHistory.DateUpdated,
ChangeBy = new User(Id: ChangeHistory.UserId),
Action = ChangeHistory.UpdateAction,
TableName = ChangeHistory.TableName,
ColumnName = ChangeHistory.ColumnName,
OldValue = ChangeHistory.OldValue,
NewValue = ChangeHistory.NewValue
};
}
#endregion
// =============================================================
#region Set Logic and Relations
public void PrepareContext(CusRelEntities context)
{
log.Debug("Begin PrepareContext");
try
{
log.Debug(string.Format("Contact.FileNum: {0}", Contact.FileNum));
if (Contact.FileNum >= 0)
{
Contact.updatedOn = DateTime.Now;
context.tblContacts.AddOrUpdate(Contact);
}
if (Contact.FileNum == 0)
return;
if (Attachments != null)
foreach (var item in Attachments)
{
// ignore when item.FileSize is 0
log.Debug(string.Format("Attachment id:{0} ({1}), FileSize:{2}", item.AttachmentNum, item.FileName, item.FileSize));
if (item.FileSize > 0)
{
if (item.DateUploaded == null)
item.DateUploaded = DateTime.Now;
context.tblAttachments.AddOrUpdate(item);
}
else if (item.FileSize == -1)
{
context.tblAttachments.Attach(item);
context.tblAttachments.Remove(item);
}
}
if (ResponseHistory != null)
foreach (var item in ResponseHistory)
{
// deletes not allowed
if (item.ContactDateTime == null)
item.ContactDateTime = DateTime.Now;
context.tblContactHistory.AddOrUpdate(item);
}
if (ResearchHistory != null)
foreach (var item in ResearchHistory)
{
// deletes not allowed
if (item.EnteredDateTime == null)
item.EnteredDateTime = DateTime.Now;
context.tblResearchHistory.AddOrUpdate(item);
}
if (IncidentUpdateHistory != null)
foreach (var item in IncidentUpdateHistory)
{
// deletes not allowed
context.tblIncidentUpdateHistory.AddOrUpdate(item);
}
if (LinkedContacts != null)
foreach (var item in LinkedContacts)
{
if (item.Active)
context.tblLinkedContacts.AddOrUpdate(item);
else
{
context.tblLinkedContacts.Attach(item);
context.tblLinkedContacts.Remove(item);
}
}
// ChangeHistory is read-only, do nothing
}
finally
{
log.Debug("Begin PrepareContext");
}
}
public void DetachObject(CusRelEntities context, object obj)
{
((IObjectContextAdapter)context).ObjectContext.Detach(obj);
}
public void Detach(CusRelEntities context)
{
DetachObject(context, Contact);
if (Attachments != null)
foreach (var item in Attachments)
DetachObject(context, item);
if (ResponseHistory != null)
foreach (var item in ResponseHistory)
DetachObject(context, item);
if (ResearchHistory != null)
foreach (var item in ResearchHistory)
DetachObject(context, item);
if (IncidentUpdateHistory != null)
foreach (var item in IncidentUpdateHistory)
DetachObject(context, item);
if (LinkedContacts != null)
foreach (var item in LinkedContacts)
DetachObject(context, item);
if (ChangeHistory != null)
foreach (var item in ChangeHistory)
DetachObject(context, item);
}
#endregion
// =============================================================
#region Change Tracking
public class ChangeTracking
{
public bool ForAction;
public bool AssignedTo;
public bool Priority;
}
#endregion
// =============================================================
}
}
| 40.947531 | 144 | 0.502902 | [
"MIT"
] | actransitorg/ACTransit.CusRel | CusRel/ACTransit.CusRel.Repositories/Mapping/TicketEntities.cs | 13,269 | C# |
using System.Linq;
using System.Threading.Tasks;
using CleanTemplate.Application.Features.Forecast.Queries;
using CleanTemplate.WebUI.Controllers;
using Microsoft.AspNetCore.Mvc;
namespace CleanTemplate.WebUI.Features.Weather
{
[Route("api/forecast")]
public class WeatherForecastController : ApiController
{
[HttpGet("{location}")]
public async Task<ActionResult<IQueryable<WeatherForecastContract>>> Get(string location)
{
var action = new GetAllForecastForLocationQuery(User?.Identity?.Name, location);
var result = await Mediator.Send(action);
return Ok(result);
}
}
}
| 29.26087 | 97 | 0.68945 | [
"MIT"
] | Leefrost/dotnet-clean-template | src/CleanTemplate.WebUI/Features/Weather/WeatherForecastController.cs | 675 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.WebUtilities
{
// https://www.ietf.org/rfc/rfc2046.txt
/// <summary>
/// Reads multipart form content from the specified <see cref="Stream"/>.
/// </summary>
public class MultipartReader
{
/// <summary>
/// Gets the default value for <see cref="HeadersCountLimit"/>.
/// Defaults to 16.
/// </summary>
public const int DefaultHeadersCountLimit = 16;
/// <summary>
/// Gets the default value for <see cref="HeadersLengthLimit"/>.
/// Defaults to 16,384 bytes, which is approximately 16KB.
/// </summary>
public const int DefaultHeadersLengthLimit = 1024 * 16;
private const int DefaultBufferSize = 1024 * 4;
private readonly BufferedReadStream _stream;
private readonly MultipartBoundary _boundary;
private MultipartReaderStream _currentStream;
/// <summary>
/// Initializes a new instance of <see cref="MultipartReader"/>.
/// </summary>
/// <param name="boundary">The multipart boundary.</param>
/// <param name="stream">The <see cref="Stream"/> containing multipart data.</param>
public MultipartReader(string boundary, Stream stream)
: this(boundary, stream, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of <see cref="MultipartReader"/>.
/// </summary>
/// <param name="boundary">The multipart boundary.</param>
/// <param name="stream">The <see cref="Stream"/> containing multipart data.</param>
/// <param name="bufferSize">The minimum buffer size to use.</param>
public MultipartReader(string boundary, Stream stream, int bufferSize)
{
if (boundary == null)
{
throw new ArgumentNullException(nameof(boundary));
}
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (bufferSize < boundary.Length + 8) // Size of the boundary + leading and trailing CRLF + leading and trailing '--' markers.
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, "Insufficient buffer space, the buffer must be larger than the boundary: " + boundary);
}
_stream = new BufferedReadStream(stream, bufferSize);
_boundary = new MultipartBoundary(boundary, false);
// This stream will drain any preamble data and remove the first boundary marker.
// TODO: HeadersLengthLimit can't be modified until after the constructor.
_currentStream = new MultipartReaderStream(_stream, _boundary) { LengthLimit = HeadersLengthLimit };
}
/// <summary>
/// The limit for the number of headers to read.
/// </summary>
public int HeadersCountLimit { get; set; } = DefaultHeadersCountLimit;
/// <summary>
/// The combined size limit for headers per multipart section.
/// </summary>
public int HeadersLengthLimit { get; set; } = DefaultHeadersLengthLimit;
/// <summary>
/// The optional limit for the total response body length.
/// </summary>
public long? BodyLengthLimit { get; set; }
/// <summary>
/// Reads the next <see cref="MultipartSection"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.
/// The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns></returns>
public async Task<MultipartSection?> ReadNextSectionAsync(CancellationToken cancellationToken = new CancellationToken())
{
// Drain the prior section.
await _currentStream.DrainAsync(cancellationToken);
// If we're at the end return null
if (_currentStream.FinalBoundaryFound)
{
// There may be trailer data after the last boundary.
await _stream.DrainAsync(HeadersLengthLimit, cancellationToken);
return null;
}
var headers = await ReadHeadersAsync(cancellationToken);
_boundary.ExpectLeadingCrlf = true;
_currentStream = new MultipartReaderStream(_stream, _boundary) { LengthLimit = BodyLengthLimit };
long? baseStreamOffset = _stream.CanSeek ? (long?)_stream.Position : null;
return new MultipartSection() { Headers = headers, Body = _currentStream, BaseStreamOffset = baseStreamOffset };
}
private async Task<Dictionary<string, StringValues>> ReadHeadersAsync(CancellationToken cancellationToken)
{
int totalSize = 0;
var accumulator = new KeyValueAccumulator();
var line = await _stream.ReadLineAsync(HeadersLengthLimit - totalSize, cancellationToken);
while (!string.IsNullOrEmpty(line))
{
if (HeadersLengthLimit - totalSize < line.Length)
{
throw new InvalidDataException($"Multipart headers length limit {HeadersLengthLimit} exceeded.");
}
totalSize += line.Length;
int splitIndex = line.IndexOf(':');
if (splitIndex <= 0)
{
throw new InvalidDataException($"Invalid header line: {line}");
}
var name = line.Substring(0, splitIndex);
var value = line.Substring(splitIndex + 1, line.Length - splitIndex - 1).Trim();
accumulator.Append(name, value);
if (accumulator.KeyCount > HeadersCountLimit)
{
throw new InvalidDataException($"Multipart headers count limit {HeadersCountLimit} exceeded.");
}
line = await _stream.ReadLineAsync(HeadersLengthLimit - totalSize, cancellationToken);
}
return accumulator.GetResults();
}
}
}
| 43.675676 | 173 | 0.609994 | [
"Apache-2.0"
] | AshesNord/aspnetcore | src/Http/WebUtilities/src/MultipartReader.cs | 6,470 | 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("Injector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Injector")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[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("15d902f3-90da-4786-8ca1-a91e906f7acf")]
// 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.378378 | 85 | 0.727465 | [
"MIT"
] | JaimeTR/Injector | Injector/Injector/Properties/AssemblyInfo.cs | 1,423 | C# |
namespace Tennis_Open_Data_Standards
{
public interface ITennis
{
}
}
| 11.5 | 37 | 0.619565 | [
"MIT"
] | itftennis/tods | src/Tennis-Open-Data-Standards/ITennis.cs | 94 | C# |
namespace asktomyself
{
partial class main
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components;
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(main));
this.contextMenuStripIcon = new System.Windows.Forms.ContextMenuStrip(this.components);
this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.categoriesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.stopAskToMyselfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.invertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.logOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openWebAccountToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buyMeABeerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.aboutAskToMyselfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.buttonOK = new System.Windows.Forms.Button();
this.lblQuestion = new System.Windows.Forms.Label();
this.lblAnswer = new System.Windows.Forms.Label();
this.txtFrom = new System.Windows.Forms.TextBox();
this.txtTo = new System.Windows.Forms.TextBox();
this.contextMenuStripLogin = new System.Windows.Forms.ContextMenuStrip(this.components);
this.signInToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.aboutAskToMyselfToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.Thunbnail = new System.Windows.Forms.PictureBox();
this.labelCategory = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.btnSolution = new System.Windows.Forms.Button();
this.lblCountdown = new System.Windows.Forms.Label();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.contextMenuStripIcon.SuspendLayout();
this.contextMenuStripLogin.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.Thunbnail)).BeginInit();
this.SuspendLayout();
//
// contextMenuStripIcon
//
this.contextMenuStripIcon.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addToolStripMenuItem,
this.categoriesToolStripMenuItem,
this.stopAskToMyselfToolStripMenuItem,
this.invertToolStripMenuItem,
this.logOutToolStripMenuItem,
this.toolStripMenuItem5,
this.openWebAccountToolStripMenuItem,
this.buyMeABeerToolStripMenuItem,
this.toolStripMenuItem1,
this.aboutAskToMyselfToolStripMenuItem,
this.toolStripMenuItem2,
this.exitToolStripMenuItem});
this.contextMenuStripIcon.Name = "contextMenuStripIcon";
this.contextMenuStripIcon.Size = new System.Drawing.Size(185, 220);
//
// addToolStripMenuItem
//
this.addToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addToolStripMenuItem.Image")));
this.addToolStripMenuItem.Name = "addToolStripMenuItem";
this.addToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.addToolStripMenuItem.Text = "Add";
this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click);
//
// categoriesToolStripMenuItem
//
this.categoriesToolStripMenuItem.Image = global::asktomyself.Properties.Resources.category;
this.categoriesToolStripMenuItem.Name = "categoriesToolStripMenuItem";
this.categoriesToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.categoriesToolStripMenuItem.Text = "Categories";
//
// stopAskToMyselfToolStripMenuItem
//
this.stopAskToMyselfToolStripMenuItem.Name = "stopAskToMyselfToolStripMenuItem";
this.stopAskToMyselfToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.stopAskToMyselfToolStripMenuItem.Text = "Stop ask to myself";
this.stopAskToMyselfToolStripMenuItem.Click += new System.EventHandler(this.stopAskToMyselfToolStripMenuItem_Click);
//
// invertToolStripMenuItem
//
this.invertToolStripMenuItem.CheckOnClick = true;
this.invertToolStripMenuItem.Image = global::asktomyself.Properties.Resources.invert;
this.invertToolStripMenuItem.Name = "invertToolStripMenuItem";
this.invertToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.invertToolStripMenuItem.Text = "Invert";
this.invertToolStripMenuItem.Click += new System.EventHandler(this.invertToolStripMenuItem_Click);
//
// logOutToolStripMenuItem
//
this.logOutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("logOutToolStripMenuItem.Image")));
this.logOutToolStripMenuItem.Name = "logOutToolStripMenuItem";
this.logOutToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.logOutToolStripMenuItem.Text = "Sign out";
this.logOutToolStripMenuItem.Click += new System.EventHandler(this.logOutToolStripMenuItem_Click);
//
// openWebAccountToolStripMenuItem
//
this.openWebAccountToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openWebAccountToolStripMenuItem.Image")));
this.openWebAccountToolStripMenuItem.Name = "openWebAccountToolStripMenuItem";
this.openWebAccountToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.openWebAccountToolStripMenuItem.Text = "Open web account";
this.openWebAccountToolStripMenuItem.Click += new System.EventHandler(this.openWebAccountToolStripMenuItem_Click);
//
// buyMeABeerToolStripMenuItem
//
this.buyMeABeerToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("buyMeABeerToolStripMenuItem.Image")));
this.buyMeABeerToolStripMenuItem.Name = "buyMeABeerToolStripMenuItem";
this.buyMeABeerToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.buyMeABeerToolStripMenuItem.Text = "Buy me a beer";
this.buyMeABeerToolStripMenuItem.Click += new System.EventHandler(this.buyMeABeerToolStripMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(181, 6);
//
// aboutAskToMyselfToolStripMenuItem
//
this.aboutAskToMyselfToolStripMenuItem.Image = global::asktomyself.Properties.Resources.messagebox_info;
this.aboutAskToMyselfToolStripMenuItem.Name = "aboutAskToMyselfToolStripMenuItem";
this.aboutAskToMyselfToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.aboutAskToMyselfToolStripMenuItem.Text = "About Ask To Myself";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(181, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Image = global::asktomyself.Properties.Resources.exit;
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.exitToolStripMenuItem.Text = "Exit";
//
// buttonOK
//
this.buttonOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.buttonOK.Location = new System.Drawing.Point(77, 164);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(75, 23);
this.buttonOK.TabIndex = 1;
this.buttonOK.Text = "Ok";
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click);
//
// lblQuestion
//
this.lblQuestion.AutoSize = true;
this.lblQuestion.BackColor = System.Drawing.Color.Transparent;
this.lblQuestion.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblQuestion.Location = new System.Drawing.Point(13, 51);
this.lblQuestion.Name = "lblQuestion";
this.lblQuestion.Size = new System.Drawing.Size(64, 16);
this.lblQuestion.TabIndex = 2;
this.lblQuestion.Text = "Question:";
//
// lblAnswer
//
this.lblAnswer.AutoSize = true;
this.lblAnswer.BackColor = System.Drawing.Color.Transparent;
this.lblAnswer.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblAnswer.Location = new System.Drawing.Point(13, 100);
this.lblAnswer.Name = "lblAnswer";
this.lblAnswer.Size = new System.Drawing.Size(55, 16);
this.lblAnswer.TabIndex = 3;
this.lblAnswer.Text = "Answer:";
//
// txtFrom
//
this.txtFrom.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtFrom.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtFrom.Location = new System.Drawing.Point(16, 70);
this.txtFrom.Name = "txtFrom";
this.txtFrom.Size = new System.Drawing.Size(229, 22);
this.txtFrom.TabIndex = 4;
//
// txtTo
//
this.txtTo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtTo.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtTo.Location = new System.Drawing.Point(16, 119);
this.txtTo.Name = "txtTo";
this.txtTo.Size = new System.Drawing.Size(229, 22);
this.txtTo.TabIndex = 5;
this.txtTo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtTo_KeyDown);
//
// contextMenuStripLogin
//
this.contextMenuStripLogin.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.signInToolStripMenuItem,
this.toolStripMenuItem4,
this.aboutAskToMyselfToolStripMenuItem1,
this.toolStripMenuItem3,
this.exitToolStripMenuItem1});
this.contextMenuStripLogin.Name = "contextMenuStripLogin";
this.contextMenuStripLogin.Size = new System.Drawing.Size(185, 82);
//
// signInToolStripMenuItem
//
this.signInToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("signInToolStripMenuItem.Image")));
this.signInToolStripMenuItem.Name = "signInToolStripMenuItem";
this.signInToolStripMenuItem.Size = new System.Drawing.Size(184, 22);
this.signInToolStripMenuItem.Text = "Sign In";
this.signInToolStripMenuItem.Click += new System.EventHandler(this.signInToolStripMenuItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(181, 6);
//
// aboutAskToMyselfToolStripMenuItem1
//
this.aboutAskToMyselfToolStripMenuItem1.Image = global::asktomyself.Properties.Resources.messagebox_info;
this.aboutAskToMyselfToolStripMenuItem1.Name = "aboutAskToMyselfToolStripMenuItem1";
this.aboutAskToMyselfToolStripMenuItem1.Size = new System.Drawing.Size(184, 22);
this.aboutAskToMyselfToolStripMenuItem1.Text = "About Ask To Myself";
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(181, 6);
//
// exitToolStripMenuItem1
//
this.exitToolStripMenuItem1.Image = global::asktomyself.Properties.Resources.exit;
this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1";
this.exitToolStripMenuItem1.Size = new System.Drawing.Size(184, 22);
this.exitToolStripMenuItem1.Text = "Exit";
//
// Thunbnail
//
this.Thunbnail.BackColor = System.Drawing.Color.Transparent;
this.Thunbnail.Location = new System.Drawing.Point(269, 42);
this.Thunbnail.Name = "Thunbnail";
this.Thunbnail.Size = new System.Drawing.Size(152, 145);
this.Thunbnail.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.Thunbnail.TabIndex = 6;
this.Thunbnail.TabStop = false;
//
// labelCategory
//
this.labelCategory.AutoSize = true;
this.labelCategory.BackColor = System.Drawing.Color.Transparent;
this.labelCategory.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelCategory.Location = new System.Drawing.Point(90, 11);
this.labelCategory.Name = "labelCategory";
this.labelCategory.Size = new System.Drawing.Size(226, 20);
this.labelCategory.TabIndex = 7;
this.labelCategory.Text = "No category selected right now";
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(12, 11);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(81, 18);
this.label3.TabIndex = 8;
this.label3.Text = "Category:";
//
// btnSolution
//
this.btnSolution.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSolution.Location = new System.Drawing.Point(170, 164);
this.btnSolution.Name = "btnSolution";
this.btnSolution.Size = new System.Drawing.Size(75, 23);
this.btnSolution.TabIndex = 9;
this.btnSolution.Text = "Solution";
this.btnSolution.UseVisualStyleBackColor = true;
this.btnSolution.Click += new System.EventHandler(this.btnSolution_Click);
//
// lblCountdown
//
this.lblCountdown.AutoSize = true;
this.lblCountdown.BackColor = System.Drawing.Color.Transparent;
this.lblCountdown.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblCountdown.Location = new System.Drawing.Point(12, 167);
this.lblCountdown.Name = "lblCountdown";
this.lblCountdown.Size = new System.Drawing.Size(29, 20);
this.lblCountdown.TabIndex = 10;
this.lblCountdown.Text = "15";
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(181, 6);
//
// main
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.ClientSize = new System.Drawing.Size(436, 201);
this.Controls.Add(this.lblCountdown);
this.Controls.Add(this.btnSolution);
this.Controls.Add(this.labelCategory);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.txtTo);
this.Controls.Add(this.label3);
this.Controls.Add(this.Thunbnail);
this.Controls.Add(this.txtFrom);
this.Controls.Add(this.lblAnswer);
this.Controls.Add(this.lblQuestion);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Location = new System.Drawing.Point(10, 10);
this.MaximizeBox = false;
this.Name = "main";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Ask To Myself";
this.Load += new System.EventHandler(this.main_Load);
this.Shown += new System.EventHandler(this.main_Shown);
this.contextMenuStripIcon.ResumeLayout(false);
this.contextMenuStripLogin.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.Thunbnail)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ContextMenuStrip contextMenuStripIcon;
private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Button buttonOK;
private System.Windows.Forms.Label lblQuestion;
private System.Windows.Forms.Label lblAnswer;
private System.Windows.Forms.TextBox txtFrom;
private System.Windows.Forms.TextBox txtTo;
private System.Windows.Forms.ToolStripMenuItem categoriesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem invertToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem stopAskToMyselfToolStripMenuItem;
private System.Windows.Forms.PictureBox Thunbnail;
private System.Windows.Forms.ToolStripMenuItem logOutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutAskToMyselfToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ContextMenuStrip contextMenuStripLogin;
private System.Windows.Forms.ToolStripMenuItem signInToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem aboutAskToMyselfToolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1;
private System.Windows.Forms.Label labelCategory;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ToolStripMenuItem openWebAccountToolStripMenuItem;
private System.Windows.Forms.Button btnSolution;
private System.Windows.Forms.Label lblCountdown;
private System.Windows.Forms.ToolStripMenuItem buyMeABeerToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
}
}
| 56.265464 | 173 | 0.649123 | [
"MIT"
] | darionato/asktomyself | client/askme/main.Designer.cs | 21,831 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the waf-regional-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.WAFRegional.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.WAFRegional.Model.Internal.MarshallTransformations
{
/// <summary>
/// DeleteRuleGroup Request Marshaller
/// </summary>
public class DeleteRuleGroupRequestMarshaller : IMarshaller<IRequest, DeleteRuleGroupRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DeleteRuleGroupRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DeleteRuleGroupRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.WAFRegional");
string target = "AWSWAF_Regional_20161128.DeleteRuleGroup";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetChangeToken())
{
context.Writer.WritePropertyName("ChangeToken");
context.Writer.Write(publicRequest.ChangeToken);
}
if(publicRequest.IsSetRuleGroupId())
{
context.Writer.WritePropertyName("RuleGroupId");
context.Writer.Write(publicRequest.RuleGroupId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static DeleteRuleGroupRequestMarshaller _instance = new DeleteRuleGroupRequestMarshaller();
internal static DeleteRuleGroupRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteRuleGroupRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.657658 | 145 | 0.625568 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/WAFRegional/Generated/Model/Internal/MarshallTransformations/DeleteRuleGroupRequestMarshaller.cs | 3,958 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Xml;
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.ServiceModel.Security.Tokens
{
internal struct SecurityContextCookieSerializer
{
private const int SupportedPersistanceVersion = 1;
private SecurityStateEncoder _securityStateEncoder;
private IList<Type> _knownTypes;
public SecurityContextCookieSerializer(SecurityStateEncoder securityStateEncoder, IList<Type> knownTypes)
{
if (securityStateEncoder == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityStateEncoder");
}
_securityStateEncoder = securityStateEncoder;
_knownTypes = knownTypes ?? new List<Type>();
}
public byte[] CreateCookieFromSecurityContext(UniqueId contextId, string id, byte[] key, DateTime tokenEffectiveTime,
DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime,
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
throw ExceptionHelper.PlatformNotSupported();
}
}
}
| 38.777778 | 125 | 0.739828 | [
"MIT"
] | 777Eternal777/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/Security/Tokens/SecurityContextCookieSerializer.cs | 1,745 | C# |
#pragma checksum "P:\Backend\ControlDashboard\ControlDashboard\Pages\Components\InfoText.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "a66c0578e52ead0ddf6c436172e871a8d2d62bd4"
// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169
namespace ControlDashboard.Pages.Components
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.AspNetCore.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.AspNetCore.Components.Authorization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using System.Diagnostics;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard.Shared;
#line default
#line hidden
#nullable disable
#nullable restore
#line 11 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard.Pages.Components;
#line default
#line hidden
#nullable disable
#nullable restore
#line 12 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard.Pages.Products_Components;
#line default
#line hidden
#nullable disable
#nullable restore
#line 13 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard.Services;
#line default
#line hidden
#nullable disable
#nullable restore
#line 14 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using ControlDashboard.Data;
#line default
#line hidden
#nullable disable
#nullable restore
#line 15 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Radzen;
#line default
#line hidden
#nullable disable
#nullable restore
#line 16 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using Radzen.Blazor;
#line default
#line hidden
#nullable disable
#nullable restore
#line 17 "P:\Backend\ControlDashboard\ControlDashboard\_Imports.razor"
using RestSharp;
#line default
#line hidden
#nullable disable
public partial class InfoText : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
}
#pragma warning restore 1998
#nullable restore
#line 1 "P:\Backend\ControlDashboard\ControlDashboard\Pages\Components\InfoText.razor"
[Parameter]
public string Text { get; set; }
[Parameter]
public string Value { get; set; }
#line default
#line hidden
#nullable disable
}
}
#pragma warning restore 1591
| 25.433121 | 179 | 0.802404 | [
"Apache-2.0"
] | andreyminea/ECommerce_Dashboard | obj/Release/netcoreapp3.1/RazorDeclaration/Pages/Components/InfoText.razor.g.cs | 3,993 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the athena-2017-05-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Athena.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Athena.Model.Internal.MarshallTransformations
{
/// <summary>
/// EngineVersion Marshaller
/// </summary>
public class EngineVersionMarshaller : IRequestMarshaller<EngineVersion, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(EngineVersion requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetEffectiveEngineVersion())
{
context.Writer.WritePropertyName("EffectiveEngineVersion");
context.Writer.Write(requestObject.EffectiveEngineVersion);
}
if(requestObject.IsSetSelectedEngineVersion())
{
context.Writer.WritePropertyName("SelectedEngineVersion");
context.Writer.Write(requestObject.SelectedEngineVersion);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static EngineVersionMarshaller Instance = new EngineVersionMarshaller();
}
} | 33.794118 | 104 | 0.679721 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Athena/Generated/Model/Internal/MarshallTransformations/EngineVersionMarshaller.cs | 2,298 | C# |
// <copyright file="Grid.cs" company="MageWang">
// Copyright (c) MageWang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using Godot;
/// <summary>
/// Grid.
/// </summary>
public class Grid : Sprite
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
/// <summary>
/// Called when the node enters the scene tree for the first time.
/// </summary>
public override void _Ready()
{
}
// // Called every frame. 'delta' is the elapsed time since the previous frame.
// public override void _Process(float delta)
// {
// }
}
| 24.586207 | 101 | 0.652174 | [
"MIT"
] | MageWang/hive_crawler | script/Grid.cs | 713 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.DataBoxEdge;
using Microsoft.Azure.PowerShell.Cmdlets.DataBoxEdge.Models;
using Microsoft.Rest.Azure;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using ResourceModel = Microsoft.Azure.Management.DataBoxEdge.Models.DataBoxEdgeDevice;
using PSResourceModel = Microsoft.Azure.PowerShell.Cmdlets.DataBoxEdge.Models.PSDataBoxEdgeDevice;
namespace Microsoft.Azure.PowerShell.Cmdlets.DataBoxEdge.Common.Cmdlets.Devices
{
[Cmdlet(VerbsCommon.Get, Constants.Device, DefaultParameterSetName = ListByParameterSet
),
OutputType(typeof(PSResourceModel)),
]
[OutputType(typeof(PSDataBoxEdgeNetworkAdapter), ParameterSetName =
new[] {GetExtendedInfoParameterSet, GetExtendedInfoByResourceIdParameterSet})]
[OutputType(typeof(PSDataBoxEdgeDeviceExtendedInfo), ParameterSetName =
(new[] {GetExtendedInfoParameterSet, GetExtendedInfoByResourceIdParameterSet}))]
[OutputType(typeof(PSDataBoxEdgeUpdateSummary), ParameterSetName =
(new[] {GetSummaryUpdateByResourceIdParameterSet, GetSummaryUpdateParameterSet}))]
[OutputType(typeof(PSDataBoxEdgeAlert), ParameterSetName =
(new[] {GetAlertParameterSet, GetAlertByResourceIdParameterSet}))]
public class DataBoxEdgeDeviceGetCmdletBase : AzureDataBoxEdgeCmdletBase
{
private const string ListByParameterSet = "ListByParameterSet";
private const string GetByResourceIdParameterSet = "GetByResourceIdParameterSet";
private const string GetByNameParameterSet = "GetByNameParameterSet";
private const string GetExtendedInfoParameterSet = "GetExtendedInfoParameterSet";
private const string GetNetworkSettingParameterSet = "GetNetworkSettingParameterSet";
private const string GetSummaryUpdateParameterSet = "GetSummaryUpdateParameterSet";
private const string GetAlertParameterSet = "GetAlertParameterSet";
private const string GetExtendedInfoByResourceIdParameterSet = "GetExtendedInfoByResourceIdParameterSet";
private const string GetNetworkSettingByResourceIdParameterSet = "GetNetworkSettingByResourceIdParameterSet";
private const string GetSummaryUpdateByResourceIdParameterSet = "GetSummaryUpdateByResourceIdParameterSet";
private const string GetAlertByResourceIdParameterSet = "GetAlertByResourceIdParameterSet";
[Parameter(Mandatory = true,
ParameterSetName = GetByResourceIdParameterSet,
HelpMessage = Constants.ResourceIdHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetExtendedInfoByResourceIdParameterSet,
HelpMessage = Constants.ResourceIdHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetNetworkSettingByResourceIdParameterSet,
HelpMessage = Constants.ResourceIdHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetSummaryUpdateByResourceIdParameterSet,
HelpMessage = Constants.ResourceIdHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetAlertByResourceIdParameterSet,
HelpMessage = Constants.ResourceIdHelpMessage)]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }
[Parameter(Mandatory = false,
ParameterSetName = ListByParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[Parameter(Mandatory = true,
ParameterSetName = GetByNameParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[Parameter(Mandatory = true,
ParameterSetName = GetSummaryUpdateParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[Parameter(Mandatory = true,
ParameterSetName = GetNetworkSettingParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[Parameter(Mandatory = true,
ParameterSetName = GetExtendedInfoParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[Parameter(Mandatory = true,
ParameterSetName = GetAlertParameterSet,
HelpMessage = Constants.ResourceGroupNameHelpMessage,
Position = 0)]
[ValidateNotNullOrEmpty]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(Mandatory = true,
ParameterSetName = GetByNameParameterSet,
HelpMessage = Constants.DeviceNameHelpMessage,
Position = 1)]
[Parameter(Mandatory = true,
ParameterSetName = GetSummaryUpdateParameterSet,
HelpMessage = Constants.DeviceNameHelpMessage,
Position = 1)]
[Parameter(Mandatory = true,
ParameterSetName = GetNetworkSettingParameterSet,
HelpMessage = Constants.DeviceNameHelpMessage,
Position = 1)]
[Parameter(Mandatory = true,
ParameterSetName = GetExtendedInfoParameterSet,
HelpMessage = Constants.DeviceNameHelpMessage,
Position = 1)]
[Parameter(Mandatory = true,
ParameterSetName = GetAlertParameterSet,
HelpMessage = Constants.DeviceNameHelpMessage,
Position = 1)]
[ResourceNameCompleter("Microsoft.DataBoxEdge/dataBoxEdgeDevices", nameof(ResourceGroupName))]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(Mandatory = true,
ParameterSetName = GetExtendedInfoParameterSet,
HelpMessage = HelpMessageDevice.ExtendedInfoHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetExtendedInfoByResourceIdParameterSet,
HelpMessage = HelpMessageDevice.ExtendedInfoHelpMessage)]
[ValidateNotNullOrEmpty]
public SwitchParameter ExtendedInfo { get; set; }
[Parameter(Mandatory = true,
ParameterSetName = GetNetworkSettingParameterSet,
HelpMessage = HelpMessageDevice.NetworkSettingHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetNetworkSettingByResourceIdParameterSet,
HelpMessage = HelpMessageDevice.NetworkSettingHelpMessage)]
[ValidateNotNullOrEmpty]
public SwitchParameter NetworkSetting { get; set; }
[Parameter(Mandatory = true,
ParameterSetName = GetAlertParameterSet,
HelpMessage = HelpMessageDevice.AlertHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetAlertByResourceIdParameterSet,
HelpMessage = HelpMessageDevice.AlertHelpMessage)]
[ValidateNotNullOrEmpty]
public SwitchParameter Alert { get; set; }
[Parameter(Mandatory = true,
ParameterSetName = GetSummaryUpdateParameterSet,
HelpMessage = HelpMessageDevice.UpdateSummaryHelpMessage)]
[Parameter(Mandatory = true,
ParameterSetName = GetSummaryUpdateByResourceIdParameterSet,
HelpMessage = HelpMessageDevice.UpdateSummaryHelpMessage)]
[ValidateNotNullOrEmpty]
public SwitchParameter UpdateSummary { get; set; }
private ResourceModel GetResourceModel()
{
return DevicesOperationsExtensions.Get(
this.DataBoxEdgeManagementClient.Devices,
this.Name,
this.ResourceGroupName);
}
private IPage<ResourceModel> ListResourceModel()
{
if (!string.IsNullOrEmpty(this.ResourceGroupName))
{
return DevicesOperationsExtensions.ListByResourceGroup(
this.DataBoxEdgeManagementClient.Devices,
this.ResourceGroupName);
}
return DevicesOperationsExtensions.ListBySubscription(
this.DataBoxEdgeManagementClient.Devices);
}
private IPage<ResourceModel> ListResourceModel(string nextPageLink)
{
if (!string.IsNullOrEmpty(this.ResourceGroupName))
{
return DevicesOperationsExtensions.ListByResourceGroupNext(
this.DataBoxEdgeManagementClient.Devices,
nextPageLink);
}
return DevicesOperationsExtensions.ListBySubscriptionNext(
this.DataBoxEdgeManagementClient.Devices,
nextPageLink
);
}
private List<PSResourceModel> GetByResourceName()
{
var resourceModel = GetResourceModel();
return new List<PSResourceModel>() {new PSResourceModel(resourceModel)};
}
private List<PSResourceModel> ListForEverything()
{
var results = new List<PSResourceModel>();
if (!string.IsNullOrEmpty(this.Name))
{
return GetByResourceName();
}
else
{
var resourceModels = ListResourceModel();
var paginatedResult = new List<ResourceModel>(resourceModels);
while (!string.IsNullOrEmpty(resourceModels.NextPageLink))
{
resourceModels = ListResourceModel(resourceModels.NextPageLink);
paginatedResult.AddRange(resourceModels);
}
results = paginatedResult.Select(t => new PSResourceModel(t)).ToList();
}
return results;
}
private IList<PSDataBoxEdgeNetworkAdapter> GetNetworkSettings()
{
var networkSettings = new PSDataBoxEdgeNetworkSetting(DevicesOperationsExtensions.GetNetworkSettings(
this.DataBoxEdgeManagementClient.Devices,
this.Name,
this.ResourceGroupName));
return networkSettings.NetworkAdapters;
}
private PSDataBoxEdgeDeviceExtendedInfo GetExtendedInfo()
{
return new PSDataBoxEdgeDeviceExtendedInfo(DevicesOperationsExtensions.GetExtendedInformation(
this.DataBoxEdgeManagementClient.Devices,
this.Name,
this.ResourceGroupName));
}
private PSDataBoxEdgeUpdateSummary GetUpdatedSummary()
{
return new PSDataBoxEdgeUpdateSummary(DevicesOperationsExtensions.GetUpdateSummary(
this.DataBoxEdgeManagementClient.Devices,
this.Name,
this.ResourceGroupName));
}
private List<PSDataBoxEdgeAlert> GetAlert()
{
var alerts = new DataBoxEdgeAlert(this.DataBoxEdgeManagementClient, this.ResourceGroupName, this.Name)
.Get();
return alerts;
}
public override void ExecuteCmdlet()
{
var results = new List<PSResourceModel>();
if (this.IsParameterBound(c => c.ResourceId))
{
var resourceIdentifier = new DataBoxEdgeResourceIdentifier(this.ResourceId);
this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
this.Name = resourceIdentifier.ResourceName;
}
results = ListForEverything();
if (this.ExtendedInfo.IsPresent)
{
WriteObject(GetExtendedInfo(), true);
}
else if (this.NetworkSetting.IsPresent)
{
WriteObject(GetNetworkSettings(), enumerateCollection: true);
}
else if (this.UpdateSummary.IsPresent)
{
var info = GetUpdatedSummary();
WriteObject(info, enumerateCollection: true);
}
else if (this.Alert.IsPresent)
{
WriteObject(GetAlert(), enumerateCollection: true);
}
else
{
WriteObject(results, true);
}
}
}
} | 45 | 118 | 0.640904 | [
"MIT"
] | Agazoth/azure-powershell | src/DataBoxEdge/DataBoxEdge/Common/Cmdlets/Devices/DataBoxEdgeDeviceGetCmdletBase.cs | 12,983 | C# |
namespace Plugin.Messaging
{
/// <summary>
/// Abstraction to access the <see cref="IEmailTask"/>, <see cref="IPhoneCallTask"/> and <see cref="ISmsTask"/> functionality
/// </summary>
public interface IMessaging
{
/// <summary>
/// Gets an instance of the platform implementation for the <see cref="IEmailTask" />
/// </summary>
IEmailTask EmailMessenger { get; }
/// <summary>
/// Gets an instance of the platform implementation for the <see cref="IPhoneCallTask" />
/// </summary>
IPhoneCallTask PhoneDialer { get; }
/// <summary>
/// Gets an instance of the platform implementation for the <see cref="ISmsTask" />
/// </summary>
ISmsTask SmsMessenger { get; }
}
} | 35 | 133 | 0.581366 | [
"MIT"
] | BSVN/Xamarin.Plugins | Messaging/Plugin.Messaging.Abstractions/IMessaging.cs | 807 | C# |
using PublicApiGeneratorTests.Examples;
using Xunit;
namespace PublicApiGeneratorTests
{
public class Property_attributes : ApiGeneratorTestsBase
{
[Fact]
public void Should_add_attribute_with_no_parameters()
{
AssertPublicApi<PropertyWithSimpleAttribute>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithSimpleAttribute
{
public PropertyWithSimpleAttribute() { }
[PublicApiGeneratorTests.Examples.SimpleAttribute()]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_attribute_with_positional_parameters()
{
AssertPublicApi<PropertyWithAttributeWithStringPositionalParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithStringPositionalParameters
{
public PropertyWithAttributeWithStringPositionalParameters() { }
[PublicApiGeneratorTests.Examples.AttributeWithPositionalParameters1Attribute(""Hello"")]
public string Value { get; set; }
}
}");
AssertPublicApi<PropertyWithAttributeWithIntPositionalParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithIntPositionalParameters
{
public PropertyWithAttributeWithIntPositionalParameters() { }
[PublicApiGeneratorTests.Examples.AttributeWithPositionalParameters2Attribute(42)]
public string Value { get; set; }
}
}");
AssertPublicApi<PropertyWithAttributeWithMultiplePositionalParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithMultiplePositionalParameters
{
public PropertyWithAttributeWithMultiplePositionalParameters() { }
[PublicApiGeneratorTests.Examples.AttributeWithMultiplePositionalParametersAttribute(42, ""Hello world"")]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_attribute_with_named_parameters()
{
AssertPublicApi<PropertyWithIntNamedParameterAttribute>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithIntNamedParameterAttribute
{
public PropertyWithIntNamedParameterAttribute() { }
[PublicApiGeneratorTests.Examples.AttributeWithNamedParameterAttribute(IntValue=42)]
public string Value { get; set; }
}
}");
AssertPublicApi<PropertyWithStringNamedParameterAttribute>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithStringNamedParameterAttribute
{
public PropertyWithStringNamedParameterAttribute() { }
[PublicApiGeneratorTests.Examples.AttributeWithNamedParameterAttribute(StringValue=""Hello"")]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_multiple_named_parameters_in_alphabetical_order()
{
AssertPublicApi<PropertyWithAttributeWithMultipleNamedParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithMultipleNamedParameters
{
public PropertyWithAttributeWithMultipleNamedParameters() { }
[PublicApiGeneratorTests.Examples.AttributeWithNamedParameterAttribute(IntValue=42, StringValue=""Hello world"")]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_attribute_with_both_named_and_positional_parameters()
{
AssertPublicApi<PropertyWithAttributeWithBothNamedAndPositionalParameters>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithBothNamedAndPositionalParameters
{
public PropertyWithAttributeWithBothNamedAndPositionalParameters() { }
[PublicApiGeneratorTests.Examples.AttributeWithNamedAndPositionalParameterAttribute(42, ""Hello world"", IntValue=13, StringValue=""Thingy"")]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_output_enum_value()
{
AssertPublicApi<PropertyWithAttributeWithSimpleEnum>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithSimpleEnum
{
public PropertyWithAttributeWithSimpleEnum() { }
[PublicApiGeneratorTests.Examples.AttributeWithSimpleEnumAttribute(PublicApiGeneratorTests.Examples.SimpleEnum.Blue)]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_expand_enum_flags()
{
AssertPublicApi<PropertyWithAttributeWithEnumFlags>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithAttributeWithEnumFlags
{
public PropertyWithAttributeWithEnumFlags() { }
[PublicApiGeneratorTests.Examples.AttributeWithEnumFlagsAttribute(PublicApiGeneratorTests.Examples.EnumWithFlags.One | PublicApiGeneratorTests.Examples.EnumWithFlags.Two | PublicApiGeneratorTests.Examples.EnumWithFlags.Three)]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_multiple_attributes_in_alphabetical_order()
{
AssertPublicApi<PropertyWithMultipleAttributes>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithMultipleAttributes
{
public PropertyWithMultipleAttributes() { }
[PublicApiGeneratorTests.Examples.Attribute_AA()]
[PublicApiGeneratorTests.Examples.Attribute_MM()]
[PublicApiGeneratorTests.Examples.Attribute_ZZ()]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_add_attributes_on_getters_and_setters()
{
// Yes, it's a hack, but the CodeDOM doesn't support it. Sigh
AssertPublicApi<PropertyWithSimpleAttributeOnGetterAndSetter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithSimpleAttributeOnGetterAndSetter
{
public PropertyWithSimpleAttributeOnGetterAndSetter() { }
[get: PublicApiGeneratorTests.Examples.SimpleAttribute()]
[set: PublicApiGeneratorTests.Examples.SimpleAttribute()]
public string Value { get; set; }
}
}");
}
[Fact]
public void Should_skip_excluded_attributes()
{
AssertPublicApi<PropertyWithSimpleAttributeOnGetterAndSetter>(
@"namespace PublicApiGeneratorTests.Examples
{
public class PropertyWithSimpleAttributeOnGetterAndSetter
{
public PropertyWithSimpleAttributeOnGetterAndSetter() { }
public string Value { get; set; }
}
}", excludeAttributes: new[] { "PublicApiGeneratorTests.Examples.SimpleAttribute" });
}
}
// ReSharper disable UnusedMember.Global
// ReSharper disable ClassNeverInstantiated.Global
namespace Examples
{
public class PropertyWithSimpleAttribute
{
[SimpleAttribute]
public string Value { get; set; }
}
public class PropertyWithAttributeWithStringPositionalParameters
{
[AttributeWithPositionalParameters1("Hello")]
public string Value { get; set; }
}
public class PropertyWithAttributeWithIntPositionalParameters
{
[AttributeWithPositionalParameters2(42)]
public string Value { get; set; }
}
public class PropertyWithAttributeWithMultiplePositionalParameters
{
[AttributeWithMultiplePositionalParameters(42, "Hello world")]
public string Value { get; set; }
}
public class PropertyWithIntNamedParameterAttribute
{
[AttributeWithNamedParameter(IntValue = 42)]
public string Value { get; set; }
}
public class PropertyWithStringNamedParameterAttribute
{
[AttributeWithNamedParameter(StringValue = "Hello")]
public string Value { get; set; }
}
public class PropertyWithAttributeWithMultipleNamedParameters
{
[AttributeWithNamedParameter(StringValue = "Hello world", IntValue = 42)]
public string Value { get; set; }
}
public class PropertyWithAttributeWithBothNamedAndPositionalParameters
{
[AttributeWithNamedAndPositionalParameter(42, "Hello world", StringValue = "Thingy", IntValue = 13)]
public string Value { get; set; }
}
public class PropertyWithAttributeWithSimpleEnum
{
[AttributeWithSimpleEnum(SimpleEnum.Blue)]
public string Value { get; set; }
}
public class PropertyWithAttributeWithEnumFlags
{
[AttributeWithEnumFlags(EnumWithFlags.One | EnumWithFlags.Two | EnumWithFlags.Three)]
public string Value { get; set; }
}
public class PropertyWithMultipleAttributes
{
[Attribute_ZZ]
[Attribute_MM]
[Attribute_AA]
public string Value { get; set; }
}
public class PropertyWithSimpleAttributeOnGetterAndSetter
{
public string Value
{
[SimpleAttribute] get;
[SimpleAttribute] set;
}
}
}
// ReSharper restore ClassNeverInstantiated.Global
// ReSharper restore UnusedMember.Global
} | 34.326087 | 234 | 0.688094 | [
"MIT"
] | devlead/ApiApprover | src/PublicApiGeneratorTests/Property_attributes.cs | 9,476 | C# |
using System.Net.Http;
using System.Threading.Tasks;
using Fhi.Smittestopp.Verification.Msis.Interfaces;
using Fhi.Smittestopp.Verification.Msis.Models;
using Newtonsoft.Json;
namespace Fhi.Smittestopp.Verification.Msis
{
public class MsisClient : IMsisClient
{
private readonly HttpClient _httpClient;
public MsisClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<Covid19Status> GetCovid19Status(string nationalId)
{
var result = await _httpClient.GetAsync("covid19status?ident=" + nationalId);
result.EnsureSuccessStatusCode();
var responseJson = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Covid19Status>(responseJson);
}
public async Task<bool> GetMsisOnlineStatus()
{
var result = await _httpClient.GetAsync("erMsisOnline");
result.EnsureSuccessStatusCode();
var responseJson = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<bool>(responseJson);
}
}
}
| 33.028571 | 89 | 0.677336 | [
"MIT"
] | HenrikWM/Fhi.Smittestopp.Verification | Fhi.Smittestopp.Verification.Msis/MsisClient.cs | 1,158 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.452)
// Version 5.452.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
/// <summary>
/// Draws a scrolling button with given orientation.
/// </summary>
internal class ViewDrawRibbonScrollButton : ViewLeaf
{
#region Instance Fields
private readonly KryptonRibbon _ribbon;
private IDisposable _mementoBack;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawRibbonScrollButton class.
/// </summary>
/// <param name="ribbon">Reference to owning ribbon control.</param>
/// <param name="orientation">Scroller orientation.</param>
public ViewDrawRibbonScrollButton(KryptonRibbon ribbon,
VisualOrientation orientation)
{
_ribbon = ribbon;
Orientation = orientation;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawRibbonScrollButton:" + Id;
}
/// <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)
{
if (_mementoBack != null)
{
_mementoBack.Dispose();
_mementoBack = null;
}
}
base.Dispose(disposing);
}
#endregion
#region Orientation
/// <summary>
/// Gets and sets the visual orientation of the scroller button.
/// </summary>
public VisualOrientation Orientation { get; set; }
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
return Size.Empty;
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
}
#endregion
#region Paint
/// <summary>
/// Perform rendering before child elements are rendered.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void RenderBefore(RenderContext context)
{
// Create a border offset down and right for drawing a shadow
Rectangle shadowRect = ClientRectangle;
shadowRect.X++;
shadowRect.Y++;
// Reduce background to fit inside the border
Rectangle backRect = ClientRectangle;
backRect.Inflate(-1, -1);
// Create border paths
using (GraphicsPath borderPath = CreateBorderPath(ClientRectangle),
shadowPath = CreateBorderPath(shadowRect))
{
// Are we allowed to draw a border?
if (_ribbon.StateCommon.RibbonScroller.PaletteBorder.GetBorderDraw(State) == InheritBool.True)
{
// Draw the border shadow
using (AntiAlias aa = new AntiAlias(context.Graphics))
using (SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(16, Color.Black)))
{
context.Graphics.FillPath(shadowBrush, shadowPath);
}
}
// Are we allowed to draw a background?
if (_ribbon.StateCommon.RibbonScroller.PaletteBack.GetBackDraw(State) == InheritBool.True)
{
_mementoBack = context.Renderer.RenderStandardBack.DrawBack(context, backRect, borderPath,
_ribbon.StateCommon.RibbonScroller.PaletteBack,
VisualOrientation.Top,State, _mementoBack);
}
// Are we allowed to draw the content?
if (_ribbon.StateCommon.RibbonScroller.PaletteContent.GetContentDraw(State) == InheritBool.True)
{
// Get the text color from palette
Color textColor = _ribbon.StateCommon.RibbonScroller.PaletteContent.GetContentShortTextColor1(State);
// Draw the arrow content in center of the background
DrawArrow(context.Graphics, textColor, backRect);
}
// Are we allowed to draw border?
if (_ribbon.StateCommon.RibbonScroller.PaletteBorder.GetBorderDraw(State) == InheritBool.True)
{
// Get the border color from palette
Color borderColor = _ribbon.StateCommon.RibbonScroller.PaletteBorder.GetBorderColor1(State);
// Draw the border last to overlap the background
using (AntiAlias aa = new AntiAlias(context.Graphics))
using (Pen borderPen = new Pen(borderColor))
{
context.Graphics.DrawPath(borderPen, borderPath);
}
}
}
}
#endregion
#region Implementation
private GraphicsPath CreateBorderPath(Rectangle rect)
{
GraphicsPath path = new GraphicsPath();
switch (Orientation)
{
case VisualOrientation.Top:
path.AddLine(rect.Left, rect.Bottom - 1, rect.Left, rect.Top + 2);
path.AddLine(rect.Left, rect.Top + 2, rect.Left + 2, rect.Top);
path.AddLine(rect.Left + 2, rect.Top, rect.Right - 3, rect.Top);
path.AddLine(rect.Right - 3, rect.Top, rect.Right - 1, rect.Top + 2);
path.AddLine(rect.Right - 1, rect.Top + 2, rect.Right - 1, rect.Bottom - 1);
path.AddLine(rect.Right - 1, rect.Bottom - 1, rect.Left, rect.Bottom - 1);
break;
case VisualOrientation.Bottom:
path.AddLine(rect.Left, rect.Top, rect.Left, rect.Bottom - 3);
path.AddLine(rect.Left, rect.Bottom - 3, rect.Left + 2, rect.Bottom - 1);
path.AddLine(rect.Left + 2, rect.Bottom - 1, rect.Right - 3, rect.Bottom - 1);
path.AddLine(rect.Right - 3, rect.Bottom - 1, rect.Right - 1, rect.Bottom - 3);
path.AddLine(rect.Right - 1, rect.Bottom - 3, rect.Right - 1, rect.Top);
path.AddLine(rect.Right - 1, rect.Top, rect.Left, rect.Top);
break;
case VisualOrientation.Left:
path.AddLine(rect.Right - 1, rect.Top, rect.Left + 2, rect.Top);
path.AddLine(rect.Left + 2, rect.Top, rect.Left, rect.Top + 2);
path.AddLine(rect.Left, rect.Top + 2, rect.Left, rect.Bottom - 3);
path.AddLine(rect.Left, rect.Bottom - 3, rect.Left + 2, rect.Bottom - 1);
path.AddLine(rect.Left + 2, rect.Bottom - 1, rect.Right - 1, rect.Bottom - 1);
path.AddLine(rect.Right - 1, rect.Bottom - 1, rect.Right - 1, rect.Top);
break;
case VisualOrientation.Right:
path.AddLine(rect.Left, rect.Top, rect.Right - 3, rect.Top);
path.AddLine(rect.Right - 3, rect.Top, rect.Right - 1, rect.Top + 2);
path.AddLine(rect.Right - 1, rect.Top + 2, rect.Right - 1, rect.Bottom - 3);
path.AddLine(rect.Right - 1, rect.Bottom - 3, rect.Right - 3, rect.Bottom - 1);
path.AddLine(rect.Right - 3, rect.Bottom - 1, rect.Left, rect.Bottom - 1);
path.AddLine(rect.Left, rect.Bottom - 1, rect.Left, rect.Top);
break;
}
return path;
}
private void DrawArrow(Graphics g, Color textColor, Rectangle rect)
{
// Create path that describes the arrow in orientation needed
using (GraphicsPath arrowPath = CreateArrowPath(rect))
using (SolidBrush arrowBrush = new SolidBrush(textColor))
{
g.FillPath(arrowBrush, arrowPath);
}
}
private GraphicsPath CreateArrowPath(Rectangle rect)
{
int x, y;
// Find the correct starting position, which depends on direction
if ((Orientation == VisualOrientation.Left) ||
(Orientation == VisualOrientation.Right))
{
x = rect.Right - ((rect.Width - 4) / 2);
y = rect.Y + (rect.Height / 2);
}
else
{
x = rect.X + (rect.Width / 2);
y = rect.Bottom - ((rect.Height - 3) / 2);
}
// Create triangle using a series of lines
GraphicsPath path = new GraphicsPath();
switch (Orientation)
{
case VisualOrientation.Right:
path.AddLine(x, y, x - 4, y - 4);
path.AddLine(x - 4, y - 4, x - 4, y + 4);
path.AddLine(x - 4, y + 4, x, y);
break;
case VisualOrientation.Left:
path.AddLine(x - 4, y, x, y - 4);
path.AddLine(x, y - 4, x, y + 4);
path.AddLine(x, y + 4, x - 4, y);
break;
case VisualOrientation.Bottom:
path.AddLine(x + 3f, y - 3f, x - 2f, y - 3f);
path.AddLine(x - 2f, y - 3f, x, y);
path.AddLine(x, y, x + 3f, y - 3f);
break;
case VisualOrientation.Top:
path.AddLine(x + 3f, y, x - 3f, y);
path.AddLine(x - 3f, y, x, y - 4f);
path.AddLine(x, y - 4f, x + 3f, y);
break;
}
return path;
}
#endregion
}
}
| 43.051471 | 157 | 0.518531 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.452 | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/View Draw/ViewDrawRibbonScrollButton.cs | 11,713 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrderNumberGenerator : NumberGenerator {
public int[] order;
int current = 0;
public override int Next(){
int result = order [current % order.Length];
current++;
return result;
}
}
| 16.055556 | 53 | 0.726644 | [
"Unlicense"
] | hosoji/CodeLab2-2017-InClass | WarmUp/Assets/Scripts/OrderNumberGenerator.cs | 291 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Destine.Samples
{
class ElectricCar
{
public static void Run()
{
Console.WriteLine("ElectricCar");
var world = new World {SimEndCondition = world1 => world1.CurrentTime == 15};
var electricCar = new ElectricCar(world);
var driver = new Driver(world, electricCar);
world.Run();
Console.ReadLine();
}
private readonly World _world;
public Task Action { get; }
public CancellationTokenSource CancellationToken { get; private set; }
public ElectricCar(World world)
{
_world = world;
Action = _world.Process(Process());
}
public async Task Process()
{
while (true)
{
Console.WriteLine($"Start parking and charging at {_world.CurrentTime}");
uint chargeDuration = 5;
await _world.Process(Charge(chargeDuration));
Console.WriteLine($"Start driving at {_world.CurrentTime}");
uint tripDuration = 2;
await _world.Timeout(tripDuration);
}
}
private async Task Charge(uint duration)
{
CancellationToken = new CancellationTokenSource();
await _world.Timeout(duration, CancellationToken);
if (CancellationToken.IsCancellationRequested)
{
Console.WriteLine("Was interrupted. Hope the battery is full enough...");
}
}
}
class Driver
{
private readonly World _world;
private readonly ElectricCar _car;
public Driver(World world, ElectricCar car)
{
_world = world;
_car = car;
_world.Process(Process());
}
public async Task Process()
{
await _world.Timeout(3);
_car.CancellationToken.Cancel();
}
}
}
| 27.802632 | 89 | 0.551822 | [
"Apache-2.0"
] | Sprunth/Destine | Destine.Samples/ElectricCar.cs | 2,115 | C# |
using System.Runtime.InteropServices;
using Qml.Net.Internal;
using Qml.Net.Internal.Types;
namespace Qml.Net
{
public static class Qml
{
public static int RegisterType<T>(string uri, int versionMajor = 1, int versionMinor = 0)
{
return QQmlApplicationEngine.RegisterType(NetTypeManager.GetTypeInfo<T>(), uri, typeof(T).Name, versionMajor, versionMinor);
}
public static int RegisterSingletonType(string url, string uri, int versionMajor, int versionMinor, string qmlName)
{
return Interop.QQmlApplicationEngine.RegisterSingletonTypeQml(url, uri, versionMajor, versionMinor, qmlName);
}
public static int RegisterSingletonType<T>(string uri, int versionMajor = 1, int versionMinor = 0)
{
using (var type = NetTypeManager.GetTypeInfo<T>())
{
return Interop.QQmlApplicationEngine.RegisterSingletonTypeNet(type.Handle, uri, versionMajor, versionMinor, typeof(T).Name);
}
}
}
} | 38.666667 | 140 | 0.667625 | [
"MIT"
] | TripleWhy/qmlnet | src/net/Qml.Net/Qml.cs | 1,044 | C# |
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using CommunityToolkit.Diagnostics;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static TerraFX.Interop.DirectX.D3D12_MESSAGE_SEVERITY;
#if NET6_0_OR_GREATER
using Enum = System.Enum;
#else
using Enum = ComputeSharp.NetStandard.System.Enum;
#endif
namespace ComputeSharp.Graphics.Helpers;
/// <inheritdoc/>
internal static partial class DeviceHelper
{
/// <summary>
/// Flushes all the pending debug messages for all existing <see cref="ID3D12Device"/> instances to the console/debugger.
/// It also checks whether or not there are any error messages being logged that didn't result in an actual crash yet.
/// </summary>
/// <return>Whether or not there are any logged errors or warnings.</return>
public static unsafe bool FlushAllID3D12InfoQueueMessagesAndCheckForErrorsOrWarnings()
{
bool hasErrorsOrWarnings = false;
lock (DevicesCache)
{
StringBuilder builder = new(1024);
foreach (var pair in D3D12InfoQueueMap)
{
GraphicsDevice device = DevicesCache[pair.Key];
ID3D12InfoQueue* queue = pair.Value.Get();
ulong messages = queue->GetNumStoredMessagesAllowedByRetrievalFilter();
for (ulong i = 0; i < messages; i++)
{
nuint length;
queue->GetMessage(i, null, &length);
D3D12_MESSAGE* message = (D3D12_MESSAGE*)NativeMemory.Alloc(length);
try
{
queue->GetMessage(i, message, &length);
builder.Clear();
builder.AppendLine($"[D3D12 message #{i} for \"{device}\" (HW: {device.IsHardwareAccelerated}, UMA: {device.IsCacheCoherentUMA})]");
builder.AppendLine($"[Category]: {Enum.GetName(message->Category)}");
builder.AppendLine($"[Severity]: {Enum.GetName(message->Severity)}");
builder.AppendLine($"[ID]: {Enum.GetName(message->ID)}");
builder.Append($"[Description]: \"{new string(message->pDescription)}\"");
}
finally
{
NativeMemory.Free(message);
}
if (message->Severity is D3D12_MESSAGE_SEVERITY_ERROR or D3D12_MESSAGE_SEVERITY_CORRUPTION or D3D12_MESSAGE_SEVERITY_WARNING)
{
hasErrorsOrWarnings = true;
}
string text = builder.ToString();
if (Debugger.IsAttached)
{
Debug.WriteLine(text);
}
else
{
Trace.WriteLine(text);
}
}
queue->ClearStoredMessages();
HRESULT result = device.D3D12Device->GetDeviceRemovedReason();
if (result != S.S_OK)
{
string message = (int)result switch
{
DXGI.DXGI_ERROR_DEVICE_HUNG => nameof(DXGI.DXGI_ERROR_DEVICE_HUNG),
DXGI.DXGI_ERROR_DEVICE_REMOVED => nameof(DXGI.DXGI_ERROR_DEVICE_REMOVED),
DXGI.DXGI_ERROR_DEVICE_RESET => nameof(DXGI.DXGI_ERROR_DEVICE_RESET),
DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR => nameof(DXGI.DXGI_ERROR_DRIVER_INTERNAL_ERROR),
DXGI.DXGI_ERROR_INVALID_CALL => nameof(DXGI.DXGI_ERROR_INVALID_CALL),
_ => ThrowHelper.ThrowArgumentOutOfRangeException<string>("Invalid GetDeviceRemovedReason HRESULT.")
};
builder.Clear();
builder.AppendLine($"[D3D12 device remove \"{device}\" (HW: {device.IsHardwareAccelerated}, UMA: {device.IsCacheCoherentUMA})]");
builder.AppendLine($"[Reason]: {message}");
hasErrorsOrWarnings = true;
string text = builder.ToString();
if (Debugger.IsAttached)
{
Debug.WriteLine(text);
}
else
{
Trace.WriteLine(text);
}
}
}
}
return hasErrorsOrWarnings;
}
}
| 38.453782 | 156 | 0.534747 | [
"MIT"
] | sharwell/ComputeSharp | src/ComputeSharp/Graphics/Helpers/DeviceHelper.ID3D12InfoQueue.cs | 4,578 | C# |
using UnityEngine;
using Assets.Utilities;
namespace UnityEngine.InputNew
{
public class JoystickProfile
: InputDeviceProfile
{
#region Public Properties
public JoystickControlMapping[] mappings;
public string[] nameOverrides;
protected static Range defaultDeadZones = new Range(0.2f, 0.9f);
#endregion
#region Public Methods
public override void Remap(InputEvent inputEvent)
{
var controlEvent = inputEvent as GenericControlEvent;
if (controlEvent != null)
{
var mapping = mappings[controlEvent.controlIndex];
if (mapping.targetIndex != -1)
{
controlEvent.controlIndex = mapping.targetIndex;
controlEvent.value = Mathf.InverseLerp(mapping.fromRange.min, mapping.fromRange.max, controlEvent.value);
controlEvent.value = Mathf.Lerp(mapping.toRange.min, mapping.toRange.max, controlEvent.value);
Range deadZones = mapping.interDeadZoneRange;
controlEvent.value = Mathf.InverseLerp(deadZones.min, deadZones.max, Mathf.Abs(controlEvent.value))
* Mathf.Sign(controlEvent.value);
}
}
}
public void SetMappingsCount(int sourceControlCount, int tarcontrolCount)
{
mappings = new JoystickControlMapping[sourceControlCount];
nameOverrides = new string[tarcontrolCount];
}
public void SetMapping(int sourceControlIndex, int targetControlIndex, string displayName)
{
SetMapping(sourceControlIndex, targetControlIndex, displayName, defaultDeadZones, Range.full, Range.full);
}
public void SetMapping(int sourceControlIndex, int targetControlIndex, string displayName, Range interDeadZoneRange)
{
SetMapping(sourceControlIndex, targetControlIndex, displayName, interDeadZoneRange, Range.full, Range.full);
}
public void SetMapping(int sourceControlIndex, int targetControlIndex, string displayName, Range interDeadZoneRange, Range sourceRange, Range targetRange)
{
mappings[sourceControlIndex] = new JoystickControlMapping
{
targetIndex = targetControlIndex,
fromRange = sourceRange,
toRange = targetRange,
interDeadZoneRange = interDeadZoneRange
};
nameOverrides[targetControlIndex] = displayName;
}
public override string GetControlNameOverride(int controlIndex)
{
if (controlIndex >= nameOverrides.Length)
return null;
return nameOverrides[controlIndex];
}
#endregion
}
}
| 30.776316 | 156 | 0.761437 | [
"MIT"
] | antila/castle-game-jam-2016 | Assets/input-prototype/Input/JoystickProfile.cs | 2,339 | C# |
namespace InfraWatcher.Core.Models.Configuration
{
public class InfraWatcherOption
{
public ServerTTLOption TTLOption { get; set; }
public CommandOption[] Commands { get; set; }
}
}
| 23.444444 | 54 | 0.672986 | [
"MIT"
] | jhonnyelhelou91/InfraWatcher | InfraWatcher.Core/Models/Configuration/InfraWatcherOption.cs | 213 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Pinpoint.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Pinpoint.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for SegmentLocation Object
/// </summary>
public class SegmentLocationUnmarshaller : IUnmarshaller<SegmentLocation, XmlUnmarshallerContext>, IUnmarshaller<SegmentLocation, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
SegmentLocation IUnmarshaller<SegmentLocation, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public SegmentLocation Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
SegmentLocation unmarshalledObject = new SegmentLocation();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Country", targetDepth))
{
var unmarshaller = SetDimensionUnmarshaller.Instance;
unmarshalledObject.Country = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static SegmentLocationUnmarshaller _instance = new SegmentLocationUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SegmentLocationUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 33.673913 | 158 | 0.642027 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/Pinpoint/Generated/Model/Internal/MarshallTransformations/SegmentLocationUnmarshaller.cs | 3,098 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120
{
using static Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.Extensions;
public partial class CustomRolloutSpecificationCanary :
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ICustomRolloutSpecificationCanary,
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ICustomRolloutSpecificationCanaryInternal,
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegions"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegions __trafficRegions = new Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.TrafficRegions();
[Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Origin(Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.PropertyOrigin.Inherited)]
public string[] Region { get => ((Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegionsInternal)__trafficRegions).Region; set => ((Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegionsInternal)__trafficRegions).Region = value; }
/// <summary>Creates an new <see cref="CustomRolloutSpecificationCanary" /> instance.</summary>
public CustomRolloutSpecificationCanary()
{
}
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__trafficRegions), __trafficRegions);
await eventListener.AssertObjectIsValid(nameof(__trafficRegions), __trafficRegions);
}
}
public partial interface ICustomRolloutSpecificationCanary :
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegions
{
}
internal partial interface ICustomRolloutSpecificationCanaryInternal :
Microsoft.Azure.PowerShell.Cmdlets.ProviderHub.Models.Api20201120.ITrafficRegionsInternal
{
}
} | 59.166667 | 293 | 0.740845 | [
"MIT"
] | wwendyc/azure-powershell | src/ProviderHub/generated/api/Models/Api20201120/CustomRolloutSpecificationCanary.cs | 2,793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace iCollections.Data
{
/// <summary>
/// Helper class to hold all the information we need to construct the users for this app. Basically
/// a union of FujiUser and IdentityUser. Not great to have to duplicate this data but it is only for one-time seeding
/// of the databases. Does NOT hold passwords since we need to store those in a secret location.
/// </summary>
public class UserInfoData
{
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool EmailConfirmed { get; set; } = true;
}
public class SeedData
{
/// <summary>
/// Data to be used to seed the FujiUsers and ASPNetUsers tables
/// </summary>
public static readonly UserInfoData[] UserSeedData = new UserInfoData[]
{
new UserInfoData { UserName = "TaliaK", Email = "knott@example.com", FirstName = "Talia", LastName = "Knott" },
new UserInfoData { UserName = "ZaydenC", Email = "clark@example.com", FirstName = "Zayden", LastName = "Clark" },
new UserInfoData { UserName = "DavilaH", Email = "hareem@example.com", FirstName = "Hareem", LastName = "Davila" },
new UserInfoData { UserName = "KrzysztofP", Email = "krzysztof@example.com", FirstName = "Krzysztof", LastName = "Ponce" },
new UserInfoData { UserName = "AlphaTester1", Email = "alphatester1@example.com", FirstName = "Joe", LastName = "Fixit" },
new UserInfoData { UserName = "AlphaTester2", Email = "alphatester2@example.com", FirstName = "Jessica", LastName = "Cruz" },
new UserInfoData { UserName = "AlphaTester3", Email = "alphatester3@example.com", FirstName = "Jason", LastName = "Todd" },
new UserInfoData { UserName = "AlphaTester4", Email = "alphatester4@example.com", FirstName = "James", LastName = "Howlett" }
};
}
}
| 52.375 | 137 | 0.640573 | [
"Unlicense"
] | drussell33/wou-cs-46x-starlane | main_project_code/TeamProject/iCollections/Data/SeedData.cs | 2,097 | C# |
/*
* Selling Partner API for Notifications
*
* The Selling Partner API for Notifications lets you subscribe to notifications that are relevant to a selling partner's business. Using this API you can create a destination to receive notifications, subscribe to notifications, delete notification subscriptions, and more.
*
* OpenAPI spec version: v1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text;
namespace AmazonSpApiSDK.Models.Notifications
{
/// <summary>
/// The request schema for the createSubscription operation.
/// </summary>
[DataContract]
public partial class CreateSubscriptionRequest : IEquatable<CreateSubscriptionRequest>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateSubscriptionRequest" /> class.
/// </summary>
/// <param name="PayloadVersion">The version of the payload object to be used in the notification..</param>
/// <param name="DestinationId">The identifier for the destination where notifications will be delivered..</param>
public CreateSubscriptionRequest(string PayloadVersion = default(string), string DestinationId = default(string))
{
this.PayloadVersion = PayloadVersion;
this.DestinationId = DestinationId;
}
/// <summary>
/// The version of the payload object to be used in the notification.
/// </summary>
/// <value>The version of the payload object to be used in the notification.</value>
[DataMember(Name = "payloadVersion", EmitDefaultValue = false)]
public string PayloadVersion { get; set; }
/// <summary>
/// The identifier for the destination where notifications will be delivered.
/// </summary>
/// <value>The identifier for the destination where notifications will be delivered.</value>
[DataMember(Name = "destinationId", EmitDefaultValue = false)]
public string DestinationId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CreateSubscriptionRequest {\n");
sb.Append(" PayloadVersion: ").Append(PayloadVersion).Append("\n");
sb.Append(" DestinationId: ").Append(DestinationId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CreateSubscriptionRequest);
}
/// <summary>
/// Returns true if CreateSubscriptionRequest instances are equal
/// </summary>
/// <param name="input">Instance of CreateSubscriptionRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CreateSubscriptionRequest input)
{
if (input == null)
return false;
return
(
this.PayloadVersion == input.PayloadVersion ||
(this.PayloadVersion != null &&
this.PayloadVersion.Equals(input.PayloadVersion))
) &&
(
this.DestinationId == input.DestinationId ||
(this.DestinationId != null &&
this.DestinationId.Equals(input.DestinationId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.PayloadVersion != null)
hashCode = hashCode * 59 + this.PayloadVersion.GetHashCode();
if (this.DestinationId != null)
hashCode = hashCode * 59 + this.DestinationId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 38.698529 | 274 | 0.602128 | [
"MIT"
] | KristopherMackowiak/Amazon-SP-API-CSharp | Source/AmazonSpApiSDK/Models/Notifications/CreateSubscriptionRequest.cs | 5,263 | C# |
using System;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
/*
* $Id$
*
* This file is part of the iText project.
* Copyright (c) 1998-2016 iText Group NV
* Authors: Bruno Lowagie, Paulo Soares, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://itextpdf.com/terms-of-use/
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the iText software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers as an ASP,
* serving PDFs on the fly in a web application, shipping iText with a closed
* source product.
*
* For more information, please contact iText Software Corp. at this
* address: sales@itextpdf.com
*/
namespace iTextSharp.text.pdf.crypto {
/**
* Creates an AES Cipher with CBC and no padding.
* @author Paulo Soares
*/
public class AESCipherCBCnoPad {
private IBlockCipher cbc;
/** Creates a new instance of AESCipher */
public AESCipherCBCnoPad(bool forEncryption, byte[] key) {
IBlockCipher aes = new AesFastEngine();
cbc = new CbcBlockCipher(aes);
KeyParameter kp = new KeyParameter(key);
cbc.Init(forEncryption, kp);
}
virtual public byte[] ProcessBlock(byte[] inp, int inpOff, int inpLen) {
if ((inpLen % cbc.GetBlockSize()) != 0)
throw new ArgumentException("Not multiple of block: " + inpLen);
byte[] outp = new byte[inpLen];
int baseOffset = 0;
while (inpLen > 0) {
cbc.ProcessBlock(inp, inpOff, outp, baseOffset);
inpLen -= cbc.GetBlockSize();
baseOffset += cbc.GetBlockSize();
inpOff += cbc.GetBlockSize();
}
return outp;
}
}
}
| 42.121951 | 80 | 0.693399 | [
"MIT"
] | mdalaminmiah/Diagnostic-Bill-management-System | packages/itextsharp-all-5.5.10/itextsharp-src-core/iTextSharp/text/pdf/crypto/AESCipher.cs | 3,454 | C# |
namespace VirtualRadar.WinForms.Controls
{
partial class WebServerStatusControl
{
/// <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 Component 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.components = new System.ComponentModel.Container();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.buttonToggleUPnpStatus = new System.Windows.Forms.Button();
this.labelUPnpStatus = new System.Windows.Forms.Label();
this.comboBoxShowAddressType = new System.Windows.Forms.ComboBox();
this.comboBoxSite = new System.Windows.Forms.ComboBox();
this.buttonToggleServerStatus = new System.Windows.Forms.Button();
this.labelServerStatus = new System.Windows.Forms.Label();
this.linkLabelAddress = new System.Windows.Forms.LinkLabel();
this.contextMenuStripWebSiteLink = new System.Windows.Forms.ContextMenuStrip(this.components);
this.openInBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyLinkToClipboardToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.webServerUserList = new VirtualRadar.WinForms.Controls.WebServerUserListControl();
this.groupBox1.SuspendLayout();
this.contextMenuStripWebSiteLink.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.buttonToggleUPnpStatus);
this.groupBox1.Controls.Add(this.labelUPnpStatus);
this.groupBox1.Controls.Add(this.comboBoxShowAddressType);
this.groupBox1.Controls.Add(this.comboBoxSite);
this.groupBox1.Controls.Add(this.webServerUserList);
this.groupBox1.Controls.Add(this.buttonToggleServerStatus);
this.groupBox1.Controls.Add(this.labelServerStatus);
this.groupBox1.Controls.Add(this.linkLabelAddress);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(658, 385);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "::WebServerStatus::";
//
// buttonToggleUPnpStatus
//
this.buttonToggleUPnpStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonToggleUPnpStatus.Location = new System.Drawing.Point(535, 44);
this.buttonToggleUPnpStatus.Name = "buttonToggleUPnpStatus";
this.buttonToggleUPnpStatus.Size = new System.Drawing.Size(120, 23);
this.buttonToggleUPnpStatus.TabIndex = 7;
this.buttonToggleUPnpStatus.Text = "Toggle Port Mapping";
this.buttonToggleUPnpStatus.UseVisualStyleBackColor = true;
this.buttonToggleUPnpStatus.Click += new System.EventHandler(this.buttonToggleUPnpStatus_Click);
//
// labelUPnpStatus
//
this.labelUPnpStatus.AutoSize = true;
this.labelUPnpStatus.Location = new System.Drawing.Point(4, 49);
this.labelUPnpStatus.Name = "labelUPnpStatus";
this.labelUPnpStatus.Size = new System.Drawing.Size(220, 13);
this.labelUPnpStatus.TabIndex = 6;
this.labelUPnpStatus.Text = "UPnP port mapping status will be shown here";
//
// comboBoxShowAddressType
//
this.comboBoxShowAddressType.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboBoxShowAddressType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxShowAddressType.FormattingEnabled = true;
this.comboBoxShowAddressType.Location = new System.Drawing.Point(7, 358);
this.comboBoxShowAddressType.Name = "comboBoxShowAddressType";
this.comboBoxShowAddressType.Size = new System.Drawing.Size(193, 21);
this.comboBoxShowAddressType.TabIndex = 3;
this.comboBoxShowAddressType.SelectedIndexChanged += new System.EventHandler(this.comboBoxShowAddressType_SelectedIndexChanged);
//
// comboBoxSite
//
this.comboBoxSite.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.comboBoxSite.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxSite.FormattingEnabled = true;
this.comboBoxSite.Location = new System.Drawing.Point(206, 358);
this.comboBoxSite.Name = "comboBoxSite";
this.comboBoxSite.Size = new System.Drawing.Size(140, 21);
this.comboBoxSite.TabIndex = 4;
this.comboBoxSite.SelectedIndexChanged += new System.EventHandler(this.comboBoxSite_SelectedIndexChanged);
//
// buttonToggleServerStatus
//
this.buttonToggleServerStatus.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonToggleServerStatus.Location = new System.Drawing.Point(535, 15);
this.buttonToggleServerStatus.Name = "buttonToggleServerStatus";
this.buttonToggleServerStatus.Size = new System.Drawing.Size(120, 23);
this.buttonToggleServerStatus.TabIndex = 1;
this.buttonToggleServerStatus.Text = "Toggle Server";
this.buttonToggleServerStatus.UseVisualStyleBackColor = true;
this.buttonToggleServerStatus.Click += new System.EventHandler(this.buttonToggleServerStatus_Click);
//
// labelServerStatus
//
this.labelServerStatus.AutoSize = true;
this.labelServerStatus.Location = new System.Drawing.Point(4, 20);
this.labelServerStatus.Name = "labelServerStatus";
this.labelServerStatus.Size = new System.Drawing.Size(183, 13);
this.labelServerStatus.TabIndex = 0;
this.labelServerStatus.Text = "Web server status will be shown here";
//
// linkLabelAddress
//
this.linkLabelAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelAddress.AutoEllipsis = true;
this.linkLabelAddress.Location = new System.Drawing.Point(352, 357);
this.linkLabelAddress.Name = "linkLabelAddress";
this.linkLabelAddress.Size = new System.Drawing.Size(299, 20);
this.linkLabelAddress.TabIndex = 5;
this.linkLabelAddress.TabStop = true;
this.linkLabelAddress.Text = "http://localhost/Whatever.html";
this.linkLabelAddress.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.linkLabelAddress.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelAddress_LinkClicked);
//
// contextMenuStripWebSiteLink
//
this.contextMenuStripWebSiteLink.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openInBrowserToolStripMenuItem,
this.copyLinkToClipboardToolStripMenuItem});
this.contextMenuStripWebSiteLink.Name = "contextMenuStripWebSiteLink";
this.contextMenuStripWebSiteLink.Size = new System.Drawing.Size(197, 48);
//
// openInBrowserToolStripMenuItem
//
this.openInBrowserToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold);
this.openInBrowserToolStripMenuItem.Name = "openInBrowserToolStripMenuItem";
this.openInBrowserToolStripMenuItem.Size = new System.Drawing.Size(196, 22);
this.openInBrowserToolStripMenuItem.Text = "&Open in Browser";
this.openInBrowserToolStripMenuItem.Click += new System.EventHandler(this.openInBrowserToolStripMenuItem_Click);
//
// copyLinkToClipboardToolStripMenuItem
//
this.copyLinkToClipboardToolStripMenuItem.Name = "copyLinkToClipboardToolStripMenuItem";
this.copyLinkToClipboardToolStripMenuItem.Size = new System.Drawing.Size(196, 22);
this.copyLinkToClipboardToolStripMenuItem.Text = "&Copy Link to Clipboard";
this.copyLinkToClipboardToolStripMenuItem.Click += new System.EventHandler(this.copyLinkToClipboardToolStripMenuItem_Click);
//
// webServerUserList
//
this.webServerUserList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.webServerUserList.Location = new System.Drawing.Point(7, 73);
this.webServerUserList.MillisecondsBeforeDelete = 60000;
this.webServerUserList.Name = "webServerUserList";
this.webServerUserList.ShowPortNumber = false;
this.webServerUserList.Size = new System.Drawing.Size(644, 279);
this.webServerUserList.TabIndex = 2;
//
// WebServerStatusControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupBox1);
this.Name = "WebServerStatusControl";
this.Size = new System.Drawing.Size(658, 385);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.contextMenuStripWebSiteLink.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.LinkLabel linkLabelAddress;
private System.Windows.Forms.Label labelServerStatus;
private System.Windows.Forms.Button buttonToggleServerStatus;
private System.Windows.Forms.ContextMenuStrip contextMenuStripWebSiteLink;
private System.Windows.Forms.ToolStripMenuItem openInBrowserToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyLinkToClipboardToolStripMenuItem;
private WebServerUserListControl webServerUserList;
private System.Windows.Forms.ComboBox comboBoxShowAddressType;
private System.Windows.Forms.ComboBox comboBoxSite;
private System.Windows.Forms.Button buttonToggleUPnpStatus;
private System.Windows.Forms.Label labelUPnpStatus;
}
}
| 58.902913 | 174 | 0.654442 | [
"BSD-3-Clause"
] | wiseman/virtual-radar-server | VirtualRadar.WinForms/Controls/WebServerStatusControl.Designer.cs | 12,136 | C# |
namespace dp2Catalog
{
partial class OaiTargeControl
{
/// <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 Component 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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OaiTargeControl));
this.imageList_resIcon = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// imageList_resIcon
//
this.imageList_resIcon.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList_resIcon.ImageStream")));
this.imageList_resIcon.TransparentColor = System.Drawing.Color.Fuchsia;
this.imageList_resIcon.Images.SetKeyName(0, "folder.bmp");
this.imageList_resIcon.Images.SetKeyName(1, "offline_computer.bmp");
this.imageList_resIcon.Images.SetKeyName(2, "database.bmp");
this.imageList_resIcon.Images.SetKeyName(3, "computer.bmp");
//
// OaiTargeControl
//
this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.OaiTargeControl_MouseUp);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ImageList imageList_resIcon;
}
}
| 38.052632 | 147 | 0.614569 | [
"Apache-2.0"
] | DigitalPlatform/dp2 | dp2Catalog/OAI/OaiTargeControl.Designer.cs | 2,169 | 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.Outputs.App.V1Alpha1
{
[OutputType]
public sealed class KogitoDataIndexSpecEnvsValueFromResourceFieldRef
{
/// <summary>
/// Container name: required for volumes, optional for env vars
/// </summary>
public readonly string ContainerName;
/// <summary>
/// Specifies the output format of the exposed resources, defaults to "1"
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.App.V1Alpha1.KogitoDataIndexSpecEnvsValueFromResourceFieldRefDivisor Divisor;
/// <summary>
/// Required: resource to select
/// </summary>
public readonly string Resource;
[OutputConstructor]
private KogitoDataIndexSpecEnvsValueFromResourceFieldRef(
string containerName,
Pulumi.Kubernetes.Types.Outputs.App.V1Alpha1.KogitoDataIndexSpecEnvsValueFromResourceFieldRefDivisor divisor,
string resource)
{
ContainerName = containerName;
Divisor = divisor;
Resource = resource;
}
}
}
| 32.72093 | 133 | 0.672353 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/kogito-operator/dotnet/Kubernetes/Crds/Operators/KogitoOperator/App/V1Alpha1/Outputs/KogitoDataIndexSpecEnvsValueFromResourceFieldRef.cs | 1,407 | C# |
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
* Copyright (C) 2018 天下商机(txooo.com)版权所有
*
* 文 件 名:BinarySerializeHelper
* 所属项目:System
* 创建用户:iwenli(HouWeiya)
* 创建时间:2018/5/21 15:58:06
*
* 功能描述:
* 1、
*
* 修改标识:
* 修改描述:
* 修改时间:
* 待 完 善:
* 1、
----------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace System
{
/// <summary>
/// 二进制序列化辅助类
/// </summary>
public static class BinarySerializeHelper
{
/// <summary>
/// 从文件中反序列化对象
/// </summary>
/// <param name="FileName">文件名</param>
/// <returns>原对象</returns>
public static object DeserializeFromFile(string FileName)
{
using (System.IO.FileStream stream = new FileStream(FileName, FileMode.Open))
{
object res = stream.DeserializeFromStream();
stream.Dispose();
return res;
}
}
/// <summary>
/// 从字节数组中反序列化
/// </summary>
/// <param name="array">字节数组</param>
/// <returns>序列化结果</returns>
public static object DeserialzieFromBytes(byte[] array)
{
object result = null;
if (array == null || array.Length == 0)
return result;
using (var ms = new System.IO.MemoryStream())
{
ms.Write(array, 0, array.Length);
ms.Seek(0, SeekOrigin.Begin);
result = ms.DeserializeFromStream();
ms.Dispose();
}
return result;
}
/// <summary>
/// 序列化对象到文件
/// </summary>
/// <param name="ObjectToSerilize">要序列化的对象</param>
/// <param name="FileName">保存到的文件路径</param>
public static void SerializeToFile(this object ObjectToSerialize, string FileName)
{
if (ObjectToSerialize == null || String.IsNullOrEmpty(FileName))
return;
using (FileStream stream = new FileStream(FileName, FileMode.Create))
{
SerializeToStream(ObjectToSerialize, stream);
stream.Dispose();
}
}
/// <summary>
/// 序列化对象到字节数组
/// </summary>
/// <param name="objectToSerialize">要序列化的对象</param>
/// <returns>返回创建后的字节数组</returns>
public static byte[] SerializeToBytes(this object objectToSerialize)
{
byte[] result = null;
if (objectToSerialize == null)
return result;
using (var ms = new MemoryStream())
{
objectToSerialize.SerializeToStream(ms);
ms.Dispose();
result = ms.ToArray();
}
return result;
}
/// <summary>
/// 序列化对象到流
/// </summary>
/// <param name="objectToSerialize">要序列化的对象</param>
/// <param name="stream">保存对象信息的流</param>
public static void SerializeToStream(this object objectToSerialize, Stream stream)
{
if (objectToSerialize == null || stream == null)
return;
BinaryFormatter xso = new BinaryFormatter();
xso.Serialize(stream, objectToSerialize);
}
/// <summary>
/// 从流中反序列化对象
/// </summary>
/// <param name="stream">流</param>
/// <returns>反序列化的对象</returns>
public static object DeserializeFromStream(this Stream stream)
{
object result = null;
if (stream == null)
return result;
BinaryFormatter xso = new BinaryFormatter();
result = xso.Deserialize(stream);
return result;
}
}
}
| 27.489655 | 90 | 0.506774 | [
"Apache-2.0"
] | iwenli/ILI | Iwenli/Extension/BinarySerializeHelper.cs | 4,372 | C# |
namespace QFramework.GraphDesigner
{
public class ApplyRenameCommand : Command
{
public IDiagramNode Item { get; set; }
public string Old { get; set; }
public string Name { get; set; }
}
} | 24.888889 | 46 | 0.620536 | [
"MIT"
] | SkyAbyss/QFramework | Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/uFrame.Editor/Systems/Platform/api/ApplyRenameCommand.cs | 224 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** 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.Outputs.Authentication.V1Beta1
{
[OutputType]
public sealed class TokenReviewStatus
{
/// <summary>
/// Audiences are audience identifiers chosen by the authenticator that are compatible with both the TokenReview and token. An identifier is any identifier in the intersection of the TokenReviewSpec audiences and the token's audiences. A client of the TokenReview API that sets the spec.audiences field should validate that a compatible audience identifier is returned in the status.audiences field to ensure that the TokenReview server is audience aware. If a TokenReview returns an empty status.audience field where status.authenticated is "true", the token is valid against the audience of the Kubernetes API server.
/// </summary>
public readonly ImmutableArray<string> Audiences;
/// <summary>
/// Authenticated indicates that the token was associated with a known user.
/// </summary>
public readonly bool Authenticated;
/// <summary>
/// Error indicates that the token couldn't be checked
/// </summary>
public readonly string Error;
/// <summary>
/// User is the UserInfo associated with the provided token.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Authentication.V1Beta1.UserInfo User;
[OutputConstructor]
private TokenReviewStatus(
ImmutableArray<string> audiences,
bool authenticated,
string error,
Pulumi.Kubernetes.Types.Outputs.Authentication.V1Beta1.UserInfo user)
{
Audiences = audiences;
Authenticated = authenticated;
Error = error;
User = user;
}
}
}
| 41.74 | 627 | 0.685194 | [
"Apache-2.0"
] | Teshel/pulumi-kubernetes | sdk/dotnet/Authentication/V1Beta1/Outputs/TokenReviewStatus.cs | 2,087 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.RazorPages;
using socialarts.club.Data;
namespace socialarts.club.Pages.Tools
{
public class PeopleAreDoingTheBestTheyCanModel : ToolsPageModel<PeopleAreDoingTheBestTheyCan>
{
public override string CitationAuthor => "McKay";
public override int CitationYear => 2000;
public PeopleAreDoingTheBestTheyCanModel(
ApplicationDbContext db,
UserManager<IdentityUser> userManager) : base(db, userManager)
{
}
}
}
| 27.083333 | 97 | 0.730769 | [
"MIT"
] | jessejburton/socialarts.club | src/Pages/Tools/PeopleAreDoingTheBestTheyCan.cshtml.cs | 650 | C# |
using System.Collections.Generic;
namespace Edelstein.Common.Gameplay.Stages.Game
{
public record GameStageConfig : ServerStageInfo
{
public int WorldID { get; init; }
public int ChannelID { get; init; }
public override void AddMetadata(IDictionary<string, string> metadata)
{
base.AddMetadata(metadata);
metadata["WorldID"] = WorldID.ToString();
metadata["ChannelID"] = ChannelID.ToString();
}
}
}
| 25.894737 | 78 | 0.626016 | [
"MIT"
] | R3DIANCE/Edelstein | src/common/Edelstein.Common.Gameplay.Stages.Game/GameStageConfig.cs | 494 | C# |
using MySqlConnector.Logging;
using MySqlConnector.Protocol;
using MySqlConnector.Protocol.Serialization;
namespace MySqlConnector.Core;
internal sealed class ConcatenatedCommandPayloadCreator : ICommandPayloadCreator
{
public static ICommandPayloadCreator Instance { get; } = new ConcatenatedCommandPayloadCreator();
public bool WriteQueryCommand(ref CommandListPosition commandListPosition, IDictionary<string, CachedProcedure?> cachedProcedures, ByteBufferWriter writer, bool appendSemicolon)
{
if (commandListPosition.CommandIndex == commandListPosition.Commands.Count)
return false;
writer.Write((byte) CommandKind.Query);
// ConcatenatedCommandPayloadCreator is only used by MySqlBatch, and MySqlBatchCommand doesn't expose attributes,
// so just write an empty attribute set if the server needs it.
if (commandListPosition.Commands[commandListPosition.CommandIndex].Connection!.Session.SupportsQueryAttributes)
{
// attribute count
writer.WriteLengthEncodedInteger(0);
// attribute set count (always 1)
writer.Write((byte) 1);
}
bool isComplete;
do
{
var command = commandListPosition.Commands[commandListPosition.CommandIndex];
if (Log.IsTraceEnabled())
Log.Trace("Session{0} Preparing command payload; CommandText: {1}", command.Connection!.Session.Id, command.CommandText);
isComplete = SingleCommandPayloadCreator.WriteQueryPayload(command, cachedProcedures, writer, commandListPosition.CommandIndex < commandListPosition.Commands.Count - 1 || appendSemicolon);
commandListPosition.CommandIndex++;
}
while (commandListPosition.CommandIndex < commandListPosition.Commands.Count && isComplete);
return true;
}
private static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(ConcatenatedCommandPayloadCreator));
}
| 39.717391 | 191 | 0.80405 | [
"MIT"
] | Muzsor/MySqlConnector | src/MySqlConnector/Core/ConcatenatedCommandPayloadCreator.cs | 1,827 | C# |
using Algebra;
using Algebra.Mappings;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace AtomTests.AdditionTests
{
class AdditionImmutability
{
[Test]
public void CopiesArgumentList()
{
// ARANGE
List<Expression> arguments = new List<Expression>() { Expression.VarX, Expression.VarY, Expression.VarZ };
Expression expression = Expression.Add(arguments);
Expression expected = Expression.VarX + Expression.VarY + Expression.VarZ;
// ACT
arguments.Add(Expression.VarA);
// ASSERT
Assert.AreEqual(expected, expression);
}
[Test]
public void DoesntExposeThroughEvaluator()
{
// ARANGE
Expression expression = Expression.VarX + Expression.VarY + Expression.VarZ;
Expression expected = Expression.VarX + Expression.VarY + Expression.VarZ;
AnonymousMapping<bool> evaluator = new AnonymousMapping<bool>(() => false)
{
Sum = args =>
{
args.Remove(0);
return true;
}
};
// ACT
// ASSERT
Assert.Throws(typeof(NotSupportedException), () => expression.Map(evaluator));
}
}
}
| 28.306122 | 118 | 0.559481 | [
"MIT"
] | Joeoc2001/AlgebraSystem | AlgebraSystem.Test/AtomTests/AdditionTests/AdditionImmutability.cs | 1,389 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class PatternTests : EmitMetadataTestBase
{
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_01()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
}
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_02()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion)
);
}
[Fact]
public void MissingNullable_03()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (12,9): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// switch (x)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (x)
{
case int i: break;
}").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(12, 9),
// (12,9): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// switch (x)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (x)
{
case int i: break;
}").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(12, 9),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36)
);
}
[Fact]
public void MissingNullable_04()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (12,9): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// switch (x)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"switch (x)
{
case int i: break;
}").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(12, 9),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36)
);
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void DoubleEvaluation01()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (TryGet() is int index)
{
Console.WriteLine(index);
}
}
public static int? TryGet()
{
Console.WriteLine(""eval"");
return null;
}
}";
var compilation = CreateStandardCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.Main",
@"{
// Code size 36 (0x24)
.maxstack 1
.locals init (int V_0, //index
bool V_1,
int? V_2)
IL_0000: nop
IL_0001: call ""int? C.TryGet()""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""int int?.GetValueOrDefault()""
IL_000e: stloc.0
IL_000f: ldloca.s V_2
IL_0011: call ""bool int?.HasValue.get""
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: brfalse.s IL_0023
IL_001a: nop
IL_001b: ldloc.0
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: nop
IL_0022: nop
IL_0023: ret
}");
}
[Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")]
public void PatternCrash_01()
{
var source = @"using System;
using System.Collections.Generic;
using System.Linq;
public class Class2 : IDisposable
{
public Class2(bool parameter = false)
{
}
public void Dispose()
{
}
}
class X<T>
{
IdentityAccessor<T> idAccessor = new IdentityAccessor<T>();
void Y<U>() where U : T
{
// BUG: The following line is the problem
if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u)
{
}
}
IEnumerable<T> GetT()
{
yield return default(T);
}
}
class IdentityAccessor<T>
{
public Guid GetId(T t)
{
return Guid.Empty;
}
}";
var compilation = CreateStandardCompilation(source, options: TestOptions.DebugDll, references: new[] { LinqAssemblyRef });
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("X<T>.Y<U>",
@"{
// Code size 67 (0x43)
.maxstack 3
.locals init (U V_0, //u
bool V_1,
object V_2,
U V_3)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()""
IL_0007: ldarg.0
IL_0008: ldftn ""bool X<T>.<Y>b__1_0<U>(T)""
IL_000e: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)""
IL_0013: call ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)""
IL_0018: box ""T""
IL_001d: stloc.2
IL_001e: ldloc.2
IL_001f: isinst ""U""
IL_0024: ldnull
IL_0025: cgt.un
IL_0027: dup
IL_0028: brtrue.s IL_0035
IL_002a: ldloca.s V_3
IL_002c: initobj ""U""
IL_0032: ldloc.3
IL_0033: br.s IL_003b
IL_0035: ldloc.2
IL_0036: unbox.any ""U""
IL_003b: stloc.0
IL_003c: stloc.1
IL_003d: ldloc.1
IL_003e: brfalse.s IL_0042
IL_0040: nop
IL_0041: nop
IL_0042: ret
}");
}
}
}
| 34.434164 | 194 | 0.614303 | [
"Apache-2.0"
] | ElanHasson/roslyn | src/Compilers/CSharp/Test/Emit/CodeGen/PatternTests.cs | 9,678 | C# |
using System;
using System.Numerics;
namespace Bhp.Compiler.JVM
{
public partial class ModuleConverter
{
private BhpCode _Insert1(VM.OpCode code, string comment, BhpMethod to, byte[] data = null)
{
BhpCode _code = new BhpCode();
int startaddr = addr;
_code.addr = addr;
{
_code.debugcode = comment;
_code.debugline = 0;
}
addr++;
_code.code = code;
if (data != null)
{
_code.bytes = data;
addr += _code.bytes.Length;
}
to.body_Codes[startaddr] = _code;
return _code;
}
private BhpCode _InsertPush(byte[] data, string comment, BhpMethod to)
{
if (data.Length == 0) return _Insert1(VM.OpCode.PUSH0, comment, to);
if (data.Length <= 75) return _Insert1((VM.OpCode)data.Length, comment, to, data);
byte prefixLen;
VM.OpCode code;
if (data.Length <= byte.MaxValue)
{
prefixLen = sizeof(byte);
code = VM.OpCode.PUSHDATA1;
}
else if (data.Length <= ushort.MaxValue)
{
prefixLen = sizeof(ushort);
code = VM.OpCode.PUSHDATA2;
}
else
{
prefixLen = sizeof(uint);
code = VM.OpCode.PUSHDATA4;
}
byte[] bytes = new byte[data.Length + prefixLen];
Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, bytes, 0, prefixLen);
Buffer.BlockCopy(data, 0, bytes, prefixLen, data.Length);
return _Insert1(code, comment, to, bytes);
}
private BhpCode _InsertPush(int i, string comment, BhpMethod to)
{
if (i == 0) return _Insert1(VM.OpCode.PUSH0, comment, to);
if (i == -1) return _Insert1(VM.OpCode.PUSHM1, comment, to);
if (i > 0 && i <= 16) return _Insert1((VM.OpCode)(byte)i + 0x50, comment, to);
return _InsertPush(((BigInteger)i).ToByteArray(), comment, to);
}
private BhpCode _Convert1by1(VM.OpCode code, OpCode src, BhpMethod to, byte[] data = null)
{
BhpCode _code = new BhpCode();
int startaddr = addr;
_code.addr = addr;
if (src != null)
{
addrconv[src.addr] = addr;
_code.debugcode = src.debugcode;
_code.debugline = src.debugline;
_code.debugILAddr = src.addr;
_code.debugILCode = src.code.ToString();
}
addr++;
_code.code = code;
if (data != null)
{
_code.bytes = data;
addr += _code.bytes.Length;
}
to.body_Codes[startaddr] = _code;
return _code;
}
private BhpCode _ConvertPush(byte[] data, OpCode src, BhpMethod to)
{
if (data.Length == 0) return _Convert1by1(VM.OpCode.PUSH0, src, to);
//if (data.Length <= 75) return _Convert1by1((VM.OpCode)data.Length, src, to, data);
byte prefixLen;
VM.OpCode code;
if (data.Length <= byte.MaxValue)
{
prefixLen = sizeof(byte);
code = VM.OpCode.PUSHDATA1;
}
else if (data.Length <= ushort.MaxValue)
{
prefixLen = sizeof(ushort);
code = VM.OpCode.PUSHDATA2;
}
else
{
prefixLen = sizeof(uint);
code = VM.OpCode.PUSHDATA4;
}
byte[] bytes = new byte[data.Length + prefixLen];
Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, bytes, 0, prefixLen);
Buffer.BlockCopy(data, 0, bytes, prefixLen, data.Length);
return _Convert1by1(code, src, to, bytes);
}
private BhpCode _ConvertPush(long i, OpCode src, BhpMethod to)
{
if (i == 0) return _Convert1by1(VM.OpCode.PUSH0, src, to);
if (i == -1) return _Convert1by1(VM.OpCode.PUSHM1, src, to);
if (i > 0 && i <= 16) return _Convert1by1((VM.OpCode)(byte)i + 0x50, src, to);
return _ConvertPush(((BigInteger)i).ToByteArray(), src, to);
}
private void _insertBeginCode(JavaMethod from, BhpMethod to)
{
//压入槽位栈
_InsertPush(from.MaxVariableIndex + 1, "begincode", to);
_Insert1(VM.OpCode.NEWARRAY, "", to);
_Insert1(VM.OpCode.TOALTSTACK, "", to);
for (var i = 0; i < from.paramTypes.Count; i++)
{
int pos = 0;
if (from.method.IsStatic)
{
pos = from.argTable[i];
}
else
{//非静态0号是this
pos = from.argTable[i + 1];
}
_Insert1(VM.OpCode.DUPFROMALTSTACK, "init param:" + i, to);
_InsertPush(pos, "", to);
_InsertPush(2, "", to);
_Insert1(VM.OpCode.ROLL, "", to);
_Insert1(VM.OpCode.SETITEM, "", to);
}
////初始化临时槽位位置
//to.addVariablesCount = from.addLocal_VariablesCount;
//for (var i = 0; i < from.addLocal_VariablesCount; i++)
//{
// //to.body_Variables.Add(new JavaParam(src.name, src.type));
// _InsertPush(0, "body_Variables init", to);
//}
}
private void _insertEndCode(JavaMethod from, BhpMethod to, OpCode src)
{
//占位不谢
//_Convert1by1(VM.OpCode.NOP, src, to);
////移除临时槽位
////drop body_Variables
//for (var i = 0; i < from.addLocal_VariablesCount; i++)
//{
// _Insert1(VM.OpCode.DEPTH, "body_Variables drop", to, null);
// _Insert1(VM.OpCode.DEC, null, to, null);
// //push olddepth
// _Insert1(VM.OpCode.FROMALTSTACK, null, to);
// _Insert1(VM.OpCode.DUP, null, to);
// _Insert1(VM.OpCode.TOALTSTACK, null, to);
// //(d-1)-olddepth
// _Insert1(VM.OpCode.SUB, null, to);
// _Insert1(VM.OpCode.XDROP, null, to, null);
//}
////移除参数槽位
//for (var i = 0; i < from.paramTypes.Count; i++)
//{
// //d
// _Insert1(VM.OpCode.DEPTH, "param drop", to, null);
// //push olddepth
// _Insert1(VM.OpCode.FROMALTSTACK, null, to);
// _Insert1(VM.OpCode.DUP, null, to);
// _Insert1(VM.OpCode.DEC, null, to);//深度-1
// _Insert1(VM.OpCode.TOALTSTACK, null, to);
// //(d)-olddepth
// _Insert1(VM.OpCode.SUB, null, to);
// _Insert1(VM.OpCode.XDROP, null, to, null);
//}
//移除深度临时栈
_Insert1(VM.OpCode.FROMALTSTACK, "", to);
_Insert1(VM.OpCode.DROP, "", to);
}
}
}
| 34.947115 | 98 | 0.480946 | [
"MIT"
] | BHPCash/bhp-compiler | bhpj/JVM/Converter_Common.cs | 7,359 | C# |
using System.Threading.Tasks;
using Swisschain.Exchange.Fees.Client.Api;
using Swisschain.Exchange.Fees.Client.Common;
using Swisschain.Exchange.Fees.Client.Models.Settings;
using Swisschain.Exchange.Fees.Contract;
namespace Swisschain.Exchange.Fees.Client.Grpc
{
internal class SettingsApi : BaseGrpcClient, ISettingsApi
{
private readonly Settings.SettingsClient _client;
public SettingsApi(string address) : base(address)
{
_client = new Settings.SettingsClient(Channel);
}
public async Task<SettingsModel> GetByBrokerId(string brokerId)
{
var response = await _client.GetByBrokerIdAsync(new GetSettingsByBrokerIdRequest { BrokerId = brokerId });
if (response.Settings == null)
return null;
return new SettingsModel(response.Settings);
}
}
}
| 30.448276 | 118 | 0.690827 | [
"Apache-2.0"
] | swisschain/Exchange.Fees | src/Fees.Client/Grpc/SettingsApi.cs | 885 | C# |
// by @torahhorse
// Instructions:
// Place on player. OnBelowLevel will get called if the player ever falls below
using UnityEngine;
using System.Collections;
public class CheckIfBelowLevel : MonoBehaviour
{
public float resetBelowThisY = -100f;
public bool fadeInOnReset = true;
private Vector3 startingPosition;
void Awake()
{
startingPosition = transform.position;
}
void Update ()
{
if( transform.position.y < resetBelowThisY )
{
OnBelowLevel();
}
}
private void OnBelowLevel()
{
Debug.Log("Player fell below level");
// reset the player
transform.position = startingPosition;
if( fadeInOnReset )
{
// see if we already have a "camera fade on start"
CameraFadeOnStart fade = GameObject.Find("Main Camera").GetComponent<CameraFadeOnStart>();
if( fade != null )
{
fade.Fade();
}
else
{
Debug.LogWarning("CheckIfBelowLevel couldn't find a CameraFadeOnStart on the main camera");
}
}
// alternatively, you could just reload the current scene using this line:
//Application.LoadLevel(Application.loadedLevel);
}
}
| 20.462963 | 95 | 0.700452 | [
"Unlicense"
] | EmiSchaufeld/cinema-studio-1-final | Cinema/CinemaV/Assets/First Person Drifter Controller/Scripts/Optional/CheckIfBelowLevel.cs | 1,107 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// <Area> Nullable - Box-Unbox </Area>
// <Title> Nullable type with unbox box expr </Title>
// <Description>
// checking type of byte using is operator
// </Description>
// <RelatedBugs> </RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQ(ValueType o)
{
return Helper.Compare((byte)o, Helper.Create(default(byte)));
}
private static bool BoxUnboxToQ(ValueType o)
{
return Helper.Compare((byte?)o, Helper.Create(default(byte)));
}
private static int Main()
{
byte? s = Helper.Create(default(byte));
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| 23.731707 | 71 | 0.651593 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/jit64/valuetypes/nullable/box-unbox/value/box-unbox-value003.cs | 973 | C# |
using System;
namespace ConsoleApp1
{
public static class ExtendSimpleLogger
{
public static void LogError(this ISimpleLogger logger,String message)
{
var defautColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
logger.Log(message, "Error");
Console.ForegroundColor = defautColor;
}
public static void LogWarning(this ISimpleLogger logger, String message)
{
var defautColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
logger.Log(message, "Warning");
Console.ForegroundColor = defautColor;
}
}
}
| 29.4 | 81 | 0.608163 | [
"MIT"
] | migu-chen/tryhelp1 | ConsoleApp1/ExtendSimpleLogger.cs | 737 | C# |
using Ionic.Zlib;
using LiteNetLib;
using Multiplayer.Common;
using RimWorld;
using Steamworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.ComponentModel;
using Verse;
using UnityEngine;
namespace Multiplayer.Client
{
public static class ClientUtil
{
public static void TryConnect(string address, int port)
{
Multiplayer.session = new MultiplayerSession();
Multiplayer.session.mods.remoteAddress = address;
Multiplayer.session.mods.remotePort = port;
NetManager netClient = new NetManager(new MpClientNetListener());
netClient.Start();
netClient.ReconnectDelay = 300;
netClient.MaxConnectAttempts = 8;
Multiplayer.session.netClient = netClient;
netClient.Connect(address, port, "");
}
public static void HostServer(ServerSettings settings, bool fromReplay, bool withSimulation = false, bool debugMode = false, bool logDesyncTraces = false)
{
Log.Message($"Starting the server");
var session = Multiplayer.session = new MultiplayerSession();
session.myFactionId = Faction.OfPlayer.loadID;
session.localSettings = settings;
session.gameName = settings.gameName;
var localServer = new MultiplayerServer(settings);
if (withSimulation)
{
localServer.savedGame = GZipStream.CompressBuffer(OnMainThread.cachedGameData);
localServer.mapData = OnMainThread.cachedMapData.ToDictionary(kv => kv.Key, kv => GZipStream.CompressBuffer(kv.Value));
localServer.mapCmds = OnMainThread.cachedMapCmds.ToDictionary(kv => kv.Key, kv => kv.Value.Select(c => c.Serialize()).ToList());
}
else
{
OnMainThread.ClearCaches();
}
localServer.debugMode = debugMode;
localServer.debugOnlySyncCmds = new HashSet<int>(Sync.handlers.Where(h => h.debugOnly).Select(h => h.syncId));
localServer.hostOnlySyncCmds = new HashSet<int>(Sync.handlers.Where(h => h.hostOnly).Select(h => h.syncId));
localServer.hostUsername = Multiplayer.username;
localServer.coopFactionId = Faction.OfPlayer.loadID;
localServer.rwVersion = session.mods.remoteRwVersion = VersionControl.CurrentVersionString;
localServer.modNames = session.mods.remoteModNames = LoadedModManager.RunningModsListForReading.Select(m => m.Name).ToArray();
localServer.modIds = session.mods.remoteModIds = LoadedModManager.RunningModsListForReading.Select(m => m.PackageId).ToArray();
localServer.workshopModIds = session.mods.remoteWorkshopModIds = ModManagement.GetEnabledWorkshopMods().ToArray();
localServer.defInfos = session.mods.defInfo = Multiplayer.localDefInfos;
Log.Message($"MP Host modIds: {string.Join(", ", localServer.modIds)}");
Log.Message($"MP Host workshopIds: {string.Join(", ", localServer.workshopModIds)}");
if (settings.steam)
localServer.NetTick += SteamIntegration.ServerSteamNetTick;
if (fromReplay)
localServer.gameTimer = TickPatch.Timer;
MultiplayerServer.instance = localServer;
session.localServer = localServer;
if (!fromReplay)
SetupGame();
foreach (var tickable in TickPatch.AllTickables)
tickable.Cmds.Clear();
Find.PlaySettings.usePlanetDayNightSystem = false;
Multiplayer.RealPlayerFaction = Faction.OfPlayer;
localServer.playerFactions[Multiplayer.username] = Faction.OfPlayer.loadID;
SetupLocalClient();
Find.MainTabsRoot.EscapeCurrentTab(false);
Multiplayer.session.AddMsg("If you are having a issue with the mod and would like some help resolving it, then please reach out to us on our discord server:", false);
Multiplayer.session.AddMsg(new ChatMsg_Url("https://discord.gg/S4bxXpv"), false);
if (withSimulation)
{
StartServerThread();
}
else
{
var timeSpeed = TimeSpeed.Paused;
Multiplayer.WorldComp.TimeSpeed = timeSpeed;
foreach (var map in Find.Maps)
map.AsyncTime().TimeSpeed = timeSpeed;
Multiplayer.WorldComp.UpdateTimeSpeed();
Multiplayer.WorldComp.debugMode = debugMode;
Multiplayer.WorldComp.logDesyncTraces = logDesyncTraces;
LongEventHandler.QueueLongEvent(() =>
{
SaveLoad.CacheGameData(SaveLoad.SaveAndReload());
SaveLoad.SendCurrentGameData(false);
StartServerThread();
}, "MpSaving", false, null);
}
void StartServerThread()
{
var netStarted = localServer.StartListeningNet();
var lanStarted = localServer.StartListeningLan();
string text = "Server started.";
if (netStarted != null)
text += (netStarted.Value ? $" Direct at {settings.bindAddress}:{localServer.NetPort}." : " Couldn't bind direct.");
if (lanStarted != null)
text += (lanStarted.Value ? $" LAN at {settings.lanAddress}:{localServer.LanPort}." : " Couldn't bind LAN.");
session.serverThread = new Thread(localServer.Run)
{
Name = "Local server thread"
};
session.serverThread.Start();
Messages.Message(text, MessageTypeDefOf.SilentInput, false);
Log.Message(text);
}
}
private static void SetupGame()
{
MultiplayerWorldComp comp = new MultiplayerWorldComp(Find.World);
Faction dummyFaction = Find.FactionManager.AllFactions.FirstOrDefault(f => f.loadID == -1);
if (dummyFaction == null)
{
dummyFaction = new Faction() { loadID = -1, def = Multiplayer.DummyFactionDef };
foreach (Faction other in Find.FactionManager.AllFactionsListForReading)
dummyFaction.TryMakeInitialRelationsWith(other);
Find.FactionManager.Add(dummyFaction);
comp.factionData[dummyFaction.loadID] = FactionWorldData.New(dummyFaction.loadID);
}
dummyFaction.Name = "Multiplayer dummy faction";
dummyFaction.def = Multiplayer.DummyFactionDef;
Faction.OfPlayer.Name = $"{Multiplayer.username}'s faction";
comp.factionData[Faction.OfPlayer.loadID] = FactionWorldData.FromCurrent();
Multiplayer.game = new MultiplayerGame
{
dummyFaction = dummyFaction,
worldComp = comp
};
comp.globalIdBlock = new IdBlock(GetMaxUniqueId(), 1_000_000_000);
foreach (FactionWorldData data in comp.factionData.Values)
{
foreach (DrugPolicy p in data.drugPolicyDatabase.policies)
p.uniqueId = Multiplayer.GlobalIdBlock.NextId();
foreach (Outfit o in data.outfitDatabase.outfits)
o.uniqueId = Multiplayer.GlobalIdBlock.NextId();
foreach (FoodRestriction o in data.foodRestrictionDatabase.foodRestrictions)
o.id = Multiplayer.GlobalIdBlock.NextId();
}
foreach (Map map in Find.Maps)
{
//mapComp.mapIdBlock = localServer.NextIdBlock();
BeforeMapGeneration.SetupMap(map);
MapAsyncTimeComp async = map.AsyncTime();
async.mapTicks = Find.TickManager.TicksGame;
async.TimeSpeed = Find.TickManager.CurTimeSpeed;
}
Multiplayer.WorldComp.UpdateTimeSpeed();
}
private static void SetupLocalClient()
{
if (Multiplayer.session.localSettings.arbiter)
StartArbiter();
LocalClientConnection localClient = new LocalClientConnection(Multiplayer.username);
LocalServerConnection localServerConn = new LocalServerConnection(Multiplayer.username);
localServerConn.clientSide = localClient;
localClient.serverSide = localServerConn;
localClient.State = ConnectionStateEnum.ClientPlaying;
localServerConn.State = ConnectionStateEnum.ServerPlaying;
var serverPlayer = Multiplayer.LocalServer.OnConnected(localServerConn);
serverPlayer.color = new ColorRGB(255, 0, 0);
serverPlayer.status = PlayerStatus.Playing;
serverPlayer.SendPlayerList();
Multiplayer.session.client = localClient;
Multiplayer.session.ReapplyPrefs();
}
private static void StartArbiter()
{
Multiplayer.session.AddMsg("The Arbiter instance is starting...", false);
Multiplayer.LocalServer.SetupArbiterConnection();
string args = $"-batchmode -nographics -arbiter -logfile arbiter_log.txt -connect=127.0.0.1:{Multiplayer.LocalServer.ArbiterPort}";
if (GenCommandLine.TryGetCommandLineArg("savedatafolder", out string saveDataFolder))
args += $" \"-savedatafolder={saveDataFolder}\"";
string arbiterInstancePath;
if (Application.platform == RuntimePlatform.OSXPlayer) {
arbiterInstancePath = Application.dataPath + "/MacOS/" + Process.GetCurrentProcess().MainModule.ModuleName;
} else {
arbiterInstancePath = Process.GetCurrentProcess().MainModule.FileName;
}
try
{
Multiplayer.session.arbiter = Process.Start(
arbiterInstancePath,
args
);
}
catch (Exception ex)
{
Multiplayer.session.AddMsg("Arbiter failed to start.", false);
Log.Error("Arbiter failed to start.", false);
Log.Error(ex.ToString());
if (ex.InnerException is Win32Exception)
{
Log.Error("Win32 Error Code: " + ((Win32Exception)ex).NativeErrorCode.ToString());
}
}
}
private static int GetMaxUniqueId()
{
return typeof(UniqueIDsManager)
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(f => f.FieldType == typeof(int))
.Select(f => (int)f.GetValue(Find.UniqueIDsManager))
.Max();
}
}
public class MpClientNetListener : INetEventListener
{
public void OnPeerConnected(NetPeer peer)
{
IConnection conn = new MpNetConnection(peer);
conn.username = Multiplayer.username;
conn.State = ConnectionStateEnum.ClientJoining;
Multiplayer.session.client = conn;
Multiplayer.session.ReapplyPrefs();
MpLog.Log("Net client connected");
}
public void OnNetworkError(IPEndPoint endPoint, SocketError error)
{
Log.Warning($"Net client error {error}");
}
public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod method)
{
byte[] data = reader.GetRemainingBytes();
Multiplayer.HandleReceive(new ByteReader(data), method == DeliveryMethod.ReliableOrdered);
}
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo info)
{
var reader = new ByteReader(info.AdditionalData.GetRemainingBytes());
Multiplayer.session.HandleDisconnectReason((MpDisconnectReason)reader.ReadByte(), reader.ReadPrefixedBytes());
ConnectionStatusListeners.TryNotifyAll_Disconnected();
OnMainThread.StopMultiplayer();
MpLog.Log("Net client disconnected");
}
private static string DisconnectReasonString(DisconnectReason reason)
{
switch (reason)
{
case DisconnectReason.ConnectionFailed: return "Connection failed";
case DisconnectReason.ConnectionRejected: return "Connection rejected";
case DisconnectReason.Timeout: return "Timed out";
case DisconnectReason.HostUnreachable: return "Host unreachable";
case DisconnectReason.InvalidProtocol: return "Invalid library protocol";
default: return "Disconnected";
}
}
public void OnConnectionRequest(ConnectionRequest request) { }
public void OnNetworkLatencyUpdate(NetPeer peer, int latency) { }
public void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType) { }
}
public class LocalClientConnection : IConnection
{
public LocalServerConnection serverSide;
public override int Latency { get => 0; set { } }
public LocalClientConnection(string username)
{
this.username = username;
}
protected override void SendRaw(byte[] raw, bool reliable)
{
Multiplayer.LocalServer.Enqueue(() =>
{
try
{
serverSide.HandleReceive(new ByteReader(raw), reliable);
}
catch (Exception e)
{
Log.Error($"Exception handling packet by {serverSide}: {e}");
}
});
}
public override void Close(MpDisconnectReason reason, byte[] data)
{
}
public override string ToString()
{
return "LocalClientConn";
}
}
public class LocalServerConnection : IConnection
{
public LocalClientConnection clientSide;
public override int Latency { get => 0; set { } }
public LocalServerConnection(string username)
{
this.username = username;
}
protected override void SendRaw(byte[] raw, bool reliable)
{
OnMainThread.Enqueue(() =>
{
try
{
clientSide.HandleReceive(new ByteReader(raw), reliable);
}
catch (Exception e)
{
Log.Error($"Exception handling packet by {clientSide}: {e}");
}
});
}
public override void Close(MpDisconnectReason reason, byte[] data)
{
}
public override string ToString()
{
return "LocalServerConn";
}
}
public abstract class SteamBaseConn : IConnection
{
public readonly CSteamID remoteId;
public SteamBaseConn(CSteamID remoteId)
{
this.remoteId = remoteId;
}
protected override void SendRaw(byte[] raw, bool reliable)
{
byte[] full = new byte[1 + raw.Length];
full[0] = reliable ? (byte)2 : (byte)0;
raw.CopyTo(full, 1);
SteamNetworking.SendP2PPacket(remoteId, full, (uint)full.Length, reliable ? EP2PSend.k_EP2PSendReliable : EP2PSend.k_EP2PSendUnreliable, 0);
}
public override void Close(MpDisconnectReason reason, byte[] data)
{
Send(Packets.Special_Steam_Disconnect, GetDisconnectBytes(reason, data));
}
protected override void HandleReceive(int msgId, int fragState, ByteReader reader, bool reliable)
{
if (msgId == (int)Packets.Special_Steam_Disconnect)
{
OnDisconnect();
}
else
{
base.HandleReceive(msgId, fragState, reader, reliable);
}
}
public virtual void OnError(EP2PSessionError error)
{
OnDisconnect();
}
protected abstract void OnDisconnect();
public override string ToString()
{
return $"SteamP2P ({remoteId}) ({username})";
}
}
public class SteamClientConn : SteamBaseConn
{
public SteamClientConn(CSteamID remoteId) : base(remoteId)
{
SteamIntegration.ClearChannel(0);
SteamNetworking.SendP2PPacket(remoteId, new byte[] { 1 }, 1, EP2PSend.k_EP2PSendReliable, 0);
}
protected override void HandleReceive(int msgId, int fragState, ByteReader reader, bool reliable)
{
if (msgId == (int)Packets.Special_Steam_Disconnect)
Multiplayer.session.HandleDisconnectReason((MpDisconnectReason)reader.ReadByte(), reader.ReadPrefixedBytes());
base.HandleReceive(msgId, fragState, reader, reliable);
}
public override void OnError(EP2PSessionError error)
{
Multiplayer.session.disconnectReasonKey = error == EP2PSessionError.k_EP2PSessionErrorTimeout ? "Connection timed out" : "Connection error";
base.OnError(error);
}
protected override void OnDisconnect()
{
ConnectionStatusListeners.TryNotifyAll_Disconnected();
OnMainThread.StopMultiplayer();
}
}
public class SteamServerConn : SteamBaseConn
{
public SteamServerConn(CSteamID remoteId) : base(remoteId)
{
}
protected override void OnDisconnect()
{
serverPlayer.Server.OnDisconnected(this, MpDisconnectReason.ClientLeft);
}
}
}
| 36.593496 | 178 | 0.597923 | [
"MIT"
] | derplayer/RimWorldMultiplayerHeadlessServer | Source/Client/ClientNetworking.cs | 18,004 | C# |
using System;
using HealthChecks.SqlServer;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Collections.Generic;
namespace Microsoft.Extensions.DependencyInjection
{
public static class SqlServerHealthCheckBuilderExtensions
{
private const string HEALTH_QUERY = "SELECT 1;";
private const string NAME = "sqlserver";
/// <summary>
/// Add a health check for SqlServer services.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="connectionString">The Sql Server connection string to be used.</param>
/// <param name="healthQuery">The query to be executed.Optional. If <c>null</c> select 1 is used.</param>
/// <param name="name">The health check name. Optional. If <c>null</c> the type name 'sqlserver' will be used for the name.</param>
/// <param name="failureStatus">
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
/// </param>
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
/// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
public static IHealthChecksBuilder AddSqlServer(this IHealthChecksBuilder builder, string connectionString,
string healthQuery = default, string name = default, HealthStatus? failureStatus = default,
IEnumerable<string> tags = default)
{
return builder.AddSqlServer(_ => connectionString, healthQuery, name, failureStatus, tags);
}
/// <summary>
/// Add a health check for SqlServer services.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="connectionStringFactory">A factory to build the SQL Server connection string to use.</param>
/// <param name="healthQuery">The query to be executed.Optional. If <c>null</c> select 1 is used.</param>
/// <param name="name">The health check name. Optional. If <c>null</c> the type name 'sqlserver' will be used for the name.</param>
/// <param name="failureStatus">
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
/// </param>
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
/// <returns>The <see cref="IHealthChecksBuilder"/>.</returns>
public static IHealthChecksBuilder AddSqlServer(this IHealthChecksBuilder builder,
Func<IServiceProvider, string> connectionStringFactory, string healthQuery = default,
string name = default, HealthStatus? failureStatus = default, IEnumerable<string> tags = default)
{
if (connectionStringFactory == null)
{
throw new ArgumentNullException(nameof(connectionStringFactory));
}
return builder.Add(new HealthCheckRegistration(
name ?? NAME,
sp => new SqlServerHealthCheck(connectionStringFactory(sp), healthQuery ?? HEALTH_QUERY),
failureStatus,
tags));
}
}
}
| 55.587302 | 139 | 0.649058 | [
"Apache-2.0"
] | EnhWeb/AspNetCore.Diagnostics.HealthChecks | src/HealthChecks.SqlServer/DependencyInjection/SqlServerHealthCheckBuilderExtensions.cs | 3,504 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
#if K10
using System.Threading;
using System.Runtime.Loader;
#endif
using System.Threading.Tasks;
using Microsoft.Framework.Runtime.Common.CommandLine;
namespace klr.hosting
{
internal static class RuntimeBootstrapper
{
private static readonly Dictionary<string, Assembly> _assemblyCache = new Dictionary<string, Assembly>();
private static readonly char[] _libPathSeparator = new[] { ';' };
public static int Execute(string[] args)
{
// If we're a console host then print exceptions to stderr
var printExceptionsToStdError = Environment.GetEnvironmentVariable("KRE_CONSOLE_HOST") == "1";
try
{
return ExecuteAsync(args).Result;
}
catch (Exception ex)
{
if (printExceptionsToStdError)
{
PrintErrors(ex);
return 1;
}
throw;
}
}
private static void PrintErrors(Exception ex)
{
var enableTrace = Environment.GetEnvironmentVariable("KRE_TRACE") == "1";
while (ex != null)
{
if (ex is TargetInvocationException ||
ex is AggregateException)
{
// Skip these exception messages as they are
// generic
}
else
{
if (enableTrace)
{
Console.Error.WriteLine(ex);
}
else
{
Console.Error.WriteLine(ex.Message);
}
}
ex = ex.InnerException;
}
}
public static Task<int> ExecuteAsync(string[] args)
{
var enableTrace = Environment.GetEnvironmentVariable("KRE_TRACE") == "1";
#if NET45
// TODO: Make this pluggable and not limited to the console logger
if (enableTrace)
{
var listener = new ConsoleTraceListener();
Trace.Listeners.Add(listener);
Trace.AutoFlush = true;
}
#endif
var app = new CommandLineApplication(throwOnUnexpectedArg: false);
app.Name = "klr";
var optionLib = app.Option("--lib <LIB_PATHS>", "Paths used for library look-up",
CommandOptionType.MultipleValue);
app.HelpOption("-?|-h|--help");
app.VersionOption("--version", GetVersion());
app.Execute(args);
if (!app.IsShowingInformation && !app.RemainingArguments.Any())
{
app.ShowHelp();
}
if (app.IsShowingInformation)
{
return Task.FromResult(0);
}
// Resolve the lib paths
string[] searchPaths = ResolveSearchPaths(optionLib.Values, app.RemainingArguments);
Func<string, Assembly> loader = _ => null;
Func<Stream, Assembly> loadStream = _ => null;
Func<string, Assembly> loadFile = _ => null;
Func<AssemblyName, Assembly> loaderCallback = assemblyName =>
{
string name = assemblyName.Name;
// If the assembly was already loaded use it
Assembly assembly;
if (_assemblyCache.TryGetValue(name, out assembly))
{
return assembly;
}
assembly = loader(name) ?? ResolveHostAssembly(loadFile, searchPaths, name);
if (assembly != null)
{
#if K10
ExtractAssemblyNeutralInterfaces(assembly, loadStream);
#endif
_assemblyCache[name] = assembly;
}
return assembly;
};
#if K10
var loaderImpl = new DelegateAssemblyLoadContext(loaderCallback);
loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, pdbStream: null);
loadFile = path => loaderImpl.LoadFile(path);
AssemblyLoadContext.InitializeDefaultContext(loaderImpl);
if (loaderImpl.EnableMultiCoreJit())
{
loaderImpl.StartMultiCoreJitProfile("startup.prof");
}
#else
var loaderImpl = new LoaderEngine();
loadStream = assemblyStream => loaderImpl.LoadStream(assemblyStream, pdbStream: null);
loadFile = path => loaderImpl.LoadFile(path);
ResolveEventHandler handler = (sender, a) =>
{
// Special case for retargetable assemblies on desktop
if (a.Name.EndsWith("Retargetable=Yes"))
{
return Assembly.Load(a.Name);
}
return loaderCallback(new AssemblyName(a.Name));
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
AppDomain.CurrentDomain.AssemblyLoad += (object sender, AssemblyLoadEventArgs loadedArgs) =>
{
// Skip loading interfaces for dynamic assemblies
if (loadedArgs.LoadedAssembly.IsDynamic)
{
return;
}
ExtractAssemblyNeutralInterfaces(loadedArgs.LoadedAssembly, loadStream);
};
#endif
try
{
var assembly = Assembly.Load(new AssemblyName("klr.host"));
// Loader impl
// var loaderEngine = new DefaultLoaderEngine(loaderImpl);
var loaderEngineType = assembly.GetType("klr.host.DefaultLoaderEngine");
var loaderEngine = Activator.CreateInstance(loaderEngineType, loaderImpl);
// The following code is doing:
// var hostContainer = new klr.host.HostContainer();
// var rootHost = new klr.host.RootHost(loaderEngine, searchPaths);
// hostContainer.AddHost(rootHost);
// var bootstrapper = new klr.host.Bootstrapper(hostContainer, loaderEngine);
// bootstrapper.Main(bootstrapperArgs);
var hostContainerType = assembly.GetType("klr.host.HostContainer");
var rootHostType = assembly.GetType("klr.host.RootHost");
var hostContainer = Activator.CreateInstance(hostContainerType);
var rootHost = Activator.CreateInstance(rootHostType, new object[] { loaderEngine, searchPaths });
MethodInfo addHostMethodInfo = hostContainerType.GetTypeInfo().GetDeclaredMethod("AddHost");
var disposable = (IDisposable)addHostMethodInfo.Invoke(hostContainer, new[] { rootHost });
var hostContainerLoad = hostContainerType.GetTypeInfo().GetDeclaredMethod("Load");
loader = (Func<string, Assembly>)hostContainerLoad.CreateDelegate(typeof(Func<string, Assembly>), hostContainer);
var bootstrapperType = assembly.GetType("klr.host.Bootstrapper");
var mainMethod = bootstrapperType.GetTypeInfo().GetDeclaredMethod("Main");
var bootstrapper = Activator.CreateInstance(bootstrapperType, hostContainer, loaderEngine);
try
{
var bootstrapperArgs = new object[]
{
app.RemainingArguments.ToArray()
};
var task = (Task<int>)mainMethod.Invoke(bootstrapper, bootstrapperArgs);
return task.ContinueWith(async (t, state) =>
{
// Dispose the host
((IDisposable)state).Dispose();
#if NET45
AppDomain.CurrentDomain.AssemblyResolve -= handler;
#endif
return await t;
},
disposable).Unwrap();
}
catch
{
// If we throw synchronously then dispose then rethtrow
disposable.Dispose();
throw;
}
}
catch
{
#if NET45
AppDomain.CurrentDomain.AssemblyResolve -= handler;
#endif
throw;
}
}
private static string[] ResolveSearchPaths(IEnumerable<string> libPaths, List<string> remainingArgs)
{
var searchPaths = new List<string>();
var defaultLibPath = Environment.GetEnvironmentVariable("KRE_DEFAULT_LIB");
if (!string.IsNullOrEmpty(defaultLibPath))
{
// Add the default lib folder if specified
searchPaths.AddRange(ExpandSearchPath(defaultLibPath));
}
// Add the expanded search libs to the list of paths
searchPaths.AddRange(libPaths.SelectMany(ExpandSearchPath));
// If a .dll or .exe is specified then turn this into
// --lib {path to dll/exe} [dll/exe name]
if (remainingArgs.Any())
{
var application = remainingArgs[0];
var extension = Path.GetExtension(application);
if (!string.IsNullOrEmpty(extension) &&
extension.Equals(".dll", StringComparison.OrdinalIgnoreCase) ||
extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
{
// Add the directory to the list of search paths
searchPaths.Add(Path.GetDirectoryName(application));
// Modify the argument to be the dll/exe name
remainingArgs[0] = Path.GetFileNameWithoutExtension(application);
}
}
return searchPaths.ToArray();
}
private static IEnumerable<string> ExpandSearchPath(string libPath)
{
// Expand ; separated arguments
return libPath.Split(_libPathSeparator, StringSplitOptions.RemoveEmptyEntries)
.Select(Path.GetFullPath);
}
private static void ExtractAssemblyNeutralInterfaces(Assembly assembly, Func<Stream, Assembly> load)
{
// Embedded assemblies end with .dll
foreach (var name in assembly.GetManifestResourceNames())
{
if (name.EndsWith(".dll"))
{
var assemblyName = Path.GetFileNameWithoutExtension(name);
if (_assemblyCache.ContainsKey(assemblyName))
{
continue;
}
var neutralAssemblyStream = assembly.GetManifestResourceStream(name);
_assemblyCache[assemblyName] = load(neutralAssemblyStream);
}
}
}
private static Assembly ResolveHostAssembly(Func<string, Assembly> loadFile, IList<string> searchPaths, string name)
{
foreach (var searchPath in searchPaths)
{
var path = Path.Combine(searchPath, name + ".dll");
if (File.Exists(path))
{
return loadFile(path);
}
}
return null;
}
private static string GetVersion()
{
var assembly = typeof(RuntimeBootstrapper).GetTypeInfo().Assembly;
var assemblyInformationalVersionAttribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (assemblyInformationalVersionAttribute == null)
{
return assembly.GetName().Version.ToString();
}
return assemblyInformationalVersionAttribute.InformationalVersion;
}
}
}
| 36.421365 | 129 | 0.544729 | [
"Apache-2.0"
] | augustoproiete-forks/aspnet--dnx | src/klr.hosting.shared/RuntimeBootstrapper.cs | 12,274 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.EntityFrameworkCore.Query.Internal;
using SoftUni.Data;
using SoftUni.Models;
namespace SoftUni
{
public class StartUp
{
static void Main(string[] args)
{
SoftUniContext context = new SoftUniContext();
string result = RemoveTown(context);
Console.WriteLine(result);
}
//Problem 03
public static string GetEmployeesFullInformation(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Select(e => new
{
e.FirstName,
e.LastName,
e.MiddleName,
e.JobTitle,
e.Salary,
e.EmployeeId
})
.OrderBy(e => e.EmployeeId)
.ToList();
foreach (var e in employees)
{
sb.AppendLine($"{e.FirstName} {e.LastName} {e.MiddleName} {e.JobTitle} {e.Salary:f2}");
}
return sb.ToString().TrimEnd();
}
//Problem 04
public static string GetEmployeesWithSalaryOver50000(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Where(e => e.Salary > 50000)
.Select(e => new
{
e.FirstName,
e.Salary
})
.OrderBy(e => e.FirstName)
.ToList();
foreach (var employee in employees)
{
sb.AppendLine($"{employee.FirstName} - {employee.Salary:F2}");
}
return sb.ToString().TrimEnd();
}
//Problem 05
public static string GetEmployeesFromResearchAndDevelopment(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Where(e => e.Department.Name == "Research and Development ")
.Select(e => new
{
e.FirstName,
e.LastName,
DepartmentName = e.Department.Name,
e.Salary
})
.OrderBy(e => e.Salary)
.ThenByDescending(e => e.FirstName)
.ToList();
foreach (var e in employees)
{
sb.AppendLine($"{e.FirstName} {e.LastName} from {e.DepartmentName} - ${e.Salary:f2}");
}
return sb.ToString().TrimEnd();
}
//Problem 06
public static string AddNewAddressToEmployee(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
Address newAddress = new Address()
{
AddressText = "Vitoshka 15",
TownId = 4
};
Employee employeeNakov = context.Employees
.First(e => e.LastName == "Nakov");
employeeNakov.Address = newAddress;
context.SaveChanges();
List<string> addresses = context.Employees
.OrderByDescending(e => e.AddressId)
.Take(10)
.Select(e => e.Address.AddressText)
.ToList();
foreach (string address in addresses)
{
sb.AppendLine(address);
}
return sb.ToString().TrimEnd();
}
//Problem 07
public static string GetEmployeesInPeriod(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Where(e => e.EmployeesProjects
.Any(ep => ep.Project.StartDate.Year >= 2001 &&
ep.Project.StartDate.Year <= 2003))
.Take(10)
.Select(e => new
{
e.FirstName,
e.LastName,
ManagerFirstName = e.Manager.FirstName,
ManagerLastName = e.Manager.LastName,
Projects = e.EmployeesProjects
.Select(ep => new
{
ProjectName = ep.Project.Name,
StartDate = ep.Project.StartDate
.ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture),
EndDate = ep.Project.EndDate.HasValue
? ep.Project
.EndDate
.Value
.ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
: "not finished"
})
.ToList()
})
.ToList();
foreach (var e in employees)
{
sb.AppendLine($"{e.FirstName} {e.LastName} - Manager: {e.ManagerFirstName} {e.ManagerLastName}");
foreach (var pr in e.Projects)
{
sb.AppendLine($"--{pr.ProjectName} - {pr.StartDate} - {pr.EndDate}");
}
}
return sb.ToString().TrimEnd();
}
//Problem 08
public static string GetAddressesByTown(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var addresses = context.Addresses
.Take(10)
.Select(a => new
{
a.AddressText,
TownName = a.Town.Name,
EmployeesCount = a.Employees.Count
})
.OrderByDescending(a => a.EmployeesCount)
.ThenBy(a => a.TownName)
.ThenBy(a => a.AddressText)
.ToList();
foreach (var a in addresses)
{
sb.AppendLine($"{a.AddressText}, {a.TownName} - {a.EmployeesCount} employees");
}
return sb.ToString().TrimEnd();
}
//Problem 09
public static string GetEmployee147(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Where(e => e.EmployeeId == 147)
.Select(e => new
{
e.FirstName,
e.LastName,
e.JobTitle,
Projects = e.EmployeesProjects
.Select(ep => ep.Project.Name)
.OrderBy(pn => pn)
.ToList()
}).Single();
sb.AppendLine($"{employees.FirstName} {employees.LastName} - {employees.JobTitle}");
foreach (var projectName in employees.Projects)
{
sb.AppendLine($"{projectName}");
}
return sb.ToString().TrimEnd();
}
//Problem 10
public static string GetDepartmentsWithMoreThan5Employees(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var departments = context.Departments
.Where(d => d.Employees.Count > 5)
.OrderBy(d => d.Employees.Count)
.ThenBy(d => d.Name)
.Select(d => new
{
d.Name,
ManagerFirstName = d.Manager.FirstName,
ManagderLastName = d.Manager.LastName,
DepEmployees = d.Employees
.Select(e => new
{
EmployeeFirstName = e.FirstName,
EmployeeLastName = e.LastName,
e.JobTitle
}).OrderBy(e => e.EmployeeFirstName)
.ThenBy(e => e.EmployeeLastName)
.ToList()
})
.ToList();
foreach (var d in departments)
{
sb.AppendLine($"{d.Name} - {d.ManagerFirstName} {d.ManagderLastName}");
foreach (var de in d.DepEmployees)
{
sb.AppendLine($"{de.EmployeeFirstName} {de.EmployeeLastName} - {de.JobTitle}");
}
}
return sb.ToString().TrimEnd();
}
//Problem 11
public static string GetLatestProjects(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var lastTenProjects = context.Projects
.OrderByDescending(p => p.StartDate)
.Take(10)
.Select(p => new
{
p.Name,
p.Description,
p.StartDate
})
.OrderBy(p => p.Name)
.ToList();
foreach (var p in lastTenProjects)
{
sb
.AppendLine($"{p.Name}")
.AppendLine($"{p.Description}")
.AppendLine($"{p.StartDate.ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)}");
}
return sb.ToString().TrimEnd();
}
//Problem 12
public static string IncreaseSalaries(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
IQueryable<Employee> employeesToIncrease = context.Employees
.Where(e => e.Department.Name == "Engineering" ||
e.Department.Name == "Tool Design" ||
e.Department.Name == "Marketing" ||
e.Department.Name == "Information Services");
foreach (Employee employee in employeesToIncrease)
{
employee.Salary += employee.Salary * 0.12m;
}
context.SaveChanges();
var employeesInfo = employeesToIncrease
.Select(e => new
{
e.FirstName,
e.LastName,
e.Salary
})
.OrderBy(e => e.FirstName)
.ThenBy(e => e.LastName)
.ToList();
foreach (var employee in employeesInfo)
{
sb.AppendLine($"{employee.FirstName} {employee.LastName} (${employee.Salary:f2})");
}
return sb.ToString().TrimEnd();
}
//Problem 13
public static string GetEmployeesByFirstNameStartingWithSa(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var employees = context.Employees
.Where(e => e.FirstName.StartsWith("Sa"))
.Select(e => new
{
e.FirstName,
e.LastName,
e.JobTitle,
e.Salary
})
.OrderBy(e => e.FirstName)
.ThenBy(e => e.LastName);
foreach (var e in employees)
{
sb.AppendLine($"{e.FirstName} {e.LastName} - {e.JobTitle} - (${e.Salary:f2})");
}
return sb.ToString().TrimEnd();
}
//Problem 14
public static string DeleteProjectById(SoftUniContext context)
{
StringBuilder sb = new StringBuilder();
var project = context.Projects.First(p => p.ProjectId == 2);
context.EmployeesProjects.ToList().ForEach(ep => context.EmployeesProjects.Remove(ep));
context.Projects.Remove(project);
context.SaveChanges();
var projects = context.Projects
.Take(10)
.Select(p =>new
{
p.Name
})
.ToList();
foreach (var p in projects)
{
sb.AppendLine($"{p.Name}");
}
return sb.ToString().TrimEnd();
}
//Problem 15
public static string RemoveTown(SoftUniContext context)
{
Town townToDel = context
.Towns
.First(t => t.Name == "Seattle");
IQueryable<Address> addressesToDelete = context
.Addresses
.Where(a => a.TownId == townToDel.TownId);
int addressesCount = addressesToDelete.Count();
IQueryable<Employee> employeesOnDeletedAddresses = context
.Employees
.Where(e => addressesToDelete.Any(a => a.AddressId == e.AddressId));
foreach (Employee e in employeesOnDeletedAddresses)
{
e.AddressId = null;
}
foreach (var a in addressesToDelete)
{
context
.Addresses
.Remove(a);
}
context.Towns.Remove(townToDel);
context.SaveChanges();
return $"{addressesCount} addresses in Seattle were deleted";
}
}
}
| 31.817967 | 113 | 0.458578 | [
"MIT"
] | dimitarkolev00/SoftUni-DB | Entity Framework Core/03.Entity Framework Introduction/SoftUni/StartUp.cs | 13,461 | C# |
using System;
namespace _05._Game_Of_Intervals
{
class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
double result = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
for (int i = 0; i < n; i++)
{
double num = double.Parse(Console.ReadLine());
if (num >= 0 && num <10)
{
result = result + (num / 100 * 20);
count1 += 1;
}
else if (num >= 10 && num < 20)
{
result = result + (num / 100 * 30);
count2 += 1;
}
else if (num >= 20 && num < 30)
{
result = result + (num / 100 * 40);
count3 += 1;
}
else if (num >= 30 && num < 40)
{
result = result + 50;
count4 += 1;
}
else if (num >= 40 && num <= 50)
{
result = result + 100;
count5 += 1;
}
else
{
result = result / 2;
count6 += 1;
}
}
double totalCount = count1 + count2 + count3 + count4 + count5 + count6;
double A1 = count1 * 1.0 / totalCount * 100;
double A2 = count2 * 1.0 / totalCount * 100;
double A3 = count3 * 1.0 / totalCount * 100;
double A4 = count4 * 1.0 / totalCount * 100;
double A5 = count5 * 1.0 / totalCount * 100;
double A6 = count6 * 1.0 / totalCount * 100;
Console.WriteLine($"{result:f2}");
Console.WriteLine($"From 0 to 9: {A1:f2}%");
Console.WriteLine($"From 10 to 19: {A2:f2}%");
Console.WriteLine($"From 20 to 29: {A3:f2}%");
Console.WriteLine($"From 30 to 39: {A4:f2}%");
Console.WriteLine($"From 40 to 50: {A5:f2}%");
Console.WriteLine($"Invalid numbers: {A6:f2}%");
}
}
}
| 32.194444 | 84 | 0.378775 | [
"MIT"
] | GeorgiGradev/SoftUni | 01. Programming Basics/05.3. MORE - For-Loops/05. Game Of Intervals/Program.cs | 2,320 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EmpowerBusiness
{
using System;
public partial class CMS_Man_ReserveAndPayments_Result
{
public string Type { get; set; }
public string Claimaint { get; set; }
public Nullable<System.DateTime> CreationDate { get; set; }
public Nullable<int> sysID { get; set; }
public Nullable<System.DateTime> ReserveDate { get; set; }
public string TypeDesc { get; set; }
public string TypeCode { get; set; }
public string ExpenseCode { get; set; }
public Nullable<int> CheckNo { get; set; }
public Nullable<int> CheckDate { get; set; }
public int Voided { get; set; }
public Nullable<int> PaymentCode { get; set; }
public Nullable<decimal> ResAmount { get; set; }
public Nullable<decimal> ExpenseAmount { get; set; }
public Nullable<decimal> PayAmount { get; set; }
public Nullable<decimal> RECOVERYAmount { get; set; }
}
}
| 40.970588 | 85 | 0.568557 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerBusiness/CMS_Man_ReserveAndPayments_Result.cs | 1,393 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Clymate.Scaffolding.Sass.Test.MvcWebsite
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 25.333333 | 99 | 0.600329 | [
"MIT"
] | ClydeDz/clymate-scaffolding-sass-nuget | Src/Clymate.Scaffolding.Sass.Test.MvcWebsite/App_Start/RouteConfig.cs | 610 | C# |
// Listener binding interface.
// Copyright (C) 2010 Lex Li
//
// 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 Lextm.SharpSnmpLib.Messaging;
using System.Net;
using System.Threading.Tasks;
namespace Samples.Pipeline
{
/// <summary>
/// Listener binding interface.
/// </summary>
public interface IListenerBinding
{
/// <summary>
/// Sends a response message.
/// </summary>
/// <param name="response">
/// A <see cref="ISnmpMessage"/>.
/// </param>
/// <param name="receiver">Receiver.</param>
void SendResponse(ISnmpMessage response, EndPoint receiver);
/// <summary>
/// Sends a response message.
/// </summary>
/// <param name="response">
/// A <see cref="ISnmpMessage"/>.
/// </param>
/// <param name="receiver">Receiver.</param>
Task SendResponseAsync(ISnmpMessage response, EndPoint receiver);
/// <summary>
/// Endpoint.
/// </summary>
IPEndPoint Endpoint { get; }
}
}
| 38.036364 | 93 | 0.66826 | [
"MIT"
] | fatihGunalp/snmpsharp | Samples.Engine/Pipeline/IListenerBinding.cs | 2,094 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SaaSEqt.Common.Domain.Model;
using SaaSEqt.IdentityAccess.Domain.Model.Identity.Entities;
namespace SaaSEqt.IdentityAccess.Domain.Model.Identity.Events.User
{
public class UserPasswordChanged : IDomainEvent
{
public UserPasswordChanged(
Guid tenantId,
Guid userId,
String username)
{
this.TenantId = tenantId;
this.UserId = userId;
this.Username = username;
this.Version = 1;
this.TimeStamp = DateTimeOffset.Now;
}
public int Version { get; set; }
public DateTimeOffset TimeStamp { get; set; }
public Guid TenantId { get; private set; }
public Guid UserId { get; set; }
public string Username { get; private set; }
}
}
| 25.542857 | 66 | 0.620805 | [
"MIT"
] | Liang-Zhinian/CqrsFrameworkDotNet | Sample/SaaSEqt/IdentityAccess/IdentityAccess/Domain.Model/Identity/Events/User/UserPasswordChanged.cs | 896 | C# |
namespace BashSoft.Contracts
{
public interface IContentComparer
{
void CompareContent(string firstPath, string secondPath);
}
} | 21.285714 | 65 | 0.711409 | [
"MIT"
] | gaydov/Softuni-OOP-Advanced | BashSoft/BashSoft/Contracts/IContentComparer.cs | 151 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Highlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Highlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using Core.Common;
using Orion.Constants;
using Orion.Util.Helpers;
using Orion.Util.Logging;
using Orion.Util.NamedValues;
using FpML.V5r3.Reporting;
using FpML.V5r3.Codes;
using Orion.Util.Serialisation;
using Exception = System.Exception;
namespace Orion.V5r3.Configuration
{
public static class FpMLTradeLoader
{
private static string TradeTypeHelper(FpML.V5r3.Confirmation.Product product)
{
if (product is FpML.V5r3.Confirmation.Swap) return "swap";
if (product is FpML.V5r3.Confirmation.TermDeposit) return "termDeposit";
if (product is FpML.V5r3.Confirmation.BulletPayment) return "bulletPayment";
if (product is FpML.V5r3.Confirmation.BondOption) return "bondOption";
if (product is FpML.V5r3.Confirmation.BrokerEquityOption) return "brokerEquityOption";
if (product is FpML.V5r3.Confirmation.CapFloor) return "capFloor";
if (product is FpML.V5r3.Confirmation.CommodityForward) return "commodityForward";
if (product is FpML.V5r3.Confirmation.CommodityOption) return "commodityOption";
if (product is FpML.V5r3.Confirmation.CommoditySwaption) return "commoditySwaption";
if (product is FpML.V5r3.Confirmation.CommoditySwap) return "commoditySwap";
if (product is FpML.V5r3.Confirmation.CorrelationSwap) return "correlationSwap";
if (product is FpML.V5r3.Confirmation.CreditDefaultSwap) return "creditDefaultSwap";
if (product is FpML.V5r3.Confirmation.CreditDefaultSwapOption) return "creditDefaultSwapOption";
if (product is FpML.V5r3.Confirmation.DividendSwapTransactionSupplement) return "dividendSwapTransactionSupplement";
if (product is FpML.V5r3.Confirmation.EquityForward) return "equityForward";
if (product is FpML.V5r3.Confirmation.EquityOption) return "equityOption";
if (product is FpML.V5r3.Confirmation.EquityOptionTransactionSupplement) return "equityOptionTransactionSupplement";
if (product is FpML.V5r3.Confirmation.ReturnSwap) return "returnSwap";
if (product is FpML.V5r3.Confirmation.EquitySwapTransactionSupplement) return "equitySwapTransactionSupplement";
if (product is FpML.V5r3.Confirmation.Fra ) return "fra";
if (product is FpML.V5r3.Confirmation.FxDigitalOption) return "fxDigitalOption";
if (product is FpML.V5r3.Confirmation.FxOption) return "fxOption";
if (product is FpML.V5r3.Confirmation.FxSingleLeg) return "fxSingleLeg";
if (product is FpML.V5r3.Confirmation.FxSwap) return "fxSwap";
if (product is FpML.V5r3.Confirmation.Strategy) return "strategy";
if (product is FpML.V5r3.Confirmation.Swaption) return "swaption";
if (product is FpML.V5r3.Confirmation.VarianceOptionTransactionSupplement) return "varianceOptionTransactionSupplement";
if (product is FpML.V5r3.Confirmation.VarianceSwap) return "varianceSwap";
if (product is FpML.V5r3.Confirmation.VarianceSwapTransactionSupplement) return "varianceSwapTransactionSupplement";
return "swap";
}
private static string TradeTypeHelper(Product product)
{
if (product is Swap) return "swap";
if (product is TermDeposit) return "termDeposit";
if (product is BulletPayment) return "bulletPayment";
if (product is BondOption) return "bondOption";
if (product is BrokerEquityOption) return "brokerEquityOption";
if (product is CapFloor) return "capFloor";
if (product is CommodityForward) return "commodityForward";
if (product is CommodityOption) return "commodityOption";
if (product is CommoditySwaption) return "commoditySwaption";
if (product is CommoditySwap) return "commoditySwap";
if (product is CorrelationSwap) return "correlationSwap";
if (product is CreditDefaultSwap) return "creditDefaultSwap";
if (product is CreditDefaultSwapOption) return "creditDefaultSwapOption";
if (product is DividendSwapTransactionSupplement) return "dividendSwapTransactionSupplement";
if (product is EquityForward) return "equityForward";
if (product is EquityOption) return "equityOption";
if (product is EquityOptionTransactionSupplement) return "equityOptionTransactionSupplement";
if (product is ReturnSwap) return "returnSwap";
if (product is EquitySwapTransactionSupplement) return "equitySwapTransactionSupplement";
if (product is Fra) return "fra";
if (product is FxDigitalOption) return "fxDigitalOption";
if (product is FxOption) return "fxOption";
if (product is FxSingleLeg) return "fxSingleLeg";
if (product is FxSwap) return "fxSwap";
if (product is Strategy) return "strategy";
if (product is Swaption) return "swaption";
if (product is VarianceOptionTransactionSupplement) return "varianceOptionTransactionSupplement";
if (product is VarianceSwap) return "varianceSwap";
if (product is VarianceSwapTransactionSupplement) return "varianceSwapTransactionSupplement";
return "swap";
}
private class ItemInfo
{
public string ItemName;
public NamedValueSet ItemProps;
}
private static ItemInfo MakeConfirmationTradeProps(string type, string idSuffix, NamedValueSet extraProps, string nameSpace)
{
var itemProps = new NamedValueSet(extraProps);
itemProps.Set(EnvironmentProp.DataGroup, nameSpace + ".Confirmation." + type);
itemProps.Set(EnvironmentProp.SourceSystem, "Murex");
itemProps.Set(EnvironmentProp.Function, FunctionProp.Trade.ToString());
itemProps.Set(EnvironmentProp.Type, type);
itemProps.Set(EnvironmentProp.Schema, "V5r3.Confirmation");
itemProps.Set(EnvironmentProp.NameSpace, nameSpace);
string itemName = nameSpace + "." + type + ".Confirmation.Murex" + (idSuffix != null ? "." + idSuffix : null);
itemProps.Set(TradeProp.UniqueIdentifier, itemName);
//itemProps.Set(TradeProp.TradeDate, null);
//itemProps.Set(CurveProp.MarketAndDate, marketEnv);
return new ItemInfo { ItemName = itemName, ItemProps = itemProps };
}
private static ItemInfo MakeReportingTradeProps(string type, string idSuffix, NamedValueSet extraProps, string nameSpace)
{
var itemProps = new NamedValueSet(extraProps);
itemProps.Set(EnvironmentProp.DataGroup, nameSpace + ".Reporting." + type);
itemProps.Set(EnvironmentProp.SourceSystem, "Murex");
itemProps.Set(EnvironmentProp.Function, FunctionProp.Trade.ToString());
itemProps.Set(EnvironmentProp.Type, type);
itemProps.Set(EnvironmentProp.Schema, "V5r3.Reporting");
itemProps.Set(EnvironmentProp.NameSpace, nameSpace);
string itemName = nameSpace + "." + type + ".Reporting.Murex" + (idSuffix != null ? "." + idSuffix : null);
itemProps.Set(TradeProp.UniqueIdentifier, itemName);
//itemProps.Set(TradeProp.TradeDate, null);
//itemProps.Set(CurveProp.MarketAndDate, marketEnv);
return new ItemInfo { ItemName = itemName, ItemProps = itemProps };
}
public static FpML.V5r3.Confirmation.Trade GetTradeObject(string resourceAsString)
{
//string resourceAsString = ResourceHelper.GetResourceWithPartialName(Assembly.GetExecutingAssembly(), resourceName);
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(resourceAsString);
XmlNameTable xmlNameTable = new NameTable();
var xmlNamespaceManager = new XmlNamespaceManager(xmlNameTable);
xmlNamespaceManager.AddNamespace("fpml", "http://www.fpml.org/FpML-5/confirmation");
XmlNode tradeNode = xmlDocument.SelectSingleNode("//fpml:trade", xmlNamespaceManager);
var trade = XmlSerializerHelper.DeserializeNode<FpML.V5r3.Confirmation.Trade>(tradeNode);
trade.id = resourceAsString;
return trade;
}
//public static FpML.V5r3.Confirmation.RequestConfirmation GetTradeObjectUsingCast(string resourceAsString)
//{
// var confirmation = XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.RequestConfirmation>(resourceAsString);
// return confirmation;
//}
public static Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade> ExtractTradeInfoFromRootNode(string resourceAsString)
{
try
{
var element = XElement.Parse(resourceAsString);
var localName = element.Name.LocalName;
//switch (localName)
//{
if(localName=="requestConfirmation")
{
var confirmation1 = XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.RequestConfirmation>(resourceAsString);
if (confirmation1 != null)
{
var result = new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation1.party, confirmation1.trade);
return result;
}
}
if (localName == "dataDocument")
{
var confirmation2 =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.DataDocument>(
resourceAsString);
if (confirmation2 != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(
confirmation2.party,
confirmation2.trade[0]);
return result;
}
}
if (localName == "confirmationAgreed")
{
var confirmation3 =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ConfirmationAgreed>(
resourceAsString);
if (confirmation3 != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(
confirmation3.party,
confirmation3.trade);
return result;
}
}
if (localName == "executionNotification")
{
var confirmation4 =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ExecutionNotification>(
resourceAsString);
if (confirmation4 != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(
confirmation4.party,
confirmation4.trade);
return result;
}
}
if (localName == "executionRetracted")
{
var confirmation5 =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ExecutionRetracted>(
resourceAsString);
if (confirmation5 != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(
confirmation5.party,
confirmation5.trade);
return result;
}
}
return null;
}
catch (Exception)
{
throw new Exception("This trade has not been serialized.");
}
}
public static Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade> ExtractTradeInfo(string resourceAsString)
{
try
{
var confirmation = XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.RequestConfirmation>(resourceAsString);
if (confirmation != null)
{
var result = new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation.party, confirmation.trade);
return result;
}
}
catch
{
throw new Exception("This trade has not been serialized.");
}
try
{
var confirmation =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.DataDocument>(resourceAsString);
if (confirmation != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation.party,
confirmation.trade[0]);
return result;
}
}
catch
{
throw new Exception("This trade has not been serialized.");
}
try
{
var confirmation =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ConfirmationAgreed>(
resourceAsString);
if (confirmation != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation.party,
confirmation.trade);
return result;
}
}
catch
{
throw new Exception("This trade has not been serialized.");
}
try
{
var confirmation =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ExecutionNotification>(
resourceAsString);
if (confirmation != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation.party,
confirmation.trade);
return result;
}
}
catch
{
throw new Exception("This trade has not been serialized.");
}
try
{
var confirmation =
XmlSerializerHelper.DeserializeFromString<FpML.V5r3.Confirmation.ExecutionRetracted>(
resourceAsString);
if (confirmation != null)
{
var result =
new Pair<FpML.V5r3.Confirmation.Party[], FpML.V5r3.Confirmation.Trade>(confirmation.party,
confirmation.trade);
return result;
}
}
catch
{
throw new Exception("This trade has not been serialized.");
}
return null;
}
public static void LoadTrades1(ILogger logger, ICoreCache targetClient, string nameSpace)
{
logger.LogDebug("Loading trades...");
Assembly assembly = Assembly.GetExecutingAssembly();
const string prefix = "Orion.V5r3.Configuration.TradeData.";
Dictionary<string, string> chosenFiles = ResourceHelper.GetResources(assembly, prefix, "xml");
if (chosenFiles.Count == 0)
throw new InvalidOperationException("Missing Trades");
foreach (KeyValuePair<string, string> file in chosenFiles)
{
var confirmation = ExtractTradeInfoFromRootNode(file.Value);//TODO check ExtractTradeInfo!
var tradeVersion = confirmation.Second;//GetTradeObject(file.Value);
if (tradeVersion != null)
{
var party = confirmation.First;
BuildBothTrades(logger, targetClient, nameSpace, tradeVersion, party);
}
} // foreach file
//as TradeConfirmed
logger.LogDebug("Loaded {0} trades.", chosenFiles.Count);
}
public static void BuildTrade(ILogger logger, ICoreCache targetClient, string nameSpace, Trade tradeVersion, Party[] party)
{
var extraProps = new NamedValueSet();
var party1 = party[0].partyId[0].Value;
var party2 = party[1].partyId[0].Value;
extraProps.Set(TradeProp.Party1, party1);
extraProps.Set(TradeProp.Party2, party2);
//extraProps.Set(TradeProp.CounterPartyId, party2);//Redundant
//extraProps.Set(TradeProp.OriginatingPartyId, party1);//Redundant
extraProps.Set(TradeProp.TradeDate, tradeVersion.tradeHeader.tradeDate.Value);
extraProps.Set(TradeProp.TradingBookName, "Test");
TradeId tradeId;
if (tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[1] is VersionedTradeId tempId)
{
tradeId = tempId.tradeId;
extraProps.Set(TradeProp.TradeId, tradeId.Value);
}
else
{
tradeId = tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[1] as TradeId ??
new TradeId { Value = "temp001" };
extraProps.Set(TradeProp.TradeId, tradeId.Value);
}
//tradeId = (TradeId)tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];
extraProps.Set(TradeProp.TradeState, "Pricing");
//extraProps.Set("TradeType", "Deposit");
extraProps.Set(TradeProp.TradeSource, "FPMLSamples");
extraProps.Set(TradeProp.BaseParty, TradeProp.Party1);//party1
extraProps.Set(TradeProp.CounterPartyName, TradeProp.Party2);//party2
extraProps.Set(TradeProp.AsAtDate, DateTime.Today);
var product = tradeVersion.Item;
var tradeType = TradeTypeHelper(product);
extraProps.Set(TradeProp.TradeType, tradeType);
extraProps.Set(TradeProp.ProductType, tradeType);//TODO this should be a product type...
//Get the required currencies
var currencies = tradeVersion.Item.GetRequiredCurrencies().ToArray();
var curveNames = tradeVersion.Item.GetRequiredPricingStructures().ToArray();
extraProps.Set(TradeProp.RequiredCurrencies, currencies);
extraProps.Set(TradeProp.RequiredPricingStructures, curveNames);
string idSuffix = $"{tradeType}.{tradeId.Value}";
ItemInfo itemInfo2 = MakeReportingTradeProps("Trade", idSuffix, extraProps, nameSpace);
logger.LogDebug(" {0} ...", idSuffix);
targetClient.SaveObject(tradeVersion, itemInfo2.ItemName, itemInfo2.ItemProps, false, TimeSpan.MaxValue);
}
public static void BuildBothTrades(ILogger logger, ICoreCache targetClient, string nameSpace, FpML.V5r3.Confirmation.Trade tradeVersion, FpML.V5r3.Confirmation.Party[] party)
{
var extraProps = new NamedValueSet();
var party1 = party[0].partyId[0].Value;
var party2 = party[1].partyId[0].Value;
extraProps.Set(TradeProp.Party1, party1);
extraProps.Set(TradeProp.Party2, party2);
extraProps.Set(TradeProp.TradeDate, tradeVersion.tradeHeader.tradeDate.Value);
extraProps.Set(TradeProp.TradingBookName, "Test");
FpML.V5r3.Confirmation.TradeId tradeId;
if (tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[1] is FpML.V5r3.Confirmation.VersionedTradeId tempId)
{
tradeId = tempId.tradeId;
extraProps.Set(TradeProp.TradeId, tradeId.Value);
}
else
{
tradeId = tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[1] as FpML.V5r3.Confirmation.TradeId ??
new FpML.V5r3.Confirmation.TradeId {Value = "temp001"};
extraProps.Set(TradeProp.TradeId, tradeId.Value);
}
//tradeId = (TradeId)tradeVersion.tradeHeader.partyTradeIdentifier[0].Items[0];
extraProps.Set(TradeProp.TradeState, "Pricing");
//extraProps.Set("TradeType", "Deposit");
extraProps.Set(TradeProp.TradeSource, "FPMLSamples");
extraProps.Set(TradeProp.BaseParty, TradeProp.Party1);//party1
extraProps.Set(TradeProp.CounterPartyName, TradeProp.Party2);//party2
extraProps.Set(TradeProp.AsAtDate, DateTime.Today);
var product = tradeVersion.Item;
var tradeType = TradeTypeHelper(product);
extraProps.Set(TradeProp.TradeType, tradeType);
extraProps.Set(TradeProp.ProductType, tradeType);//TODO this should be a product type...
//Get the required currencies
//1. need to convert to Reporting namespace, where the functionality exists.
var xml = XmlSerializerHelper.SerializeToString(tradeVersion);
var newxml = xml.Replace("FpML-5/confirmation", "FpML-5/reporting");
var reportingTrade = XmlSerializerHelper.DeserializeFromString<Trade>(newxml);
var currencies = reportingTrade.Item.GetRequiredCurrencies().ToArray();
var curveNames = reportingTrade.Item.GetRequiredPricingStructures().ToArray();
extraProps.Set(TradeProp.RequiredCurrencies, currencies);
extraProps.Set(TradeProp.RequiredPricingStructures, curveNames);
string idSuffix = $"{tradeType}.{tradeId.Value}";
ItemInfo itemInfo = MakeConfirmationTradeProps("Trade", idSuffix, extraProps, nameSpace);
logger.LogDebug(" {0} ...", idSuffix);
targetClient.SaveObject(tradeVersion, itemInfo.ItemName, itemInfo.ItemProps, false, TimeSpan.MaxValue);
ItemInfo itemInfo2 = MakeReportingTradeProps("Trade", idSuffix, extraProps, nameSpace);
logger.LogDebug(" {0} ...", idSuffix);
targetClient.SaveObject(reportingTrade, itemInfo2.ItemName, itemInfo2.ItemProps, false, TimeSpan.MaxValue);
}
}
}
| 53.860987 | 182 | 0.59995 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | Metadata/FpML.V5r3/FpML.V5r3.Reporting.ConfigData/FpMLTradeLoader.cs | 24,024 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MyGameMode : MonoBehaviour
{
public InputHandler playerInputHandler;
public MyPlayer player;
public TriggerVolume[] deathTriggerVolumes;
public TriggerVolume winTriggerVolume;
public GameObject startPosition;
private class InputPermission : InputHandler.PermissionProvider
{
public bool enable;
public bool HasPermission()
{
return enable;
}
}
InputPermission playerInputPermission;
private class PlayerDeathHandler : MyPlayer.DeathHandler
{
MyGameMode myGameMode;
public PlayerDeathHandler(MyGameMode myGameMode)
{
this.myGameMode = myGameMode;
}
public void OnDeath()
{
myGameMode.StartCoroutine(myGameMode.GameOverAndRespawnCoroutine());
}
}
PlayerDeathHandler playerDeathHandler;
public class DeathTriggerVolumeHandler : TriggerVolume.Handler
{
public void OnEnter(TriggerVolume trigger, Collider2D collision)
{
MyPlayer myPlayer = collision.GetComponent<MyPlayer>();
if ( myPlayer != null)
myPlayer.Die();
}
}
DeathTriggerVolumeHandler deathTriggerVolumeHandler;
public class WinTriggerVolumeHandler : TriggerVolume.Handler
{
MyGameMode myGameMode;
public WinTriggerVolumeHandler(MyGameMode myGameMode)
{
this.myGameMode = myGameMode;
}
public void OnEnter(TriggerVolume trigger, Collider2D collision)
{
MyPlayer myPlayer = collision.GetComponent<MyPlayer>();
if (myPlayer != null)
{
myPlayer.Ceremony();
myGameMode.StartCoroutine(myGameMode.GameWinCoroutine());
}
}
}
WinTriggerVolumeHandler winTriggerVolumeHandler;
// Start is called before the first frame update
void Start()
{
playerInputPermission = new InputPermission();
playerInputPermission.enable = true;
playerInputHandler.SetPermissionProvider(playerInputPermission);
playerDeathHandler = new PlayerDeathHandler(this);
player.deathHandler = playerDeathHandler;
deathTriggerVolumeHandler = new DeathTriggerVolumeHandler();
foreach (var volume in deathTriggerVolumes)
volume.handler = deathTriggerVolumeHandler;
winTriggerVolumeHandler = new WinTriggerVolumeHandler(this);
winTriggerVolume.handler = winTriggerVolumeHandler;
}
// Update is called once per frame
void Update()
{
}
IEnumerator GameOverAndRespawnCoroutine()
{
playerInputPermission.enable = false;
Debug.Log("GameOver");
yield return new WaitForSeconds(3);
player.TeleportAt( startPosition.transform.position );
playerInputPermission.enable = true;
}
IEnumerator GameWinCoroutine()
{
playerInputPermission.enable = false;
Debug.Log("GameWin");
yield return new WaitForSeconds(3);
MyGameInstance.instance.hasCleared = true;
SceneManager.LoadScene(0);
}
}
| 29.681818 | 80 | 0.662787 | [
"MIT"
] | Feverfew826/JumpAndReach | Assets/Scripts/MyGameMode.cs | 3,267 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 06:00:27 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using go;
#nullable enable
namespace go {
namespace cmd {
namespace vendor {
namespace golang.org {
namespace x {
namespace sys
{
public static partial class unix_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct RawSockaddrUnix
{
// Constructors
public RawSockaddrUnix(NilType _)
{
this.Len = default;
this.Family = default;
this.Path = default;
}
public RawSockaddrUnix(byte Len = default, byte Family = default, array<byte> Path = default)
{
this.Len = Len;
this.Family = Family;
this.Path = Path;
}
// Enable comparisons between nil and RawSockaddrUnix struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(RawSockaddrUnix value, NilType nil) => value.Equals(default(RawSockaddrUnix));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(RawSockaddrUnix value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, RawSockaddrUnix value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, RawSockaddrUnix value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RawSockaddrUnix(NilType nil) => default(RawSockaddrUnix);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static RawSockaddrUnix RawSockaddrUnix_cast(dynamic value)
{
return new RawSockaddrUnix(value.Len, value.Family, value.Path);
}
}
}}}}}} | 34.028571 | 121 | 0.596977 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_aix_ppc64_RawSockaddrUnixStruct.cs | 2,382 | C# |
/*
* Hydrogen Nucleus API
*
* The Hydrogen Nucleus API
*
* OpenAPI spec version: 1.9.5
* Contact: info@hydrogenplatform.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = Nucleus.Client.SwaggerDateConverter;
namespace Nucleus.ModelEntity
{
/// <summary>
/// Date-Double Mapping Object
/// </summary>
[DataContract]
public partial class DateDoubleVO : IEquatable<DateDoubleVO>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DateDoubleVO" /> class.
/// </summary>
/// <param name="additions">additions.</param>
/// <param name="date">date.</param>
/// <param name="value">value.</param>
public DateDoubleVO(double? additions = default(double?), string date = default(string), double? value = default(double?))
{
this.Additions = additions;
this.Date = date;
this.Value = value;
}
/// <summary>
/// additions
/// </summary>
/// <value>additions</value>
[DataMember(Name="additions", EmitDefaultValue=false)]
public double? Additions { get; set; }
/// <summary>
/// date
/// </summary>
/// <value>date</value>
[DataMember(Name="date", EmitDefaultValue=false)]
public string Date { get; set; }
/// <summary>
/// value
/// </summary>
/// <value>value</value>
[DataMember(Name="value", EmitDefaultValue=false)]
public double? Value { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DateDoubleVO {\n");
sb.Append(" Additions: ").Append(Additions).Append("\n");
sb.Append(" Date: ").Append(Date).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DateDoubleVO);
}
/// <summary>
/// Returns true if DateDoubleVO instances are equal
/// </summary>
/// <param name="input">Instance of DateDoubleVO to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DateDoubleVO input)
{
if (input == null)
return false;
return
(
this.Additions == input.Additions ||
(this.Additions != null &&
this.Additions.Equals(input.Additions))
) &&
(
this.Date == input.Date ||
(this.Date != null &&
this.Date.Equals(input.Date))
) &&
(
this.Value == input.Value ||
(this.Value != null &&
this.Value.Equals(input.Value))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Additions != null)
hashCode = hashCode * 59 + this.Additions.GetHashCode();
if (this.Date != null)
hashCode = hashCode * 59 + this.Date.GetHashCode();
if (this.Value != null)
hashCode = hashCode * 59 + this.Value.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.5875 | 140 | 0.539125 | [
"Apache-2.0"
] | AbhiGupta03/SDK | atom/nucleus/csharp/src/Nucleus/Model/DateDoubleVO.cs | 5,214 | C# |
using System;
using TestHouse.Domain.Enums;
namespace TestHouse.Domain.Models
{
/// <summary>
/// Change history of test case run
/// </summary>
public class TestRunCaseHistory
{
/// <summary>
/// test case run history id
/// </summary>
public long Id { get; private set; }
/// <summary>
/// Type of history
/// </summary>
public RunHistoryType Type { get; private set; }
/// <summary>
/// History message
/// </summary>
public string Message { get; private set; }
/// <summary>
/// Creation date
/// </summary>
public DateTime CreatedAt { get; private set; }
/// <summary>
/// Parent test case run
/// </summary>
public TestRunCase TestCaseRun { get; private set; }
//for ef
private TestRunCaseHistory() { }
public TestRunCaseHistory(RunHistoryType type, string message, TestRunCase testCaseRun)
{
if (string.IsNullOrEmpty(message))
throw new ArgumentException("Message is not specified", "message");
Type = type;
Message = message;
CreatedAt = DateTime.UtcNow;
TestCaseRun = testCaseRun ?? throw new ArgumentException("Test case run is not specified", nameof(testCaseRun));
}
}
} | 27.98 | 124 | 0.553252 | [
"Apache-2.0"
] | another-mi/TestHouse | TestHouse.Domain/Models/TestRunCaseHistory.cs | 1,401 | C# |
// ***********************************************************************
// <copyright file="CsvConfig.cs" company="ServiceStack, Inc.">
// Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************
using System;
using System.Globalization;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
/// <summary>
/// Class CsvConfig.
/// </summary>
public static class CsvConfig
{
/// <summary>
/// Initializes static members of the <see cref="CsvConfig"/> class.
/// </summary>
static CsvConfig()
{
Reset();
}
/// <summary>
/// The s real number culture information
/// </summary>
private static CultureInfo sRealNumberCultureInfo;
/// <summary>
/// Gets or sets the real number culture information.
/// </summary>
/// <value>The real number culture information.</value>
public static CultureInfo RealNumberCultureInfo
{
get => sRealNumberCultureInfo ?? CultureInfo.InvariantCulture;
set => sRealNumberCultureInfo = value;
}
/// <summary>
/// The ts item seperator string
/// </summary>
[ThreadStatic]
private static string tsItemSeperatorString;
/// <summary>
/// The s item seperator string
/// </summary>
private static string sItemSeperatorString;
/// <summary>
/// Gets or sets the item seperator string.
/// </summary>
/// <value>The item seperator string.</value>
public static string ItemSeperatorString
{
get => tsItemSeperatorString ?? sItemSeperatorString ?? JsWriter.ItemSeperatorString;
set
{
tsItemSeperatorString = value;
if (sItemSeperatorString == null) sItemSeperatorString = value;
ResetEscapeStrings();
}
}
/// <summary>
/// The ts item delimiter string
/// </summary>
[ThreadStatic]
private static string tsItemDelimiterString;
/// <summary>
/// The s item delimiter string
/// </summary>
private static string sItemDelimiterString;
/// <summary>
/// Gets or sets the item delimiter string.
/// </summary>
/// <value>The item delimiter string.</value>
public static string ItemDelimiterString
{
get => tsItemDelimiterString ?? sItemDelimiterString ?? JsWriter.QuoteString;
set
{
tsItemDelimiterString = value;
if (sItemDelimiterString == null) sItemDelimiterString = value;
EscapedItemDelimiterString = value + value;
ResetEscapeStrings();
}
}
/// <summary>
/// The default escaped item delimiter string
/// </summary>
private const string DefaultEscapedItemDelimiterString = JsWriter.QuoteString + JsWriter.QuoteString;
/// <summary>
/// The ts escaped item delimiter string
/// </summary>
[ThreadStatic]
private static string tsEscapedItemDelimiterString;
/// <summary>
/// The s escaped item delimiter string
/// </summary>
private static string sEscapedItemDelimiterString;
/// <summary>
/// Gets or sets the escaped item delimiter string.
/// </summary>
/// <value>The escaped item delimiter string.</value>
internal static string EscapedItemDelimiterString
{
get => tsEscapedItemDelimiterString ?? sEscapedItemDelimiterString ?? DefaultEscapedItemDelimiterString;
set
{
tsEscapedItemDelimiterString = value;
if (sEscapedItemDelimiterString == null) sEscapedItemDelimiterString = value;
}
}
/// <summary>
/// The default escape strings
/// </summary>
private static readonly string[] defaultEscapeStrings = GetEscapeStrings();
/// <summary>
/// The ts escape strings
/// </summary>
[ThreadStatic]
private static string[] tsEscapeStrings;
/// <summary>
/// The s escape strings
/// </summary>
private static string[] sEscapeStrings;
/// <summary>
/// Gets the escape strings.
/// </summary>
/// <value>The escape strings.</value>
public static string[] EscapeStrings
{
get => tsEscapeStrings ?? sEscapeStrings ?? defaultEscapeStrings;
private set
{
tsEscapeStrings = value;
if (sEscapeStrings == null) sEscapeStrings = value;
}
}
/// <summary>
/// Gets the escape strings.
/// </summary>
/// <returns>System.String[].</returns>
private static string[] GetEscapeStrings()
{
return new[] { ItemDelimiterString, ItemSeperatorString, RowSeparatorString, "\r", "\n" };
}
/// <summary>
/// Resets the escape strings.
/// </summary>
private static void ResetEscapeStrings()
{
EscapeStrings = GetEscapeStrings();
}
/// <summary>
/// The ts row separator string
/// </summary>
[ThreadStatic]
private static string tsRowSeparatorString;
/// <summary>
/// The s row separator string
/// </summary>
private static string sRowSeparatorString;
/// <summary>
/// Gets or sets the row separator string.
/// </summary>
/// <value>The row separator string.</value>
public static string RowSeparatorString
{
get => tsRowSeparatorString ?? sRowSeparatorString ?? "\r\n";
set
{
tsRowSeparatorString = value;
if (sRowSeparatorString == null) sRowSeparatorString = value;
ResetEscapeStrings();
}
}
/// <summary>
/// Resets this instance.
/// </summary>
public static void Reset()
{
tsItemSeperatorString = sItemSeperatorString = null;
tsItemDelimiterString = sItemDelimiterString = null;
tsEscapedItemDelimiterString = sEscapedItemDelimiterString = null;
tsRowSeparatorString = sRowSeparatorString = null;
tsEscapeStrings = sEscapeStrings = null;
}
}
/// <summary>
/// Class CsvConfig.
/// </summary>
/// <typeparam name="T"></typeparam>
public static class CsvConfig<T>
{
/// <summary>
/// Gets or sets a value indicating whether [omit headers].
/// </summary>
/// <value><c>true</c> if [omit headers]; otherwise, <c>false</c>.</value>
public static bool OmitHeaders { get; set; }
}
} | 34.79717 | 117 | 0.532059 | [
"Apache-2.0"
] | Spinks90/YAFNET | yafsrc/ServiceStack/ServiceStack/Text/CsvConfig.cs | 7,168 | C# |
using System.Threading.Tasks;
namespace RentalSystem.Authentication.External
{
public interface IExternalAuthManager
{
Task<bool> IsValidUser(string provider, string providerKey, string providerAccessCode);
Task<ExternalAuthUserInfo> GetUserInfo(string provider, string accessCode);
}
}
| 26.5 | 95 | 0.761006 | [
"MIT"
] | CiscoNinja/RentalSystem | aspnet-core/src/RentalSystem.Web.Core/Authentication/External/IExternalAuthManager.cs | 320 | C# |
using System;
using System.Text;
namespace BrainAI.AI.GOAP
{
public struct WorldState : IEquatable<WorldState>
{
/// <summary>
/// we use a bitmask shifting on the condition index to flip bits
/// </summary>
public long Values;
/// <summary>
/// bitmask used to explicitly state false. We need a separate store for negatives because the absence of a value doesnt necessarily mean
/// it is false.
/// </summary>
public long DontCare;
/// <summary>
/// required so that we can get the condition index from the string name
/// </summary>
internal ActionPlanner Planner;
public static WorldState Create( ActionPlanner planner )
{
return new WorldState( planner, 0, -1 );
}
public WorldState( ActionPlanner planner, long values, long dontcare )
{
this.Planner = planner;
this.Values = values;
this.DontCare = dontcare;
}
public bool Set( string conditionName, bool value )
{
return this.Set( this.Planner.FindConditionNameIndex( conditionName ), value );
}
internal bool Set( int conditionId, bool value )
{
this.Values = value ? ( this.Values | ( 1L << conditionId ) ) : ( this.Values & ~( 1L << conditionId ) );
this.DontCare ^= ( 1 << conditionId );
return true;
}
public bool Equals( WorldState other )
{
var care = this.DontCare ^ -1L;
return ( this.Values & care ) == ( other.Values & care );
}
/// <summary>
/// for debugging purposes. Provides a human readable string of all the preconditions.
/// </summary>
/// <param name="planner">Planner.</param>
public string Describe( ActionPlanner planner )
{
var sb = new StringBuilder();
for( var i = 0; i < ActionPlanner.MaxConditions; i++ )
{
if( ( this.DontCare & ( 1L << i ) ) == 0 )
{
var val = planner.ConditionNames[i];
if( val == null )
continue;
var set = ( this.Values & ( 1L << i ) ) != 0L;
if( sb.Length > 0 )
sb.Append( ", " );
sb.Append( set ? val.ToUpper() : val );
}
}
return sb.ToString();
}
}
}
| 28.965909 | 145 | 0.503727 | [
"MIT"
] | ApmeM/BrainAI | BrainAI/AI/GOAP/WorldState.cs | 2,551 | C# |
using System;
using SLua;
using System.Collections.Generic;
[UnityEngine.Scripting.Preserve]
public class Lua_UnityEngine_Projector : LuaObject {
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_nearClipPlane(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.nearClipPlane);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_nearClipPlane(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
float v;
checkType(l,2,out v);
self.nearClipPlane=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_farClipPlane(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.farClipPlane);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_farClipPlane(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
float v;
checkType(l,2,out v);
self.farClipPlane=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_fieldOfView(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.fieldOfView);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_fieldOfView(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
float v;
checkType(l,2,out v);
self.fieldOfView=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_aspectRatio(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.aspectRatio);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_aspectRatio(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
float v;
checkType(l,2,out v);
self.aspectRatio=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_orthographic(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.orthographic);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_orthographic(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
bool v;
checkType(l,2,out v);
self.orthographic=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_orthographicSize(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.orthographicSize);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_orthographicSize(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
float v;
checkType(l,2,out v);
self.orthographicSize=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_ignoreLayers(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.ignoreLayers);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_ignoreLayers(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
int v;
checkType(l,2,out v);
self.ignoreLayers=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int get_material(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
pushValue(l,true);
pushValue(l,self.material);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
[UnityEngine.Scripting.Preserve]
static public int set_material(IntPtr l) {
try {
UnityEngine.Projector self=(UnityEngine.Projector)checkSelf(l);
UnityEngine.Material v;
checkType(l,2,out v);
self.material=v;
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[UnityEngine.Scripting.Preserve]
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.Projector");
addMember(l,"nearClipPlane",get_nearClipPlane,set_nearClipPlane,true);
addMember(l,"farClipPlane",get_farClipPlane,set_farClipPlane,true);
addMember(l,"fieldOfView",get_fieldOfView,set_fieldOfView,true);
addMember(l,"aspectRatio",get_aspectRatio,set_aspectRatio,true);
addMember(l,"orthographic",get_orthographic,set_orthographic,true);
addMember(l,"orthographicSize",get_orthographicSize,set_orthographicSize,true);
addMember(l,"ignoreLayers",get_ignoreLayers,set_ignoreLayers,true);
addMember(l,"material",get_material,set_material,true);
createTypeMetatable(l,null, typeof(UnityEngine.Projector),typeof(UnityEngine.Behaviour));
}
}
| 27.122951 | 91 | 0.730281 | [
"MIT"
] | MonkeyKingMKY/luaide-lite | test/slua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Projector.cs | 6,620 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class PlayerResources : MonoBehaviour
{
public static PlayerResources main;
private GameConfig config;
PlayerInventory inventory;
bool resetWasCalled = false;
void Awake()
{
main = this;
}
public void Init()
{
config = Configs.main.Game;
foreach (PlayerResource resource in config.Resources)
{
resource.Value = resource.InitialValue;
resource.Level = 0;
resource.TotalXp = 0;
}
}
void Start()
{
Reset();
HUDManager.main.Refresh();
inventory = Configs.main.PlayerInventory;
}
void Update()
{
}
public void Reset()
{
config = Configs.main.Game;
HUDManager.main.Init();
foreach (PlayerResource resource in config.Resources)
{
resource.Reset();
}
}
public void Gain(PlayerResourceType resourceType, int amount)
{
PlayerResource resource = config.Resources.Find(r => r.Type == resourceType);
resource.Gain(amount);
HUDManager.main.Refresh();
UIManager.main.ShowBillboardText(amount + "xp", Tools.GetPlayerPositionWithOffset(), resource.Icon, resource.Color);
}
public ResetCause GetResetCause() {
PlayerResource energy = config.Resources.Find(r => r.Type == PlayerResourceType.Energy);
PlayerResource health = config.Resources.Find(r => r.Type == PlayerResourceType.Health);
if (energy.Value <= 0) {
return ResetCause.EnergyLoss;
}
if (health.Value <= 0) {
return ResetCause.Death;
}
return ResetCause.None;
}
public bool SpendEnergy(int amount)
{
bool spent = Spend(PlayerResourceType.Energy, amount);
return spent;
}
public void DialogFinished () {
}
public bool Spend(PlayerResourceType resourceType, int amount)
{
bool success = config.Resources
.Find(resource => resource.Type == resourceType)
.Spend(amount);
HUDManager.main.Refresh();
ResetIfNeeded();
return success;
}
private void ResetIfNeeded() {
bool reset = config.Resources.Where(resource => !resource.IsSkill).Any(resource => resource.Value <= 0);
if (reset && !resetWasCalled) {
LoopManager.main.Reset(true);
resetWasCalled = true;
}
}
public float GetDistanceTraveledPerEnergy()
{
var efficiency = getBootsEfficiency(inventory.GetBoots()) * getWalkingSkillEfficiency();
return efficiency * config.BaseDistanceWalkedPerEnergy;
}
public float GetMoveSpeed()
{
InventoryItem boots = inventory.GetBoots();
var moveSpeedIndex = boots == null ? 0 : boots.ItemLevel + 1;
return config.MoveSpeeds[moveSpeedIndex];
}
public int GetEnergyPerStrike()
{
var skillLevel = config.Resources
.Find(resource => resource.Type == PlayerResourceType.StrengthSkill)
.Level;
return Mathf.CeilToInt(config.BaseEnergySpentByHit / (1.0f + 0.5f * skillLevel));
}
private float getBootsEfficiency(InventoryItem item)
{
// 0 = no boots, 1 = slippers (itemlevel = 0) etc.
InventoryItem boots = inventory.GetBoots();
var index = boots == null ? 0 : boots.ItemLevel + 1;
return config.BootsEfficiency[index];
}
private float getWalkingSkillEfficiency()
{
var skillLevel = config.Resources
.Find(resource => resource.Type == PlayerResourceType.AthleticsSkill)
.Level;
return 1.0f + skillLevel * 0.25f;
}
}
[System.Serializable]
public class PlayerResource
{
[SerializeField]
private Sprite resourceIcon;
public Sprite Icon { get { return resourceIcon; } }
[SerializeField]
private Color resourceColor;
public Color Color { get { return resourceColor; } }
[SerializeField]
private PlayerResourceType resourceType;
public PlayerResourceType Type { get { return resourceType; } }
[SerializeField]
private int initialValue;
public int InitialValue { get { return initialValue; } }
[SerializeField]
private bool isSkill = false;
public bool IsSkill { get { return isSkill; } }
private int currentValue;
public int Value { get { return currentValue; } set { currentValue = value; } }
private int totalXp;
public int TotalXp { get { return totalXp; } set { totalXp = value; } }
[SerializeField]
private int baseXpPerLevel = 10;
public int XpPerLevel {
get {
return baseXpPerLevel + 5 * level;
}
}
private int level = 0;
public int Level { get { return level; } set { level = value; } }
public bool Spend(int amount)
{
if (currentValue < amount)
{
currentValue = 0;
return false;
}
else
{
currentValue -= amount;
return true;
}
}
public void Gain(int amount)
{
currentValue += amount;
if (isSkill) {
totalXp += amount;
}
}
public void Reset()
{
if (isSkill)
{
}
else
{
currentValue = initialValue;
}
}
}
public enum PlayerResourceType
{
None,
Energy,
Health,
AthleticsSkill,
StrengthSkill
}
| 26.04955 | 125 | 0.578765 | [
"MIT"
] | bradur/LD47 | Game/Assets/Scripts/PlayerResources/PlayerResources.cs | 5,785 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.Redshift.Model
{
///<summary>
/// Redshift exception
/// </summary>
public class SubscriptionNotFoundException : AmazonRedshiftException
{
/// <summary>
/// Constructs a new SubscriptionNotFoundException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public SubscriptionNotFoundException(string message)
: base(message) {}
public SubscriptionNotFoundException(string message, Exception innerException)
: base(message, innerException) {}
public SubscriptionNotFoundException(Exception innerException)
: base(innerException) {}
public SubscriptionNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, RequestId, statusCode) {}
public SubscriptionNotFoundException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, RequestId, statusCode) {}
}
} | 38.792453 | 171 | 0.68823 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.Redshift/Model/SubscriptionNotFoundException.cs | 2,056 | C# |
using System;
using System.Collections.Generic;
namespace Sekure.Models
{
public class TenantContact
{
public int Id { get; set; }
public Guid TenantId { get; set; }
public virtual Tenant Tenant { get; set; }
public string Email { get; set; }
public string Details { get; set; }
public virtual List<Session> Sessions { get; set; }
public virtual List<Estimate> Estimates { get; set; }
public virtual List<Product> Products { get; set; }
public virtual List<Payment> Payments { get; set; }
public TenantContact(int id, Guid tenantId, string email, string details)
{
Id = id;
TenantId = tenantId;
Email = email;
Details = details;
}
}
} | 30.5 | 81 | 0.583859 | [
"MIT"
] | DeybiSuanca07/sekure-sdk-dotnet | src/Sekure/Models/TenantContact/TenantContact.cs | 795 | C# |
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using static Swifter.Tools.MethodHelper;
using static Swifter.Tools.StringHelper;
namespace Swifter.Tools
{
internal sealed unsafe class Utf16sDifferenceComparer : IDifferenceComparer<Ps<char>>
{
public readonly bool IgnoreCase;
public Utf16sDifferenceComparer(bool ignoreCase)
{
IgnoreCase = ignoreCase;
}
public int ElementAt(Ps<char> str, int index)
{
if (IgnoreCase)
{
return ToLower(str.Pointer[index]);
}
return str.Pointer[index];
}
public void EmitElementAt(ILGenerator ilGen)
{
ilGen.Call(MethodOf<Ps<char>, int, char>(StringHelper.CharAt));
if (IgnoreCase)
{
ilGen.Call(MethodOf<char, char>(ToLower));
}
}
public void EmitEquals(ILGenerator ilGen)
{
if (IgnoreCase)
{
ilGen.Call(MethodOf<Ps<char>, Ps<char>, bool>(EqualsWithIgnoreCase));
}
else
{
ilGen.Call(MethodOf<Ps<char>, Ps<char>, bool>(StringHelper.Equals));
}
}
public void EmitGetHashCode(ILGenerator ilGen)
{
if (IgnoreCase)
{
ilGen.Call(MethodOf<Ps<char>, int>(GetHashCodeWithIgnoreCase));
}
else
{
ilGen.Call(MethodOf<Ps<char>, int>(StringHelper.GetHashCode));
}
}
public void EmitGetLength(ILGenerator ilGen)
{
ilGen.Call(MethodOf<Ps<char>, int>(StringHelper.GetLength));
}
public bool Equals(Ps<char> x, Ps<char> y)
{
if (IgnoreCase)
{
return EqualsWithIgnoreCase(x, y);
}
return StringHelper.Equals(x, y);
}
public int GetHashCode(Ps<char> str)
{
if (IgnoreCase)
{
return GetHashCodeWithIgnoreCase(str);
}
return StringHelper.GetHashCode(str);
}
public int GetLength(Ps<char> str)
{
return str.Length;
}
}
} | 24.817204 | 89 | 0.515165 | [
"MIT"
] | Dogwei/Swifter.Json | Swifter.Core/Tools/Emit/Utf16sDifferenceComparer.cs | 2,310 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace VueValidation.Migrations
{
public partial class InitialCustomer : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Customers",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CompanyName = table.Column<string>(nullable: true),
ContactName = table.Column<string>(nullable: true),
Phone = table.Column<string>(nullable: true),
AddressLine1 = table.Column<string>(nullable: true),
AddressLine2 = table.Column<string>(nullable: true),
CityTown = table.Column<string>(nullable: true),
StateProvince = table.Column<string>(nullable: true),
PostalCode = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Customers", x => x.Id);
});
migrationBuilder.InsertData(
table: "Customers",
columns: new[] { "Id", "AddressLine1", "AddressLine2", "CityTown", "CompanyName", "ContactName", "Country", "Phone", "PostalCode", "StateProvince" },
values: new object[] { 1, "123 Main Street", null, "Atlanta", "Wilder Minds LLC", "Shawn Wildermuth", "USA", "404-555-1212", "12345", "GA" });
migrationBuilder.InsertData(
table: "Customers",
columns: new[] { "Id", "AddressLine1", "AddressLine2", "CityTown", "CompanyName", "ContactName", "Country", "Phone", "PostalCode", "StateProvince" },
values: new object[] { 2, "123 Main Street", null, "Atlanta", "Hello World Film", "Jake Smith", "USA", "404-555-1212", "12345", "GA" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Customers");
}
}
}
| 48.408163 | 165 | 0.56113 | [
"Unlicense"
] | shawnwildermuth/AsyncVuexExample | src/CustomerEditor/Migrations/20190422080047_InitialCustomer.cs | 2,374 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private abstract class GlobalOperationAwareIdleProcessor : IdleProcessor
{
protected readonly IncrementalAnalyzerProcessor Processor;
private readonly IGlobalOperationNotificationService _globalOperationNotificationService;
private TaskCompletionSource<object> _globalOperation;
private Task _globalOperationTask;
public GlobalOperationAwareIdleProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
this.Processor = processor;
_globalOperation = null;
_globalOperationTask = SpecializedTasks.EmptyTask;
_globalOperationNotificationService = globalOperationNotificationService;
_globalOperationNotificationService.Started += OnGlobalOperationStarted;
_globalOperationNotificationService.Stopped += OnGlobalOperationStopped;
if (this.Processor._documentTracker != null)
{
this.Processor._documentTracker.NonRoslynBufferTextChanged += OnNonRoslynBufferTextChanged;
}
}
private void OnNonRoslynBufferTextChanged(object sender, EventArgs e)
{
// There are 2 things incremental processor takes care of
//
// #1 is making sure we delay processing any work until there is enough idle (ex, typing) in host.
// #2 is managing cancellation and pending works.
//
// we used to do #1 and #2 only for Roslyn files. and that is usually fine since most of time solution contains only roslyn files.
//
// but for mixed solution (ex, Roslyn files + HTML + JS + CSS), #2 still makes sense but #1 doesn't. We want
// to pause any work while something is going on in other project types as well.
//
// we need to make sure we play nice with neighbors as well.
//
// now, we don't care where changes are coming from. if there is any change in host, we pause ourselves for a while.
this.UpdateLastAccessTime();
}
protected Task GlobalOperationTask
{
get
{
return _globalOperationTask;
}
}
protected abstract void PauseOnGlobalOperation();
private void OnGlobalOperationStarted(object sender, EventArgs e)
{
Contract.ThrowIfFalse(_globalOperation == null);
// events are serialized. no lock is needed
_globalOperation = new TaskCompletionSource<object>();
_globalOperationTask = _globalOperation.Task;
SolutionCrawlerLogger.LogGlobalOperation(this.Processor._logAggregator);
PauseOnGlobalOperation();
}
private void OnGlobalOperationStopped(object sender, GlobalOperationEventArgs e)
{
if (_globalOperation == null)
{
// we subscribed to the event while it is already running.
return;
}
// events are serialized. no lock is needed
_globalOperation.SetResult(null);
_globalOperation = null;
// set to empty task so that we don't need a lock
_globalOperationTask = SpecializedTasks.EmptyTask;
}
protected abstract Task HigherQueueOperationTask { get; }
protected abstract bool HigherQueueHasWorkItem { get; }
protected async Task WaitForHigherPriorityOperationsAsync()
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_WaitForHigherPriorityOperationsAsync, this.CancellationToken))
{
do
{
// Host is shutting down
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// we wait for global operation and higher queue operation if there is anything going on
if (!this.GlobalOperationTask.IsCompleted || !this.HigherQueueOperationTask.IsCompleted)
{
await Task.WhenAll(this.GlobalOperationTask, this.HigherQueueOperationTask).ConfigureAwait(false);
}
// if there are no more work left for higher queue, then it is our time to go ahead
if (!HigherQueueHasWorkItem)
{
return;
}
// back off and wait for next time slot.
this.UpdateLastAccessTime();
await this.WaitForIdleAsync().ConfigureAwait(false);
}
while (true);
}
}
public virtual void Shutdown()
{
_globalOperationNotificationService.Started -= OnGlobalOperationStarted;
_globalOperationNotificationService.Stopped -= OnGlobalOperationStopped;
if (this.Processor._documentTracker != null)
{
this.Processor._documentTracker.NonRoslynBufferTextChanged -= OnNonRoslynBufferTextChanged;
}
}
}
}
}
}
}
| 47.834395 | 160 | 0.510386 | [
"Apache-2.0"
] | Unknown6656/roslyn | src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.GlobalOperationAwareIdleProcessor.cs | 7,510 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using System;
using System.IO;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Provides input recording into an internal buffer and exporting to files.
/// </summary>
[MixedRealityDataProvider(
typeof(IMixedRealityInputSystem),
(SupportedPlatforms)(-1), // Supported on all platforms
"Input Recording Service",
"Profiles/DefaultMixedRealityInputRecordingProfile.asset",
"MixedRealityToolkit.SDK",
true)]
public class InputRecordingService :
BaseInputDeviceManager,
IMixedRealityInputRecordingService
{
private static readonly int jointCount = Enum.GetNames(typeof(TrackedHandJoint)).Length;
public event Action OnRecordingStarted;
public event Action OnRecordingStopped;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the data provider.</param>
/// <param name="inputSystem">The <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem"/> instance that receives data from this provider.</param>
/// <param name="name">Friendly name of the service.</param>
/// <param name="priority">Service priority. Used to determine order of instantiation.</param>
/// <param name="profile">The service's configuration profile.</param>
[Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")]
public InputRecordingService(
IMixedRealityServiceRegistrar registrar,
IMixedRealityInputSystem inputSystem,
string name = null,
uint priority = DefaultPriority,
BaseMixedRealityProfile profile = null) : this(inputSystem, name, priority, profile)
{
Registrar = registrar;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="inputSystem">The <see cref="Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem"/> instance that receives data from this provider.</param>
/// <param name="name">Friendly name of the service.</param>
/// <param name="priority">Service priority. Used to determine order of instantiation.</param>
/// <param name="profile">The service's configuration profile.</param>
public InputRecordingService(
IMixedRealityInputSystem inputSystem,
string name = null,
uint priority = DefaultPriority,
BaseMixedRealityProfile profile = null) : base(inputSystem, name, priority, profile)
{ }
/// <summary>
/// Return the service profile and ensure that the type is correct.
/// </summary>
public MixedRealityInputRecordingProfile InputRecordingProfile
{
get
{
var profile = ConfigurationProfile as MixedRealityInputRecordingProfile;
if (!profile)
{
Debug.LogError("Profile for Input Recording Service must be a MixedRealityInputRecordingProfile");
}
return profile;
}
}
/// <summary>
/// Service has been enabled.
/// </summary>
public bool IsEnabled { get; private set; } = false;
/// <inheritdoc />
public bool IsRecording { get; private set; } = false;
private bool useBufferTimeLimit = true;
/// <inheritdoc />
public bool UseBufferTimeLimit
{
get { return useBufferTimeLimit; }
set
{
if (useBufferTimeLimit && !value)
{
// Start at buffer limit when making buffer unlimited
unlimitedRecordingStartTime = StartTime;
}
useBufferTimeLimit = value;
if (useBufferTimeLimit)
{
PruneBuffer();
}
}
}
private float recordingBufferTimeLimit = 30.0f;
/// <inheritdoc />
public float RecordingBufferTimeLimit
{
get { return recordingBufferTimeLimit; }
set
{
recordingBufferTimeLimit = Mathf.Max(value, 0.0f);
if (useBufferTimeLimit)
{
PruneBuffer();
}
}
}
private InputAnimation recordingBuffer = null;
// Start time of recording if buffer is unlimited.
// Nullable to determine when time needs to be reset.
private float? unlimitedRecordingStartTime = null;
public float StartTime
{
get
{
if (unlimitedRecordingStartTime.HasValue)
{
if (useBufferTimeLimit)
{
return Mathf.Max(unlimitedRecordingStartTime.Value, Time.time - recordingBufferTimeLimit);
}
else
{
return unlimitedRecordingStartTime.Value;
}
}
return Time.time;
}
}
private void ResetStartTime()
{
if (IsRecording)
{
unlimitedRecordingStartTime = Time.time;
}
else
{
unlimitedRecordingStartTime = null;
}
}
/// <inheritdoc />
public override void Enable()
{
IsEnabled = true;
recordingBuffer = new InputAnimation();
}
/// <inheritdoc />
public override void Disable()
{
IsEnabled = false;
recordingBuffer = null;
ResetStartTime();
}
/// <inheritdoc />
public void StartRecording()
{
IsRecording = true;
if (UseBufferTimeLimit)
{
PruneBuffer();
}
if (!unlimitedRecordingStartTime.HasValue)
{
unlimitedRecordingStartTime = Time.time;
}
OnRecordingStarted?.Invoke();
}
/// <inheritdoc />
public void StopRecording()
{
IsRecording = false;
OnRecordingStopped?.Invoke();
}
/// <inheritdoc />
public override void LateUpdate()
{
if (IsEnabled)
{
if (IsRecording)
{
if (UseBufferTimeLimit)
{
PruneBuffer();
}
RecordKeyframe();
}
}
}
/// <inheritdoc />
public void DiscardRecordedInput()
{
if (IsEnabled)
{
recordingBuffer.Clear();
ResetStartTime();
}
}
/// <summary>
/// Record a keyframe at the given time for the main camera and tracked input devices.
/// </summary>
private void RecordKeyframe()
{
float time = Time.time;
var profile = InputRecordingProfile;
RecordInputHandData(Handedness.Left);
RecordInputHandData(Handedness.Right);
if (CameraCache.Main)
{
var cameraPose = new MixedRealityPose(CameraCache.Main.transform.position, CameraCache.Main.transform.rotation);
recordingBuffer.AddCameraPoseKey(time, cameraPose, profile.CameraPositionThreshold, profile.CameraRotationThreshold);
}
}
/// <summary>
/// Record a keyframe at the given time for a hand with the given handedness it is tracked.
/// </summary>
private bool RecordInputHandData(Handedness handedness)
{
float time = Time.time;
var profile = InputRecordingProfile;
var hand = HandJointUtils.FindHand(handedness);
if (hand == null)
{
recordingBuffer.AddHandStateKey(time, handedness, false, false);
return false;
}
bool isTracked = (hand.TrackingState == TrackingState.Tracked);
// Extract extra information from current interactions
bool isPinching = false;
for (int i = 0; i < hand.Interactions?.Length; i++)
{
var interaction = hand.Interactions[i];
switch (interaction.InputType)
{
case DeviceInputType.Select:
isPinching = interaction.BoolData;
break;
}
}
recordingBuffer.AddHandStateKey(time, handedness, isTracked, isPinching);
if (isTracked)
{
for (int i = 0; i < jointCount; ++i)
{
if (hand.TryGetJoint((TrackedHandJoint)i, out MixedRealityPose jointPose))
{
recordingBuffer.AddHandJointKey(time, handedness, (TrackedHandJoint)i, jointPose, profile.JointPositionThreshold, profile.JointRotationThreshold);
}
}
}
return true;
}
/// <inheritdoc />
public string SaveInputAnimation(string directory = null)
{
return SaveInputAnimation(InputAnimationSerializationUtils.GetOutputFilename(), directory);
}
/// <inheritdoc />
public string SaveInputAnimation(string filename, string directory = null)
{
if (IsEnabled)
{
string path = Path.Combine(directory ?? Application.persistentDataPath, filename);
try
{
using (Stream fileStream = File.Open(path, FileMode.Create))
{
PruneBuffer();
recordingBuffer.ToStream(fileStream, StartTime);
Debug.Log($"Recorded input animation exported to {path}");
}
return path;
}
catch (IOException ex)
{
Debug.LogWarning(ex.Message);
}
}
return "";
}
/// Discard keyframes before the cutoff time.
private void PruneBuffer()
{
recordingBuffer.CutoffBeforeTime(StartTime);
}
}
}
| 33.693252 | 174 | 0.533958 | [
"MIT"
] | MRW-Eric/MixedRealityToolkit-Unity | Assets/MRTK/Services/InputAnimation/InputRecordingService.cs | 10,986 | C# |
#pragma warning disable 0649
#pragma warning disable 0219
// -----------------------------------------------------------------------
// <copyright file="Quality.cs">
// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html
// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/
// </copyright>
// -----------------------------------------------------------------------
namespace TriangleNet
{
using System;
using System.Collections.Generic;
using TriangleNet.Data;
using TriangleNet.Log;
using TriangleNet.Geometry;
/// <summary>
/// Provides methods for mesh quality enforcement and testing.
/// </summary>
class Quality
{
Queue<BadSubseg> badsubsegs;
BadTriQueue queue;
Mesh mesh;
Behavior behavior;
NewLocation newLocation;
// Not used at the moment
Func<Point, Point, Point, double, bool> userTest;
ILog<SimpleLogItem> logger;
public Quality(Mesh mesh)
{
logger = SimpleLog.Instance;
badsubsegs = new Queue<BadSubseg>();
queue = new BadTriQueue();
this.mesh = mesh;
this.behavior = mesh.behavior;
newLocation = new NewLocation(mesh);
}
/// <summary>
/// Add a bad subsegment to the queue.
/// </summary>
/// <param name="badseg">Bad subsegment.</param>
public void AddBadSubseg(BadSubseg badseg)
{
badsubsegs.Enqueue(badseg);
}
#region Check
/// <summary>
/// Test the mesh for topological consistency.
/// </summary>
public bool CheckMesh()
{
Otri tri = default(Otri);
Otri oppotri = default(Otri), oppooppotri = default(Otri);
Vertex triorg, tridest, triapex;
Vertex oppoorg, oppodest;
int horrors;
bool saveexact;
// Temporarily turn on exact arithmetic if it's off.
saveexact = Behavior.NoExact;
Behavior.NoExact = false;
horrors = 0;
// Run through the list of triangles, checking each one.
foreach (var t in mesh.triangles.Values)
{
tri.triangle = t;
// Check all three edges of the triangle.
for (tri.orient = 0; tri.orient < 3; tri.orient++)
{
triorg = tri.Org();
tridest = tri.Dest();
if (tri.orient == 0)
{ // Only test for inversion once.
// Test if the triangle is flat or inverted.
triapex = tri.Apex();
if (Primitives.CounterClockwise(triorg, tridest, triapex) <= 0.0)
{
logger.Warning("Triangle is flat or inverted.",
"Quality.CheckMesh()");
horrors++;
}
}
// Find the neighboring triangle on this edge.
tri.Sym(ref oppotri);
if (oppotri.triangle != Mesh.dummytri)
{
// Check that the triangle's neighbor knows it's a neighbor.
oppotri.Sym(ref oppooppotri);
if ((tri.triangle != oppooppotri.triangle) || (tri.orient != oppooppotri.orient))
{
if (tri.triangle == oppooppotri.triangle)
{
logger.Warning("Asymmetric triangle-triangle bond: (Right triangle, wrong orientation)",
"Quality.CheckMesh()");
}
horrors++;
}
// Check that both triangles agree on the identities
// of their shared vertices.
oppoorg = oppotri.Org();
oppodest = oppotri.Dest();
if ((triorg != oppodest) || (tridest != oppoorg))
{
logger.Warning("Mismatched edge coordinates between two triangles.",
"Quality.CheckMesh()");
horrors++;
}
}
}
}
// Check for unconnected vertices
mesh.MakeVertexMap();
foreach (var v in mesh.vertices.Values)
{
if (v.tri.triangle == null)
{
logger.Warning("Vertex (ID " + v.id + ") not connected to mesh (duplicate input vertex?)",
"Quality.CheckMesh()");
}
}
if (horrors == 0) // && Behavior.Verbose
{
logger.Info("Mesh topology appears to be consistent.");
}
// Restore the status of exact arithmetic.
Behavior.NoExact = saveexact;
return (horrors == 0);
}
/// <summary>
/// Ensure that the mesh is (constrained) Delaunay.
/// </summary>
public bool CheckDelaunay()
{
Otri loop = default(Otri);
Otri oppotri = default(Otri);
Osub opposubseg = default(Osub);
Vertex triorg, tridest, triapex;
Vertex oppoapex;
bool shouldbedelaunay;
int horrors;
bool saveexact;
// Temporarily turn on exact arithmetic if it's off.
saveexact = Behavior.NoExact;
Behavior.NoExact = false;
horrors = 0;
// Run through the list of triangles, checking each one.
foreach (var tri in mesh.triangles.Values)
{
loop.triangle = tri;
// Check all three edges of the triangle.
for (loop.orient = 0; loop.orient < 3;
loop.orient++)
{
triorg = loop.Org();
tridest = loop.Dest();
triapex = loop.Apex();
loop.Sym(ref oppotri);
oppoapex = oppotri.Apex();
// Only test that the edge is locally Delaunay if there is an
// adjoining triangle whose pointer is larger (to ensure that
// each pair isn't tested twice).
shouldbedelaunay = (oppotri.triangle != Mesh.dummytri) &&
!Otri.IsDead(oppotri.triangle) && loop.triangle.id < oppotri.triangle.id &&
(triorg != mesh.infvertex1) && (triorg != mesh.infvertex2) &&
(triorg != mesh.infvertex3) &&
(tridest != mesh.infvertex1) && (tridest != mesh.infvertex2) &&
(tridest != mesh.infvertex3) &&
(triapex != mesh.infvertex1) && (triapex != mesh.infvertex2) &&
(triapex != mesh.infvertex3) &&
(oppoapex != mesh.infvertex1) && (oppoapex != mesh.infvertex2) &&
(oppoapex != mesh.infvertex3);
if (mesh.checksegments && shouldbedelaunay)
{
// If a subsegment separates the triangles, then the edge is
// constrained, so no local Delaunay test should be done.
loop.SegPivot(ref opposubseg);
if (opposubseg.seg != Mesh.dummysub)
{
shouldbedelaunay = false;
}
}
if (shouldbedelaunay)
{
if (Primitives.NonRegular(triorg, tridest, triapex, oppoapex) > 0.0)
{
logger.Warning(String.Format("Non-regular pair of triangles found (IDs {0}/{1}).",
loop.triangle.id, oppotri.triangle.id), "Quality.CheckDelaunay()");
horrors++;
}
}
}
}
if (horrors == 0) // && Behavior.Verbose
{
logger.Info("Mesh is Delaunay.");
}
// Restore the status of exact arithmetic.
Behavior.NoExact = saveexact;
return (horrors == 0);
}
/// <summary>
/// Check a subsegment to see if it is encroached; add it to the list if it is.
/// </summary>
/// <param name="testsubseg">The subsegment to check.</param>
/// <returns>Returns a nonzero value if the subsegment is encroached.</returns>
/// <remarks>
/// A subsegment is encroached if there is a vertex in its diametral lens.
/// For Ruppert's algorithm (-D switch), the "diametral lens" is the
/// diametral circle. For Chew's algorithm (default), the diametral lens is
/// just big enough to enclose two isosceles triangles whose bases are the
/// subsegment. Each of the two isosceles triangles has two angles equal
/// to 'b.minangle'.
///
/// Chew's algorithm does not require diametral lenses at all--but they save
/// time. Any vertex inside a subsegment's diametral lens implies that the
/// triangle adjoining the subsegment will be too skinny, so it's only a
/// matter of time before the encroaching vertex is deleted by Chew's
/// algorithm. It's faster to simply not insert the doomed vertex in the
/// first place, which is why I use diametral lenses with Chew's algorithm.
/// </remarks>
public int CheckSeg4Encroach(ref Osub testsubseg)
{
Otri neighbortri = default(Otri);
Osub testsym = default(Osub);
BadSubseg encroachedseg;
double dotproduct;
int encroached;
int sides;
Vertex eorg, edest, eapex;
encroached = 0;
sides = 0;
eorg = testsubseg.Org();
edest = testsubseg.Dest();
// Check one neighbor of the subsegment.
testsubseg.TriPivot(ref neighbortri);
// Does the neighbor exist, or is this a boundary edge?
if (neighbortri.triangle != Mesh.dummytri)
{
sides++;
// Find a vertex opposite this subsegment.
eapex = neighbortri.Apex();
// Check whether the apex is in the diametral lens of the subsegment
// (the diametral circle if 'conformdel' is set). A dot product
// of two sides of the triangle is used to check whether the angle
// at the apex is greater than (180 - 2 'minangle') degrees (for
// lenses; 90 degrees for diametral circles).
dotproduct = (eorg.x - eapex.x) * (edest.x - eapex.x) +
(eorg.y - eapex.y) * (edest.y - eapex.y);
if (dotproduct < 0.0)
{
if (behavior.ConformingDelaunay ||
(dotproduct * dotproduct >=
(2.0 * behavior.goodAngle - 1.0) * (2.0 * behavior.goodAngle - 1.0) *
((eorg.x - eapex.x) * (eorg.x - eapex.x) +
(eorg.y - eapex.y) * (eorg.y - eapex.y)) *
((edest.x - eapex.x) * (edest.x - eapex.x) +
(edest.y - eapex.y) * (edest.y - eapex.y))))
{
encroached = 1;
}
}
}
// Check the other neighbor of the subsegment.
testsubseg.Sym(ref testsym);
testsym.TriPivot(ref neighbortri);
// Does the neighbor exist, or is this a boundary edge?
if (neighbortri.triangle != Mesh.dummytri)
{
sides++;
// Find the other vertex opposite this subsegment.
eapex = neighbortri.Apex();
// Check whether the apex is in the diametral lens of the subsegment
// (or the diametral circle, if 'conformdel' is set).
dotproduct = (eorg.x - eapex.x) * (edest.x - eapex.x) +
(eorg.y - eapex.y) * (edest.y - eapex.y);
if (dotproduct < 0.0)
{
if (behavior.ConformingDelaunay ||
(dotproduct * dotproduct >=
(2.0 * behavior.goodAngle - 1.0) * (2.0 * behavior.goodAngle - 1.0) *
((eorg.x - eapex.x) * (eorg.x - eapex.x) +
(eorg.y - eapex.y) * (eorg.y - eapex.y)) *
((edest.x - eapex.x) * (edest.x - eapex.x) +
(edest.y - eapex.y) * (edest.y - eapex.y))))
{
encroached += 2;
}
}
}
if (encroached > 0 && (behavior.NoBisect == 0 || ((behavior.NoBisect == 1) && (sides == 2))))
{
// Add the subsegment to the list of encroached subsegments.
// Be sure to get the orientation right.
encroachedseg = new BadSubseg();
if (encroached == 1)
{
encroachedseg.encsubseg = testsubseg;
encroachedseg.subsegorg = eorg;
encroachedseg.subsegdest = edest;
}
else
{
encroachedseg.encsubseg = testsym;
encroachedseg.subsegorg = edest;
encroachedseg.subsegdest = eorg;
}
badsubsegs.Enqueue(encroachedseg);
}
return encroached;
}
/// <summary>
/// Test a triangle for quality and size.
/// </summary>
/// <param name="testtri">Triangle to check.</param>
/// <remarks>
/// Tests a triangle to see if it satisfies the minimum angle condition and
/// the maximum area condition. Triangles that aren't up to spec are added
/// to the bad triangle queue.
/// </remarks>
public void TestTriangle(ref Otri testtri)
{
Otri tri1 = default(Otri), tri2 = default(Otri);
Osub testsub = default(Osub);
Vertex torg, tdest, tapex;
Vertex base1, base2;
Vertex org1, dest1, org2, dest2;
Vertex joinvertex;
double dxod, dyod, dxda, dyda, dxao, dyao;
double dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
double apexlen, orglen, destlen, minedge;
double angle;
double area;
double dist1, dist2;
double maxangle;
torg = testtri.Org();
tdest = testtri.Dest();
tapex = testtri.Apex();
dxod = torg.x - tdest.x;
dyod = torg.y - tdest.y;
dxda = tdest.x - tapex.x;
dyda = tdest.y - tapex.y;
dxao = tapex.x - torg.x;
dyao = tapex.y - torg.y;
dxod2 = dxod * dxod;
dyod2 = dyod * dyod;
dxda2 = dxda * dxda;
dyda2 = dyda * dyda;
dxao2 = dxao * dxao;
dyao2 = dyao * dyao;
// Find the lengths of the triangle's three edges.
apexlen = dxod2 + dyod2;
orglen = dxda2 + dyda2;
destlen = dxao2 + dyao2;
if ((apexlen < orglen) && (apexlen < destlen))
{
// The edge opposite the apex is shortest.
minedge = apexlen;
// Find the square of the cosine of the angle at the apex.
angle = dxda * dxao + dyda * dyao;
angle = angle * angle / (orglen * destlen);
base1 = torg;
base2 = tdest;
testtri.Copy(ref tri1);
}
else if (orglen < destlen)
{
// The edge opposite the origin is shortest.
minedge = orglen;
// Find the square of the cosine of the angle at the origin.
angle = dxod * dxao + dyod * dyao;
angle = angle * angle / (apexlen * destlen);
base1 = tdest;
base2 = tapex;
testtri.Lnext(ref tri1);
}
else
{
// The edge opposite the destination is shortest.
minedge = destlen;
// Find the square of the cosine of the angle at the destination.
angle = dxod * dxda + dyod * dyda;
angle = angle * angle / (apexlen * orglen);
base1 = tapex;
base2 = torg;
testtri.Lprev(ref tri1);
}
if (behavior.VarArea || behavior.fixedArea || behavior.Usertest)
{
// Check whether the area is larger than permitted.
area = 0.5 * (dxod * dyda - dyod * dxda);
if (behavior.fixedArea && (area > behavior.MaxArea))
{
// Add this triangle to the list of bad triangles.
queue.Enqueue(ref testtri, minedge, tapex, torg, tdest);
return;
}
// Nonpositive area constraints are treated as unconstrained.
if ((behavior.VarArea) && (area > testtri.triangle.area) && (testtri.triangle.area > 0.0))
{
// Add this triangle to the list of bad triangles.
queue.Enqueue(ref testtri, minedge, tapex, torg, tdest);
return;
}
// Check whether the user thinks this triangle is too large.
if (behavior.Usertest && userTest != null)
{
if (userTest(torg, tdest, tapex, area))
{
queue.Enqueue(ref testtri, minedge, tapex, torg, tdest);
return;
}
}
}
// find the maximum edge and accordingly the pqr orientation
if ((apexlen > orglen) && (apexlen > destlen))
{
// The edge opposite the apex is longest.
// maxedge = apexlen;
// Find the cosine of the angle at the apex.
maxangle = (orglen + destlen - apexlen) / (2 * Math.Sqrt(orglen * destlen));
}
else if (orglen > destlen)
{
// The edge opposite the origin is longest.
// maxedge = orglen;
// Find the cosine of the angle at the origin.
maxangle = (apexlen + destlen - orglen) / (2 * Math.Sqrt(apexlen * destlen));
}
else
{
// The edge opposite the destination is longest.
// maxedge = destlen;
// Find the cosine of the angle at the destination.
maxangle = (apexlen + orglen - destlen) / (2 * Math.Sqrt(apexlen * orglen));
}
// Check whether the angle is smaller than permitted.
if ((angle > behavior.goodAngle) || (maxangle < behavior.maxGoodAngle && behavior.MaxAngle != 0.0))
{
// Use the rules of Miller, Pav, and Walkington to decide that certain
// triangles should not be split, even if they have bad angles.
// A skinny triangle is not split if its shortest edge subtends a
// small input angle, and both endpoints of the edge lie on a
// concentric circular shell. For convenience, I make a small
// adjustment to that rule: I check if the endpoints of the edge
// both lie in segment interiors, equidistant from the apex where
// the two segments meet.
// First, check if both points lie in segment interiors.
if ((base1.type == VertexType.SegmentVertex) &&
(base2.type == VertexType.SegmentVertex))
{
// Check if both points lie in a common segment. If they do, the
// skinny triangle is enqueued to be split as usual.
tri1.SegPivot(ref testsub);
if (testsub.seg == Mesh.dummysub)
{
// No common segment. Find a subsegment that contains 'torg'.
tri1.Copy(ref tri2);
do
{
tri1.OprevSelf();
tri1.SegPivot(ref testsub);
} while (testsub.seg == Mesh.dummysub);
// Find the endpoints of the containing segment.
org1 = testsub.SegOrg();
dest1 = testsub.SegDest();
// Find a subsegment that contains 'tdest'.
do
{
tri2.DnextSelf();
tri2.SegPivot(ref testsub);
} while (testsub.seg == Mesh.dummysub);
// Find the endpoints of the containing segment.
org2 = testsub.SegOrg();
dest2 = testsub.SegDest();
// Check if the two containing segments have an endpoint in common.
joinvertex = null;
if ((dest1.x == org2.x) && (dest1.y == org2.y))
{
joinvertex = dest1;
}
else if ((org1.x == dest2.x) && (org1.y == dest2.y))
{
joinvertex = org1;
}
if (joinvertex != null)
{
// Compute the distance from the common endpoint (of the two
// segments) to each of the endpoints of the shortest edge.
dist1 = ((base1.x - joinvertex.x) * (base1.x - joinvertex.x) +
(base1.y - joinvertex.y) * (base1.y - joinvertex.y));
dist2 = ((base2.x - joinvertex.x) * (base2.x - joinvertex.x) +
(base2.y - joinvertex.y) * (base2.y - joinvertex.y));
// If the two distances are equal, don't split the triangle.
if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2))
{
// Return now to avoid enqueueing the bad triangle.
return;
}
}
}
}
// Add this triangle to the list of bad triangles.
queue.Enqueue(ref testtri, minedge, tapex, torg, tdest);
}
}
#endregion
#region Maintanance
/// <summary>
/// Traverse the entire list of subsegments, and check each to see if it
/// is encroached. If so, add it to the list.
/// </summary>
private void TallyEncs()
{
Osub subsegloop = default(Osub);
subsegloop.orient = 0;
foreach (var seg in mesh.subsegs.Values)
{
subsegloop.seg = seg;
// If the segment is encroached, add it to the list.
CheckSeg4Encroach(ref subsegloop);
}
}
/// <summary>
/// Split all the encroached subsegments.
/// </summary>
/// <param name="triflaws">A flag that specifies whether one should take
/// note of new bad triangles that result from inserting vertices to repair
/// encroached subsegments.</param>
/// <remarks>
/// Each encroached subsegment is repaired by splitting it - inserting a
/// vertex at or near its midpoint. Newly inserted vertices may encroach
/// upon other subsegments; these are also repaired.
/// </remarks>
private void SplitEncSegs(bool triflaws)
{
Otri enctri = default(Otri);
Otri testtri = default(Otri);
Osub testsh = default(Osub);
Osub currentenc = default(Osub);
BadSubseg seg;
Vertex eorg, edest, eapex;
Vertex newvertex;
InsertVertexResult success;
double segmentlength, nearestpoweroftwo;
double split;
double multiplier, divisor;
bool acuteorg, acuteorg2, acutedest, acutedest2;
// Note that steinerleft == -1 if an unlimited number
// of Steiner points is allowed.
while (badsubsegs.Count > 0)
{
if (mesh.steinerleft == 0)
{
break;
}
seg = badsubsegs.Dequeue();
currentenc = seg.encsubseg;
eorg = currentenc.Org();
edest = currentenc.Dest();
// Make sure that this segment is still the same segment it was
// when it was determined to be encroached. If the segment was
// enqueued multiple times (because several newly inserted
// vertices encroached it), it may have already been split.
if (!Osub.IsDead(currentenc.seg) && (eorg == seg.subsegorg) && (edest == seg.subsegdest))
{
// To decide where to split a segment, we need to know if the
// segment shares an endpoint with an adjacent segment.
// The concern is that, if we simply split every encroached
// segment in its center, two adjacent segments with a small
// angle between them might lead to an infinite loop; each
// vertex added to split one segment will encroach upon the
// other segment, which must then be split with a vertex that
// will encroach upon the first segment, and so on forever.
// To avoid this, imagine a set of concentric circles, whose
// radii are powers of two, about each segment endpoint.
// These concentric circles determine where the segment is
// split. (If both endpoints are shared with adjacent
// segments, split the segment in the middle, and apply the
// concentric circles for later splittings.)
// Is the origin shared with another segment?
currentenc.TriPivot(ref enctri);
enctri.Lnext(ref testtri);
testtri.SegPivot(ref testsh);
acuteorg = testsh.seg != Mesh.dummysub;
// Is the destination shared with another segment?
testtri.LnextSelf();
testtri.SegPivot(ref testsh);
acutedest = testsh.seg != Mesh.dummysub;
// If we're using Chew's algorithm (rather than Ruppert's)
// to define encroachment, delete free vertices from the
// subsegment's diametral circle.
if (!behavior.ConformingDelaunay && !acuteorg && !acutedest)
{
eapex = enctri.Apex();
while ((eapex.type == VertexType.FreeVertex) &&
((eorg.x - eapex.x) * (edest.x - eapex.x) +
(eorg.y - eapex.y) * (edest.y - eapex.y) < 0.0))
{
mesh.DeleteVertex(ref testtri);
currentenc.TriPivot(ref enctri);
eapex = enctri.Apex();
enctri.Lprev(ref testtri);
}
}
// Now, check the other side of the segment, if there's a triangle there.
enctri.Sym(ref testtri);
if (testtri.triangle != Mesh.dummytri)
{
// Is the destination shared with another segment?
testtri.LnextSelf();
testtri.SegPivot(ref testsh);
acutedest2 = testsh.seg != Mesh.dummysub;
acutedest = acutedest || acutedest2;
// Is the origin shared with another segment?
testtri.LnextSelf();
testtri.SegPivot(ref testsh);
acuteorg2 = testsh.seg != Mesh.dummysub;
acuteorg = acuteorg || acuteorg2;
// Delete free vertices from the subsegment's diametral circle.
if (!behavior.ConformingDelaunay && !acuteorg2 && !acutedest2)
{
eapex = testtri.Org();
while ((eapex.type == VertexType.FreeVertex) &&
((eorg.x - eapex.x) * (edest.x - eapex.x) +
(eorg.y - eapex.y) * (edest.y - eapex.y) < 0.0))
{
mesh.DeleteVertex(ref testtri);
enctri.Sym(ref testtri);
eapex = testtri.Apex();
testtri.LprevSelf();
}
}
}
// Use the concentric circles if exactly one endpoint is shared
// with another adjacent segment.
if (acuteorg || acutedest)
{
segmentlength = Math.Sqrt((edest.x - eorg.x) * (edest.x - eorg.x) +
(edest.y - eorg.y) * (edest.y - eorg.y));
// Find the power of two that most evenly splits the segment.
// The worst case is a 2:1 ratio between subsegment lengths.
nearestpoweroftwo = 1.0;
while (segmentlength > 3.0 * nearestpoweroftwo)
{
nearestpoweroftwo *= 2.0;
}
while (segmentlength < 1.5 * nearestpoweroftwo)
{
nearestpoweroftwo *= 0.5;
}
// Where do we split the segment?
split = nearestpoweroftwo / segmentlength;
if (acutedest)
{
split = 1.0 - split;
}
}
else
{
// If we're not worried about adjacent segments, split
// this segment in the middle.
split = 0.5;
}
// Create the new vertex (interpolate coordinates).
newvertex = new Vertex(
eorg.x + split * (edest.x - eorg.x),
eorg.y + split * (edest.y - eorg.y),
currentenc.Mark(),
mesh.nextras);
newvertex.type = VertexType.SegmentVertex;
newvertex.hash = mesh.hash_vtx++;
newvertex.id = newvertex.hash;
mesh.vertices.Add(newvertex.hash, newvertex);
// Interpolate attributes.
for (int i = 0; i < mesh.nextras; i++)
{
newvertex.attributes[i] = eorg.attributes[i]
+ split * (edest.attributes[i] - eorg.attributes[i]);
}
if (!Behavior.NoExact)
{
// Roundoff in the above calculation may yield a 'newvertex'
// that is not precisely collinear with 'eorg' and 'edest'.
// Improve collinearity by one step of iterative refinement.
multiplier = Primitives.CounterClockwise(eorg, edest, newvertex);
divisor = ((eorg.x - edest.x) * (eorg.x - edest.x) +
(eorg.y - edest.y) * (eorg.y - edest.y));
if ((multiplier != 0.0) && (divisor != 0.0))
{
multiplier = multiplier / divisor;
// Watch out for NANs.
if (!double.IsNaN(multiplier))
{
newvertex.x += multiplier * (edest.y - eorg.y);
newvertex.y += multiplier * (eorg.x - edest.x);
}
}
}
// Check whether the new vertex lies on an endpoint.
if (((newvertex.x == eorg.x) && (newvertex.y == eorg.y)) ||
((newvertex.x == edest.x) && (newvertex.y == edest.y)))
{
logger.Error("Ran out of precision: I attempted to split a"
+ " segment to a smaller size than can be accommodated by"
+ " the finite precision of floating point arithmetic.",
"Quality.SplitEncSegs()");
throw new Exception("Ran out of precision");
}
// Insert the splitting vertex. This should always succeed.
success = mesh.InsertVertex(newvertex, ref enctri, ref currentenc, true, triflaws);
if ((success != InsertVertexResult.Successful) && (success != InsertVertexResult.Encroaching))
{
logger.Error("Failure to split a segment.", "Quality.SplitEncSegs()");
throw new Exception("Failure to split a segment.");
}
if (mesh.steinerleft > 0)
{
mesh.steinerleft--;
}
// Check the two new subsegments to see if they're encroached.
CheckSeg4Encroach(ref currentenc);
currentenc.NextSelf();
CheckSeg4Encroach(ref currentenc);
}
// Set subsegment's origin to NULL. This makes it possible to detect dead
// badsubsegs when traversing the list of all badsubsegs.
seg.subsegorg = null;
}
}
/// <summary>
/// Test every triangle in the mesh for quality measures.
/// </summary>
private void TallyFaces()
{
Otri triangleloop = default(Otri);
triangleloop.orient = 0;
foreach (var tri in mesh.triangles.Values)
{
triangleloop.triangle = tri;
// If the triangle is bad, enqueue it.
TestTriangle(ref triangleloop);
}
}
/// <summary>
/// Inserts a vertex at the circumcenter of a triangle. Deletes
/// the newly inserted vertex if it encroaches upon a segment.
/// </summary>
/// <param name="badtri"></param>
private void SplitTriangle(BadTriangle badtri)
{
Otri badotri = default(Otri);
Vertex borg, bdest, bapex;
Point newloc; // Location of the new vertex
double xi = 0, eta = 0;
InsertVertexResult success;
bool errorflag;
badotri = badtri.poortri;
borg = badotri.Org();
bdest = badotri.Dest();
bapex = badotri.Apex();
// Make sure that this triangle is still the same triangle it was
// when it was tested and determined to be of bad quality.
// Subsequent transformations may have made it a different triangle.
if (!Otri.IsDead(badotri.triangle) && (borg == badtri.triangorg) &&
(bdest == badtri.triangdest) && (bapex == badtri.triangapex))
{
errorflag = false;
// Create a new vertex at the triangle's circumcenter.
// Using the original (simpler) Steiner point location method
// for mesh refinement.
// TODO: NewLocation doesn't work for refinement. Why? Maybe
// reset VertexType?
if (behavior.fixedArea || behavior.VarArea)
{
newloc = Primitives.FindCircumcenter(borg, bdest, bapex, ref xi, ref eta, behavior.offconstant);
}
else
{
newloc = newLocation.FindLocation(borg, bdest, bapex, ref xi, ref eta, true, badotri);
}
// Check whether the new vertex lies on a triangle vertex.
if (((newloc.x == borg.x) && (newloc.y == borg.y)) ||
((newloc.x == bdest.x) && (newloc.y == bdest.y)) ||
((newloc.x == bapex.x) && (newloc.y == bapex.y)))
{
if (Behavior.Verbose)
{
logger.Warning("New vertex falls on existing vertex.", "Quality.SplitTriangle()");
errorflag = true;
}
}
else
{
// The new vertex must be in the interior, and therefore is a
// free vertex with a marker of zero.
Vertex newvertex = new Vertex(newloc.x, newloc.y, 0, mesh.nextras);
newvertex.type = VertexType.FreeVertex;
for (int i = 0; i < mesh.nextras; i++)
{
// Interpolate the vertex attributes at the circumcenter.
newvertex.attributes[i] = borg.attributes[i]
+ xi * (bdest.attributes[i] - borg.attributes[i])
+ eta * (bapex.attributes[i] - borg.attributes[i]);
}
// Ensure that the handle 'badotri' does not represent the longest
// edge of the triangle. This ensures that the circumcenter must
// fall to the left of this edge, so point location will work.
// (If the angle org-apex-dest exceeds 90 degrees, then the
// circumcenter lies outside the org-dest edge, and eta is
// negative. Roundoff error might prevent eta from being
// negative when it should be, so I test eta against xi.)
if (eta < xi)
{
badotri.LprevSelf();
}
// Insert the circumcenter, searching from the edge of the triangle,
// and maintain the Delaunay property of the triangulation.
Osub tmp = default(Osub);
success = mesh.InsertVertex(newvertex, ref badotri, ref tmp, true, true);
if (success == InsertVertexResult.Successful)
{
newvertex.hash = mesh.hash_vtx++;
newvertex.id = newvertex.hash;
mesh.vertices.Add(newvertex.hash, newvertex);
if (mesh.steinerleft > 0)
{
mesh.steinerleft--;
}
}
else if (success == InsertVertexResult.Encroaching)
{
// If the newly inserted vertex encroaches upon a subsegment,
// delete the new vertex.
mesh.UndoVertex();
}
else if (success == InsertVertexResult.Violating)
{
// Failed to insert the new vertex, but some subsegment was
// marked as being encroached.
}
else
{ // success == DUPLICATEVERTEX
// Couldn't insert the new vertex because a vertex is already there.
if (Behavior.Verbose)
{
logger.Warning("New vertex falls on existing vertex.", "Quality.SplitTriangle()");
errorflag = true;
}
}
}
if (errorflag)
{
logger.Error("The new vertex is at the circumcenter of triangle: This probably "
+ "means that I am trying to refine triangles to a smaller size than can be "
+ "accommodated by the finite precision of floating point arithmetic.",
"Quality.SplitTriangle()");
throw new Exception("The new vertex is at the circumcenter of triangle.");
}
}
}
/// <summary>
/// Remove all the encroached subsegments and bad triangles from the triangulation.
/// </summary>
public void EnforceQuality()
{
BadTriangle badtri;
// Test all segments to see if they're encroached.
TallyEncs();
// Fix encroached subsegments without noting bad triangles.
SplitEncSegs(false);
// At this point, if we haven't run out of Steiner points, the
// triangulation should be (conforming) Delaunay.
// Next, we worry about enforcing triangle quality.
if ((behavior.MinAngle > 0.0) || behavior.VarArea || behavior.fixedArea || behavior.Usertest)
{
// TODO: Reset queue? (Or is it always empty at this point)
// Test all triangles to see if they're bad.
TallyFaces();
mesh.checkquality = true;
while ((queue.Count > 0) && (mesh.steinerleft != 0))
{
// Fix one bad triangle by inserting a vertex at its circumcenter.
badtri = queue.Dequeue();
SplitTriangle(badtri);
if (badsubsegs.Count > 0)
{
// Put bad triangle back in queue for another try later.
queue.Enqueue(badtri);
// Fix any encroached subsegments that resulted.
// Record any new bad triangles that result.
SplitEncSegs(true);
}
}
}
// At this point, if the "-D" switch was selected and we haven't run out
// of Steiner points, the triangulation should be (conforming) Delaunay
// and have no low-quality triangles.
// Might we have run out of Steiner points too soon?
if (Behavior.Verbose && behavior.ConformingDelaunay && (badsubsegs.Count > 0) && (mesh.steinerleft == 0))
{
logger.Warning("I ran out of Steiner points, but the mesh has encroached subsegments, "
+ "and therefore might not be truly Delaunay. If the Delaunay property is important "
+ "to you, try increasing the number of Steiner points.",
"Quality.EnforceQuality()");
}
}
#endregion
}
}
| 44.450199 | 120 | 0.462602 | [
"MIT"
] | eppz/Deprecated.Unity.Library.eppz | Geometry/Triangle.NET/Triangle/Quality.cs | 44,630 | C# |
using NAME.Core;
using NAME.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NAME.Json;
namespace NAME.Dependencies
{
/// <summary>
/// Represents a versioned dependency.
/// </summary>
/// <seealso cref="NAME.Dependencies.Dependency" />
internal abstract class VersionedDependency : Dependency
{
/// <summary>
/// Initializes a new instance of the <see cref="VersionedDependency"/> class.
/// </summary>
/// <param name="versionResolver">The version resolver.</param>
public VersionedDependency(IVersionResolver versionResolver)
{
this.VersionResolver = versionResolver;
}
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>
/// The type.
/// </value>
public SupportedDependencies Type { get; set; }
/// <summary>
/// Gets or sets the minimum version.
/// </summary>
/// <value>
/// The minimum version.
/// </value>
public DependencyVersion MinimumVersion { get; set; }
/// <summary>
/// Gets or sets the maximum version. If this value is null, it means there is no upper bound.
/// </summary>
/// <value>
/// The maximum version.
/// </value>
public DependencyVersion MaximumVersion { get; set; }
/// <summary>
/// Gets the version resolver.
/// </summary>
/// <value>
/// The version resolver.
/// </value>
protected IVersionResolver VersionResolver { get; }
/// <summary>
/// Determines the dependency status.
/// </summary>
/// <returns>
/// Returns a task that represents the asynchronous operation. The result contains the status of the dependency.
/// </returns>
public override async Task<DependencyCheckStatus> GetStatus()
{
try
{
IEnumerable<DependencyVersion> actualVersions = await this.VersionResolver.GetVersions().ConfigureAwait(false);
if (!actualVersions.Any())
return new DependencyCheckStatus(false, message: "Could not fetch the versions.");
foreach (var version in actualVersions)
{
if (version < this.MinimumVersion || (this.MaximumVersion != null && version > this.MaximumVersion))
{
return new DependencyCheckStatus(false, version: version, message: "Unsupported version.");
}
}
return new DependencyCheckStatus(true, actualVersions.FirstOrDefault());
}
catch (Exception ex)
{
return new DependencyCheckStatus(false, message: ex.Message, innerException: ex);
}
}
internal override async Task<JsonNode> ToJson()
{
JsonClass jsonDependency = new JsonClass();
jsonDependency.Add("name", this.ToString());
DependencyCheckStatus status = await this.GetStatus().ConfigureAwait(false);
if (status.Version != null)
jsonDependency.Add("version", status.Version.ToString());
if (!status.CheckPassed)
jsonDependency.Add("error", status.Message ?? "Unhandled error");
jsonDependency.Add("min_version", this.MinimumVersion.ToString());
jsonDependency.Add("max_version", this.MaximumVersion?.ToString() ?? "*");
if (status.Version?.ManifestNode != null)
{
JsonNode infrastructureDependencies = status.Version.ManifestNode["infrastructure_dependencies"];
JsonNode serviceDependencies = status.Version.ManifestNode["service_dependencies"];
if (infrastructureDependencies != null)
jsonDependency.Add("infrastructure_dependencies", infrastructureDependencies);
if (serviceDependencies != null)
jsonDependency.Add("service_dependencies", serviceDependencies);
}
return jsonDependency;
}
public override string ToString()
{
return string.IsNullOrEmpty(this.Name) ? this.Type.ToString() : this.Name;
}
}
}
| 34.916667 | 127 | 0.56867 | [
"BSD-3-Clause"
] | Mozcatel/name-sdk | src/NAME/Dependencies/VersionedDependency.cs | 4,611 | C# |
using FineGameDesign.Utils;
using UnityEngine;
namespace FineGameDesign.Entitas
{
public sealed class SpawnListener : ISpawnListener
{
private readonly GameContext m_Context;
private int m_PublisherId = -1;
public SpawnListener(GameContext context)
{
m_Context = context;
}
public void AddListener()
{
RemoveListener();
GameEntity publisher = m_Context.GetEntityWithId(m_PublisherId);
if (publisher == null)
{
publisher = m_Context.CreateEntity();
m_PublisherId = publisher.id.value;
}
publisher.AddSpawnListener(this);
}
public void RemoveListener()
{
GameEntity publisher = m_Context.GetEntityWithId(m_PublisherId);
if (publisher == null)
return;
if (!publisher.hasSpawnListener)
return;
publisher.RemoveSpawnListener(this);
}
public void OnSpawn(GameEntity entity, GameObject prefab)
{
GameObject origin = GameLinkUtils.GetObject(entity.id.value);
DebugUtil.Assert(origin != null,
"Expected link at spawn entity=" + entity + ". Spawning at world origin. prefab=" + prefab);
if (origin == null)
{
UnityEngine.Object.Instantiate(prefab);
return;
}
GameObject clone = UnityEngine.Object.Instantiate(prefab, origin.transform);
clone.transform.SetParent(null, true);
}
}
}
| 28.155172 | 108 | 0.564605 | [
"MIT"
] | ethankennerly/digestion-defense | DigestionDefense/Assets/Scripts/Views/SpawnListener.cs | 1,633 | C# |
namespace Helix.Bot.Abstractions
{
public class WorkflowActivatedEvent : Event { }
} | 22 | 51 | 0.761364 | [
"Apache-2.0"
] | hieucd04/Helix | Bot.Abstractions/Model/Event/WorkflowActivatedEvent.cs | 88 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ServiceFabric.Latest.Inputs
{
/// <summary>
/// Describes capacity information for a custom resource balancing metric. This can be used to limit the total consumption of this metric by the services of this application.
/// </summary>
public sealed class ApplicationMetricDescriptionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The maximum node capacity for Service Fabric application.
/// This is the maximum Load for an instance of this application on a single node. Even if the capacity of node is greater than this value, Service Fabric will limit the total load of services within the application on each node to this value.
/// If set to zero, capacity for this metric is unlimited on each node.
/// When creating a new application with application capacity defined, the product of MaximumNodes and this value must always be smaller than or equal to TotalApplicationCapacity.
/// When updating existing application with application capacity, the product of MaximumNodes and this value must always be smaller than or equal to TotalApplicationCapacity.
/// </summary>
[Input("maximumCapacity")]
public Input<double>? MaximumCapacity { get; set; }
/// <summary>
/// The name of the metric.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The node reservation capacity for Service Fabric application.
/// This is the amount of load which is reserved on nodes which have instances of this application.
/// If MinimumNodes is specified, then the product of these values will be the capacity reserved in the cluster for the application.
/// If set to zero, no capacity is reserved for this metric.
/// When setting application capacity or when updating application capacity; this value must be smaller than or equal to MaximumCapacity for each metric.
/// </summary>
[Input("reservationCapacity")]
public Input<double>? ReservationCapacity { get; set; }
/// <summary>
/// The total metric capacity for Service Fabric application.
/// This is the total metric capacity for this application in the cluster. Service Fabric will try to limit the sum of loads of services within the application to this value.
/// When creating a new application with application capacity defined, the product of MaximumNodes and MaximumCapacity must always be smaller than or equal to this value.
/// </summary>
[Input("totalApplicationCapacity")]
public Input<double>? TotalApplicationCapacity { get; set; }
public ApplicationMetricDescriptionArgs()
{
}
}
}
| 54.403509 | 251 | 0.700419 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ServiceFabric/Latest/Inputs/ApplicationMetricDescriptionArgs.cs | 3,101 | C# |
using BlazorMusicCatalog.Data;
using BlazorMusicCatalog.Models;
using BlazorMusicCatalog.Services.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlazorMusicCatalog.Services.classes
{
public class AlbumService : IAlbumService
{
private readonly ApplicationDbContext _dbContext;
public AlbumService(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<bool> DeleteAlbum(Album album)
{
_dbContext.Remove(album);
return await _dbContext.SaveChangesAsync() > 0;
}
public async Task<Album> GetAlbumDetails(int id)
{
return await _dbContext.Albums
.Where(s => s.Id == id)
.Include(s => s.Songs)
.FirstOrDefaultAsync();
}
public async Task<IEnumerable<Album>> GetAlbums()
{
return await _dbContext.Albums.ToListAsync();
}
public async Task<bool> InsertAlbum(Album album)
{
_dbContext.Add(album);
return await _dbContext.SaveChangesAsync() > 0;
}
public async Task<bool> UpdateAlbum(Album album)
{
_dbContext.Update(album);
return await _dbContext.SaveChangesAsync() > 0;
}
}
}
| 27.339623 | 59 | 0.619048 | [
"MIT"
] | aratar79/BlazorMusicCatalog_Pract03 | BlazorMusicCatalog.Services/classes/AlbumService.cs | 1,451 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
[CustomEditor(typeof(MixedRealityToolkit))]
public class MixedRealityToolkitInspector : UnityEditor.Editor
{
private SerializedProperty activeProfile;
private int currentPickerWindow = -1;
private bool checkChange = false;
private void OnEnable()
{
activeProfile = serializedObject.FindProperty("activeProfile");
currentPickerWindow = -1;
checkChange = activeProfile.objectReferenceValue == null;
}
public override void OnInspectorGUI()
{
MixedRealityToolkit instance = (MixedRealityToolkit)target;
if (MixedRealityToolkit.Instance == null)
{ // See if an active instance exists at all. If it doesn't register this instance preemptively.
MixedRealityToolkit.SetActiveInstance(instance);
}
if (!instance.IsActiveInstance)
{
EditorGUILayout.HelpBox("This instance of the toolkit is inactive. There can only be one active instance loaded at any time.", MessageType.Warning);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Select Active Instance"))
{
UnityEditor.Selection.activeGameObject = MixedRealityToolkit.Instance.gameObject;
}
if (GUILayout.Button("Make this the Active Instance"))
{
MixedRealityToolkit.SetActiveInstance(instance);
}
EditorGUILayout.EndHorizontal();
return;
}
serializedObject.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(activeProfile);
bool changed = EditorGUI.EndChangeCheck();
string commandName = Event.current.commandName;
var allConfigProfiles = ScriptableObjectExtensions.GetAllInstances<MixedRealityToolkitConfigurationProfile>();
if (activeProfile.objectReferenceValue == null && currentPickerWindow == -1 && checkChange && !BuildPipeline.isBuildingPlayer)
{
if (allConfigProfiles.Length > 1)
{
EditorUtility.DisplayDialog("Attention!", "You must choose a profile for the Mixed Reality Toolkit.", "OK");
currentPickerWindow = GUIUtility.GetControlID(FocusType.Passive);
// Shows the list of MixedRealityToolkitConfigurationProfiles in our project,
// selecting the default profile by default (if it exists).
EditorGUIUtility.ShowObjectPicker<MixedRealityToolkitConfigurationProfile>(MixedRealityInspectorUtility.GetDefaultConfigProfile(allConfigProfiles), false, string.Empty, currentPickerWindow);
}
else if (allConfigProfiles.Length == 1)
{
activeProfile.objectReferenceValue = allConfigProfiles[0];
changed = true;
Selection.activeObject = allConfigProfiles[0];
EditorGUIUtility.PingObject(allConfigProfiles[0]);
}
else
{
if (EditorUtility.DisplayDialog("Attention!", "No profiles were found for the Mixed Reality Toolkit.\n\n" +
"Would you like to create one now?", "OK", "Later"))
{
ScriptableObject profile = CreateInstance(nameof(MixedRealityToolkitConfigurationProfile));
profile.CreateAsset("Assets/MixedRealityToolkit.Generated/CustomProfiles");
activeProfile.objectReferenceValue = profile;
Selection.activeObject = profile;
EditorGUIUtility.PingObject(profile);
}
}
checkChange = false;
}
if (EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow)
{
switch (commandName)
{
case "ObjectSelectorUpdated":
activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
changed = true;
break;
case "ObjectSelectorClosed":
activeProfile.objectReferenceValue = EditorGUIUtility.GetObjectPickerObject();
currentPickerWindow = -1;
changed = true;
Selection.activeObject = activeProfile.objectReferenceValue;
EditorGUIUtility.PingObject(activeProfile.objectReferenceValue);
break;
}
}
serializedObject.ApplyModifiedProperties();
if (changed)
{
MixedRealityToolkit.Instance.ResetConfiguration((MixedRealityToolkitConfigurationProfile)activeProfile.objectReferenceValue);
}
if (activeProfile.objectReferenceValue != null)
{
UnityEditor.Editor activeProfileEditor = CreateEditor(activeProfile.objectReferenceValue);
activeProfileEditor.OnInspectorGUI();
}
}
[MenuItem("Mixed Reality Toolkit/Add to Scene and Configure...")]
public static void CreateMixedRealityToolkitGameObject()
{
MixedRealityInspectorUtility.AddMixedRealityToolkitToScene();
EditorGUIUtility.PingObject(MixedRealityToolkit.Instance);
}
}
}
| 46.24031 | 210 | 0.5943 | [
"MIT"
] | AdamMitchell-ms/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/Inspectors/MixedRealityToolkitInspector.cs | 5,967 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace System.Management.Automation.Runspaces
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Internal;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
/// <summary>
/// This class has common base implementation for Pipeline class.
/// LocalPipeline and RemotePipeline classes derives from it.
/// </summary>
internal abstract class PipelineBase : Pipeline
{
#region constructors
/// <summary>
/// Create a pipeline initialized with a command string
/// </summary>
/// <param name="runspace">The associated Runspace/></param>
/// <param name="command">Command string.</param>
/// <param name="addToHistory">If true, add pipeline to history.</param>
/// <param name="isNested">True for nested pipeline.</param>
/// <exception cref="ArgumentNullException">
/// Command is null and add to history is true
/// </exception>
protected PipelineBase(Runspace runspace, string command, bool addToHistory, bool isNested)
: base(runspace)
{
Initialize(runspace, command, addToHistory, isNested);
//Initialize streams
InputStream = new ObjectStream();
OutputStream = new ObjectStream();
ErrorStream = new ObjectStream();
}
/// <summary>
/// Create a Pipeline with an existing command string.
/// Caller should validate all the parameters.
/// </summary>
/// <param name="runspace">
/// The LocalRunspace to associate with this pipeline.
/// </param>
/// <param name="command">
/// The command to invoke.
/// </param>
/// <param name="addToHistory">
/// If true, add the command to history.
/// </param>
/// <param name="isNested">
/// If true, mark this pipeline as a nested pipeline.
/// </param>
/// <param name="inputStream">
/// Stream to use for reading input objects.
/// </param>
/// <param name="errorStream">
/// Stream to use for writing error objects.
/// </param>
/// <param name="outputStream">
/// Stream to use for writing output objects.
/// </param>
/// <param name="infoBuffers">
/// Buffers used to write progress, verbose, debug, warning, information
/// information of an invocation.
/// </param>
/// <exception cref="ArgumentNullException">
/// Command is null and add to history is true
/// </exception>
/// <exception cref="ArgumentNullException">
/// 1. InformationalBuffers is null
/// </exception>
protected PipelineBase(Runspace runspace,
CommandCollection command,
bool addToHistory,
bool isNested,
ObjectStreamBase inputStream,
ObjectStreamBase outputStream,
ObjectStreamBase errorStream,
PSInformationalBuffers infoBuffers)
: base(runspace, command)
{
Dbg.Assert(inputStream != null, "Caller Should validate inputstream parameter");
Dbg.Assert(outputStream != null, "Caller Should validate outputStream parameter");
Dbg.Assert(errorStream != null, "Caller Should validate errorStream parameter");
Dbg.Assert(infoBuffers != null, "Caller Should validate informationalBuffers parameter");
Dbg.Assert(command != null, "Command cannot be null");
// Since we are constructing this pipeline using a commandcollection we dont need
// to add cmd to CommandCollection again (Initialize does this).. because of this
// I am handling history here..
Initialize(runspace, null, false, isNested);
if (true == addToHistory)
{
// get command text for history..
string cmdText = command.GetCommandStringForHistory();
HistoryString = cmdText;
AddToHistory = addToHistory;
}
//Initialize streams
InputStream = inputStream;
OutputStream = outputStream;
ErrorStream = errorStream;
InformationalBuffers = infoBuffers;
}
/// <summary>
/// Copy constructor to support cloning
/// </summary>
/// <param name="pipeline">The source pipeline.</param>
/// <remarks>
/// The copy constructor's intent is to support the scenario
/// where a host needs to run the same set of commands multiple
/// times. This is accomplished via creating a master pipeline
/// then cloning it and executing the cloned copy.
/// </remarks>
protected PipelineBase(PipelineBase pipeline)
: this(pipeline.Runspace, null, false, pipeline.IsNested)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (pipeline == null)
{
throw PSTraceSource.NewArgumentNullException("pipeline");
}
if (pipeline._disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
AddToHistory = pipeline.AddToHistory;
HistoryString = pipeline.HistoryString;
foreach (Command command in pipeline.Commands)
{
Command clone = command.Clone();
// Attach the cloned Command to this pipeline.
Commands.Add(clone);
}
}
#endregion constructors
#region properties
private Runspace _runspace;
/// <summary>
/// Access the runspace this pipeline is created on.
/// </summary>
public override Runspace Runspace
{
get
{
return _runspace;
}
}
/// <summary>
/// This internal method doesn't do the _disposed check.
/// </summary>
/// <returns></returns>
internal Runspace GetRunspace()
{
return _runspace;
}
private bool _isNested;
/// <summary>
/// Is this pipeline nested
/// </summary>
public override bool IsNested
{
get
{
return _isNested;
}
}
/// <summary>
/// Is this a pulse pipeline (created by the EventManager)
/// </summary>
internal bool IsPulsePipeline { get; set; }
private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted);
/// <summary>
/// Info about current state of the pipeline.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
public override PipelineStateInfo PipelineStateInfo
{
get
{
lock (SyncRoot)
{
//Note:We do not return internal state.
return _pipelineStateInfo.Clone();
}
}
}
// 913921-2005/07/08 ObjectWriter can be retrieved on a closed stream
/// <summary>
/// Access the input writer for this pipeline.
/// </summary>
public override PipelineWriter Input
{
get
{
return InputStream.ObjectWriter;
}
}
/// <summary>
/// Access the output reader for this pipeline.
/// </summary>
public override PipelineReader<PSObject> Output
{
get
{
return OutputStream.PSObjectReader;
}
}
/// <summary>
/// Access the error output reader for this pipeline.
/// </summary>
/// <remarks>
/// This is the non-terminating error stream from the command.
/// In this release, the objects read from this PipelineReader
/// are PSObjects wrapping ErrorRecords.
/// </remarks>
public override PipelineReader<object> Error
{
get
{
return _errorStream.ObjectReader;
}
}
/// <summary>
/// Is this pipeline a child pipeline?
///
/// IsChild flag makes it possible for the pipeline to differentiate between
/// a true v1 nested pipeline and the cmdlets calling cmdlets case. See bug
/// 211462.
/// </summary>
internal override bool IsChild { get; set; }
#endregion properties
#region stop
/// <summary>
/// Synchronous call to stop the running pipeline.
/// </summary>
public override void Stop()
{
CoreStop(true);
}
/// <summary>
/// Asynchronous call to stop the running pipeline.
/// </summary>
public override void StopAsync()
{
CoreStop(false);
}
/// <summary>
/// Stop the running pipeline.
/// </summary>
/// <param name="syncCall">If true pipeline is stoped synchronously
/// else asynchronously.</param>
private void CoreStop(bool syncCall)
{
//Is pipeline already in stopping state.
bool alreadyStopping = false;
lock (SyncRoot)
{
switch (PipelineState)
{
case PipelineState.NotStarted:
SetPipelineState(PipelineState.Stopping);
SetPipelineState(PipelineState.Stopped);
break;
//If pipeline execution has failed or completed or
//stoped, return silently.
case PipelineState.Stopped:
case PipelineState.Completed:
case PipelineState.Failed:
return;
//If pipeline is in Stopping state, ignore the second
//stop.
case PipelineState.Stopping:
alreadyStopping = true;
break;
case PipelineState.Running:
SetPipelineState(PipelineState.Stopping);
break;
}
}
//If pipeline is already in stopping state. Wait for pipeline
//to finish. We do need to raise any events here as no
//change of state has occurred.
if (alreadyStopping)
{
if (syncCall)
{
PipelineFinishedEvent.WaitOne();
}
return;
}
//Raise the event outside the lock
RaisePipelineStateEvents();
//A pipeline can be stoped before it is started. See NotStarted
//case in above switch statement. This is done to allow stoping a pipeline
//in another thread before it has been started.
lock (SyncRoot)
{
if (PipelineState == PipelineState.Stopped)
{
//Note:if we have reached here, Stopped state was set
//in PipelineState.NotStarted case above. Only other
//way Stopped can be set when this method calls
//StopHelper below
return;
}
}
//Start stop operation in derived class
ImplementStop(syncCall);
}
/// <summary>
/// Stop execution of pipeline
/// </summary>
/// <param name="syncCall">If false, call is asynchronous.</param>
protected abstract void ImplementStop(bool syncCall);
#endregion stop
#region invoke
/// <summary>
/// Invoke the pipeline, synchronously, returning the results as an
/// array of objects.
/// </summary>
/// <param name="input">an array of input objects to pass to the pipeline.
/// Array may be empty but may not be null</param>
/// <returns>An array of zero or more result objects.</returns>
/// <remarks>Caller of synchronous exectute should not close
/// input objectWriter. Synchronous invoke will always close the input
/// objectWriter.
///
/// On Synchronous Invoke if output is throttled and no one is reading from
/// output pipe, Execution will block after buffer is full.
/// </remarks>
public override Collection<PSObject> Invoke(IEnumerable input)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
CoreInvoke(input, true);
//Wait for pipeline to finish execution
PipelineFinishedEvent.WaitOne();
if (SyncInvokeCall)
{
//Raise the pipeline completion events. These events are set in
//pipeline execution thread. However for Synchronous execution
//we raise the event in the main thread.
RaisePipelineStateEvents();
}
if (PipelineStateInfo.State == PipelineState.Stopped)
{
return new Collection<PSObject>();
}
else if (PipelineStateInfo.State == PipelineState.Failed && PipelineStateInfo.Reason != null)
{
// If this is an error pipe for a hosting applicationand we are logging,
// then log the error.
if (this.Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing)
{
this.Runspace.ExecutionContext.InternalHost.UI.TranscribeResult(this.Runspace, PipelineStateInfo.Reason.Message);
}
throw PipelineStateInfo.Reason;
}
//Execution completed successfully
// 2004/06/30-JonN was ReadAll() which was non-blocking
return Output.NonBlockingRead(Int32.MaxValue);
}
/// <summary>
/// Invoke the pipeline asynchronously
/// </summary>
/// <remarks>
/// Results are returned through the <see cref="Pipeline.Output"/> reader.
/// </remarks>
public override void InvokeAsync()
{
CoreInvoke(null, false);
}
/// <summary>
/// This parameter is true if Invoke is called.
/// It is false if InvokeAsync is called.
/// </summary>
protected bool SyncInvokeCall { get; private set; }
/// <summary>
/// Invoke the pipeline asynchronously with input.
/// </summary>
/// <param name="input">input to provide to pipeline. Input is
/// used only for synchronous execution</param>
/// <param name="syncCall">True if this method is called from
/// synchronous invoke else false</param>
/// <remarks>
/// Results are returned through the <see cref="Pipeline.Output"/> reader.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// No command is added to pipeline
/// </exception>
/// <exception cref="InvalidPipelineStateException">
/// PipelineState is not NotStarted.
/// </exception>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) InvokeAsync is called on nested pipeline. Nested pipeline
/// cannot be executed Asynchronously.
/// 3) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
/// <exception cref="InvalidRunspaceStateException">
/// RunspaceState is not Open
/// </exception>
/// <exception cref="ObjectDisposedException">
/// Pipeline already disposed
/// </exception>
private void CoreInvoke(IEnumerable input, bool syncCall)
{
lock (SyncRoot)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("pipeline");
}
if (Commands == null || Commands.Count == 0)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NoCommandInPipeline);
}
if (PipelineState != PipelineState.NotStarted)
{
InvalidPipelineStateException e =
new InvalidPipelineStateException
(
StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed),
PipelineState,
PipelineState.NotStarted
);
throw e;
}
if (syncCall && !(InputStream is PSDataCollectionStream<PSObject> || InputStream is PSDataCollectionStream<object>))
{
//Method is called from synchronous invoke.
if (input != null)
{
//TO-DO-Add a test make sure that ObjectDisposed
//exception is thrown
//Write input data in to inputStream and close the input
//pipe. If Input stream is already closed an
//ObjectDisposed exception will be thrown
foreach (object temp in input)
{
InputStream.Write(temp);
}
}
InputStream.Close();
}
SyncInvokeCall = syncCall;
//Create event which will be signalled when pipeline execution
//is completed/failed/stoped.
//Note:Runspace.Close waits for all the running pipeline
//to finish. This Event must be created before pipeline is
//added to list of running pipelines. This avoids the race condition
//where Close is called after pipeline is added to list of
//running pipeline but before event is created.
PipelineFinishedEvent = new ManualResetEvent(false);
//1) Do the check to ensure that pipeline no other
// pipeline is running.
//2) Runspace object maintains a list of pipelines in
//execution. Add this pipeline to the list.
RunspaceBase.DoConcurrentCheckAndAddToRunningPipelines(this, syncCall);
//Note: Set PipelineState to Running only after adding pipeline to list
//of pipelines in execution. AddForExecution checks that runspace is in
//state where pipeline can be run.
//StartPipelineExecution raises this event. See Windows Bug 1160481 for
//more details.
SetPipelineState(PipelineState.Running);
}
try
{
//Let the derived class start the pipeline execution.
StartPipelineExecution();
}
catch (Exception exception)
{
//If we fail in any of the above three steps, set the correct states.
RunspaceBase.RemoveFromRunningPipelineList(this);
SetPipelineState(PipelineState.Failed, exception);
//Note: we are not raising the events in this case. However this is
//fine as user is getting the exception.
throw;
}
}
/// <summary>
/// Invokes a remote command and immediately disconnects if
/// transport layer supports it.
/// </summary>
internal override void InvokeAsyncAndDisconnect()
{
throw new NotSupportedException();
}
/// <summary>
/// Starts execution of pipeline.
/// </summary>
protected abstract void StartPipelineExecution();
#region concurrent pipeline check
private bool _performNestedCheck = true;
/// <summary>
/// For nested pipeline, system checks that Execute is called from
/// currently executing pipeline.
/// If PerformNestedCheck is false, this check is bypassed. This
/// is set to true by remote provider. In remote provider case all
/// the checks are done by the client proxy.
/// </summary>
internal bool PerformNestedCheck
{
set
{
_performNestedCheck = value;
}
}
/// <summary>
/// This is the thread on which NestedPipeline can be executed.
/// In case of LocalPipeline, this is the thread of execution
/// of LocalPipeline. In case of RemotePipeline, this is thread
/// on which EnterNestedPrompt is called.
/// RemotePipeline proxy should set it on at the beginning of
/// EnterNestedPrompt and clear it on return.
/// </summary>
internal Thread NestedPipelineExecutionThread { get; set; }
/// <summary>
/// Check if anyother pipeline is executing.
/// In case of nested pipeline, checks that it is called
/// from currently executing pipeline's thread.
/// </summary>
/// <param name="syncCall">True if method is called from Invoke, false
/// if called from InvokeAsync</param>
/// <param name="syncObject">The sync object on which the lock is acquired.</param>
/// <param name="isInLock">True if the method is invoked in a critical section.</param>
/// <exception cref="InvalidOperationException">
/// 1) A pipeline is already executing. Pipeline cannot execute
/// concurrently.
/// 2) InvokeAsync is called on nested pipeline. Nested pipeline
/// cannot be executed Asynchronously.
/// 3) Attempt is made to invoke a nested pipeline directly. Nested
/// pipeline must be invoked from a running pipeline.
/// </exception>
internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock)
{
PipelineBase currentPipeline = (PipelineBase)RunspaceBase.GetCurrentlyRunningPipeline();
if (IsNested == false)
{
if (currentPipeline == null)
{
return;
}
else
{
// Detect if we're running a pulse pipeline, or we're running a nested pipeline
// in a pulse pipeline
if (currentPipeline == RunspaceBase.PulsePipeline ||
(currentPipeline.IsNested && RunspaceBase.PulsePipeline != null))
{
// If so, wait and try again
if (isInLock)
{
// If the method is invoked in the lock statement, release the
// lock before wait on the pulse pipeline
Monitor.Exit(syncObject);
}
try
{
RunspaceBase.WaitForFinishofPipelines();
}
finally
{
if (isInLock)
{
// If the method is invoked in the lock statement, acquire the
// lock before we carry on with the rest operations
Monitor.Enter(syncObject);
}
}
DoConcurrentCheck(syncCall, syncObject, isInLock);
return;
}
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.ConcurrentInvokeNotAllowed);
}
}
else
{
if (_performNestedCheck)
{
if (syncCall == false)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineInvokeAsync);
}
if (currentPipeline == null)
{
if (this.IsChild)
{
// OK it's not really a nested pipeline but a call with RunspaceMode=UseCurrentRunspace
// This shouldn't fail so we'll clear the IsNested and IsChild flags and then return
// That way executions proceeds but everything gets clean up at the end when the pipeline completes
this.IsChild = false;
_isNested = false;
return;
}
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineNoParentPipeline);
}
Dbg.Assert(currentPipeline.NestedPipelineExecutionThread != null, "Current pipeline should always have NestedPipelineExecutionThread set");
Thread th = Thread.CurrentThread;
if (currentPipeline.NestedPipelineExecutionThread.Equals(th) == false)
{
throw PSTraceSource.NewInvalidOperationException(
RunspaceStrings.NestedPipelineNoParentPipeline);
}
}
}
}
#endregion concurrent pipeline check
#endregion invoke
#region Connect
/// <summary>
/// Connects synchronously to a running command on a remote server.
/// The pipeline object must be in the disconnected state.
/// </summary>
/// <returns>A collection of result objects.</returns>
public override Collection<PSObject> Connect()
{
// Connect semantics not supported on local (non-remoting) pipelines.
throw PSTraceSource.NewNotSupportedException(PipelineStrings.ConnectNotSupported);
}
/// <summary>
/// Connects asynchronously to a running command on a remote server.
/// </summary>
public override void ConnectAsync()
{
// Connect semantics not supported on local (non-remoting) pipelines.
throw PSTraceSource.NewNotSupportedException(PipelineStrings.ConnectNotSupported);
}
#endregion
#region state change event
/// <summary>
/// Event raised when Pipeline's state changes.
/// </summary>
public override event EventHandler<PipelineStateEventArgs> StateChanged = null;
/// <summary>
/// Current state of the pipeline.
/// </summary>
/// <remarks>
/// This value indicates the state of the pipeline after the change.
/// </remarks>
protected PipelineState PipelineState
{
get
{
return _pipelineStateInfo.State;
}
}
/// <summary>
/// This returns true if pipeline state is Completed, Failed or Stopped
/// </summary>
/// <returns></returns>
protected bool IsPipelineFinished()
{
return (PipelineState == PipelineState.Completed ||
PipelineState == PipelineState.Failed ||
PipelineState == PipelineState.Stopped);
}
/// <summary>
/// This is queue of all the state change event which have occured for
/// this pipeline. RaisePipelineStateEvents raises event for each
/// item in this queue. We don't raise the event with in SetPipelineState
/// because often SetPipelineState is called with in a lock.
/// Raising event in lock introduces chances of deadlock in GUI applications.
/// </summary>
private Queue<ExecutionEventQueueItem> _executionEventQueue = new Queue<ExecutionEventQueueItem>();
private class ExecutionEventQueueItem
{
public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability)
{
this.PipelineStateInfo = pipelineStateInfo;
this.CurrentRunspaceAvailability = currentAvailability;
this.NewRunspaceAvailability = newAvailability;
}
public PipelineStateInfo PipelineStateInfo;
public RunspaceAvailability CurrentRunspaceAvailability;
public RunspaceAvailability NewRunspaceAvailability;
}
/// <summary>
/// Sets the new execution state.
/// </summary>
/// <param name="state">The new state.</param>
/// <param name="reason">
/// An exception indicating that state change is the result of an error,
/// otherwise; null.
/// </param>
/// <remarks>
/// Sets the internal execution state information member variable. It
/// also adds PipelineStateInfo to a queue. RaisePipelineStateEvents
/// raises event for each item in this queue.
/// </remarks>
protected void SetPipelineState(PipelineState state, Exception reason)
{
lock (SyncRoot)
{
if (state != PipelineState)
{
_pipelineStateInfo = new PipelineStateInfo(state, reason);
//Add _pipelineStateInfo to _executionEventQueue.
//RaisePipelineStateEvents will raise event for each item
//in this queue.
//Note:We are doing clone here instead of passing the member
//_pipelineStateInfo because we donot want outside
//to change pipeline state.
RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability;
_runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false);
_executionEventQueue.Enqueue(
new ExecutionEventQueueItem(
_pipelineStateInfo.Clone(),
previousAvailability,
_runspace.RunspaceAvailability));
}
}
}
/// <summary>
/// Set the new execution state
/// </summary>
/// <param name="state">The new state.</param>
protected void SetPipelineState(PipelineState state)
{
SetPipelineState(state, null);
}
/// <summary>
/// Raises events for changes in execution state.
/// </summary>
protected void RaisePipelineStateEvents()
{
Queue<ExecutionEventQueueItem> tempEventQueue = null;
EventHandler<PipelineStateEventArgs> stateChanged = null;
bool runspaceHasAvailabilityChangedSubscribers = false;
lock (SyncRoot)
{
stateChanged = this.StateChanged;
runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers;
if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers)
{
tempEventQueue = _executionEventQueue;
_executionEventQueue = new Queue<ExecutionEventQueueItem>();
}
else
{
//Clear the events if there are no EventHandlers. This
//ensures that events do not get called for state
//changes prior to their registration.
_executionEventQueue.Clear();
}
}
if (tempEventQueue != null)
{
while (tempEventQueue.Count > 0)
{
ExecutionEventQueueItem queueItem = tempEventQueue.Dequeue();
if (runspaceHasAvailabilityChangedSubscribers && queueItem.NewRunspaceAvailability != queueItem.CurrentRunspaceAvailability)
{
_runspace.RaiseAvailabilityChangedEvent(queueItem.NewRunspaceAvailability);
}
// this is shipped as part of V1. So disabling the warning here.
#pragma warning disable 56500
//Exception raised in the eventhandler are not error in pipeline.
//silently ignore them.
if (stateChanged != null)
{
try
{
stateChanged(this, new PipelineStateEventArgs(queueItem.PipelineStateInfo));
}
catch (Exception)
{
}
}
#pragma warning restore 56500
}
}
}
/// <summary>
/// ManualResetEvent which is signaled when pipeline execution is
/// completed/failed/stoped.
/// </summary>
internal ManualResetEvent PipelineFinishedEvent { get; private set; }
#endregion
#region streams
/// <summary>
/// OutputStream from PipelineProcessor. Host will read on
/// ObjectReader of this stream. PipelineProcessor will write to
/// ObjectWriter of this stream.
/// </summary>
protected ObjectStreamBase OutputStream { get; }
private ObjectStreamBase _errorStream;
/// <summary>
/// ErrorStream from PipelineProcessor. Host will read on
/// ObjectReader of this stream. PipelineProcessor will write to
/// ObjectWriter of this stream.
/// </summary>
protected ObjectStreamBase ErrorStream
{
get
{
return _errorStream;
}
private set
{
Dbg.Assert(value != null, "ErrorStream cannot be null");
_errorStream = value;
_errorStream.DataReady += new EventHandler(OnErrorStreamDataReady);
}
}
// Winblue: 26115. This handler is used to populate Pipeline.HadErrors.
private void OnErrorStreamDataReady(object sender, EventArgs e)
{
if (_errorStream.Count > 0)
{
// unsubscribe from further event notifications as
// this notification is suffice to say there is an
// error.
_errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady);
SetHadErrors(true);
}
}
/// <summary>
/// Informational Buffers that represent verbose, debug, progress,
/// warning emanating from the command execution.
/// </summary>
/// <remarks>
/// Informational buffers are introduced after 1.0. This can be
/// null if executing command as part of 1.0 hosting interfaces.
/// </remarks>
protected PSInformationalBuffers InformationalBuffers { get; }
/// <summary>
/// Stream for providing input to PipelineProcessor. Host will write on
/// ObjectWriter of this stream. PipelineProcessor will read from
/// ObjectReader of this stream.
/// </summary>
protected ObjectStreamBase InputStream { get; }
#endregion streams
#region history
//History information is internal so that Pipeline serialization code
//can access it.
/// <summary>
/// if true, this pipeline is added in history
/// </summary>
internal bool AddToHistory { get; set; }
/// <summary>
/// String which is added in the history
/// </summary>
/// <remarks>This needs to be internal so that it can be replaced
/// by invoke-cmd to place correct string in history.</remarks>
internal string HistoryString { get; set; }
#endregion history
#region misc
/// <summary>
/// Initialized the current pipeline instance with the supplied data.
/// </summary>
/// <param name="runspace"></param>
/// <param name="command"></param>
/// <param name="addToHistory"></param>
/// <param name="isNested"></param>
/// <exception cref="ArgumentNullException">
/// 1. addToHistory is true and command is null.
/// </exception>
private void Initialize(Runspace runspace, string command, bool addToHistory, bool isNested)
{
Dbg.Assert(runspace != null, "caller should validate the parameter");
_runspace = runspace;
_isNested = isNested;
if (addToHistory && command == null)
{
throw PSTraceSource.NewArgumentNullException("command");
}
if (command != null)
{
Commands.Add(new Command(command, true, false));
}
AddToHistory = addToHistory;
if (AddToHistory)
{
HistoryString = command;
}
}
private RunspaceBase RunspaceBase
{
get
{
return (RunspaceBase)Runspace;
}
}
/// <summary>
/// Object used for synchronization
/// </summary>
protected internal object SyncRoot { get; } = new object();
#endregion misc
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
private bool _disposed;
/// <summary>
/// Protected dispose which can be overridden by derived classes.
/// </summary>
/// <param name="disposing"></param>
protected override
void
Dispose(bool disposing)
{
try
{
if (_disposed == false)
{
_disposed = true;
if (disposing)
{
InputStream.Close();
OutputStream.Close();
_errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady);
_errorStream.Close();
_executionEventQueue.Clear();
}
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion IDisposable Members
}
}
| 37.285714 | 159 | 0.540055 | [
"MIT"
] | renovate-mirrors/PowerShell | src/System.Management.Automation/engine/hostifaces/pipelinebase.cs | 39,933 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetLearner.SharedLib.Data;
using NetLearner.SharedLib.Models;
namespace NetLearner.Pages.TopicTags
{
public class CreateModel : PageModel
{
private readonly NetLearner.SharedLib.Data.LibDbContext _context;
public CreateModel(NetLearner.SharedLib.Data.LibDbContext context)
{
_context = context;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public TopicTag TopicTag { get; set; }
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.TopicTags.Add(TopicTag);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
| 26.5 | 110 | 0.638228 | [
"MIT"
] | Pank12/NetLearnerApp | src/NetLearner.Pages/Pages/TopicTags/Create.cshtml.cs | 1,221 | 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.Ecs.Transform;
using Aliyun.Acs.Ecs.Transform.V20140526;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class DescribeHpcClustersRequest : RpcAcsRequest<DescribeHpcClustersResponse>
{
public DescribeHpcClustersRequest()
: base("Ecs", "2014-05-26", "DescribeHpcClusters", "ecs", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private long? resourceOwnerId;
private string clientToken;
private int? pageNumber;
private int? pageSize;
private string resourceOwnerAccount;
private string ownerAccount;
private long? ownerId;
private string hpcClusterIds;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string ClientToken
{
get
{
return clientToken;
}
set
{
clientToken = value;
DictionaryUtil.Add(QueryParameters, "ClientToken", value);
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string HpcClusterIds
{
get
{
return hpcClusterIds;
}
set
{
hpcClusterIds = value;
DictionaryUtil.Add(QueryParameters, "HpcClusterIds", value);
}
}
public override DescribeHpcClustersResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeHpcClustersResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 22.928994 | 134 | 0.653935 | [
"Apache-2.0"
] | chys0404/aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Model/V20140526/DescribeHpcClustersRequest.cs | 3,875 | C# |
namespace ROBot.Core.Twitch.Commands
{
public class Highscore : Leaderboard { }
}
| 17.4 | 44 | 0.724138 | [
"MIT"
] | AbbyTheRat/RavenBot | src/ROBot.Core/Twitch/Commands/Highscore.cs | 89 | C# |
using Acme.Graphs.Helpers;
using Acme.Tests.TestHelpers;
using FluentAssertions;
using System.Linq;
using Xunit;
namespace Acme.Tests {
public class EdgeHelpersTests {
[Theory]
[InlineData("ABC", "D-A", true)]
[InlineData("ABC", "D-B", true)]
[InlineData("ABC", "D-E", false)]
[InlineData("ABC", "A-B", false)]
[InlineData("ABC", "C-A", false)]
public void LeadsInto(string pathDescription, string edgeDescription, bool expected) {
var path = GraphFactory.CreatePath(pathDescription.Select(c => c.ToString()).ToArray());
var edge = GraphFactory.CreateEdge(edgeDescription);
edge.LeadsInto(path).Should().Be(expected);
}
[Theory]
[InlineData("ABC", "A-D", true)]
[InlineData("ABC", "B-D", true)]
[InlineData("ABC", "D-E", false)]
[InlineData("ABC", "A-B", false)]
[InlineData("ABC", "C-A", false)]
public void LeadsOutOf(string pathDescription, string edgeDescription, bool expected) {
var path = GraphFactory.CreatePath(pathDescription.Select(c => c.ToString()).ToArray());
var edge = GraphFactory.CreateEdge(edgeDescription);
edge.LeadsOutOf(path).Should().Be(expected);
}
}
}
| 35.861111 | 100 | 0.605732 | [
"MIT"
] | Muamaidbengt/Acme.Graphs | Acme.Tests/EdgeHelpersTests.cs | 1,293 | 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;
using Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.ProjectModel.FileSystemGlobbing
{
public struct FilePatternMatch : IEquatable<FilePatternMatch>
{
public string Path { get; }
public string Stem { get; }
public FilePatternMatch(string path, string stem)
{
Path = path;
Stem = stem;
}
public bool Equals(FilePatternMatch other)
{
return string.Equals(other.Path, Path, StringComparison.OrdinalIgnoreCase) &&
string.Equals(other.Stem, Stem, StringComparison.OrdinalIgnoreCase);
}
public override bool Equals(object obj)
{
return Equals((FilePatternMatch)obj);
}
public override int GetHashCode()
{
var hashCodeCombiner = HashCodeCombiner.Start();
hashCodeCombiner.Add(Path, StringComparer.OrdinalIgnoreCase);
hashCodeCombiner.Add(Stem, StringComparer.OrdinalIgnoreCase);
return hashCodeCombiner.CombinedHash;
}
}
} | 31.625 | 101 | 0.651383 | [
"MIT"
] | DustinCampbell/omnisharp-roslyn | src/OmniSharp.DotNet.ProjectModel/FileSystemGlobbing/FilePatternMatch.cs | 1,265 | C# |
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
// SPDX-License-Identifier: Apache-2.0
namespace AspNetAppEcsFargate.Configurations
{
public class VpcConfiguration
{
/// <summary>
/// If set, use default VPC
/// </summary>
public bool IsDefault { get; set; }
/// <summary>
/// If set and <see cref="CreateNew"/> is false, create a new VPC
/// </summary>
public bool CreateNew { get; set; }
/// <summary>
/// If <see cref="IsDefault" /> is false and <see cref="CreateNew" /> is false,
/// then use an existing VPC by referencing through <see cref="VpcId"/>
/// </summary>
public string VpcId { get; set; }
}
}
| 30.08 | 87 | 0.574468 | [
"MIT"
] | joseph-burrows/aws-dotnet-deploy | src/AWS.Deploy.Recipes/CdkTemplates/AspNetAppEcsFargate/Configurations/VpcConfiguration.cs | 752 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
** Purpose: provide a cached reusable instance of stringbuilder
** per thread it's an optimisation that reduces the
** number of instances constructed and collected.
**
** Acquire - is used to get a string builder to use of a
** particular size. It can be called any number of
** times, if a stringbuilder is in the cache then
** it will be returned and the cache emptied.
** subsequent calls will return a new stringbuilder.
**
** A StringBuilder instance is cached in
** Thread Local Storage and so there is one per thread
**
** Release - Place the specified builder in the cache if it is
** not too big.
** The stringbuilder should not be used after it has
** been released.
** Unbalanced Releases are perfectly acceptable. It
** will merely cause the runtime to create a new
** stringbuilder next time Acquire is called.
**
** GetStringAndRelease
** - ToString() the stringbuilder, Release it to the
** cache and return the resulting string
**
===========================================================*/
using System.Threading;
namespace System.Text
{
internal static class StringBuilderCache
{
// The value 360 was chosen in discussion with performance experts as a compromise between using
// as litle memory (per thread) as possible and still covering a large part of short-lived
// StringBuilder creations on the startup path of VS designers.
private const int MAX_BUILDER_SIZE = 360;
[ThreadStatic]
private static StringBuilder CachedInstance;
public static StringBuilder Acquire(int capacity = StringBuilder.DefaultCapacity)
{
if(capacity <= MAX_BUILDER_SIZE)
{
StringBuilder sb = StringBuilderCache.CachedInstance;
if (sb != null)
{
// Avoid stringbuilder block fragmentation by getting a new StringBuilder
// when the requested size is larger than the current capacity
if(capacity <= sb.Capacity)
{
StringBuilderCache.CachedInstance = null;
sb.Clear();
return sb;
}
}
}
return new StringBuilder(capacity);
}
public static void Release(StringBuilder sb)
{
if (sb.Capacity <= MAX_BUILDER_SIZE)
{
StringBuilderCache.CachedInstance = sb;
}
}
public static string GetStringAndRelease(StringBuilder sb)
{
string result = sb.ToString();
Release(sb);
return result;
}
}
}
| 37.253012 | 104 | 0.565653 | [
"MIT"
] | 1Crazymoney/cs2cpp | CoreLib/System/Text/StringBuilderCache.cs | 3,092 | 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/DirectML.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="DML_ELEMENT_WISE_LOG_OPERATOR_DESC" /> struct.</summary>
public static unsafe class DML_ELEMENT_WISE_LOG_OPERATOR_DESCTests
{
/// <summary>Validates that the <see cref="DML_ELEMENT_WISE_LOG_OPERATOR_DESC" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<DML_ELEMENT_WISE_LOG_OPERATOR_DESC>(), Is.EqualTo(sizeof(DML_ELEMENT_WISE_LOG_OPERATOR_DESC)));
}
/// <summary>Validates that the <see cref="DML_ELEMENT_WISE_LOG_OPERATOR_DESC" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(DML_ELEMENT_WISE_LOG_OPERATOR_DESC).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="DML_ELEMENT_WISE_LOG_OPERATOR_DESC" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(DML_ELEMENT_WISE_LOG_OPERATOR_DESC), Is.EqualTo(24));
}
else
{
Assert.That(sizeof(DML_ELEMENT_WISE_LOG_OPERATOR_DESC), Is.EqualTo(12));
}
}
}
}
| 40.159091 | 147 | 0.672892 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/DirectML/DML_ELEMENT_WISE_LOG_OPERATOR_DESCTests.cs | 1,769 | C# |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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.Net;
using Ds3.Models;
using System.Collections.Generic;
namespace Ds3.Runtime
{
public class Ds3BadStatusCodeException : Ds3RequestException
{
private readonly HttpStatusCode _statusCode;
private readonly Error _error;
private readonly string _responseBody;
public HttpStatusCode StatusCode
{
get { return _statusCode; }
}
public Error Error
{
get { return _error; }
}
public string ResponseBody
{
get { return _responseBody; }
}
public Ds3BadStatusCodeException(IEnumerable<HttpStatusCode> expectedStatusCodes, HttpStatusCode receivedStatusCode, Error error, string responseBody)
: base(StatusCodeMessage(expectedStatusCodes, receivedStatusCode, error))
{
this._statusCode = receivedStatusCode;
this._error = error;
this._responseBody = responseBody;
}
private static string StatusCodeMessage(IEnumerable<HttpStatusCode> expectedStatusCodes, HttpStatusCode receivedStatusCode, Error error)
{
var expectedCodesString = string.Join(", ", expectedStatusCodes);
if (error == null)
{
return string.Format(Resources.BadStatusCodeInvalidErrorResponseException, receivedStatusCode, expectedCodesString);
}
else
{
return string.Format(Resources.BadStatusCodeException, receivedStatusCode, expectedCodesString, error.Message);
}
}
}
}
| 36.338462 | 158 | 0.617697 | [
"Apache-2.0"
] | RachelTucker/ds3_net_sdk | Ds3/Runtime/Ds3BadStatusCodeException.cs | 2,364 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using Xunit;
using static Delta.Units.Systems.Dimensionless;
namespace Delta.Units
{
[ExcludeFromCodeCoverage]
public class DimensionlessCoverageTests
{
// Angles
[Fact]
public void RadianIsDegreeMultipliedByPIDividedBy180()
{
var degrees = 1m * degree;
var radians = degrees.ConvertTo(radian);
Assert.Equal(Helpers.PI / 180m, radians.Value);
}
[Fact]
public void DegreeIsRadianDividedByPIMultipliedBy180()
{
var radians = 1m * radian;
var degrees = radians.ConvertTo(degree);
// We can't be exact: we are accurate up to 13 decimals by using decimal type.
Assert.Equal(Math.Round(180m / Helpers.PI, 13), Math.Round(degrees.Value, 13));
}
[Fact]
public void RadianIsTurnMultipliedBy2ByPI()
{
var turns = 1m * turn;
var radians = turns.ConvertTo(radian);
Assert.Equal(2m * Helpers.PI, radians.Value);
}
[Fact]
public void TurnIsRadianDividedBy2ByPI()
{
var radians = 1m * radian;
var turns = radians.ConvertTo(turn);
Assert.Equal(1m / (2m * Helpers.PI), turns.Value);
}
// Proportions
[Fact]
public void PercentIsPermilleMultipliedBy10()
{
var pc = 1m * percent;
var pm = pc.ConvertTo(permille);
Assert.Equal(10m, pm.Value);
}
[Fact]
public void PermilleIsPercentDividedBy10()
{
var pm = 1m * permille;
var pc = pm.ConvertTo(percent);
Assert.Equal(0.1m, pc.Value);
}
[Fact]
public void PercentIsPpmMultipliedBy10000()
{
var pc = 1m * percent;
var ppm = pc.ConvertTo(parts_per_million);
Assert.Equal(10000m, ppm.Value);
}
}
}
| 27.22973 | 91 | 0.552854 | [
"MIT"
] | odalet/Delta.Units | src/UnitTests/UnitTests.Delta.Units/DimensionlessCoverageTests.cs | 2,017 | C# |
using System.IO;
using System.Linq;
using Baseline;
using StoryTeller.Grammars.API;
namespace StoryTeller.CSV
{
public class CsvFile
{
private readonly StringWriter _writer = new StringWriter();
public void WriteValues(params string[] values)
{
var line = values.Select(Escape).Join(",");
_writer.WriteLine(line);
}
public static string Escape(string raw)
{
var shouldBeEscaped = raw.Contains(",") || raw.Contains("\"");
if (shouldBeEscaped)
{
var escaped = raw.Replace("\"", "\"\"");
return $"\"{escaped}\"";
}
return raw;
}
public override string ToString()
{
return _writer.ToString();
}
/// <summary>
/// Generated string for the Csv content
/// </summary>
/// <returns></returns>
public string Contents()
{
return _writer.ToString();
}
/// <summary>
/// Write the generated contents of this CsvFile to the file system
/// </summary>
/// <param name="path"></param>
public void WriteToFile(string path)
{
File.WriteAllText(path, _writer.ToString());
}
}
}
| 23.086207 | 75 | 0.506348 | [
"Apache-2.0"
] | SergeiGolos/Storyteller | src/StoryTeller/CSV/CsvFile.cs | 1,339 | C# |
using MakeSimple.SharedKernel.Infrastructure.Api;
using MakeSimple.SharedKernel.Infrastructure.DTO;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Org.VSATemplate.Application.Features.Students;
using Org.VSATemplate.Domain.Dtos.Student;
using System.Threading.Tasks;
namespace Org.VSATemplate.WebApi.Apis.v1
{
[ApiController]
[ApiVersion("1.0")]
public class StudentController : ControllerApiBase
{
private readonly IMediator _mediator;
public StudentController(IMediator mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets a single Student by ID.
/// </summary>
/// <response code="200">Student record returned successfully.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while creating the Student.</response>
[HttpGet("{studentId}")]
[AllowAnonymous]
[ProducesResponseType(typeof(Response<ClassDto>), 200)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
public async Task<IActionResult> GetAsync(long studentId)
{
return ResultDTO(await _mediator.Send(new StudentQuery(studentId)));
}
/// <summary>
/// Gets a list of all Students.
/// </summary>
/// <response code="200">Student list returned successfully.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while proccess.</response>
/// <remarks>
/// Requests can be narrowed down with a variety of query string values:
/// ## Query String Parameters
/// - **PageNumber**: An integer value that designates the page of records that should be returned.
/// - **PageSize**: An integer value that designates the number of records returned on the given page that you would like to return. This value is capped by the internal MaxPageSize.
/// - **SortOrder**: A comma delimited ordered list of property names to sort by. Adding a `-` before the name switches to sorting descendingly.
/// - **Filters**: A comma delimited list of fields to filter by formatted as `{Name}{Operator}{Value}` where
/// - {Name} is the name of a filterable property. You can also have multiple names (for OR logic) by enclosing them in brackets and using a pipe delimiter, eg. `(LikeCount|CommentCount)>10` asks if LikeCount or CommentCount is >10
/// - {Operator} is one of the Operators below
/// - {Value} is the value to use for filtering. You can also have multiple values (for OR logic) by using a pipe delimiter, eg.`Title@= new|hot` will return posts with titles that contain the text "new" or "hot"
///
/// | Operator | Meaning | Operator | Meaning |
/// | -------- | ----------------------------- | --------- | -------------------------------------------- |
/// | `==` | Equals | `!@=` | Does not Contains |
/// | `!=` | Not equals | `!_=` | Does not Starts with |
/// | `>` | Greater than | `@=*` | Case-insensitive string Contains |
/// | `<` | Less than | `_=*` | Case-insensitive string Starts with |
/// | `>=` | Greater than or equal to | `==*` | Case-insensitive string Equals |
/// | `<=` | Less than or equal to | `!=*` | Case-insensitive string Not equals |
/// | `@=` | Contains | `!@=*` | Case-insensitive string does not Contains |
/// | `_=` | Starts with | `!_=*` | Case-insensitive string does not Starts with |
/// </remarks>
[HttpGet]
[AllowAnonymous]
[ProducesResponseType(typeof(PaginatedList<ClassDto>), 200)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
public async Task<IActionResult> Get([FromQuery] StudentListQuery query)
{
return ResultDTO(await _mediator.Send(query));
}
/// <summary>
/// Creates a new Student record.
/// </summary>
/// <response code="200">Student created.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while creating the Student.</response>
[HttpPost]
[AllowAnonymous]
[ProducesResponseType(typeof(Response<ClassDto>), 200)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
[Consumes("application/json")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromBody] StudentForCreationDto request)
{
return ResultDTO(await _mediator.Send(new AddStudentCommand(request)));
}
/// <summary>
/// Updates an entire existing Student.
/// </summary>
/// <response code="204">Student updated.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while creating the Student.</response>
[HttpPut("{studentId}")]
[AllowAnonymous]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
[Consumes("application/json")]
[Produces("application/json")]
public async Task<IActionResult> Put(long studentId, [FromBody] StudentForUpdateDto request)
{
return ResultDTO(await _mediator.Send(new UpdateStudentCommand(studentId, request)));
}
/// <summary>
/// Updates specific properties on an existing Student.
/// </summary>
/// <response code="204">Student updated.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while creating the Student.</response>
[HttpPatch("{studentId}")]
[AllowAnonymous]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
[Consumes("application/json")]
[Produces("application/json")]
public async Task<IActionResult> Patch(long studentId, [FromBody] JsonPatchDocument<StudentForUpdateDto> patchDoc)
{
return ResultDTO(await _mediator.Send(new PatchStudentCommand(studentId, patchDoc)));
}
/// <summary>
/// Deletes an existing Student record.
/// </summary>
/// <response code="204">Student deleted.</response>
/// <response code="400">Student has missing/invalid values.</response>
/// <response code="500">There was an error on the server while creating the Student.</response>
[HttpDelete("{studentId}")]
[AllowAnonymous]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(Response<>), 400)]
[ProducesResponseType(typeof(Response<>), 500)]
public async Task<IActionResult> Delete(long studentId)
{
return ResultDTO(await _mediator.Send(new DeleteStudentCommand(studentId)));
}
}
} | 54.236486 | 244 | 0.583032 | [
"MIT"
] | coderstrong/VSATemplate | Sources/Org.VSATemplate.WebApi/Apis/v1/StudentController.cs | 8,029 | C# |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using ProtoBuf;
namespace VsChromium.Core.Ipc.TypedMessages {
[ProtoContract]
public class ProjectEntry {
[ProtoMember(1)]
public string RootPath { get; set; }
}
} | 26.461538 | 73 | 0.729651 | [
"BSD-3-Clause"
] | C-EO/vs-chromium | src/Core/Ipc/TypedMessages/ProjectEntry.cs | 344 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the AcceptTransitGatewayVpcAttachment operation.
/// Accepts a request to attach a VPC to a transit gateway.
///
///
/// <para>
/// The VPC attachment must be in the <code>pendingAcceptance</code> state. Use <a>DescribeTransitGatewayVpcAttachments</a>
/// to view your pending VPC attachment requests. Use <a>RejectTransitGatewayVpcAttachment</a>
/// to reject a VPC attachment request.
/// </para>
/// </summary>
public partial class AcceptTransitGatewayVpcAttachmentRequest : AmazonEC2Request
{
private string _transitGatewayAttachmentId;
/// <summary>
/// Gets and sets the property TransitGatewayAttachmentId.
/// <para>
/// The ID of the attachment.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string TransitGatewayAttachmentId
{
get { return this._transitGatewayAttachmentId; }
set { this._transitGatewayAttachmentId = value; }
}
// Check to see if TransitGatewayAttachmentId property is set
internal bool IsSetTransitGatewayAttachmentId()
{
return this._transitGatewayAttachmentId != null;
}
}
} | 33.272727 | 127 | 0.680783 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/AcceptTransitGatewayVpcAttachmentRequest.cs | 2,196 | C# |
using System.Collections.Generic;
namespace Orchard.Indexing {
public interface IIndexProvider : ISingletonDependency {
/// <summary>
/// Creates a new index
/// </summary>
void CreateIndex(string name);
/// <summary>
/// Checks whether an index is already existing or not
/// </summary>
bool Exists(string name);
/// <summary>
/// Lists all existing indexes
/// </summary>
IEnumerable<string> List();
/// <summary>
/// Deletes an existing index
/// </summary>
void DeleteIndex(string name);
/// <summary>
/// Whether an index is empty or not
/// </summary>
bool IsEmpty(string indexName);
/// <summary>
/// Gets the number of indexed documents
/// </summary>
int NumDocs(string indexName);
/// <summary>
/// Creates an empty document
/// </summary>
/// <returns></returns>
IDocumentIndex New(int documentId);
/// <summary>
/// Adds a new document to the index
/// </summary>
void Store(string indexName, IDocumentIndex indexDocument);
/// <summary>
/// Adds a set of new document to the index
/// </summary>
void Store(string indexName, IEnumerable<IDocumentIndex> indexDocuments);
/// <summary>
/// Removes an existing document from the index
/// </summary>
void Delete(string indexName, int documentId);
/// <summary>
/// Removes a set of existing document from the index
/// </summary>
void Delete(string indexName, IEnumerable<int> documentIds);
/// <summary>
/// Creates a search builder for this provider
/// </summary>
/// <returns>A search builder instance</returns>
ISearchBuilder CreateSearchBuilder(string indexName);
/// <summary>
/// Returns every field available in the specified index
/// </summary>
IEnumerable<string> GetFields(string indexName);
}
} | 30.458333 | 82 | 0.544916 | [
"MIT"
] | AccentureRapid/OrchardCollaboration | src/Orchard/Indexing/IIndexProvider.cs | 2,195 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
namespace Bermuda.AdminService.Controllers.Amazon
{
public class S3Controller : ApiController
{
// GET /api/s3
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET /api/s3/5
public string Get(int id)
{
return "value";
}
// POST /api/s3
public void Post(string value)
{
}
// PUT /api/s3/5
public void Put(int id, string value)
{
}
// DELETE /api/s3/5
public void Delete(int id)
{
}
}
}
| 19.820513 | 56 | 0.489004 | [
"MIT"
] | melnx/Bermuda | BermudaAdmin/Bermuda.AdminService/Controllers/Amazon/S3Controller.cs | 775 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.