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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcStructuralElementsDomain
{
public enum IfcTendonTypeEnum
{
[Description("The tendon is configured as a bar.")]
BAR = 1,
[Description("The tendon is coated.")]
COATED = 2,
[Description("The tendon is a strand.")]
STRAND = 3,
[Description("The tendon is a wire.")]
WIRE = 4,
[Description("The type of tendon is user defined.")]
USERDEFINED = -1,
[Description("The type of tendon is not defined.")]
NOTDEFINED = 0,
}
}
| 24.789474 | 97 | 0.746285 | [
"Unlicense",
"MIT"
] | BuildingSMART/IfcDoc | IfcKit/schemas/IfcStructuralElementsDomain/IfcTendonTypeEnum.cs | 942 | C# |
using System.IO;
using NUnit.Framework;
using Solutionizer.Models;
using Solutionizer.Services;
using Solutionizer.ViewModels;
namespace Solutionizer.Tests {
[TestFixture]
public class SolutionViewModelTests : ProjectTestBase {
private readonly ISettings _settings;
private readonly IVisualStudioInstallationsProvider _visualStudioInstallationsProvider = new DummyVisualStudioInstallationProvider();
public SolutionViewModelTests() {
_settings = new Settings {
SimplifyProjectTree = true
};
}
[Test]
public void CanAddProject() {
CopyTestDataToPath("CsTestProject1.csproj", _testDataPath);
var scanningCommand = new ScanningCommand(_testDataPath, true);
scanningCommand.Start().Wait();
Project project;
scanningCommand.Projects.TryGetValue(Path.Combine(_testDataPath, "CsTestProject1.csproj"), out project);
var sut = new SolutionViewModel(new DummyStatusMessenger(), _settings, _visualStudioInstallationsProvider, _testDataPath, scanningCommand.Projects);
sut.AddProject(project);
Assert.AreEqual(1, sut.SolutionItems.Count);
Assert.AreEqual("CsTestProject1", sut.SolutionItems[0].Name);
Assert.AreEqual(typeof (SolutionProject), sut.SolutionItems[0].GetType());
}
[Test]
public void CanAddProjectWithProjectReference() {
CopyTestDataToPath("CsTestProject1.csproj", Path.Combine(_testDataPath, "p1"));
CopyTestDataToPath("CsTestProject2.csproj", Path.Combine(_testDataPath, "p2"));
var scanningCommand = new ScanningCommand(_testDataPath, true);
scanningCommand.Start().Wait();
Project project;
scanningCommand.Projects.TryGetValue(Path.Combine(_testDataPath, "p2", "CsTestProject2.csproj"), out project);
var sut = new SolutionViewModel(new DummyStatusMessenger(), _settings, _visualStudioInstallationsProvider, _testDataPath, scanningCommand.Projects);
sut.AddProject(project);
Assert.AreEqual(2, sut.SolutionItems.Count);
Assert.AreEqual("_References", sut.SolutionItems[0].Name);
Assert.AreEqual("CsTestProject2", sut.SolutionItems[1].Name);
Assert.AreEqual(1, ((SolutionFolder) sut.SolutionItems[0]).Items.Count);
Assert.AreEqual("CsTestProject1", ((SolutionFolder) sut.SolutionItems[0]).Items[0].Name);
}
}
} | 43.983051 | 161 | 0.665896 | [
"MIT"
] | thoemmi/Solutionizer | Solutionizer.Tests/SolutionViewModelTests.cs | 2,539 | C# |
using AutoFixture;
namespace Framework.Extensions.Fixture;
public static class FixtureExtensions
{
public static AutoFixture.Fixture IgnoreCircular(this AutoFixture.Fixture fixture)
{
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
return fixture;
}
public static AutoFixture.Fixture OnlyOwnValues(this AutoFixture.Fixture fixture)
{
fixture.Customizations.Add(new OmitSpecimenBuilder());
return fixture;
}
} | 28.894737 | 86 | 0.723133 | [
"BSD-3-Clause"
] | byCrookie/Framework | src/Framework/Extensions/Fixture/FixtureExtensions.cs | 551 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Blockycraft.World.Chunk
{
public sealed class ChunkBlocks : IEnumerable<BlockType>
{
public BlockType[,,] Blocks { get; }
public int Length => Blocks.GetLength(0);
public int Height => Blocks.GetLength(1);
public int Depth => Blocks.GetLength(2);
public Vector3Int Coordinate => new Vector3Int(X, Y, Z);
public int X { get; }
public int Y { get; }
public int Z { get; }
public ChunkBlocks(int x, int y, int z, int size)
{
Blocks = new BlockType[size, size, size];
X = x;
Y = y;
Z = z;
}
public bool TryGet(ref Vector3Int coord, out BlockType type)
{
if (coord.x < 0 || coord.x >= Length ||
coord.y < 0 || coord.y >= Height ||
coord.z < 0 || coord.z >= Depth)
{
type = null;
return false;
}
type = Blocks[coord.x, coord.y, coord.z];
return true;
}
public bool Contains(int x, int y, int z)
{
if (x < 0 || x >= Length ||
y < 0 || y >= Height ||
z < 0 || z >= Depth)
{
return false;
}
return true;
}
public Iterator3D GetIterator()
{
return new Iterator3D(Length, Height, Depth);
}
public IEnumerator<BlockType> GetEnumerator()
{
var iterator = GetIterator();
foreach (var coord in iterator)
yield return Blocks[coord.x, coord.y, coord.z];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} | 28.731343 | 69 | 0.465455 | [
"MIT"
] | blockycraft/blockycraft | blockycraft/Assets/Engine/Spatial/ChunkBlocks.cs | 1,927 | C# |
namespace FormatValidator
{
using System.Collections.Generic;
public interface ISourceReader
{
IEnumerable<string> ReadLines(string rowSeperator);
}
}
| 16.181818 | 59 | 0.702247 | [
"MIT"
] | alexander-sml/csv-validator | src/Validate.Lib/ISourceReader.cs | 180 | C# |
namespace UblTr.Common
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("LimitationDescription", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)]
public partial class LimitationDescriptionType : TextType1
{
}
} | 52.454545 | 176 | 0.774697 | [
"MIT"
] | enisgurkann/UblTr | Ubl-Tr/Common/CommonBasicComponents/LimitationDescriptionType.cs | 577 | C# |
using Azimuth.DataProviders.Interfaces;
using Azimuth.Infrastructure.Concrete;
namespace Azimuth.DataProviders.Concrete
{
//public class MusicServiceWorkUnit : IMusicServiceWorkUnit
//{
// private readonly IMusicServiceFactory _musicServiceFactory;
// public MusicServiceWorkUnit(IMusicServiceFactory musicServiceFactory)
// {
// _musicServiceFactory = musicServiceFactory;
// }
// public IMusicService<T> GetMusicService<T>()
// {
// return _musicServiceFactory.Resolve<T>();
// }
//}
} | 30.157895 | 79 | 0.675393 | [
"MIT"
] | DmitrijDN/Azimuth | Azimuth/DataProviders/Concrete/MusicServiceWorkUnit.cs | 575 | C# |
using System;
using AdjacentProduct;
using Xunit;
namespace AdjacentProductTests
{
public class UnitTest1
{
[Fact]
public void LargestValue1()
{
int[,] dataSet = new int[,] { { 1, 2, 1 }, { 2, 4, 2 }, { 3, 6, 8 }, { 7, 8, 1 } };
Assert.Equal(64, Program.LargestProduct(dataSet));
}
[Fact]
public void LargestValue2()
{
int[,] dataSet = new int[,] { { 6, 3, 5, 9 }, { 2, 8, 4, 6 }, { 3, 8, 2, 1 }, { 6, 7, 3, 5 } };
Assert.Equal(64, Program.LargestProduct(dataSet));
}
[Fact]
public void LargestValue3()
{
int[,] dataSet = new int[,] { {2,5,8,6,7 }, { 10,3,4,9,8},
{ 1,6,15,11,2}, { 8,4,6,2,8} ,{ 9,20,2,4,10} };
Assert.Equal(180, Program.LargestProduct(dataSet));
}
}
}
| 24.277778 | 107 | 0.45881 | [
"MIT"
] | ericsingletonjr/Data-Structures-and-Algorithms | First_Iteration/Challenges/AdjacentProduct/AdjacentProductTests/UnitTest1.cs | 874 | C# |
using System;
using System.IO;
namespace ReadAoe2Recrod
{
public partial class Aoe2Record
{
public string GameVersion;
public double SaveVersion;
public bool IsDE = false;
public double Version;
private void ReadVersion(BinaryReader reader)
{
GameVersion = CString(reader);
SaveVersion = Math.Round(reader.ReadSingle(), 2);
IsDE = GameVersion == "VER 9.4" && SaveVersion >= 12.97;
if(!IsDE) return;
var build= reader.ReadUInt32();
var timestamp= reader.ReadUInt32();
Version = reader.ReadSingle();
var intervalVersion = reader.ReadUInt32();
var gameOptionsVersion = reader.ReadUInt32();
var dlcCount = reader.ReadUInt32();
var dlcIds = ArrayUInt32(reader, (int)dlcCount);
}
}
} | 31.678571 | 68 | 0.582864 | [
"MIT"
] | Aoe2Overlay/Aoe2DEOverlay | Aoe2DEOverlay/Parser/Aoe2Record.Version.cs | 887 | C# |
namespace ExampleApi
{
// ReSharper disable once UnusedMember.Global
public record HeadersReceived(ExternalCorrelation External, InternalCorrelation Internal, IAllCorrelation All);
}
| 27.428571 | 115 | 0.8125 | [
"MIT"
] | stevetalkscode/TypedHttpHeaders | example/ExampleApi/HeadersReceived.cs | 192 | C# |
#if NGUI
using System;
using System.Collections.Generic;
using UnityEngine;
using Renko.Utility;
using Renko.LapseFramework;
namespace Renko.MVCFramework
{
/// <summary>
/// The base class of all MVC view components.
/// </summary>
public class BaseMvcView : MonoBehaviour, IMvcView {
/// <summary>
/// Just keeping this value as a reference rather than hard-coding it every time an editor script needs it.
/// </summary>
public const string ClassName = "BaseMvcView";
/// <summary>
/// Whether to reset the UIPanel's rect based on current resolution.
/// </summary>
public bool ResizePanel = true;
/// <summary>
/// Backing field of ViewSize property.
/// </summary>
public ScreenAdaptor ViewSize;
/// <summary>
/// Whether the view is no longer being managed by MVC.
/// </summary>
private bool isDestroyed;
/// <summary>
/// Backing field of ViewId property.
/// </summary>
private int viewId;
/// <summary>
/// Backing field of Animations property for caching.
/// </summary>
private BaseMvcAnimation[] animations;
/// <summary>
/// The longest hide animation for temporary use.
/// </summary>
private BaseMvcAnimation longestHideAni;
/// <summary>
/// Returns the gameObject component of this view.
/// </summary>
public GameObject ViewObject {
get { return gameObject; }
}
/// <summary>
/// The unique id received from UIController upon creation.
/// </summary>
public int ViewId {
get { return viewId; }
}
/// <summary>
/// Returns whether this view is active.
/// If you're using Recycle method, MVC will check for this flag whether this view can be reused.
/// </summary>
public bool IsActive {
get { return gameObject.activeInHierarchy && !isDestroyed; }
}
/// <summary>
/// Array of animations included in this view.
/// </summary>
public BaseMvcAnimation[] Animations {
get {
if(animations == null)
animations = GetComponentsInChildren<BaseMvcAnimation>(true);
return animations;
}
}
/// <summary>
/// For integration with auto generated code with MVC base views.
/// You should use OnInitialize for the actual initialization process.
/// </summary>
public virtual void Awake() {
// Nothing to do!
}
/// <summary>
/// Use this method to resize UIPanel and handle view anchoring.
/// Called ONLY once after Awake() and before OnInitialize().
/// </summary>
public virtual void OnAdaptView(ScreenAdaptor viewSize, MvcRescaleType type) {
this.ViewSize = viewSize;
if(ResizePanel) {
Vector2 newSize = viewSize.GetScaledResolution((ScreenAdaptor.ScaleMode)(int)type);
UIPanel up = GetComponent<UIPanel>();
if(up != null) {
up.SetRect(0f, 0f, newSize.x, newSize.y);
}
}
}
/// <summary>
/// Use this method to handle initialization of fields, resources, etc.
/// Called ONLY once after Awake() and OnAdaptView().
/// </summary>
public virtual void OnInitialize(int viewId, MvcParameter param) {
this.viewId = viewId;
isDestroyed = false;
}
/// <summary>
/// Use this method to handle re-initialization of fields, resources, etc.
/// Will invoke OnViewShow() afterwards.
/// Called everytime this view is being recycled.
/// </summary>
public virtual void OnRecycle(int viewId, MvcParameter param) {
this.viewId = viewId;
isDestroyed = false;
}
/// <summary>
/// Use this method to handle view setup. Ideal place for a show animation, if any.
/// </summary>
public virtual void OnViewShow() {
PlayShowAnimations();
}
/// <summary>
/// Use this method to handle view hiding. Ideal place for a hide animation, if any.
/// You should return a MvcParameter value that represents a return data from this view.
/// If none, just return null.
/// Don't call this base method if you wish to handle animation yourself.
/// </summary>
public virtual MvcParameter OnViewHide() {
PlayHideAnimations();
return null;
}
/// <summary>
/// Use this method to dispose unused resources.
/// Called right before destruction/deactivation of the view for cleanup.
/// </summary>
public virtual void OnDisposeView() {
isDestroyed = true;
}
/// <summary>
/// Plays view animations flagged to view show event.
/// </summary>
public void PlayShowAnimations() {
var ani = Animations;
for(int i=0; i<ani.Length; i++)
ani[i].Play(MvcAnimationEvent.OnViewShow);
}
/// <summary>
/// Plays view animations flagged to view hide event.
/// Will also handle view disposal action.
/// </summary>
public void PlayHideAnimations() {
var ani = Animations;
longestHideAni = null;
for(int i=0; i<ani.Length; i++) {
var curAni = ani[i];
if(curAni.Play(MvcAnimationEvent.OnViewHide)) {
if(longestHideAni == null) {
longestHideAni = curAni;
}
else if(curAni.Duration > longestHideAni.Duration) {
longestHideAni = curAni;
}
}
else if(curAni.TargetEvent == MvcAnimationEvent.OnViewShow) {
curAni.FateAni.Stop();
}
}
// Raising view disposal event.
if(longestHideAni != null) {
longestHideAni.FateAni.AddEvent(FateEvents.OnEnd, OnHideAniEnded);
}
else {
MVC.DisposeView(this);
}
}
/// <summary>
/// Callback method after longestHideAni finishes.
/// </summary>
void OnHideAniEnded(IFateTimer item)
{
longestHideAni.FateAni.RemoveEvent(FateEvents.OnEnd, OnHideAniEnded);
MVC.DisposeView(this);
}
}
}
#endif | 26.878049 | 109 | 0.669147 | [
"MIT"
] | jerryrox/Renko-L | Framework/MVC/BaseMvcView.cs | 5,512 | C# |
using System;
namespace Discord.Json.Objects.Guilds
{
public class IntegrationObject
{
public ulong id;
public string name;
public string type;
public bool enabled;
public bool syncing;
public ulong role_id;
public int expire_behavior;
public int expire_grace_period;
public UserObject user;
public IntegrationAccountObject account;
public DateTime synced_at;
}
}
| 23.3 | 48 | 0.645923 | [
"MIT"
] | QuiCM/Discord-Core-Objects | Json/Objects/Guilds/IntegrationObject.cs | 468 | C# |
using System.ComponentModel.DataAnnotations;
namespace ApiScanner.Entities.Models
{
public class ConfigurationModel
{
/// <summary>
/// Name of config.
/// </summary>
[Key]
[MaxLength(50)]
public string Name { get; set; }
/// <summary>
/// Value of config.
/// </summary>
[MaxLength(250)]
public string Value { get; set; }
}
}
| 20.47619 | 45 | 0.525581 | [
"MIT"
] | icehowler/ApiScanner | ApiScanner.Entities/Models/ConfigurationModel.cs | 432 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LCU.NET
{
public enum InitializeMethod
{
CommandLine,
Lockfile
}
}
| 14.866667 | 33 | 0.695067 | [
"MIT"
] | Chobocharles/LCU.NET | InitializeMethod.cs | 225 | C# |
using Phantasma.Cryptography;
using Phantasma.Numerics;
namespace Phantasma.Domain
{
public enum AccountTrigger
{
OnMint, // address, symbol, amount
OnBurn, // address, symbol, amount
OnSend, // address, symbol, amount
OnReceive, // address, symbol, amount
OnWitness, // address
}
public enum TokenTrigger
{
OnMint, // address, symbol, amount
OnBurn, // address, symbol, amount
OnSend, // address, symbol, amount
OnReceive, // address, symbol, amount
OnMetadata // address, symbol, key, value
}
public enum OrganizationTrigger
{
OnAdd, // address
OnRemove, // address
}
public static class DomainSettings
{
public const int MAX_TOKEN_DECIMALS = 18;
public const string FuelTokenSymbol = "KCAL";
public const string FuelTokenName = "Phantasma Energy";
public const int FuelTokenDecimals = 10;
public const string StakingTokenSymbol = "SOUL";
public const string StakingTokenName = "Phantasma Stake";
public const int StakingTokenDecimals = 8;
public const string FiatTokenSymbol = "USD";
public const string FiatTokenName = "Dollars";
public const int FiatTokenDecimals = 8;
public const string RootChainName = "main";
public const string ValidatorsOrganizationName = "validators";
public const string MastersOrganizationName = "masters";
public const string StakersOrganizationName = "stakers";
public const string PhantomForceOrganizationName = "phantom_force";
public static readonly BigInteger PlatformSupply = UnitConversion.ToBigInteger(100000000, FuelTokenDecimals);
public static readonly string PlatformName = "phantasma";
public static readonly int ArchiveMinSize = 1024; //1kb
public static readonly int ArchiveMaxSize = 104857600; //100mb
public static readonly uint ArchiveBlockSize = MerkleTree.ChunkSize;
}
}
| 32.903226 | 117 | 0.670098 | [
"MIT"
] | merl111/PhantasmaChain | Phantasma.Domain/DomainSettings.cs | 2,042 | C# |
// Copyright (c) 2017 Jan Pluskal
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Castle.Core.Internal;
using GalaSoft.MvvmLight.CommandWpf;
using Netfox.AnalyzerAppIdent.Models;
using Netfox.AnalyzerAppIdent.Properties;
using Netfox.AppIdent.Statistics;
namespace Netfox.AnalyzerAppIdent.ViewModels
{
public class ProtocolModelsClusteringVm : INotifyPropertyChanged
{
public AppIdentMainVm AppIdentMainVm { get; set; }
private RelayCommand<ClusterNodeModel> _collapsNodeCommand;
private RelayCommand<ClusterNodeModel> _expandNodeCommand;
public ProtocolModelsClusteringVm(AppIdentMainVm appIdentMainVm)
{
this.AppIdentMainVm = appIdentMainVm;
this.AppIdentMainVm.EpiPrecMeasureObservable.Subscribe(this.InitializeClusters);
}
public ObservableCollection<ClusterNodeModel> Nodes { get; } = new ObservableCollection<ClusterNodeModel>();
public RelayCommand<ClusterNodeModel> ExpandNodeCommand => this._expandNodeCommand ?? (this._expandNodeCommand = new RelayCommand<ClusterNodeModel>(this.ExpandCluster));
public RelayCommand<ClusterNodeModel> CollapsNodeCommand => this._collapsNodeCommand ?? (this._collapsNodeCommand = new RelayCommand<ClusterNodeModel>(this.CollapsCluster));
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void CollapsCluster(ClusterNodeModel clusterNodeModel)
{
// if(!clusterNodeModel.IsExpanded || clusterNodeModel.ParrentCluster == null) { return; }
ClusterNodeModel clusterNode;
if (clusterNodeModel.IsExpanded && !clusterNodeModel.IsLiefNode) { clusterNode = clusterNodeModel; }
else { clusterNode = clusterNodeModel.ParrentCluster; }
clusterNode.IsExpanded = false;
clusterNode.IsLiefNode = true;
var clusterChildren = clusterNode.Cluster.Children == null? clusterNode.Cluster.FlattenChildren: clusterNode.Cluster.FlattenChildren.Concat(clusterNode.Cluster.Children);
if(!clusterChildren.IsNullOrEmpty())
{
foreach(var node in this.Nodes.ToArray()) {
if(clusterChildren.Contains(node.Cluster)) { this.Nodes.Remove(node); }
}
}
this.UpdatePrecMeter();
}
private void ExpandCluster(ClusterNodeModel clusterNodeModel)
{
if(clusterNodeModel.IsExpanded) { return; }
clusterNodeModel.IsExpanded = true;
clusterNodeModel.IsLiefNode = false;
var clusterChildren = clusterNodeModel.Cluster.Children;
if(!clusterChildren.IsNullOrEmpty())
{
var newClusterNodes = new List<ClusterNodeModel>();
foreach(var cluster in clusterChildren)
{
var clusterNode = new ClusterNodeModel
{
Cluster = cluster,
ParrentCluster = clusterNodeModel
};
this.Nodes.Add(clusterNode);
newClusterNodes.Add(clusterNode);
}
foreach(var clusterNode in newClusterNodes)
{
clusterNode.Connections.Add(new ConnectionModel
{
Target = clusterNodeModel
});
clusterNodeModel.Connections.Add(new ConnectionModel
{
Target = clusterNode
});
}
}
this.UpdatePrecMeter();
}
private void UpdatePrecMeter()
{
var applicationProtocolClassificationStatisticsMeter = new ApplicationProtocolClassificationStatisticsMeter();
foreach(var node in this.Nodes.Where(n=>n.IsLiefNode))
{
applicationProtocolClassificationStatisticsMeter.AppStatistics.AddOrUpdate(node.Cluster.ClusterAppTags, node.Cluster.ApplicationProtocolClassificationStatistics,
(s, statistics) => statistics);
}
this.PrecMeasure = applicationProtocolClassificationStatisticsMeter;
this.AppIdentMainVm.EpiPrecMeasure = applicationProtocolClassificationStatisticsMeter;
}
public ApplicationProtocolClassificationStatisticsMeter PrecMeasure { get; set; }
private void InitializeClusters(ApplicationProtocolClassificationStatisticsMeter precMeasure)
{
if(this.PrecMeasure == precMeasure) return;
var cluesters = this.AppIdentMainVm.AppProtoModelEval.ApplicationProtocolModelsHierachivalClustering();
this.Nodes.Clear();
if(cluesters == null) return;
foreach(var cluster in cluesters)
{
cluster.UpdateStatistics(precMeasure);
var clusterNode = new ClusterNodeModel
{
Cluster = cluster
};
clusterNode.ParrentCluster = clusterNode;
this.Nodes.Add(clusterNode);
}
}
}
} | 41.591837 | 183 | 0.648348 | [
"Apache-2.0"
] | pokornysimon/NetfoxDetective | NetfoxCore/Detective/App/Analyzers/AnalyzerAppIdent/ViewModels/ProtocolModelsClusteringVm.cs | 6,116 | 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 dynamodb-2012-08-10.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.DynamoDBv2.Model
{
/// <summary>
/// For the <code>UpdateItem</code> operation, represents the attributes to be modified,
/// the action to perform on each, and the new value for each.
///
/// <note>
/// <para>
/// You cannot use <code>UpdateItem</code> to update any primary key attributes. Instead,
/// you will need to delete the item, and then use <code>PutItem</code> to create a new
/// item with new attributes.
/// </para>
/// </note>
/// <para>
/// Attribute values cannot be null; string and binary type attributes must have lengths
/// greater than zero; and set type attributes must not be empty. Requests with empty
/// values will be rejected with a <code>ValidationException</code> exception.
/// </para>
/// </summary>
public partial class AttributeValueUpdate
{
private AttributeAction _action;
private AttributeValue _value;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public AttributeValueUpdate() { }
/// <summary>
/// Instantiates AttributeValueUpdate with the parameterized properties
/// </summary>
/// <param name="value">Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">Data Types</a> in the <i>Amazon DynamoDB Developer Guide</i>. </param>
/// <param name="action">Specifies how to perform the update. Valid values are <code>PUT</code> (default), <code>DELETE</code>, and <code>ADD</code>. The behavior depends on whether the specified primary key already exists in the table. <b>If an item with the specified <i>Key</i> is found in the table:</b> <ul> <li> <code>PUT</code> - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value. </li> <li> <code>DELETE</code> - If no value is specified, the attribute and its value are removed from the item. The data type of the specified value must match the existing value's data type. If a <i>set</i> of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set <code>[a,b,c]</code> and the <code>DELETE</code> action specified <code>[a,c]</code>, then the final attribute value would be <code>[b]</code>. Specifying an empty set is an error. </li> <li> <code>ADD</code> - If the attribute does not already exist, then the attribute and its values are added to the item. If the attribute does exist, then the behavior of <code>ADD</code> depends on the data type of the attribute: <ul> <li> If the existing attribute is a number, and if <code>Value</code> is also a number, then the <code>Value</code> is mathematically added to the existing attribute. If <code>Value</code> is a negative number, then it is subtracted from the existing attribute. <note> If you use <code>ADD</code> to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. In addition, if you use <code>ADD</code> to update an existing item, and intend to increment or decrement an attribute value which does not yet exist, DynamoDB uses <code>0</code> as the initial value. For example, suppose that the item you want to update does not yet have an attribute named <i>itemcount</i>, but you decide to <code>ADD</code> the number <code>3</code> to this attribute anyway, even though it currently does not exist. DynamoDB will create the <i>itemcount</i> attribute, set its initial value to <code>0</code>, and finally add <code>3</code> to it. The result will be a new <i>itemcount</i> attribute in the item, with a value of <code>3</code>. </note> </li> <li> If the existing data type is a set, and if the <code>Value</code> is also a set, then the <code>Value</code> is added to the existing set. (This is a <i>set</i> operation, not mathematical addition.) For example, if the attribute value was the set <code>[1,2]</code>, and the <code>ADD</code> action specified <code>[3]</code>, then the final attribute value would be <code>[1,2,3]</code>. An error occurs if an Add action is specified for a set attribute and the attribute type specified does not match the existing set type. Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, the <code>Value</code> must also be a set of strings. The same holds true for number sets and binary sets. </li> </ul> This action is only valid for an existing attribute whose data type is number or is a set. Do not use <code>ADD</code> for any other data types. </li> </ul> <b>If no item with the specified <i>Key</i> is found:</b> <ul> <li> <code>PUT</code> - DynamoDB creates a new item with the specified primary key, and then adds the attribute. </li> <li> <code>DELETE</code> - Nothing happens; there is no attribute to delete. </li> <li> <code>ADD</code> - DynamoDB creates an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are number and number set; no other data types can be specified. </li> </ul></param>
public AttributeValueUpdate(AttributeValue value, AttributeAction action)
{
_value = value;
_action = action;
}
/// <summary>
/// Gets and sets the property Action.
/// <para>
/// Specifies how to perform the update. Valid values are <code>PUT</code> (default),
/// <code>DELETE</code>, and <code>ADD</code>. The behavior depends on whether the specified
/// primary key already exists in the table.
/// </para>
///
/// <para>
/// <b>If an item with the specified <i>Key</i> is found in the table:</b>
/// </para>
/// <ul> <li>
/// <para>
/// <code>PUT</code> - Adds the specified attribute to the item. If the attribute already
/// exists, it is replaced by the new value.
/// </para>
/// </li> <li>
/// <para>
/// <code>DELETE</code> - If no value is specified, the attribute and its value are removed
/// from the item. The data type of the specified value must match the existing value's
/// data type.
/// </para>
///
/// <para>
/// If a <i>set</i> of values is specified, then those values are subtracted from the
/// old set. For example, if the attribute value was the set <code>[a,b,c]</code> and
/// the <code>DELETE</code> action specified <code>[a,c]</code>, then the final attribute
/// value would be <code>[b]</code>. Specifying an empty set is an error.
/// </para>
/// </li> <li>
/// <para>
/// <code>ADD</code> - If the attribute does not already exist, then the attribute and
/// its values are added to the item. If the attribute does exist, then the behavior of
/// <code>ADD</code> depends on the data type of the attribute:
/// </para>
/// <ul> <li>
/// <para>
/// If the existing attribute is a number, and if <code>Value</code> is also a number,
/// then the <code>Value</code> is mathematically added to the existing attribute. If
/// <code>Value</code> is a negative number, then it is subtracted from the existing attribute.
/// </para>
/// <note>
/// <para>
/// If you use <code>ADD</code> to increment or decrement a number value for an item
/// that doesn't exist before the update, DynamoDB uses 0 as the initial value.
/// </para>
///
/// <para>
/// In addition, if you use <code>ADD</code> to update an existing item, and intend to
/// increment or decrement an attribute value which does not yet exist, DynamoDB uses
/// <code>0</code> as the initial value. For example, suppose that the item you want to
/// update does not yet have an attribute named <i>itemcount</i>, but you decide to <code>ADD</code>
/// the number <code>3</code> to this attribute anyway, even though it currently does
/// not exist. DynamoDB will create the <i>itemcount</i> attribute, set its initial value
/// to <code>0</code>, and finally add <code>3</code> to it. The result will be a new
/// <i>itemcount</i> attribute in the item, with a value of <code>3</code>.
/// </para>
/// </note> </li> <li>
/// <para>
/// If the existing data type is a set, and if the <code>Value</code> is also a set, then
/// the <code>Value</code> is added to the existing set. (This is a <i>set</i> operation,
/// not mathematical addition.) For example, if the attribute value was the set <code>[1,2]</code>,
/// and the <code>ADD</code> action specified <code>[3]</code>, then the final attribute
/// value would be <code>[1,2,3]</code>. An error occurs if an Add action is specified
/// for a set attribute and the attribute type specified does not match the existing set
/// type.
/// </para>
///
/// <para>
/// Both sets must have the same primitive data type. For example, if the existing data
/// type is a set of strings, the <code>Value</code> must also be a set of strings. The
/// same holds true for number sets and binary sets.
/// </para>
/// </li> </ul>
/// <para>
/// This action is only valid for an existing attribute whose data type is number or is
/// a set. Do not use <code>ADD</code> for any other data types.
/// </para>
/// </li> </ul>
/// <para>
/// <b>If no item with the specified <i>Key</i> is found:</b>
/// </para>
/// <ul> <li>
/// <para>
/// <code>PUT</code> - DynamoDB creates a new item with the specified primary key, and
/// then adds the attribute.
/// </para>
/// </li> <li>
/// <para>
/// <code>DELETE</code> - Nothing happens; there is no attribute to delete.
/// </para>
/// </li> <li>
/// <para>
/// <code>ADD</code> - DynamoDB creates an item with the supplied primary key and number
/// (or set of numbers) for the attribute value. The only data types allowed are number
/// and number set; no other data types can be specified.
/// </para>
/// </li> </ul>
/// </summary>
public AttributeAction Action
{
get { return this._action; }
set { this._action = value; }
}
// Check to see if Action property is set
internal bool IsSetAction()
{
return this._action != null;
}
/// <summary>
/// Gets and sets the property Value.
/// <para>
/// Represents the data for an attribute.
/// </para>
///
/// <para>
/// Each attribute value is described as a name-value pair. The name is the data type,
/// and the value is the data itself.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">Data
/// Types</a> in the <i>Amazon DynamoDB Developer Guide</i>.
/// </para>
/// </summary>
public AttributeValue Value
{
get { return this._value; }
set { this._value = value; }
}
// Check to see if Value property is set
internal bool IsSetValue()
{
return this._value != null;
}
}
} | 62.239234 | 3,762 | 0.63238 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/DynamoDBv2/Generated/Model/AttributeValueUpdate.cs | 13,008 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Game.Screens.Tournament.Components
{
public class DrawingsConfigManager : IniConfigManager<DrawingsConfig>
{
protected override string Filename => @"drawings.ini";
protected override void InitialiseDefaults()
{
Set(DrawingsConfig.Groups, 8, 1, 8);
Set(DrawingsConfig.TeamsPerGroup, 8, 1, 8);
}
public DrawingsConfigManager(Storage storage)
: base(storage)
{
}
}
public enum DrawingsConfig
{
Groups,
TeamsPerGroup
}
}
| 26.258065 | 93 | 0.62285 | [
"MIT"
] | AtomCrafty/osu | osu.Game/Screens/Tournament/Components/DrawingsConfigManager.cs | 786 | C# |
// This sample, non-production-ready project that demonstrates how to detect when an Amazon Elastic Beanstalk
// platform's base AMI has been updated and starts an EC2 Image Builder Pipeline to automate the creation of a golden image.
// © 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
// This AWS Content is provided subject to the terms of the AWS Customer Agreement available at
// http://aws.amazon.com/agreement or other written agreement between Customer and either
// Amazon Web Services, Inc. or Amazon Web Services EMEA SARL or both.
// SPDX-License-Identifier: MIT-0
[assembly: Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace BeanstalkImageBuilderPipeline
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Amazon.Lambda.Core;
using System.Threading.Tasks;
using Amazon.ElasticBeanstalk;
using Amazon.Lambda.CloudWatchEvents.ScheduledEvents;
using Amazon.SimpleSystemsManagement;
using BeanstalkImageBuilderPipeline.Repositories;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
public sealed class AmiMonitor : LambdaFunction {
/// <summary>
/// Constructor used by Lambda at runtime.
/// </summary>
[ExcludeFromCodeCoverage]
public AmiMonitor() { }
public AmiMonitor(IServiceProvider serviceProvider) : base(serviceProvider) { }
[ExcludeFromCodeCoverage]
protected override void ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services) {
services.AddScoped<IBeanstalkRepository, BeanstalkRepository>();
services.AddScoped<ISsmRepository, SsmRepository>();
services.AddAWSService<IAmazonElasticBeanstalk>();
services.AddAWSService<IAmazonSimpleSystemsManagement>();
}
public async Task Handler(ScheduledEvent request, ILambdaContext context) {
var logger = ServiceProvider.GetRequiredService<ILogger<AmiMonitor>>();
using (logger.BeginScope(new Dictionary<string, string> { ["AwsRequestId"] = context.AwsRequestId })) {
try {
var beanstalkRepo = ServiceProvider.GetRequiredService<IBeanstalkRepository>();
string beanstalkPlatform = Environment.GetEnvironmentVariable("PLATFORM_ARN");
string latestAmiId = await beanstalkRepo.GetLatestAmiVersionAsync(beanstalkPlatform);
if (string.IsNullOrEmpty(latestAmiId)) {
logger.LogError("Unable to retrieve latest AMI ID for Beanstalk platform {BeanstalkPlatformId}. Ensure PLATFORM_ARN environment variable is valid.", beanstalkPlatform);
return;
}
var ssmRepo = ServiceProvider.GetRequiredService<ISsmRepository>();
await ssmRepo.UpdateParameterAsync(Environment.GetEnvironmentVariable("SSM_PARAMETER_NAME"), latestAmiId);
}
catch (Exception ex) {
logger.LogError(ex, "Unhandled Exception During Handler Execution.");
throw;
}
}
}
}
}
| 47.861111 | 193 | 0.677597 | [
"MIT-0"
] | aws-samples/elastic-beanstalk-image-pipeline-trigger | src/BeanstalkImageBuilderPipeline/AmiMonitor.cs | 3,447 | C# |
using UnityEngine;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEditor;
using Random = Demo.Utils.Random;
namespace Demo.Systems
{
[AlwaysUpdateSystem]
[DisableAutoCreation]
public class SpawnEntitySystem : JobComponentSystem
{
public int Spawning = 1024;
public int Spawned = 0;
public int SpawnPerBatch = 64;
public Mesh AgentMesh;
public Material AgentMaterial;
private MeshInstanceRenderer sharedMeshRenderer;
private struct RandomizeDataJob : IJobParallelFor
{
[WriteOnly] public NativeArray<float3> positions;
[WriteOnly] public NativeArray<quaternion> rotations;
public void Execute (int index)
{
var position = Random.InUnitSphere () * 100f;
position.y = 0;
positions[index] = position;
rotations[index] = Quaternion.identity;
}
}
// [BurstCompile]
private struct CreateAgentJob : IJobParallelFor
{
[WriteOnly] public EntityCommandBuffer.Concurrent buffer;
[ReadOnly][DeallocateOnJobCompletion] public NativeArray<float3> positions;
[ReadOnly][DeallocateOnJobCompletion] public NativeArray<quaternion> rotations;
public void Execute (int index)
{
buffer.CreateEntity ();
buffer.AddComponent<Position> (new Position { Value = positions[index] });
buffer.AddComponent<Rotation> (new Rotation { Value = rotations[index] });
buffer.AddComponent<MoveSpeed> (new MoveSpeed { speed = 10f });
buffer.AddComponent<TransformMatrix> (new TransformMatrix { Value = new Matrix4x4 () });
}
}
struct PendingMeshRenderer
{
public readonly int Length;
public EntityArray entities;
public ComponentDataArray<TransformMatrix> transforms;
public SubtractiveComponent<MeshInstanceRenderer> sub;
}
struct ExistingEntities
{
public readonly int Length;
public EntityArray entities;
public ComponentDataArray<TransformMatrix> transforms;
}
[Inject] SpawnBarrier barrier;
[Inject] PendingMeshRenderer pendingMeshRenderer;
[Inject] ExistingEntities existingEntities;
protected override JobHandle OnUpdate (JobHandle inputDeps)
{
if (sharedMeshRenderer.mesh != AgentMesh || sharedMeshRenderer.material != AgentMaterial)
{
var buffer = barrier.CreateCommandBuffer ();
sharedMeshRenderer.mesh = AgentMesh;
sharedMeshRenderer.material = AgentMaterial;
for (int i = 0; i < existingEntities.Length; i++)
{
buffer.SetSharedComponent<MeshInstanceRenderer> (existingEntities.entities[i], sharedMeshRenderer);
}
}
if (Spawning > 0)
{
int batchCount = math.min (SpawnPerBatch, Spawning);
Spawning -= batchCount;
Spawned += batchCount;
var positions = new NativeArray<float3> (batchCount, Allocator.TempJob);
var rotations = new NativeArray<quaternion> (batchCount, Allocator.TempJob);
var randomDataJob = new RandomizeDataJob
{
positions = positions,
rotations = rotations
}.Schedule (batchCount, 16, inputDeps);
var createAgentJob = new CreateAgentJob
{
buffer = barrier.CreateCommandBuffer (),
positions = positions,
rotations = rotations
}.Schedule (batchCount, 16, randomDataJob);
return createAgentJob;
}
if (pendingMeshRenderer.Length > 0)
{
var buffer = barrier.CreateCommandBuffer ();
for (int i = 0; i < pendingMeshRenderer.Length; i++)
{
buffer.AddSharedComponent<MeshInstanceRenderer> (pendingMeshRenderer.entities[i], sharedMeshRenderer);
}
}
return inputDeps;
}
protected override void OnCreateManager (int capacity)
{
var go = GameObject.CreatePrimitive (PrimitiveType.Cube);
AgentMesh = go.GetComponent<MeshFilter> ().sharedMesh;
AgentMaterial = Resources.Load ("AgentMaterial") as Material;
GameObject.DestroyImmediate (go);
var entityManager = World.Active.GetOrCreateManager<EntityManager> ();
sharedMeshRenderer = new MeshInstanceRenderer { mesh = AgentMesh, material = AgentMaterial };
}
protected override void OnDestroyManager () { }
public void Spawn ()
{
Spawning += 1024;
}
}
}
| 34.66443 | 122 | 0.585286 | [
"MIT"
] | zulfajuniadi/unity-ecs-system-debugger | Assets/EntitySystemDebugger/Demo/Systems/SpawnEntitySystem.cs | 5,165 | C# |
using Alura.CoisasAFazer.Core.Models;
using MediatR;
namespace Alura.CoisasAFazer.Core.Commands
{
public class ObtemCategoriaPorId: IRequest<Categoria>
{
public ObtemCategoriaPorId(int idCategoria)
{
IdCategoria = idCategoria;
}
public int IdCategoria { get; }
}
}
| 21.1875 | 58 | 0.628319 | [
"MIT"
] | deividt/alura_cursos_csharp | curso_testes_integracao/testes-integracao/src/Alura.CoisasAFazer.Core/Commands/ObtemCategoriaPorId.cs | 341 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Nop.Core.Configuration
{
/// <summary>
/// Represents distributed cache configuration parameters
/// </summary>
public partial class DistributedCacheConfig : IConfig
{
/// <summary>
/// Gets or sets a distributed cache type
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public DistributedCacheType DistributedCacheType { get; set; } = DistributedCacheType.Redis;
/// <summary>
/// Gets or sets a value indicating whether we should use distributed cache
/// </summary>
public bool Enabled { get; set; } = false;
/// <summary>
/// Gets or sets connection string. Used when distributed cache is enabled
/// </summary>
public string ConnectionString { get; set; } = "127.0.0.1:6379,ssl=False";
/// <summary>
/// Gets or sets schema name. Used when distributed cache is enabled and DistributedCacheType property is set as SqlServer
/// </summary>
public string SchemaName { get; set; } = "dbo";
/// <summary>
/// Gets or sets table name. Used when distributed cache is enabled and DistributedCacheType property is set as SqlServer
/// </summary>
public string TableName { get; set; } = "DistributedCache";
}
} | 37.378378 | 130 | 0.632683 | [
"CC0-1.0"
] | peterthomet/BioPuur | nopCommerce 4.4/src/Libraries/Nop.Core/Configuration/DistributedCacheConfig.cs | 1,385 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Tizen.NUI
{
internal static partial class Interop
{
internal static partial class Renderer
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Range_BACKGROUND_EFFECT_get")]
public static extern int RangesBackgroundEffectGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Range_BACKGROUND_get")]
public static extern int RangesBackgroundGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Range_CONTENT_get")]
public static extern int RangesContentGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Range_DECORATION_get")]
public static extern int RangesDecorationGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Range_FOREGROUND_EFFECT_get")]
public static extern int RangesForegroundEffectGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_DEPTH_INDEX_get")]
public static extern int DepthIndexGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_FACE_CULLING_MODE_get")]
public static extern int FaceCullingModeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_MODE_get")]
public static extern int BlendModeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_EQUATION_RGB_get")]
public static extern int BlendEquationRgbGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_EQUATION_ALPHA_get")]
public static extern int BlendEquationAlphaGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_FACTOR_SRC_RGB_get")]
public static extern int BlendFactorSrcRgbGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_FACTOR_DEST_RGB_get")]
public static extern int BlendFactorDestRgbGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_FACTOR_SRC_ALPHA_get")]
public static extern int BlendFactorSrcAlphaGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_FACTOR_DEST_ALPHA_get")]
public static extern int BlendFactorDestAlphaGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_COLOR_get")]
public static extern int BlendColorGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_BLEND_PRE_MULTIPLIED_ALPHA_get")]
public static extern int BlendPreMultipliedAlphaGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_INDEX_RANGE_FIRST_get")]
public static extern int IndexRangeFirstGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_INDEX_RANGE_COUNT_get")]
public static extern int IndexRangeCountGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_DEPTH_WRITE_MODE_get")]
public static extern int DepthWriteModeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_DEPTH_FUNCTION_get")]
public static extern int DepthFunctionGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_DEPTH_TEST_MODE_get")]
public static extern int DepthTestModeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_RENDER_MODE_get")]
public static extern int RenderModeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_FUNCTION_get")]
public static extern int StencilFunctionGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_FUNCTION_MASK_get")]
public static extern int StencilFunctionMaskGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_FUNCTION_REFERENCE_get")]
public static extern int StencilFunctionReferenceGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_MASK_get")]
public static extern int StencilMaskGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_OPERATION_ON_FAIL_get")]
public static extern int StencilOperationOnFailGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_OPERATION_ON_Z_FAIL_get")]
public static extern int StencilOperationOnZFailGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Property_STENCIL_OPERATION_ON_Z_PASS_get")]
public static extern int StencilOperationOnZPassGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Renderer_Property")]
public static extern global::System.IntPtr NewRendererProperty();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_Renderer_Property")]
public static extern void DeleteRendererProperty(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_New")]
public static extern global::System.IntPtr New(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Renderer__SWIG_0")]
public static extern global::System.IntPtr NewRenderer();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_Renderer")]
public static extern void DeleteRenderer(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_Renderer__SWIG_1")]
public static extern global::System.IntPtr NewRenderer(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_DownCast")]
public static extern global::System.IntPtr DownCast(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_Assign")]
public static extern global::System.IntPtr Assign(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_SetGeometry")]
public static extern void SetGeometry(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_GetGeometry")]
public static extern global::System.IntPtr GetGeometry(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_SetIndexRange")]
public static extern void SetIndexRange(global::System.Runtime.InteropServices.HandleRef jarg1, int jarg2, int jarg3);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_SetTextures")]
public static extern void SetTextures(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_GetTextures")]
public static extern global::System.IntPtr GetTextures(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_SetShader")]
public static extern void SetShader(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_GetShader")]
public static extern global::System.IntPtr GetShader(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_Renderer_SWIGUpcast")]
public static extern global::System.IntPtr Upcast(global::System.IntPtr jarg1);
}
}
}
| 70.851351 | 174 | 0.759012 | [
"Apache-2.0",
"MIT"
] | bshsqa/TizenFX | src/Tizen.NUI/src/internal/Interop/Interop.Renderer.cs | 10,488 | C# |
using PnP.Framework.Entities;
using PnP.Framework.Graph;
using PnP.PowerShell.Commands.Attributes;
using PnP.PowerShell.Commands.Base;
using PnP.PowerShell.Commands.Base.PipeBinds;
using System;
using System.IO;
using System.Management.Automation;
namespace PnP.PowerShell.Commands.Microsoft365Groups
{
[Cmdlet(VerbsCommon.Set, "PnPMicrosoft365Group")]
[RequiredMinimalApiPermissions("Group.ReadWrite.All")]
public class SetMicrosoft365Group : PnPGraphCmdlet
{
[Parameter(Mandatory = true, ValueFromPipeline = true)]
public Microsoft365GroupPipeBind Identity;
[Parameter(Mandatory = false)]
public string DisplayName;
[Parameter(Mandatory = false)]
public string Description;
[Parameter(Mandatory = false)]
public String[] Owners;
[Parameter(Mandatory = false)]
public String[] Members;
[Parameter(Mandatory = false)]
public SwitchParameter IsPrivate;
[Parameter(Mandatory = false)]
public string GroupLogoPath;
[Parameter(Mandatory = false)]
public SwitchParameter CreateTeam;
[Parameter(Mandatory = false)]
public bool? HideFromAddressLists;
[Parameter(Mandatory = false)]
public bool? HideFromOutlookClients;
protected override void ExecuteCmdlet()
{
UnifiedGroupEntity group = null;
if (Identity != null)
{
group = Identity.GetGroup(AccessToken, false);
}
Stream groupLogoStream = null;
if (group != null)
{
if (GroupLogoPath != null)
{
if (!Path.IsPathRooted(GroupLogoPath))
{
GroupLogoPath = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, GroupLogoPath);
}
groupLogoStream = new FileStream(GroupLogoPath, FileMode.Open, FileAccess.Read);
}
bool? isPrivateGroup = null;
if (IsPrivate.IsPresent)
{
isPrivateGroup = IsPrivate.ToBool();
}
try
{
UnifiedGroupsUtility.UpdateUnifiedGroup(
groupId: group.GroupId,
accessToken: AccessToken,
displayName: DisplayName,
description: Description,
owners: Owners,
members: Members,
groupLogo: groupLogoStream,
isPrivate: isPrivateGroup,
createTeam: CreateTeam);
if (ParameterSpecified(nameof(HideFromAddressLists)) || ParameterSpecified(nameof(HideFromOutlookClients)))
{
// For this scenario a separate call needs to be made
UnifiedGroupsUtility.SetUnifiedGroupVisibility(group.GroupId, AccessToken, HideFromAddressLists, HideFromOutlookClients);
}
}
catch(Exception e)
{
while (e.InnerException != null) e = e.InnerException;
WriteError(new ErrorRecord(e, "GROUPUPDATEFAILED", ErrorCategory.InvalidOperation, this));
}
}
else
{
WriteError(new ErrorRecord(new Exception("Group not found"), "GROUPNOTFOUND", ErrorCategory.ObjectNotFound, this));
}
}
}
} | 35.058252 | 145 | 0.557463 | [
"MIT"
] | manishsati/powershell | src/Commands/Microsoft365Groups/SetMicrosoft365Group.cs | 3,613 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
namespace System.Collections.Tests
{
public partial class Dictionary_IDictionary_NonGeneric_Tests : IDictionary_NonGeneric_Tests
{
protected override IDictionary NonGenericIDictionaryFactory()
{
return new Dictionary<string, string>();
}
protected override ModifyOperation ModifyEnumeratorThrows => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorThrows : ModifyOperation.Add | ModifyOperation.Insert;
protected override ModifyOperation ModifyEnumeratorAllowed => PlatformDetection.IsNetFramework ? base.ModifyEnumeratorAllowed : ModifyOperation.Overwrite | ModifyOperation.Remove | ModifyOperation.Clear;
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTKey(int seed)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected override object CreateTValue(int seed) => CreateTKey(seed);
protected override Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException);
#region IDictionary tests
[Fact]
public void IDictionary_NonGeneric_ItemSet_NullValueWhenDefaultValueIsNonNull()
{
IDictionary dictionary = new Dictionary<string, int>();
Assert.Throws<ArgumentNullException>(() => dictionary[GetNewKey(dictionary)] = null);
}
[Fact]
public void IDictionary_NonGeneric_ItemSet_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
AssertExtensions.Throws<ArgumentException>("key", () => dictionary[23] = CreateTValue(12345));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_ItemSet_ValueOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = GetNewKey(dictionary);
AssertExtensions.Throws<ArgumentException>("value", () => dictionary[missingKey] = 324);
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = 23;
AssertExtensions.Throws<ArgumentException>("key", () => dictionary.Add(missingKey, CreateTValue(12345)));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_ValueOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, string>();
object missingKey = GetNewKey(dictionary);
AssertExtensions.Throws<ArgumentException>("value", () => dictionary.Add(missingKey, 324));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Add_NullValueWhenDefaultTValueIsNonNull()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, int>();
object missingKey = GetNewKey(dictionary);
Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, null));
Assert.Empty(dictionary);
}
}
[Fact]
public void IDictionary_NonGeneric_Contains_KeyOfWrongType()
{
if (!IsReadOnly)
{
IDictionary dictionary = new Dictionary<string, int>();
Assert.False(dictionary.Contains(1));
}
}
[Fact]
public void Clear_OnEmptyCollection_DoesNotInvalidateEnumerator()
{
if (ModifyEnumeratorAllowed.HasFlag(ModifyOperation.Clear))
{
IDictionary dictionary = new Dictionary<string, string>();
IEnumerator valuesEnum = dictionary.GetEnumerator();
dictionary.Clear();
Assert.Empty(dictionary);
Assert.False(valuesEnum.MoveNext());
}
}
#endregion
#region ICollection tests
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfIncorrectKeyValuePairType(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
KeyValuePair<string, int>[] array = new KeyValuePair<string, int>[count * 3 / 2];
AssertExtensions.Throws<ArgumentException>(null, () => collection.CopyTo(array, 0));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void ICollection_NonGeneric_CopyTo_ArrayOfCorrectKeyValuePairType(int count)
{
ICollection collection = NonGenericICollectionFactory(count);
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
#endregion
}
public class Dictionary_Tests
{
[Fact]
public void CopyConstructorExceptions()
{
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, null));
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new Dictionary<int, int>((IDictionary<int, int>)null, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>()));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), null));
AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Dictionary<int, int>(new NegativeCountDictionary<int, int>(), EqualityComparer<int>.Default));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void ICollection_NonGeneric_CopyTo_NonContiguousDictionary(int count)
{
ICollection collection = (ICollection)CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (object obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void ICollection_Generic_CopyTo_NonContiguousDictionary(int count)
{
ICollection<KeyValuePair<string, string>> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void IDictionary_Generic_CopyTo_NonContiguousDictionary(int count)
{
IDictionary<string, string> collection = CreateDictionary(count, k => k.ToString());
KeyValuePair<string, string>[] array = new KeyValuePair<string, string>[count];
collection.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(101)]
public void CopyTo_NonContiguousDictionary(int count)
{
Dictionary<string, string> collection = (Dictionary<string, string>)CreateDictionary(count, k => k.ToString());
string[] array = new string[count];
collection.Keys.CopyTo(array, 0);
int i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj.Key);
collection.Values.CopyTo(array, 0);
i = 0;
foreach (KeyValuePair<string, string> obj in collection)
Assert.Equal(array[i++], obj.Key);
}
[Fact]
public void Remove_NonExistentEntries_DoesNotPreventEnumeration()
{
const string SubKey = "-sub-key";
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
dictionary.Add("c", "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
dictionary.Add("c" + SubKey, "d");
foreach (string key in dictionary.Keys)
{
if (dictionary.Remove(key + SubKey))
break;
}
}
[Fact]
public void TryAdd_ItemAlreadyExists_DoesNotInvalidateEnumerator()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("a", "b");
IEnumerator valuesEnum = dictionary.GetEnumerator();
Assert.False(dictionary.TryAdd("a", "c"));
Assert.True(valuesEnum.MoveNext());
}
[Theory]
[MemberData(nameof(CopyConstructorInt32Data))]
public void CopyConstructorInt32(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
public static IEnumerable<object[]> CopyConstructorInt32Data
{
get { return GetCopyConstructorData(i => i); }
}
[Theory]
[MemberData(nameof(CopyConstructorStringData))]
public void CopyConstructorString(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector);
}
public static IEnumerable<object[]> CopyConstructorStringData
{
get { return GetCopyConstructorData(i => i.ToString()); }
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector));
Assert.Equal(expected, new Dictionary<T, T>(input));
}
[Theory]
[MemberData(nameof(CopyConstructorInt32ComparerData))]
public void CopyConstructorInt32Comparer(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector, IEqualityComparer<int> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
public static IEnumerable<object[]> CopyConstructorInt32ComparerData
{
get
{
var comparers = new IEqualityComparer<int>[]
{
null,
EqualityComparer<int>.Default
};
return GetCopyConstructorData(i => i, comparers);
}
}
[Theory]
[MemberData(nameof(CopyConstructorStringComparerData))]
public void CopyConstructorStringComparer(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector, IEqualityComparer<string> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
}
[Fact]
public void CantAcceptDuplicateKeysFromSourceDictionary()
{
Dictionary<string, int> source = new Dictionary<string, int> { { "a", 1 }, { "A", 1 } };
AssertExtensions.Throws<ArgumentException>(null, () => new Dictionary<string, int>(source, StringComparer.OrdinalIgnoreCase));
}
public static IEnumerable<object[]> CopyConstructorStringComparerData
{
get
{
var comparers = new IEqualityComparer<string>[]
{
null,
EqualityComparer<string>.Default,
StringComparer.Ordinal,
StringComparer.OrdinalIgnoreCase
};
return GetCopyConstructorData(i => i.ToString(), comparers);
}
}
private static void TestCopyConstructor<T>(int size, Func<int, T> keyValueSelector, Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector, IEqualityComparer<T> comparer)
{
IDictionary<T, T> expected = CreateDictionary(size, keyValueSelector, comparer);
IDictionary<T, T> input = dictionarySelector(CreateDictionary(size, keyValueSelector, comparer));
Assert.Equal(expected, new Dictionary<T, T>(input, comparer));
}
private static IEnumerable<object[]> GetCopyConstructorData<T>(Func<int, T> keyValueSelector, IEqualityComparer<T>[] comparers = null)
{
var dictionarySelectors = new Func<IDictionary<T, T>, IDictionary<T, T>>[]
{
d => d,
d => new DictionarySubclass<T, T>(d),
d => new ReadOnlyDictionary<T, T>(d)
};
var sizes = new int[] { 0, 1, 2, 3 };
foreach (Func<IDictionary<T, T>, IDictionary<T, T>> dictionarySelector in dictionarySelectors)
{
foreach (int size in sizes)
{
if (comparers != null)
{
foreach (IEqualityComparer<T> comparer in comparers)
{
yield return new object[] { size, keyValueSelector, dictionarySelector, comparer };
}
}
else
{
yield return new object[] { size, keyValueSelector, dictionarySelector };
}
}
}
}
private static IDictionary<T, T> CreateDictionary<T>(int size, Func<int, T> keyValueSelector, IEqualityComparer<T> comparer = null)
{
Dictionary<T, T> dict = Enumerable.Range(0, size + 1).ToDictionary(keyValueSelector, keyValueSelector, comparer);
// Remove first item to reduce Count to size and alter the contiguity of the dictionary
dict.Remove(keyValueSelector(0));
return dict;
}
[Fact]
public void ComparerSerialization()
{
// Strings switch between randomized and non-randomized comparers,
// however this should never be observable externally.
TestComparerSerialization(EqualityComparer<string>.Default);
// OrdinalCaseSensitiveComparer is internal and (de)serializes as OrdinalComparer
TestComparerSerialization(StringComparer.Ordinal, "System.OrdinalComparer");
// OrdinalIgnoreCaseComparer is internal and (de)serializes as OrdinalComparer
TestComparerSerialization(StringComparer.OrdinalIgnoreCase, "System.OrdinalComparer");
TestComparerSerialization(StringComparer.CurrentCulture);
TestComparerSerialization(StringComparer.CurrentCultureIgnoreCase);
TestComparerSerialization(StringComparer.InvariantCulture);
TestComparerSerialization(StringComparer.InvariantCultureIgnoreCase);
// Check other types while here, IEquatable valuetype, nullable valuetype, and non IEquatable object
TestComparerSerialization(EqualityComparer<int>.Default);
TestComparerSerialization(EqualityComparer<int?>.Default);
TestComparerSerialization(EqualityComparer<object>.Default);
}
private static void TestComparerSerialization<T>(IEqualityComparer<T> equalityComparer, string internalTypeName = null)
{
var bf = new BinaryFormatter();
var s = new MemoryStream();
var dict = new Dictionary<T, T>(equalityComparer);
Assert.Same(equalityComparer, dict.Comparer);
bf.Serialize(s, dict);
s.Position = 0;
dict = (Dictionary<T, T>)bf.Deserialize(s);
if (internalTypeName == null)
{
Assert.IsType(equalityComparer.GetType(), dict.Comparer);
}
else
{
Assert.Equal(internalTypeName, dict.Comparer.GetType().ToString());
}
Assert.True(equalityComparer.Equals(dict.Comparer));
}
private sealed class DictionarySubclass<TKey, TValue> : Dictionary<TKey, TValue>
{
public DictionarySubclass(IDictionary<TKey, TValue> dictionary)
{
foreach (var pair in dictionary)
{
Add(pair.Key, pair.Value);
}
}
}
/// <summary>
/// An incorrectly implemented dictionary that returns -1 from Count.
/// </summary>
private sealed class NegativeCountDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
public int Count { get { return -1; } }
public TValue this[TKey key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public ICollection<TKey> Keys { get { throw new NotImplementedException(); } }
public ICollection<TValue> Values { get { throw new NotImplementedException(); } }
public void Add(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public void Add(TKey key, TValue value) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool ContainsKey(TKey key) { throw new NotImplementedException(); }
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); }
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { throw new NotImplementedException(); }
public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotImplementedException(); }
public bool Remove(TKey key) { throw new NotImplementedException(); }
public bool TryGetValue(TKey key, out TValue value) { throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
}
}
| 42.43595 | 214 | 0.606699 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs | 20,539 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace WinRT
{
[EditorBrowsable(EditorBrowsableState.Never)]
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class ProjectedRuntimeClassAttribute : Attribute
{
public ProjectedRuntimeClassAttribute(string defaultInterfaceProp)
{
DefaultInterfaceProperty = defaultInterfaceProp;
}
public string DefaultInterfaceProperty { get; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class ObjectReferenceWrapperAttribute : Attribute
{
public ObjectReferenceWrapperAttribute(string objectReferenceField)
{
ObjectReferenceField = objectReferenceField;
}
public string ObjectReferenceField { get; }
}
/// <summary>
/// When applied to a type, designates to WinRT.Runtime that this type represents a type defined in WinRT metadata.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
public sealed class WindowsRuntimeTypeAttribute : Attribute
{
public WindowsRuntimeTypeAttribute(string sourceMetadata = null)
{
SourceMetadata = sourceMetadata;
}
public string SourceMetadata { get; }
}
}
| 34.765957 | 193 | 0.718482 | [
"MIT"
] | angelazhangmsft/CsWinRT | WinRT.Runtime/Attributes.cs | 1,636 | C# |
using Mosa.Runtime;
using System;
using System.Collections.Generic;
namespace Mosa.External.x86
{
public static class Impl
{
public static string[] Split(this string s, char c)
{
string str = s;
List<string> ls = new List<string>();
int indx;
while ((indx = str.IndexOf(c)) != -1)
{
ls.Add(str.Substring(0, indx));
str = str.Substring(indx + 1);
}
if (str.Length > 0)
{
ls.Add(str);
}
string[] result = ls.ToArray();
GC.DisposeObject(ls);
return result;
}
}
}
| 23.066667 | 60 | 0.455202 | [
"Unlicense"
] | SartoxOnlyGNU/MOSA-Core | Source/Mosa.External.x86/Impl.cs | 694 | C# |
namespace WildernessCallouts.Callouts
{
using Rage;
using Rage.Native;
using LSPD_First_Response.Mod.API;
using LSPD_First_Response.Mod.Callouts;
using System.Drawing;
using WildernessCallouts.Types;
[CalloutInfo("IllegalHunting", CalloutProbability.Medium)]
internal class IllegalHunting : CalloutBase
{
//Here we declare our variables, things we need or our callout
private Vehicle hunterVeh; // a rage vehicle
private Ped hunter; // a rage ped
private Ped animal;
private Vector3 spawnPoint; // a Vector3
private Blip animalBlip; // a rage blip
private LHandle pursuit; // an API pursuit handle
private static string[] animalsModels = { "a_c_coyote", "a_c_boar", "a_c_chimp", "a_c_deer", "a_c_cormorant", "a_c_pig", "a_c_deer", "a_c_coyote", "a_c_boar", "a_c_rhesus" };
private static string[] huntersModels = { "csb_cletus", "ig_clay", "ig_oneil", "a_m_m_tramp_01", "ig_old_man1a", "ig_hunter", "player_two", "mp_m_exarmy_01", "ig_clay", "ig_oneil", "ig_old_man2", "ig_old_man1a", "ig_hunter",
"ig_russiandrunk", "ig_clay", "mp_m_exarmy_01", "ig_old_man2", "ig_old_man1a", "ig_hunter", "s_m_y_armymech_01", "s_m_m_ammucountry", "s_m_m_trucker_01", "ig_ortega",
"ig_russiandrunk", "a_m_m_tramp_01", "a_m_m_trampbeac_01", "a_m_m_rurmeth_01", "mp_m_exarmy_01", "g_m_y_pologoon_01", "g_m_y_mexgoon_03", "g_m_y_lost_03", "g_m_y_lost_02",
"g_m_y_pologoon_02", "g_m_m_armboss_01", "u_m_o_taphillbilly", "u_m_o_taphillbilly"
};
private static WeaponAsset[] hunterWeapons = { "WEAPON_PUMPSHOTGUN", "WEAPON_HEAVYSNIPER", "WEAPON_PISTOL50" , "WEAPON_PUMPSHOTGUN", "WEAPON_PISTOL" ,
"WEAPON_HEAVYSNIPER", "WEAPON_SNIPERRIFLE", "WEAPON_HEAVYSNIPER", "WEAPON_COMBATMG" , "WEAPON_PISTOL" ,
"WEAPON_PUMPSHOTGUN", "WEAPON_PISTOL" , "WEAPON_SNIPERRIFLE", "WEAPON_PISTOL50" , "WEAPON_HEAVYSNIPER",
"WEAPON_PUMPSHOTGUN", "WEAPON_HEAVYSNIPER", "WEAPON_PISTOL50" , "WEAPON_SNIPERRIFLE", "WEAPON_SNIPERRIFLE",
"WEAPON_SNIPERRIFLE", "WEAPON_HEAVYSNIPER", "WEAPON_SNIPERRIFLE", "WEAPON_HEAVYSNIPER", "WEAPON_MINIGUN"
};
private static string[] hunterVehicleModels = { "rebel", "rebel2", "sadler", "mesa", "mesa3", "sandking", "sandking2", "bison", "bodhi2", "bobcatxl", "dubsta", "dubsta", "landstalker", "brawler" };
private EIllegalHuntingState state;
private bool breakForceEnd = false;
private static string[] policeGreetings = { "Hi, sir", "Hello", "Hey", "Hello, sir" };
//private string[] policeInsults = { "Asshole!", "Hello", "Hey", "", "" };
private static string[] policeQuestions = { "Where is your hunting license?", "Do you have any hunting license?", "Any hunting license?", "Your hunting license?", "Do you have your hunting license here?" };
private static string[] hunterLicenseAnswers = { "Here you have", "It's here", "I've it here" };
private static string[] hunterNoLicenseAndStayAnswers = { "I forgot it at home", "I don't have a license", "I didn't know I needed a license", "...a license?" };
private static string[] hunterNoLicenseAndFleeAnswers = { "...a license? Not today!", "Bye! I don't need a license!" };
private static string[] hunterNoLicenseAndAttackAnswers = { "I don't have the license, but... I can hunt you!", "Fuck you!", "Fuck the license!", "Fuck you and fuck the license, asshole!" };
private static string[] policeLicenseGood = { "All good, goodbye", "All right, happy hunting" };
private static string[] policeLicenseBad = { "Sir, your license is suspended", "The license is invalid", "The license is suspended" };
private static string[] hunterLicenseSuspended = { "What?", "It can't be..", "Are you sure?" };
private bool licenseHasBeenGiven = false;
private bool isPursuitRunning = false;
private int rndAimAtAnimal = MathHelper.GetRandomInteger(0, 4);
private EScenario scenario;
public override bool OnBeforeCalloutDisplayed()
{
spawnPoint = World.GetNextPositionOnStreet(Game.LocalPlayer.Character.Position.AroundPosition(400f));
if (Vector3.Distance(Game.LocalPlayer.Character.Position, spawnPoint) < 40.0f) return false;
EWorldArea spawnZone = WorldZone.GetArea(spawnPoint);
if (spawnZone == EWorldArea.Los_Santos) return false;
hunterVeh = new Vehicle(hunterVehicleModels.GetRandomElement(true), spawnPoint);
if (!hunterVeh.Exists()) return false;
Vector3 hunterSpawnPos = hunterVeh.Position.AroundPosition(9.5f);
while (Vector3.Distance(hunterSpawnPos, hunterVeh.Position) < 4.0f)
{
hunterSpawnPos = hunterVeh.Position.AroundPosition(9.5f);
GameFiber.Yield();
}
hunter = new Ped(huntersModels.GetRandomElement(true), hunterSpawnPos, 0.0f);
if (!hunter.Exists()) return false;
hunter.Inventory.GiveNewWeapon(hunterWeapons.GetRandomElement(true), 666, true);
Vector3 spawnPos = hunter.Position.AroundPosition(0.2f);
Vector3 spawnPos2 = spawnPos + new Vector3(MathHelper.GetRandomSingle(-0.05f, 0.05f), MathHelper.GetRandomSingle(-0.05f, 0.05f), 0.0f);
Vector3 spawnPos3 = new Vector3(spawnPos2.X, spawnPos2.Y, spawnPos2.GetGroundZ() + 0.1525f); /// Gets the Z position
animal = new Ped(animalsModels.GetRandomElement(true), hunter.Position.AroundPosition(0.5f).ToGroundUsingRaycasting(hunter), 0.0f);
if (!animal.Exists() || animal.Position.Z < 0.5f) return false;
hunter.RelationshipGroup = new RelationshipGroup("HUNTER");
hunter.BlockPermanentEvents = true;
if (animal.Exists()) animal.IsRagdoll = true;
if (hunter.Exists()) hunter.Heading = hunter.GetHeadingTowards(animal);
if (Globals.Random.Next(60) <= 1) hunterVeh.InstallRandomMods();
this.ShowCalloutAreaBlipBeforeAccepting(spawnPoint, 35f);
this.AddMinimumDistanceCheck(20.0f, hunter.Position);
this.CalloutMessage = "Possible illegal hunting";
this.CalloutPosition = spawnPoint;
int rndAudioNum = Globals.Random.Next(0, 8);
if (rndAudioNum == 0) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_GUNFIRE IN_OR_ON_POSITION UNITS_RESPOND_CODE_03", spawnPoint);
else if (rndAudioNum == 1) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_ANIMAL_KILL IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 2) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_ANIMAL_CRUELTY IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 3) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_UNAUTHORIZED_HUNTING IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 4) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_HUNTING_AN_ENDANGERED_SPECIES IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 5) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_HUNTING_WITHOUT_A_PERMIT IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 6) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_KILLING_ANIMALS IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
else if (rndAudioNum == 7) LSPD_First_Response.Mod.API.Functions.PlayScannerAudioUsingPosition("WE_HAVE CRIME_SHOOTING_AT_ANIMALS IN_OR_ON_POSITION UNITS_RESPOND_CODE_02", spawnPoint);
return base.OnBeforeCalloutDisplayed();
}
public override bool OnCalloutAccepted()
{
animal.Kill();
animalBlip = animal.AttachBlip();
animalBlip.Sprite = BlipSprite.Hunting;
animalBlip.Color = Color.GreenYellow;
animalBlip.EnableRoute(Color.Green);
animalBlip.Scale = 1.3f;
if (rndAimAtAnimal == 1) NativeFunction.CallByName<uint>("TASK_AIM_GUN_AT_ENTITY", hunter, animal, -1, true);
state = EIllegalHuntingState.EnRoute;
return base.OnCalloutAccepted();
}
/// <summary>
/// If you don't accept the callout this will be called, we clear anything we spawned here to prevent it staying in the game
/// </summary>
public override void OnCalloutNotAccepted()
{
breakForceEnd = true;
base.OnCalloutNotAccepted();
if (hunter.Exists()) hunter.Delete();
if (hunterVeh.Exists()) hunterVeh.Delete();
if (animal.Exists()) animal.Delete();
}
//This is where it all happens, run all of your callouts logic here
public override void Process()
{
//Game.LogTrivial("[Wilderness Callouts | IllegalHunting] Process()");
if (state == EIllegalHuntingState.EnRoute && Vector3.Distance(Game.LocalPlayer.Character.Position, hunter.Position) < 12.0f)
{
state = EIllegalHuntingState.OnScene;
if (rndAimAtAnimal == 1) NativeFunction.CallByName<uint>("TASK_SHOOT_AT_ENTITY", hunter, animal, 1000, (uint)Rage.FiringPattern.SingleShot);
OnScene();
}
if (!hunter.Exists() || hunter.IsDead || Functions.IsPedArrested(hunter))
{
}
else if (state == EIllegalHuntingState.End && !isPursuitRunning)
{
this.End();
}
base.Process();
}
public override void End()
{
breakForceEnd = true;
if (scenario == EScenario.License && ((hunter.Exists() && (hunter.IsAlive && !Functions.IsPedArrested(hunter) && !Functions.IsPedGettingArrested(hunter))) && (hunterVeh.Exists() && hunterVeh.IsAlive)))
{
GameFiber.StartNew(delegate
{
NativeFunction.CallByName<uint>("TASK_GO_TO_ENTITY", hunter, hunterVeh, -1, 5.0f, 1.0f, 0, 0);
while (Vector3.Distance(hunter.Position, hunterVeh.Position) > 6.0f)
GameFiber.Yield();
hunter.Tasks.Clear();
GameFiber.Sleep(200);
hunter.Tasks.EnterVehicle(hunterVeh, -1).WaitForCompletion(10000);
if (hunter.IsInVehicle(hunterVeh, false)) hunter.Tasks.CruiseWithVehicle(hunterVeh, 20.0f, VehicleDrivingFlags.Normal);
if (hunter.Exists()) hunter.Dismiss();
});
}
else if (hunter.Exists()) hunter.Dismiss();
if (animalBlip.Exists()) animalBlip.Delete();
if (animal.Exists()) animal.Dismiss();
if (hunterVeh.Exists()) hunterVeh.Dismiss();
base.End();
}
protected override void CleanUp()
{
// TODO: implement CleanUp()
}
public void OnScene() // ON SCENE, STARTS DIALOGUE
{
Logger.LogTrivial(this.GetType().Name, "OnScene()");
GameFiber.StartNew(delegate
{
while (true)
{
GameFiber.Yield();
Game.DisplayHelp("Press ~b~" + Controls.PrimaryAction.ToUserFriendlyName() + "~w~ to ask for the hunting license", 10);
if (Controls.PrimaryAction.IsJustPressed())
{
hunter.Tasks.AchieveHeading(hunter.GetHeadingTowards(Game.LocalPlayer.Character));
hunter.LookAtEntity(Game.LocalPlayer.Character, 60000);
Game.LocalPlayer.Character.PlayAmbientSpeech(Globals.Random.Next(2) == 1 ?Globals.Random.Next(2) == 1 ? Speech.KIFFLOM_GREET : Speech.GENERIC_HI : Speech.GENERIC_HOWS_IT_GOING);
Game.DisplaySubtitle("~b~" + Settings.General.Name + ": ~w~" + policeGreetings.GetRandomElement(), 2000);
GameFiber.Wait(2000);
Game.DisplaySubtitle("~b~" + Settings.General.Name + ": ~w~" + policeQuestions.GetRandomElement(), 2500);
GameFiber.Wait(2250);
StartScenario();
break;
}
if (breakForceEnd) break;
}
});
}
public void StartScenario() // STARTS THE SCENARIO
{
Logger.LogTrivial(this.GetType().Name, "StartScenario()");
GameFiber.StartNew(delegate
{
int rndScenario = MathHelper.GetRandomInteger(101);
if (rndScenario <= 7) // Shoot
{
Shoot();
}
else if (rndScenario > 7 && rndScenario < 15) // No license and stay
{
NoLicenseStay();
}
else if (rndScenario >= 15 && rndScenario < 50) // No license and flee
{
NoLicenseFlee();
}
else // License
{
License();
}
});
}
// SCENARIOS
public void Shoot() // SHOOT SCENARIO
{
Logger.LogTrivial(this.GetType().Name, "Shoot()");
scenario = EScenario.Shoot;
GameFiber.StartNew(delegate
{
if (!licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterNoLicenseAndAttackAnswers.GetRandomElement(), 2500);
else if (licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterLicenseSuspended.GetRandomElement(), 2500);
hunter.PlayAmbientSpeech(Globals.Random.Next(2) == 1 ? Globals.Random.Next(2) == 1 ? Speech.GENERIC_FUCK_YOU : Speech.GENERIC_INSULT_HIGH : Speech.GENERIC_INSULT_MED);
Game.SetRelationshipBetweenRelationshipGroups("HUNTER", "COP", Relationship.Hate);
Game.SetRelationshipBetweenRelationshipGroups("HUNTER", "PLAYER", Relationship.Hate);
this.pursuit = LSPD_First_Response.Mod.API.Functions.CreatePursuit();
LSPD_First_Response.Mod.API.Functions.AddPedToPursuit(this.pursuit, this.hunter);
isPursuitRunning = true;
while (true)
{
GameFiber.Yield();
if (breakForceEnd) break;
if (hunter.Exists() && hunter.IsAlive && !hunter.IsInAnyVehicle(false) && !LSPD_First_Response.Mod.API.Functions.IsPedGettingArrested(hunter) && !LSPD_First_Response.Mod.API.Functions.IsPedArrested(hunter))
hunter.AttackPed(Game.LocalPlayer.Character);
state = EIllegalHuntingState.End;
}
});
}
public void NoLicenseStay() // NO LICENSE AND STAY SCENARIO
{
Logger.LogTrivial(this.GetType().Name, "NoLicenseStay()");
scenario = EScenario.NoLicenseStay;
hunter.PlayAmbientSpeech(Globals.Random.Next(2) == 1 ? Speech.GENERIC_CURSE_HIGH : Speech.GENERIC_CURSE_MED);
GameFiber.StartNew(delegate
{
if (!licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterNoLicenseAndStayAnswers.GetRandomElement(), 2500);
else if (licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterLicenseSuspended.GetRandomElement(), 2500);
isPursuitRunning = false;
Game.DisplayHelp("Press " + Controls.ForceCalloutEnd.ToUserFriendlyName() + " to finish the callout");
});
}
public void NoLicenseFlee() // NO LICENSE AND FLEE SCENARIO
{
Logger.LogTrivial(this.GetType().Name, "NoLicenseFlee()");
scenario = EScenario.NoLicenseFlee;
GameFiber.StartNew(delegate
{
Game.SetRelationshipBetweenRelationshipGroups("HUNTER", "COP", Relationship.Dislike);
Game.SetRelationshipBetweenRelationshipGroups("HUNTER", "PLAYER", Relationship.Dislike);
if (!licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterNoLicenseAndFleeAnswers.GetRandomElement(), 2500);
else if (licenseHasBeenGiven) Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterLicenseSuspended.GetRandomElement(), 2500);
hunter.PlayAmbientSpeech(Globals.Random.Next(2) == 1 ? Globals.Random.Next(2) == 1 ? Globals.Random.Next(2) == 1 ? Globals.Random.Next(2) == 1 ? Speech.GENERIC_CURSE_HIGH : Speech.GENERIC_CURSE_MED : Speech.GENERIC_FUCK_YOU : Speech.GENERIC_INSULT_HIGH : Speech.GENERIC_INSULT_MED);
hunter.EnterVehicle(hunterVeh, 8000, EVehicleSeats.Driver, 2.0f, 1);
while (true)
{
GameFiber.Yield();
if (breakForceEnd || !hunter.Exists() ||hunter.IsInAnyVehicle(false)|| hunter.IsDead || Functions.IsPedArrested(hunter)) break;
}
VehicleDrivingFlags driveFlags = VehicleDrivingFlags.None;
switch (Globals.Random.Next(3))
{
case 0:
driveFlags = (VehicleDrivingFlags)20;
break;
case 1:
driveFlags = (VehicleDrivingFlags)786468;
break;
case 2:
if (!hunterVeh.Model.IsBike || !hunterVeh.Model.IsBicycle) driveFlags = (VehicleDrivingFlags)1076;
else driveFlags = (VehicleDrivingFlags)786468;
break;
default:
break;
}
if (hunter.Exists())
{
if (hunter.IsInAnyVehicle(false) && hunter.IsAlive) hunter.Tasks.CruiseWithVehicle(hunterVeh, 200.0f, driveFlags);
this.pursuit = LSPD_First_Response.Mod.API.Functions.CreatePursuit();
LSPD_First_Response.Mod.API.Functions.AddPedToPursuit(this.pursuit, this.hunter);
isPursuitRunning = true;
}
state = EIllegalHuntingState.End;
});
}
public void License() // LICENSE SCENARIO
{
Logger.LogTrivial(this.GetType().Name, "License()");
scenario = EScenario.License;
GameFiber.StartNew(delegate
{
Game.DisplaySubtitle("~b~Hunter: ~w~" + hunterLicenseAnswers.GetRandomElement(), 2500);
hunter.Tasks.PlayAnimation("mp_WildernessCallouts.Common", "givetake1_a", 2.5f, AnimationFlags.None);
isPursuitRunning = false;
WildernessCallouts.Common.HuntingLicense(hunter);
while (true)
{
GameFiber.Yield();
if (breakForceEnd) break;
Game.DisplayHelp("Press ~b~" + Controls.PrimaryAction.ToUserFriendlyName() + "~w~ to let the hunter leave~n~Press ~r~" + Controls.SecondaryAction.ToUserFriendlyName() + "~w~ if the license is invalid");
if (Controls.PrimaryAction.IsJustPressed())
{
Game.DisplaySubtitle("~b~" + Settings.General.Name + ": ~w~" + policeLicenseGood.GetRandomElement(), 2500);
state = EIllegalHuntingState.End;
hunter.PlayAmbientSpeech(Globals.Random.Next(2) == 1 ? Speech.GENERIC_THANKS : Speech.GENERIC_BYE);
break;
}
else if (Controls.SecondaryAction.IsJustPressed())
{
Game.DisplaySubtitle("~b~" + Settings.General.Name + ": ~w~" + policeLicenseBad.GetRandomElement(), 2500);
licenseHasBeenGiven = true;
GameFiber.Wait(2250);
int rndState = Globals.Random.Next(101);
if (rndState <= 8) Shoot();
else if (rndState >= 30 && rndState < 55) NoLicenseFlee();
else NoLicenseStay();
break;
}
}
});
}
public enum EScenario
{
Shoot,
NoLicenseStay,
NoLicenseFlee,
License,
}
// ENUM
public enum EIllegalHuntingState
{
EnRoute,
OnScene,
Scenario,
End,
}
}
}
| 47.525386 | 298 | 0.585257 | [
"MIT"
] | EvolutionaryCode/Wilderness-Callouts | src/Callouts/IllegalHunting.cs | 21,531 | C# |
namespace Gu.Units.Benchmarks
{
using System.Globalization;
using BenchmarkDotNet.Attributes;
[MemoryDiagnoser]
public class Parse
{
[Benchmark(Baseline = true)]
public double DoubleParse()
{
return double.Parse("1.2", CultureInfo.InvariantCulture);
}
[Benchmark]
public Length LengthParse()
{
return Length.Parse("1.2 m", CultureInfo.InvariantCulture);
}
}
}
| 20.695652 | 71 | 0.588235 | [
"MIT"
] | GuOrg/Gu.Units | Gu.Units.Benchmarks/Benchmarks/Parse.cs | 478 | C# |
namespace MassTransit.Pipeline.Pipes
{
using System;
using System.Threading.Tasks;
using Context.Converters;
using GreenPipes;
public class ConsumeObserverAdapter :
IFilterObserver
{
readonly IConsumeObserver _observer;
public ConsumeObserverAdapter(IConsumeObserver observer)
{
_observer = observer;
}
Task IFilterObserver.PreSend<T>(T context)
{
return ConsumeObserverConverterCache.PreConsume(typeof(T), _observer, context);
}
Task IFilterObserver.PostSend<T>(T context)
{
return ConsumeObserverConverterCache.PostConsume(typeof(T), _observer, context);
}
Task IFilterObserver.SendFault<T>(T context, Exception exception)
{
return ConsumeObserverConverterCache.ConsumeFault(typeof(T), _observer, context, exception);
}
}
public class ConsumeObserverAdapter<T> :
IFilterObserver<ConsumeContext<T>>
where T : class
{
readonly IConsumeMessageObserver<T> _observer;
public ConsumeObserverAdapter(IConsumeMessageObserver<T> observer)
{
_observer = observer;
}
Task IFilterObserver<ConsumeContext<T>>.PreSend(ConsumeContext<T> context)
{
return _observer.PreConsume(context);
}
Task IFilterObserver<ConsumeContext<T>>.PostSend(ConsumeContext<T> context)
{
return _observer.PostConsume(context);
}
Task IFilterObserver<ConsumeContext<T>>.SendFault(ConsumeContext<T> context, Exception exception)
{
return _observer.ConsumeFault(context, exception);
}
}
}
| 27.47619 | 105 | 0.64067 | [
"ECL-2.0",
"Apache-2.0"
] | MathiasZander/ServiceFabricPerfomanceTest | src/MassTransit/Pipeline/Pipes/ConsumeObserverAdapter.cs | 1,731 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Common;
using Microsoft.Azure.Devices.Common.Service.Auth;
using Newtonsoft.Json;
namespace Microsoft.Azure.Devices.Provisioning.Service
{
internal static class EnrollmentGroupManager
{
private const string ServiceName = "enrollmentGroups";
private const string EnrollmentIdUriFormat = "{0}/{1}?{2}";
private const string EnrollmentAttestationName = "attestationmechanism";
private const string EnrollmentAttestationUriFormat = "{0}/{1}/{2}?{3}";
internal static async Task<EnrollmentGroup> CreateOrUpdateAsync(
IContractApiHttp contractApiHttp,
EnrollmentGroup enrollmentGroup,
CancellationToken cancellationToken)
{
if (enrollmentGroup == null)
{
throw new ArgumentNullException(nameof(enrollmentGroup));
}
ContractApiResponse contractApiResponse = await contractApiHttp
.RequestAsync(
HttpMethod.Put,
GetEnrollmentUri(enrollmentGroup.EnrollmentGroupId),
null,
JsonConvert.SerializeObject(enrollmentGroup),
enrollmentGroup.ETag,
cancellationToken)
.ConfigureAwait(false);
if (contractApiResponse.Body == null)
{
throw new ProvisioningServiceClientHttpException(contractApiResponse, true);
}
return JsonConvert.DeserializeObject<EnrollmentGroup>(contractApiResponse.Body);
}
internal static async Task<EnrollmentGroup> GetAsync(
IContractApiHttp contractApiHttp,
string enrollmentGroupId,
CancellationToken cancellationToken)
{
ContractApiResponse contractApiResponse = await contractApiHttp
.RequestAsync(
HttpMethod.Get,
GetEnrollmentUri(enrollmentGroupId),
null,
null,
null,
cancellationToken)
.ConfigureAwait(false);
if (contractApiResponse.Body == null)
{
throw new ProvisioningServiceClientHttpException(contractApiResponse, true);
}
return JsonConvert.DeserializeObject<EnrollmentGroup>(contractApiResponse.Body);
}
internal static async Task DeleteAsync(
IContractApiHttp contractApiHttp,
EnrollmentGroup enrollmentGroup,
CancellationToken cancellationToken)
{
if (enrollmentGroup == null)
{
throw new ArgumentNullException(nameof(enrollmentGroup));
}
await contractApiHttp
.RequestAsync(
HttpMethod.Delete,
GetEnrollmentUri(enrollmentGroup.EnrollmentGroupId),
null,
null,
enrollmentGroup.ETag,
cancellationToken)
.ConfigureAwait(false);
}
internal static async Task DeleteAsync(
IContractApiHttp contractApiHttp,
string enrollmentGroupId,
CancellationToken cancellationToken,
string eTag = null)
{
await contractApiHttp
.RequestAsync(
HttpMethod.Delete,
GetEnrollmentUri(enrollmentGroupId),
null,
null,
eTag,
cancellationToken)
.ConfigureAwait(false);
}
internal static Query CreateQuery(
ServiceConnectionString provisioningConnectionString,
QuerySpecification querySpecification,
HttpTransportSettings httpTransportSettings,
CancellationToken cancellationToken,
int pageSize = 0)
{
if (querySpecification == null)
{
throw new ArgumentNullException(nameof(querySpecification));
}
if (pageSize < 0)
{
throw new ArgumentException($"{nameof(pageSize)} cannot be negative");
}
return new Query(provisioningConnectionString, ServiceName, querySpecification, httpTransportSettings, pageSize, cancellationToken);
}
private static Uri GetEnrollmentUri(string enrollmentGroupId)
{
enrollmentGroupId = WebUtility.UrlEncode(enrollmentGroupId);
return new Uri(EnrollmentIdUriFormat.FormatInvariant(ServiceName, enrollmentGroupId, SdkUtils.ApiVersionQueryString), UriKind.Relative);
}
internal static async Task<AttestationMechanism> GetEnrollmentAttestationAsync(
IContractApiHttp contractApiHttp,
string enrollmentGroupId,
CancellationToken cancellationToken)
{
ContractApiResponse contractApiResponse = await contractApiHttp
.RequestAsync(
HttpMethod.Post,
GetEnrollmentAttestationUri(enrollmentGroupId),
null,
null,
null,
cancellationToken)
.ConfigureAwait(false);
if (contractApiResponse.Body == null)
{
throw new ProvisioningServiceClientHttpException(contractApiResponse, true);
}
return JsonConvert.DeserializeObject<AttestationMechanism>(contractApiResponse.Body);
}
private static Uri GetEnrollmentAttestationUri(string enrollmentGroupId)
{
enrollmentGroupId = WebUtility.UrlEncode(enrollmentGroupId);
return new Uri(
EnrollmentAttestationUriFormat.FormatInvariant(ServiceName, enrollmentGroupId, EnrollmentAttestationName, SdkUtils.ApiVersionQueryString),
UriKind.Relative);
}
}
}
| 37.284024 | 154 | 0.60054 | [
"MIT"
] | brycewang-microsoft/azure-iot-sdk-csharp | provisioning/service/src/Manager/EnrollmentGroupManager.cs | 6,303 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class SausagMan : MonoBehaviour
{
public List<AudioClip> clips;
public bool hasCarrot, hasSausage, hasLemon = false;
// Start is called before the first frame update
void Start()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (!other.GetComponent<PlayerMovement>())
{
return;
}
var pm = FindObjectOfType<PlayerMovement>();
var ca = pm.GetCurrentActive();
var ec = pm.eater;
if (ca.name == "Sidrun" && !hasLemon)
{
hasLemon = true;
ec.MorphBack(other.gameObject);
// Destroy(other.gameObject);
}
else if (ca.name == "Vorst" && !hasSausage)
{
hasSausage = true;
ec.MorphBack(other.gameObject);
// Destroy(other.gameObject);
}
else if (ca.name == "Porg" && !hasCarrot)
{
hasCarrot = true;
ec.MorphBack(other.gameObject);
// Destroy(other.gameObject);
}
var findObjectOfType = FindObjectOfType<AudioSource>();
if (pm.characters.Count == 1)
{
findObjectOfType.clip = clips[1];
findObjectOfType.Play ();
}
if (hasCarrot && hasLemon && hasSausage)
{
GetComponentInChildren<TextMeshProUGUI>().text = "Thank you for bringing me back my food :) And thank you for playing";
findObjectOfType.clip = clips[2];
findObjectOfType.Play ();
}
}
// Update is called once per frame
void Update()
{
}
}
| 24.633803 | 131 | 0.547742 | [
"MIT"
] | SiiMeR/WorldEater | Assets/SausagMan.cs | 1,749 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Shooty.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var mvcviews = services.AddControllersWithViews();
#if (DEBUG)
mvcviews.AddRazorRuntimeCompilation();
#endif
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 29.967742 | 143 | 0.61141 | [
"MIT"
] | kasuken/Shooty | src/Shooty/Shooty.Web/Startup.cs | 1,858 | 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 sesv2-2019-09-27.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.SimpleEmailV2.Model
{
/// <summary>
/// Container for the parameters to the DeleteConfigurationSetEventDestination operation.
/// Delete an event destination.
///
///
/// <para>
/// <i>Events</i> include message sends, deliveries, opens, clicks, bounces, and complaints.
/// <i>Event destinations</i> are places that you can send information about these events
/// to. For example, you can send event data to Amazon SNS to receive notifications when
/// you receive bounces or complaints, or you can use Amazon Kinesis Data Firehose to
/// stream data to Amazon S3 for long-term storage.
/// </para>
/// </summary>
public partial class DeleteConfigurationSetEventDestinationRequest : AmazonSimpleEmailServiceV2Request
{
private string _configurationSetName;
private string _eventDestinationName;
/// <summary>
/// Gets and sets the property ConfigurationSetName.
/// <para>
/// The name of the configuration set that contains the event destination that you want
/// to delete.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ConfigurationSetName
{
get { return this._configurationSetName; }
set { this._configurationSetName = value; }
}
// Check to see if ConfigurationSetName property is set
internal bool IsSetConfigurationSetName()
{
return this._configurationSetName != null;
}
/// <summary>
/// Gets and sets the property EventDestinationName.
/// <para>
/// The name of the event destination that you want to delete.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string EventDestinationName
{
get { return this._eventDestinationName; }
set { this._eventDestinationName = value; }
}
// Check to see if EventDestinationName property is set
internal bool IsSetEventDestinationName()
{
return this._eventDestinationName != null;
}
}
} | 35.438202 | 107 | 0.638871 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/DeleteConfigurationSetEventDestinationRequest.cs | 3,154 | C# |
namespace StreamMarkers
{
public class ConstantsBase
{
public static readonly string CLIENT_ID = "";
public static readonly string CLIENT_SECRET = "";
}
public partial class Constants : ConstantsBase
{
}
} | 20.583333 | 57 | 0.647773 | [
"MIT"
] | aplulu/StreamMarkers | Constants.cs | 249 | C# |
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Skia;
using SimpleDraw.Avalonia;
using SimpleDraw.Skia;
using SimpleDraw.ViewModels.Containers;
using SimpleDraw.ViewModels.Tools;
using SkiaSharp;
namespace SimpleDraw.Controls
{
public class SimpleCanvas : Canvas
{
public static ISimpleDrawApplication App { get; set; }
public static readonly StyledProperty<IInputElement> InputSourceProperty =
AvaloniaProperty.Register<SimpleCanvas, IInputElement>(nameof(InputSource));
public static readonly StyledProperty<bool> CustomDrawProperty =
AvaloniaProperty.Register<SimpleCanvas, bool>(nameof(CustomDraw));
public IInputElement InputSource
{
get => GetValue(InputSourceProperty);
set => SetValue(InputSourceProperty, value);
}
public bool CustomDraw
{
get => GetValue(CustomDrawProperty);
set => SetValue(CustomDrawProperty, value);
}
private ToolPointerType ToToolPointerType(PointerUpdateKind pointerUpdateKind)
{
switch (pointerUpdateKind)
{
case PointerUpdateKind.LeftButtonPressed:
case PointerUpdateKind.LeftButtonReleased:
return ToolPointerType.Left;
case PointerUpdateKind.RightButtonPressed:
case PointerUpdateKind.RightButtonReleased:
return ToolPointerType.Right;
default:
return ToolPointerType.None;
}
}
private ToolKeyModifiers ToToolKeyModifiers(KeyModifiers keyModifiers)
{
var result = ToolKeyModifiers.None;
if (keyModifiers.HasFlag(KeyModifiers.Alt))
{
result |= ToolKeyModifiers.Alt;
}
if (keyModifiers.HasFlag(KeyModifiers.Control))
{
result |= ToolKeyModifiers.Control;
}
if (keyModifiers.HasFlag(KeyModifiers.Shift))
{
result |= ToolKeyModifiers.Shift;
}
if (keyModifiers.HasFlag(KeyModifiers.Meta))
{
result |= ToolKeyModifiers.Meta;
}
return result;
}
public SimpleCanvas()
{
Focusable = true;
Focus();
}
private void Canvas_Invalidate(object sender, EventArgs e)
{
InvalidateVisual();
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
var inputSource = InputSource ?? this;
if (inputSource != null)
{
inputSource.PointerPressed += InputSource_PointerPressed;
inputSource.PointerReleased += InputSource_PointerReleased;
inputSource.PointerMoved += InputSource_PointerMoved;
inputSource.KeyDown += InputSource_KeyDown;
}
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
canvas.InvalidateCanvas += Canvas_Invalidate;
}
protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTree(e);
var inputSource = InputSource ?? this;
if (inputSource != null)
{
inputSource.PointerPressed -= InputSource_PointerPressed;
inputSource.PointerReleased -= InputSource_PointerReleased;
inputSource.PointerMoved -= InputSource_PointerMoved;
inputSource.KeyDown -= InputSource_KeyDown;
}
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
canvas.InvalidateCanvas -= Canvas_Invalidate;
}
private void InputSource_PointerPressed(object sender, PointerPressedEventArgs e)
{
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
var point = e.GetCurrentPoint(this);
var type = point.Properties.PointerUpdateKind;
var pointerType = ToToolPointerType(type);
var keyModifiers = ToToolKeyModifiers(e.KeyModifiers);
canvas.Tool?.Pressed(canvas, point.Position.X, point.Position.Y, pointerType, keyModifiers);
}
private void InputSource_PointerReleased(object sender, PointerReleasedEventArgs e)
{
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
var point = e.GetCurrentPoint(this);
var type = point.Properties.PointerUpdateKind;
var pointerType = ToToolPointerType(type);
var keyModifiers = ToToolKeyModifiers(e.KeyModifiers);
canvas.Tool?.Released(canvas, point.Position.X, point.Position.Y, pointerType, keyModifiers);
}
private void InputSource_PointerMoved(object sender, PointerEventArgs e)
{
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
var point = e.GetCurrentPoint(this);
var type = point.Properties.PointerUpdateKind;
var pointerType = ToToolPointerType(type);
var keyModifiers = ToToolKeyModifiers(e.KeyModifiers);
canvas.Tool?.Moved(canvas, point.Position.X, point.Position.Y, pointerType, keyModifiers);
}
private async void InputSource_KeyDown(object sender, KeyEventArgs e)
{
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
switch (e.Key)
{
case Key.A:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.SelectAll();
}
}
break;
case Key.C:
{
if (e.KeyModifiers == KeyModifiers.None)
{
if (canvas.Tool is PathToolViewModel pathTool && pathTool.Mode != PathToolMode.CubicBezier)
{
pathTool.PreviousMode = pathTool.Mode;
pathTool.Mode = PathToolMode.CubicBezier;
}
else
{
canvas.SetTool("CubicBezier");
}
}
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.Copy();
}
}
break;
case Key.E:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.SetTool("Ellipse");
}
if (e.KeyModifiers == KeyModifiers.Control)
{
await Export(canvas);
}
}
break;
case Key.G:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.Group();
}
}
break;
case Key.H:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.SetTool("Path");
}
}
break;
case Key.L:
{
if (e.KeyModifiers == KeyModifiers.None)
{
if (canvas.Tool is PathToolViewModel pathTool && pathTool.Mode != PathToolMode.Line)
{
pathTool.PreviousMode = pathTool.Mode;
pathTool.Mode = PathToolMode.Line;
}
else
{
canvas.SetTool("Line");
}
}
}
break;
case Key.M:
{
if (e.KeyModifiers == KeyModifiers.None)
{
if (canvas.Tool is PathToolViewModel pathTool)
{
pathTool.PreviousMode = pathTool.Mode;
pathTool.Mode = PathToolMode.Move;
}
}
}
break;
case Key.N:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.SetTool("None");
}
if (e.KeyModifiers == KeyModifiers.Control)
{
New();
}
}
break;
case Key.O:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
await Open();
}
}
break;
case Key.Q:
{
if (e.KeyModifiers == KeyModifiers.None)
{
if (canvas.Tool is PathToolViewModel pathTool && pathTool.Mode != PathToolMode.QuadraticBezier)
{
pathTool.PreviousMode = pathTool.Mode;
pathTool.Mode = PathToolMode.QuadraticBezier;
}
else
{
canvas.SetTool("QuadraticBezier");
}
}
}
break;
case Key.R:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.SetTool("Rectangle");
}
}
break;
case Key.S:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.SetTool("Selection");
}
if (e.KeyModifiers == KeyModifiers.Control)
{
await Save(canvas);
}
}
break;
case Key.U:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.Ungroup();
}
}
break;
case Key.V:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.Paste();
}
}
break;
case Key.X:
{
if (e.KeyModifiers == KeyModifiers.Control)
{
canvas.Cut();
}
}
break;
case Key.Delete:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.Delete();
}
}
break;
case Key.Escape:
{
if (e.KeyModifiers == KeyModifiers.None)
{
canvas.Selected.Clear();
}
}
break;
}
}
private void Load(Window window, CanvasViewModel canvasOpen)
{
if (window.DataContext is CanvasViewModel canvasOld)
{
canvasOld.InvalidateCanvas -= Canvas_Invalidate;
}
window.DataContext = canvasOpen;
canvasOpen.InvalidateCanvas += Canvas_Invalidate;
canvasOpen.Invalidate();
}
public void New()
{
var window = this.VisualRoot as Window;
var canvasNew = App.New();
Load(window, canvasNew);
}
public async Task Open()
{
var dlg = new OpenFileDialog() { Title = "Open" };
dlg.Filters.Add(new FileDialogFilter() { Name = "Json", Extensions = { "json" } });
dlg.Filters.Add(new FileDialogFilter() { Name = "All", Extensions = { "*" } });
var window = this.VisualRoot as Window;
var result = await dlg.ShowAsync(window);
if (result != null)
{
var path = result.FirstOrDefault();
if (path != null)
{
var canvasOpen = App.Open(path);
if (canvasOpen != null)
{
Load(window, canvasOpen);
}
}
}
}
public async Task Save(CanvasViewModel canvas)
{
var dlg = new SaveFileDialog() { Title = "Save" };
dlg.Filters.Add(new FileDialogFilter() { Name = "Json", Extensions = { "json" } });
dlg.Filters.Add(new FileDialogFilter() { Name = "All", Extensions = { "*" } });
dlg.InitialFileName = "canvas";
dlg.DefaultExtension = "json";
var window = this.VisualRoot as Window;
var path = await dlg.ShowAsync(window);
if (path != null)
{
App.Save(path, canvas);
}
}
public async Task Export(CanvasViewModel canvas)
{
var dlg = new SaveFileDialog() { Title = "Save" };
dlg.Filters.Add(new FileDialogFilter() { Name = "Skp", Extensions = { "skp" } });
dlg.Filters.Add(new FileDialogFilter() { Name = "All", Extensions = { "*" } });
dlg.InitialFileName = "canvas";
dlg.DefaultExtension = "skp";
var window = this.VisualRoot as Window;
var path = await dlg.ShowAsync(window);
if (path != null)
{
using var skPictureRecorder = new SKPictureRecorder();
var cullRect = SKRect.Create((float)this.Bounds.X, (float)this.Bounds.Y, (float)this.Bounds.Width, (float)this.Bounds.Height);
using var skCanvas = skPictureRecorder.BeginRecording(cullRect);
SkiaRenderer.Render(skCanvas, canvas);
using var skPicture = skPictureRecorder.EndRecording();
using var stream = File.Create(path);
skPicture.Serialize(stream);
}
}
public void Exit()
{
var window = this.VisualRoot as Window;
window.Close();
}
public override void Render(DrawingContext context)
{
base.Render(context);
if (!(DataContext is CanvasViewModel canvas))
{
return;
}
if (CustomDraw)
{
if (InputSource != null)
{
var translated = this.TranslatePoint(new Point(0, 0), InputSource);
var position = new Point(-translated.Value.X, -translated.Value.Y);
var bounds = new Rect(position, InputSource.Bounds.Size);
context.Custom(new SkiaCustomDraw(canvas, bounds));
}
else
{
var bounds = new Rect(new Point(0, 0), this.Bounds.Size);
context.Custom(new SkiaCustomDraw(canvas, bounds));
}
}
else
{
AvaloniaRenderer.Render(context, canvas);
}
}
private class SkiaCustomDraw : ICustomDrawOperation
{
private readonly Rect _bounds;
private readonly CanvasViewModel _canvas;
public SkiaCustomDraw(CanvasViewModel canvas, Rect bounds)
{
_canvas = canvas;
_bounds = bounds;
}
public Rect Bounds => _bounds;
public void Dispose()
{
}
public bool Equals(ICustomDrawOperation other) => false;
public bool HitTest(Point p) => false;
public void Render(IDrawingContextImpl context)
{
var skCanvas = (context as ISkiaDrawingContextImpl)?.SkCanvas;
if (skCanvas == null)
{
return;
}
SkiaRenderer.Render(skCanvas, _canvas);
}
}
}
}
| 34.266284 | 142 | 0.439481 | [
"MIT"
] | wieslawsoltes/SimpleDraw | SimpleDraw/Controls/SimpleCanvas.cs | 17,889 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LAB_05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Medicine> Medicine_list = new List<Medicine>();
private void Add_Medicine_Onclick(object sender, EventArgs e)
{
Medicine new_medicine = new Medicine(textBox_type.Text, textBox_Name.Text, textBox_companyName.Text, Convert.ToInt32(textBox_amount.Text), Convert.ToInt32(textBox_Price.Text), textBox_expireDate.Text);
Medicine_list.Add(new_medicine);
comboBox_Name_sell.Items.Add(new_medicine.Name);
comboBox_Name_show.Items.Add(new_medicine.Name);
MessageBox.Show("You have added " + new_medicine.amount + " amount of" + new_medicine.Name + " medicine successfully.");
}
private void show_avaibality_onclick(object sender, EventArgs e)
{
foreach (Medicine new_med in Medicine_list)
{
if (comboBox_Name_show.Text== new_med.Name) {
Available_amount.Text = "Available Amount :" + new_med.amount.ToString();
Price.Text = "Price : " + new_med.price.ToString();
Expire_Date.Text ="Expire date : "+new_med.expire_date.ToString();
}
}
}
Account current_Balance = new Account();
private void sell_Onclick(object sender, EventArgs e)
{
foreach(Medicine sell_med in Medicine_list)
{
if(comboBox_Name_sell.Text== sell_med.Name)
{
if (sell_med.amount >= Convert.ToInt32(textBox_amount_sell.Text))
{
sell_med.amount -= Convert.ToInt32(textBox_amount_sell.Text);
MessageBox.Show("You have sold " + textBox_amount_sell.Text + " " + comboBox_Name_sell.Text + " successfully.");
current_Balance.initial_Balance = current_Balance.initial_Balance+ (sell_med.amount*sell_med.price);
}
else MessageBox.Show(" We have only " + sell_med.amount.ToString() + " " + comboBox_Name_sell.Text);
}
}
}
private void showBalance_onclick(object sender, EventArgs e)
{
MessageBox.Show("Your current Balance is " + current_Balance.initial_Balance + " tk.");
}
}
}
| 39.376812 | 214 | 0.587045 | [
"MIT"
] | kawsarahamad/SWE4202 | LAB-05/LAB-05/Form1.cs | 2,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CollectionsNamespace {
public class QueueExample {
static void Main(string[] args) {
// CONSTRUCTORS
Queue<char> charQ = new Queue<char>();
Queue<double> doubleQ = new Queue<double>(Enumerable.Range(start: 0, count: 5).Select(x => (double)x));
Queue<string> stringQ = new Queue<string>(20);
// PROPERTIES
foreach (char ch in "words") { charQ.Enqueue(ch); }
Console.WriteLine("charQ Count = {0}", charQ.Count);
// METHODS
charQ.Clear();
Console.WriteLine("charQ Count after Clear = {0}", charQ.Count);
stringQ.Enqueue(item: "My");
stringQ.Enqueue(item: "Chemical");
stringQ.Enqueue(item: "Romance");
stringQ.Enqueue(item: "Sleeping");
stringQ.Enqueue(item: "With");
stringQ.Enqueue(item: "Sirens");
Console.WriteLine("stringQ Contains 'Sirens'? {0}", stringQ.Contains(item: "Sirens")); // true
string[] arr = new string[20];
stringQ.CopyTo(array: arr, arrayIndex: 0); // {"My", "Chemical", "Romance", "Sleeping", "With", "Sirens"}
Console.Write("arr = ");
foreach (string str in arr) { Console.Write(str + ", "); }
Console.WriteLine();
Console.WriteLine("stringQ Dequeue value = {0}", stringQ.Dequeue()); // "My"
Console.WriteLine("stringQ Contains 'Sirens'? {0}", stringQ.Contains(item: "My")); // false
Queue<string> temp = new Queue<string>(new string[]{"My", "Chemical", "Romance", "Sleeping", "With", "Sirens"});
Console.WriteLine("stringQ equals temp ? {0}", stringQ.Equals(obj: temp));
Console.WriteLine("stringQ type = {0}", stringQ.GetType()); // string
Console.WriteLine("stringQ Peek = {0}", stringQ.Peek()); // "Chemical"
arr = stringQ.ToArray();
Console.Write("arr = ");
foreach (string str in arr) { Console.Write(str + ", "); } // {"My", "Chemical", "Romance", "Sleeping", "With"}
Console.WriteLine();
Console.WriteLine("stringQ converted to string = {0}", stringQ.ToString());
stringQ.TrimExcess();
Console.WriteLine("stringQ Count = {0}", stringQ.Count);
string top;
Console.WriteLine(stringQ.TryDequeue(out top)); // true
Console.WriteLine("TryDequeue value = {0}", top); // "Chemical"
Console.WriteLine(stringQ.TryPeek(out top));
Console.WriteLine("TryPeek value = {0}", top); // "Romance"
}
}
} | 42.446154 | 124 | 0.550924 | [
"MIT"
] | Fennec2000GH/Software_Engineering_Interview | src/C# Examples/Collections/QueueExample.cs | 2,761 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace TerraViewer
{
public class FilterGraphTool : IUiController
{
SpreadSheetLayer layer = null;
int domainColumn = -1;
public int DomainColumn
{
get { return domainColumn; }
set { domainColumn = value; }
}
private int targetColumn = 0;
public int TargetColumn
{
get { return targetColumn; }
set { targetColumn = value; }
}
private int denominatorColumn = -1;
public int DenominatorColumn
{
get { return denominatorColumn; }
set { denominatorColumn = value; }
}
ChartTypes chartType = ChartTypes.Histogram;
public ChartTypes ChartType
{
get { return chartType; }
set { chartType = value; }
}
private StatTypes statType = StatTypes.Count;
public StatTypes StatType
{
get { return statType; }
set { statType = value; }
}
public FilterGraphTool(SpreadSheetLayer layer)
{
this.layer = layer;
targetColumn = layer.AltColumn;
}
private DateFilter dateFilter = DateFilter.None;
public DateFilter DateFilter
{
get { return dateFilter; }
set { dateFilter = value; }
}
#region IUiController Members
Texture11 texture = null;
int Width = 500;
int Height = 200;
int Top = 0;
int Left = 0;
ColumnStats stats = new ColumnStats();
public ColumnStats Stats
{
get { return stats; }
set { stats = value; }
}
public void PreRender(RenderEngine renderEngine)
{
}
public void Render(RenderEngine renderEngine)
{
//todo11 reanble this
if (texture == null)
{
Bitmap bmp = null;
bmp = GetChartImageBitmap(renderEngine);
bmp.Dispose();
}
Sprite2d.Draw2D(renderEngine.RenderContext11, texture, new SizeF(texture.Width, texture.Height), new PointF(0, 0), 0, new PointF(Left + texture.Width / 2, Top + texture.Height / 2), Color.White);
if (!String.IsNullOrEmpty(HoverText))
{
Rectangle recttext = new Rectangle((int)(hoverPoint.X + 15), (int)(hoverPoint.Y - 8), 0, 0);
}
return;
}
private Bitmap GetChartImageBitmap(RenderEngine renderEngine)
{
Bitmap bmp = null;
if (chartType == ChartTypes.Histogram)
{
if (!Stats.Computed)
{
Stats = layer.GetSingleColumnHistogram(TargetColumn);
}
bmp = GetBarChartBitmap(Stats);
texture = Texture11.FromBitmap( bmp, 0);
}
else if (chartType == ChartTypes.BarChart)
{
if (!Stats.Computed)
{
Stats = layer.GetDomainValueBarChart(domainColumn, targetColumn, denominatorColumn, statType);
}
bmp = GetBarChartBitmap(Stats);
texture = Texture11.FromBitmap(bmp, 0);
}
else if (chartType == ChartTypes.TimeChart)
{
if (!Stats.Computed)
{
Stats = layer.GetDateHistogram(TargetColumn, DateFilter);
}
bmp = GetBarChartBitmap(Stats);
texture = Texture11.FromBitmap(bmp, 0);
}
Width = bmp.Width;
Height = bmp.Height;
Top = (int)renderEngine.RenderContext11.ViewPort.Height - (Height + 120);
Left = (int)renderEngine.RenderContext11.ViewPort.Width / 2 - (Width / 2);
return bmp;
}
public void ComputeChart()
{
if (chartType == ChartTypes.Histogram)
{
if (!Stats.Computed)
{
Stats = layer.GetSingleColumnHistogram(TargetColumn);
}
}
else if (chartType == ChartTypes.BarChart)
{
if (!Stats.Computed)
{
Stats = layer.GetDomainValueBarChart(domainColumn, targetColumn, denominatorColumn, statType);
}
}
else if (chartType == ChartTypes.TimeChart)
{
if (!Stats.Computed)
{
Stats = layer.GetDateHistogram(TargetColumn, DateFilter);
}
}
}
Point hoverPoint = new Point();
String hoverText = "";
public String HoverText
{
get { return hoverText; }
set { hoverText = value; }
}
void CleanUp()
{
if (texture != null)
{
texture.Dispose();
texture = null;
}
}
public static Bitmap GetHistogramBitmap(ColumnStats stats)
{
Bitmap bmp = new Bitmap(stats.Buckets, 150);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.FromArgb(128, 68, 82, 105));
Pen pen = new Pen(Color.FromArgb(127, 137, 157));
double logMax = Math.Log(stats.HistogramMax);
if (stats.Histogram != null)
{
for (int i = 0; i < stats.Histogram.Length; i++)
{
double height = Math.Log(stats.Histogram[i]) / logMax;
if (height < 0)
{
height = 0;
}
g.DrawLine(Pens.White, new System.Drawing.Point(i, 150), new System.Drawing.Point(i, (int)(150 - (height * 150))));
}
}
pen.Dispose();
g.Flush();
g.Dispose();
return bmp;
}
Rectangle[] barHitTest = null;
int ScrollPosition = 0;
int MaxUnits = 50;
// int TotalUnits = 50;
bool ScrollBarVisible = false;
int sortType = 0; // 0 = A-Z, 1 = Z-A, 2= 0-9, 3 = 9-0
string title = "";
public string Title
{
get { return (stats.DomainColumn > -1 ? layer.Table.Header[stats.DomainColumn] + " : " : "") + layer.Table.Header[stats.TargetColumn] + " " + stats.DomainStatType.ToString() + ((stats.DomainStatType == StatTypes.Ratio) ? (" to " + layer.Table.Header[stats.DemoninatorColumn]) : ""); }
set { title = value; }
}
public Bitmap GetBarChartBitmap(ColumnStats stats)
{
int Chrome = 25;
int height = 150;
int count = Math.Min(MaxUnits, stats.Buckets);
int border = 10;
int colWidth = Math.Min(30, (int)(1000 / count));
int width = count * colWidth;
Width = width + 2 * border;
Bitmap bmp = new Bitmap(Width, height + border * 2 + 20 + Chrome);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.FromArgb(128, 5, 75, 35));
bool anythingSelected = false;
double selectedAmount = 0;
double totalAmount = 0;
if (stats.Selected != null)
{
for (int i = 0; i < stats.Buckets; i++)
{
if (stats.Selected[i])
{
anythingSelected = true;
selectedAmount += stats.Histogram[i];
}
totalAmount += stats.Histogram[i];
}
}
// Draw title
string text = (stats.DomainColumn > -1 ? layer.Table.Header[stats.DomainColumn] + " : " : "" )+ layer.Table.Header[stats.TargetColumn] + " " + stats.DomainStatType.ToString() + ((stats.DomainStatType == StatTypes.Ratio) ? (" to " + layer.Table.Header[stats.DemoninatorColumn]) : "");
title = text;
if (anythingSelected && stats.DomainStatType != StatTypes.Ratio)
{
text += String.Format(" {0:p1} Selected", selectedAmount / totalAmount);
}
g.DrawString(text, UiTools.StandardGargantuan, Brushes.White, new PointF(border, 0));
string sort = "AZ";
switch (sortType)
{
case 0:
sort = "AZ";
break;
case 1:
sort = "ZA";
break;
case 2:
sort = "09";
break;
case 3:
sort = "90";
break;
}
if (chartType == ChartTypes.BarChart)
{
g.DrawString(sort, UiTools.StandardLarge, Brushes.White, new PointF(Width - 25, 0));
}
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
drawFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical;
drawFormat.Alignment = StringAlignment.Near;
drawFormat.LineAlignment = StringAlignment.Center;
SolidBrush brush = new SolidBrush(Color.FromArgb(20, 128, 255));
Brush selectedBrush = Brushes.Yellow;
//Brushes.White;
Pen pen = new Pen(Color.FromArgb(20, 128, 255));
double logMax = Math.Log(stats.HistogramMax);
int end = Math.Min(stats.Buckets, ScrollPosition + MaxUnits);
if (stats.Histogram != null)
{
barHitTest = new Rectangle[stats.Buckets];
for (int i = ScrollPosition; i < end; i++)
{
int pos = i - ScrollPosition;
double val = stats.Histogram[i] / (stats.HistogramMax * 1.05);
if (val < 0)
{
val = 0;
}
barHitTest[i] = new Rectangle((int)(pos * colWidth) + border, border + Chrome, colWidth, (int)(height));
Rectangle rect = new Rectangle((int)(pos * colWidth) + border, (int)(height - (val * height)) + border + Chrome, colWidth, (int)(val * height));
if (stats.Selected[i])
{
g.FillRectangle(selectedBrush,rect);
}
else
{
g.FillRectangle(brush, rect);
}
if (stats.DomainColumn > -1 || (stats.DomainValues != null && stats.DomainValues.Length > pos))
{
g.DrawString(stats.DomainValues[i], UiTools.StandardLarge, Brushes.White, new RectangleF((pos * colWidth) + border, border + Chrome, colWidth, height), drawFormat);
}
}
ScrollBarVisible = false;
if (MaxUnits < stats.Buckets)
{
int ScrollAreaWidth = Width - (2 * border);
// Scroll bars are needed
ScrollBarVisible = true;
int scrollWidth = (int)((double)MaxUnits / (double)stats.Buckets * ScrollAreaWidth) +2;
int scrollStart = (int)((double)ScrollPosition/ (double)stats.Buckets * ScrollAreaWidth);
scrollUnitPixelRatio = (double)ScrollAreaWidth / (double)stats.Buckets;
g.DrawLine(Pens.White, new Point(border, height + 22 + Chrome), new Point(border + ScrollAreaWidth, height + 22 + Chrome));
Rectangle rect = new Rectangle(border + scrollStart, height + 15 + Chrome, scrollWidth, 15);
g.FillRectangle(brush, rect);
}
}
brush.Dispose();
pen.Dispose();
g.Flush();
g.Dispose();
return bmp;
}
bool scrolling = false;
int scrollLastMouseX = 0;
int scrollPositionMouseDown = 0;
double scrollUnitPixelRatio = 1;
bool capture = false;
int lastClick = -1;
public bool MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.X > Left && (e.X - Left) < Width)
{
if (e.Y > Top && (e.Y - Top) < Height)
{
int x = e.X - Left;
int y = e.Y - Top;
int i = 0;
if (e.Button == MouseButtons.Right)
{
ContextMenuStrip contextMenu = new ContextMenuStrip();
ToolStripMenuItem closeMenu = new ToolStripMenuItem(Language.GetLocalizedText(212, "Close"));
ToolStripMenuItem copyMenu = new ToolStripMenuItem(Language.GetLocalizedText(428, "Copy"));
ToolStripMenuItem domainColumn = new ToolStripMenuItem(Language.GetLocalizedText(1271, "Domain Column"));
ToolStripMenuItem sortOrder = new ToolStripMenuItem(Language.GetLocalizedText(1272, "Sort Order"));
ToolStripMenuItem sortOrderAZ = new ToolStripMenuItem(Language.GetLocalizedText(1273, "Alpha Ascending"));
ToolStripMenuItem sortOrderZA = new ToolStripMenuItem(Language.GetLocalizedText(1274, "Alpha Descending"));
ToolStripMenuItem sortOrder09 = new ToolStripMenuItem(Language.GetLocalizedText(1275, "Numeric Increasing"));
ToolStripMenuItem sortOrder90 = new ToolStripMenuItem(Language.GetLocalizedText(1276, "Numeric Decreasing"));
sortOrderAZ.Click += new EventHandler(sortOrderAZ_Click);
sortOrderZA.Click += new EventHandler(sortOrderZA_Click);
sortOrder09.Click += new EventHandler(sortOrder09_Click);
sortOrder90.Click += new EventHandler(sortOrder90_Click);
sortOrder.DropDownItems.Add(sortOrderAZ);
sortOrder.DropDownItems.Add(sortOrderZA);
sortOrder.DropDownItems.Add(sortOrder09);
sortOrder.DropDownItems.Add(sortOrder90);
closeMenu.Click += new EventHandler(closeMenu_Click);
copyMenu.Click += new EventHandler(copyMenu_Click);
domainColumn.DropDownOpening += new EventHandler(domainColumn_DropDownOpening);
contextMenu.Items.Add(closeMenu);
contextMenu.Items.Add(copyMenu);
if (chartType != ChartTypes.Histogram)
{
contextMenu.Items.Add(sortOrder);
contextMenu.Items.Add(domainColumn);
}
contextMenu.Show(Cursor.Position);
}
else
{
if (barHitTest != null)
{
foreach (Rectangle rect in barHitTest)
{
if (rect.Contains(x, y))
{
if ((Control.ModifierKeys & Keys.Control) != Keys.Control)
{
for (int j = 0; j < Stats.Buckets; j++)
{
if (i != j)
{
Stats.Selected[j] = false;
}
}
}
else
{
}
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
{
if (lastClick > -1)
{
int dir = lastClick > i ? -1 : 1;
for (int j = lastClick; j != i; j += dir)
{
Stats.Selected[j] = true;
}
}
else
{
lastClick = i;
}
}
else
{
lastClick = i;
}
Stats.Selected[i] = !Stats.Selected[i];
//layer.filters.Add(stats);
layer.CleanUp();
CleanUp();
break;
}
i++;
}
}
}
if (MaxUnits < Stats.Buckets)
{
int Chrome = 25;
int border = 10;
int height = 150;
int ScrollAreaWidth = Width - (2 * border);
// Scroll bars are needed
ScrollBarVisible = true;
int scrollWidth = (int)((double)MaxUnits / (double)Stats.Buckets * ScrollAreaWidth);
int scrollStart = (int)((double)ScrollPosition / (double)Stats.Buckets * ScrollAreaWidth);
Rectangle rect = new Rectangle(border + scrollStart, height + 15 + Chrome, scrollWidth, 15);
if (rect.Contains(x, y))
{
scrolling = true;
scrollLastMouseX = e.X;
scrollPositionMouseDown = ScrollPosition;
}
}
Rectangle sortRect = new Rectangle(Width - 25, 2, 16, 16);
if (sortRect.Contains(x, y) && chartType == ChartTypes.BarChart)
{
// Clicked on sort
sortType = (sortType + 1) % 4;
Stats.Sort(sortType);
CleanUp();
}
capture = true;
return true;
}
}
return false;
}
void sortOrder90_Click(object sender, EventArgs e)
{
sortType = 3;
Stats.Sort(sortType);
CleanUp();
}
void sortOrder09_Click(object sender, EventArgs e)
{
sortType = 2;
Stats.Sort(sortType);
CleanUp();
}
void sortOrderZA_Click(object sender, EventArgs e)
{
sortType = 1;
Stats.Sort(sortType);
CleanUp();
}
void sortOrderAZ_Click(object sender, EventArgs e)
{
sortType = 0;
Stats.Sort(sortType);
CleanUp();
}
void domainColumn_DropDownOpening(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
int index = 0;
if (item.DropDownItems.Count == 0)
{
foreach (string col in layer.Header)
{
ToolStripMenuItem domainColumn = new ToolStripMenuItem(col);
domainColumn.Click += new EventHandler(domainColumn_Click);
item.DropDownItems.Add(domainColumn);
domainColumn.Checked = Stats.DomainColumn == index;
domainColumn.Tag = index;
index++;
}
}
}
void domainColumn_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
Stats.Computed = false;
domainColumn = (int)item.Tag;
CleanUp();
}
void copyMenu_Click(object sender, EventArgs e)
{
Clipboard.Clear();
Clipboard.SetImage(GetChartImageBitmap(RenderEngine.Engine));
}
void closeMenu_Click(object sender, EventArgs e)
{
CleanUp();
Earth3d.MainWindow.UiController = null;
layer.Filters.Remove(this);
layer.CleanUp();
((SpreadSheetLayerUI)layer.GetPrimaryUI()).UpdateNodes();
}
public bool MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (capture)
{
capture = false;
scrolling = false;
return true;
}
return false;
}
public bool MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (capture)
{
if (scrolling)
{
ScrollPosition = Math.Min(Stats.Buckets-MaxUnits,Math.Max(0,(int)(scrollPositionMouseDown + (e.X - scrollLastMouseX) / scrollUnitPixelRatio)));
CleanUp();
}
return true;
}
return false;
}
public bool MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.X > Left && (e.X - Left) < Width)
{
if (e.Y > Top && (e.Y - Top) < Height)
{
return true;
}
}
return false;
}
public bool Click(object sender, EventArgs e)
{
return false;
}
public bool MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.X > Left && (e.X - Left) < Width)
{
if (e.Y > Top && (e.Y - Top) < Height)
{
return true;
}
}
return false;
}
public bool KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
return false;
}
public bool KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
return false;
}
public bool Hover(System.Drawing.Point pnt)
{
if (pnt.X > Left && (pnt.X - Left) < Width)
{
if (pnt.Y > Top && (pnt.Y - Top) < Height)
{
int x = pnt.X - Left;
int y = pnt.Y - Top;
int i = 0;
HoverText = null;
if (barHitTest != null)
{
foreach (Rectangle rect in barHitTest)
{
if (rect.Contains(x, y))
{
hoverPoint = new Point(x, y);
double bucketSize = ((Stats.Max - Stats.Min) / Stats.Buckets);
double start = Stats.Min + bucketSize * i;
double end = start + bucketSize;
if (chartType == ChartTypes.Histogram)
{
HoverText = String.Format("{0}-{1} : Count : {2}", start, end, Stats.Histogram[i]);
}
else
{
if (Stats.DomainStatType == StatTypes.Ratio)
{
HoverText = String.Format("{0:p1}", Stats.Histogram[i]);
}
else
{
HoverText = String.Format("{2}", start, end, Stats.Histogram[i]);
}
}
break;
}
i++;
}
}
return true;
}
}
HoverText = "";
return false;
}
#endregion
}
public class DxUiElement
{
public Rectangle Rect;
}
public enum StatTypes { Count, Average, Median, Sum, Min, Max, Ratio };
public enum ChartTypes { Histogram, BarChart, LineChart, Scatter, TimeChart };
}
| 34.58728 | 296 | 0.43748 | [
"MIT"
] | Carifio24/wwt-windows-client | WWTExplorer3d/FilterGraphTool.cs | 25,562 | C# |
using System;
using System.Collections.Generic;
namespace DotNext.Reflection
{
/// <summary>
/// Indicates that requested constructor doesn't exist.
/// </summary>
public sealed class MissingConstructorException : ConstraintViolationException
{
/// <summary>
/// Initializes a new exception indicating that requested constructor doesn't exist.
/// </summary>
/// <param name="target">The inspected type.</param>
/// <param name="parameters">An array of types representing constructor parameters.</param>
public MissingConstructorException(Type target, params Type[] parameters)
: base(target, ExceptionMessages.MissingCtor(target, parameters))
{
Parameters = parameters;
}
/// <summary>
/// An array of types representing constructor parameters.
/// </summary>
public IReadOnlyList<Type> Parameters { get; }
internal static MissingConstructorException Create<TSignature>()
where TSignature : Delegate
{
var invokeMethod = DelegateType.GetInvokeMethod<TSignature>();
return new MissingConstructorException(invokeMethod.ReturnType, invokeMethod.GetParameterTypes());
}
internal static MissingConstructorException Create<T, TArgs>()
where TArgs : struct
=> new MissingConstructorException(typeof(T), Signature.Reflect(typeof(TArgs)).Parameters);
}
}
| 38.153846 | 110 | 0.659946 | [
"MIT"
] | human33/dotNext | src/DotNext.Reflection/Reflection/MissingConstructorException.cs | 1,490 | C# |
using System;
namespace GitVersion
{
[Serializable]
public class WarningException : Exception
{
public WarningException(string message)
: base(message)
{
}
}
}
| 15.214286 | 47 | 0.58216 | [
"MIT"
] | AlexGoris-KasparSolutions/GitVersion | src/GitVersionCore/Model/Exceptions/WarningException.cs | 213 | C# |
using Azure.Storage.Blobs.Specialized;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace CsvImporter.Services
{
class AzureReaderCsvService : IReaderService
{
private readonly ILogger<IReaderService> _logger;
private readonly IConfiguration _configuration;
public AzureReaderCsvService(ILogger<IReaderService> logger, IConfiguration config)
{
_logger = logger;
_configuration = config;
}
/// <summary>
/// Lectura de un archivo Csv cargado en una cuenta de Azure Blob Storage
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
Task<int> IReaderService.Read(string path, string delimiter)
{
throw new NotImplementedException();
}
}
}
| 27.514286 | 91 | 0.663551 | [
"MIT"
] | cristiantorres/CSVImporter | CsvImporter/Services/AzureReaderCsvService.cs | 965 | C# |
#pragma warning disable SA1300
using System.Collections.Generic;
namespace AudioBand.Settings.Models.V3
{
/// <summary>
/// The format for exported profiles.
/// </summary>
public class ProfileExportV3
{
/// <summary>
/// Gets or sets the version.
/// </summary>
public string Version { get; set; } = "3";
/// <summary>
/// Gets or sets the profiles.
/// </summary>
public Dictionary<string, ProfileV3> Profiles { get; set; }
}
}
| 24.636364 | 68 | 0.54797 | [
"MIT",
"BSD-3-Clause"
] | AudioBand/AudioBand | src/AudioBand/Settings/Models/v3/ProfileExportV3.cs | 544 | C# |
/*
* Prime Developer Trial
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Client.OpenAPIDateConverter;
namespace FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals.Model
{
/// <summary>
/// Maturity data.
/// </summary>
[DataContract(Name = "inline_response_200_6_instrument_lifeCycle_maturity")]
public partial class InlineResponse2006InstrumentLifeCycleMaturity : IEquatable<InlineResponse2006InstrumentLifeCycleMaturity>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="InlineResponse2006InstrumentLifeCycleMaturity" /> class.
/// </summary>
/// <param name="date">Date of the securitized derivative's maturity. The value is empty if the instrument is perpetual..</param>
/// <param name="remainingTermDays">Remaining term to maturity expressed in days. The value is empty if the instrument is perpetual..</param>
/// <param name="perpetual">If `true`, the securitized derivative is perpetual, i.e. it does not mature, therefore the attributes `date` and `remainingTermDays` are `null`..</param>
public InlineResponse2006InstrumentLifeCycleMaturity(DateTime date = default(DateTime), decimal remainingTermDays = default(decimal), bool perpetual = default(bool))
{
this.Date = date;
this.RemainingTermDays = remainingTermDays;
this.Perpetual = perpetual;
}
/// <summary>
/// Date of the securitized derivative's maturity. The value is empty if the instrument is perpetual.
/// </summary>
/// <value>Date of the securitized derivative's maturity. The value is empty if the instrument is perpetual.</value>
[DataMember(Name = "date", EmitDefaultValue = false)]
[JsonConverter(typeof(OpenAPIDateConverter))]
public DateTime Date { get; set; }
/// <summary>
/// Remaining term to maturity expressed in days. The value is empty if the instrument is perpetual.
/// </summary>
/// <value>Remaining term to maturity expressed in days. The value is empty if the instrument is perpetual.</value>
[DataMember(Name = "remainingTermDays", EmitDefaultValue = false)]
public decimal RemainingTermDays { get; set; }
/// <summary>
/// If `true`, the securitized derivative is perpetual, i.e. it does not mature, therefore the attributes `date` and `remainingTermDays` are `null`.
/// </summary>
/// <value>If `true`, the securitized derivative is perpetual, i.e. it does not mature, therefore the attributes `date` and `remainingTermDays` are `null`.</value>
[DataMember(Name = "perpetual", EmitDefaultValue = true)]
public bool Perpetual { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class InlineResponse2006InstrumentLifeCycleMaturity {\n");
sb.Append(" Date: ").Append(Date).Append("\n");
sb.Append(" RemainingTermDays: ").Append(RemainingTermDays).Append("\n");
sb.Append(" Perpetual: ").Append(Perpetual).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 InlineResponse2006InstrumentLifeCycleMaturity);
}
/// <summary>
/// Returns true if InlineResponse2006InstrumentLifeCycleMaturity instances are equal
/// </summary>
/// <param name="input">Instance of InlineResponse2006InstrumentLifeCycleMaturity to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(InlineResponse2006InstrumentLifeCycleMaturity input)
{
if (input == null)
{
return false;
}
return
(
this.Date == input.Date ||
(this.Date != null &&
this.Date.Equals(input.Date))
) &&
(
this.RemainingTermDays == input.RemainingTermDays ||
this.RemainingTermDays.Equals(input.RemainingTermDays)
) &&
(
this.Perpetual == input.Perpetual ||
this.Perpetual.Equals(input.Perpetual)
);
}
/// <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.Date != null)
{
hashCode = (hashCode * 59) + this.Date.GetHashCode();
}
hashCode = (hashCode * 59) + this.RemainingTermDays.GetHashCode();
hashCode = (hashCode * 59) + this.Perpetual.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 43.15528 | 229 | 0.619891 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/SecuritizedDerivativesAPIforDigitalPortals/v2/src/FactSet.SDK.SecuritizedDerivativesAPIforDigitalPortals/Model/InlineResponse2006InstrumentLifeCycleMaturity.cs | 6,948 | 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.AzureNextGen.DataFactory.V20170901Preview.Outputs
{
[OutputType]
public sealed class SparkSourceResponse
{
/// <summary>
/// A query to retrieve data from source. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? Query;
/// <summary>
/// Source retry count. Type: integer (or Expression with resultType integer).
/// </summary>
public readonly object? SourceRetryCount;
/// <summary>
/// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
public readonly object? SourceRetryWait;
/// <summary>
/// Copy source type.
/// Expected value is 'SparkSource'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private SparkSourceResponse(
object? query,
object? sourceRetryCount,
object? sourceRetryWait,
string type)
{
Query = query;
SourceRetryCount = sourceRetryCount;
SourceRetryWait = sourceRetryWait;
Type = type;
}
}
}
| 30.882353 | 146 | 0.600635 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/V20170901Preview/Outputs/SparkSourceResponse.cs | 1,575 | C# |
using System;
using Zilon.Core.World;
namespace Zilon.Core.PersonModules
{
public class MovingModule : IMovingModule
{
private const int BASE_DEXTERITY = 10;
private const int COST_PER_DEXTERITY_UNIT = 1;
private readonly IAttributesModule _attributesModule;
private readonly int BASE_COST = GlobeMetrics.OneIterationLength;
public MovingModule(IAttributesModule attributesModule)
{
_attributesModule = attributesModule;
}
public string Key => nameof(IMovingModule);
public bool IsActive { get; set; }
public int CalculateCost()
{
var dexterityAttribute = _attributesModule.GetAttribute(PersonAttributeType.Dexterity);
var significantValue = (int)Math.Ceiling(dexterityAttribute.Value);
var diffValue = significantValue - BASE_DEXTERITY;
return BASE_COST - (diffValue * COST_PER_DEXTERITY_UNIT);
}
}
} | 31.483871 | 99 | 0.67623 | [
"MIT"
] | kreghek/Zilon_Roguelike | Zilon.Core/Zilon.Core/PersonModules/MovingModule.cs | 978 | C# |
using UnityEngine;
using System;
namespace Obi
{
[RequireComponent(typeof(Animator))]
[DisallowMultipleComponent]
public class ObiAnimatorController : MonoBehaviour
{
private Animator animator;
private float lastUpdate;
private float updateDelta;
public float UpdateDelta{
get{return updateDelta;}
}
public void Awake(){
animator = GetComponent<Animator>();
lastUpdate = Time.time;
}
public void OnDisable(){
ResumeAutonomousUpdate();
}
public void UpdateAnimation(bool fixedUpdate)
{
// UpdateAnimation might becalled during FixedUpdate(), but we still need to account for the full frame's worth of animation.
// Since Time.deltaTime returns the fixed step during FixedUpdate(), we need to use our own delta.
updateDelta = Time.time - lastUpdate;
lastUpdate = Time.time;
if (animator.updateMode == AnimatorUpdateMode.AnimatePhysics)
updateDelta = Time.fixedDeltaTime;
// Note: when using AnimatorUpdateMode.Normal, the update method of your character controller
// should be Update() instead of FixedUpdate() (ObiCharacterController.cs, in this case).
if (animator != null && isActiveAndEnabled && (animator.updateMode != AnimatorUpdateMode.AnimatePhysics || fixedUpdate)){
animator.enabled = false;
animator.Update(updateDelta);
}
}
public void ResumeAutonomousUpdate(){
if (animator != null){
animator.enabled = true;
}
}
}
}
| 26.574074 | 128 | 0.726829 | [
"MIT"
] | Ultra-lion/Tajurbagah | Assets/Global Plugins/Obi/Scripts/Solver/ObiAnimatorController.cs | 1,437 | C# |
// <copyright file="IBlobRepository.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.EmployeeTraining.Repositories
{
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
/// <summary>
/// Interface for handling Azure Blob Storage operations like uploading and deleting images from blob.
/// </summary>
public interface IBlobRepository
{
/// <summary>
/// Delete file from Azure Storage Blob container.
/// </summary>
/// <param name="blobFilePath">Blob URL file path on which file is uploaded.</param>
/// <returns>Returns success if file deletion from blob is successful.</returns>
Task<bool> DeleteAsync(string blobFilePath);
/// <summary>
/// Initialize a blob client for interacting with the blob service.
/// </summary>
/// <returns>Returns blob client for blob operations.</returns>
CloudBlobClient InitializeBlobClient();
/// <summary>
/// Upload event image to blob container.
/// </summary>
/// <param name="fileStream">File stream of file to be uploaded on blob storage.</param>
/// <param name="contentType">Content type to be set on blob.</param>
/// <returns>Returns uploaded file blob URL.</returns>
Task<string> UploadAsync(Stream fileStream, string contentType);
}
} | 40.864865 | 107 | 0.638889 | [
"MIT"
] | Prachii2020/EmployeeTraining20 | Source/Microsoft.Teams.Apps.EmployeeTraining/Repositories/Blob/IBlobRepository.cs | 1,514 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
using System.Collections.Generic;
namespace Aliyun.Acs.Cdn.Model.V20180510
{
public class DescribeDomainFileSizeProportionDataResponse : AcsResponse
{
private string requestId;
private string domainName;
private string dataInterval;
private string startTime;
private string endTime;
private List<DescribeDomainFileSizeProportionData_UsageData> fileSizeProportionDataInterval;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
}
}
public string DataInterval
{
get
{
return dataInterval;
}
set
{
dataInterval = value;
}
}
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
}
}
public List<DescribeDomainFileSizeProportionData_UsageData> FileSizeProportionDataInterval
{
get
{
return fileSizeProportionDataInterval;
}
set
{
fileSizeProportionDataInterval = value;
}
}
public class DescribeDomainFileSizeProportionData_UsageData
{
private string timeStamp;
private List<DescribeDomainFileSizeProportionData_FileSizeProportionData> _value;
public string TimeStamp
{
get
{
return timeStamp;
}
set
{
timeStamp = value;
}
}
public List<DescribeDomainFileSizeProportionData_FileSizeProportionData> _Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
public class DescribeDomainFileSizeProportionData_FileSizeProportionData
{
private string fileSize;
private string proportion;
public string FileSize
{
get
{
return fileSize;
}
set
{
fileSize = value;
}
}
public string Proportion
{
get
{
return proportion;
}
set
{
proportion = value;
}
}
}
}
}
} | 17.72 | 95 | 0.626895 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-cdn/Cdn/Model/V20180510/DescribeDomainFileSizeProportionDataResponse.cs | 3,101 | C# |
using Cumulocity.MQTT.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static Cumulocity.MQTT.Client;
namespace Cumulocity.MQTT.Model
{
public class AlarmUpdateRequest : Request
{
private readonly AlarmFragment _alarmFragment;
private readonly IList<CustomValue> _customValues;
private readonly bool? _response;
private readonly string _type;
public AlarmUpdateRequest(string messageId, bool? response, string type, AlarmFragment alarmFragment, IList<CustomValue> customValues) : base(messageId, ValidApis.Alarm, HttpMethods.PUT)
{
_type = type;
_customValues = customValues;
_response = response;
_alarmFragment = alarmFragment;
}
public override string RequestTemplate()
{
string method = base._httpMethods.ToString();
return String.Concat(PreTemplate(method), AlarmFragmentTemplate(), PostTemplate());
}
private string AlarmFragmentTemplate()
{
return _alarmFragment.ToString();
}
private string PostTemplate()
{
StringBuilder result = new StringBuilder();
if (_customValues != null && _customValues.Any())
{
foreach (var item in _customValues)
{
result.Append(item.CustomValueAsString);
}
}
return result.ToString();
}
private string PreTemplate(string method)
{
return String.Format("10,{0},{1},ALARM,{2},{3}", _messageId, method, _response == null ? String.Empty : _response.ToString(), _type);
}
}
} | 33.407407 | 195 | 0.593126 | [
"MIT"
] | SoftwareAG/cumulocity-clients-cs | DeviceSDK/MQTT/src/MQTT.Client.NetFramework/Model/AlarmUpdateRequest.cs | 1,806 | C# |
namespace Snyk.VisualStudio.Extension.UI.Toolwindow.SnykCode
{
using System.Windows.Input;
/// <summary>
/// Data flow step object for UI representation of SnykCode markers.
/// </summary>
public class DataFlowStep
{
/// <summary>
/// Gets or sets row number in source file.
/// </summary>
public string RowNumber { get; set; }
/// <summary>
/// Gets or sets file name.
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Gets or sets line content.
/// </summary>
public string LineContent { get; set; }
/// <summary>
/// Gets or sets navigation command.
/// </summary>
public ICommand NavigateCommand { get; set; }
/// <summary>
/// Compare by file name and line content.
/// </summary>
/// <param name="obj">Object to compare.</param>
/// <returns>True if file name and line content are equal.</returns>
public override bool Equals(object obj) => this.Equals(obj as DataFlowStep);
/// <summary>
/// Get hash code using fileName and lineContent.
/// </summary>
/// <returns>Int hash value.</returns>
public override int GetHashCode() => (this.FileName, this.LineContent).GetHashCode();
private bool Equals(DataFlowStep dataFlowStep)
{
if (dataFlowStep is null)
{
return false;
}
if (object.ReferenceEquals(this, dataFlowStep))
{
return true;
}
return (this.FileName == dataFlowStep.FileName) && (this.LineContent == dataFlowStep.LineContent);
}
}
}
| 29.864407 | 110 | 0.548241 | [
"Apache-2.0"
] | snyk/snyk-visual-studio-plugin | Snyk.VisualStudio.Extension.Shared/Snyk/VisualStudio/Extension/UI/Toolwindow/SnykCode/DataFlowStep.cs | 1,764 | 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("FrequentNumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FrequentNumber")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("c537ceb6-8f96-4c3a-8ec5-fed8c630888f")]
// 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.837838 | 85 | 0.727209 | [
"MIT"
] | SevdalinZhelyazkov/TelerikAcademy | CSharp-Part-2/Arrays/FrequentNumber/Properties/AssemblyInfo.cs | 1,440 | C# |
using Blog.Core.Common;
using Blog.Core.IRepository.Base;
using Blog.Core.IServices;
using Blog.Core.Model.Models;
using Blog.Core.Services.BASE;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Blog.Core.Services
{
public class TopicDetailServices : BaseServices<TopicDetail>, ITopicDetailServices
{
/// <summary>
/// 获取开Bug数据(缓存)
/// </summary>
/// <returns></returns>
[Caching(AbsoluteExpiration = 10)]
public async Task<List<TopicDetail>> GetTopicDetails()
{
return await base.Query(a => !a.tdIsDelete && a.tdSectendDetail == "tbug");
}
}
}
| 27.5 | 87 | 0.654545 | [
"Apache-2.0"
] | hudingwen/Blog.Core | Blog.Core.Services/TopicDetailServices.cs | 680 | C# |
using System;
using System.Diagnostics;
using AliceServices;
using BobServices;
using CarolServices;
using IAliceServices;
using IBobServices;
using ICarolServices;
using Xunit;
namespace Zaaby.Shared.Test
{
public class UnitTest1
{
[Fact]
public void GetByAttribute()
{
var types0 = LoadHelper.GetByAttributes(typeof(TestAttribute));
var types1 = LoadHelper.GetByAttributes(typeof(TestDerivedAttribute));
Assert.Equal(2, types0.Count);
Assert.Single(types1);
Assert.Contains(typeof(TestClassWithAttribute), types0);
Assert.Contains(typeof(TestClassWithDerivedAttribute), types0);
Assert.Contains(typeof(TestClassWithDerivedAttribute), types1);
}
[Fact]
public void GetByBaseType()
{
var types0 = LoadHelper.GetByBaseTypes(typeof(ITestInterface));
var types1 = LoadHelper.GetByBaseTypes(typeof(IDerivedTestInterface));
Assert.Equal(2, types0.Count);
Assert.Contains(typeof(IDerivedTestInterface), types0);
Assert.Contains(typeof(ClassWithInterface), types0);
Assert.Contains(typeof(ClassWithDerivedInterface), types0);
}
[Fact]
public void ScanTypesTest()
{
var sw = Stopwatch.StartNew();
LoadHelper.FromAssemblyOf<IAliceService>();
LoadHelper.FromAssemblyOf<AliceService>();
LoadHelper.FromAssemblyOf<IBobService>();
LoadHelper.FromAssemblyOf<BobService>();
LoadHelper.FromAssemblyOf<ICarolService>();
LoadHelper.FromAssemblyOf<CarolService>();
sw.Stop();
var i0 = sw.ElapsedMilliseconds;
LoadHelper.LoadMode = LoadTypesMode.LoadByAllDirectory;
sw.Restart();
LoadHelper.LoadTypes();
sw.Stop();
var i1 = sw.ElapsedMilliseconds;
Assert.True(LoadHelper.LoadSpecifyTypes().Count > 0);
}
}
public class TestAttribute : Attribute
{
}
public class TestDerivedAttribute : TestAttribute
{
}
[Test]
public class TestClassWithAttribute
{
}
[TestDerived]
public class TestClassWithDerivedAttribute
{
}
public interface ITestInterface
{
}
public interface IDerivedTestInterface : ITestInterface
{
}
public class ClassWithInterface : ITestInterface
{
}
public class ClassWithDerivedInterface : IDerivedTestInterface
{
}
} | 25.50495 | 82 | 0.632764 | [
"MIT"
] | Mutuduxf/Zaaby | tests/Zaaby.Shared.Test/LoadHelperTest.cs | 2,576 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Surging.Core.CPlatform.Utilities
{
public class EnvironmentHelper
{
public static string GetEnvironmentVariable(string name)
{
return Environment.GetEnvironmentVariable(name);
}
public static bool GetEnvironmentVariableAsBool(string name, bool defaultValue = false)
{
var str = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrEmpty(str))
{
return defaultValue;
}
switch (str.ToLowerInvariant())
{
case "true":
case "1":
case "yes":
return true;
case "false":
case "0":
case "no":
return false;
default:
return defaultValue;
}
}
}
}
| 25.526316 | 95 | 0.5 | [
"MIT"
] | haibinli/surging | src/Surging.Core/Surging.Core.CPlatform/Utilities/EnvironmentHelper.cs | 972 | C# |
using System;
using System.Linq;
using System.Reflection;
using UnityEditor.Build.Content;
namespace BundleKit.Utility
{
internal static class ReflectionExtensions
{
private static FieldInfo WriteResult_SerializedObjects;
private static FieldInfo WriteResult_ResourceFiles;
private static FieldInfo SceneDependencyInfo_Scene;
private static FieldInfo SceneDependencyInfo_ProcessedScene;
private static FieldInfo SceneDependencyInfo_ReferencedObjects;
private static bool BuildUsageTagSet_SupportsFilterToSubset;
private static bool ContentBuildInterface_SupportsMultiThreadedArchiving;
public static bool SupportsFilterToSubset => BuildUsageTagSet_SupportsFilterToSubset;
public static bool SupportsMultiThreadedArchiving => ContentBuildInterface_SupportsMultiThreadedArchiving;
static ReflectionExtensions()
{
WriteResult_SerializedObjects = typeof(WriteResult).GetField("m_SerializedObjects", BindingFlags.Instance | BindingFlags.NonPublic);
WriteResult_ResourceFiles = typeof(WriteResult).GetField("m_ResourceFiles", BindingFlags.Instance | BindingFlags.NonPublic);
SceneDependencyInfo_Scene = typeof(SceneDependencyInfo).GetField("m_Scene", BindingFlags.Instance | BindingFlags.NonPublic);
SceneDependencyInfo_ProcessedScene = typeof(SceneDependencyInfo).GetField("m_ProcessedScene", BindingFlags.Instance | BindingFlags.NonPublic);
SceneDependencyInfo_ReferencedObjects = typeof(SceneDependencyInfo).GetField("m_ReferencedObjects", BindingFlags.Instance | BindingFlags.NonPublic);
BuildUsageTagSet_SupportsFilterToSubset = (typeof(BuildUsageTagSet).GetMethod("FilterToSubset") != null);
foreach (MethodInfo item in from x in typeof(ContentBuildInterface).GetMethods()
where x.Name == "ArchiveAndCompress"
select x)
{
foreach (CustomAttributeData customAttribute in item.CustomAttributes)
{
ContentBuildInterface_SupportsMultiThreadedArchiving = (customAttribute.AttributeType.Name == "ThreadSafeAttribute");
if (ContentBuildInterface_SupportsMultiThreadedArchiving)
{
break;
}
}
}
}
public static void SetSerializedObjects(this ref WriteResult result, ObjectSerializedInfo[] osis)
{
object obj = result;
WriteResult_SerializedObjects.SetValue(obj, osis);
result = (WriteResult)obj;
}
public static void SetResourceFiles(this ref WriteResult result, ResourceFile[] files)
{
object obj = result;
WriteResult_ResourceFiles.SetValue(obj, files);
result = (WriteResult)obj;
}
public static void SetScene(this ref SceneDependencyInfo dependencyInfo, string scene)
{
object obj = dependencyInfo;
SceneDependencyInfo_Scene.SetValue(obj, scene);
dependencyInfo = (SceneDependencyInfo)obj;
}
public static void SetReferencedObjects(this ref SceneDependencyInfo dependencyInfo, ObjectIdentifier[] references)
{
object obj = dependencyInfo;
SceneDependencyInfo_ReferencedObjects.SetValue(obj, references);
dependencyInfo = (SceneDependencyInfo)obj;
}
public static void FilterToSubset(this BuildUsageTagSet usageSet, ObjectIdentifier[] objectIds)
{
throw new Exception("FilterToSubset is not supported in this Unity version");
}
}
} | 44.821429 | 160 | 0.683134 | [
"MIT"
] | PassivePicasso/BundleKit | Editor/Utility/ReflectionExtensions.cs | 3,767 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.BAASDT.Models
{
public class QueryIpCodeResponse : TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
[NameInMap("req_msg_id")]
[Validation(Required=false)]
public string ReqMsgId { get; set; }
// 结果码,一般OK表示调用成功
[NameInMap("result_code")]
[Validation(Required=false)]
public string ResultCode { get; set; }
// 异常信息的文本描述
[NameInMap("result_msg")]
[Validation(Required=false)]
public string ResultMsg { get; set; }
// 正版码信息
[NameInMap("code_info")]
[Validation(Required=false)]
public IPCodeScannedInfo CodeInfo { get; set; }
// 首次扫码信息
[NameInMap("first_scanned_info")]
[Validation(Required=false)]
public IPSimpleScannedInfo FirstScannedInfo { get; set; }
// 扫码信息
[NameInMap("scanned_info_list")]
[Validation(Required=false)]
public List<IPSimpleScannedInfo> ScannedInfoList { get; set; }
// 扫码次数
[NameInMap("scanned_count")]
[Validation(Required=false)]
public long? ScannedCount { get; set; }
}
}
| 25.54 | 70 | 0.613156 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | baasdt/csharp/core/Models/QueryIpCodeResponse.cs | 1,389 | C# |
using LagoVista.IoT.DeviceManagement.Repos.Repos;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LagoVista.IoT.DeviceManagement.Core.Tests.PEMs
{
[TestClass]
public class PEMReconstructionTests
{
[TestMethod]
public void PEM_RecreateFromFields_Tests()
{
var pemIndex = new PEMIndexDTO();
pemIndex.JSON = @"{""pemId"":""1FBFB2BE162D4AD880E610CA6CC6BE79"",""messageType"":""Regular"",""status"":""Completed"",""errorReason"":""None"",""payloadType"":""Text"",""device"":{""DatabaseName"":""nuviot"",""EntityType"":""Device"",""CreationDate"":""2018-05-08T19:55:38.000Z"",""LastUpdatedDate"":""2018-05-08T19:55:38.000Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""DeviceRepository"":{""Id"":""B2B8E9211AAD49A8B4B74F950AD160BC"",""Text"":""LagoVista Devices""},""Status"":{""HasValue"":true,""Value"":2,""Id"":""ready"",""Text"":""Ready""},""id"":""6C8929ECD3394AA18A454A7EE8BD837A"",""Name"":""Lago Vista Pool"",""DeviceId"":""24002a000547343337373737"",""DeviceConfiguration"":{""Id"":""16C8782E6E254DC9B48B6115DB173352"",""Text"":""Pool""},""DeviceType"":{""Id"":""B777D72BE8824809A9919AB0D4EF8684"",""Text"":""Pool""},""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""Location"":null,""OwnerUser"":null,""DeviceURI"":null,""ShowDiagnostics"":null,""SerialNumber"":""1847lagovsita"",""FirmwareVersion"":null,""IsConnected"":null,""LastContact"":""2018-06-02T12:14:23.782Z"",""PrimaryAccessKey"":""NGgyMWIxeGxjamd5M2hpNWQ="",""SecondaryAccessKey"":""ZTh2cGxnOGM1dHZqZ3kzaGk1ZA=="",""GeoLocation"":null,""Heading"":0.0,""Speeed"":0.0,""CustomStatus"":null,""DebugMode"":false,""PropertiesMetaData"":null,""AttributeMetaData"":null,""StateMachineMetaData"":null,""PropertyBag"":{},""Properties"":[{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Hot Tub Setpoint"",""Key"":""hottubsetpoint"",""Value"":""103"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Pool Setpoint"",""Key"":""poolsetpoint"",""Value"":""87"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null}],""States"":[{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Pool Status"",""Key"":""poolstatus"",""Value"":""pooloff"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":false,""Value"":{""DatabaseName"":null,""EntityType"":null,""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Pool On"",""Key"":""poolon"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[{""Event"":{""HasValue"":true,""Value"":null,""Id"":""hottubon"",""Text"":""Turn Hot Tub On""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""hottubon"",""Text"":""Hot Tub On""},""TransitionAction"":null,""Description"":""""},{""Event"":{""HasValue"":true,""Value"":null,""Id"":""turnpooloff"",""Text"":""Turn Pool Off""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""pooloff"",""Text"":""Pool Off""},""TransitionAction"":null,""Description"":""""}],""Description"":null,""DiagramLocations"":[{""X"":556,""Y"":35,""Page"":1}]},{""TransitionInAction"":null,""Name"":""Pool Off"",""Key"":""pooloff"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[{""Event"":{""HasValue"":true,""Value"":null,""Id"":""poolon"",""Text"":""Turn Pool On""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""poolon"",""Text"":""Pool On""},""TransitionAction"":null,""Description"":""""},{""Event"":{""HasValue"":true,""Value"":null,""Id"":""hottubon"",""Text"":""Turn Hot Tub On""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""hottubon"",""Text"":""Hot Tub On""},""TransitionAction"":null,""Description"":""""}],""Description"":null,""DiagramLocations"":[{""X"":148,""Y"":138,""Page"":1}]},{""TransitionInAction"":null,""Name"":""Hot Tub On"",""Key"":""hottubon"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[{""Event"":{""HasValue"":true,""Value"":null,""Id"":""poolon"",""Text"":""Turn Pool On""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""poolon"",""Text"":""Pool On""},""TransitionAction"":null,""Description"":""""},{""Event"":{""HasValue"":true,""Value"":null,""Id"":""turnpooloff"",""Text"":""Turn Pool Off""},""NewState"":{""HasValue"":true,""Value"":null,""Id"":""pooloff"",""Text"":""Pool Off""},""TransitionAction"":null,""Description"":""""}],""Description"":null,""DiagramLocations"":[{""X"":542,""Y"":409,""Page"":1}]}],""RequireEnum"":false,""Key"":null,""IsPublic"":false,""OwnerOrganization"":null,""OwnerUser"":null,""id"":""6AA35E8626D7401DAB12E3180DEE7C93"",""CreationDate"":null,""CreatedBy"":null,""LastUpdatedDate"":null,""LastUpdatedBy"":null,""Name"":null,""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":null,""Text"":null}}],""Attributes"":[{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Counter Value"",""Key"":""counter"",""Value"":""1"",""AttributeType"":{""HasValue"":true,""Value"":1,""Id"":""integer"",""Text"":""Integer""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Compressor State"",""Key"":""compressorstate"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""11/03/2017 11:34:17"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""05/08/2018 18:51:00"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Fan State"",""Key"":""fanstate"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""11/03/2017 11:34:17"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""05/08/2018 18:51:00"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Water Source"",""Key"":""watersource"",""Value"":""pool"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from both the pool and the spa"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the spa"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""watersource"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""CreationDate"":""11/05/2017 18:45:01"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""11/05/2017 18:45:01"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Input Water Source"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""Text"":""Input Water Source""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Pool Water Output"",""Key"":""outputmode"",""Value"":""both"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":""Unknown where the water is output."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the pool."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the spa."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is going to both the pool and the spa."",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolwateroutput"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A25FD9DE0604441EADCBF18BD60F2823"",""CreationDate"":""11/05/2017 18:46:48"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""11/05/2017 18:46:48"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Water Output"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A25FD9DE0604441EADCBF18BD60F2823"",""Text"":""Pool Water Output""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Spa Mode"",""Key"":""spamode"",""Value"":""jets"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Normal"",""Key"":""normal"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Single flow in, usually used in conjunction with pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Jets"",""Key"":""jets"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""The three output nozzles that provide air infused jets into the hot tub"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""spamode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""88D4300C8DA445EEA295BFA3D73B8548"",""CreationDate"":""11/05/2017 18:42:07"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""11/05/2017 18:42:07"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Spa Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""88D4300C8DA445EEA295BFA3D73B8548"",""Text"":""Spa Mode""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Temperature Into Heater"",""Key"":""temperaturein"",""Value"":""86"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Temperature From Heater"",""Key"":""temperatureout"",""Value"":""62"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""High Pressure"",""Key"":""highpressure"",""Value"":""ok"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""05/08/2018 18:40:07"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""05/08/2018 18:40:07"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Low Pressure"",""Key"":""lowpressure"",""Value"":""ok"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""05/08/2018 18:40:07"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""05/08/2018 18:40:07"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Water Flow"",""Key"":""waterflow"",""Value"":""warning"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""05/08/2018 18:40:07"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""05/08/2018 18:40:07"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}},{""LastUpdated"":null,""LastUpdatedBy"":null,""Name"":""Pool Mode"",""Key"":""poolmode"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolmode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""CreationDate"":""11/05/2017 18:38:14"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""11/05/2017 18:38:14"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""Text"":""Pool Mode""}}],""MessageValues"":[{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Pool Mode"",""Key"":""poolmode"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolmode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""CreationDate"":""2017-11-05T18:38:14.629Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:38:14.629Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""Text"":""Pool Mode""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Temperature In"",""Key"":""temperaturein"",""Value"":""86"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Temperature Out"",""Key"":""temperatureout"",""Value"":""62"",""AttributeType"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Spa Mode"",""Key"":""spamode"",""Value"":""jets"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Normal"",""Key"":""normal"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Single flow in, usually used in conjunction with pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Jets"",""Key"":""jets"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""The three output nozzles that provide air infused jets into the hot tub"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""spamode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""88D4300C8DA445EEA295BFA3D73B8548"",""CreationDate"":""2017-11-05T18:42:07.794Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:42:07.794Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Spa Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""88D4300C8DA445EEA295BFA3D73B8548"",""Text"":""Spa Mode""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Current Water Source"",""Key"":""watersource"",""Value"":""pool"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from both the pool and the spa"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the spa"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""watersource"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""CreationDate"":""2017-11-05T18:45:01.022Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:45:01.022Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Input Water Source"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""Text"":""Input Water Source""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Current Water Output"",""Key"":""currentwateroutput"",""Value"":""both"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":""Unknown where the water is output."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the pool."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the spa."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is going to both the pool and the spa."",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolwateroutput"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A25FD9DE0604441EADCBF18BD60F2823"",""CreationDate"":""2017-11-05T18:46:48.585Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:46:48.585Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Water Output"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A25FD9DE0604441EADCBF18BD60F2823"",""Text"":""Pool Water Output""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""RSSI"",""Key"":""rssi"",""Value"":""-57"",""AttributeType"":{""HasValue"":true,""Value"":1,""Id"":""integer"",""Text"":""Integer""},""UnitSet"":null,""StateSet"":null},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Flow"",""Key"":""flow"",""Value"":""warning"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Compressor State"",""Key"":""compressorstate"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""2017-11-03T11:34:17.977Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:51:00.589Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Fan State"",""Key"":""fanstate"",""Value"":""off"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""2017-11-03T11:34:17.977Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:51:00.589Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""Low Pressure"",""Key"":""lowpressure"",""Value"":""ok"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}},{""LastUpdated"":""2018-06-02T12:14:23.942Z"",""LastUpdatedBy"":""Message"",""Name"":""High Pressure"",""Key"":""highpressure"",""Value"":""ok"",""AttributeType"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""},""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""}}],""InputCommandEndPoints"":null,""DeviceGroups"":[],""Notes"":[]},""instructions"":null,""creationTimeStamp"":""2018-06-02T12:14:23.782Z"",""completionTimeStamp"":""2018-06-02T12:14:24.026Z"",""executionTimeMS"":243.51199999999997,""envelope"":{""deviceRepoId"":""B2B8E9211AAD49A8B4B74F950AD160BC"",""deviceid"":""24002a000547343337373737"",""method"":""POST"",""path"":""/poolstatus/24002a000547343337373737"",""headers"":{""method"":""POST"",""2CACE6AC9FE742388E7FD9AB7DEB0D9D"":""CD8E9BBE586D48378EE0531055EEAD44"",""Connection"":""close"",""Content-Type"":""application/json"",""Host"":""lagovista.softwarelogistics.iothost.net"",""Content-Length"":""233""}},""payloadLength"":233,""messageId"":""poolstatus""}";
pemIndex.TextPayload = "{\"mode\":\"off\",\"temperatureIn\":86,\"temperatureOut\":62,\"flow\":\"warning\",\"lowPressure\":\"ok\",\"highPressure\":\"ok\",\"fanState\":\"off\",\"compressorState\":\"off\",\"currentSpaMode\":\"jets\",\"currentSource\":\"pool\",\"currentOutput\":\"both\",\"rssi\":\"-57\"}";
pemIndex.OutgoingMessages = "[{'msgid':'001'},{'msgid':'002'}]";
pemIndex.Values = @"{""poolmode"":{""Name"":""Pool Mode"",""Key"":""poolmode"",""Value"":""off"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolmode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""CreationDate"":""2017-11-05T18:38:14.629Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:38:14.629Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""9C5ECC78068243739DB1D67EAE39D5AF"",""Text"":""Pool Mode""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""temperaturein"":{""Name"":""Temperature In"",""Key"":""temperaturein"",""Value"":""86"",""UnitSet"":null,""StateSet"":null,""Type"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""}},""temperatureout"":{""Name"":""Temperature Out"",""Key"":""temperatureout"",""Value"":""62"",""UnitSet"":null,""StateSet"":null,""Type"":{""HasValue"":true,""Value"":2,""Id"":""decimal"",""Text"":""Decimal""}},""spamode"":{""Name"":""Spa Mode"",""Key"":""spamode"",""Value"":""jets"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Normal"",""Key"":""normal"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Single flow in, usually used in conjunction with pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Jets"",""Key"":""jets"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""The three output nozzles that provide air infused jets into the hot tub"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""spamode"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""88D4300C8DA445EEA295BFA3D73B8548"",""CreationDate"":""2017-11-05T18:42:07.794Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:42:07.794Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Spa Mode"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""88D4300C8DA445EEA295BFA3D73B8548"",""Text"":""Spa Mode""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""watersource"":{""Name"":""Current Water Source"",""Key"":""watersource"",""Value"":""pool"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the pool"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from both the pool and the spa"",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is coming from the spa"",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""watersource"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""CreationDate"":""2017-11-05T18:45:01.022Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:45:01.022Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Input Water Source"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""D1257B5DABF04D63A3AA7CE6FF1C7311"",""Text"":""Input Water Source""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""currentwateroutput"":{""Name"":""Current Water Output"",""Key"":""currentwateroutput"",""Value"":""both"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""Unknown"",""Key"":""unknown"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":""Unknown where the water is output."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Pool"",""Key"":""pool"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the pool."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Spa"",""Key"":""spa"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is only going to the spa."",""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Both"",""Key"":""both"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":""Water is going to both the pool and the spa."",""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""poolwateroutput"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A25FD9DE0604441EADCBF18BD60F2823"",""CreationDate"":""2017-11-05T18:46:48.585Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2017-11-05T18:46:48.585Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""Pool Water Output"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A25FD9DE0604441EADCBF18BD60F2823"",""Text"":""Pool Water Output""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""rssi"":{""Name"":""RSSI"",""Key"":""rssi"",""Value"":""-57"",""UnitSet"":null,""StateSet"":null,""Type"":{""HasValue"":true,""Value"":1,""Id"":""integer"",""Text"":""Integer""}},""flow"":{""Name"":""Flow"",""Key"":""flow"",""Value"":""warning"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""compressorstate"":{""Name"":""Compressor State"",""Key"":""compressorstate"",""Value"":""off"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""2017-11-03T11:34:17.977Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:51:00.589Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""fanstate"":{""Name"":""Fan State"",""Key"":""fanstate"",""Value"":""off"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""On"",""Key"":""on"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Off"",""Key"":""off"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""onoff"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A6F0263F5B1944B191DCCC9A8239A196"",""CreationDate"":""2017-11-03T11:34:17.977Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:51:00.589Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""On/Off"",""Description"":"""",""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A6F0263F5B1944B191DCCC9A8239A196"",""Text"":""On/Off""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""lowpressure"":{""Name"":""Low Pressure"",""Key"":""lowpressure"",""Value"":""ok"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}},""highpressure"":{""Name"":""High Pressure"",""Key"":""highpressure"",""Value"":""ok"",""UnitSet"":null,""StateSet"":{""HasValue"":true,""Value"":{""DatabaseName"":""nuviot"",""EntityType"":""StateSet"",""IsLocked"":false,""LockedBy"":null,""LockedDateStamp"":null,""States"":[{""TransitionInAction"":null,""Name"":""OK"",""Key"":""ok"",""EnumValue"":null,""IsInitialState"":true,""Transitions"":[],""Description"":null,""DiagramLocations"":[]},{""TransitionInAction"":null,""Name"":""Warning"",""Key"":""warning"",""EnumValue"":null,""IsInitialState"":false,""Transitions"":[],""Description"":null,""DiagramLocations"":[]}],""RequireEnum"":false,""Key"":""okwarning"",""IsPublic"":false,""OwnerOrganization"":{""Id"":""AA2C78499D0140A5A9CE4B7581EF9691"",""Text"":""Software Logistics""},""OwnerUser"":null,""id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""CreationDate"":""2018-05-08T18:40:07.072Z"",""CreatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""LastUpdatedDate"":""2018-05-08T18:40:07.072Z"",""LastUpdatedBy"":{""Id"":""CC648B3B51164A8296EB7092F312D5CB"",""Text"":""Kevin Wolf""},""Name"":""OK/Warning"",""Description"":null,""Notes"":[],""IsValid"":true,""ValidationErrors"":[]},""Id"":""A829E2F83BEF4C15B0500D5BAB3ABF92"",""Text"":""OK/Warning""},""Type"":{""HasValue"":true,""Value"":6,""Id"":""state"",""Text"":""States""}}}";
pemIndex.Instructions = @"[{""name"":""REST 9000"",""type"":""RESTListener"",""queueUri"":null,""queueId"":""E7A28C0078374CA4910126DCAD409ED3"",""enqueued"":""2018-06-02T12:14:23.782Z"",""startDateStamp"":""2018-06-02T12:14:23.782Z"",""timeInQueueMS"":0.0,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":0.168},{""name"":""Pool Planner"",""type"":""Planner"",""queueUri"":null,""queueId"":""843985724D08451797AA1A4CF8AE9FB7"",""enqueued"":""2018-06-02T12:14:23.782Z"",""startDateStamp"":""2018-06-02T12:14:23.782Z"",""timeInQueueMS"":0.21,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":158.953},{""name"":""Anonymous"",""type"":""Sentinel"",""queueUri"":null,""queueId"":""3C570A76989C4FE4A03B3B0E578803A2"",""enqueued"":""2018-06-02T12:14:23.941Z"",""startDateStamp"":""2018-06-02T12:14:23.941Z"",""timeInQueueMS"":0.08,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":0.016},{""name"":""Message Based"",""type"":""Input Translator"",""queueUri"":null,""queueId"":""B0AD07CADE8F473D87406DF3E50C4C0D"",""enqueued"":""2018-06-02T12:14:23.941Z"",""startDateStamp"":""2018-06-02T12:14:23.942Z"",""timeInQueueMS"":0.08,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":42.304},{""name"":""Pool Workflow"",""type"":""Workflow"",""queueUri"":null,""queueId"":""B2CFFE1F988B4165876F71A60613BBB3"",""enqueued"":""2018-06-02T12:14:23.984Z"",""startDateStamp"":""2018-06-02T12:14:23.984Z"",""timeInQueueMS"":0.26,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":0.432},{""name"":""Messag Based"",""type"":""Output Translator"",""queueUri"":null,""queueId"":""F881085852844890AC9E84695657AD26"",""enqueued"":""2018-06-02T12:14:23.985Z"",""startDateStamp"":""2018-06-02T12:14:23.985Z"",""timeInQueueMS"":0.07,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":0.009},{""name"":""Temperature Logging"",""type"":""DataStream"",""queueUri"":null,""queueId"":""607C8195E71E40B6B53160A1A737ACEC"",""enqueued"":""2018-06-02T12:14:23.985Z"",""startDateStamp"":""2018-06-02T12:14:23.985Z"",""timeInQueueMS"":0.06,""processByHostId"":""AEFCC95E48D640D7A50B3A4A5FB3CE52"",""executionTimeMS"":41.798}]";
pemIndex.Log = "[{'log':'001'},{'log':'002'}]";
pemIndex.ResponseMessage = "{'resp':'001'}";
pemIndex.Device = "{'deviceid':'dev001'}";
var pem = pemIndex.ToPEM();
Console.WriteLine(pem.Result);
}
}
}
| 1,561.029412 | 35,367 | 0.644974 | [
"MIT"
] | LagoVista/DeviceManagement | tests/LagoVista.IoT.DeviceManagement.Core.Tests/PEMs/PEMReconstructionTests.cs | 53,077 | C# |
using NHyphenator.Loaders;
using NUnit.Framework;
namespace NHyphenator.Tests
{
public class FileLoaderTests
{
[Test]
public void LoadPatternsTest()
{
var loader = new FilePatternsLoader("./Resources/test_pat.txt");
var hyphenator = new Hyphenator(loader, "-");
var hyphenateText = hyphenator.HyphenateText("перенос");
Assert.AreEqual("пере-нос", hyphenateText);
}
[Test]
public void LoadExceptionsTest()
{
var loader = new FilePatternsLoader("./Resources/test_pat.txt", "./Resources/test_ex.txt");
var hyphenator = new Hyphenator(loader, "-");
var hyphenateText = hyphenator.HyphenateText("перенос");
Assert.AreEqual("пе-ре-нос", hyphenateText);
}
}
} | 30.962963 | 103 | 0.595694 | [
"Apache-2.0"
] | SimUTZ/NHyphenator | NHyphenator.Tests/FileLoaderTests.cs | 866 | C# |
// Control|Controls3D|100010
namespace VRTK
{
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// All 3D controls extend the `VRTK_Control` abstract class which provides a default set of methods and events that all of the subsequent controls expose.
/// </summary>
[ExecuteInEditMode]
public abstract class VRTK_Control : MonoBehaviour
{
public enum Direction
{
autodetect, x, y, z
}
[System.Serializable]
public class ValueChangedEvent : UnityEvent<float, float> { }
[System.Serializable]
public class DefaultControlEvents
{
/// <summary>
/// Emitted when the control is interacted with.
/// </summary>
public ValueChangedEvent OnValueChanged;
}
// to be registered by each control to support value normalization
public struct ControlValueRange
{
public float controlMin;
public float controlMax;
}
private static Color COLOR_OK = Color.yellow;
private static Color COLOR_ERROR = new Color(1, 0, 0, 0.9f);
private static float MIN_OPENING_DISTANCE = 20f; // percentage how far open something needs to be in order to activate it
public DefaultControlEvents defaultEvents;
[Tooltip("If active the control will react to the controller without the need to push the grab button.")]
public bool interactWithoutGrab = false;
abstract protected void InitRequiredComponents();
abstract protected bool DetectSetup();
abstract protected ControlValueRange RegisterValueRange();
abstract protected void HandleUpdate();
protected Bounds bounds;
protected bool setupSuccessful = true;
protected float value;
private ControlValueRange cvr;
private GameObject controlContent;
private bool hideControlContent = false;
/// <summary>
/// The GetValue method returns the current value/position/setting of the control depending on the control that is extending this abstract class.
/// </summary>
/// <returns>The current value of the control.</returns>
public float GetValue()
{
return value;
}
/// <summary>
/// The GetNormalizedValue method returns the current value mapped onto a range between 0 and 100.
/// </summary>
/// <returns>The current normalized value of the control.</returns>
public float GetNormalizedValue()
{
return Mathf.Abs(Mathf.Round((value - cvr.controlMin) / (cvr.controlMax - cvr.controlMin) * 100));
}
/// <summary>
/// The SetContent method sets the given game object as the content of the control. This will then disable and optionally hide the content when a control is obscuring its view to prevent interacting with content within a control.
/// </summary>
/// <param name="content">The content to be considered within the control.</param>
/// <param name="hideContent">When true the content will be hidden in addition to being non-interactable in case the control is fully closed.</param>
public void SetContent(GameObject content, bool hideContent)
{
controlContent = content;
hideControlContent = hideContent;
}
/// <summary>
/// The GetContent method returns the current game object of the control's content.
/// </summary>
/// <returns>The currently stored content for the control.</returns>
public GameObject GetContent()
{
return controlContent;
}
protected virtual void Awake()
{
if (Application.isPlaying)
{
InitRequiredComponents();
if (interactWithoutGrab)
{
CreateTriggerVolume();
}
}
setupSuccessful = DetectSetup();
if (Application.isPlaying)
{
cvr = RegisterValueRange();
HandleInteractables();
}
}
protected virtual void Update()
{
if (!Application.isPlaying)
{
setupSuccessful = DetectSetup();
}
else if (setupSuccessful)
{
float oldValue = value;
HandleUpdate();
// trigger events
if (value != oldValue)
{
HandleInteractables();
defaultEvents.OnValueChanged.Invoke(GetValue(), GetNormalizedValue());
}
}
}
protected virtual void OnDrawGizmos()
{
if (!enabled)
{
return;
}
bounds = VRTK_SharedMethods.GetBounds(transform);
Gizmos.color = (setupSuccessful) ? COLOR_OK : COLOR_ERROR;
if (setupSuccessful)
{
Gizmos.DrawWireCube(bounds.center, bounds.size);
}
else
{
Gizmos.DrawCube(bounds.center, bounds.size * 1.01f); // draw slightly bigger to eliminate flickering
}
}
protected Vector3 getThirdDirection(Vector3 axis1, Vector3 axis2)
{
bool xTaken = axis1.x != 0 || axis2.x != 0;
bool yTaken = axis1.y != 0 || axis2.y != 0;
bool zTaken = axis1.z != 0 || axis2.z != 0;
if (xTaken && yTaken)
{
return Vector3.forward;
}
else if (xTaken && zTaken)
{
return Vector3.up;
}
else
{
return Vector3.right;
}
}
private void CreateTriggerVolume()
{
GameObject tvGo = new GameObject(name + "-Trigger");
tvGo.transform.SetParent(transform);
tvGo.AddComponent<VRTK_ControllerRigidbodyActivator>();
// calculate bounding box
Bounds bounds = VRTK_SharedMethods.GetBounds(transform);
bounds.Expand(bounds.size * 0.2f);
tvGo.transform.position = bounds.center;
BoxCollider bc = tvGo.AddComponent<BoxCollider>();
bc.isTrigger = true;
bc.size = bounds.size;
}
private void HandleInteractables()
{
if (controlContent == null)
{
return;
}
if (hideControlContent)
{
controlContent.SetActive(value > 0);
}
// do not cache objects since otherwise they would still be made inactive once taken out of the content
foreach (VRTK_InteractableObject io in controlContent.GetComponentsInChildren<VRTK_InteractableObject>(true))
{
io.enabled = value > MIN_OPENING_DISTANCE;
}
}
}
} | 33.592417 | 237 | 0.561653 | [
"MIT"
] | GeekLiB/VRTK | Assets/VRTK/Scripts/Controls/3D/VRTK_Control.cs | 7,090 | C# |
using System;
class MyName
{
static void Main()
{
Console.WriteLine("Kristina Tsvetkova");
}
}
| 13.272727 | 52 | 0.472603 | [
"MIT"
] | krismy/CSharp-One | HW_krismy_Vuvedenie-v-programiraneto_2015-01-16_15-57/Homework 1/Homework 1/Problem 5. Print Your Name/PrintMyName.cs | 148 | C# |
namespace Mpdn.PlayerExtensions
{
namespace GitHub
{
public partial class DisplayChangerConfigDialog : DisplayChangerConfigBase
{
public DisplayChangerConfigDialog()
{
InitializeComponent();
}
protected override void LoadSettings()
{
checkBoxActivate.Checked = Settings.Activate;
checkBoxRestore.Checked = Settings.Restore;
checkBoxRestoreExit.Checked = Settings.RestoreOnExit;
checkBoxHighestRate.Checked = Settings.HighestRate;
checkBoxRestricted.Checked = Settings.Restricted;
textBoxVideoTypes.Text = Settings.VideoTypes;
}
protected override void SaveSettings()
{
Settings.Activate = checkBoxActivate.Checked;
Settings.Restore = checkBoxRestore.Checked;
Settings.RestoreOnExit = checkBoxRestoreExit.Checked;
Settings.HighestRate = checkBoxHighestRate.Checked;
Settings.Restricted = checkBoxRestricted.Checked;
Settings.VideoTypes = textBoxVideoTypes.Text;
}
}
public class DisplayChangerConfigBase : ScriptConfigDialog<DisplayChangerSettings>
{
}
}
}
| 36.131579 | 91 | 0.585579 | [
"MIT"
] | Shiandow/PlayerExtensions | PlayerExtensions/DisplayChanger.ConfigDialog.cs | 1,375 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
[SupportTags(typeof(TagPropertyEditorTagDefinition), ValueType = TagValueType.CustomTagList)]
[PropertyEditor(Constants.PropertyEditors.TagsAlias, "Tags", "tags")]
public class TagsPropertyEditor : PropertyEditor
{
public TagsPropertyEditor()
{
_defaultPreVals = new Dictionary<string, object>
{
{"group", "default"},
{"storageType", TagCacheStorageType.Csv.ToString()}
};
}
private IDictionary<string, object> _defaultPreVals;
/// <summary>
/// Override to supply the default group
/// </summary>
public override IDictionary<string, object> DefaultPreValues
{
get { return _defaultPreVals; }
set { _defaultPreVals = value; }
}
protected override PropertyValueEditor CreateValueEditor()
{
return new TagPropertyValueEditor(base.CreateValueEditor());
}
protected override PreValueEditor CreatePreValueEditor()
{
return new TagPreValueEditor();
}
internal class TagPropertyValueEditor : PropertyValueEditorWrapper
{
public TagPropertyValueEditor(PropertyValueEditor wrapped)
: base(wrapped)
{
}
/// <summary>
/// This needs to return IEnumerable{string}
/// </summary>
/// <param name="editorValue"></param>
/// <param name="currentValue"></param>
/// <returns></returns>
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
{
var json = editorValue.Value as JArray;
return json == null ? null : json.Select(x => x.Value<string>());
}
}
internal class TagPreValueEditor : PreValueEditor
{
public TagPreValueEditor()
{
Fields.Add(new PreValueField(new ManifestPropertyValidator { Type = "Required" })
{
Description = "Define a tag group",
Key = "group",
Name = "Tag group",
View = "requiredfield"
});
Fields.Add(new PreValueField(new ManifestPropertyValidator {Type = "Required"})
{
Description = "Select whether to store the tags in cache as CSV (default) or as JSON. The only benefits of storage as JSON is that you are able to have commas in a tag value but this will require parsing the json in your views or using a property value converter",
Key = "storageType",
Name = "Storage Type",
View = "views/propertyeditors/tags/tags.prevalues.html"
});
}
public override IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals)
{
var result = base.ConvertDbToEditor(defaultPreVals, persistedPreVals);
//This is required because we've added this pre-value so old installs that don't have it will need to have a default.
if (result.ContainsKey("storageType") == false || result["storageType"] == null || result["storageType"].ToString().IsNullOrWhiteSpace())
{
result["storageType"] = TagCacheStorageType.Csv.ToString();
}
return result;
}
}
}
} | 39.653465 | 285 | 0.567041 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs | 4,007 | C# |
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;
using Lachlan.Visual.Sample.Models;
using Lachlan.Visual.Sample.Views;
namespace Lachlan.Visual.Sample.ViewModels
{
public class ItemsViewModel : BaseViewModel
{
public ObservableCollection<Item> Items { get; set; }
public Command LoadItemsCommand { get; set; }
public ItemsViewModel()
{
Title = "Browse";
Items = new ObservableCollection<Item>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
var newItem = item as Item;
Items.Add(newItem);
await DataStore.AddItemAsync(newItem);
});
}
async Task ExecuteLoadItemsCommand()
{
if (IsBusy)
return;
IsBusy = true;
try
{
Items.Clear();
var items = await DataStore.GetItemsAsync(true);
foreach (var item in items)
{
Items.Add(item);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
}
} | 25.706897 | 94 | 0.511066 | [
"MIT"
] | lachlanwgordon/Lachlan.Visual | Source/Lachlan.Visual.Sample/ViewModels/ItemsViewModel.cs | 1,493 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Network
{
/// <summary> A class representing collection of PrivateDnsZoneGroup and their operations over its parent. </summary>
public partial class PrivateDnsZoneGroupCollection : ArmCollection, IEnumerable<PrivateDnsZoneGroup>, IAsyncEnumerable<PrivateDnsZoneGroup>
{
private readonly ClientDiagnostics _privateDnsZoneGroupClientDiagnostics;
private readonly PrivateDnsZoneGroupsRestOperations _privateDnsZoneGroupRestClient;
/// <summary> Initializes a new instance of the <see cref="PrivateDnsZoneGroupCollection"/> class for mocking. </summary>
protected PrivateDnsZoneGroupCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="PrivateDnsZoneGroupCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal PrivateDnsZoneGroupCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_privateDnsZoneGroupClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", PrivateDnsZoneGroup.ResourceType.Namespace, DiagnosticOptions);
TryGetApiVersion(PrivateDnsZoneGroup.ResourceType, out string privateDnsZoneGroupApiVersion);
_privateDnsZoneGroupRestClient = new PrivateDnsZoneGroupsRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri, privateDnsZoneGroupApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != PrivateEndpoint.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, PrivateEndpoint.ResourceType), nameof(id));
}
/// <summary>
/// Creates or updates a private dns zone group in the specified private endpoint.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_CreateOrUpdate
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="parameters"> Parameters supplied to the create or update private dns zone group operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> or <paramref name="parameters"/> is null. </exception>
public virtual async Task<ArmOperation<PrivateDnsZoneGroup>> CreateOrUpdateAsync(WaitUntil waitUntil, string privateDnsZoneGroupName, PrivateDnsZoneGroupData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _privateDnsZoneGroupRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, parameters, cancellationToken).ConfigureAwait(false);
var operation = new NetworkArmOperation<PrivateDnsZoneGroup>(new PrivateDnsZoneGroupOperationSource(Client), _privateDnsZoneGroupClientDiagnostics, Pipeline, _privateDnsZoneGroupRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Creates or updates a private dns zone group in the specified private endpoint.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_CreateOrUpdate
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="parameters"> Parameters supplied to the create or update private dns zone group operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> or <paramref name="parameters"/> is null. </exception>
public virtual ArmOperation<PrivateDnsZoneGroup> CreateOrUpdate(WaitUntil waitUntil, string privateDnsZoneGroupName, PrivateDnsZoneGroupData parameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
Argument.AssertNotNull(parameters, nameof(parameters));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _privateDnsZoneGroupRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, parameters, cancellationToken);
var operation = new NetworkArmOperation<PrivateDnsZoneGroup>(new PrivateDnsZoneGroupOperationSource(Client), _privateDnsZoneGroupClientDiagnostics, Pipeline, _privateDnsZoneGroupRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, parameters).Request, response, OperationFinalStateVia.AzureAsyncOperation);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the private dns zone group resource by specified private dns zone group name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual async Task<Response<PrivateDnsZoneGroup>> GetAsync(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.Get");
scope.Start();
try
{
var response = await _privateDnsZoneGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new PrivateDnsZoneGroup(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the private dns zone group resource by specified private dns zone group name.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual Response<PrivateDnsZoneGroup> Get(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.Get");
scope.Start();
try
{
var response = _privateDnsZoneGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new PrivateDnsZoneGroup(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets all private dns zone groups in a private endpoint.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups
/// Operation Id: PrivateDnsZoneGroups_List
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="PrivateDnsZoneGroup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<PrivateDnsZoneGroup> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<PrivateDnsZoneGroup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetAll");
scope.Start();
try
{
var response = await _privateDnsZoneGroupRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new PrivateDnsZoneGroup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<PrivateDnsZoneGroup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetAll");
scope.Start();
try
{
var response = await _privateDnsZoneGroupRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new PrivateDnsZoneGroup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Gets all private dns zone groups in a private endpoint.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups
/// Operation Id: PrivateDnsZoneGroups_List
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="PrivateDnsZoneGroup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<PrivateDnsZoneGroup> GetAll(CancellationToken cancellationToken = default)
{
Page<PrivateDnsZoneGroup> FirstPageFunc(int? pageSizeHint)
{
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetAll");
scope.Start();
try
{
var response = _privateDnsZoneGroupRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new PrivateDnsZoneGroup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<PrivateDnsZoneGroup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetAll");
scope.Start();
try
{
var response = _privateDnsZoneGroupRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new PrivateDnsZoneGroup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual async Task<Response<bool>> ExistsAsync(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(privateDnsZoneGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual Response<bool> Exists(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(privateDnsZoneGroupName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual async Task<Response<PrivateDnsZoneGroup>> GetIfExistsAsync(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetIfExists");
scope.Start();
try
{
var response = await _privateDnsZoneGroupRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<PrivateDnsZoneGroup>(null, response.GetRawResponse());
return Response.FromValue(new PrivateDnsZoneGroup(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}
/// Operation Id: PrivateDnsZoneGroups_Get
/// </summary>
/// <param name="privateDnsZoneGroupName"> The name of the private dns zone group. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="privateDnsZoneGroupName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="privateDnsZoneGroupName"/> is null. </exception>
public virtual Response<PrivateDnsZoneGroup> GetIfExists(string privateDnsZoneGroupName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(privateDnsZoneGroupName, nameof(privateDnsZoneGroupName));
using var scope = _privateDnsZoneGroupClientDiagnostics.CreateScope("PrivateDnsZoneGroupCollection.GetIfExists");
scope.Start();
try
{
var response = _privateDnsZoneGroupRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, privateDnsZoneGroupName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<PrivateDnsZoneGroup>(null, response.GetRawResponse());
return Response.FromValue(new PrivateDnsZoneGroup(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<PrivateDnsZoneGroup> IEnumerable<PrivateDnsZoneGroup>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<PrivateDnsZoneGroup> IAsyncEnumerable<PrivateDnsZoneGroup>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 62.933162 | 480 | 0.681263 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/PrivateDnsZoneGroupCollection.cs | 24,481 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using MtdKey.Storage.DataModels;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MtdKey.Storage
{
public partial class RequestProvider : IDisposable
{
private async Task<List<NodePatternItem>> GetNodePatternItemsAsync(IList<Stack> stacks)
{
List<NodePatternItem> nodeItems = new();
List<long> fieldIds = stacks.GroupBy(x => x.FieldId).Select(x => x.Key).ToList();
Dictionary<long, int> fieldTypes = await context.Set<Field>()
.Where(field => fieldIds.Contains(field.Id))
.Select(s => new { s.Id, s.FieldType })
.ToDictionaryAsync(d => d.Id, d => d.FieldType);
foreach (var stack in stacks)
{
int fieldType = fieldTypes
.Where(x => x.Key.Equals(stack.FieldId)).Select(x => x.Value)
.FirstOrDefault();
if (fieldType == FieldType.Numeric)
{
await context.Entry(stack).Reference(x => x.StackDigital).LoadAsync();
var value = stack.StackDigital.Value;
NodePatternItem nodeItem = new(value, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
if (fieldType == FieldType.Boolean)
{
await context.Entry(stack).Reference(x => x.StackDigital).LoadAsync();
bool value = stack.StackDigital.Value == 1;
NodePatternItem nodeItem = new(value, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
if (fieldType == FieldType.DateTime)
{
await context.Entry(stack).Reference(x => x.StackDigital).LoadAsync();
DateTime value = new((long)stack.StackDigital.Value);
NodePatternItem nodeItem = new(value, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
if (fieldType == FieldType.Text)
{
await context.Entry(stack).Collection(x => x.StackTexts).LoadAsync();
List<string> values = stack.StackTexts.Select(x => x.Value).ToList();
string value = string.Concat(values);
NodePatternItem nodeItem = new(value, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
if (fieldType == FieldType.LinkSingle)
{
await context.Entry(stack).Collection(x => x.StackLists).LoadAsync();
var nodePatterns = new List<NodePattern>();
foreach (var stackList in stack.StackLists)
{
await context.Entry(stackList).Reference(x => x.Node).LoadAsync();
var listNode = stackList.Node;
await context.Entry(listNode).Collection(x => x.Stacks).LoadAsync();
await context.Entry(listNode).Reference(x => x.NodeExt).LoadAsync();
var catalogStacks = listNode.Stacks.ToList();
var nodePatternItems = await GetNodePatternItemsAsync(catalogStacks);
nodePatterns.Add(new()
{
NodeId = listNode.Id,
BunchId = listNode.BunchId,
Number = listNode.NodeExt.Number,
Items = nodePatternItems
});
}
NodePatternItem nodeItem = new(nodePatterns, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
if (fieldType == FieldType.File)
{
await context.Entry(stack).Collection(x => x.StackFiles).LoadAsync();
var fileDatas = new List<FileData>();
foreach(var stackFile in stack.StackFiles)
{
fileDatas.Add(new()
{
Name = stackFile.FileName,
Mime = stackFile.FileType,
ByteArray = stackFile.Data,
Size = stackFile.FileSize
});
}
NodePatternItem nodeItem = new(fileDatas, stack.FieldId, stack.CreatorInfo, stack.DateCreated);
nodeItem.NodeId = stack.NodeId;
nodeItems.Add(nodeItem);
}
}
return nodeItems;
}
}
}
| 43.090909 | 118 | 0.50326 | [
"MIT"
] | mtdkey/storage | src/RequestProvider/Node/RequestProvider.NodeHelper.cs | 5,216 | C# |
#region CopyrightHeader
//
// Copyright by Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using gov.va.medora.utils;
namespace gov.va.medora.mdo.dao.hl7.segments
{
public class MshSegment
{
EncodingCharacters encChars = new EncodingCharacters();
string sendingApp = "";
string sendingFacility = "";
string receivingApp = "";
string receivingFacility = "";
string timestamp = "";
string security = "";
string msgCode = "";
string eventTrigger = "";
string msgCtlId = "";
string processingId = "";
string versionId = "";
string sequenceNumber = "";
string continuationPointer = "";
string acceptAckType = "";
string appAckType = "";
string countryCode = "";
public MshSegment() {}
public MshSegment(string rawSegmentString)
{
parse(rawSegmentString);
}
public string SendingApplication
{
get { return sendingApp; }
set { sendingApp = value; }
}
public string SendingFacility
{
get { return sendingFacility; }
set { sendingFacility = value; }
}
public string ReceivingApplication
{
get { return receivingApp; }
set { receivingApp = value; }
}
public string ReceivingFacility
{
get { return receivingFacility; }
set { receivingFacility = value; }
}
public string Timestamp
{
get { return timestamp; }
set { timestamp = value; }
}
public string Security
{
get { return security; }
set { security = value; }
}
public string MessageCode
{
get { return msgCode; }
set { msgCode = value; }
}
public string EventTrigger
{
get { return eventTrigger; }
set { eventTrigger = value; }
}
public string MessageControlID
{
get { return msgCtlId; }
set { msgCtlId = value; }
}
public string ProcessingID
{
get { return processingId; }
set { processingId = value; }
}
public string VersionID
{
get { return versionId; }
set { versionId = value; }
}
public string SequenceNumber
{
get { return sequenceNumber; }
set { sequenceNumber = value; }
}
public string ContinuationPointer
{
get { return continuationPointer; }
set { continuationPointer = value; }
}
public string AcceptAckType
{
get { return acceptAckType; }
set { acceptAckType = value; }
}
public string ApplicationAckType
{
get { return appAckType; }
set { appAckType = value; }
}
public string CountryCode
{
get { return countryCode; }
set { countryCode = value; }
}
public EncodingCharacters EncodingChars
{
get { return encChars; }
set { encChars = value; }
}
public virtual void parse(string rawSegmentString)
{
if (rawSegmentString.Substring(0,3) != "MSH")
{
throw new Exception("Invalid MSH segment: incorrect header");
}
setSeparators(rawSegmentString);
string[] flds = StringUtils.split(rawSegmentString,EncodingChars.FieldSeparator);
if (flds.Length < 12)
{
throw new Exception("Invalid MSH segment: incorrect number of fields");
}
SendingApplication = flds[2];
SendingFacility = flds[3];
ReceivingApplication = flds[4];
ReceivingFacility = flds[5];
Timestamp = flds[6];
// TODO - Validate UTC timestamp
Security = flds[7];
if (StringUtils.isEmpty(flds[8]))
{
throw new Exception("Invalid MSH segment: missing message type");
}
string[] components = StringUtils.split(flds[8],EncodingChars.ComponentSeparator);
if (StringUtils.isEmpty(components[0]))
{
throw new Exception("Invalid MSH segment: incorrect message type fields");
}
MessageCode = components[0];
if (components.Length > 1)
{
EventTrigger = components[1];
}
if (StringUtils.isEmpty(flds[9]))
{
throw new Exception("Invalid MSH segment: missing message control ID");
}
MessageControlID = flds[9];
if (StringUtils.isEmpty(flds[10]))
{
throw new Exception("Invalid MSH segment: missing processing ID");
}
ProcessingID = flds[10];
if (StringUtils.isEmpty(flds[11]))
{
throw new Exception("Invalid MSH segment: missing version ID");
}
VersionID = flds[11];
if (flds.Length > 12)
{
SequenceNumber = flds[12];
}
if (flds.Length > 13)
{
ContinuationPointer = flds[13];
}
if (flds.Length > 14)
{
AcceptAckType = flds[14];
}
if (flds.Length > 15)
{
ApplicationAckType = flds[15];
}
if (flds.Length > 16)
{
CountryCode = flds[16];
}
}
internal void setSeparators(string s)
{
encChars = new EncodingCharacters(s[3], s.Substring(4, 8));
}
public string toSegment()
{
string result = "MSH" +
EncodingChars.FieldSeparator + EncodingChars.toString() +
EncodingChars.FieldSeparator + SendingApplication +
EncodingChars.FieldSeparator + SendingFacility +
EncodingChars.FieldSeparator + ReceivingApplication +
EncodingChars.FieldSeparator + ReceivingFacility +
EncodingChars.FieldSeparator + DateTime.Now.ToString("yyyyMMddhhmmss") +
EncodingChars.FieldSeparator + Security +
EncodingChars.FieldSeparator + MessageCode + EncodingChars.ComponentSeparator + EventTrigger +
EncodingChars.FieldSeparator + MessageControlID +
EncodingChars.FieldSeparator + ProcessingID +
EncodingChars.FieldSeparator + VersionID;
return result + '\r';
}
}
}
| 27.37594 | 110 | 0.546965 | [
"Apache-2.0"
] | marcsommer/mdo | mdo/src/mdo/dao/hl7/segments/MshSegment.cs | 7,282 | C# |
/*
* Copyright 2010-2013 OBS.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
*
*
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using OBS.Runtime;
namespace OBS.S3.Model
{
/// <summary>
/// Returns information about the DeleteCORSConfiguration response metadata.
/// The DeleteCORSConfiguration operation has a void result type.
/// </summary>
public partial class DeleteCORSConfigurationResponse : ObsWebServiceResponse
{
}
}
| 29.909091 | 80 | 0.729483 | [
"Apache-2.0"
] | huaweicloud/huaweicloud-sdk-net-dis | DotNet/eSDK_OBS_API/OBS.S3/Model/DeleteCORSConfigurationResponse.cs | 987 | C# |
using GameEstate.Core;
using System.Collections.Generic;
using System.IO;
namespace GameEstate.Formats.Binary.Tes.Records
{
public class LVSPRecord : Record
{
public override string ToString() => $"LVSP: {EDID.Value}";
public STRVField EDID { get; set; } // Editor ID
public BYTEField LVLD; // Chance
public BYTEField LVLF; // Flags
public List<LVLIRecord.LVLOField> LVLOs = new List<LVLIRecord.LVLOField>(); // Number of items in list
public override bool CreateField(BinaryReader r, TesFormat format, string type, int dataSize)
{
switch (type)
{
case "EDID": EDID = r.ReadSTRV(dataSize); return true;
case "LVLD": LVLD = r.ReadT<BYTEField>(dataSize); return true;
case "LVLF": LVLF = r.ReadT<BYTEField>(dataSize); return true;
case "LVLO": LVLOs.Add(new LVLIRecord.LVLOField(r, dataSize)); return true;
default: return false;
}
}
}
} | 39.111111 | 111 | 0.590909 | [
"MIT"
] | smorey2/GameEstate | src/GameExtensions/Tes/src/GameEstate.Extensions.Tes/Formats/Binary/Tes/Records/040-LVSP.Leveled Spell.cs | 1,058 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Notifications
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class ToastDismissedEventArgs
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.UI.Notifications.ToastDismissalReason Reason
{
get
{
throw new global::System.NotImplementedException("The member ToastDismissalReason ToastDismissedEventArgs.Reason is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.UI.Notifications.ToastDismissedEventArgs.Reason.get
}
}
| 39.173913 | 146 | 0.752497 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Notifications/ToastDismissedEventArgs.cs | 901 | C# |
using ProtoBuf.Meta;
using ProtoBuf.Serializers;
using System;
using System.Text;
namespace ProtoBuf.Internal
{
partial class PrimaryTypeProvider :
IMeasuringSerializer<string>,
IMeasuringSerializer<int>,
IMeasuringSerializer<long>,
IMeasuringSerializer<bool>,
IMeasuringSerializer<float>,
IMeasuringSerializer<double>,
IMeasuringSerializer<byte[]>,
IMeasuringSerializer<ArraySegment<byte>>,
IMeasuringSerializer<Memory<byte>>,
IMeasuringSerializer<ReadOnlyMemory<byte>>,
IMeasuringSerializer<byte>,
IMeasuringSerializer<ushort>,
IMeasuringSerializer<uint>,
IMeasuringSerializer<ulong>,
IMeasuringSerializer<sbyte>,
IMeasuringSerializer<short>,
IMeasuringSerializer<char>,
IMeasuringSerializer<Uri>,
IMeasuringSerializer<Type>,
IFactory<string>,
IFactory<byte[]>,
ISerializer<int?>,
ISerializer<long?>,
ISerializer<bool?>,
ISerializer<float?>,
ISerializer<double?>,
ISerializer<byte?>,
ISerializer<ushort?>,
ISerializer<uint?>,
ISerializer<ulong?>,
ISerializer<sbyte?>,
ISerializer<short?>,
ISerializer<char?>,
IValueChecker<string>,
IValueChecker<int>,
IValueChecker<long>,
IValueChecker<bool>,
IValueChecker<float>,
IValueChecker<double>,
IValueChecker<byte[]>,
IValueChecker<byte>,
IValueChecker<ushort>,
IValueChecker<uint>,
IValueChecker<ulong>,
IValueChecker<sbyte>,
IValueChecker<short>,
IValueChecker<char>,
IValueChecker<Uri>,
IValueChecker<Type>
{
string ISerializer<string>.Read(ref ProtoReader.State state, string value) => state.ReadString();
void ISerializer<string>.Write(ref ProtoWriter.State state, string value) => state.WriteString(value);
SerializerFeatures ISerializer<string>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<string>.Measure(ISerializationContext context, WireType wireType, string value)
=> wireType switch
{
WireType.String => ProtoWriter.UTF8.GetByteCount(value),
_ => -1,
};
int ISerializer<int>.Read(ref ProtoReader.State state, int value) => state.ReadInt32();
void ISerializer<int>.Write(ref ProtoWriter.State state, int value) => state.WriteInt32(value);
SerializerFeatures ISerializer<int>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<int>.Measure(ISerializationContext context, WireType wireType, int value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => value < 0 ? 10 : ProtoWriter.MeasureUInt32((uint)value),
WireType.SignedVarint => ProtoWriter.MeasureUInt32(ProtoWriter.Zig(value)),
_ => -1,
};
byte[] ISerializer<byte[]>.Read(ref ProtoReader.State state, byte[] value) => state.AppendBytes(value);
void ISerializer<byte[]>.Write(ref ProtoWriter.State state, byte[] value) => state.WriteBytes(value);
SerializerFeatures ISerializer<byte[]>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<byte[]>.Measure(ISerializationContext context, WireType wireType, byte[] value)
=> wireType switch
{
WireType.String => value.Length,
_ => -1,
};
ArraySegment<byte> ISerializer<ArraySegment<byte>>.Read(ref ProtoReader.State state, ArraySegment<byte> value) => state.AppendBytes(value);
void ISerializer<ArraySegment<byte>>.Write(ref ProtoWriter.State state, ArraySegment<byte> value) => state.WriteBytes(value);
SerializerFeatures ISerializer<ArraySegment<byte>>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<ArraySegment<byte>>.Measure(ISerializationContext context, WireType wireType, ArraySegment<byte> value)
=> wireType switch
{
WireType.String => value.Count,
_ => -1,
};
Memory<byte> ISerializer<Memory<byte>>.Read(ref ProtoReader.State state, Memory<byte> value) => state.AppendBytes(value);
void ISerializer<Memory<byte>>.Write(ref ProtoWriter.State state, Memory<byte> value) => state.WriteBytes(value);
SerializerFeatures ISerializer<Memory<byte>>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<Memory<byte>>.Measure(ISerializationContext context, WireType wireType, Memory<byte> value)
=> wireType switch
{
WireType.String => value.Length,
_ => -1,
};
ReadOnlyMemory<byte> ISerializer<ReadOnlyMemory<byte>>.Read(ref ProtoReader.State state, ReadOnlyMemory<byte> value) => state.AppendBytes(value);
void ISerializer<ReadOnlyMemory<byte>>.Write(ref ProtoWriter.State state, ReadOnlyMemory<byte> value) => state.WriteBytes(value);
SerializerFeatures ISerializer<ReadOnlyMemory<byte>>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<ReadOnlyMemory<byte>>.Measure(ISerializationContext context, WireType wireType, ReadOnlyMemory<byte> value)
=> wireType switch
{
WireType.String => value.Length,
_ => -1,
};
byte ISerializer<byte>.Read(ref ProtoReader.State state, byte value) => state.ReadByte();
void ISerializer<byte>.Write(ref ProtoWriter.State state, byte value) => state.WriteByte(value);
SerializerFeatures ISerializer<byte>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<byte>.Measure(ISerializationContext context, WireType wireType, byte value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt32(value),
_ => -1,
};
ushort ISerializer<ushort>.Read(ref ProtoReader.State state, ushort value) => state.ReadUInt16();
void ISerializer<ushort>.Write(ref ProtoWriter.State state, ushort value) => state.WriteUInt16(value);
SerializerFeatures ISerializer<ushort>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<ushort>.Measure(ISerializationContext context, WireType wireType, ushort value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt32(value),
_ => -1,
};
uint ISerializer<uint>.Read(ref ProtoReader.State state, uint value) => state.ReadUInt32();
void ISerializer<uint>.Write(ref ProtoWriter.State state, uint value) => state.WriteUInt32(value);
SerializerFeatures ISerializer<uint>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<uint>.Measure(ISerializationContext context, WireType wireType, uint value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt32(value),
_ => -1,
};
ulong ISerializer<ulong>.Read(ref ProtoReader.State state, ulong value) => state.ReadUInt64();
void ISerializer<ulong>.Write(ref ProtoWriter.State state, ulong value) => state.WriteUInt64(value);
SerializerFeatures ISerializer<ulong>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<ulong>.Measure(ISerializationContext context, WireType wireType, ulong value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt64(value),
_ => -1,
};
long ISerializer<long>.Read(ref ProtoReader.State state, long value) => state.ReadInt64();
void ISerializer<long>.Write(ref ProtoWriter.State state, long value) => state.WriteInt64(value);
SerializerFeatures ISerializer<long>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<long>.Measure(ISerializationContext context, WireType wireType, long value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt64((ulong)value),
WireType.SignedVarint => ProtoWriter.MeasureUInt64(ProtoWriter.Zig(value)),
_ => -1,
};
bool ISerializer<bool>.Read(ref ProtoReader.State state, bool value) => state.ReadBoolean();
void ISerializer<bool>.Write(ref ProtoWriter.State state, bool value) => state.WriteBoolean(value);
SerializerFeatures ISerializer<bool>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<bool>.Measure(ISerializationContext context, WireType wireType, bool value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => 1,
_ => -1,
};
float ISerializer<float>.Read(ref ProtoReader.State state, float value) => state.ReadSingle();
void ISerializer<float>.Write(ref ProtoWriter.State state, float value) => state.WriteSingle(value);
SerializerFeatures ISerializer<float>.Features => SerializerFeatures.WireTypeFixed32 | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<float>.Measure(ISerializationContext context, WireType wireType, float value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
_ => -1,
};
double ISerializer<double>.Read(ref ProtoReader.State state, double value) => state.ReadDouble();
void ISerializer<double>.Write(ref ProtoWriter.State state, double value) => state.WriteDouble(value);
SerializerFeatures ISerializer<double>.Features => SerializerFeatures.WireTypeFixed64 | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<double>.Measure(ISerializationContext context, WireType wireType, double value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
_ => -1,
};
sbyte ISerializer<sbyte>.Read(ref ProtoReader.State state, sbyte value) => state.ReadSByte();
void ISerializer<sbyte>.Write(ref ProtoWriter.State state, sbyte value) => state.WriteSByte(value);
SerializerFeatures ISerializer<sbyte>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<sbyte>.Measure(ISerializationContext context, WireType wireType, sbyte value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => value < 0 ? 10 : ProtoWriter.MeasureUInt32((uint)value),
WireType.SignedVarint => ProtoWriter.MeasureUInt32(ProtoWriter.Zig(value)),
_ => -1,
};
short ISerializer<short>.Read(ref ProtoReader.State state, short value) => state.ReadInt16();
void ISerializer<short>.Write(ref ProtoWriter.State state, short value) => state.WriteInt16(value);
SerializerFeatures ISerializer<short>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<short>.Measure(ISerializationContext context, WireType wireType, short value)
=> wireType switch
{
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => value < 0 ? 10 : ProtoWriter.MeasureUInt32((uint)value),
WireType.SignedVarint => ProtoWriter.MeasureUInt32(ProtoWriter.Zig(value)),
_ => -1,
};
Uri ISerializer<Uri>.Read(ref ProtoReader.State state, Uri value)
{
var uri = state.ReadString();
return string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute);
}
void ISerializer<Uri>.Write(ref ProtoWriter.State state, Uri value) => state.WriteString(value.OriginalString);
SerializerFeatures ISerializer<Uri>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<Uri>.Measure(ISerializationContext context, WireType wireType, Uri value)
=> wireType switch
{
WireType.String => ProtoWriter.UTF8.GetByteCount(value.OriginalString),
_ => -1,
};
char ISerializer<char>.Read(ref ProtoReader.State state, char value) => (char)state.ReadUInt16();
void ISerializer<char>.Write(ref ProtoWriter.State state, char value) => state.WriteUInt16(value);
SerializerFeatures ISerializer<char>.Features => SerializerFeatures.WireTypeVarint | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<char>.Measure(ISerializationContext context, WireType wireType, char value)
=> wireType switch {
WireType.Fixed32 => 4,
WireType.Fixed64 => 8,
WireType.Varint => ProtoWriter.MeasureUInt32(value),
_ => -1,
};
string IFactory<string>.Create(ISerializationContext context) => "";
byte[] IFactory<byte[]>.Create(ISerializationContext context) => Array.Empty<byte>();
SerializerFeatures ISerializer<int?>.Features => ((ISerializer<int>)this).Features;
void ISerializer<int?>.Write(ref ProtoWriter.State state, int? value) => ((ISerializer<int>)this).Write(ref state, value.Value);
int? ISerializer<int?>.Read(ref ProtoReader.State state, int? value) => ((ISerializer<int>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<short?>.Features => ((ISerializer<short>)this).Features;
void ISerializer<short?>.Write(ref ProtoWriter.State state, short? value) => ((ISerializer<short>)this).Write(ref state, value.Value);
short? ISerializer<short?>.Read(ref ProtoReader.State state, short? value) => ((ISerializer<short>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<long?>.Features => ((ISerializer<long>)this).Features;
void ISerializer<long?>.Write(ref ProtoWriter.State state, long? value) => ((ISerializer<long>)this).Write(ref state, value.Value);
long? ISerializer<long?>.Read(ref ProtoReader.State state, long? value) => ((ISerializer<long>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<sbyte?>.Features => ((ISerializer<sbyte>)this).Features;
void ISerializer<sbyte?>.Write(ref ProtoWriter.State state, sbyte? value) => ((ISerializer<sbyte>)this).Write(ref state, value.Value);
sbyte? ISerializer<sbyte?>.Read(ref ProtoReader.State state, sbyte? value) => ((ISerializer<sbyte>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<uint?>.Features => ((ISerializer<uint>)this).Features;
void ISerializer<uint?>.Write(ref ProtoWriter.State state, uint? value) => ((ISerializer<uint>)this).Write(ref state, value.Value);
uint? ISerializer<uint?>.Read(ref ProtoReader.State state, uint? value) => ((ISerializer<uint>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<ushort?>.Features => ((ISerializer<ushort>)this).Features;
void ISerializer<ushort?>.Write(ref ProtoWriter.State state, ushort? value) => ((ISerializer<ushort>)this).Write(ref state, value.Value);
ushort? ISerializer<ushort?>.Read(ref ProtoReader.State state, ushort? value) => ((ISerializer<ushort>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<ulong?>.Features => ((ISerializer<ulong>)this).Features;
void ISerializer<ulong?>.Write(ref ProtoWriter.State state, ulong? value) => ((ISerializer<ulong>)this).Write(ref state, value.Value);
ulong? ISerializer<ulong?>.Read(ref ProtoReader.State state, ulong? value) => ((ISerializer<ulong>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<byte?>.Features => ((ISerializer<byte>)this).Features;
void ISerializer<byte?>.Write(ref ProtoWriter.State state, byte? value) => ((ISerializer<byte>)this).Write(ref state, value.Value);
byte? ISerializer<byte?>.Read(ref ProtoReader.State state, byte? value) => ((ISerializer<byte>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<char?>.Features => ((ISerializer<char>)this).Features;
void ISerializer<char?>.Write(ref ProtoWriter.State state, char? value) => ((ISerializer<char>)this).Write(ref state, value.Value);
char? ISerializer<char?>.Read(ref ProtoReader.State state, char? value) => ((ISerializer<char>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<bool?>.Features => ((ISerializer<bool>)this).Features;
void ISerializer<bool?>.Write(ref ProtoWriter.State state, bool? value) => ((ISerializer<bool>)this).Write(ref state, value.Value);
bool? ISerializer<bool?>.Read(ref ProtoReader.State state, bool? value) => ((ISerializer<bool>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<float?>.Features => ((ISerializer<float>)this).Features;
void ISerializer<float?>.Write(ref ProtoWriter.State state, float? value) => ((ISerializer<float>)this).Write(ref state, value.Value);
float? ISerializer<float?>.Read(ref ProtoReader.State state, float? value) => ((ISerializer<float>)this).Read(ref state, value.GetValueOrDefault());
SerializerFeatures ISerializer<double?>.Features => ((ISerializer<double>)this).Features;
void ISerializer<double?>.Write(ref ProtoWriter.State state, double? value) => ((ISerializer<double>)this).Write(ref state, value.Value);
double? ISerializer<double?>.Read(ref ProtoReader.State state, double? value) => ((ISerializer<double>)this).Read(ref state, value.GetValueOrDefault());
Type ISerializer<Type>.Read(ref ProtoReader.State state, Type value) => state.ReadType();
void ISerializer<Type>.Write(ref ProtoWriter.State state, Type value) => state.WriteType(value);
SerializerFeatures ISerializer<Type>.Features => SerializerFeatures.WireTypeString | SerializerFeatures.CategoryScalar;
int IMeasuringSerializer<Type>.Measure(ISerializationContext context, WireType wireType, Type value)
=> wireType switch
{
WireType.String => Encoding.UTF8.GetByteCount(TypeModel.SerializeType(context?.Model, value)),
_ => -1,
};
bool IValueChecker<string>.HasNonTrivialValue(string value) => value is not null; // note: we write "" (when found), for compat
bool IValueChecker<Uri>.HasNonTrivialValue(Uri value) => value?.OriginalString is not null; // note: we write "" (when found), for compat
bool IValueChecker<Type>.HasNonTrivialValue(Type value) => value is not null;
bool IValueChecker<byte[]>.HasNonTrivialValue(byte[] value) => value is not null; // note: we write [] (when found), for compat
bool IValueChecker<sbyte>.HasNonTrivialValue(sbyte value) => value != 0;
bool IValueChecker<short>.HasNonTrivialValue(short value) => value != 0;
bool IValueChecker<int>.HasNonTrivialValue(int value) => value != 0;
bool IValueChecker<long>.HasNonTrivialValue(long value) => value != 0;
bool IValueChecker<byte>.HasNonTrivialValue(byte value) => value != 0;
bool IValueChecker<ushort>.HasNonTrivialValue(ushort value) => value != 0;
bool IValueChecker<uint>.HasNonTrivialValue(uint value) => value != 0;
bool IValueChecker<ulong>.HasNonTrivialValue(ulong value) => value != 0;
bool IValueChecker<char>.HasNonTrivialValue(char value) => value != 0;
bool IValueChecker<bool>.HasNonTrivialValue(bool value) => value;
bool IValueChecker<float>.HasNonTrivialValue(float value) => value != 0;
bool IValueChecker<double>.HasNonTrivialValue(double value) => value != 0;
bool IValueChecker<sbyte>.IsNull(sbyte value) => false;
bool IValueChecker<short>.IsNull(short value) => false;
bool IValueChecker<int>.IsNull(int value) => false;
bool IValueChecker<long>.IsNull(long value) => false;
bool IValueChecker<byte>.IsNull(byte value) => false;
bool IValueChecker<ushort>.IsNull(ushort value) => false;
bool IValueChecker<uint>.IsNull(uint value) => false;
bool IValueChecker<ulong>.IsNull(ulong value) => false;
bool IValueChecker<char>.IsNull(char value) => false;
bool IValueChecker<bool>.IsNull(bool value) => false;
bool IValueChecker<float>.IsNull(float value) => false;
bool IValueChecker<double>.IsNull(double value) => false;
bool IValueChecker<string>.IsNull(string value) => value is null;
bool IValueChecker<byte[]>.IsNull(byte[] value) => value is null;
bool IValueChecker<Uri>.IsNull(Uri value) => value is null;
bool IValueChecker<Type>.IsNull(Type value) => value is null;
}
}
| 59.705094 | 160 | 0.667939 | [
"Apache-2.0"
] | mgravell/protobuf-net | src/protobuf-net.Core/Internal/PrimaryTypeProvider.Primitives.cs | 22,272 | C# |
using System;
using System.Data.SqlClient;
using System.Linq;
using AutoMapper;
using ZNCHANY.Api.Entities;
using ZNCHANY.Api.Entities.Enums;
using ZNCHANY.Api.Extensions;
using ZNCHANY.Api.Extensions.AuthContext;
using ZNCHANY.Api.Extensions.CustomException;
using ZNCHANY.Api.Extensions.DataAccess;
using ZNCHANY.Api.Models.Response;
using ZNCHANY.Api.RequestPayload.Rbac.Role;
using ZNCHANY.Api.Utils;
using ZNCHANY.Api.ViewModels.Rbac.DncRole;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ZNCHANY.Api.RequestPayload.Rbac.Chlist;
using ZNCHANY.Api.ViewModels.Rbac.Dncchlist;
using System.Transactions;
using System.Collections.Generic;
using ZNCHANY.Api.Utils;
using MySql.Data.MySqlClient;
namespace ZNCHANY.Api.Controllers.Api.ZNCHANY1
{
/// <summary>
///
/// </summary>
//[CustomAuthorize]
[Route("api/ZNCHANY1/[controller]/[action]")]
[ApiController]
//[CustomAuthorize]
public class DncchlistController : ControllerBase
{
private readonly ZNCHANYDbContext _dbContext;
private readonly IMapper _mapper;
/// <summary>
/// 构造control
/// </summary>
/// <param name="dbContext"></param>
/// <param name="mapper"></param>
public DncchlistController(ZNCHANYDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
[HttpGet]
public IActionResult List()
{
using (_dbContext)
{
var list = _dbContext.Dncchlist.ToList();
list = list.FindAll(x => x.IsDeleted != CommonEnum.IsDeleted.Yes );
var response = ResponseModelFactory.CreateInstance;
response.SetData(list);
return Ok(response);
}
}
[HttpGet]
public IActionResult RunPush(int bid,int type)
{
var response = ResponseModelFactory.CreateInstance;
//ZNCHANY.Api.dataoperate.Chcompute.ZNCHANYrun(bid, DateTime.Now, type);
response.SetSuccess("ok");
return Ok(response);
}
/// <summary>
/// 查询请求
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult List(DncchlistRequestPayload payload)
{
var response = ResponseModelFactory.CreateResultInstance;
using (_dbContext)
{
var query = _dbContext.Dncchlist.Include(x=>x.DncChqpoint.DncChtype).AsQueryable();
//模糊查询
if (!string.IsNullOrEmpty(payload.Kw))
{
query = query.Where(x => x.K_Name_kw.Contains(payload.Kw.Trim()) );
}
//是否删除,是否启用
if (payload.IsDeleted > CommonEnum.IsDeleted.All)
{
query = query.Where(x => x.IsDeleted == payload.IsDeleted);
}
if (payload.Status > CommonEnum.Status.All)
{
query = query.Where(x => x.Status == payload.Status);
}
if (payload.boilerid != -1)
{
query = query.Where(x => x.DncBoilerId == payload.boilerid);
}
if (payload.FirstSort != null)
{
query = query.OrderBy(payload.FirstSort.Field, payload.FirstSort.Direct == "DESC");
}
var list = query.Paged(payload.CurrentPage, payload.PageSize).ToList();
var totalCount = query.Count();
foreach (var item in list)
{
item.Remarks = item.DncChqpoint.DncChtype.Ch_time_Val+"";
}
var data = list.Select(_mapper.Map< Dncchlist, DncchlistJsonModel>);
response.SetData(data, totalCount);
return Ok(response);
}
}
/// <summary>
/// 创建
/// </summary>
/// <param name="model">视图实体</param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(200)]
public IActionResult Create(DncchlistCreateViewModel model)
{
var response = ResponseModelFactory.CreateInstance;
if (model.K_Name_kw.Trim().Length <= 0)
{
response.SetFailed("请输入吹灰器描述");
return Ok(response);
}
using (_dbContext)
{
//3 只有未删除的有重复才提示
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == model.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.No) > 0)
{
response.SetFailed(model.K_Name_kw+"已存在");
return Ok(response);
}
//4 删除的有重复就真删掉
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == model.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.Yes) > 0)
{
var entity2 = _dbContext.Dncchlist.FirstOrDefault(x => x.K_Name_kw == model.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.Yes);
_dbContext.Dncchlist.Remove(entity2);
}
var entity = _mapper.Map< DncchlistCreateViewModel, Dncchlist>(model);
entity.DncChqpoint = _dbContext.Dncchqpoint.FirstOrDefault(x => (x.Name_kw + "") == model.DncChqpoint_Name);
entity.DncChqpoint_Name = entity.DncChqpoint.Name_kw;
entity.DncBoiler = _dbContext.Dncboiler.FirstOrDefault(x => (x.K_Name_kw + "") == model.DncBoiler_Name);
entity.DncBoiler_Name = entity.DncBoiler.K_Name_kw;
entity.Status = CommonEnum.Status.Normal;
_dbContext.Dncchlist.Add(entity);
_dbContext.SaveChanges();
response.SetSuccess();
return Ok(response);
}
}
/// <summary>
/// 编辑页获取实体
/// </summary>
/// <param name="code">惟一编码</param>
/// <returns></returns>
[HttpGet("{code}")]
[ProducesResponseType(200)]
public IActionResult Edit(string code)
{
using (_dbContext)
{
var entity = _dbContext.Dncchlist.FirstOrDefault(x => x.Id == int.Parse(code));
var response = ResponseModelFactory.CreateInstance;
response.SetData(_mapper.Map< Dncchlist, DncchlistCreateViewModel>(entity));
return Ok(response);
}
}
/// <summary>
/// 保存编辑后的信息
/// </summary>
/// <param name="model">视图实体</param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(200)]
public IActionResult Edit(DncchlistEditViewModel model)
{
var response = ResponseModelFactory.CreateInstance;
using (_dbContext)
{
var entity = _dbContext.Dncchlist.FirstOrDefault(x => x.Id == model.Id);
//1 未删除的其他记录重复校验 K_Name_kw
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == model.K_Name_kw && x.Id != model.Id && x.IsDeleted == CommonEnum.IsDeleted.No) > 0 )
{
response.SetFailed(model.K_Name_kw + "已存在");
return Ok(response);
}
//2 已删除的其他记录重复的真删 K_Name_kw
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == model.K_Name_kw && x.Id != model.Id && x.IsDeleted == CommonEnum.IsDeleted.Yes) > 0)
{
var entity2 = _dbContext.Dncchlist.FirstOrDefault(x => x.K_Name_kw == model.K_Name_kw && x.Id != model.Id && x.IsDeleted == CommonEnum.IsDeleted.Yes);
_dbContext.Dncchlist.Remove(entity2);
}
entity.K_Name_kw = model.K_Name_kw;
entity.AddTime = model.AddTime;
entity.RunTime = model.RunTime;
entity.Remarks = model.Remarks;
entity.DncChqpoint = _dbContext.Dncchqpoint.FirstOrDefault(x => x.Name_kw == model.DncChqpoint_Name);
entity.DncChqpoint_Name = entity.DncChqpoint.Name_kw;
entity.DncChqpoint_Name = model.DncChqpoint_Name;
entity.Wrl_Val = model.Wrl_Val;
entity.Wrlhigh_Val = model.Wrlhigh_Val;
entity.AddReason = model.AddReason;
entity.DncBoiler = _dbContext.Dncboiler.FirstOrDefault(x => x.K_Name_kw == model.DncBoiler_Name);
entity.DncBoiler_Name = entity.DncBoiler.K_Name_kw;
entity.DncBoiler_Name = model.DncBoiler_Name;
entity.Status = model.Status;
entity.IsDeleted = model.IsDeleted;
_dbContext.SaveChanges();
return Ok(response);
}
}
/// <summary>
/// 删除
/// </summary>
/// <param name="ids">ID,多个以逗号分隔</param>
/// <returns></returns>
[HttpGet("{ids}")]
[ProducesResponseType(200)]
public IActionResult Delete(string ids)
{
var response = ResponseModelFactory.CreateInstance;
response = UpdateIsDelete(CommonEnum.IsDeleted.Yes, ids);
return Ok(response);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="isDeleted"></param>
/// <param name="ids">ID字符串,多个以逗号隔开</param>
/// <returns></returns>
private ResponseModel UpdateIsDelete(CommonEnum.IsDeleted isDeleted, string ids)
{
using (_dbContext)
{
if (ToolService.DbType.Equals("mysql")){
var parameters = ids.Split(",").Select((id, index) => new MySqlParameter(string.Format("@p{0}", index), id)).ToList();
var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
var sql = string.Format("UPDATE Dncchlist SET IsDeleted=@IsDeleted WHERE id IN ({0})", parameterNames);
parameters.Add(new MySqlParameter("@IsDeleted", (int)isDeleted));
_dbContext.Database.ExecuteSqlCommand(sql, parameters);
var response = ResponseModelFactory.CreateInstance;
return response;
}else{
var parameters = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList();
var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
var sql = string.Format("UPDATE Dncchlist SET IsDeleted=@IsDeleted WHERE id IN ({0})", parameterNames);
parameters.Add(new SqlParameter("@IsDeleted", (int)isDeleted));
_dbContext.Database.ExecuteSqlCommand(sql, parameters);
var response = ResponseModelFactory.CreateInstance;
return response;
}
}
}
/// <summary>
/// 恢复
/// </summary>
/// <param name="ids">ID,多个以逗号分隔</param>
/// <returns></returns>
[HttpGet("{ids}")]
[ProducesResponseType(200)]
public IActionResult Recover(string ids)
{
var response = UpdateIsDelete(CommonEnum.IsDeleted.No, ids);
return Ok(response);
}
/// <summary>
/// 批量更新状态
/// </summary>
/// <param name="status">状态</param>
/// <param name="ids">ID字符串,多个以逗号隔开</param>
/// <returns></returns>
private ResponseModel UpdateStatus(UserStatus status, string ids)
{
using (_dbContext)
{
if (ToolService.DbType.Equals("mysql")){
var parameters = ids.Split(",").Select((id, index) => new MySqlParameter(string.Format("@p{0}", index), id)).ToList();
var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
var sql = string.Format("UPDATE Dncchlist SET Status=@Status WHERE id IN ({0})", parameterNames);
parameters.Add(new MySqlParameter("@Status", (int)status));
_dbContext.Database.ExecuteSqlCommand(sql, parameters);
var response = ResponseModelFactory.CreateInstance;
return response;
}else{
var parameters = ids.Split(",").Select((id, index) => new SqlParameter(string.Format("@p{0}", index), id)).ToList();
var parameterNames = string.Join(", ", parameters.Select(p => p.ParameterName));
var sql = string.Format("UPDATE Dncchlist SET Status=@Status WHERE id IN ({0})", parameterNames);
parameters.Add(new SqlParameter("@Status", (int)status));
_dbContext.Database.ExecuteSqlCommand(sql, parameters);
var response = ResponseModelFactory.CreateInstance;
return response;
}
}
}
/// <summary>
/// 批量操作
/// </summary>
/// <param name="command"></param>
/// <param name="ids">ID,多个以逗号分隔</param>
/// <returns></returns>
[HttpGet]
[ProducesResponseType(200)]
public IActionResult Batch(string command, string ids)
{
var response = ResponseModelFactory.CreateInstance;
switch (command)
{
case "delete":
response = UpdateIsDelete(CommonEnum.IsDeleted.Yes, ids);
break;
case "recover":
response = UpdateIsDelete(CommonEnum.IsDeleted.No, ids);
break;
case "forbidden":
response = UpdateStatus(UserStatus.Forbidden, ids);
break;
case "normal":
response = UpdateStatus(UserStatus.Normal, ids);
break;
default:
break;
}
return Ok(response);
}
/// <summary>
/// 批量创建
/// </summary>
[HttpPost]
[ProducesResponseType(200)]
public IActionResult BatchCreate(string fsts)
{
var response = ResponseModelFactory.CreateInstance;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (_dbContext)
{
KeyValuePair<string, List< DncchlistCreateViewModel>> res = ValidateJson.Validation< DncchlistCreateViewModel>(fsts);
if (res.Key.Equals("ok"))
{
List< DncchlistCreateViewModel> arr = res.Value;
foreach ( DncchlistCreateViewModel item in arr)
{
if (item.K_Name_kw.Trim().Length <= 0)
{
response.SetFailed("请输入吹灰器描述");
return Ok(response);
}
//5 只有未删除的有重复才提示
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == item.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.No) > 0)
{
response.SetFailed(item.K_Name_kw+"已存在");
return Ok(response);
}
//6 删除的有重复就真删掉
if (_dbContext.Dncchlist.Count(x => x.K_Name_kw == item.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.Yes) > 0)
{
var entity2 = _dbContext.Dncchlist.FirstOrDefault(x => x.K_Name_kw == item.K_Name_kw && x.IsDeleted == CommonEnum.IsDeleted.Yes);
_dbContext.Dncchlist.Remove(entity2);
}
var entity = _mapper.Map< DncchlistCreateViewModel, Dncchlist>(item);
entity.DncChqpoint = _dbContext.Dncchqpoint.FirstOrDefault(x => x.Name_kw == item.DncChqpoint_Name);
entity.DncBoiler = _dbContext.Dncboiler.FirstOrDefault(x => x.K_Name_kw == item.DncBoiler_Name);
entity.Status = CommonEnum.Status.Normal;
_dbContext.Dncchlist.Add(entity);
}
}
else
{
response.SetFailed(res.Key + " 数据格式有误.");
return Ok(response);
}
_dbContext.SaveChanges();
}
// 如果所有的操作都执行成功,则Complete()会被调用来提交事务
// 如果发生异常,则不会调用它并回滚事务
scope.Complete();
}
response.SetSuccess();
return Ok(response);
}
catch (Exception ex)
{
response.SetFailed(ex.Message);
return Ok(response);
}
}
}
}
| 39.616408 | 170 | 0.50417 | [
"Apache-2.0"
] | zazzlec/znchany | ZNCHANY.Api/Controllers/Api/ZNRS1/ch/DncchlistController.cs | 18,373 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OldiEraser.Common
{
public class DateTimeProvider : IDateTimeProvider
{
public DateTime Now => DateTime.Now;
}
}
| 18.714286 | 53 | 0.732824 | [
"MIT"
] | shoter/OldiEraser | OldiEraser.Common/DateTimeProvider.cs | 264 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Box.V2.Models
{
/// <summary>
/// Box representation of a retention assignment
/// </summary>
public class BoxRetentionPolicyAssignment : BoxEntity
{
public const string FieldRetentionPolicy = "retention_policy";
public const string FieldAssignedTo = "assigned_to";
public const string FieldAssignedBy = "assigned_by";
public const string FieldAssignedAt = "assigned_at";
public const string FieldFilterFields = "filter_fields";
/// <summary>
/// A mini retention policy object representing the retention policy that has been assigned to this content.
/// </summary>
[JsonProperty(PropertyName = FieldRetentionPolicy)]
public virtual BoxRetentionPolicy RetentionPolicy { get; set; }
/// <summary>
/// The type and id of the content that is under retention. The type can either be folder or enterprise.
/// </summary>
[JsonProperty(PropertyName = FieldAssignedTo)]
public virtual BoxEntity AssignedTo { get; set; }
/// <summary>
/// A mini user object representing the user that created the retention policy assignment.
/// </summary>
[JsonProperty(PropertyName = FieldAssignedBy)]
public virtual BoxUser AssignedBy { get; set; }
/// <summary>
/// The time that the retention policy assignment was created.
/// </summary>
[JsonProperty(PropertyName = FieldAssignedAt)]
public virtual DateTimeOffset? AssignedAt { get; set; }
/// <summary>
/// Optional field filters for an assignment to a metadata template
/// </summary>
[JsonProperty(PropertyName = FieldFilterFields)]
public virtual List<BoxMetadataFieldFilter> FilterFields { get; set; }
}
}
| 39.673469 | 117 | 0.643519 | [
"Apache-2.0"
] | box/box-windows-sdk-v2 | Box.V2/Models/BoxRetentionPolicyAssignment.cs | 1,944 | C# |
using GitVersion.BuildAgents;
using GitVersion.Common;
using GitVersion.Configuration;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.VersionCalculation;
using GitVersion.VersionCalculation.Cache;
using GitVersion.VersionConverters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace GitVersion;
public class GitVersionCoreModule : IGitVersionModule
{
public void RegisterTypes(IServiceCollection services)
{
services.AddSingleton<ILog, Log>();
services.AddSingleton<IFileSystem, FileSystem>();
services.AddSingleton<IEnvironment, Environment>();
services.AddSingleton<IConsole, ConsoleAdapter>();
services.AddSingleton<IGitVersionCache, GitVersionCache>();
services.AddSingleton<IGitVersionCacheKeyFactory, GitVersionCacheKeyFactory>();
services.AddSingleton<IGitVersionCalculateTool, GitVersionCalculateTool>();
services.AddSingleton<IGitVersionOutputTool, GitVersionOutputTool>();
services.AddSingleton<IGitPreparer, GitPreparer>();
services.AddSingleton<IRepositoryStore, RepositoryStore>();
services.AddSingleton<IGitVersionContextFactory, GitVersionContextFactory>();
services.AddSingleton(sp =>
{
var options = sp.GetService<IOptions<GitVersionOptions>>();
var contextFactory = sp.GetService<IGitVersionContextFactory>();
return new Lazy<GitVersionContext?>(() => contextFactory?.Create(options?.Value));
});
services.AddModule(new BuildServerModule());
services.AddModule(new ConfigurationModule());
services.AddModule(new VersionCalculationModule());
services.AddModule(new VersionConvertersModule());
}
}
| 38.73913 | 94 | 0.745791 | [
"MIT"
] | GitTools/GitVersion | src/GitVersion.Core/GitVersionCoreModule.cs | 1,782 | C# |
namespace DocoptNet.Tests
{
using NUnit.Framework;
[TestFixture]
public class ShortOptionsErrorHandlingTests
{
[Test]
public void Duplicate()
{
Assert.Throws<DocoptLanguageErrorException>(
() => new Docopt().Apply("Usage: prog -x\nOptions: -x this\n -x that"));
}
[Test]
public void Non_existent()
{
Assert.Throws<DocoptInputErrorException>(
() => new Docopt().Apply("Usage: prog", "-x"));
}
[Test]
public void Wrong_opt_with_arg_spec()
{
Assert.Throws<DocoptLanguageErrorException>(
() => new Docopt().Apply("Usage: prog -o\nOptions: -o ARG"));
}
[Test]
public void Wrong_missing_arg()
{
Assert.Throws<DocoptInputErrorException>(
() => new Docopt().Apply("Usage: prog -o ARG\nOptions: -o ARG", "-o"));
}
}
}
| 26.351351 | 90 | 0.521026 | [
"MIT"
] | GerHobbelt/docopt.net | tests/DocoptNet.Tests/ShortOptionsErrorHandlingTests.cs | 975 | C# |
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Radzen.Blazor;
using Radzen.Blazor.GridColumnVisibilityChooser.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Radzen.Blazor.GridColumnVisibilityChooser
{
public partial class RadzenGridColumnVisibilityChooser<TItem>
{
[Parameter]
public RadzenDataGrid<TItem> Grid { get; set; }
[Parameter]
public Action RefreshParentStateAction { get; set; }
[Parameter]
public Func<string, bool> GetDefaultVisibility { get; set; }
[Parameter]
public string Placeholder { get; set; }
[Parameter]
public bool PreserveState { get; set; }
[Parameter]
public string SelectAllText { get; set; }
[Parameter]
public string SelectedItemsText { get; set; } = "items selected";
[Parameter]
public int MaxSelectedLabels { get; set; } = 4;
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public ILocalStorageService LocalStorageService { get; set; }
public IEnumerable<Tuple<string, string>> Columns { get; private set; }
public IEnumerable<string> VisibleColumns { get; private set; }
bool _isInitialVisibilitySet { get; set; }
public static string ColumnVisibilityLocalStorageIdentifier => $"radzen-blazor-gridcolumnvisibilities";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (Grid != null && !_isInitialVisibilitySet)
{
//Collection initial data
Columns = Grid.ColumnsCollection.Select(x => new Tuple<string, string>(String.IsNullOrEmpty(x.Property) ? x.Title : x.Property, x.Title)).ToList();
//Check local storage and apply if found
if (PreserveState && !_isInitialVisibilitySet)
{
var columnVisibilities = await GetPreservedColumnVisibility();
if (columnVisibilities != null && columnVisibilities.Any())
{
foreach (var col in columnVisibilities)
{
if (Grid.ColumnsCollection.Any(x => x.Title == col.ColumnName || x.Property == col.ColumnName))
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
Grid.ColumnsCollection.FirstOrDefault(x => x.Title == col.ColumnName || x.Property == col.ColumnName).Visible = col.IsVisible;
#pragma warning restore BL0005 // Component parameter should not be set outside of its component.
}
_isInitialVisibilitySet = true;
//Refresh parent component
RefreshParentStateAction();
}
}
else if (!_isInitialVisibilitySet)
await ClearColumnVisibilityFromStorage();
//Set default visibility
if (GetDefaultVisibility != null && !_isInitialVisibilitySet)
{
foreach (var col in Columns)
{
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
Grid.ColumnsCollection.FirstOrDefault(x => x.Title == col.Item2 || x.Property == col.Item1).Visible = GetDefaultVisibility(col.Item2);
#pragma warning restore BL0005 // Component parameter should not be set outside of its component.
}
_isInitialVisibilitySet = true;
//Refresh parent component
RefreshParentStateAction();
}
VisibleColumns = Grid.ColumnsCollection.Where(x => x.Visible).Select(x => String.IsNullOrEmpty(x.Property) ? x.Title : x.Property).ToList();
InvokeAsync(StateHasChanged);
}
}
async void OnColumnVisibilityChanged(object value)
{
var converted = value as IEnumerable<string>;
if (converted != null)
{
var diff = Columns.Where(x => !converted.Contains(x.Item1)).ToList();
foreach (var d in diff)
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
Grid.ColumnsCollection.FirstOrDefault(x => x.Title == d.Item2 || x.Property == d.Item1).Visible = false;
#pragma warning restore BL0005 // Component parameter should not be set outside of its component.
var same = Columns.Where(x => converted.Contains(x.Item1)).ToList();
foreach (var s in same)
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
Grid.ColumnsCollection.FirstOrDefault(x => x.Title == s.Item2 || x.Property == s.Item1).Visible = true;
#pragma warning restore BL0005 // Component parameter should not be set outside of its component.
//Refresh parent component
RefreshParentStateAction();
//If preservation is enabled, preserve state
if (PreserveState)
await PreserveColumnVisibility(Grid.ColumnsCollection.Select(x => new ColumnVisibility()
{
ColumnName = String.IsNullOrEmpty(x.Property) ? x.Title : x.Property,
IsVisible = x.Visible
}));
}
}
/// <summary>
/// If there're any, gets preserved column visibility from local storage
/// </summary>
/// <returns>List of column names</returns>
public async Task<IEnumerable<ColumnVisibility>> GetPreservedColumnVisibility()
{
var identifier = GetPageIdentifier();
var htmlId = GetGridIdentifier();
var containsKey = await LocalStorageService.ContainKeyAsync(ColumnVisibilityLocalStorageIdentifier);
if (!containsKey)
return new List<ColumnVisibility>();
var visibilities = await LocalStorageService.GetItemAsync<IEnumerable<ColumnsVisibility>>(ColumnVisibilityLocalStorageIdentifier);
if (visibilities == null || !visibilities.Any())
return new List<ColumnVisibility>();
var pageVisibilities = visibilities.FirstOrDefault(x => x.PageIdentifier == identifier &&
x.HtmlId == htmlId);
if (pageVisibilities == null)
return new List<ColumnVisibility>();
return pageVisibilities.Visibilities;
}
/// <summary>
/// Preserves the state of column visibility
/// </summary>
/// <param name="visibilities"></param>
/// <returns></returns>
public async Task PreserveColumnVisibility(IEnumerable<ColumnVisibility> visibilities)
{
var identifier = GetPageIdentifier();
var htmlId = GetGridIdentifier();
var containsKey = await LocalStorageService.ContainKeyAsync(ColumnVisibilityLocalStorageIdentifier);
List<ColumnsVisibility> data;
if (containsKey)
{
data = await LocalStorageService.GetItemAsync<List<ColumnsVisibility>>(ColumnVisibilityLocalStorageIdentifier);
var pageVisibility = data.FirstOrDefault(x => x.PageIdentifier == identifier &&
x.HtmlId == htmlId);
//If page data is found, just update visibilities
if (pageVisibility != null)
data[data.IndexOf(pageVisibility)].Visibilities = visibilities;
//if it isn't, add new item
else
data.Add(new ColumnsVisibility() { PageIdentifier = identifier, Visibilities = visibilities, HtmlId = htmlId });
}
else
data = new List<ColumnsVisibility>()
{
new ColumnsVisibility(){ PageIdentifier = identifier, Visibilities = visibilities, HtmlId = htmlId }
};
await LocalStorageService.SetItemAsync(ColumnVisibilityLocalStorageIdentifier, data);
}
/// <summary>
/// Clears column visibility from local storage
/// </summary>
/// <returns></returns>
public async Task ClearColumnVisibilityFromStorage()
{
var identifier = GetPageIdentifier();
var containsKey = await LocalStorageService.ContainKeyAsync(ColumnVisibilityLocalStorageIdentifier);
if (!containsKey)
return;
var data = await LocalStorageService.GetItemAsync<IEnumerable<ColumnsVisibility>>(ColumnVisibilityLocalStorageIdentifier);
if (data == null || !data.Any())
return;
var dataCleared = data.Where(x => x.PageIdentifier != identifier).ToList();
await LocalStorageService.SetItemAsync(ColumnVisibilityLocalStorageIdentifier, dataCleared);
}
/// <summary>
/// Gets current page identifier
/// </summary>
/// <returns>Current page identifier</returns>
public string GetPageIdentifier()
{
var relativeUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
return relativeUrl.IndexOf("?") > -1 ? relativeUrl.Substring(0, relativeUrl.IndexOf("?")) : relativeUrl;
}
/// <summary>
/// Gets grid identifier, html id
/// </summary>
/// <returns>If id is provided via html attribute, return id, otherwise returns empty string.</returns>
public string GetGridIdentifier()
{
string htmlId = "";
//Get html id
if (Grid.Attributes != null &&
Grid.Attributes.TryGetValue("id", out var id) &&
!String.IsNullOrEmpty(Convert.ToString(id)))
htmlId = Convert.ToString(id);
return htmlId;
}
}
}
| 43.353909 | 163 | 0.583009 | [
"MIT"
] | Inspirare-LLC/Radzen.Blazor.GridColumnVisibilityChooser | Radzen.Blazor.GridColumnVisibilityChooser/RadzenGridColumnVisibilityChooser.razor.cs | 10,537 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Headless_Pi
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
| 23.086957 | 66 | 0.585687 | [
"MIT"
] | lbussy/headless-pi | Headless Pi/Program.cs | 533 | C# |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Ovr
{
/// <summary>
/// A 2D vector with integer components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector2i
{
[FieldOffset(0)] public Int32 x;
[FieldOffset(4)] public Int32 y;
public Vector2i(Int32 _x, Int32 _y)
{
x = _x;
y = _y;
}
};
/// <summary>
/// A 2D size with integer components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Sizei
{
[FieldOffset(0)] public Int32 w;
[FieldOffset(4)] public Int32 h;
public Sizei(Int32 _w, Int32 _h)
{
w = _w;
h = _h;
}
};
/// <summary>
/// A 2D rectangle with a position and size.
/// All components are integers.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Recti
{
[FieldOffset(0)] public Vector2i Pos;
[FieldOffset(8)] public Sizei Size;
};
/// <summary>
/// A quaternion rotation.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Quatf
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
[FieldOffset(8)] public float z;
[FieldOffset(12)] public float w;
public Quatf(float _x, float _y, float _z, float _w)
{
x = _x;
y = _y;
z = _z;
w = _w;
}
};
/// <summary>
/// A 2D vector with float components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector2f
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
public Vector2f(float _x, float _y)
{
x = _x;
y = _y;
}
};
/// <summary>
/// A 3D vector with float components.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Vector3f
{
[FieldOffset(0)] public float x;
[FieldOffset(4)] public float y;
[FieldOffset(8)] public float z;
public Vector3f(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
};
/// <summary>
/// A 4x4 matrix with float elements.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix4f
{
public float[,] m;
internal Matrix4f(Matrix4f_Raw raw)
{
this.m = new float[,] {
{ raw.m00, raw.m01, raw.m02, raw.m03 },
{ raw.m10, raw.m11, raw.m12, raw.m13 },
{ raw.m20, raw.m21, raw.m22, raw.m23 },
{ raw.m30, raw.m31, raw.m32, raw.m33 } };
}
};
[StructLayout(LayoutKind.Explicit)]
internal struct Matrix4f_Raw
{
[FieldOffset(0)] public float m00;
[FieldOffset(4)] public float m01;
[FieldOffset(8)] public float m02;
[FieldOffset(12)] public float m03;
[FieldOffset(16)] public float m10;
[FieldOffset(20)] public float m11;
[FieldOffset(24)] public float m12;
[FieldOffset(28)] public float m13;
[FieldOffset(32)] public float m20;
[FieldOffset(36)] public float m21;
[FieldOffset(40)] public float m22;
[FieldOffset(44)] public float m23;
[FieldOffset(48)] public float m30;
[FieldOffset(52)] public float m31;
[FieldOffset(56)] public float m32;
[FieldOffset(60)] public float m33;
};
/// <summary>
/// Position and orientation together.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct Posef
{
[FieldOffset(0)] public Quatf Orientation;
[FieldOffset(16)] public Vector3f Position;
public Posef(Quatf q, Vector3f p)
{
Orientation = q;
Position = p;
}
};
/// <summary>
/// A full pose (rigid body) configuration with first and second derivatives.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct PoseStatef
{
/// <summary>
/// The body's position and orientation.
/// </summary>
[FieldOffset(0)] public Posef ThePose;
/// <summary>
/// The body's angular velocity in radians per second.
/// </summary>
[FieldOffset(28)] public Vector3f AngularVelocity;
/// <summary>
/// The body's velocity in meters per second.
/// </summary>
[FieldOffset(40)] public Vector3f LinearVelocity;
/// <summary>
/// The body's angular acceleration in radians per second per second.
/// </summary>
[FieldOffset(52)] public Vector3f AngularAcceleration;
/// <summary>
/// The body's acceleration in meters per second per second.
/// </summary>
[FieldOffset(64)] public Vector3f LinearAcceleration;
[FieldOffset(76)] private UInt32 pad0;
/// <summary>
/// Absolute time of this state sample.
/// </summary>
[FieldOffset(80)] public double TimeInSeconds;
};
public enum InitFlags
{
/// <summary>
// When a debug library is requested, a slower debugging version of the library will
// be run which can be used to help solve problems in the library and debug game code.
/// </summary>
Debug = 0x00000001,
/// <summary>
// When ServerOptional is set, the ovr_Initialize() call not will block waiting for
// the server to respond. If the server is not reachable it may still succeed.
/// </summary>
ServerOptional = 0x00000002,
/// <summary>
// When a version is requested, LibOVR runtime will respect the RequestedMinorVersion
// field and will verify that the RequestedMinorVersion is supported.
/// </summary>
RequestVersion = 0x00000004,
/// <summary>
// Forces debug features of LibOVR off explicitly, even if it is built in debug mode.
/// </summary>
ForceNoDebug = 0x00000008,
}
/// <summary>
/// Logging levels
/// </summary>
public enum LogLevel
{
Debug = 0,
Info = 1,
Error = 2,
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CAPICallback(int level, string message);
/// <summary>
/// Configuration settings passed to the Initialize function
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class InitParams
{
/// <summary>
/// Flags from ovrExFlags to override default behavior.
/// Pass 0 for the defaults.
/// </summary>
public UInt32 Flags; // Combination of ovrExFlags or 0
/// <summary>
/// Request a specific version.
/// This must be set to OVR_MINOR_VERSION.
/// </summary>
public UInt32 RequestedMinorVersion;
/// <summary>
/// Log callback function, which may be called at any time asynchronously from
/// multiple threads until ovr_Shutdown() completes.
/// Pass 0 for no log callback.
/// </summary>
public CAPICallback LogCallback; // Function pointer or 0
/// <summary>
/// Number of milliseconds to wait for a connection to the server.
/// Pass 0 for the default timeout.
/// </summary>
public UInt32 ConnectionTimeoutMS; // Timeout in Milliseconds or 0
// This technically pads too far in 32-bit mode, but providing too large a buffer is okay.
private UInt32 pad0;
}
/// <summary>
/// Field Of View (FOV) in tangent of the angle units.
/// As an example, for a standard 90 degree vertical FOV, we would
/// have: { UpTan = tan(90 degrees / 2), DownTan = tan(90 degrees / 2) }.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct FovPort
{
/// <summary>
/// The tangent of the angle between the viewing vector and the top edge of the field of view.
/// </summary>
[FieldOffset(0)] public float UpTan;
/// <summary>
/// The tangent of the angle between the viewing vector and the bottom edge of the field of view.
/// </summary>
[FieldOffset(4)] public float DownTan;
/// <summary>
/// The tangent of the angle between the viewing vector and the left edge of the field of view.
/// </summary>
[FieldOffset(8)] public float LeftTan;
/// <summary>
/// The tangent of the angle between the viewing vector and the right edge of the field of view.
/// </summary>
[FieldOffset(12)] public float RightTan;
};
//-----------------------------------------------------------------------------------
// ***** HMD Types
/// <summary>
/// Enumerates all HMD types that we support.
/// </summary>
public enum HmdType
{
None = 0,
DK1 = 3,
DKHD = 4,
DK2 = 6,
BlackStar = 7,
CB = 8,
Other // Some HMD other than the ones in this enumeration.
};
/// <summary>
/// HMD capability bits reported by device.
/// </summary>
public enum HmdCaps
{
/// <summary>
/// (read only) The HMD is plugged in and detected by the system.
/// </summary>
Present = 0x0001,
/// <summary>
/// (read only) The HMD and its sensor are available for ownership use.
/// i.e. it is not already owned by another application.
/// </summary>
Available = 0x0002,
/// <summary>
/// (read only) Set to 'true' if we captured ownership of this HMD.
/// </summary>
Captured = 0x0004,
/// <summary>
/// (read only) Means the display driver is in compatibility mode.
/// </summary>
ExtendDesktop = 0x0008,
/// <summary>
/// (read only) Means HMD device is a virtual debug device.
/// </summary>
DebugDevice = 0x0010,
// Modifiable flags (through ovrHmd_SetEnabledCaps).
/// <summary>
/// Disables mirroring of HMD output to the window. This may improve
/// rendering performance slightly (only if 'ExtendDesktop' is off).
/// </summary>
NoMirrorToWindow = 0x2000,
/// <summary>
/// Turns off HMD screen and output (only if 'ExtendDesktop' is off).
/// </summary>
DisplayOff = 0x0040,
/// <summary>
/// HMD supports low persistence mode.
/// </summary>
LowPersistence = 0x0080,
/// <summary>
/// Adjust prediction dynamically based on internally measured latency.
/// </summary>
DynamicPrediction = 0x0200,
/// <summary>
/// Support rendering without VSync for debugging.
/// </summary>
NoVSync = 0x1000,
/// <summary>
/// These bits can be modified by ovrHmd_SetEnabledCaps.
/// </summary>
WritableMask = NoMirrorToWindow
| DisplayOff
| LowPersistence
| DynamicPrediction
| NoVSync,
/// <summary>
/// These flags are currently passed into the service. May change without notice.
/// </summary>
ServiceMask = NoMirrorToWindow
| DisplayOff
| LowPersistence
| DynamicPrediction,
};
/// <summary>
/// Tracking capability bits reported by the device.
/// Used with ovrHmd_ConfigureTracking.
/// </summary>
public enum TrackingCaps
{
/// <summary>
/// Supports orientation tracking (IMU).
/// </summary>
Orientation = 0x0010,
/// <summary>
/// Supports yaw drift correction via a magnetometer or other means.
/// </summary>
MagYawCorrection = 0x0020,
/// <summary>
/// Supports positional tracking.
/// </summary>
Position = 0x0040,
/// <summary>
/// Overrides the other flags. Indicates that the application
/// doesn't care about tracking settings. This is the internal
/// default before ovrHmd_ConfigureTracking is called.
/// </summary>
Idle = 0x0100,
};
/// <summary>
/// Distortion capability bits reported by device.
/// Used with ovrHmd_ConfigureRendering and ovrHmd_CreateDistortionMesh.
/// </summary>
public enum DistortionCaps
{
/// <summary>
/// Supports chromatic aberration correction.
/// </summary>
Chromatic = 0x01,
/// <summary>
/// Supports timewarp.
/// </summary>
TimeWarp = 0x02,
// 0x04 unused
/// <summary>
/// Supports vignetting around the edges of the view.
/// </summary>
Vignette = 0x08,
/// <summary>
/// Do not save and restore the graphics state when rendering distortion.
/// </summary>
NoRestore = 0x10,
/// <summary>
/// Flip the vertical texture coordinate of input images.
/// </summary>
FlipInput = 0x20,
/// <summary>
/// Assume input images are in sRGB gamma-corrected color space.
/// </summary>
SRGB = 0x40,
/// <summary>
/// Overdrive brightness transitions to reduce artifacts on DK2+ displays
/// </summary>
Overdrive = 0x80,
/// <summary>
/// High-quality sampling of distortion buffer for anti-aliasing
/// </summary>
HqDistortion = 0x100,
/// </summary>
/// Indicates window is fullscreen on a device when set.
/// The SDK will automatically apply distortion mesh rotation if needed.
/// </summary>
LinuxDevFullscreen = 0x200,
/// <summary>
/// Using compute shader (DX11+ only)
/// </summary>
ComputeShader = 0x400,
/// <summary>
/// Use when profiling with timewarp to remove false positives
/// </summary>
ProfileNoTimewarpSpinWaits = 0x10000,
};
/// <summary>
/// Specifies which eye is being used for rendering.
/// This type explicitly does not include a third "NoStereo" option, as such is
/// not required for an HMD-centered API.
/// </summary>
public enum Eye
{
Left = 0,
Right = 1,
Count = 2,
};
/// <summary>
/// This is a complete descriptor of the HMD.
/// </summary>
public struct HmdDesc
{
/// <summary>
/// Internal handle of this HMD.
/// </summary>
public IntPtr Handle;
/// <summary>
/// This HMD's type.
/// </summary>
public HmdType Type;
/// <summary>
/// Name string describing the product: "Oculus Rift DK1", etc.
/// </summary>
public string ProductName;
public string Manufacturer;
/// <summary>
/// HID Vendor and ProductId of the device.
/// </summary>
public short VendorId;
public short ProductId;
/// <summary>
/// Sensor (and display) serial number.
/// </summary>
public string SerialNumber;
/// <summary>
/// Sensor firmware version.
/// </summary>
public short FirmwareMajor;
public short FirmwareMinor;
/// <summary>
/// External tracking camera frustum dimensions (if present).
/// </summary>
public float CameraFrustumHFovInRadians;
public float CameraFrustumVFovInRadians;
public float CameraFrustumNearZInMeters;
public float CameraFrustumFarZInMeters;
/// <summary>
/// Capability bits described by ovrHmdCaps.
/// </summary>
public uint HmdCaps;
/// <summary>
/// Capability bits described by ovrTrackingCaps.
/// </summary>
public uint TrackingCaps;
/// <summary>
/// Capability bits described by ovrDistortionCaps.
/// </summary>
public uint DistortionCaps;
/// <summary>
/// Defines the recommended optical FOV for the HMD.
/// </summary>
public FovPort[] DefaultEyeFov;
/// <summary>
/// Defines the maximum optical FOV for the HMD.
/// </summary>
public FovPort[] MaxEyeFov;
/// <summary>
/// Preferred eye rendering order for best performance.
/// Can help reduce latency on sideways-scanned screens.
/// </summary>
public Eye[] EyeRenderOrder;
/// <summary>
/// Resolution of the full HMD screen (both eyes) in pixels.
/// </summary>
public Sizei Resolution;
/// <summary>
/// Location of the application window on the desktop (or 0,0).
/// </summary>
public Vector2i WindowsPos;
/// <summary>
/// Display that the HMD should present on.
/// TBD: It may be good to remove this information relying on WindowPos instead.
/// Ultimately, we may need to come up with a more convenient alternative,
/// such as API-specific functions that return adapter, or something that will
/// work with our monitor driver.
/// Windows: (e.g. "\\\\.\\DISPLAY3", can be used in EnumDisplaySettings/CreateDC).
/// </summary>
public string DisplayDeviceName;
/// <summary>
/// MacOS:
/// </summary>
public int DisplayId;
internal HmdDesc(HmdDesc_Raw32 raw)
{
this.Handle = raw.Handle;
this.Type = (HmdType)raw.Type;
this.ProductName = Marshal.PtrToStringAnsi(raw.ProductName);
this.Manufacturer = Marshal.PtrToStringAnsi(raw.Manufacturer);
this.VendorId = (short)raw.VendorId;
this.ProductId = (short)raw.ProductId;
this.SerialNumber = raw.SerialNumber;
this.FirmwareMajor = (short)raw.FirmwareMajor;
this.FirmwareMinor = (short)raw.FirmwareMinor;
this.CameraFrustumHFovInRadians = raw.CameraFrustumHFovInRadians;
this.CameraFrustumVFovInRadians = raw.CameraFrustumVFovInRadians;
this.CameraFrustumNearZInMeters = raw.CameraFrustumNearZInMeters;
this.CameraFrustumFarZInMeters = raw.CameraFrustumFarZInMeters;
this.HmdCaps = raw.HmdCaps;
this.TrackingCaps = raw.TrackingCaps;
this.DistortionCaps = raw.DistortionCaps;
this.Resolution = raw.Resolution;
this.WindowsPos = raw.WindowsPos;
this.DefaultEyeFov = new FovPort[2] { raw.DefaultEyeFov_0, raw.DefaultEyeFov_1 };
this.MaxEyeFov = new FovPort[2] { raw.MaxEyeFov_0, raw.MaxEyeFov_1 };
this.EyeRenderOrder = new Eye[2] { Eye.Left, Eye.Right };
this.DisplayDeviceName = Marshal.PtrToStringAnsi(raw.DisplayDeviceName);
this.DisplayId = raw.DisplayId;
}
internal HmdDesc(HmdDesc_Raw64 raw)
{
this.Handle = raw.Handle;
this.Type = (HmdType)raw.Type;
this.ProductName = Marshal.PtrToStringAnsi(raw.ProductName);
this.Manufacturer = Marshal.PtrToStringAnsi(raw.Manufacturer);
this.VendorId = (short)raw.VendorId;
this.ProductId = (short)raw.ProductId;
this.SerialNumber = raw.SerialNumber;
this.FirmwareMajor = (short)raw.FirmwareMajor;
this.FirmwareMinor = (short)raw.FirmwareMinor;
this.CameraFrustumHFovInRadians = raw.CameraFrustumHFovInRadians;
this.CameraFrustumVFovInRadians = raw.CameraFrustumVFovInRadians;
this.CameraFrustumNearZInMeters = raw.CameraFrustumNearZInMeters;
this.CameraFrustumFarZInMeters = raw.CameraFrustumFarZInMeters;
this.HmdCaps = raw.HmdCaps;
this.TrackingCaps = raw.TrackingCaps;
this.DistortionCaps = raw.DistortionCaps;
this.Resolution = raw.Resolution;
this.WindowsPos = raw.WindowsPos;
this.DefaultEyeFov = new FovPort[2] { raw.DefaultEyeFov_0, raw.DefaultEyeFov_1 };
this.MaxEyeFov = new FovPort[2] { raw.MaxEyeFov_0, raw.MaxEyeFov_1 };
this.EyeRenderOrder = new Eye[2] { Eye.Left, Eye.Right };
this.DisplayDeviceName = Marshal.PtrToStringAnsi(raw.DisplayDeviceName);
this.DisplayId = raw.DisplayId;
}
};
// Internal description for HMD; must match C 'ovrHmdDesc' layout.
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
internal struct HmdDesc_Raw32
{
public IntPtr Handle;
public UInt32 Type;
// Use IntPtr so that CLR doesn't try to deallocate string.
public IntPtr ProductName;
public IntPtr Manufacturer;
// HID Vendor and ProductId of the device.
public UInt16 VendorId;
public UInt16 ProductId;
// Sensor (and display) serial number.
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 24)]
public string SerialNumber;
// Sensor firmware
public UInt16 FirmwareMajor;
public UInt16 FirmwareMinor;
// Fixed camera frustum dimensions, if present
public float CameraFrustumHFovInRadians;
public float CameraFrustumVFovInRadians;
public float CameraFrustumNearZInMeters;
public float CameraFrustumFarZInMeters;
public UInt32 HmdCaps;
public UInt32 TrackingCaps;
public UInt32 DistortionCaps;
// C# arrays are dynamic and thus not supported as return values, so just expand the struct.
public FovPort DefaultEyeFov_0;
public FovPort DefaultEyeFov_1;
public FovPort MaxEyeFov_0;
public FovPort MaxEyeFov_1;
public UInt32 EyeRenderOrder_0;
public UInt32 EyeRenderOrder_1;
public Sizei Resolution;
public Vector2i WindowsPos;
public IntPtr DisplayDeviceName;
public Int32 DisplayId;
};
// Internal description for HMD; must match C 'ovrHmdDesc' layout.
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
internal struct HmdDesc_Raw64
{
public IntPtr Handle;
public UInt32 Type;
private UInt32 pad0;
// Use IntPtr so that CLR doesn't try to deallocate string.
public IntPtr ProductName;
public IntPtr Manufacturer;
// HID Vendor and ProductId of the device.
public UInt16 VendorId;
public UInt16 ProductId;
// Sensor (and display) serial number.
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 24)]
public string SerialNumber;
// Sensor firmware
public UInt16 FirmwareMajor;
public UInt16 FirmwareMinor;
// Fixed camera frustum dimensions, if present
public float CameraFrustumHFovInRadians;
public float CameraFrustumVFovInRadians;
public float CameraFrustumNearZInMeters;
public float CameraFrustumFarZInMeters;
public UInt32 HmdCaps;
public UInt32 TrackingCaps;
public UInt32 DistortionCaps;
// C# arrays are dynamic and thus not supported as return values, so just expand the struct.
public FovPort DefaultEyeFov_0;
public FovPort DefaultEyeFov_1;
public FovPort MaxEyeFov_0;
public FovPort MaxEyeFov_1;
public UInt32 EyeRenderOrder_0;
public UInt32 EyeRenderOrder_1;
public Sizei Resolution;
public Vector2i WindowsPos;
private UInt32 pad1;
public IntPtr DisplayDeviceName;
public Int32 DisplayId;
private UInt32 pad2;
};
/// <summary>
/// Bit flags describing the current status of sensor tracking.
/// The values must be the same as in enum StatusBits.
/// </summary>
public enum StatusBits
{
/// <summary>
/// Orientation is currently tracked (connected and in use).
/// </summary>
OrientationTracked = 0x0001,
/// <summary>
/// Position is currently tracked (false if out of range).
/// </summary>
PositionTracked = 0x0002,
/// <summary>
/// Camera pose is currently tracked.
/// </summary>
CameraPoseTracked = 0x0004,
/// <summary>
/// Position tracking hardware is connected.
/// </summary>
PositionConnected = 0x0020,
/// <summary>
/// HMD Display is available and connected.
/// </summary>
HmdConnected = 0x0080,
};
/// <summary>
/// Specifies a reading we can query from the sensor.
/// </summary>
public struct SensorData
{
/// <summary>
/// Acceleration reading in m/s^2.
/// </summary>
public Vector3f Accelerometer;
/// <summary>
/// Rotation rate in rad/s.
/// </summary>
public Vector3f Gyro;
/// <summary>
/// Magnetic field in Gauss.
/// </summary>
public Vector3f Magnetometer;
/// <summary>
/// Temperature of the sensor in degrees Celsius.
/// </summary>
public float Temperature;
/// <summary>
/// Time when the reported IMU reading took place, in seconds.
/// </summary>
public float TimeInSeconds;
};
/// <summary>
/// Tracking state at a given absolute time (describes predicted HMD pose etc).
/// Returned by ovrHmd_GetTrackingState.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct TrackingState
{
/// <summary>
/// Predicted head pose (and derivatives) at the requested absolute time.
/// The look-ahead interval is equal to (HeadPose.TimeInSeconds - RawSensorData.TimeInSeconds).
/// </summary>
[FieldOffset(0)] public PoseStatef HeadPose;
/// <summary>
/// Current pose of the external camera (if present).
/// This pose includes camera tilt (roll and pitch). For a leveled coordinate
/// system use LeveledCameraPose.
/// </summary>
[FieldOffset(88)] public Posef CameraPose;
/// <summary>
/// Camera frame aligned with gravity.
/// This value includes position and yaw of the camera, but not roll and pitch.
/// It can be used as a reference point to render real-world objects in the correct location.
/// </summary>
[FieldOffset(116)] public Posef LeveledCameraPose;
/// <summary>
/// The most recent sensor data received from the HMD.
/// </summary>
[FieldOffset(144)] public SensorData RawSensorData;
/// <summary>
/// Tracking status described by ovrStatusBits.
/// </summary>
[FieldOffset(188)] public UInt32 StatusFlags;
/// <summary>
/// Tag the vision processing results to a certain frame counter number.
/// </summary>
[FieldOffset(192)] public UInt32 LastCameraFrameCounter;
[FieldOffset(196)] private UInt32 pad0;
};
/// <summary>
/// Frame timing data reported by ovrHmd_BeginFrameTiming() or ovrHmd_BeginFrame().
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct FrameTiming
{
/// <summary>
/// The amount of time that has passed since the previous frame's
/// ThisFrameSeconds value (usable for movement scaling).
/// This will be clamped to no more than 0.1 seconds to prevent
/// excessive movement after pauses due to loading or initialization.
/// </summary>
public float DeltaSeconds;
// It is generally expected that the following holds:
// ThisFrameSeconds < TimewarpPointSeconds < NextFrameSeconds <
// EyeScanoutSeconds[EyeOrder[0]] <= ScanoutMidpointSeconds <= EyeScanoutSeconds[EyeOrder[1]].
/// <summary>
/// Absolute time value when rendering of this frame began or is expected to
/// begin. Generally equal to NextFrameSeconds of the previous frame. Can be used
/// for animation timing.
/// </summary>
public double ThisFrameSeconds;
/// <summary>
/// Absolute point when IMU expects to be sampled for this frame.
/// </summary>
public double TimewarpPointSeconds;
/// <summary>
/// Absolute time when frame Present followed by GPU Flush will finish and the next frame begins.
/// </summary>
public double NextFrameSeconds;
/// <summary>
/// Time when half of the screen will be scanned out. Can be passed as an absolute time
/// to ovrHmd_GetTrackingState() to get the predicted general orientation.
/// </summary>
public double ScanoutMidpointSeconds;
/// <summary>
/// Timing points when each eye will be scanned out to display. Used when rendering each eye.
/// </summary>
public double[] EyeScanoutSeconds;
internal FrameTiming(FrameTiming_Raw raw)
{
this.DeltaSeconds = raw.DeltaSeconds;
this.ThisFrameSeconds = raw.ThisFrameSeconds;
this.TimewarpPointSeconds = raw.TimewarpPointSeconds;
this.NextFrameSeconds = raw.NextFrameSeconds;
this.ScanoutMidpointSeconds = raw.ScanoutMidpointSeconds;
this.EyeScanoutSeconds = new double[2] { raw.EyeScanoutSeconds_0, raw.EyeScanoutSeconds_1 };
}
};
// Internal description for ovrFrameTiming; must match C 'ovrFrameTiming' layout.
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
internal struct FrameTiming_Raw
{
[FieldOffset(0)] public float DeltaSeconds;
[FieldOffset(4)] private UInt32 pad0;
[FieldOffset(8)] public double ThisFrameSeconds;
[FieldOffset(16)] public double TimewarpPointSeconds;
[FieldOffset(24)] public double NextFrameSeconds;
[FieldOffset(32)] public double ScanoutMidpointSeconds;
// C# arrays are dynamic and thus not supported as return values, so just expand the struct.
[FieldOffset(40)] public double EyeScanoutSeconds_0;
[FieldOffset(48)] public double EyeScanoutSeconds_1;
};
/// <summary>
/// Rendering information for each eye. Computed by either ovrHmd_ConfigureRendering()
/// or ovrHmd_GetRenderDesc() based on the specified FOV. Note that the rendering viewport
/// is not included here as it can be specified separately and modified per frame through:
/// (a) ovrHmd_GetRenderScaleAndOffset in the case of client rendered distortion,
/// or (b) passing different values via ovrTexture in the case of SDK rendered distortion.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct EyeRenderDesc
{
/// <summary>
/// The eye index this instance corresponds to.
/// </summary>
[FieldOffset(0)] public UInt32 Eye;
/// <summary>
/// The field of view.
/// </summary>
[FieldOffset(4)] public FovPort Fov;
/// <summary>
/// Distortion viewport.
/// </summary>
[FieldOffset(20)] public Recti DistortedViewport;
/// <summary>
/// How many display pixels will fit in tan(angle) = 1.
/// </summary>
[FieldOffset(36)] public Vector2f PixelsPerTanAngleAtCenter;
/// <summary>
/// Translation to be applied to view matrix for each eye offset.
/// </summary>
[FieldOffset(44)] public Vector3f HmdToEyeViewOffset;
};
//-----------------------------------------------------------------------------------
// ***** Platform-independent Rendering Configuration
/// <summary>
/// These types are used to hide platform-specific details when passing
/// render device, OS, and texture data to the API.
///
/// The benefit of having these wrappers versus platform-specific API functions is
/// that they allow game glue code to be portable. A typical example is an
/// engine that has multiple back ends, say GL and D3D. Portable code that calls
/// these back ends may also use LibOVR. To do this, back ends can be modified
/// to return portable types such as ovrTexture and ovrRenderAPIConfig.
/// </summary>
public enum RenderAPIType
{
None,
OpenGL,
Android_GLES, // May include extra native window pointers, etc.
D3D9,
D3D10, // Deprecated: Not supported for SDK rendering
D3D11,
Count,
};
/// <summary>
/// Platform-independent part of rendering API-configuration data.
/// It is a part of ovrRenderAPIConfig, passed to ovrHmd_Configure.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct RenderAPIConfigHeader
{
[FieldOffset(0)] public RenderAPIType API;
[FieldOffset(4)] public Sizei BackBufferSize; // Previously named RTSize.
[FieldOffset(12)] public Int32 Multisample;
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct RenderAPIConfig_Raw
{
public RenderAPIConfigHeader Header;
public IntPtr PlatformData0;
public IntPtr PlatformData1;
public IntPtr PlatformData2;
public IntPtr PlatformData3;
public IntPtr PlatformData4;
public IntPtr PlatformData5;
public IntPtr PlatformData6;
public IntPtr PlatformData7;
};
/// <summary>
/// Contains platform-specific information for rendering.
/// </summary>
public abstract class RenderAPIConfig
{
public RenderAPIConfig() { Header.API = RenderAPIType.None; }
public RenderAPIConfigHeader Header;
internal abstract RenderAPIConfig_Raw ToRaw();
}
/// <summary>
/// Contains OpenGL-specific rendering information for Windows.
/// </summary>
public class OpenGLWindowsConfig : RenderAPIConfig
{
public OpenGLWindowsConfig(Sizei backBufferSize, int multisample, IntPtr hwnd, IntPtr HDCDeviceContext)
{
Header.API = RenderAPIType.OpenGL;
Header.BackBufferSize = backBufferSize;
Header.Multisample = multisample;
_hwnd = hwnd;
_HDCDeviceContext = HDCDeviceContext;
}
internal override RenderAPIConfig_Raw ToRaw()
{
RenderAPIConfig_Raw config = new RenderAPIConfig_Raw();
config.Header = this.Header;
config.PlatformData0 = this._hwnd;
config.PlatformData1 = this._HDCDeviceContext;
return config;
}
public IntPtr _hwnd;
public IntPtr _HDCDeviceContext;
}
/// <summary>
/// Contains OpenGL-specific rendering information for Linux.
/// </summary>
public class OpenGLLinuxConfig : RenderAPIConfig
{
public OpenGLLinuxConfig(Sizei backBufferSize, int multisample, IntPtr optionalXDisplay, IntPtr optionalWindow)
{
Header.API = RenderAPIType.OpenGL;
Header.BackBufferSize = backBufferSize;
Header.Multisample = multisample;
_OptionalXDisplay = optionalXDisplay;
_OptionalWindow = optionalWindow;
}
internal override RenderAPIConfig_Raw ToRaw()
{
RenderAPIConfig_Raw config = new RenderAPIConfig_Raw();
config.Header = this.Header;
config.PlatformData0 = this._OptionalXDisplay;
config.PlatformData1 = this._OptionalWindow;
return config;
}
IntPtr _OptionalXDisplay;
IntPtr _OptionalWindow;
}
/// <summary>
/// Contains OpenGL ES-specific rendering information.
/// </summary>
public class AndroidGLESConfig : RenderAPIConfig
{
public AndroidGLESConfig(Sizei backBufferSize, int multisample)
{
Header.API = RenderAPIType.Android_GLES;
Header.BackBufferSize = backBufferSize;
Header.Multisample = multisample;
}
internal override RenderAPIConfig_Raw ToRaw()
{
RenderAPIConfig_Raw config = new RenderAPIConfig_Raw();
config.Header = this.Header;
return config;
}
}
/// <summary>
/// Contains D3D9-specific rendering information.
/// </summary>
public class D3D9Config : RenderAPIConfig
{
public D3D9Config(Sizei backBufferSize, int multisample, IntPtr IDirect3DDevice9_pDevice, IntPtr IDirect3DSwapChain9_pSwapChain)
{
Header.API = RenderAPIType.D3D9;
Header.BackBufferSize = backBufferSize;
Header.Multisample = multisample;
_IDirect3DDevice9_pDevice = IDirect3DDevice9_pDevice;
_IDirect3DSwapChain9_pSwapChain = IDirect3DSwapChain9_pSwapChain;
}
internal override RenderAPIConfig_Raw ToRaw()
{
RenderAPIConfig_Raw config = new RenderAPIConfig_Raw();
config.Header = this.Header;
config.PlatformData0 = this._IDirect3DDevice9_pDevice;
config.PlatformData1 = this._IDirect3DSwapChain9_pSwapChain;
return config;
}
IntPtr _IDirect3DDevice9_pDevice;
IntPtr _IDirect3DSwapChain9_pSwapChain;
}
/// <summary>
/// Contains D3D11-specific rendering information.
/// </summary>
public class D3D11Config : RenderAPIConfig
{
public D3D11Config(Sizei backBufferSize, int multisample, IntPtr ID3D11Device_pDevice, IntPtr ID3D11DeviceContext_pDeviceContext, IntPtr ID3D11RenderTargetView_pBackBufferRT, IntPtr ID3D11BackBufferUAV, IntPtr IDXGISwapChain_pSwapChain)
{
Header.API = RenderAPIType.D3D11;
Header.BackBufferSize = backBufferSize;
Header.Multisample = multisample;
_ID3D11Device_pDevice = ID3D11Device_pDevice;
_ID3D11DeviceContext_pDeviceContext = ID3D11DeviceContext_pDeviceContext;
_ID3D11RenderTargetView_pBackBufferRT = ID3D11RenderTargetView_pBackBufferRT;
_ID3D11BackBufferUAV = ID3D11BackBufferUAV;
_IDXGISwapChain_pSwapChain = IDXGISwapChain_pSwapChain;
}
internal override RenderAPIConfig_Raw ToRaw()
{
RenderAPIConfig_Raw config = new RenderAPIConfig_Raw();
config.Header = this.Header;
config.PlatformData0 = this._ID3D11Device_pDevice;
config.PlatformData1 = this._ID3D11DeviceContext_pDeviceContext;
config.PlatformData2 = this._ID3D11RenderTargetView_pBackBufferRT;
config.PlatformData3 = this._ID3D11BackBufferUAV;
config.PlatformData4 = this._IDXGISwapChain_pSwapChain;
return config;
}
IntPtr _ID3D11Device_pDevice;
IntPtr _ID3D11DeviceContext_pDeviceContext;
IntPtr _ID3D11RenderTargetView_pBackBufferRT;
IntPtr _ID3D11BackBufferUAV;
IntPtr _IDXGISwapChain_pSwapChain;
}
/// <summary>
/// Platform-independent part of the eye texture descriptor.
/// It is a part of ovrTexture, passed to ovrHmd_EndFrame.
/// If RenderViewport is all zeros then the full texture will be used.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct TextureHeader
{
[FieldOffset(0)] public UInt32 API;
[FieldOffset(4)] public Sizei TextureSize;
[FieldOffset(12)] public Recti RenderViewport; // Pixel viewport in texture that holds eye image.
};
/// <summary>
/// Contains platform-specific information for rendering.
/// </summary>
public abstract class Texture
{
public Texture() { Header.API = (UInt32)RenderAPIType.None; }
public TextureHeader Header;
internal abstract Texture_Raw ToRaw();
}
/// <summary>
/// Contains OpenGL-specific texture information
/// </summary>
public class GLTextureData : Texture
{
public GLTextureData(Sizei textureSize, Recti renderViewport, IntPtr texId)
{
Header.API = (UInt32)RenderAPIType.OpenGL;
Header.TextureSize = textureSize;
Header.RenderViewport = renderViewport;
_texId = texId;
}
internal override Texture_Raw ToRaw()
{
Texture_Raw config = new Texture_Raw();
config.Header = this.Header;
config.PlatformData_0 = this._texId;
return config;
}
public IntPtr _texId;
}
/// <summary>
/// Contains D3D9-specific texture information
/// </summary>
public class D3D9TextureData : Texture
{
public D3D9TextureData(Sizei textureSize, Recti renderViewport, IntPtr IDirect3DTexture9_pTexture)
{
Header.API = (UInt32)RenderAPIType.D3D9;
Header.TextureSize = textureSize;
Header.RenderViewport = renderViewport;
_IDirect3DTexture9_pTexture = IDirect3DTexture9_pTexture;
}
internal override Texture_Raw ToRaw()
{
Texture_Raw config = new Texture_Raw();
config.Header = this.Header;
config.PlatformData_0 = this._IDirect3DTexture9_pTexture;
return config;
}
public IntPtr _IDirect3DTexture9_pTexture;
}
/// <summary>
/// Contains D3D10-specific texture information
/// </summary>
public class D3D10TextureData : Texture
{
public D3D10TextureData(Sizei textureSize, Recti renderViewport, IntPtr ID3D10Texture2D_pTexture, IntPtr ID3D10ShaderResourceView_pSRView)
{
Header.API = (UInt32)RenderAPIType.D3D10;
Header.TextureSize = textureSize;
Header.RenderViewport = renderViewport;
_ID3D10Texture2D_pTexture = ID3D10Texture2D_pTexture;
_ID3D10ShaderResourceView_pSRView = ID3D10ShaderResourceView_pSRView;
}
internal override Texture_Raw ToRaw()
{
Texture_Raw config = new Texture_Raw();
config.Header = this.Header;
config.PlatformData_0 = this._ID3D10Texture2D_pTexture;
config.PlatformData_1 = this._ID3D10ShaderResourceView_pSRView;
return config;
}
public IntPtr _ID3D10Texture2D_pTexture, _ID3D10ShaderResourceView_pSRView;
}
/// <summary>
/// Contains D3D11-specific texture information
/// </summary>
public class D3D11TextureData : Texture
{
public D3D11TextureData(Sizei textureSize, Recti renderViewport, IntPtr ID3D11Texture2D_pTexture, IntPtr ID3D11ShaderResourceView_pSRView)
{
Header.API = (UInt32)RenderAPIType.D3D11;
Header.TextureSize = textureSize;
Header.RenderViewport = renderViewport;
_ID3D11Texture2D_pTexture = ID3D11Texture2D_pTexture;
_ID3D11ShaderResourceView_pSRView = ID3D11ShaderResourceView_pSRView;
}
internal override Texture_Raw ToRaw()
{
Texture_Raw config = new Texture_Raw();
config.Header = this.Header;
config.PlatformData_0 = this._ID3D11Texture2D_pTexture;
config.PlatformData_1 = this._ID3D11ShaderResourceView_pSRView;
return config;
}
public IntPtr _ID3D11Texture2D_pTexture, _ID3D11ShaderResourceView_pSRView;
}
// Internal description for ovrTexture; must match C 'ovrTexture' layout.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Texture_Raw
{
public TextureHeader Header;
private UInt32 pad0;
public IntPtr PlatformData_0;
public IntPtr PlatformData_1;
public IntPtr PlatformData_2;
public IntPtr PlatformData_3;
public IntPtr PlatformData_4;
public IntPtr PlatformData_5;
public IntPtr PlatformData_6;
public IntPtr PlatformData_7;
};
/// <summary>
/// Describes a vertex used by the distortion mesh. This is intended to be converted into
/// the engine-specific format. Some fields may be unused based on the ovrDistortionCaps
/// flags selected. TexG and TexB, for example, are not used if chromatic correction is
/// not requested.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct DistortionVertex
{
/// <summary>
/// [-1,+1],[-1,+1] over the entire framebuffer.
/// </summary>
[FieldOffset(0)] public Vector2f ScreenPosNDC;
/// <summary>
/// Lerp factor between time-warp matrices. Can be encoded in Pos.z.
/// </summary>
[FieldOffset(8)] public float TimeWarpFactor;
/// <summary>
/// Vignette fade factor. Can be encoded in Pos.w.
/// </summary>
[FieldOffset(12)] public float VignetteFactor;
/// <summary>
/// The tangents of the horizontal and vertical eye angles for the red channel.
/// </summary>
[FieldOffset(16)] public Vector2f TanEyeAnglesR;
/// <summary>
/// The tangents of the horizontal and vertical eye angles for the green channel.
/// </summary>
[FieldOffset(24)] public Vector2f TanEyeAnglesG;
/// <summary>
/// The tangents of the horizontal and vertical eye angles for the blue channel.
/// </summary>
[FieldOffset(32)] public Vector2f TanEyeAnglesB;
};
/// <summary>
/// Describes a full set of distortion mesh data, filled in by ovrHmd_CreateDistortionMesh.
/// Contents of this data structure, if not null, should be freed by ovrHmd_DestroyDistortionMesh.
/// </summary>
public struct DistortionMesh
{
/// <summary>
/// The distortion vertices representing each point in the mesh.
/// </summary>
public DistortionVertex[] pVertexData;
/// <summary>
/// Indices for connecting the mesh vertices into polygons.
/// </summary>
public short[] pIndexData;
/// <summary>
/// The number of vertices in the mesh.
/// </summary>
public uint VertexCount;
/// <summary>
/// The number of indices in the mesh.
/// </summary>
public uint IndexCount;
internal DistortionMesh(DistortionMesh_Raw raw)
{
this.VertexCount = raw.VertexCount;
this.pVertexData = new DistortionVertex[this.VertexCount];
this.IndexCount = raw.IndexCount;
this.pIndexData = new short[this.IndexCount];
// Copy data
System.Type vertexType = typeof(DistortionVertex);
Int32 vertexSize = Marshal.SizeOf(vertexType);
Int32 indexSize = sizeof(short);
Int64 pvertices = raw.pVertexData.ToInt64();
Int64 pindices = raw.pIndexData.ToInt64();
// TODO: Investigate using Marshal.Copy() or Buffer.BlockCopy() for improved performance
for (int i = 0; i < raw.VertexCount; i++)
{
pVertexData[i] = (DistortionVertex)Marshal.PtrToStructure(new IntPtr(pvertices), vertexType);
pvertices += vertexSize;
}
// Indices are stored as shorts.
for (int j = 0; j < raw.IndexCount; j++)
{
pIndexData[j] = Marshal.ReadInt16(new IntPtr(pindices));
pindices += indexSize;
}
}
};
// Internal description for ovrDistortionMesh; must match C 'ovrDistortionMesh' layout.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct DistortionMesh_Raw
{
public IntPtr pVertexData;
public IntPtr pIndexData;
public UInt32 VertexCount;
public UInt32 IndexCount;
};
/// <summary>
/// Used by ovrhmd_GetHSWDisplayState to report the current display state.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public struct HSWDisplayState
{
/// <summary>
/// If true then the warning should be currently visible
/// and the following variables have meaning. Else there is no
/// warning being displayed for this application on the given HMD.
/// True if the Health&Safety Warning is currently displayed.
/// </summary>
[FieldOffset(0)] public byte Displayed;
/// <summary>
/// Absolute time when the warning was first displayed. See ovr_GetTimeInSeconds().
/// </summary>
[FieldOffset(8)] public double StartTime;
/// <summary>
/// Earliest absolute time when the warning can be dismissed. May be a time in the past.
/// </summary>
[FieldOffset(16)] public double DismissibleTime;
};
/// <summary>
/// Provides an interface to a CAPI HMD object. The ovrHmd instance is normally
/// created by ovrHmd::Create, after which its other methods can be called.
/// The typical process would involve calling:
///
/// Setup:
/// - Initialize() to initialize the OVR SDK.
/// - Construct Hmd to create an ovrHmd.
/// - Use hmd members and ovrHmd_GetFovTextureSize() to determine graphics configuration.
/// - ConfigureTracking() to configure and initialize tracking.
/// - ConfigureRendering() to setup graphics for SDK rendering, which is the preferred approach.
/// - Please refer to "Client Distortion Rendering" below if you prefer to do that instead.
/// - If ovrHmdCap_ExtendDesktop is not set, use ovrHmd_AttachToWindow to associate the window with an Hmd.
/// - Allocate render textures as needed.
///
/// Game Loop:
/// - Call ovrHmd_BeginFrame() to get frame timing and orientation information.
/// - Render each eye in between, using ovrHmd_GetEyePoses or ovrHmd_GetHmdPosePerEye to get the predicted hmd pose and each eye pose.
/// - Call ovrHmd_EndFrame() to render distorted textures to the back buffer
/// and present them on the Hmd.
///
/// Shutdown:
/// - Dispose the Hmd to release the ovrHmd.
/// - ovr_Shutdown() to shutdown the OVR SDK.
/// </summary>
public class Hmd : IDisposable
{
public const string OVR_VERSION_STRING = "0.5.0";
public const string OVR_KEY_USER = "User";
public const string OVR_KEY_NAME = "Name";
public const string OVR_KEY_GENDER = "Gender";
public const string OVR_KEY_PLAYER_HEIGHT = "PlayerHeight";
public const string OVR_KEY_EYE_HEIGHT = "EyeHeight";
public const string OVR_KEY_IPD = "IPD";
public const string OVR_KEY_NECK_TO_EYE_DISTANCE = "NeckEyeDistance";
public const string OVR_KEY_EYE_RELIEF_DIAL = "EyeReliefDial";
public const string OVR_KEY_EYE_TO_NOSE_DISTANCE = "EyeToNoseDist";
public const string OVR_KEY_MAX_EYE_TO_PLATE_DISTANCE = "MaxEyeToPlateDist";
public const string OVR_KEY_EYE_CUP = "EyeCup";
public const string OVR_KEY_CUSTOM_EYE_RENDER = "CustomEyeRender";
public const string OVR_KEY_CAMERA_POSITION = "CenteredFromWorld";
// Default measurements empirically determined at Oculus to make us happy
// The neck model numbers were derived as an average of the male and female averages from ANSUR-88
// NECK_TO_EYE_HORIZONTAL = H22 - H43 = INFRAORBITALE_BACK_OF_HEAD - TRAGION_BACK_OF_HEAD
// NECK_TO_EYE_VERTICAL = H21 - H15 = GONION_TOP_OF_HEAD - ECTOORBITALE_TOP_OF_HEAD
// These were determined to be the best in a small user study, clearly beating out the previous default values
public const string OVR_DEFAULT_GENDER = "Unknown";
public const float OVR_DEFAULT_PLAYER_HEIGHT = 1.778f;
public const float OVR_DEFAULT_EYE_HEIGHT = 1.675f;
public const float OVR_DEFAULT_IPD = 0.064f;
public const float OVR_DEFAULT_NECK_TO_EYE_HORIZONTAL = 0.0805f;
public const float OVR_DEFAULT_NECK_TO_EYE_VERTICAL = 0.075f;
public const float OVR_DEFAULT_EYE_RELIEF_DIAL = 3;
public readonly float[] OVR_DEFAULT_CAMERA_POSITION = {0,0,0,1,0,0,0};
private IntPtr HmdPtr;
private bool IsUserAllocated = false;
// Used to return color result to avoid per-frame allocation.
private byte[] LatencyTestRgb = new byte[3];
// -----------------------------------------------------------------------------------
// Static Methods
/// <summary>
/// ovr_InitializeRenderingShim initializes the rendering shim apart from everything
/// else in LibOVR. This may be helpful if the application prefers to avoid
/// creating any OVR resources (allocations, service connections, etc) at this point.
/// ovr_InitializeRenderingShim does not bring up anything within LibOVR except the
/// necessary hooks to enable the Direct-to-Rift functionality.
///
/// Either ovr_InitializeRenderingShim() or ovr_Initialize() must be called before any
/// Direct3D or OpenGL initialization is done by application (creation of devices, etc).
/// ovr_Initialize() must still be called after to use the rest of LibOVR APIs.
///
/// Same as ovr_InitializeRenderingShim except it requests to support at least the
/// given minor LibOVR library version.
/// </summary>
public static bool InitializeRenderingShim(int requestedMinorVersion)
{
return ovr_InitializeRenderingShim(requestedMinorVersion) != 0;
}
public static bool InitializeRenderingShim()
{
return ovr_InitializeRenderingShim() != 0;
}
/// Library init/shutdown, must be called around all other OVR code.
/// No other functions calls besides ovr_InitializeRenderingShim are allowed
/// before ovr_Initialize succeeds or after ovr_Shutdown.
/// <summary>
/// Initializes all Oculus functionality.
/// A second call to Initialize after successful second call returns true.
/// </summary>
public static bool Initialize(InitParams Params)
{
return ovr_Initialize(Params) != 0;
}
/// <summary>
/// Shuts down all Oculus functionality.
/// </summary>
public static void Shutdown()
{
ovr_Shutdown();
}
/// <summary>
/// Returns version string representing libOVR version.
/// </summary>
public static string GetVersionString()
{
return Marshal.PtrToStringAnsi(ovr_GetVersionString());
}
/// <summary>
/// Detects or re-detects HMDs and reports the total number detected.
/// Users can get information about each HMD by calling ovrHmd_Create with an index.
/// Returns -1 when the service is unreachable.
/// </summary>
public static int Detect()
{
return ovrHmd_Detect();
}
/// <summary>
/// Enumerates modifications to the projection matrix based on the application's needs
/// </summary>
[Flags]
public enum ProjectionModifier
{
/// <summary>
/// Use for generating a default projection matrix that is:
/// * Left-handed
/// * Near depth values stored in the depth buffer are smaller than far depth values
/// * Both near and far are explicitly defined
/// * With a clipping range that is (0 to w)
/// </summary>
None = 0x00,
/// <summary>
/// Enable if using right-handed transformations in your application
/// </summary>
RightHanded = 0x01,
/// <summary>
/// After projection transform is applied, far values stored in the depth buffer will be less than closer depth values
/// NOTE: Enable only if application is using a floating-point depth buffer for proper precision
/// </summary>
FarLessThanNear = 0x02,
/// <summary>
/// When this flag is used, the zfar value pushed into ovrMatrix4f_Projection() will be ignored
/// NOTE: Enable only if ovrProjection_FarLessThanNear is also enabled where the far clipping plane will be pushed to infinity
/// </summary>
FarClipAtInfinity = 0x04,
/// <summary>
/// Enable if application is rendering with OpenGL and expects a projection matrix with a clipping range of (-w to w)
/// Ignore this flag if your application already handles the conversion from D3D range (0 to w) to OpenGL
/// </summary>
ClipRangeOpenGL = 0x08,
}
/// <summary>
/// Used to generate projection from ovrEyeDesc::Fov.
/// </summary>
public static Matrix4f GetProjection(
FovPort fov,
float znear,
float zfar,
uint projectionModFlags)
{
return new Matrix4f(ovrMatrix4f_Projection(
fov,
znear,
zfar,
projectionModFlags));
}
/// <summary>
/// Used for 2D rendering, Y is down
/// orthoScale = 1.0f / pixelsPerTanAngleAtCenter
/// orthoDistance = distance from camera, such as 0.8m
/// </summary>
public static Matrix4f GetOrthoSubProjection(Matrix4f projection, Vector2f orthoScale, float orthoDistance, float hmdToEyeViewOffsetX)
{
return new Matrix4f(ovrMatrix4f_OrthoSubProjection(projection, orthoScale, orthoDistance, hmdToEyeViewOffsetX));
}
/// <summary>
/// Returns global, absolute high-resolution time in seconds. This is the same
/// value as used in sensor messages.
/// </summary>
public static double GetTimeInSeconds()
{
return ovr_GetTimeInSeconds();
}
/// <summary>
/// Waits until the specified absolute time.
/// </summary>
public static double WaitTillTime(double absTime)
{
return ovr_WaitTillTime(absTime);
}
// -----------------------------------------------------------------------------------
// **** Constructor
/// <summary>
/// Creates an HMD and the underlying native ovrHmd pointer at the given index.
/// Index can [0 .. ovrHmd_Detect()-1]. Index mappings can cange after each ovrHmd_Detect call.
/// </summary>
public Hmd(int index)
{
this.HmdPtr = ovrHmd_Create(index);
if (this.HmdPtr == IntPtr.Zero)
throw new ArgumentException("Failed to create HMD at index " + index);
}
/// <summary>
/// Constructs an Hmd that wraps the given native ovrHmd pointer.
/// </summary>
public Hmd(IntPtr hmdPtr)
{
this.HmdPtr = hmdPtr;
IsUserAllocated = true;
}
/// <summary>
/// Creates a 'fake' HMD used for debugging only. This is not tied to specific hardware,
/// but may be used to debug some of the related rendering.
/// </summary>
public Hmd(HmdType type)
{
this.HmdPtr = ovrHmd_CreateDebug(type);
if (this.HmdPtr == IntPtr.Zero)
throw new ArgumentException("Failed to create debug HMD of type " + type);
}
~Hmd()
{
Dispose();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Ovr.Hmd"/>. The <see cref="Dispose"/> method
/// leaves the <see cref="Ovr.Hmd"/> in an unusable state. After calling <see cref="Dispose"/>, you must release all
/// references to the <see cref="Ovr.Hmd"/> so the garbage collector can reclaim the memory that the
/// <see cref="Ovr.Hmd"/> was occupying.</remarks>
public void Dispose()
{
if (!IsUserAllocated && this.HmdPtr != IntPtr.Zero)
{
ovrHmd_Destroy(this.HmdPtr);
this.HmdPtr = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Returns last error for HMD state. Returns null for no error.
/// String is valid until next call or GetLastError or HMD is destroyed.
/// </summary>
public string GetLastError()
{
return ovrHmd_GetLastError(HmdPtr);
}
/// <summary>
/// Platform specific function to specify the application window whose output will be
/// displayed on the HMD. Only used if the ovrHmdCap_ExtendDesktop flag is false.
/// Windows: SwapChain associated with this window will be displayed on the HMD.
/// Specify 'destMirrorRect' in window coordinates to indicate an area
/// of the render target output that will be mirrored from 'sourceRenderTargetRect'.
/// Null pointers mean "full size".
/// @note Source and dest mirror rects are not yet implemented.
/// </summary>
public bool AttachToWindow(Recti destMirrorRect, Recti sourceRenderTargetRect, IntPtr WindowPtr)
{
return ovrHmd_AttachToWindow(HmdPtr, WindowPtr, destMirrorRect, sourceRenderTargetRect) != 0;
}
/// <summary>
/// Returns capability bits that are enabled at this time as described by ovrHmdCaps.
/// Note that this value is different font ovrHmdDesc::HmdCaps, which describes what
/// capabilities are available for that HMD.
/// </summary>
public uint GetEnabledCaps()
{
return ovrHmd_GetEnabledCaps(HmdPtr);
}
/// <summary>
/// Modifies capability bits described by ovrHmdCaps that can be modified,
/// such as ovrHmdCap_LowPersistance.
/// </summary>
public void SetEnabledCaps(uint capsBits)
{
ovrHmd_SetEnabledCaps(HmdPtr, capsBits);
}
/// <summary>
/// Returns an ovrHmdDesc, which provides a complete description for the HMD
/// </summary>
public HmdDesc GetDesc()
{
if (IntPtr.Size == 8)
{
HmdDesc_Raw64 rawDesc = (HmdDesc_Raw64)Marshal.PtrToStructure(HmdPtr, typeof(HmdDesc_Raw64));
return new HmdDesc(rawDesc);
}
else
{
HmdDesc_Raw32 rawDesc = (HmdDesc_Raw32)Marshal.PtrToStructure(HmdPtr, typeof(HmdDesc_Raw32));
return new HmdDesc(rawDesc);
}
}
//-------------------------------------------------------------------------------------
// ***** Tracking Interface
/// <summary>
/// All tracking interface functions are thread-safe, allowing tracking state to be sampled
/// from different threads.
/// ConfigureTracking starts sensor sampling, enabling specified capabilities,
/// described by ovrTrackingCaps.
/// - supportedTrackingCaps specifies support that is requested. The function will succeed
/// even if these caps are not available (i.e. sensor or camera is unplugged). Support
/// will automatically be enabled if such device is plugged in later. Software should
/// check ovrTrackingState.StatusFlags for real-time status.
/// - requiredTrackingCaps specify sensor capabilities required at the time of the call.
/// If they are not available, the function will fail. Pass 0 if only specifying
/// supportedTrackingCaps.
/// - Pass 0 for both supportedTrackingCaps and requiredTrackingCaps to disable tracking.
/// </summary>
public bool ConfigureTracking(uint supportedTrackingCaps, uint requiredTrackingCaps)
{
return ovrHmd_ConfigureTracking(HmdPtr, supportedTrackingCaps, requiredTrackingCaps) != 0;
}
/// <summary>
/// Re-centers the sensor orientation.
/// Normally this will recenter the (x,y,z) translational components and the yaw
/// component of orientation.
/// </summary>
public void RecenterPose()
{
ovrHmd_RecenterPose(HmdPtr);
}
/// <summary>
/// Returns tracking state reading based on the specified absolute system time.
/// Pass an absTime value of 0.0 to request the most recent sensor reading. In this case
/// both PredictedPose and SamplePose will have the same value.
/// ovrHmd_GetEyePoses relies on this function internally.
/// This may also be used for more refined timing of FrontBuffer rendering logic, etc.
/// </summary>
public TrackingState GetTrackingState(double absTime)
{
return ovrHmd_GetTrackingState(HmdPtr, absTime);
}
/// <summary>
/// The following is deprecated.
/// </summary>
public void ResetOnlyBackOfHeadTrackingForConnectConf()
{
ovrHmd_ResetOnlyBackOfHeadTrackingForConnectConf(HmdPtr);
}
//-------------------------------------------------------------------------------------
// ***** Graphics Setup
/// <summary>
/// Calculates the recommended texture size for rendering a given eye within the HMD
/// with a given FOV cone. Higher FOV will generally require larger textures to
/// maintain quality.
/// - pixelsPerDisplayPixel specifies the ratio of the number of render target pixels
/// to display pixels at the center of distortion. 1.0 is the default value. Lower
/// values can improve performance.
/// </summary>
public Sizei GetFovTextureSize(Eye eye, FovPort fov, float pixelsPerDisplayPixel)
{
return ovrHmd_GetFovTextureSize(HmdPtr, eye, fov, pixelsPerDisplayPixel);
}
//-------------------------------------------------------------------------------------
// ***** Rendering API Thread Safety
// All of rendering functions including the configure and frame functions
// are *NOT thread safe*. It is ok to use ConfigureRendering on one thread and handle
// frames on another thread, but explicit synchronization must be done since
// functions that depend on configured state are not reentrant.
//
// As an extra requirement, any of the following calls must be done on
// the render thread, which is the same thread that calls ovrHmd_BeginFrame
// or ovrHmd_BeginFrameTiming.
// - ovrHmd_EndFrame
// - ovrHmd_GetEyeTimewarpMatrices
//-------------------------------------------------------------------------------------
// ***** SDK Distortion Rendering Functions
// These functions support rendering of distortion by the SDK through direct
// access to the underlying rendering API, such as D3D or GL.
// This is the recommended approach since it allows better support for future
// Oculus hardware, and enables a range of low-level optimizations.
/// <summary>
/// Configures rendering and fills in computed render parameters.
/// This function can be called multiple times to change rendering settings.
/// eyeRenderDescOut is a pointer to an array of two EyeRenderDesc structs
/// that are used to return complete rendering information for each eye.
/// - apiConfig provides D3D/OpenGL specific parameters. Pass null
/// to shutdown rendering and release all resources.
/// - distortionCaps describe desired distortion settings.
/// </summary>
public EyeRenderDesc[] ConfigureRendering(ref RenderAPIConfig renderAPIConfig, FovPort[] eyeFovIn, uint distortionCaps)
{
EyeRenderDesc[] eyeRenderDesc = new EyeRenderDesc[] { new EyeRenderDesc(), new EyeRenderDesc() };
RenderAPIConfig_Raw rawConfig = renderAPIConfig.ToRaw();
bool result = ovrHmd_ConfigureRendering(HmdPtr, ref rawConfig, distortionCaps, eyeFovIn, eyeRenderDesc) != 0;
if (result)
return eyeRenderDesc;
return null;
}
/// <summary>
/// Begins a frame, returning timing information.
/// This should be called at the beginning of the game rendering loop (on the render thread).
/// Pass 0 for the frame index if not using ovrHmd_GetFrameTiming.
/// </summary>
public FrameTiming BeginFrame(uint frameIndex)
{
FrameTiming_Raw raw = ovrHmd_BeginFrame(HmdPtr, frameIndex);
return new FrameTiming(raw);
}
/// <summary>
/// Ends a frame, submitting the rendered textures to the frame buffer.
/// - RenderViewport within each eyeTexture can change per frame if necessary.
/// - 'renderPose' will typically be the value returned from ovrHmd_GetEyePoses,
/// ovrHmd_GetHmdPosePerEye but can be different if a different head pose was
/// used for rendering.
/// - This may perform distortion and scaling internally, assuming is it not
/// delegated to another thread.
/// - Must be called on the same thread as BeginFrame.
/// - *** This Function will call Present/SwapBuffers and potentially wait for GPU Sync ***.
/// </summary>
public void EndFrame(Posef[] renderPose, Texture[] eyeTexture)
{
Texture_Raw[] raw = new Texture_Raw[eyeTexture.Length];
for (int i = 0; i < eyeTexture.Length; i++)
{
raw[i] = eyeTexture[i].ToRaw();
}
ovrHmd_EndFrame(HmdPtr, renderPose, raw);
}
/// <summary>
/// Returns predicted head pose in outHmdTrackingState and offset eye poses in outEyePoses
/// as an atomic operation. Caller need not worry about applying HmdToEyeViewOffset to the
/// returned outEyePoses variables.
/// - Thread-safe function where caller should increment frameIndex with every frame
/// and pass the index where applicable to functions called on the rendering thread.
/// - hmdToEyeViewOffset[2] can be EyeRenderDesc.HmdToEyeViewOffset returned from
/// ovrHmd_ConfigureRendering or ovrHmd_GetRenderDesc. For monoscopic rendering,
/// use a vector that is the average of the two vectors for both eyes.
/// - If frameIndex is not being utilized, pass in 0.
/// - Assuming outEyePoses are used for rendering, it should be passed into ovrHmd_EndFrame.
/// - If caller doesn't need outHmdTrackingState, it can be passed in as NULL
/// </summary>
public Posef[] GetEyePoses(uint frameIndex)
{
FovPort leftFov = GetDesc().DefaultEyeFov[(int)Eye.Left];
FovPort rightFov = GetDesc().DefaultEyeFov[(int)Eye.Right];
EyeRenderDesc leftDesc = GetRenderDesc(Eye.Left, leftFov);
EyeRenderDesc rightDesc = GetRenderDesc(Eye.Right, rightFov);
TrackingState trackingState = new TrackingState();
Vector3f[] eyeOffsets = { leftDesc.HmdToEyeViewOffset, rightDesc.HmdToEyeViewOffset };
Posef[] eyePoses = { new Posef(), new Posef() };
ovrHmd_GetEyePoses(HmdPtr, frameIndex, eyeOffsets, eyePoses, ref trackingState);
return eyePoses;
}
/// <summary>
/// Function was previously called ovrHmd_GetEyePose
/// Returns the predicted head pose to use when rendering the specified eye.
/// - Important: Caller must apply HmdToEyeViewOffset before using ovrPosef for rendering
/// - Must be called between ovrHmd_BeginFrameTiming and ovrHmd_EndFrameTiming.
/// - If returned pose is used for rendering the eye, it should be passed to ovrHmd_EndFrame.
/// - Parameter 'eye' is used internally for prediction timing only
/// </summary>
public Posef GetHmdPosePerEye(Eye eye)
{
return ovrHmd_GetHmdPosePerEye(HmdPtr, eye);
}
//-------------------------------------------------------------------------------------
// ***** Client Distortion Rendering Functions
// These functions provide the distortion data and render timing support necessary to allow
// client rendering of distortion. Client-side rendering involves the following steps:
//
// 1. Setup ovrEyeDesc based on the desired texture size and FOV.
// Call ovrHmd_GetRenderDesc to get the necessary rendering parameters for each eye.
//
// 2. Use ovrHmd_CreateDistortionMesh to generate the distortion mesh.
//
// 3. Use ovrHmd_BeginFrameTiming, ovrHmd_GetEyePoses, and ovrHmd_BeginFrameTiming in
// the rendering loop to obtain timing and predicted head orientation when rendering each eye.
// - When using timewarp, use ovr_WaitTillTime after the rendering and gpu flush, followed
// by ovrHmd_GetEyeTimewarpMatrices to obtain the timewarp matrices used
// by the distortion pixel shader. This will minimize latency.
//
/// <summary>
/// Computes the distortion viewport, view adjust, and other rendering parameters for
/// the specified eye. This can be used instead of ovrHmd_ConfigureRendering to do
/// setup for client rendered distortion.
/// </summary>
public EyeRenderDesc GetRenderDesc(Eye eyeType, FovPort fov)
{
return ovrHmd_GetRenderDesc(HmdPtr, eyeType, fov);
}
/// <summary>
/// Generate distortion mesh per eye.
/// Distortion capabilities will depend on 'distortionCaps' flags. Users should
/// render using the appropriate shaders based on their settings.
/// Distortion mesh data will be allocated and written into the ovrDistortionMesh data structure,
/// which should be explicitly freed with ovrHmd_DestroyDistortionMesh.
/// Users should call ovrHmd_GetRenderScaleAndOffset to get uvScale and Offset values for rendering.
/// The function shouldn't fail unless theres is a configuration or memory error, in which case
/// ovrDistortionMesh values will be set to null.
/// This is the only function in the SDK reliant on eye relief, currently imported from profiles,
/// or overridden here.
/// </summary>
public DistortionMesh? CreateDistortionMesh(Eye eye, FovPort fov, uint distortionCaps)
{
DistortionMesh_Raw rawMesh = new DistortionMesh_Raw();
bool result = ovrHmd_CreateDistortionMesh(HmdPtr, eye, fov, distortionCaps, out rawMesh) != 0;
if (!result)
{
return null;
}
DistortionMesh mesh = new DistortionMesh(rawMesh);
ovrHmd_DestroyDistortionMesh(ref rawMesh);
return mesh;
}
public DistortionMesh? CreateDistortionMeshDebug(Eye eye, FovPort fov, uint distortionCaps, float debugEyeReliefOverrideInMeters)
{
DistortionMesh_Raw rawMesh = new DistortionMesh_Raw();
bool result = ovrHmd_CreateDistortionMeshDebug(
HmdPtr,
eye,
fov,
distortionCaps,
out rawMesh,
debugEyeReliefOverrideInMeters) != 0;
if (!result)
{
return null;
}
DistortionMesh mesh = new DistortionMesh(rawMesh);
ovrHmd_DestroyDistortionMesh(ref rawMesh);
return mesh;
}
/// <summary>
/// Computes updated 'uvScaleOffsetOut' to be used with a distortion if render target size or
/// viewport changes after the fact. This can be used to adjust render size every frame if desired.
/// </summary>
public Vector2f[] GetRenderScaleAndOffset(FovPort fov, Sizei textureSize, Recti renderViewport)
{
Vector2f[] uvScaleOffsetOut = new Vector2f[] { new Vector2f(), new Vector2f() };
ovrHmd_GetRenderScaleAndOffset(fov, textureSize, renderViewport, uvScaleOffsetOut);
return uvScaleOffsetOut;
}
/// <summary>
/// Thread-safe timing function for the main thread. Caller should increment frameIndex
/// with every frame and pass the index where applicable to functions called on the
/// rendering thread.
/// </summary>
public FrameTiming GetFrameTiming(uint frameIndex)
{
FrameTiming_Raw raw = ovrHmd_GetFrameTiming(HmdPtr, frameIndex);
return new FrameTiming(raw);
}
/// <summary>
/// Called at the beginning of the frame on the rendering thread.
/// Pass frameIndex == 0 if ovrHmd_GetFrameTiming isn't being used. Otherwise,
/// pass the same frame index as was used for GetFrameTiming on the main thread.
/// </summary>
public FrameTiming BeginFrameTiming(uint frameIndex)
{
FrameTiming_Raw raw = ovrHmd_BeginFrameTiming(HmdPtr, frameIndex);
return new FrameTiming(raw);
}
/// <summary>
/// Marks the end of client distortion rendered frame, tracking the necessary timing information.
/// This function must be called immediately after Present/SwapBuffers + GPU sync. GPU sync is
/// important before this call to reduce latency and ensure proper timing.
/// </summary>
public void EndFrameTiming()
{
ovrHmd_EndFrameTiming(HmdPtr);
}
/// <summary>
/// Initializes and resets frame time tracking. This is typically not necessary, but
/// is helpful if game changes vsync state or video mode. vsync is assumed to be on if this
/// isn't called. Resets internal frame index to the specified number.
/// </summary>
public void ResetFrameTiming(uint frameIndex)
{
ovrHmd_ResetFrameTiming(HmdPtr, frameIndex);
}
/// <summary>
/// Computes timewarp matrices used by distortion mesh shader, these are used to adjust
/// for head orientation change since the last call to ovrHmd_GetEyePoses
/// when rendering this eye. The ovrDistortionVertex::TimeWarpFactor is used to blend between the
/// matrices, usually representing two different sides of the screen.
/// Must be called on the same thread as ovrHmd_BeginFrameTiming.
/// </summary>
public Matrix4f[] GetEyeTimewarpMatrices(Eye eye, Posef renderPose)
{
Matrix4f_Raw[] rawMats = {new Matrix4f_Raw(), new Matrix4f_Raw()};
ovrHmd_GetEyeTimewarpMatrices(HmdPtr, eye, renderPose, rawMats);
Matrix4f[] mats = {new Matrix4f(rawMats[0]), new Matrix4f(rawMats[1])};
return mats;
}
public Matrix4f[] GetEyeTimewarpMatricesDebug(Eye eye, Posef renderPose, Quatf extraQuat, double debugTimingOffsetInSeconds)
{
Matrix4f_Raw[] rawMats = {new Matrix4f_Raw(), new Matrix4f_Raw()};
ovrHmd_GetEyeTimewarpMatricesDebug(HmdPtr, eye, renderPose, extraQuat, rawMats, debugTimingOffsetInSeconds);
Matrix4f[] mats = {new Matrix4f(rawMats[0]), new Matrix4f(rawMats[1])};
return mats;
}
// -----------------------------------------------------------------------------------
// ***** Latency Test interface
/// <summary>
/// Does latency test processing and returns 'TRUE' if specified rgb color should
/// be used to clear the screen.
/// </summary>
public byte[] ProcessLatencyTest()
{
if (ovrHmd_ProcessLatencyTest(HmdPtr, LatencyTestRgb) != 0)
return LatencyTestRgb;
return null;
}
/// <summary>
/// Returns non-null string once with latency test result, when it is available.
/// Buffer is valid until next call.
/// </summary>
public string GetLatencyTestResult()
{
IntPtr p = ovrHmd_GetLatencyTestResult(HmdPtr);
return (p == IntPtr.Zero) ? null : Marshal.PtrToStringAnsi(p);
}
/// <summary>
/// Returns the latency testing color in rgbColorOut to render when using a DK2
/// Returns false if this feature is disabled or not-applicable (e.g. using a DK1)
/// </summary>
public byte[] GetLatencyTest2DrawColor()
{
if (ovrHmd_GetLatencyTest2DrawColor(HmdPtr, LatencyTestRgb) != 0)
return LatencyTestRgb;
return null;
}
//-------------------------------------------------------------------------------------
// ***** Health and Safety Warning Display interface
//
/// <summary>
/// Returns the current state of the HSW display. If the application is doing the rendering of
/// the HSW display then this function serves to indicate that the warning should be
/// currently displayed. If the application is using SDK-based eye rendering then the SDK by
/// default automatically handles the drawing of the HSW display. An application that uses
/// application-based eye rendering should use this function to know when to start drawing the
/// HSW display itself and can optionally use it in conjunction with ovrhmd_DismissHSWDisplay
/// as described below.
///
/// Example usage for application-based rendering:
/// bool HSWDisplayCurrentlyDisplayed = false; // global or class member variable
/// ovrHSWDisplayState hswDisplayState = hmd.GetHSWDisplayState();
///
/// if (hswDisplayState.Displayed && !HSWDisplayCurrentlyDisplayed)
/// {
/// <insert model into the scene that stays in front of the user>
/// HSWDisplayCurrentlyDisplayed = true;
/// }
/// </summary>
public HSWDisplayState GetHSWDisplayState()
{
HSWDisplayState hswDisplayState;
ovrHmd_GetHSWDisplayState(HmdPtr, out hswDisplayState);
return hswDisplayState;
}
/// <summary>
/// Requests a dismissal of the HSWDisplay at the earliest possible time, which may be seconds
/// into the future due to display longevity requirements.
/// Returns true if the display is valid, in which case the request can always be honored.
///
/// Example usage :
/// void ProcessEvent(int key) {
/// if (key == escape)
/// hmd.DismissHSWDisplay();
/// }
/// <summary>
public bool DismissHSWDisplay()
{
return ovrHmd_DismissHSWDisplay(HmdPtr) != 0;
}
// -----------------------------------------------------------------------------------
// ***** Property Access
// NOTICE: This is experimental part of API that is likely to go away or change.
// These allow accessing different properties of the HMD and profile.
// Some of the properties may go away with profile/HMD versions, so software should
// use defaults and/or proper fallbacks.
/// <summary>
/// Get boolean property. Returns first element if property is a boolean array.
/// Returns defaultValue if property doesn't exist.
/// </summary>
public bool GetBool(string propertyName, bool defaultVal)
{
return ovrHmd_GetBool(HmdPtr, propertyName, Convert.ToSByte(defaultVal)) != 0;
}
/// <summary>
/// Modify bool property; false if property doesn't exist or is readonly.
/// </summary>
public bool SetBool(string propertyName, bool val)
{
return ovrHmd_SetBool(HmdPtr, propertyName, Convert.ToSByte(val)) != 0;
}
/// <summary>
/// Get integer property. Returns first element if property is an integer array.
/// Returns defaultValue if property doesn't exist.
/// </summary>
public int GetInt(string propertyName, int defaultVal)
{
return ovrHmd_GetInt(HmdPtr, propertyName, defaultVal);
}
/// <summary>
/// Modify integer property; false if property doesn't exist or is readonly.
/// </summary>
public bool SetInt(string propertyName, int val)
{
return ovrHmd_SetInt(HmdPtr, propertyName, val) != 0;
}
/// <summary>
/// Get float property. Returns first element if property is a float array.
/// Returns defaultValue if property doesn't exist.
/// </summary>
public float GetFloat(string propertyName, float defaultVal)
{
return ovrHmd_GetFloat(HmdPtr, propertyName, defaultVal);
}
/// <summary>
/// Modify float property; false if property doesn't exist or is readonly.
/// </summary>
public bool SetFloat(string propertyName, float val)
{
return ovrHmd_SetFloat(HmdPtr, propertyName, val) != 0;
}
/// <summary>
/// Get float[] property. Returns the number of elements filled in, 0 if property doesn't exist.
/// Maximum of arraySize elements will be written.
/// </summary>
public float[] GetFloatArray(string propertyName, float[] values)
{
if (values == null)
return null;
ovrHmd_GetFloatArray(HmdPtr, propertyName, values, (uint)values.Length);
return values;
}
/// <summary>
/// Modify float[] property; false if property doesn't exist or is readonly.
/// </summary>
public bool SetFloatArray(string propertyName, float[] values)
{
if (values == null)
values = new float[0];
return ovrHmd_SetFloatArray(HmdPtr, propertyName, values, (uint)values.Length) != 0;
}
/// <summary>
/// Get string property. Returns first element if property is a string array.
/// Returns defaultValue if property doesn't exist.
/// String memory is guaranteed to exist until next call to GetString or GetStringArray, or HMD is destroyed.
/// </summary>
public string GetString(string propertyName, string defaultVal)
{
IntPtr p = ovrHmd_GetString(HmdPtr, propertyName, null);
if (p == IntPtr.Zero)
return defaultVal;
return Marshal.PtrToStringAnsi(p);
}
/// <summary>
/// Set string property
/// </summary>
public bool SetString(string propertyName, string val)
{
return ovrHmd_SetString(HmdPtr, propertyName, val) != 0;
}
// -----------------------------------------------------------------------------------
// ***** Logging
/// <summary>
/// Start performance logging. guid is optional and if included is written with each file entry.
/// If called while logging is already active with the same filename, only the guid will be updated
/// If called while logging is already active with a different filename, ovrHmd_StopPerfLog() will be called, followed by ovrHmd_StartPerfLog()
/// </summary>
public bool StartPerfLog(string fileName, string userData1)
{
return ovrHmd_StartPerfLog(HmdPtr, fileName, userData1) != 0;
}
/// <summary>
/// Stop performance logging.
/// </summary>
public bool StopPerfLog()
{
return ovrHmd_StopPerfLog(HmdPtr) != 0;
}
public const string LibFile = "OculusPlugin";
// Imported functions from
// OVRPlugin.dll (PC)
// OVRPlugin.bundle (OSX)
// OVRPlugin.so (Linux, Android)
// -----------------------------------------------------------------------------------
// ***** Private Interface to libOVR
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovr_InitializeRenderingShim(int requestedMinorVersion);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovr_InitializeRenderingShim();
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovr_Initialize(InitParams Params);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovr_Shutdown();
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ovr_GetVersionString();
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int ovrHmd_Detect();
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ovrHmd_Create(int index);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_Destroy(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ovrHmd_CreateDebug(HmdType type);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern string ovrHmd_GetLastError(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_AttachToWindow(
IntPtr hmd,
IntPtr window,
Recti destMirrorRect,
Recti sourceRenderTargetRect);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ovrHmd_GetEnabledCaps(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_SetEnabledCaps(IntPtr hmd, uint capsBits);
//-------------------------------------------------------------------------------------
// ***** Sensor Interface
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_ConfigureTracking(
IntPtr hmd,
uint supportedTrackingCaps,
uint requiredTrackingCaps);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_RecenterPose(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern TrackingState ovrHmd_GetTrackingState(IntPtr hmd, double absTime);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_ResetOnlyBackOfHeadTrackingForConnectConf(IntPtr hmd);
//-------------------------------------------------------------------------------------
// ***** Graphics Setup
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern Sizei ovrHmd_GetFovTextureSize(
IntPtr hmd,
Eye eye,
FovPort fov,
float pixelsPerDisplayPixel);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_ConfigureRendering(
IntPtr hmd,
ref RenderAPIConfig_Raw apiConfig,
uint distortionCaps,
[In] FovPort[] eyeFovIn,
[In, Out] EyeRenderDesc[] eyeRenderDescOut);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern FrameTiming_Raw ovrHmd_BeginFrame(IntPtr hmd, uint frameIndex);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_EndFrame(
IntPtr hmd,
[In] Posef[] renderPose,
[In] Texture_Raw[] eyeTexture);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_GetEyePoses(
IntPtr hmd,
uint frameIndex,
[In] Vector3f[] hmdToEyeViewOffset,
[In, Out] Posef[] eyePosesOut,
[In, Out] ref TrackingState hmdTrackingStateOut);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern Posef ovrHmd_GetHmdPosePerEye(
IntPtr hmd,
Eye eye);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern EyeRenderDesc ovrHmd_GetRenderDesc(IntPtr hmd, Eye eye, FovPort fov);
// -----------------------------------------------------------------------------------
// **** Game-side rendering API
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_CreateDistortionMesh(
IntPtr hmd,
Eye eye,
FovPort fov,
uint distortionCaps,
[Out] out DistortionMesh_Raw meshData);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_CreateDistortionMeshDebug(
IntPtr hmd,
Eye eye,
FovPort fov,
uint distortionCaps,
[Out] out DistortionMesh_Raw meshData,
float debugEyeReliefOverrideInMeters);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_DestroyDistortionMesh(ref DistortionMesh_Raw meshData);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_GetRenderScaleAndOffset(
FovPort fov,
Sizei textureSize,
Recti renderViewport,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
[Out] Vector2f[] uvScaleOffsetOut);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern FrameTiming_Raw ovrHmd_GetFrameTiming(IntPtr hmd, uint frameIndex);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern FrameTiming_Raw ovrHmd_BeginFrameTiming(IntPtr hmd, uint frameIndex);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_EndFrameTiming(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_ResetFrameTiming(IntPtr hmd, uint frameIndex);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_GetEyeTimewarpMatrices(
IntPtr hmd,
Eye eye,
Posef renderPose,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
[Out] Matrix4f_Raw[] twnOut);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_GetEyeTimewarpMatricesDebug(
IntPtr hmd,
Eye eye,
Posef renderPose,
Quatf extraQuat,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 2)]
[Out] Matrix4f_Raw[] twnOut,
double debugTimingOffsetInSeconds);
//-------------------------------------------------------------------------------------
// Stateless math setup functions
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern Matrix4f_Raw ovrMatrix4f_Projection(
FovPort fov,
float znear,
float zfar,
uint projectionModFlags);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern Matrix4f_Raw ovrMatrix4f_OrthoSubProjection(
Matrix4f projection,
Vector2f orthoScale,
float orthoDistance,
float hmdToEyeViewOffsetX);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern double ovr_GetTimeInSeconds();
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern double ovr_WaitTillTime(double absTime);
// -----------------------------------------------------------------------------------
// ***** Latency Test interface
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_ProcessLatencyTest(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 3)]
[Out] byte[] rgbColorOut);
// Returns IntPtr to avoid allocation.
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ovrHmd_GetLatencyTestResult(IntPtr hmd);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_GetLatencyTest2DrawColor(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPArray, SizeConst = 3)]
[Out] byte[] rgbColorOut);
//-------------------------------------------------------------------------------------
// ***** Health and Safety Warning Display interface
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern void ovrHmd_GetHSWDisplayState(
IntPtr hmd,
[Out] out HSWDisplayState hasWarningState);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_DismissHSWDisplay(IntPtr hmd);
// -----------------------------------------------------------------------------------
// ***** Property Access
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_GetBool(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
sbyte defaultVal);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_SetBool(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
sbyte val);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int ovrHmd_GetInt(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
int defaultVal);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_SetInt(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
int val);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern float ovrHmd_GetFloat(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
float defaultVal);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_SetFloat(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
float val);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ovrHmd_GetFloatArray(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
float[] values, // TBD: Passing var size?
uint arraySize);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_SetFloatArray(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
float[] values, // TBD: Passing var size?
uint arraySize);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ovrHmd_GetString(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
[MarshalAs(UnmanagedType.LPStr)]
string defaultVal);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_SetString(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string propertyName,
[MarshalAs(UnmanagedType.LPStr)]
string val);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_StartPerfLog(
IntPtr hmd,
[MarshalAs(UnmanagedType.LPStr)]
string fileName,
[MarshalAs(UnmanagedType.LPStr)]
string userData1);
[DllImport(LibFile, CallingConvention = CallingConvention.Cdecl)]
private static extern sbyte ovrHmd_StopPerfLog(IntPtr hmd);
}
}
| 42.493666 | 245 | 0.586087 | [
"Apache-2.0"
] | lilshim/stock-market-visual | Assets/OVR/Scripts/OvrCapi.cs | 107,339 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace SharpIRC.API {
internal class Events {
internal void ChanMsg(IRCConnection connection, string message, string host, string channel) {
if (host.IsIgnored() || connection.DelayActive) return;
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new ChannelMessage {Channel = channel.ToLower(), Connection = connection, Message = message, Sender = newUser, Type = MessageTypes.PRIVMSG};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, channel, String.Format("({0}) <{1}> {2}", newMsg.Sender.Level, newMsg.Sender.Nick, newMsg.Message));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.ChanMsg(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void ChanAction(IRCConnection connection, string message, string host, string channel) {
if (host.IsIgnored() || connection.DelayActive) return;
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new ChannelMessage {Channel = channel.ToLower(), Connection = connection, Message = message, Sender = newUser, Type = MessageTypes.ACTION};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, channel, String.Format("({0}) * {1} {2}", newMsg.Sender.Level, newMsg.Sender.Nick, newMsg.Message));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.ChanAction(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void PrivMsg(IRCConnection connection, string message, string host) {
if (host.IsIgnored()) return;
var newUser = new IRCUser {Host = host, Level = UserLevel.Normal, Nick = Functions.NickFromHost(host), RealName = ""};
var newMsg = new PrivateMessage {Connection = connection, Sender = newUser, Message = message, Type = MessageTypes.PRIVMSG};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Sender.Nick, String.Format("<{0}> {1}", newMsg.Sender.Nick, newMsg.Message));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.PrivMsg(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void PrivAction(IRCConnection connection, string message, string host) {
if (host.IsIgnored()) return;
var newUser = new IRCUser {Host = host, Level = UserLevel.Normal, Nick = Functions.NickFromHost(host), RealName = ""};
var newMsg = new PrivateMessage {Connection = connection, Sender = newUser, Message = message, Type = MessageTypes.ACTION};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Sender.Nick, String.Format("* {0} {1}", newMsg.Sender.Nick, newMsg.Message));
foreach (PluginInterface Plugin in Program.Plugins) {
try {
Plugin.PrivAction(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void CTCP(IRCConnection connection, string message, string host, string channel) {
if (host.IsIgnored()) return;
var newUser = new IRCUser {Host = host, Level = UserLevel.Normal, Nick = Functions.NickFromHost(host), RealName = ""};
var newMsg = new CTCPMessage
{Connection = connection, Sender = newUser, Prefix = message.Split(' ')[0].Substring(0, message.Split(' ')[0].Length - 1), Message = Connect.JoinString(message.Split(' '), 1, false), Type = MessageTypes.CTCP};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.CTCP(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Notice(IRCConnection connection, string message, string host) {
if (host.IsIgnored()) return;
var newUser = new IRCUser {Host = host, Level = UserLevel.Normal, Nick = Functions.NickFromHost(host), RealName = ""};
var newMsg = new PrivateMessage {Connection = connection, Sender = newUser, Message = message, Type = MessageTypes.NOTICE};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Notice(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void ChanNotice(IRCConnection connection, string message, string host, string channel) {
if (host.IsIgnored() || connection.DelayActive) return;
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new ChannelMessage {Channel = channel.ToLower(), Connection = connection, Sender = newUser, Message = message, Type = MessageTypes.NOTICE};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.ChanNotice(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void CTCPREPLY(IRCConnection connection, string message, string host) {
if (host.IsIgnored()) return;
var newUser = new IRCUser {Host = host, Level = UserLevel.Normal, Nick = Functions.NickFromHost(host), RealName = ""};
var newMsg = new CTCPMessage {Connection = connection, Sender = newUser, Prefix = message.Split(' ')[0], Message = Connect.JoinString(message.Split(' '), 1, false), Type = MessageTypes.CTCPREPLY};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.CTCPREPLY(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Join(IRCConnection connection, string host, string channel) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new JoinMessage {Connection = connection, Sender = newUser, Channel = channel.ToLower(), Type = MessageTypes.JOIN};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Channel, String.Format("- {0} has joined the channel ({1})", newMsg.Sender.Nick, newMsg.Channel));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Join(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Part(IRCConnection connection, string host, string channel, string message) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new PartMessage {Connection = connection, Sender = newUser, Message = message, Channel = channel.ToLower(), Type = MessageTypes.PART};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Channel, String.Format("- {0} has left the channel (Message: )", newMsg.Sender.Nick, newMsg.Message));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Part(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Quit(IRCConnection connection, string host, string message) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new QuitMessage {Connection = connection, Sender = newUser, Message = message, Type = MessageTypes.QUIT};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Quit(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Nickchange(IRCConnection connection, string host, string newnick) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new NickChangeMessage {Connection = connection, Sender = newUser, NewNick = newnick, Type = MessageTypes.NICK};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.NickChange(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void TopicChange(IRCConnection connection, string host, string channel, string message) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new TopicChangeMessage {Connection = connection, Sender = newUser, Content = message, Channel = channel.ToLower(), Type = MessageTypes.TOPIC};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Channel, String.Format("- {0} has changed the topic: {1}", newMsg.Sender.Nick, newMsg.Content));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.TopicChange(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Kick(IRCConnection connection, string host, string channel, string kicked, string message) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var recieveUser = new IRCUser {Host = "", Level = UserLevel.Normal, Nick = kicked, RealName = ""};
var newMsg = new KickMessage {Connection = connection, Sender = newUser, Reciever = recieveUser, Message = message, Channel = channel.ToLower(), Type = MessageTypes.KICK};
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Channel, String.Format("- {0} has kicked {1} ({2})", newMsg.Sender.Nick, newMsg.Reciever.Nick, newMsg.Message));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Kick(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Modechange(IRCConnection connection, string host, string channel, string modes) {
IRCUser newUser = Functions.NickFromHost(host).IRCUserFromString(connection);
var newMsg = new ModeChangeMessage {Connection = connection, Sender = newUser, Modes = Functions.StringtoModeList(modes), Channel = channel.ToLower(), Type = MessageTypes.MODE};
if (modes.Split(' ').Length > 1) {
var newuMode = new UserPrivilegiesMessage {Connection = connection, Sender = newUser, Channel = channel.ToLower(), Type = MessageTypes.MODE};
foreach (UserModeChange mode in Functions.StringtoUserModeList(modes, connection, channel)) {
if (mode.Action == ModeStatus.Set) {
if (mode.Mode == 'q') {
newuMode.Change = LevelChange.Owner;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Owner(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'a') {
newuMode.Change = LevelChange.Admin;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Admin(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'o') {
newuMode.Change = LevelChange.Operator;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Chanop(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'h') {
newuMode.Change = LevelChange.Halfop;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Halfop(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'v') {
newuMode.Change = LevelChange.Voice;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Voice(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
}
if (mode.Action == ModeStatus.Removed) {
if (mode.Mode == 'q') {
newuMode.Change = LevelChange.OwnerRevoked;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.DeOwner(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'a') {
newuMode.Change = LevelChange.AdminRevoked;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.DeAdmin(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'o') {
newuMode.Change = LevelChange.OperatorRevoked;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.DeChanop(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'h') {
newuMode.Change = LevelChange.HalfopRevoked;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.DeHalfop(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
if (mode.Mode == 'v') {
newuMode.Change = LevelChange.VoiceRevoked;
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.DeVoice(newuMode);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
}
}
}
if (newMsg.Sender != null) Functions.LogHistory(connection.ActiveNetwork, newMsg.Channel, String.Format("- {0} has set channel modes: {1}", newMsg.Sender.Nick, modes));
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.ModeChange(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void Connected(IRCConnection connection) {
var newMsg = new ConnectedMessage {Connection = connection};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.Connected(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
internal void IRCMessage(IRCConnection connection, string Message) {
var newMsg = new IRCMessage {Connection = connection, Message = Message};
foreach (PluginInterface plugin in Program.Plugins) {
try {
plugin.IRCMessage(newMsg);
} catch (Exception e) {
Functions.LogError(e);
}
}
}
}
}
| 50.280556 | 221 | 0.501851 | [
"Apache-2.0"
] | kibmcz/SharpIRC | SharpIRC/SharpIRC/API/Events.cs | 18,103 | C# |
//
// IFromRouter.cs
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using JetBrains.Annotations;
namespace Couchbase.Lite.Query
{
/// <summary>
/// An interface representing a portion of a query that can be routed
/// to a FROM portion
/// </summary>
public interface IFromRouter
{
#region Public Methods
/// <summary>
/// Routes this IExpression to the nexe FROM portion of a query
/// </summary>
/// <param name="dataSource">The data source to use in the FROM portion of the query</param>
/// <returns>The next FROM portion of the query for further processing</returns>
[NotNull]
IFrom From([NotNull]IDataSource dataSource);
#endregion
}
}
| 31.52381 | 100 | 0.677492 | [
"Apache-2.0"
] | Pio1006/couchbase-lite-net | src/Couchbase.Lite.Shared/API/Query/IFromRouter.cs | 1,326 | C# |
using PresentationBase;
using Sungaila.SUBSTitute.Core;
using Sungaila.SUBSTitute.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Sungaila.SUBSTitute.Commands
{
public class BrowserRefreshDirectoryCommand
: ViewModelCommand<MainWindowViewModel>
{
public override void Execute(MainWindowViewModel parameter)
{
if (String.IsNullOrEmpty(parameter.BrowserRootDirectory))
return;
parameter.UpdateBrowserDirectories();
}
public override bool CanExecute(MainWindowViewModel parameter)
{
return base.CanExecute(parameter) && !String.IsNullOrEmpty(parameter.BrowserRootDirectory);
}
}
}
| 27.142857 | 103 | 0.703947 | [
"MIT"
] | DenisMtfl/SUBSTitute | Commands/BrowserRefreshDirectoryCommand.cs | 762 | C# |
/*
* Original author: Ali Marsh <alimarsh .at. uw.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
* Copyright 2020 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace SharedBatch.Properties
{
public sealed partial class Settings
{
[UserScopedSetting]
public ConfigList ConfigList
{
get
{
var list = (ConfigList) this["ConfigList"]; // Not L10N
if (list == null)
{
list = new ConfigList();
ConfigList = list;
}
return list;
}
set => this["ConfigList"] = value; // Not L10N
}
public void SetConfigList(List<IConfig> configs)
{
var settingsConfigList = new ConfigList();
foreach (var config in configs)
settingsConfigList.Add(config);
Default.ConfigList = settingsConfigList;
}
[UserScopedSetting]
public string InstallationId
{
get
{
var cid = (string)this["InstallationId"];
if (cid == null)
{
cid = Guid.NewGuid().ToString();
InstallationId = cid;
Save();
}
return cid;
}
private set => this["InstallationId"] = value;
}
// Upgrades the settings from the previous version and rewrites the XML to the current version
public void Update(string xmlFile, decimal currentXmlVersion, string appName)
{
try
{
if (!File.Exists(xmlFile))
return;
ProgramLog.Info(string.Format(Resources.Settings_Update_Saved_configurations_were_found_in___0_, xmlFile));
var configList = new ConfigList();
using (var stream = new FileStream(xmlFile, FileMode.Open))
{
using (var reader = XmlReader.Create(stream))
{
while (reader.Read())
{
if (!reader.IsStartElement("config_list") && !reader.IsStartElement("ConfigList")) continue;
configList.ReadXml(reader);
break;
}
}
}
Default.ConfigList = configList;
Default.Save();
}
catch (Exception e)
{
ProgramLog.Error(e.Message, e);
var folderToCopy = Path.GetDirectoryName(ProgramLog.GetProgramLogFilePath()) ?? string.Empty;
var newFileName = Path.Combine(folderToCopy, "error-user.config");
var message = string.Format(Resources.Settings_Update_There_was_an_error_reading_the_saved__0__configurations_,
appName) + Environment.NewLine + e.Message;
File.Copy(xmlFile, newFileName, true);
File.Delete(xmlFile);
message += Environment.NewLine + Environment.NewLine +
string.Format(
Resources
.Program_Main_To_help_improve__0__in_future_versions__please_post_the_configuration_file_to_the_Skyline_Support_board_,
appName) +
Environment.NewLine +
newFileName;
MessageBox.Show(message);
}
}
}
public class ConfigList : Collection<IConfig>, IXmlSerializable
{
#region IXmlSerializable Members
public static Importer Importer;
public static decimal XmlVersion = -1;
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
var isEmpty = reader.IsEmptyElement;
decimal importingXmlVersion;
try
{
importingXmlVersion = ReadXmlVersion(reader);
}
catch (ArgumentException e)
{
MessageBox.Show(e.Message);
return;
}
// Read past the property element
reader.Read();
// For an empty list in Settings.Default
if (isEmpty)
{
return;
}
// Read list items
var list = new List<IConfig>();
var message = new StringBuilder();
while (reader.IsStartElement())
{
if (Importer != null)
{
try
{
list.Add(Importer(reader, importingXmlVersion));
}
catch (ArgumentException e)
{
message.Append(e.Message + Environment.NewLine);
}
}
else
{
// this should never happen
throw new Exception("Must specify Importer before configurations are loaded.");
}
reader.Read();
}
Clear();
foreach (var config in list)
{
Add(config);
}
if (message.Length > 0)
MessageBox.Show(message.ToString(), Resources.ConfigList_ReadXml_Load_Configurations_Error, MessageBoxButtons.OK);
}
public static decimal ReadXmlVersion(XmlReader reader)
{
if (!reader.Name.Equals("ConfigList") && !reader.Name.Equals("config_list"))
throw new ArgumentException(Resources.ConfigList_ReadXmlVersion_The_XML_reader_is_not_at_the_correct_position_to_read_the_XML_version_);
var xmlVersion = reader.GetAttribute(Attr.xml_version) != null
? Convert.ToDecimal(reader.GetAttribute(Attr.xml_version))
: -1;
var importingVersion = reader.GetAttribute(Attr.version);
// if the xml version is not set, AutoQC and SkylineBatch are on the same version numbers
if (xmlVersion < 0)
xmlVersion = importingVersion != null ? 21.1M : 20.2M;
return xmlVersion;
}
enum Attr
{
xml_version,
// deprecated
version
}
public void WriteXml(XmlWriter writer)
{
// if (string.IsNullOrEmpty(Version))
// {
// // this should never happen
// throw new Exception("Must specify version before configurations are saved.");
// }
// The version should never be blank but if it is write a dummy version "0.0.0.0". An exception thrown here while
// running the program will not be caught, and any existing configurations will not be written to user.config.
// As a result, the user will not see any saved configurations next time they start the application.
writer.WriteAttribute(Attr.xml_version, XmlVersion);
foreach (var config in this)
{
config.WriteXml(writer);
}
}
#endregion // IXmlSerializable Members
}
}
| 35.439834 | 155 | 0.513172 | [
"Apache-2.0"
] | CSi-Studio/pwiz | pwiz_tools/Skyline/Executables/SharedBatch/SharedBatch/Properties/Settings.cs | 8,543 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Machinelearning.V1
{
/// <summary>
/// A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values.
/// </summary>
public class SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The label key that the selector applies to.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.
/// </summary>
[Input("operator", required: true)]
public Input<string> Operator { get; set; } = null!;
[Input("values")]
private InputList<string>? _values;
/// <summary>
/// An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.
/// </summary>
public InputList<string> Values
{
get => _values ?? (_values = new InputList<string>());
set => _values = value;
}
public SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsArgs()
{
}
}
}
| 42.680851 | 351 | 0.680957 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/seldon-operator/dotnet/Kubernetes/Crds/Operators/SeldonOperator/Machinelearning/V1/Inputs/SeldonDeploymentSpecPredictorsComponentSpecsSpecAffinityNodeAffinityRequiredDuringSchedulingIgnoredDuringExecutionNodeSelectorTermsMatchFieldsArgs.cs | 2,006 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
namespace System.ServiceModel.Channels
{
internal abstract class RequestContextBase : RequestContext
{
private TimeSpan _defaultSendTimeout;
private TimeSpan _defaultCloseTimeout;
private CommunicationState _state = CommunicationState.Opened;
private Message _requestMessage;
private Exception _requestMessageException;
private bool _replySent;
private bool _replyInitiated;
private bool _aborted;
private object _thisLock = new object();
protected RequestContextBase(Message requestMessage, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
{
_defaultSendTimeout = defaultSendTimeout;
_defaultCloseTimeout = defaultCloseTimeout;
_requestMessage = requestMessage;
}
public void ReInitialize(Message requestMessage)
{
_state = CommunicationState.Opened;
_requestMessageException = null;
_replySent = false;
_replyInitiated = false;
_aborted = false;
_requestMessage = requestMessage;
}
public override Message RequestMessage
{
get
{
if (_requestMessageException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_requestMessageException);
}
return _requestMessage;
}
}
protected void SetRequestMessage(Message requestMessage)
{
Fx.Assert(_requestMessageException == null, "Cannot have both a requestMessage and a requestException.");
_requestMessage = requestMessage;
}
protected void SetRequestMessage(Exception requestMessageException)
{
Fx.Assert(_requestMessage == null, "Cannot have both a requestMessage and a requestException.");
_requestMessageException = requestMessageException;
}
protected bool ReplyInitiated
{
get { return _replyInitiated; }
}
protected object ThisLock
{
get
{
return _thisLock;
}
}
public bool Aborted
{
get
{
return _aborted;
}
}
public TimeSpan DefaultCloseTimeout
{
get { return _defaultCloseTimeout; }
}
public TimeSpan DefaultSendTimeout
{
get { return _defaultSendTimeout; }
}
public override void Abort()
{
lock (ThisLock)
{
if (_state == CommunicationState.Closed)
return;
_state = CommunicationState.Closing;
_aborted = true;
}
try
{
this.OnAbort();
}
finally
{
_state = CommunicationState.Closed;
}
}
public override void Close()
{
this.Close(_defaultCloseTimeout);
}
public override void Close(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", timeout, SR.ValueMustBeNonNegative));
}
bool sendAck = false;
lock (ThisLock)
{
if (_state != CommunicationState.Opened)
return;
if (TryInitiateReply())
{
sendAck = true;
}
_state = CommunicationState.Closing;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
bool throwing = true;
try
{
if (sendAck)
{
OnReply(null, timeoutHelper.RemainingTime());
}
OnClose(timeoutHelper.RemainingTime());
_state = CommunicationState.Closed;
throwing = false;
}
finally
{
if (throwing)
this.Abort();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
if (_replySent)
{
this.Close();
}
else
{
this.Abort();
}
}
protected abstract void OnAbort();
protected abstract void OnClose(TimeSpan timeout);
protected abstract void OnReply(Message message, TimeSpan timeout);
protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnEndReply(IAsyncResult result);
protected void ThrowIfInvalidReply()
{
if (_state == CommunicationState.Closed || _state == CommunicationState.Closing)
{
if (_aborted)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.RequestContextAborted));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
if (_replyInitiated)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ReplyAlreadySent));
}
/// <summary>
/// Attempts to initiate the reply. If a reply is not initiated already (and the object is opened),
/// then it initiates the reply and returns true. Otherwise, it returns false.
/// </summary>
protected bool TryInitiateReply()
{
lock (_thisLock)
{
if ((_state != CommunicationState.Opened) || _replyInitiated)
{
return false;
}
else
{
_replyInitiated = true;
return true;
}
}
}
public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
{
return this.BeginReply(message, _defaultSendTimeout, callback, state);
}
public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
return OnBeginReply(message, timeout, callback, state);
}
public override void EndReply(IAsyncResult result)
{
OnEndReply(result);
_replySent = true;
}
public override void Reply(Message message)
{
this.Reply(message, _defaultSendTimeout);
}
public override void Reply(Message message, TimeSpan timeout)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
this.OnReply(message, timeout);
_replySent = true;
}
// This method is designed for WebSocket only, and will only be used once the WebSocket response was sent.
// For WebSocket, we never call HttpRequestContext.Reply to send the response back.
// Instead we call AcceptWebSocket directly. So we need to set the replyInitiated and
// replySent boolean to be true once the response was sent successfully. Otherwise when we
// are disposing the HttpRequestContext, we will see a bunch of warnings in trace log.
protected void SetReplySent()
{
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
_replySent = true;
}
}
internal class RequestContextMessageProperty : IDisposable
{
private RequestContext _context;
private object _thisLock = new object();
public RequestContextMessageProperty(RequestContext context)
{
_context = context;
}
public static string Name
{
get { return "requestContext"; }
}
void IDisposable.Dispose()
{
bool success = false;
RequestContext thisContext;
lock (_thisLock)
{
if (_context == null)
return;
thisContext = _context;
_context = null;
}
try
{
thisContext.Close();
success = true;
}
catch (CommunicationException)
{
}
catch (TimeoutException e)
{
if (TD.CloseTimeoutIsEnabled())
{
TD.CloseTimeout(e.Message);
}
}
finally
{
if (!success)
{
thisContext.Abort();
}
}
}
}
}
| 29.913433 | 154 | 0.536374 | [
"MIT"
] | 777Eternal777/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/Channels/RequestContextBase.cs | 10,021 | C# |
using Basement.BLFramework.Core.Context;
using Basement.BLFramework.Core.Util;
namespace Basement.BLFramework.Core.Model
{
public abstract class CollectionBase<TModel> : ModelBase where TModel : IModel
{
protected CollectionBase(string key, IContext context, IModel parent) : base(key, context, parent)
{
}
public virtual TModel this[string collectionKey] => (TModel)GetChildren()[collectionKey];
public override object Serialize()
{
var result = SerializeUtil.Dict();
foreach (var pair in this)
{
var serialized = pair.Value.Serialize();
if (serialized != null)
{
result.Add(pair.Key, serialized);
}
}
return result;
}
}
}
| 26.34375 | 106 | 0.569395 | [
"MIT"
] | planetouched/Unity3d_OEPFramework | Basement/BLFramework/Core/Model/CollectionBase.cs | 845 | C# |
// *****************************************************************************
//
// © 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, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 5.460.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using ComponentFactory.Krypton.Toolkit;
namespace KryptonCheckButtonExamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Setup the property grid to edit this button
propertyGrid.SelectedObject = new KryptonCheckButtonProxy(button1Sparkle);
}
private void checkButton_Enter(object sender, EventArgs e)
{
// Setup the property grid to edit this button
propertyGrid.SelectedObject = new KryptonCheckButtonProxy(sender as KryptonCheckButton);
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
}
public class KryptonCheckButtonProxy
{
private KryptonCheckButton _checkButton;
public KryptonCheckButtonProxy(KryptonCheckButton checkButton)
{
_checkButton = checkButton;
}
[Category("Visuals")]
[Description("Button style.")]
[DefaultValue(typeof(ButtonStyle), "Standalone")]
public ButtonStyle ButtonStyle
{
get { return _checkButton.ButtonStyle; }
set { _checkButton.ButtonStyle = value; }
}
[Category("Visuals")]
[Description("Button values")]
public ButtonValues Values
{
get { return _checkButton.Values; }
}
[Category("Visuals")]
[Description("Overrides for defining common button appearance that other states can override.")]
public PaletteTripleRedirect StateCommon
{
get { return _checkButton.StateCommon; }
}
[Category("Visuals")]
[Description("Overrides for defining disabled button appearance.")]
public PaletteTriple StateDisabled
{
get { return _checkButton.StateDisabled; }
}
[Category("Visuals")]
[Description("Overrides for defining normal button appearance.")]
public PaletteTriple StateNormal
{
get { return _checkButton.StateNormal; }
}
[Category("Visuals")]
[Description("Overrides for defining hot tracking button appearance.")]
public PaletteTriple StateTracking
{
get { return _checkButton.StateTracking; }
}
[Category("Visuals")]
[Description("Overrides for defining pressed button appearance.")]
public PaletteTriple StatePressed
{
get { return _checkButton.StatePressed; }
}
[Category("Visuals")]
[Description("Overrides for defining normal checked button appearance.")]
public PaletteTriple StateCheckedNormal
{
get { return _checkButton.StateCheckedNormal; }
}
[Category("Visuals")]
[Description("Overrides for defining hot tracking checked button appearance.")]
public PaletteTriple StateCheckedTracking
{
get { return _checkButton.StateCheckedTracking; }
}
[Category("Visuals")]
[Description("Overrides for defining pressed checked button appearance.")]
public PaletteTriple StateCheckedPressed
{
get { return _checkButton.StateCheckedPressed; }
}
[Category("Visuals")]
[Description("Overrides for defining normal button appearance when default.")]
public PaletteTripleRedirect OverrideDefault
{
get { return _checkButton.OverrideDefault; }
}
[Category("Visuals")]
[Description("Overrides for defining button appearance when it has focus.")]
public PaletteTripleRedirect OverrideFocus
{
get { return _checkButton.OverrideFocus; }
}
[Category("Visuals")]
[Description("Visual orientation of the control.")]
[DefaultValue(typeof(VisualOrientation), "Top")]
public VisualOrientation Orientation
{
get { return _checkButton.Orientation; }
set { _checkButton.Orientation = value; }
}
[Category("Visuals")]
[Description("Palette applied to drawing.")]
[DefaultValue(typeof(PaletteMode), "Global")]
public PaletteMode PaletteMode
{
get { return _checkButton.PaletteMode; }
set { _checkButton.PaletteMode = value; }
}
[Category("Layout")]
[Description("Specifies whether a control will automatically size itself to fit its contents.")]
[DefaultValue(false)]
public bool AutoSize
{
get { return _checkButton.AutoSize; }
set { _checkButton.AutoSize = value; }
}
[Category("Layout")]
[Description("Specifies if the control grows and shrinks to fit the contents exactly.")]
[DefaultValue(typeof(AutoSizeMode), "GrowOnly")]
public AutoSizeMode AutoSizeMode
{
get { return _checkButton.AutoSizeMode; }
set { _checkButton.AutoSizeMode = value; }
}
[Category("Layout")]
[Description("The size of the control is pixels.")]
public Size Size
{
get { return _checkButton.Size; }
set { _checkButton.Size = value; }
}
[Category("Layout")]
[Description("The location of the control in pixels.")]
public Point Location
{
get { return _checkButton.Location; }
set { _checkButton.Location = value; }
}
[Category("Appearance")]
[Description("Indicates whether the control is in the checked state.")]
public bool Checked
{
get { return _checkButton.Checked; }
set { _checkButton.Checked = value; }
}
[Category("Behavior")]
[Description("Indicates whether the control is enabled.")]
public bool Enabled
{
get { return _checkButton.Enabled; }
set { _checkButton.Enabled = value; }
}
}
}
| 32.475962 | 104 | 0.592598 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.460 | Source/Demos/Non-NuGet/Krypton Toolkit Examples/KryptonCheckButton Examples/Form1.cs | 6,758 | C# |
using System;
using System.Diagnostics;
using System.IO;
using Lucene.Net.Analysis.Tokenattributes;
using org.apache.lucene.analysis.util;
using Reader = System.IO.TextReader;
using Version = Lucene.Net.Util.LuceneVersion;
namespace Lucene.Net.Analysis.Util
{
/*
* 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.
*/
/// <summary>
/// Breaks text into sentences with a <seealso cref="BreakIterator"/> and
/// allows subclasses to decompose these sentences into words.
/// <para>
/// This can be used by subclasses that need sentence context
/// for tokenization purposes, such as CJK segmenters.
/// </para>
/// <para>
/// Additionally it can be used by subclasses that want to mark
/// sentence boundaries (with a custom attribute, extra token, position
/// increment, etc) for downstream processing.
///
/// @lucene.experimental
/// </para>
/// </summary>
public abstract class SegmentingTokenizerBase : Tokenizer
{
protected internal const int BUFFERMAX = 1024;
protected internal readonly char[] buffer = new char[BUFFERMAX];
/// <summary>
/// true length of text in the buffer </summary>
private int length = 0;
/// <summary>
/// length in buffer that can be evaluated safely, up to a safe end point </summary>
private int usableLength = 0;
/// <summary>
/// accumulated offset of previous buffers for this reader, for offsetAtt </summary>
protected internal int offset = 0;
private readonly BreakIterator iterator;
private readonly CharArrayIterator wrapper = CharArrayIterator.newSentenceInstance();
private readonly OffsetAttribute offsetAtt = addAttribute(typeof(OffsetAttribute));
/// <summary>
/// Construct a new SegmenterBase, using
/// the provided BreakIterator for sentence segmentation.
/// <para>
/// Note that you should never share BreakIterators across different
/// TokenStreams, instead a newly created or cloned one should always
/// be provided to this constructor.
/// </para>
/// </summary>
public SegmentingTokenizerBase(Reader reader, BreakIterator iterator) : this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, reader, iterator)
{
}
/// <summary>
/// Construct a new SegmenterBase, also supplying the AttributeFactory
/// </summary>
public SegmentingTokenizerBase(AttributeFactory factory, Reader reader, BreakIterator iterator) : base(factory, reader)
{
this.iterator = iterator;
}
public override bool IncrementToken()
{
if (length == 0 || !IncrementWord())
{
while (!IncrementSentence())
{
Refill();
if (length <= 0) // no more bytes to read;
{
return false;
}
}
}
return true;
}
public override void Reset()
{
base.Reset();
wrapper.setText(buffer, 0, 0);
iterator.Text = wrapper;
length = usableLength = offset = 0;
}
public override void End()
{
base.End();
int finalOffset = CorrectOffset(length < 0 ? offset : offset + length);
offsetAtt.SetOffset(finalOffset, finalOffset);
}
/// <summary>
/// Returns the last unambiguous break position in the text. </summary>
private int FindSafeEnd()
{
for (int i = length - 1; i >= 0; i--)
{
if (IsSafeEnd(buffer[i]))
{
return i + 1;
}
}
return -1;
}
/// <summary>
/// For sentence tokenization, these are the unambiguous break positions. </summary>
protected internal virtual bool IsSafeEnd(char ch)
{
switch ((int)ch)
{
case 0x000D:
case 0x000A:
case 0x0085:
case 0x2028:
case 0x2029:
return true;
default:
return false;
}
}
/// <summary>
/// Refill the buffer, accumulating the offset and setting usableLength to the
/// last unambiguous break position
/// </summary>
private void Refill()
{
offset += usableLength;
int leftover = length - usableLength;
Array.Copy(buffer, usableLength, buffer, 0, leftover);
int requested = buffer.Length - leftover;
int returned = Read(input, buffer, leftover, requested);
length = returned < 0 ? leftover : returned + leftover;
if (returned < requested) // reader has been emptied, process the rest
{
usableLength = length;
}
else // still more data to be read, find a safe-stopping place
{
usableLength = FindSafeEnd();
if (usableLength < 0)
{
usableLength = length; /*
}
* more than IOBUFFER of text without breaks,
* gonna possibly truncate tokens
*/
}
wrapper.SetText(buffer, 0, Math.Max(0, usableLength));
iterator.Text = wrapper;
}
}
// TODO: refactor to a shared readFully somewhere
// (NGramTokenizer does this too):
/// <summary>
/// commons-io's readFully, but without bugs if offset != 0 </summary>
private static int Read(TextReader input, char[] buffer, int offset, int length)
{
Debug.Assert(length >= 0, "length must not be negative: " + length);
int remaining = length;
while (remaining > 0)
{
int location = length - remaining;
int count = input.read(buffer, offset + location, remaining);
if (-1 == count) // EOF
{
break;
}
remaining -= count;
}
return length - remaining;
}
/// <summary>
/// return true if there is a token from the buffer, or null if it is
/// exhausted.
/// </summary>
private bool IncrementSentence()
{
if (length == 0) // we must refill the buffer
{
return false;
}
while (true)
{
int start = iterator.Current();
if (start == BreakIterator.DONE)
{
return false; // BreakIterator exhausted
}
// find the next set of boundaries
int end_Renamed = iterator.next();
if (end_Renamed == BreakIterator.DONE)
{
return false; // BreakIterator exhausted
}
setNextSentence(start, end_Renamed);
if (incrementWord())
{
return true;
}
}
}
/// <summary>
/// Provides the next input sentence for analysis </summary>
protected internal abstract void SetNextSentence(int sentenceStart, int sentenceEnd);
/// <summary>
/// Returns true if another word is available </summary>
protected internal abstract bool IncrementWord();
}
} | 29.016194 | 141 | 0.647272 | [
"Apache-2.0"
] | CerebralMischief/lucenenet | src/Lucene.Net.Analysis.Common/Analysis/Util/SegmentingTokenizerBase.cs | 7,169 | C# |
using System;
using System.IO;
using Krompaco.RecordCollector.Content.FrontMatterParsers;
using Krompaco.RecordCollector.Content.Models;
using Xunit;
namespace Krompaco.RecordCollector.Content.Tests
{
public class TomlTests
{
[Fact]
public void ParserTest()
{
string input = @"
+++
title = ""About""
categories = [""Development"", ""VIM""]
date = ""2012-04-06""
description = ""spf13-vim is a cross platform distribution of vim plugins and resources for Vim.""
slug = ""spf13-vim-3-0-release-and-new-website""
weight = 1
testint = 1
images = [""site-feature-image.jpg""]
testbool = false
teststring = ""What?""
testdate = ""2012-04-06""
testarray = [""Development"", ""VIM""]
tags = ["".vimrc"", ""plugins"", ""spf13-vim"", ""vim""]
[[resources]]
name = ""header""
src = ""images/sunset.jpg""
[[resources]]
src = ""documents/photo_specs.pdf""
title = ""Photo Specifications""
[resources.params]
icon = ""photo""
[[resources]]
src = ""documents/guide.pdf""
title = ""Instruction Guide""
[[resources]]
src = ""documents/checklist.pdf""
title = ""Document Checklist""
[[resources]]
src = ""documents/payment.docx""
title = ""Proof of Payment""
[[resources]]
name = ""pdf-file-:counter""
src = ""**.pdf""
[resources.params]
icon = ""pdf""
[[resources]]
src = ""**.docx""
[resources.params]
icon = ""word""
[cascade]
banner = ""images/typewriter.jpg""
tags = ["".vimrc"", ""plugins"", ""spf13-vim"", ""vim""]
+++
Lorem ipsum";
using TextReader sr = new StringReader(input);
var parser = new TomlParser<SinglePage>(sr, string.Empty);
var single = parser.GetAsSinglePage();
Assert.Equal("About", single.Title);
Assert.Equal("Development", single.Categories[0]);
Assert.Equal("VIM", single.Categories[1]);
Assert.Equal(new DateTime(2012, 4, 6).Date, single.Date.Date);
Assert.Equal("spf13-vim is a cross platform distribution of vim plugins and resources for Vim.", single.Description);
Assert.Equal("spf13-vim-3-0-release-and-new-website", single.Slug);
Assert.Equal("1", single.CustomStringProperties["testint"]);
Assert.Equal("False", single.CustomStringProperties["testbool"], StringComparer.OrdinalIgnoreCase);
Assert.Equal("What?", single.CustomStringProperties["teststring"]);
Assert.Equal("2012-04-06", single.CustomStringProperties["testdate"]);
Assert.Equal("Development", single.CustomArrayProperties["testarray"][0]);
Assert.Equal("VIM", single.CustomArrayProperties["testarray"][1]);
Assert.Equal(".vimrc", single.Tags[0]);
Assert.Equal("plugins", single.Tags[1]);
Assert.Equal("spf13-vim", single.Tags[2]);
Assert.Equal("vim", single.Tags[3]);
Assert.Equal("images/typewriter.jpg", single.Cascade.CustomStringProperties["banner"]);
Assert.Equal(".vimrc", single.Cascade.CustomArrayProperties["tags"][0]);
Assert.Equal("Lorem ipsum", single.Content);
}
}
}
| 33.126316 | 129 | 0.627582 | [
"MIT"
] | IsseMohamed/record-collector | tests/Krompaco.RecordCollector.Content.Tests/TomlTests.cs | 3,149 | C# |
using System.Linq;
using System.Collections.Generic;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using AzureBlobStorageSampleApp;
using AzureBlobStorageSampleApp.iOS;
//[assembly: ExportRenderer(typeof(ContentPage), typeof(ContentPageCustomRenderer))]
[assembly: ExportRenderer(typeof(SpecialContentPage), typeof(ContentPageCustomRenderer))]
namespace AzureBlobStorageSampleApp.iOS
{
public class ContentPageCustomRenderer : PageRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
var thisElement = Element as ContentPage;
var leftNavList = new List<UIBarButtonItem>();
var rightNavList = new List<UIBarButtonItem>();
var navigationItem = NavigationController.TopViewController.NavigationItem;
if (navigationItem?.LeftBarButtonItems?.Any() == true)
return;
for (var i = 0; i < thisElement.ToolbarItems.Count; i++)
{
var reorder = (thisElement.ToolbarItems.Count - 1);
var itemPriority = thisElement.ToolbarItems[reorder - i].Priority;
if (itemPriority == 1)
{
UIBarButtonItem LeftNavItems = navigationItem.RightBarButtonItems[i];
leftNavList.Add(LeftNavItems);
}
else if (itemPriority == 0)
{
UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
rightNavList.Add(RightNavItems);
}
}
navigationItem.SetLeftBarButtonItems(leftNavList.ToArray(), false);
navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
}
}
} | 32.464286 | 90 | 0.630363 | [
"MIT"
] | andrewchungxam/2019AzureBlobLocalOnly | AzureBlobStorageSampleApp.iOS/Custom Renderers/ContentPageCustomRenderer.cs | 1,820 | 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.NetApp.V20200701
{
/// <summary>
/// NetApp account resource
/// </summary>
[AzureNativeResourceType("azure-native:netapp/v20200701:Account")]
public partial class Account : Pulumi.CustomResource
{
/// <summary>
/// Active Directories
/// </summary>
[Output("activeDirectories")]
public Output<ImmutableArray<Outputs.ActiveDirectoryResponse>> ActiveDirectories { get; private set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Resource name
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Azure lifecycle management
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource tags
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Account resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Account(string name, AccountArgs args, CustomResourceOptions? options = null)
: base("azure-native:netapp/v20200701:Account", name, args ?? new AccountArgs(), MakeResourceOptions(options, ""))
{
}
private Account(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:netapp/v20200701:Account", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200701:Account"},
new Pulumi.Alias { Type = "azure-native:netapp:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/latest:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/latest:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20170815:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20170815:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20190501:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190501:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20190601:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190601:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20190701:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190701:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20190801:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190801:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20191001:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191001:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20191101:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191101:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200201:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200201:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200301:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200301:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200501:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200501:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200601:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200601:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200801:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200801:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20200901:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200901:Account"},
new Pulumi.Alias { Type = "azure-native:netapp/v20201101:Account"},
new Pulumi.Alias { Type = "azure-nextgen:netapp/v20201101:Account"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Account resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Account Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Account(name, id, options);
}
}
public sealed class AccountArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the NetApp account
/// </summary>
[Input("accountName")]
public Input<string>? AccountName { get; set; }
[Input("activeDirectories")]
private InputList<Inputs.ActiveDirectoryArgs>? _activeDirectories;
/// <summary>
/// Active Directories
/// </summary>
public InputList<Inputs.ActiveDirectoryArgs> ActiveDirectories
{
get => _activeDirectories ?? (_activeDirectories = new InputList<Inputs.ActiveDirectoryArgs>());
set => _activeDirectories = value;
}
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public AccountArgs()
{
}
}
}
| 44.351648 | 126 | 0.579286 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/NetApp/V20200701/Account.cs | 8,072 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501
{
using static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Extensions;
/// <summary>Customer subscription which can use a sku.</summary>
public partial class PreviewSubscription
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.IPreviewSubscription.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.IPreviewSubscription.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.IPreviewSubscription FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject json ? new PreviewSubscription(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject into a new instance of <see cref="PreviewSubscription" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject instance to deserialize from.</param>
internal PreviewSubscription(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20210501.PreviewSubscriptionProperties.FromJson(__jsonProperties) : Property;}
{_systemData = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject>("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Models.Api20.SystemData.FromJson(__jsonSystemData) : SystemData;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_id = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString>("id"), out var __jsonId) ? (string)__jsonId : (string)Id;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="PreviewSubscription" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="PreviewSubscription" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.ConnectedNetwork.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 77.920635 | 306 | 0.702893 | [
"MIT"
] | Agazoth/azure-powershell | src/ConnectedNetwork/generated/api/Models/Api20210501/PreviewSubscription.json.cs | 9,693 | C# |
using System.Collections.Generic;
using Scripts.Utilities;
using UnityEngine;
namespace Examples.UILineRenderer
{
[RequireComponent(typeof(Scripts.Primitives.UILineRenderer))]
public class LineRendererOrbit : MonoBehaviour
{
private Scripts.Primitives.UILineRenderer lr;
private Circle circle;
public GameObject OrbitGO;
private RectTransform orbitGOrt;
private float orbitTime;
[SerializeField]
private float _xAxis = 3;
public float xAxis
{
get { return _xAxis; }
set { _xAxis = value; GenerateOrbit(); }
}
[SerializeField]
private float _yAxis = 3;
public float yAxis
{
get { return _yAxis; }
set { _yAxis = value; GenerateOrbit(); }
}
[SerializeField]
private int _steps = 10;
public int Steps
{
get { return _steps; }
set { _steps = value; GenerateOrbit(); }
}
// Use this for initialization
private void Awake()
{
lr = GetComponent<Scripts.Primitives.UILineRenderer>();
orbitGOrt = OrbitGO.GetComponent<RectTransform>();
GenerateOrbit();
}
// Update is called once per frame
private void Update()
{
orbitTime = orbitTime > _steps ? orbitTime = 0 : orbitTime + Time.deltaTime;
orbitGOrt.localPosition = circle.Evaluate(orbitTime);
}
private void GenerateOrbit()
{
circle = new Circle(xAxis: _xAxis, yAxis: _yAxis, steps: _steps);
var Points = new List<Vector2>();
for (var i = 0; i < _steps; i++)
{
Points.Add(circle.Evaluate(i));
}
Points.Add(circle.Evaluate(0));
lr.Points = Points.ToArray();
}
private void OnValidate()
{
if (lr != null)
{
GenerateOrbit();
}
}
}
} | 25.725 | 88 | 0.533528 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | obkaul/VRTactileDraw | Assets/unity-ui-extensions/Examples/UILineRenderer/LineRendererOrbit.cs | 2,060 | C# |
using CMS.Base;
using Generic.Repositories.Interfaces;
using Generic.Services.Interfaces;
using System.ComponentModel.DataAnnotations;
namespace Generic.Attributes
{
/// <summary>
/// Checks if the password matches the current user's password. Used in Password reset.
/// </summary>
public class CurrentUserPasswordValidAttribute : ValidationAttribute
{
public CurrentUserPasswordValidAttribute()
{
}
public IUserService UserService { get; internal set; }
public IUserRepository UserRepository { get; internal set; }
public IAuthenticationService AuthenticationService { get; internal set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
UserService = (IUserService)validationContext.GetService(typeof(IUserService));
UserRepository = (IUserRepository)validationContext.GetService(typeof(IUserRepository));
AuthenticationService = (IAuthenticationService)validationContext.GetService(typeof(IAuthenticationService));
if (value is string)
{
string Password = value.ToString();
if (AuthenticationService.CurrentUser.IsPublic())
{
return new ValidationResult("Cannot change password of Public User");
}
if(UserService.ValidateUserPassword(AuthenticationService.CurrentUser, Password))
{
return ValidationResult.Success;
} else
{
return new ValidationResult("Invalid Password");
}
}
else
{
return new ValidationResult("Password must be a string");
}
}
}
}
| 37.408163 | 121 | 0.625205 | [
"MIT"
] | HBSTech/Kentico13CoreBaseline | MVC/MVC/Resources/Attributes/CurrentUserPasswordValidAttribute.cs | 1,835 | C# |
namespace Masny.Microservices.Identity.Api.Contracts.Requests
{
/// <summary>
/// Register request.
/// </summary>
public class RegisterRequest
{
/// <summary>
/// Email.
/// </summary>
public string Email { get; set; }
/// <summary>
/// User name.
/// </summary>
public string UserName { get; set; }
/// <summary>
/// Full name.
/// </summary>
public string FullName { get; set; }
/// <summary>
/// Password.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Password confirm.
/// </summary>
public string PasswordConfirm { get; set; }
}
}
| 22.294118 | 62 | 0.472296 | [
"MIT"
] | MikhailMasny/awesome-microservices | src/Masny.Microservices.Identity.Api/Contracts/Requests/RegisterRequest.cs | 760 | C# |
namespace Sedati
{
partial class frmAbout
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAbout));
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.linkLabel2 = new System.Windows.Forms.LinkLabel();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Sedati";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(209, 11);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(63, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Version: 1.0";
//
// label3
//
this.label3.Location = new System.Drawing.Point(12, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(260, 94);
this.label3.TabIndex = 2;
this.label3.Text = resources.GetString("label3.Text");
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(106, 9);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(67, 65);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 3;
this.pictureBox1.TabStop = false;
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(159, 114);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(38, 13);
this.linkLabel1.TabIndex = 4;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Github";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// linkLabel2
//
this.linkLabel2.AutoSize = true;
this.linkLabel2.Location = new System.Drawing.Point(159, 154);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new System.Drawing.Size(36, 13);
this.linkLabel2.TabIndex = 5;
this.linkLabel2.TabStop = true;
this.linkLabel2.Text = "Profile";
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
//
// frmAbout
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 190);
this.Controls.Add(this.linkLabel2);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmAbout";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "About";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.LinkLabel linkLabel2;
}
} | 44.015038 | 165 | 0.58507 | [
"MIT"
] | ellivr/Sedati | Sedati/frmAbout.Designer.cs | 5,856 | C# |
using System.Timers;
namespace Hotel.Client.Extensions
{
public static class TimerExtensions
{
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
}
}
| 16.928571 | 50 | 0.561181 | [
"MIT"
] | PGBSNH19/project-grupp-1-hotel | Hotel.Client/Extensions/TimerExtensions.cs | 239 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520
{
using Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.PowerShell;
/// <summary>An azure resource object</summary>
[System.ComponentModel.TypeConverter(typeof(PrivateLinkScopesResourceTypeConverter))]
public partial class PrivateLinkScopesResource
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResource"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResource"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResource DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new PrivateLinkScopesResource(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResource"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResource"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new PrivateLinkScopesResource(content);
}
/// <summary>
/// Creates a new instance of <see cref="PrivateLinkScopesResource" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResource"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal PrivateLinkScopesResource(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Location"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Location, global::System.Convert.ToString);
}
if (content.Contains("Tag"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResourceTagsTypeConverter.ConvertFrom);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResource"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal PrivateLinkScopesResource(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Location"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Location, global::System.Convert.ToString);
}
if (content.Contains("Tag"))
{
((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.IPrivateLinkScopesResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Models.Api20210520.PrivateLinkScopesResourceTagsTypeConverter.ConvertFrom);
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ConnectedMachine.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// An azure resource object
[System.ComponentModel.TypeConverter(typeof(PrivateLinkScopesResourceTypeConverter))]
public partial interface IPrivateLinkScopesResource
{
}
} | 70.596591 | 521 | 0.704225 | [
"MIT"
] | Agazoth/azure-powershell | src/ConnectedMachine/generated/api/Models/Api20210520/PrivateLinkScopesResource.PowerShell.cs | 12,250 | C# |
using System.Windows;
using System.Windows.Media;
namespace Quan.ControlLibrary
{
public static class FloatingTextHelper
{
private const double DefaultFloatingScale = 0.75;
private static readonly Point DefaultFloatingOffset = new Point(0, -15);
private const double DefaultHintOpacity = 0.46;
#region IsUseFloating
public static readonly DependencyProperty IsUseFloatingProperty =
DependencyProperty.RegisterAttached(
"IsUseFloating",
typeof(bool),
typeof(FloatingTextHelper),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.Inherits));
public static bool GetIsUseFloating(DependencyObject element) => (bool)element.GetValue(IsUseFloatingProperty);
public static void SetIsUseFloating(DependencyObject element, bool value) => element.SetValue(IsUseFloatingProperty, BooleanBoxes.Box(value));
#endregion
#region FloatingScale
public static readonly DependencyProperty FloatingScaleProperty =
DependencyProperty.RegisterAttached(
"FloatingScale",
typeof(double),
typeof(FloatingTextHelper),
new FrameworkPropertyMetadata(DefaultFloatingScale, FrameworkPropertyMetadataOptions.Inherits));
public static double GetFloatingScale(DependencyObject element) => (double)element.GetValue(FloatingScaleProperty);
public static void SetFloatingScale(DependencyObject element, double value) => element.SetValue(FloatingScaleProperty, value);
#endregion
#region FloatingOffset
public static readonly DependencyProperty FloatingOffsetProperty =
DependencyProperty.RegisterAttached(
"FloatingOffset",
typeof(Point),
typeof(FloatingTextHelper),
new FrameworkPropertyMetadata(DefaultFloatingOffset, FrameworkPropertyMetadataOptions.Inherits));
public static Point GetFloatingOffset(DependencyObject element) => (Point)element.GetValue(FloatingOffsetProperty);
public static void SetFloatingOffset(DependencyObject element, Point value) => element.SetValue(FloatingOffsetProperty, value);
#endregion
#region FloatingOpacity
public static readonly DependencyProperty FloatingOpacityProperty =
DependencyProperty.RegisterAttached(
"FloatingOpacity",
typeof(double),
typeof(FloatingTextHelper),
new FrameworkPropertyMetadata(DefaultHintOpacity, FrameworkPropertyMetadataOptions.Inherits));
public static double GetFloatingOpacity(DependencyObject element) => (double)element.GetValue(FloatingOpacityProperty);
public static void SetFloatingOpacity(DependencyObject element, double value) => element.SetValue(FloatingOpacityProperty, value);
#endregion
#region Foreground
public static readonly DependencyProperty ForegroundProperty =
DependencyProperty.RegisterAttached(
"Foreground",
typeof(Brush),
typeof(FloatingTextHelper),
new FrameworkPropertyMetadata(default(Brush)));
public static Brush GetForeground(DependencyObject element) => (Brush)element.GetValue(ForegroundProperty);
public static void SetForeground(DependencyObject element, Brush value) => element.SetValue(ForegroundProperty, value);
#endregion
}
}
| 38.945652 | 150 | 0.700809 | [
"MIT"
] | quanljh/Quan.ControlLibrary | src/Quan.ControlLibrary/AttachedProperties/FloatingTextHelper.cs | 3,585 | C# |
using System.Reflection;
using Abp.AspNetCore.TestBase;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.AspNetCore.Configuration;
using Abp.AspNetCore.Mocks;
using Abp.Auditing;
using Abp.Localization;
namespace Abp.AspNetCore.App
{
[DependsOn(typeof(AbpAspNetCoreTestBaseModule))]
public class AppModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Auditing.IsEnabledForAnonymousUsers = true;
Configuration.ReplaceService<IAuditingStore, MockAuditingStore>();
Configuration
.Modules.AbpAspNetCore()
.CreateControllersForAppServices(
Assembly.GetExecutingAssembly()
);
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
public override void PostInitialize()
{
var localizationConfiguration = IocManager.IocContainer.Resolve<ILocalizationConfiguration>();
localizationConfiguration.Languages.Add(new LanguageInfo("en-US", "English", isDefault: true));
localizationConfiguration.Languages.Add(new LanguageInfo("it", "Italian"));
}
}
}
| 31.170732 | 107 | 0.668232 | [
"MIT"
] | mehmetozkaya/aspnetboilerplate | test/Abp.AspNetCore.Tests/App/AppModule.cs | 1,280 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.