content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections.Generic;
namespace PATFileUpload
{
public interface IHorizonConfigurationsViewModel
{
List<HorizonConfigurationModel> HorizonConfirgurations{ get; set; }
}
}
| 17.818182 | 71 | 0.785714 | [
"MIT"
] | amittkSharma/PAT | PATFileUpload/Contracts/IHorizonConfigurationsViewModel.cs | 198 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
namespace Wadsworth.DynamoDB.TestUtilities
{
internal class DynamoDBLocalHelper : IDisposable
{
private const string ContainerName = "dynamodb-local-";
private const string ImageName = "amazon/dynamodb-local";
private const string ImageTag = "latest";
private readonly DockerClient dockerClient = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock")).CreateClient();
private string containerId;
public async Task<int> StartDatabaseAsync()
{
await dockerClient.Images.CreateImageAsync(new ImagesCreateParameters() { FromImage = ImageName, Tag = ImageTag }, new AuthConfig(), new Progress<JSONMessage>());
// Create the container
var config = new Config()
{
Hostname = "localhost"
};
// get an open port
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
// Configure the ports to expose
var hostConfig = new HostConfig()
{
PortBindings = new Dictionary<string, IList<PortBinding>>
{
{ $"8000/tcp", new List<PortBinding> { new PortBinding { HostIP = IPAddress.Loopback.ToString(), HostPort = port.ToString() } } },
}
};
// Create the container
var response = await dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters(config)
{
Image = ImageName + ":" + ImageTag,
Name = ContainerName + Guid.NewGuid().ToString(), // the GUID makes sure we don't have clashes if there is more than one
Tty = false,
HostConfig = hostConfig,
});
containerId = response.ID;
await dockerClient.Containers.StartContainerAsync(containerId, new ContainerStartParameters());
return port;
}
public async Task StopDatabaseAsync()
{
await dockerClient.Containers.StopContainerAsync(containerId, new ContainerStopParameters());
await dockerClient.Containers.RemoveContainerAsync(containerId, new ContainerRemoveParameters());
}
private void Log(object sender, DataReceivedEventArgs args)
{
System.Diagnostics.Debug.WriteLine(args.Data);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
dockerClient?.Dispose();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
}
| 33.54 | 174 | 0.591532 | [
"MIT"
] | jasonwadsworth/DotNet.DynamoDB.TestUtilities | src/DynamoDB.TestUtilities/DynamoDBLocalHelper.cs | 3,356 | C# |
using System.Xml;
using XMPP_API.Classes.Network.XML.Messages.XEP_0059;
namespace XMPP_API.Classes.Network.XML.Messages.XEP_0313
{
public class QueryArchiveFinishMessage: IQMessage
{
//--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
#region --Attributes--
public readonly Set RESULT_SET;
public readonly bool COMPLETE;
#endregion
//--------------------------------------------------------Constructor:----------------------------------------------------------------\\
#region --Constructors--
public QueryArchiveFinishMessage(XmlNode answer) : base(answer)
{
XmlNode finNode = XMLUtils.getChildNode(answer, "fin", Consts.XML_XMLNS, Consts.XML_XEP_0313_NAMESPACE);
if (!(finNode is null))
{
COMPLETE = XMLUtils.tryParseToBool(finNode.Attributes["complete"]?.Value);
XmlNode setNode = XMLUtils.getChildNode(finNode, "set", Consts.XML_XMLNS, Consts.XML_XEP_0059_NAMESPACE);
if (!(setNode is null))
{
RESULT_SET = new Set(setNode);
}
}
}
#endregion
//--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
#region --Set-, Get- Methods--
#endregion
//--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
#region --Misc Methods (Public)--
#endregion
#region --Misc Methods (Private)--
#endregion
#region --Misc Methods (Protected)--
#endregion
//--------------------------------------------------------Events:---------------------------------------------------------------------\\
#region --Events--
#endregion
}
}
| 34.913793 | 144 | 0.395062 | [
"MPL-2.0"
] | LibreHacker/UWPX-Client | XMPP_API/Classes/Network/XML/Messages/XEP-0313/QueryArchiveFinishMessage.cs | 2,027 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\d2d1_1.h(432,9)
using System.Runtime.InteropServices;
namespace DirectN
{
/// <summary>
/// This controls advanced settings of the Direct2D imaging pipeline.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public partial struct D2D1_RENDERING_CONTROLS
{
/// <summary>
/// The default buffer precision, used if the precision isn't otherwise specified.
/// </summary>
public D2D1_BUFFER_PRECISION bufferPrecision;
/// <summary>
/// The size of allocated tiles used to render imaging effects.
/// </summary>
public D2D_SIZE_U tileSize;
}
}
| 32.863636 | 91 | 0.634855 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/D2D1_RENDERING_CONTROLS.cs | 725 | C# |
using System;
using System.Collections.Generic;
namespace RestEaseClientGeneratorConsoleApp.Examples.PetStoreOpenApi302.Models
{
public enum Status
{
placed,
approved,
delivered
}
}
| 17.615385 | 79 | 0.668122 | [
"MIT"
] | StefH/RestEase-Client-Generator | examples/RestEaseClientGeneratorConsoleApp/Examples/PetStoreOpenApi302/Models/Status.cs | 229 | C# |
namespace Application.Common.Configuration
{
public class IdentityConfiguration
{
public bool PasswordRequireDigit { get; set; }
public int PasswordRequiredLength { get; set; }
public bool PasswordRequireNonAlphanumeric { get; set; }
public bool PasswordRequireUppercase { get; set; }
public bool PasswordRequireLowercase { get; set; }
public bool RequireUniqueEmail { get; set; }
}
} | 38 | 65 | 0.666667 | [
"MIT"
] | Reza-Neyestani/CleanArchitectureTemplate | src/Application/Common/Configuration/IdentityConfiguration.cs | 458 | C# |
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(ReadOnlyAttribute), true)]
public class ReadOnlyDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return base.GetPropertyHeight(property, label);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.enabled = (!Application.isPlaying) && ((ReadOnlyAttribute)attribute).isRunTimeOnly;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}
| 31.526316 | 95 | 0.736227 | [
"MIT"
] | LeeKangW/UNITY | API/Attributes/ReadOnly/Editor/ReadOnlyDrawer.cs | 599 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MagiQL.Framework.Model.Response;
using NUnit.Framework;
using Scenarios.Scenario2.Tests.Integration.Helpers;
namespace Scenarios.Scenario2.Tests.Integration
{
[TestFixture]
public class AggregationTests : TestBase
{
[TestCase("Location_ID", "1", "LocationHit_ResponseSizeBytes_Sum", 20000 + 20000 + 20032)]
[TestCase("Location_ID", "2", "LocationHit_ResponseSizeBytes_Sum", 19300 + 19300 + 19300)]
[TestCase("Location_ID", "5", "Calculated_HtmlBytes", 0)]
public void Grouped_SingleItemFilter_AggregatesValues(string filterColumnUniqueName, string filterValue, string testColumnUniqueName, object expected)
{
// arrange
var groupedRequest = SetupRequest(_client, "Location_ID");
groupedRequest.AddFilter(_allColumns,filterColumnUniqueName, filterValue);
// act
var groupedResult = _client.Search(_platform, 1, 1, groupedRequest);
var dataTable = groupedResult.Data.ToDataTable(_allColumnInfo.Data);
// assert
Assert.AreEqual(1, groupedResult.Data.Count);
Assert.AreEqual(expected, dataTable.Rows[0][testColumnUniqueName]);
}
#region Helpers
private void AssertAggregatesCorrectly(SearchResponse rawResult, SearchResponse groupedResult, string aggregateSuffix, Func<IEnumerable<object>, object> aggregate)
{
var columnInfo = _client.GetColumnMappings(_platform, 1, null);
var rawDt = rawResult.Data.ToDataTable(columnInfo.Data);
var aggDt = groupedResult.Data.ToDataTable(columnInfo.Data);
Assert.IsNull(rawResult.Error);
Assert.Greater(rawResult.Data.Count, 0);
Assert.IsNull(groupedResult.Error);
Assert.Greater(groupedResult.Data.Count, 0);
// check counts
var allRawCountColumns = GetAllValuesForColumn(rawResult, c => UniqueName(c).EndsWith("_Count"));
var allGroupedCountColumns = GetAllValuesForColumn(groupedResult, c => UniqueName(c) == "Room_Count");
Assert.IsTrue(allRawCountColumns.All(x => x == "1"), "All counts should equal 1 to indiccate no grouping");
Assert.IsTrue(allGroupedCountColumns.Any(x => int.Parse(x) > 1), "Some counts should be greater than 1 when grouping");
var allRawGroupKeyColumns = GetAllValuesForColumn(rawResult, c => UniqueName(c) == "Room_HouseID");
Assert.AreEqual(allRawGroupKeyColumns.Distinct().Count(), groupedResult.Data.Count);
var allAggColumns = _allColumns.Data.Where(x => x.UniqueName.ToLower().EndsWith(aggregateSuffix.ToLower()));
foreach (var aggCol in allAggColumns)
{
if (aggCol.UniqueName.StartsWith("Room_HouseID")) // cannot aggregte the group key
{
continue;
}
Console.Write(aggCol.UniqueName + " VS ");
var originalCol = _allColumns.Data.First(x => x.UniqueName == aggCol.UniqueName.Replace(aggregateSuffix, ""));
Console.Write(originalCol.UniqueName + "\n");
var allOrigValues = GetAllValuesForColumnWithKey(rawDt, originalCol.UniqueName, "Room_HouseID").GroupBy(x => x.Item2);
var allAggValues = GetAllValuesForColumnWithKey(aggDt, aggCol.UniqueName, "Room_HouseID").GroupBy(x => x.Item2);
Assert.AreEqual(allAggValues.Count(), allOrigValues.Count());
foreach (var aggRow in allAggValues)
{
Assert.AreEqual(1, aggRow.Count());
var origRow = allOrigValues.FirstOrDefault(x => x.Key.ToString() == aggRow.Key.ToString());
var actual = aggRow.Single().Item1;
var expected = aggregate(origRow.Select(x => x.Item1));
Assert.AreEqual(expected, actual);
}
}
}
private object Max(IEnumerable<object> values)
{
if (values.First() is DateTime)
{
return values.Max(x => (DateTime)x);
}
if (values.First() is decimal)
{
var ds = values.Max(x => (decimal)x);
return Math.Round(ds, 6);
}
if (values.First() is int)
{
return values.Max(x => (int)x);
}
if (values.First() is Int64)
{
return values.Max(x => (Int64)x);
}
return values.Select(x=>x.ToString()).Max();
}
private object Min(IEnumerable<object> values)
{
if (values.First() is DateTime)
{
return values.Min(x => (DateTime)x);
}
if (values.First() is decimal)
{
var ds = values.Min(x => (decimal)x);
return Math.Round(ds, 6);
}
if (values.First() is int)
{
return values.Min(x => (int)x);
}
if (values.First() is Int64)
{
return values.Min(x => (Int64)x);
}
return values.Select(x=>x.ToString()).Min();
}
private object Sum(IEnumerable<object> values)
{
if (values.First() is decimal)
{
var ds = values.Sum(x => (decimal)x);
return Math.Round(ds, 6);
}
if (values.First() is int)
{
return values.Sum(x => (int)x);
}
if (values.First() is Int64)
{
return values.Sum(x => (Int64)x);
}
throw new NotImplementedException();
}
private object Average(IEnumerable<object> values)
{
if (values.First() is decimal)
{
var ds = values.Average(x => (decimal)x);
return Math.Round(ds, 6);
}
if (values.First() is int)
{
return (int)values.Average(x => (int)x);
}
if (values.First() is Int64)
{
return (Int64)values.Average(x => (Int64)x);
}
throw new NotImplementedException();
}
protected List<Tuple<string, string>> GetAllValuesForColumnWithKey(SearchResponse response, Func<ResultColumnValue, bool> columnMatch, string groupKeyColumn)
{
var groupColumnId = _allColumns.Data.First(x => x.UniqueName == groupKeyColumn).Id;
var result =
response.Data // rows
.Select(r =>
new Tuple<string,string>(
r.Values.First(columnMatch).Value, // key
r.Values.First(c=>c.ColumnId == groupColumnId).Value // value
)
)
.ToList();
return result;
}
private List<Tuple<object, object>> GetAllValuesForColumnWithKey(DataTable dt, string selectColumn, string groupKeyColumn)
{
return dt.AsEnumerable()
.Select(x => new Tuple<object, object>(x[selectColumn], x[groupKeyColumn]))
.ToList();
}
private string UniqueName(ResultColumnValue columnValue)
{
return _allColumns.Data.First(x => x.Id == columnValue.ColumnId).UniqueName;
}
#endregion
}
}
| 36.183099 | 171 | 0.548722 | [
"BSD-3-Clause"
] | salesforce/MagiQL | src/ScenarioTests/Scenarios/Scenario2-Analytics/Scenario2.Tests.Integration/AggregationTests.cs | 7,709 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3d12video.h(2975,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct D3D12_RESOLVE_VIDEO_MOTION_VECTOR_HEAP_OUTPUT
{
public IntPtr pMotionVectorTexture2D;
public D3D12_RESOURCE_COORDINATE MotionVectorCoordinate;
}
}
| 28.571429 | 87 | 0.765 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/D3D12_RESOLVE_VIDEO_MOTION_VECTOR_HEAP_OUTPUT.cs | 402 | C# |
using System.Text.Json.Serialization;
using Horizon.Payment.Alipay.Domain;
namespace Horizon.Payment.Alipay.Response
{
/// <summary>
/// AlipayDataDataserviceCodeRecoResponse.
/// </summary>
public class AlipayDataDataserviceCodeRecoResponse : AlipayResponse
{
/// <summary>
/// 识别结果
/// </summary>
[JsonPropertyName("result")]
public AlipayCodeRecoResult Result { get; set; }
}
}
| 24.833333 | 71 | 0.651007 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Response/AlipayDataDataserviceCodeRecoResponse.cs | 457 | C# |
/*
* ISO standards can be purchased through the ANSI webstore at https://webstore.ansi.org
*/
using System.Xml;
using AgGateway.ADAPT.ISOv4Plugin.ExtensionMethods;
using AgGateway.ADAPT.ISOv4Plugin.ISOEnumerations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using AgGateway.ADAPT.ISOv4Plugin.ObjectModel;
using AgGateway.ADAPT.ApplicationDataModel.ADM;
namespace AgGateway.ADAPT.ISOv4Plugin.ISOModels
{
public class ISO11783_TaskData : ISOElement
{
public ISO11783_TaskData()
{
ChildElements = new List<ISOElement>();
}
public List<ISOElement> ChildElements { get; set; }
public ISO11783_LinkList LinkList { get; set; }
public string DataFolder { get; set; }
public string FilePath { get; set; }
public int VersionMajor { get; set;}
public int VersionMinor { get; set;}
public string ManagementSoftwareManufacturer { get; set; }
public string ManagementSoftwareVersion { get; set; }
public string TaskControllerManufacturer { get; set; }
public string TaskControllerVersion { get; set; }
public ISOTaskDataTransferOrigin DataTransferOrigin { get { return (ISOTaskDataTransferOrigin)DataTransferOriginInt; } set { DataTransferOriginInt = (int)value; } }
private int DataTransferOriginInt { get; set; }
public string DataTransferLanguage { get; set; }
public override XmlWriter WriteXML(XmlWriter xmlBuilder)
{
xmlBuilder.WriteStartElement("ISO11783_TaskData");
xmlBuilder.WriteXmlAttribute<int>("VersionMajor", VersionMajor);
xmlBuilder.WriteXmlAttribute<int>("VersionMinor", VersionMinor);
xmlBuilder.WriteAttributeString("ManagementSoftwareManufacturer", ManagementSoftwareManufacturer ?? string.Empty);
xmlBuilder.WriteAttributeString("ManagementSoftwareVersion", ManagementSoftwareVersion ?? string.Empty);
xmlBuilder.WriteAttributeString("TaskControllerManufacturer", TaskControllerManufacturer ?? string.Empty);
xmlBuilder.WriteAttributeString("TaskControllerVersion", TaskControllerVersion ?? string.Empty);
xmlBuilder.WriteXmlAttribute("DataTransferOrigin", ((int)DataTransferOrigin).ToString());
if (DataTransferLanguage != null)
{
xmlBuilder.WriteAttributeString("DataTransferLanguage", DataTransferLanguage);
}
if (ChildElements != null)
{
foreach (var item in ChildElements)
{
item.WriteXML(xmlBuilder);
}
}
xmlBuilder.WriteEndElement();
return xmlBuilder;
}
public static ISO11783_TaskData ReadXML(XmlNode taskDataNode, string baseFolder)
{
ISO11783_TaskData taskData = new ISO11783_TaskData();
//Attributes
taskData.VersionMajor = taskDataNode.GetXmlNodeValueAsInt("@VersionMajor");
taskData.VersionMinor = taskDataNode.GetXmlNodeValueAsInt("@VersionMinor");
taskData.ManagementSoftwareManufacturer = taskDataNode.GetXmlNodeValue("@ManagementSoftwareManufacturer");
taskData.ManagementSoftwareVersion = taskDataNode.GetXmlNodeValue("@ManagementSoftwareVersion");
taskData.TaskControllerManufacturer = taskDataNode.GetXmlNodeValue("@TaskControllerManufacturer");
taskData.TaskControllerVersion = taskDataNode.GetXmlNodeValue("@TaskControllerVersion");
taskData.DataTransferOriginInt = taskDataNode.GetXmlNodeValueAsInt("@DataTransferOrigin");
taskData.DataTransferLanguage = taskDataNode.GetXmlNodeValue("@DataTransferLanguage");
//--------------
//Child Elements
//--------------
//Attached Files
XmlNodeList afeNodes = taskDataNode.SelectNodes("AFE");
if (afeNodes != null)
{
taskData.ChildElements.AddRange(ISOAttachedFile.ReadXML(afeNodes));
}
ProcessExternalNodes(taskDataNode, "AFE", baseFolder, taskData, ISOAttachedFile.ReadXML);
//Coded Comments
XmlNodeList cctNodes = taskDataNode.SelectNodes("CCT");
if (cctNodes != null)
{
taskData.ChildElements.AddRange(ISOCodedComment.ReadXML(cctNodes));
}
ProcessExternalNodes(taskDataNode, "CCT", baseFolder, taskData, ISOCodedComment.ReadXML);
//Crop Types
XmlNodeList ctpNodes = taskDataNode.SelectNodes("CTP");
if (ctpNodes != null)
{
taskData.ChildElements.AddRange(ISOCropType.ReadXML(ctpNodes));
}
ProcessExternalNodes(taskDataNode, "CTP", baseFolder, taskData, ISOCropType.ReadXML);
//Cultural Practices
XmlNodeList cpcNodes = taskDataNode.SelectNodes("CPC");
if (cpcNodes != null)
{
taskData.ChildElements.AddRange(ISOCulturalPractice.ReadXML(cpcNodes));
}
ProcessExternalNodes(taskDataNode, "CPC", baseFolder, taskData, ISOCulturalPractice.ReadXML);
//Customers
XmlNodeList ctrNodes = taskDataNode.SelectNodes("CTR");
if (ctrNodes != null)
{
taskData.ChildElements.AddRange(ISOCustomer.ReadXML(ctrNodes));
}
ProcessExternalNodes(taskDataNode, "CTR", baseFolder, taskData, ISOCustomer.ReadXML);
//Devices
XmlNodeList dvcNodes = taskDataNode.SelectNodes("DVC");
if (dvcNodes != null)
{
taskData.ChildElements.AddRange(ISODevice.ReadXML(dvcNodes));
}
ProcessExternalNodes(taskDataNode, "DVC", baseFolder, taskData, ISODevice.ReadXML);
//Farms
XmlNodeList frmNodes = taskDataNode.SelectNodes("FRM");
if (frmNodes != null)
{
taskData.ChildElements.AddRange(ISOFarm.ReadXML(frmNodes));
}
ProcessExternalNodes(taskDataNode, "FRM", baseFolder, taskData, ISOFarm.ReadXML);
//Operation Techniques
XmlNodeList otqNodes = taskDataNode.SelectNodes("OTQ");
if (otqNodes != null)
{
taskData.ChildElements.AddRange(ISOOperationTechnique.ReadXML(otqNodes));
}
ProcessExternalNodes(taskDataNode, "OTQ", baseFolder, taskData, ISOOperationTechnique.ReadXML);
//Partfields
XmlNodeList pfdNodes = taskDataNode.SelectNodes("PFD");
if (pfdNodes != null)
{
taskData.ChildElements.AddRange(ISOPartfield.ReadXML(pfdNodes));
}
ProcessExternalNodes(taskDataNode, "PFD", baseFolder, taskData, ISOPartfield.ReadXML);
//Products
XmlNodeList pdtNodes = taskDataNode.SelectNodes("PDT");
if (pdtNodes != null)
{
taskData.ChildElements.AddRange(ISOProduct.ReadXML(pdtNodes));
}
ProcessExternalNodes(taskDataNode, "PDT", baseFolder, taskData, ISOProduct.ReadXML);
//Product Groups
XmlNodeList pgpNodes = taskDataNode.SelectNodes("PGP");
if (pgpNodes != null)
{
taskData.ChildElements.AddRange(ISOProductGroup.ReadXML(pgpNodes));
}
ProcessExternalNodes(taskDataNode, "PGP", baseFolder, taskData, ISOProductGroup.ReadXML);
//Task Controller Capabilities
XmlNodeList tccNodes = taskDataNode.SelectNodes("TCC");
if (tccNodes != null)
{
taskData.ChildElements.AddRange(ISOTaskControllerCapabilities.ReadXML(tccNodes));
}
ProcessExternalNodes(taskDataNode, "TCC", baseFolder, taskData, ISOTaskControllerCapabilities.ReadXML);
//Tasks
XmlNodeList tskNodes = taskDataNode.SelectNodes("TSK");
if (tskNodes != null)
{
taskData.ChildElements.AddRange(ISOTask.ReadXML(tskNodes));
}
ProcessExternalNodes(taskDataNode, "TSK", baseFolder, taskData, ISOTask.ReadXML);
//Value Presentations
XmlNodeList vpnNodes = taskDataNode.SelectNodes("VPN");
if (vpnNodes != null)
{
taskData.ChildElements.AddRange(ISOValuePresentation.ReadXML(vpnNodes));
}
ProcessExternalNodes(taskDataNode, "VPN", baseFolder, taskData, ISOValuePresentation.ReadXML);
//Workers
XmlNodeList wkrNodes = taskDataNode.SelectNodes("WKR");
if (wkrNodes != null)
{
taskData.ChildElements.AddRange(ISOWorker.ReadXML(wkrNodes));
}
ProcessExternalNodes(taskDataNode, "WKR", baseFolder, taskData, ISOWorker.ReadXML);
//LinkList
ISOAttachedFile linkListFile = taskData.ChildElements.OfType<ISOAttachedFile>().SingleOrDefault(afe => afe.FileType == 1);
if (linkListFile != null)
{
XmlDocument linkDocument = new XmlDocument();
string linkPath = Path.Combine(baseFolder, linkListFile.FilenamewithExtension);
if (File.Exists(linkPath))
{
linkDocument.Load(linkPath);
XmlNode linkRoot = linkDocument.SelectSingleNode("ISO11783LinkList");
taskData.LinkList = ISO11783_LinkList.ReadXML(linkRoot, baseFolder);
}
}
return taskData;
}
public override List<IError> Validate(List<IError> errors)
{
RequireRange(this, x => x.VersionMajor, 0, 4, errors);
RequireRange(this, x => x.VersionMinor, 0, 99, errors);
ValidateString(this, x => x.ManagementSoftwareManufacturer, 32, errors);
ValidateString(this, x => x.ManagementSoftwareVersion, 32, errors);
ValidateString(this, x => x.TaskControllerManufacturer, 32, errors);
ValidateString(this, x => x.TaskControllerVersion, 32, errors);
ValidateEnumerationValue(typeof(ISOTaskDataTransferOrigin), DataTransferOriginInt, errors);
ChildElements.ForEach(i => i.Validate(errors));
if (LinkList != null) LinkList.Validate(errors);
return errors;
}
private static void ProcessExternalNodes(XmlNode node, string xmlPrefix, string baseFolder, ISO11783_TaskData taskData, Func<XmlNodeList, IEnumerable<ISOElement>> readDelegate)
{
var externalNodes = node.SelectNodes($"XFR[starts-with(@A, '{xmlPrefix}')]");
for (int i = 0; i < externalNodes.Count; i++)
{
var inputNodes = externalNodes[i].LoadActualNodes("XFR", baseFolder);
if (inputNodes != null)
{
taskData.ChildElements.AddRange(readDelegate(inputNodes));
}
}
}
}
}
| 44.478088 | 184 | 0.622985 | [
"EPL-1.0"
] | dburkhart-itk/ISOv4Plugin | ISOv4Plugin/ISOModels/ISO11783_TaskData.cs | 11,164 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace DBCHM.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 35.962963 | 151 | 0.561277 | [
"MIT"
] | AESCR/DBCHM | DBChm/Properties/Settings.Designer.cs | 1,079 | C# |
namespace QuizWebApp.Areas.HelpPage.ModelDescriptions
{
public class DictionaryModelDescription : KeyValuePairModelDescription
{
}
} | 24 | 74 | 0.791667 | [
"MIT"
] | cristvent/QuizWebApp | QuizWebApp/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs | 144 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace fiend.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 26.375 | 89 | 0.672986 | [
"MIT"
] | sharmavishalvk/fiend | Pages/Error.cshtml.cs | 633 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace TABG_Hack.Utils
{
static class ObjectFinder
{
//private static float timeCache;
public static bool HasComponent<T>(this GameObject flag) where T : Component
{
return !(flag == null) && flag.GetComponent<T>() != null;
}
public static T FindActiveObject<T>() where T : MonoBehaviour
{
Transform[] array = Resources.FindObjectsOfTypeAll<Transform>();
for (int i = 0; i < array.Length; i++)
{
if (array[i].hideFlags == HideFlags.None && array[i].gameObject.HasComponent<T>())
{
return array[i].GetComponent<T>();
}
}
return default(T);
}
//public static T CacheObject<T>(float curTime, float waitTime) where T : MonoBehaviour
//{
// T _obj = default(T);
// if (curTime >= timeCache)
// {
// timeCache = curTime + waitTime;
// _obj = FindActiveObject<T>();
// if(_obj != null)
// {
// Debug.LogError($"{_obj.GetType()}");
// return _obj;
// }
// }
// return _obj;
//}
//public List<T> CacheObjects<T>(float curTime, float waitTime) where T : Object
//{
// List<T> _obj = null;
// if (curTime >= timeCache)
// {
// timeCache = curTime + waitTime;
// _obj = Object.FindObjectsOfType<T>().ToList();
// }
// return _obj;
//}
}
}
| 20.75 | 89 | 0.609187 | [
"MIT"
] | Wolfleader101/TABG_Hack | Utils/ObjectFinder.cs | 1,330 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Oci.Devops.Outputs
{
[OutputType]
public sealed class GetDeployPipelinesDeployPipelineCollectionItemDeployPipelineEnvironmentsItemDeployPipelineStagesItemResult
{
/// <summary>
/// The OCID of a stage
/// </summary>
public readonly string DeployStageId;
/// <summary>
/// A filter to return only resources that match the entire display name given.
/// </summary>
public readonly string DisplayName;
[OutputConstructor]
private GetDeployPipelinesDeployPipelineCollectionItemDeployPipelineEnvironmentsItemDeployPipelineStagesItemResult(
string deployStageId,
string displayName)
{
DeployStageId = deployStageId;
DisplayName = displayName;
}
}
}
| 31.611111 | 130 | 0.688928 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Devops/Outputs/GetDeployPipelinesDeployPipelineCollectionItemDeployPipelineEnvironmentsItemDeployPipelineStagesItemResult.cs | 1,138 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using Xunit;
namespace System.IO.Tests
{
public class FileStream_ctor_sfh_fa : FileSystemTest
{
protected virtual FileStream CreateFileStream(SafeFileHandle handle, FileAccess access)
{
return new FileStream(handle, access);
}
[Fact]
public void InvalidHandle_Throws()
{
using (var handle = new SafeFileHandle(new IntPtr(-1), ownsHandle: false))
{
AssertExtensions.Throws<ArgumentException>("handle", () => CreateFileStream(handle, FileAccess.Read));
}
}
[Fact]
public void InvalidAccess_Throws()
{
using (var handle = new SafeFileHandle(new IntPtr(1), ownsHandle: false))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("access", () => CreateFileStream(handle, ~FileAccess.Read));
}
}
[Fact]
public void InvalidAccess_DoesNotCloseHandle()
{
using (var handle = new SafeFileHandle(new IntPtr(1), ownsHandle: false))
{
Assert.Throws<ArgumentOutOfRangeException>(() => CreateFileStream(handle, ~FileAccess.Read));
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(handle.IsClosed);
}
}
[Fact]
public void FileAccessRead()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using (FileStream fsr = CreateFileStream(fs.SafeFileHandle, FileAccess.Read))
{
Assert.True(fsr.CanRead);
Assert.Equal(0, fsr.ReadByte());
Assert.False(fsr.CanWrite);
Assert.Throws<NotSupportedException>(() => fsr.WriteByte(0));
Assert.True(fsr.CanSeek);
}
}
}
[Fact]
public void FileAccessWrite()
{
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
{
using (FileStream fsw = CreateFileStream(fs.SafeFileHandle, FileAccess.Write))
{
Assert.False(fsw.CanRead);
Assert.Throws<NotSupportedException>(() => fsw.ReadByte());
Assert.True(fsw.CanWrite);
fsw.WriteByte(0); // should not throw
Assert.True(fsw.CanSeek);
}
}
}
[Fact]
public void FileAccessReadWrite()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
{
using (FileStream fsrw = CreateFileStream(fs.SafeFileHandle, FileAccess.ReadWrite))
{
Assert.True(fsrw.CanRead);
Assert.Equal(0, fsrw.ReadByte());
Assert.True(fsrw.CanWrite);
fsrw.WriteByte(0); // should not throw
Assert.True(fsrw.CanSeek);
}
}
}
[Fact]
public void InconsistentFileAccessThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
FileStream fsw = CreateFileStream(fs.SafeFileHandle, FileAccess.Write);
Assert.False(fsw.CanRead);
Assert.Throws<NotSupportedException>(() => fsw.ReadByte());
Assert.True(fsw.CanWrite);
// doesn't throw due to buffering.
fsw.WriteByte(0);
Assert.True(fsw.CanSeek);
// throws due to FS trying to flush write buffer
Assert.Throws<UnauthorizedAccessException>(() => fsw.Dispose());
}
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write))
{
using (FileStream fsr = CreateFileStream(fs.SafeFileHandle, FileAccess.Read))
{
Assert.True(fsr.CanRead);
Assert.Throws<UnauthorizedAccessException>(() => fsr.ReadByte());
Assert.False(fsr.CanWrite);
Assert.Throws<NotSupportedException>(() => fsr.WriteByte(0));
Assert.True(fsr.CanSeek);
}
}
}
}
public class DerivedFileStream_ctor_sfh_fa : FileSystemTest
{
[Fact]
public void VirtualCanReadWrite_ShouldNotBeCalledDuringCtor()
{
using (var fs = File.Create(GetTestFilePath()))
using (var dfs = new DerivedFileStream(fs.SafeFileHandle, FileAccess.ReadWrite))
{
Assert.False(dfs.CanReadCalled);
Assert.False(dfs.CanWriteCalled);
Assert.False(dfs.CanSeekCalled);
}
}
private sealed class DerivedFileStream : FileStream
{
public DerivedFileStream(SafeFileHandle handle, FileAccess access) : base(handle, access) { }
public bool CanReadCalled { get; set; }
public bool CanWriteCalled { get; set; }
public bool CanSeekCalled { get; set; }
public override bool CanRead
{
get
{
CanReadCalled = true;
return base.CanRead;
}
}
public override bool CanWrite
{
get
{
CanWriteCalled = true;
return base.CanWrite;
}
}
public override bool CanSeek
{
get
{
CanSeekCalled = true;
return base.CanSeek;
}
}
}
}
}
| 34.112245 | 129 | 0.515256 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.IO.FileSystem/tests/FileStream/ctor_sfh_fa.cs | 6,686 | 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("QuickstartSnoozableToastsEvenIfComputerOff")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuickstartSnoozableToastsEvenIfComputerOff")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 37.965517 | 84 | 0.755677 | [
"MIT"
] | WindowsNotifications/quickstart-snoozable-toasts-even-if-computer-is-off | cs/QuickstartSnoozableToastsEvenIfComputerOff/Properties/AssemblyInfo.cs | 1,104 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Threading.Tasks;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Migrations;
namespace Migrations.Migrations
{
public sealed class RebuildContents : IMigration
{
private readonly Rebuilder rebuilder;
public RebuildContents(Rebuilder rebuilder)
{
this.rebuilder = rebuilder;
}
public Task UpdateAsync()
{
return rebuilder.RebuildContentAsync();
}
}
}
| 29.206897 | 78 | 0.488784 | [
"MIT"
] | Jaben/squidex | backend/src/Migrations/Migrations/RebuildContents.cs | 849 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/Xinput.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct XINPUT_GAMEPAD
{
[NativeTypeName("WORD")]
public ushort wButtons;
[NativeTypeName("BYTE")]
public byte bLeftTrigger;
[NativeTypeName("BYTE")]
public byte bRightTrigger;
[NativeTypeName("SHORT")]
public short sThumbLX;
[NativeTypeName("SHORT")]
public short sThumbLY;
[NativeTypeName("SHORT")]
public short sThumbRX;
[NativeTypeName("SHORT")]
public short sThumbRY;
}
}
| 26.0625 | 145 | 0.654676 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/Xinput/XINPUT_GAMEPAD.cs | 836 | C# |
namespace Divstack.Company.Estimation.Tool.Payments.Domain.Common.UserAccess;
public interface ICurrentUserService
{
Guid GetPublicUserId();
}
| 21.285714 | 78 | 0.812081 | [
"MIT"
] | kamilbaczek/estimation-tool | Src/Modules/Payments/Divstack.Company.Estimation.Tool.Payments.Domain/Common/UserAccess/ICurrentUserService.cs | 151 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace acServerFake.view.messages
{
/// <summary>
/// Interaction logic for CarInfoView.xaml
/// </summary>
public partial class CarInfoView : UserControl
{
public CarInfoView()
{
InitializeComponent();
}
}
}
| 23.586207 | 51 | 0.69152 | [
"Apache-2.0"
] | flitzi/acplugins | acplugins4net/acServerFake/view/messages/CarInfoView.xaml.cs | 686 | C# |
////using System;
////namespace ASampleApp.BlobStorage
////{
//// public class MyClass
//// {
//// public MyClass()
//// {
//// }
//// }
////}
//using Microsoft.WindowsAzure.Storage;
//using Microsoft.WindowsAzure.Storage.Blob;
//using System.Threading.Tasks;
//using System;
//using System.IO;
//using Xamarin.Forms;
//using System.Reflection;
//using Microsoft.WindowsAzure.Storage.Auth;
//namespace ASampleApp.BlobStorage
//{
// public class MyClass
// {
// public MyClass()
// {
// }
// public static async Task performBlobOperation()
// {
// //https://stackoverflow.com/questions/22014384/getting-images-in-the-azure-blob-storage
// // var credentials = new StorageCredentials("asampleappfive", "UPDATE_YOUR_WITH_OWN_KEY+iQgcomcQ==");
// // Retrieve storage account from connection string.
// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
// CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureBlobConstants.BlobUrlAndKey);
// //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_OWN_KEY_iQgcomcQ==; EndpointSuffix = core.windows.net");
// // Create the blob client.
// CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// // Retrieve reference to a previously created container.
// CloudBlobContainer container = blobClient.GetContainerReference("my9container");
// // Create the container if it doesn't already exist.
// await container.CreateIfNotExistsAsync();
// var perm = new BlobContainerPermissions();
// perm.PublicAccess = BlobContainerPublicAccessType.Blob;
// await container.SetPermissionsAsync(perm);
// //UPLOAD IMAGE
// const string ImageToUpload = "HelloWorld.png";
// CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
// Assembly assembly = typeof(MyClass).GetTypeInfo().Assembly;
// //byte [] buffer;
// //using (Stream stream = assembly.GetManifestResourceStream (imagePath)) {
// // long length = stream.Length;
// // buffer = new byte [length];
// // stream.Read (buffer, 0, (int)length);
//#if __IOS__
// var stream = assembly.GetManifestResourceStream("ASampleApp.iOS.HelloWorld.png");
//#endif
//#if __ANDROID__
// var stream = assembly.GetManifestResourceStream("ASampleApp.Droid.HelloWorld.png");
//#endif
// //var stream = assembly.GetManifestResourceStream (imagePath);
// //var bytes = new byte [stream.Length];
// //await stream.ReadAsync (bytes, 0, (int)stream.Length);
// //string base64 = System.Convert.ToBase64String (bytes);
// await blockBlob.UploadFromStreamAsync(stream);
// //var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync (string.Format (FileNames.ApplicationIcon, app.ApplicationId), buffer);
// //app.IconURLLocal = storeragePath;
// }
// //public static async Task<string> getTheUrlFromBlob()
// public static string getTheUrlFromBlob()
// {
// // Retrieve storage account from connection string.
// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
// CloudStorageAccount storageAccount = CloudStorageAccount.Parse(AzureBlobConstants.BlobUrlAndKey);
// //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_OWN_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
// // Create the blob client.
// CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// // Retrieve reference to a previously created container.
// CloudBlobContainer container = blobClient.GetContainerReference("my7container");
// // Create the container if it doesn't already exist.
// //await container.CreateIfNotExistsAsync();
// container.CreateIfNotExistsAsync();
// //UPLOAD IMAGE
// const string ImageToUpload = "HelloWorld.png";
// CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
// Assembly assembly = typeof(MyClass).GetTypeInfo().Assembly;
//#if __IOS__
// var stream = assembly.GetManifestResourceStream("ASampleApp.iOS.HelloWorld.png");
//#endif
//#if __ANDROID__
// var stream = assembly.GetManifestResourceStream("ASampleApp.Droid.HelloWorld.png");
//#endif
// //await blockBlob.UploadFromStreamAsync(stream);
// blockBlob.UploadFromStreamAsync(stream);
// string hi = "https://xamarin.com/content/images/pages/forms/example-app.png";
// return hi;
// }
// //public static async Task<byte[]> GetFileAsync(ContainerType containerType, string name)
// //{
// // var container = GetContainer(containerType);
// // var blob = container.GetBlobReference(name);
// // if (await blob.ExistsAsync())
// // {
// // await blob.FetchAttributesAsync();
// // byte[] blobBytes = new byte[blob.Properties.Length];
// // await blob.DownloadToByteArrayAsync(blobBytes, 0);
// // return blobBytes;
// // }
// // return null;
// //}
// // public static async Task performBlobOperation()
// // {
// // // Retrieve storage account from connection string.
// // // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
// // //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
// // // Create the blob client.
// // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// // // Retrieve reference to a previously created container.
// // CloudBlobContainer container = blobClient.GetContainerReference("my6container");
// // // Create the container if it doesn't already exist.
// // await container.CreateIfNotExistsAsync();
// // //UPLOAD IMAGE
// // const string ImageToUpload = "HelloWorld.png";
// // CloudBlockBlob blockBlob = container.GetBlockBlobReference (ImageToUpload);
// //// blockBlob.Properties.ContentType = "image/png";
// //// Console.WriteLine("- {0} (type: {1})", blockBlob.Uri, blockBlob.GetType());
// ////UPLOAD FROM FILE?
// //// await blockBlob.UploadFromFileAsync (ImageToUpload);
// //// https://stackoverflow.com/questions/41707205/xamarin-forms-image-to-stream
// //// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
// // string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
// // Assembly assembly = typeof (MyClass).GetTypeInfo ().Assembly;
// // //byte [] buffer;
// // //using (Stream stream = assembly.GetManifestResourceStream (imagePath)) {
// // // long length = stream.Length;
// // // buffer = new byte [length];
// // // stream.Read (buffer, 0, (int)length);
// // var stream = assembly.GetManifestResourceStream ("ASampleApp.iOS.HelloWorld.png");
// // //var stream = assembly.GetManifestResourceStream (imagePath);
// // //var bytes = new byte [stream.Length];
// // //await stream.ReadAsync (bytes, 0, (int)stream.Length);
// // //string base64 = System.Convert.ToBase64String (bytes);
// // await blockBlob.UploadFromStreamAsync (stream);
// // //var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync (string.Format (FileNames.ApplicationIcon, app.ApplicationId), buffer);
// // //app.IconURLLocal = storeragePath;
// // }
// //UPLOAD FROM STREAM
// //UPLOAD FROM TEXT
// ////UPLOAD TEXT
// //// Retrieve reference to a blob named "myblob".
// //CloudBlockBlob blockBlob = container.GetBlockBlobReference ("mypictureblob");
// //await blockBlob.UploadTextAsync ("Hello, world!");
// // Create the "myblob" blob with the text "Hello, world!"
// // await blockBlob.UploadTextAsync ("Hello, world!");
// //// Retrieve reference to a blob named "myblob".
// //CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
// //// Create the "myblob" blob with the text "Hello, world!"
// //await blockBlob.UploadTextAsync("Hello, world!");
// }
// //public static async Task performBlobOperation ()
// //{
// // // Retrieve storage account from connection string.
// // // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse ("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
// // //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
// // // Create the blob client.
// // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient ();
// // // Retrieve reference to a previously created container.
// // CloudBlobContainer container = blobClient.GetContainerReference ("mycontainer");
// // // Create the container if it doesn't already exist.
// // await container.CreateIfNotExistsAsync ();
// // // Retrieve reference to a blob named "myblob".
// // CloudBlockBlob blockBlob = container.GetBlockBlobReference ("myblob");
// // // Create the "myblob" blob with the text "Hello, world!"
// // await blockBlob.UploadTextAsync ("Hello, world!");
// //}
//}
//////using System;
//////namespace ASampleApp.BlobStorage
//////{
////// public class MyClass
////// {
////// public MyClass()
////// {
////// }
////// }
//////}
////using Microsoft.WindowsAzure.Storage;
////using Microsoft.WindowsAzure.Storage.Blob;
////using System.Threading.Tasks;
////using System;
////using System.IO;
////using Xamarin.Forms;
////using System.Reflection;
////namespace ASampleApp.BlobStorage
////{
//// public class MyClass
//// {
//// public MyClass()
//// {
//// }
//// public static async Task performBlobOperation()
//// {
//// // Retrieve storage account from connection string.
//// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
//// CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
//// //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
//// // Create the blob client.
//// CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//// // Retrieve reference to a previously created container.
//// CloudBlobContainer container = blobClient.GetContainerReference("my7container");
//// // Create the container if it doesn't already exist.
//// await container.CreateIfNotExistsAsync();
//// //UPLOAD IMAGE
//// const string ImageToUpload = "HelloWorld.png";
//// CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
//// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
//// Assembly assembly = typeof(MyClass).GetTypeInfo().Assembly;
//// //byte [] buffer;
//// //using (Stream stream = assembly.GetManifestResourceStream (imagePath)) {
//// // long length = stream.Length;
//// // buffer = new byte [length];
//// // stream.Read (buffer, 0, (int)length);
////#if __IOS__
//// var stream = assembly.GetManifestResourceStream("ASampleApp.iOS.HelloWorld.png");
////#endif
////#if __ANDROID__
//// var stream = assembly.GetManifestResourceStream("ASampleApp.Droid.HelloWorld.png");
////#endif
//// //var stream = assembly.GetManifestResourceStream (imagePath);
//// //var bytes = new byte [stream.Length];
//// //await stream.ReadAsync (bytes, 0, (int)stream.Length);
//// //string base64 = System.Convert.ToBase64String (bytes);
//// await blockBlob.UploadFromStreamAsync(stream);
//// //var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync (string.Format (FileNames.ApplicationIcon, app.ApplicationId), buffer);
//// //app.IconURLLocal = storeragePath;
//// }
//// //public static async Task<string> getTheUrlFromBlob()
//// public static string getTheUrlFromBlob()
//// {
//// // Retrieve storage account from connection string.
//// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
//// CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
//// //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
//// // Create the blob client.
//// CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//// // Retrieve reference to a previously created container.
//// CloudBlobContainer container = blobClient.GetContainerReference("my7container");
//// // Create the container if it doesn't already exist.
//// //await container.CreateIfNotExistsAsync();
//// container.CreateIfNotExistsAsync();
//// //UPLOAD IMAGE
//// const string ImageToUpload = "HelloWorld.png";
//// CloudBlockBlob blockBlob = container.GetBlockBlobReference(ImageToUpload);
//// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
//// Assembly assembly = typeof(MyClass).GetTypeInfo().Assembly;
////#if __IOS__
//// var stream = assembly.GetManifestResourceStream("ASampleApp.iOS.HelloWorld.png");
////#endif
////#if __ANDROID__
//// var stream = assembly.GetManifestResourceStream("ASampleApp.Droid.HelloWorld.png");
////#endif
//// //await blockBlob.UploadFromStreamAsync(stream);
//// blockBlob.UploadFromStreamAsync(stream);
//// string hi = "https://xamarin.com/content/images/pages/forms/example-app.png";
//// return hi;
//// //https://stackoverflow.com/questions/22014384/getting-images-in-the-azure-blob-storage
//// }
//// //public static async Task<byte[]> GetFileAsync(ContainerType containerType, string name)
//// //{
//// // var container = GetContainer(containerType);
//// // var blob = container.GetBlobReference(name);
//// // if (await blob.ExistsAsync())
//// // {
//// // await blob.FetchAttributesAsync();
//// // byte[] blobBytes = new byte[blob.Properties.Length];
//// // await blob.DownloadToByteArrayAsync(blobBytes, 0);
//// // return blobBytes;
//// // }
//// // return null;
//// //}
//// // public static async Task performBlobOperation()
//// // {
//// // // Retrieve storage account from connection string.
//// // // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
//// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
//// // //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
//// // // Create the blob client.
//// // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//// // // Retrieve reference to a previously created container.
//// // CloudBlobContainer container = blobClient.GetContainerReference("my6container");
//// // // Create the container if it doesn't already exist.
//// // await container.CreateIfNotExistsAsync();
//// // //UPLOAD IMAGE
//// // const string ImageToUpload = "HelloWorld.png";
//// // CloudBlockBlob blockBlob = container.GetBlockBlobReference (ImageToUpload);
//// //// blockBlob.Properties.ContentType = "image/png";
//// //// Console.WriteLine("- {0} (type: {1})", blockBlob.Uri, blockBlob.GetType());
//// ////UPLOAD FROM FILE?
//// //// await blockBlob.UploadFromFileAsync (ImageToUpload);
//// //// https://stackoverflow.com/questions/41707205/xamarin-forms-image-to-stream
//// //// string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
//// // string imagePath = "ASampleApp.BlobStorage.HelloWorld.png";
//// // Assembly assembly = typeof (MyClass).GetTypeInfo ().Assembly;
//// // //byte [] buffer;
//// // //using (Stream stream = assembly.GetManifestResourceStream (imagePath)) {
//// // // long length = stream.Length;
//// // // buffer = new byte [length];
//// // // stream.Read (buffer, 0, (int)length);
//// // var stream = assembly.GetManifestResourceStream ("ASampleApp.iOS.HelloWorld.png");
//// // //var stream = assembly.GetManifestResourceStream (imagePath);
//// // //var bytes = new byte [stream.Length];
//// // //await stream.ReadAsync (bytes, 0, (int)stream.Length);
//// // //string base64 = System.Convert.ToBase64String (bytes);
//// // await blockBlob.UploadFromStreamAsync (stream);
//// // //var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync (string.Format (FileNames.ApplicationIcon, app.ApplicationId), buffer);
//// // //app.IconURLLocal = storeragePath;
//// // }
//// //UPLOAD FROM STREAM
//// //UPLOAD FROM TEXT
//// ////UPLOAD TEXT
//// //// Retrieve reference to a blob named "myblob".
//// //CloudBlockBlob blockBlob = container.GetBlockBlobReference ("mypictureblob");
//// //await blockBlob.UploadTextAsync ("Hello, world!");
//// // Create the "myblob" blob with the text "Hello, world!"
//// // await blockBlob.UploadTextAsync ("Hello, world!");
//// //// Retrieve reference to a blob named "myblob".
//// //CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
//// //// Create the "myblob" blob with the text "Hello, world!"
//// //await blockBlob.UploadTextAsync("Hello, world!");
//// }
//// //public static async Task performBlobOperation ()
//// //{
//// // // Retrieve storage account from connection string.
//// // // CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=your_account_name_here;AccountKey=your_account_key_here");
//// // CloudStorageAccount storageAccount = CloudStorageAccount.Parse ("DefaultEndpointsProtocol=https;AccountName=asampleappfive;AccountKey=UPDATE_WITH_YOUR_KEY_+iQgcomcQ==");
//// // //CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol = https; AccountName = asampleappfive; AccountKey = UPDATE_WITH_YOUR_KEY_+iQgcomcQ==; EndpointSuffix = core.windows.net");
//// // // Create the blob client.
//// // CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient ();
//// // // Retrieve reference to a previously created container.
//// // CloudBlobContainer container = blobClient.GetContainerReference ("mycontainer");
//// // // Create the container if it doesn't already exist.
//// // await container.CreateIfNotExistsAsync ();
//// // // Retrieve reference to a blob named "myblob".
//// // CloudBlockBlob blockBlob = container.GetBlockBlobReference ("myblob");
//// // // Create the "myblob" blob with the text "Hello, world!"
//// // await blockBlob.UploadTextAsync ("Hello, world!");
//// //}
////}
| 33.712681 | 231 | 0.681141 | [
"MIT"
] | andrewchungxam/ASampleAppSeventeen | ASampleApp/ASampleApp.BlobStorage/MyClassArchive.cs | 21,005 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/dwrite_1.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum DWRITE_BASELINE
{
DWRITE_BASELINE_DEFAULT,
DWRITE_BASELINE_ROMAN,
DWRITE_BASELINE_CENTRAL,
DWRITE_BASELINE_MATH,
DWRITE_BASELINE_HANGING,
DWRITE_BASELINE_IDEOGRAPHIC_BOTTOM,
DWRITE_BASELINE_IDEOGRAPHIC_TOP,
DWRITE_BASELINE_MINIMUM,
DWRITE_BASELINE_MAXIMUM,
}
}
| 32 | 145 | 0.729167 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/dwrite_1/DWRITE_BASELINE.cs | 674 | C# |
using Ship;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DamageDeckCardFE
{
public class DamagedSensorArray : GenericDamageCard
{
public DamagedSensorArray()
{
Name = "Damaged Sensor Array";
Type = CriticalCardType.Ship;
CancelDiceResults.Add(DieSide.Success);
CancelDiceResults.Add(DieSide.Crit);
}
public override void ApplyEffect(object sender, EventArgs e)
{
Host.OnTryAddAvailableAction += OnlyCancelCritActions;
Host.AfterGenerateAvailableActionsList += CallAddCancelCritAction;
Host.Tokens.AssignCondition(new Tokens.DamagedSensorArrayCritToken(Host));
Triggers.FinishTrigger();
}
public override void DiscardEffect()
{
base.DiscardEffect();
Messages.ShowInfo("You can perform actions as usual");
Host.Tokens.RemoveCondition(typeof(Tokens.DamagedSensorArrayCritToken));
Host.OnTryAddAvailableAction -= OnlyCancelCritActions;
Host.AfterGenerateAvailableActionsList -= CallAddCancelCritAction;
}
private void OnlyCancelCritActions(ActionsList.GenericAction action, ref bool result)
{
if (!action.IsCritCancelAction)
{
result = false;
}
}
}
} | 28.078431 | 93 | 0.63757 | [
"MIT"
] | borkin8r/FlyCasual | Assets/Scripts/Model/CriticalHitsDeck/CriticalHitsCardsFE/DamagedSensorArray.cs | 1,434 | 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.AwsNative.SageMaker.Inputs
{
/// <summary>
/// A key-value pair to associate with a resource.
/// </summary>
public sealed class ModelExplainabilityJobDefinitionTagArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The key name of the tag. You can specify a value that is 1 to 127 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// The value for the tag. You can specify a value that is 1 to 255 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.
/// </summary>
[Input("value", required: true)]
public Input<string> Value { get; set; } = null!;
public ModelExplainabilityJobDefinitionTagArgs()
{
}
}
}
| 40.371429 | 256 | 0.651805 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/SageMaker/Inputs/ModelExplainabilityJobDefinitionTagArgs.cs | 1,413 | 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 organizations-2016-11-28.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.Organizations.Model
{
/// <summary>
/// We can't find a root, OU, or account with the <code>TargetId</code> that you specified.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class TargetNotFoundException : AmazonOrganizationsException
{
/// <summary>
/// Constructs a new TargetNotFoundException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public TargetNotFoundException(string message)
: base(message) {}
/// <summary>
/// Construct instance of TargetNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TargetNotFoundException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of TargetNotFoundException
/// </summary>
/// <param name="innerException"></param>
public TargetNotFoundException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of TargetNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TargetNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of TargetNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TargetNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the TargetNotFoundException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected TargetNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.387097 | 178 | 0.679714 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Organizations/Generated/Model/TargetNotFoundException.cs | 5,876 | C# |
using PiRhoSoft.Expressions;
using PiRhoSoft.Variables;
using System.Collections;
using UnityEngine;
namespace PiRhoSoft.Composition
{
[CreateGraphNodeMenu("Control Flow/Conditional", 0)]
public class ConditionalNode : GraphNode
{
public GraphNode OnTrue;
public GraphNode OnFalse;
public ReadOnlyExpression Condition = new ReadOnlyExpression();
public override Color NodeColor => Colors.Branch;
public override IEnumerator Run(IGraphRunner graph, IVariableDictionary variables)
{
var condition = Condition.Execute(variables, VariableType.Bool);
if (condition.AsBool)
graph.GoTo(OnTrue, nameof(OnTrue));
else
graph.GoTo(OnFalse, nameof(OnFalse));
yield break;
}
}
}
| 22.935484 | 84 | 0.762307 | [
"MIT"
] | pirhosoft/PiRhoComposition | Assets/PiRhoComposition/Runtime/Nodes/ConditionalNode.cs | 713 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RPGGameModifier : ScriptableObject
{
public int ID = -1;
public Sprite icon;
public string _name;
public string _fileName;
public string displayName;
public string description;
public enum GameModifierUnlockType
{
MainMenu,
World,
Both
}
public GameModifierUnlockType unlockType;
public enum CategoryType
{
Combat,
General,
World,
Settings
}
public enum CombatModuleType
{
Ability,
Effect,
NPC,
Stat,
TreePoint,
Spellbook,
Faction,
WeaponTemplate
}
public enum GeneralModuleType
{
Item,
Skill,
LevelTemplate,
Race,
Class,
TalentTree,
LootTable,
MerchantTable,
Currency,
CraftingRecipe,
CraftingStation,
Bonus,
GearSet,
Enchantment,
}
public enum WorldModuleType
{
Task,
Quest,
WorldPosition,
ResourceNode,
GameScene,
Dialogue
}
public enum SettingsModuleType
{
CombatSettings,
GeneralSettings,
SceneSettings
}
public enum GameModifierType
{
Positive,
Negative
}
public GameModifierType gameModifierType;
public int cost;
public int gain;
[System.Serializable]
public class ModuleAmountModifier
{
public int entryID = -1;
public string entryName;
public float alterAmount;
public bool isPercent;
public DataModifierType dataModifierType;
}
[System.Serializable]
public class StatDataModifier
{
[StatID] public int statID = -1;
public DataModifierType dataModifierType;
public UnitType unitType;
public bool checkMin, checkMax;
public float valueMin, valueMax;
public float valueDefault;
public bool restShifting, CombatShifting;
public float restShiftAmount, restShiftInterval, combatShiftAmount, combatShiftInterval;
}
public enum UnitType
{
Player,
NPC,
All
}
public enum DataModifierType
{
Add,
Override
}
public enum AbilityModifierType
{
Unlock_Cost,
No_Use_Requirement,
No_Effect_Requirement
}
public enum PointModifierType
{
Start_At,
Max,
Gain_Value
}
public enum FactionModifierType
{
Stance_Point_Required,
Interaction_Start_Point
}
public enum SpellbookModifierType
{
Ability_Level_Required,
Bonus_Level_Required
}
public enum StatModifierType
{
Settings,
MinOverride,
MaxOverride
}
public enum NPCModifierType
{
Aggro_Range,
Exp,
Level,
Reset_Target_Distance,
Respawn_Time,
Faction_Reward,
Loot_Table_Chance,
Roam_Range,
Faction
}
public enum WeaponTemplateModifierType
{
Exp_Mod,
No_Starting_Items,
Stat_Amount,
}
public enum ItemModifierType
{
Gem_Bonus_Amount,
Attack_Speed,
Min_Damage,
Max_Damage,
Overriden_Auto_Attack,
Stat_Amount,
Max_Random_Stat_Amount,
Random_Stats_Chance,
Random_Stat_Min,
Random_Stat_Max,
Sell_Price,
Stack_Amount,
No_Requirement,
}
public enum SkillModifierType
{
Alloc_Points,
No_Starting_Items,
Stat_Amount,
}
public enum LevelTemplateModifierType
{
MaxEXPToLevel,
}
public enum RaceModifierType
{
Male_Prefab,
Female_Prefab,
Start_Scene,
Start_Position,
Faction,
Stat_Amount,
No_Starting_Items,
Alloc_Points
}
public enum ClassModifierType
{
Alloc_Points,
Alloc_Points_Menu,
No_Starting_Items,
Stat_Amount
}
public enum MerchantTableModifierType
{
Cost,
Currency,
}
public enum CurrencyModifierType
{
Min,
Max,
Start_At,
Amount_For_Convertion
}
public enum RecipeModifierType
{
Unlock_Cost,
EXP,
Crafted_Chance,
Crafted_Count,
Component_Required_Count
}
public enum BonusModifierType
{
Unlock_Cost,
No_Requirement,
}
public enum GearSetModifierType
{
Equipped_Amount,
Stat_Bonuses,
}
public enum EnchantmentModifierType
{
No_Requirement,
Time,
Price,
}
public enum QuestModifierType
{
No_Requirement,
}
public enum ResourceNodeModifierType
{
Unlock_Cost,
EXP,
Gather_Time,
Respawn_Time,
Level_Required
}
public enum GeneralSettingModifierType
{
No_Auto_Save,
}
public enum CombatSettingModifierType
{
Health_Stat,
Alloc_Tree_Point,
Can_Decrease_Alloc_Point,
Critical_Bonus,
Combat_Reset_Timer,
Action_Bar_Slots
}
public enum WorldSettingModifierType
{
Light_Intensity,
Camera_FOV,
Game_Audio
}
[System.Serializable]
public class GameModifierDATA
{
public bool showModifier;
public CategoryType categoryType;
public CombatModuleType combatModuleType;
public GeneralModuleType generalModuleType;
public WorldModuleType worldModuleType;
public SettingsModuleType settingsModuleType;
public string modifierTypeName;
public bool showEntryList;
public ModuleAmountModifier amountModifier = new ModuleAmountModifier();
public List<ModuleAmountModifier> amountModifierList = new List<ModuleAmountModifier>();
public List<int> entryIDs = new List<int>();
public bool boolValue;
public bool isGlobal = true;
public int intValue;
public float floatValue;
public GameObject gameObjectValue;
// ABILITY
public AbilityModifierType abilityModifierType;
// POINTS
public PointModifierType treePointModifierType;
// FACTIONS
public FactionModifierType factionModifierType;
// SPELLBOOK
public SpellbookModifierType spellbookModifierType;
// STATS
public StatModifierType statModifierType;
[RPGDataList] public List<StatDataModifier> statModifierData = new List<StatDataModifier>();
// NPC
public NPCModifierType npcModifierType;
// WEAPON TEMPLATES
public WeaponTemplateModifierType weaponTemplateModifierType;
// ITEMS
public ItemModifierType itemModifierType;
// SKILLS
public SkillModifierType skillModifierType;
// LEVEL TEMPLATES
public LevelTemplateModifierType levelTemplateModifierType;
// RACES
public RaceModifierType raceModifierType;
public GameObject raceOverridenMalePrefab;
public GameObject raceOverridenFemalePrefab;
// CLASSES
public ClassModifierType classModifierType;
// MERCHANT TABLES
public MerchantTableModifierType merchantTableModifierType;
// CURRENCIES
public CurrencyModifierType currencyModifierType;
// RECIPE
public RecipeModifierType recipeModifierType;
// BONUS
public BonusModifierType bonusModifierType;
// GEAR SETS
public GearSetModifierType gearSetModifierType;
// ENCHANTMENT
public EnchantmentModifierType enchantmentModifierType;
// QUEST
public QuestModifierType questModifierType;
// RESOURCE NODE
public ResourceNodeModifierType resourceNodeModifierType;
// GENERAL SETTINGS
public GeneralSettingModifierType generalSettingModifierType;
// COMBAT SETTINGS
public CombatSettingModifierType combatSettingModifierType;
// WORLD SETTINGS
public WorldSettingModifierType worldSettingModifierType;
}
[RPGDataList] public List<GameModifierDATA> gameModifiersList = new List<GameModifierDATA>();
public void updateThis(RPGGameModifier newData)
{
ID = newData.ID;
_name = newData._name;
displayName = newData.displayName;
_fileName = newData._fileName;
description = newData.description;
icon = newData.icon;
gameModifierType = newData.gameModifierType;
cost = newData.cost;
gain = newData.gain;
gameModifiersList = newData.gameModifiersList;
}
}
| 21.923261 | 100 | 0.608401 | [
"MIT"
] | noahm1216/Realistically-Projected-Game-v1 | RPGv1/Assets/Blink/Tools/RPGBuilder/Scripts/RPGData/RPGGameModifier.cs | 9,144 | C# |
namespace CoreLayer.Citrix.Adc.NitroClient.Api.Configuration.NS.NsHttpProfile
{
public class NsHttpProfileRemoveResponse : NitroResponse
{
}
} | 23.428571 | 78 | 0.731707 | [
"Apache-2.0"
] | CoreLayer/CoreLayer.Citrix.Adc.Nitro | src/CoreLayer.Citrix.Adc.NitroClient/Api/Configuration/NS/NsHttpProfile/NsHttpProfileRemoveResponse.cs | 166 | C# |
using System;
using System.Collections.Generic;
namespace P02_DatabaseFirst.Data.Models
{
public partial class Department
{
public Department()
{
Employees = new HashSet<Employee>();
}
public int DepartmentId { get; set; }
public string Name { get; set; }
public int ManagerId { get; set; }
public Employee Manager { get; set; }
public ICollection<Employee> Employees { get; set; }
}
}
| 22.761905 | 60 | 0.600418 | [
"MIT"
] | AdemTsranchaliev/Databases-Advanced---Entity-Framework | Introduction to Entity Framework Core/Data/Models/Department.cs | 480 | C# |
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using SignalRChat.Models;
namespace SignalRChat
{
public class ChatHub : Hub
{
static List<Users> SignalRUsers = new List<Users>();
static HashSet<string> CurrentConnections = new HashSet<string>();
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
public override Task OnConnected()
{
var id = Context.ConnectionId;
CurrentConnections.Add(id);
return base.OnConnected();
}
//Saves the name of the connected user
public void Connect(string userName)
{
var id = Context.ConnectionId;
if (SignalRUsers.Count(x => x.ConnectionId == id) == 0)
{
SignalRUsers.Add(new Users { ConnectionId = id, UserName = userName });
}
}
public override System.Threading.Tasks.Task OnDisconnected()
{
var item = SignalRUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
if (item != null)
{
SignalRUsers.Remove(item);
}
return base.OnDisconnected();
}
//return list of all users that are connected
public List<string> GetAllActiveConnections()
{
HashSet<string> ConnectedUsers = new HashSet<string>();
foreach (Users user in SignalRUsers)
{
ConnectedUsers.Add(user.UserName);
}
return ConnectedUsers.ToList();
}
}
} | 27.742424 | 96 | 0.572365 | [
"Apache-2.0"
] | banfayomi2002/ChatApp | C#/SignalRChat/Hubs/ChatHub.cs | 1,833 | C# |
#define GUROBI
#if GUROBI
using Gurobi;
using Petri;
using System.Collections.Generic;
using System.Linq;
using Utils;
using System;
namespace HeuristicFrontier
{
public abstract class GurobiMarkingEquationFrontier : HeuristicFrontier<Marking>
{
private GRBModel model;
/// <summary>
/// Concrete implementations can set the domain to any of Gurobis domains, such as GRB.INTEGER or GRB.CONTINUOUS
/// </summary>
/// <returns>A char representing the chosen domain. See the Gurobi .NET API.</returns>
public abstract char getDomain();
private int iteration = 0;
PetriNet net;
private Dictionary<GRBVar, Marking> indicatorVarsToMarkings;
private Dictionary<Marking, GRBVar> markingsToIndicatorVars;
private GRBLinExpr[] leftHandSides;
private GRBLinExpr[] rightHandSides;
// store the combined lhs+rhs and remember their names/senses
private GRBConstr[] equations;
private String[] constrNames;
private char[] senses;
//
private GRBLinExpr sumOfIndicators;
private GRBConstr sumOfIndicatorsConstr;
private GRBLinExpr optimizationObjective;
public GurobiMarkingEquationFrontier(PetriNet net, List<MarkingWithConstraints> targetMarkings)
{
this.model = GurobiHeuristics.InitializeModel();
this.net = net;
// TODO: Handle multiple targets
MarkingWithConstraints targetMarking = targetMarkings.First();
// create transition vars
GRBVar[] transitionTimesFiredVars = GurobiHeuristics.CreateTransitionTimesFiredVars(net.Transitions, getDomain(), model);
leftHandSides = GurobiHeuristics.GeneratePlaceExprs(net, transitionTimesFiredVars);
rightHandSides = new GRBLinExpr[net.Places.Count];
equations = new GRBConstr[net.Places.Count];
constrNames = new String[net.Places.Count];
senses = new char[net.Places.Count];
for (int i = 0; i < net.Places.Count; i++)
{
Place place = net.Places[i];
GRBLinExpr rightHandSide = new GRBLinExpr(targetMarking.Marking.GetValueOrDefault(place, 0));
rightHandSides[i] = rightHandSide;
GRBLinExpr leftHandSide = leftHandSides[i];
char sense = targetMarking.Constraints.GetValueOrDefault(place, ConstraintOperators.GreaterEqual) == ConstraintOperators.GreaterEqual ?
GRB.GREATER_EQUAL : GRB.EQUAL;
String constrName = "markingEquationConstraint_" + place.Name.Truncate(200);
equations[i] = model.AddConstr(leftHandSide, sense, rightHandSide, constrName);
constrNames[i] = constrName;
senses[i] = sense;
}
indicatorVarsToMarkings = new Dictionary<GRBVar, Marking>();
markingsToIndicatorVars = new Dictionary<Marking, GRBVar>();
sumOfIndicators = new GRBLinExpr();
sumOfIndicatorsConstr = model.AddConstr(sumOfIndicators, '=', 1, "sumOfIndicatorsConstraint");
optimizationObjective = GurobiHeuristics.CreateVariableSumExpression(transitionTimesFiredVars);
model.SetObjective(optimizationObjective, GRB.MINIMIZE);
}
public override void Add(Marking node, float distanceFromStart)
{
GRBVar indicatorVar = model.AddVar(0, 1, 0, GRB.BINARY, "markingIndicatorVar_" + node.ToString().Truncate(200));
indicatorVarsToMarkings.Add(indicatorVar, node);
markingsToIndicatorVars.Add(node, indicatorVar);
sumOfIndicators.AddTerm(1, indicatorVar);
optimizationObjective.AddTerm(distanceFromStart, indicatorVar);
model.SetObjective(optimizationObjective);
model.Remove(sumOfIndicatorsConstr);
sumOfIndicatorsConstr = model.AddConstr(sumOfIndicators, '=', 1, "sumOfIndicatorsConstraint");
foreach (Place place in node.GetMarkedPlaces())
{
int index = net.Places.IndexOf(place);
int tokenCount = node[place];
GRBConstr constraint = equations[index];
model.Remove(equations[index]);
rightHandSides[index].AddTerm(-tokenCount, indicatorVar);
equations[index] = model.AddConstr(leftHandSides[index], senses[index], rightHandSides[index], constrNames[index]);
}
}
public override (double, Marking) PopMinNode()
{
model.Optimize();
// iteration++;
// model.Write("out" + iteration + ".lp");
// model.Write("out" + iteration + ".mps");
// model.Write("out" + iteration + ".sol");
// model.Write("out" + iteration + ".json");
if (model.Status != GRB.Status.OPTIMAL && model.Status != GRB.Status.SUBOPTIMAL)
{
return (0, null);
}
foreach ((GRBVar var, Marking marking) in indicatorVarsToMarkings)
{
double solutionValue = var.X;
if (solutionValue == 1)
{
model.Remove(var);
for (int i = 0; i < net.Places.Count; i++)
{
rightHandSides[i].Remove(var);
}
optimizationObjective.Remove(var);
sumOfIndicators.Remove(var);
indicatorVarsToMarkings.Remove(var);
markingsToIndicatorVars.Remove(marking);
return (model.ObjVal, marking);
}
}
throw new System.Exception("No indicator variable was set to 1 - this behaviour is unexpected!");
}
public override void UpdateNodeScore(Marking node, float newScore)
{
GRBVar var = markingsToIndicatorVars[node];
optimizationObjective.Remove(var);
optimizationObjective.AddTerm(newScore, var);
}
public override bool Contains(Marking node)
{
return markingsToIndicatorVars.ContainsKey(node);
}
}
public class GurobiMarkingEquationOverNFrontier : GurobiMarkingEquationFrontier
{
public GurobiMarkingEquationOverNFrontier(PetriNet net, List<MarkingWithConstraints> targetMarkings) : base(net, targetMarkings)
{ }
public override char getDomain()
{
return GRB.INTEGER;
}
}
public class GurobiMarkingEquationOverQFrontier : GurobiMarkingEquationFrontier
{
public GurobiMarkingEquationOverQFrontier(PetriNet net, List<MarkingWithConstraints> targetMarkings) : base(net, targetMarkings)
{ }
public override char getDomain()
{
return GRB.CONTINUOUS;
}
}
}
#endif | 34.039024 | 151 | 0.613213 | [
"MIT"
] | p-offtermatt/FastForward | artifact/src/Heuristics/HeuristicFrontier/GurobiFrontier.cs | 6,978 | C# |
//=============================================================================================================================
//
// Copyright (c) 2015-2017 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
// EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
// and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//=============================================================================================================================
namespace EasyAR
{
public class CameraDeviceBehaviour : CameraDeviceBaseBehaviour
{
}
}
| 48.333333 | 128 | 0.481379 | [
"Apache-2.0"
] | wuxutian/HuiBenTest | Assets/EasyAR/Scripts/CameraDeviceBehaviour.cs | 725 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 17.11.2018.
//
// <field_with_null>.AddSeconds(...)
//
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.DataTypes.Extensions;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.NullableDateTime.SET001.EXT.AddSeconds{
////////////////////////////////////////////////////////////////////////////////
//using
using T_DATA=System.Nullable<System.DateTime>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet___TIMESTAMP_with_null
public static class TestSet___TIMESTAMP_with_null
{
private const string c_NameOf__TABLE="TEST_MODIFY_ROW";
private const string c_NameOf__COL_DATA="COL_TIMESTAMP";
private const string c_NameOf__COL_INTEGER="COL_INTEGER";
//-----------------------------------------------------------------------
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA)]
public T_DATA DATA { get; set; }
[Column(c_NameOf__COL_INTEGER)]
public System.Int32? COL_INTEGER { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test___const___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(1)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___const___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___field___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db,2);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(r.COL_INTEGER)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA).IS_NULL().T(") OR (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___field___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___field___ByDBMS____2()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db,2);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(r.COL_INTEGER)==r.DATA.AddSeconds(r.COL_INTEGER) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((DATEADD(MILLISECOND,1000 * CAST(").N("t",c_NameOf__COL_INTEGER).T(" AS DOUBLE PRECISION),").N("t",c_NameOf__COL_DATA).T(") = DATEADD(MILLISECOND,1000 * CAST(").N("t",c_NameOf__COL_INTEGER).T(" AS DOUBLE PRECISION),").N("t",c_NameOf__COL_DATA).T(")) OR (((").N("t",c_NameOf__COL_DATA).IS_NULL().T(") OR (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(")) AND ((").N("t",c_NameOf__COL_DATA).IS_NULL().T(") OR (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(")))) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___field___ByDBMS____2
//-----------------------------------------------------------------------
[Test]
public static void Test___param___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
int vv=3;
var recs=db.testTable.Where(r => r.DATA.AddSeconds(vv)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___param___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___paramNint___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
int? vv=null;
var recs=db.testTable.Where(r => r.DATA.AddSeconds(vv)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_1");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___paramNint___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___paramNdouble___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
double? vv=null;
var recs=db.testTable.Where(r => r.DATA.AddSeconds(vv)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_1");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___paramNdouble___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr1___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
string str="1234";
var recs=db.testTable.Where(r => r.DATA.AddSeconds(str.Length)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr1___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr1a___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
string str="1234";
var recs=db.testTable.Where(r => r.DATA.AddSeconds(str.Length+0.5)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA).IS_NULL().T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr1a___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr2___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
string str=null;
var recs=db.testTable.Where(r => r.DATA.AddSeconds(str.Length)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_1");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr2___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr2a___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
string str=null;
var recs=db.testTable.Where(r => r.DATA.AddSeconds(str.Length+0.5)==null && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ").N("t","TEST_ID").T(" = ").P_ID("__testID_1");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr2a___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr4___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db,1);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(r.COL_INTEGER)==r.DATA.AddSeconds(2) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((DATEADD(MILLISECOND,1000 * CAST(").N("t",c_NameOf__COL_INTEGER).T(" AS DOUBLE PRECISION),").N("t",c_NameOf__COL_DATA).T(") = DATEADD(MILLISECOND,1000 * 2.0,").N("t",c_NameOf__COL_DATA).T(")) OR (((").N("t",c_NameOf__COL_DATA).IS_NULL().T(") OR (").N("t",c_NameOf__COL_INTEGER).IS_NULL().T(")) AND (").N("t",c_NameOf__COL_DATA).IS_NULL().T("))) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr4___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr6___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db,1);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(r.COL_INTEGER)==r.DATA.AddSeconds(2).Value && r.TEST_ID==testID);
try
{
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
TestServices.ThrowWeWaitError();
}
catch(xdb.OleDbException exc)
{
CheckErrors.PrintException_OK(exc);
Assert.AreEqual
(3,
TestUtils.GetRecordCount(exc));
CheckErrors.CheckOleDbError__Firebird__TRAP_FOR_NULL
(exc.Errors[0]);
}//catch
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (DATEADD(MILLISECOND,1000 * CAST(").N("t",c_NameOf__COL_INTEGER).T(" AS DOUBLE PRECISION),").N("t",c_NameOf__COL_DATA).T(") = COALESCE(DATEADD(MILLISECOND,1000 * 2.0,").N("t",c_NameOf__COL_DATA).T("), CAST(_utf8 'TRAP FOR NULL' AS TIMESTAMP))) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr6___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr8___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
var recs=db.testTable.Where(r => r.DATA.AddSeconds(1)==r.DATA.AddSeconds(1) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((DATEADD(MILLISECOND,1000 * 1.0,").N("t",c_NameOf__COL_DATA).T(") = DATEADD(MILLISECOND,1000 * 1.0,").N("t",c_NameOf__COL_DATA).T(")) OR (").N("t",c_NameOf__COL_DATA).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr8___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr9___ByDBMS()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
System.Int64? testID=Helper__InsertRow(db);
var recs=db.testTable.Where(r => r.DATA==r.DATA.AddSeconds(1) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.IsNull
(r.DATA);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA).T(" = DATEADD(MILLISECOND,1000 * 1.0,").N("t",c_NameOf__COL_DATA).T(")) OR (").N("t",c_NameOf__COL_DATA).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test___expr9___ByDBMS
//-----------------------------------------------------------------------
[Test]
public static void Test___expr10___ByEF()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
TestServices.UnsupportedSQL__DataTypeUnknown
(tr,
new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_INTEGER).T(", ").N("t",c_NameOf__COL_DATA).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE DATEADD(MILLISECOND,1000*CAST(").P("__Exec_0").T(" + ").N("t",c_NameOf__COL_INTEGER).T(" AS DOUBLE PRECISION),").N("t",c_NameOf__COL_DATA).T(")").IS_NULL().T(" AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")
.BuildSql(cn));
tr.Rollback();
}//using tr
}//using cn
}//Test___expr10___ByEF
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db)
{
var newRecord=new MyContext.TEST_RECORD();
db.testTable.Add(newRecord);
db.SaveChanges();
var sqlt
=new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_INTEGER).T(", ").N(c_NameOf__COL_DATA).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
System.Int32 valueOfColInteger)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_INTEGER=valueOfColInteger;
db.testTable.Add(newRecord);
db.SaveChanges();
var sqlt
=new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_INTEGER).T(", ").N(c_NameOf__COL_DATA).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet___TIMESTAMP_with_null
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Funcs.NullableDateTime.SET001.EXT.AddSeconds
| 25.32319 | 535 | 0.548875 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Funcs/NullableDateTime/SET001/EXT/AddSeconds/TestSet___TIMESTAMP_with_null.cs | 24,135 | C# |
using System;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BCM.WebFormsApplication {
public partial class Integer_EditField : System.Web.DynamicData.FieldTemplateUserControl {
protected void Page_Load(object sender, EventArgs e) {
TextBox1.ToolTip = Column.Description;
SetUpValidator(RequiredFieldValidator1);
SetUpValidator(CompareValidator1);
SetUpValidator(RegularExpressionValidator1);
SetUpValidator(RangeValidator1);
SetUpValidator(DynamicValidator1);
}
protected override void ExtractValues(IOrderedDictionary dictionary) {
dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
}
public override Control DataControl {
get {
return TextBox1;
}
}
}
}
| 32.090909 | 95 | 0.644004 | [
"MIT"
] | chstorb/BookCollectionManager | src/BCM.WebFormsApplication/DynamicData/FieldTemplates/Integer_Edit.ascx.cs | 1,059 | C# |
using System.Collections.Generic;
using UnityEngine;
public class ItemSlotGroup : MonoBehaviour
{
public ItemData.Type type;
public Inventory inventory;
public EquipPanel equipPanel;
private List<ItemSlot> _itemSlots;
private int equippedCount;
private void Start()
{
_itemSlots = new List<ItemSlot>(GetComponentsInChildren<ItemSlot>());
}
public bool Equip(Item item)
{
if (equippedCount >= _itemSlots.Count) return false;
for (int i = 0; i < _itemSlots.Count; i++)
{
ItemSlot slot = _itemSlots[i];
if (slot.occupied) continue;
slot.Equip(item);
equippedCount++;
inventory.Equip(item);
equipPanel.UpdateStash();
return true;
}
return false;
}
public void Unequip(Item item)
{
if (equippedCount <= 0) return;
equippedCount--;
inventory.Unequip(item);
equipPanel.UpdateStash();
}
}
| 21.680851 | 77 | 0.587831 | [
"MIT"
] | DeusIntra/Snowball-Fight | Assets/Scripts/UI/Equip/ItemSlotGroup.cs | 1,019 | C# |
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.UnionPay.Notify
{
public class UnionPayForm_6_2_FrontConsumeNotifyResponse : UnionPayNotifyResponse
{
/// <summary>
/// 查询流水号
/// </summary>
[JsonProperty("queryId")]
public string QueryId { get; set; }
/// <summary>
/// 交易币种
/// </summary>
[JsonProperty("currencyCode")]
public string CurrencyCode { get; set; }
/// <summary>
/// 交易传输时间
/// </summary>
[JsonProperty("traceTime")]
public string TraceTime { get; set; }
/// <summary>
/// 签名
/// </summary>
[JsonProperty("signature")]
public string Signature { get; set; }
/// <summary>
/// 签名方法
/// </summary>
[JsonProperty("signMethod")]
public string SignMethod { get; set; }
/// <summary>
/// 清算币种
/// </summary>
[JsonProperty("settleCurrencyCode")]
public string SettleCurrencyCode { get; set; }
/// <summary>
/// 清算金额
/// </summary>
[JsonProperty("settleAmt")]
public string SettleAmt { get; set; }
/// <summary>
/// 清算日期
/// </summary>
[JsonProperty("settleDate")]
public string SettleDate { get; set; }
/// <summary>
/// 系统跟踪号
/// </summary>
[JsonProperty("traceNo")]
public string TraceNo { get; set; }
/// <summary>
/// 应答码
/// </summary>
[JsonProperty("respCode")]
public string RespCode { get; set; }
/// <summary>
/// 应答信息
/// </summary>
[JsonProperty("respMsg")]
public string RespMsg { get; set; }
/// <summary>
/// 兑换日期
/// </summary>
[JsonProperty("exchangeDate")]
public string ExchangeDate { get; set; }
/// <summary>
/// 签名公钥证书
/// </summary>
[JsonProperty("signPubKeyCert")]
public string SignPubKeyCert { get; set; }
/// <summary>
/// 清算汇率
/// </summary>
[JsonProperty("exchangeRate")]
public string ExchangeRate { get; set; }
/// <summary>
/// 账号
/// </summary>
[JsonProperty("accNo")]
public string AccNo { get; set; }
/// <summary>
/// 支付方式
/// </summary>
[JsonProperty("payType")]
public string PayType { get; set; }
/// <summary>
/// 支付卡标识
/// </summary>
[JsonProperty("payCardNo")]
public string PayCardNo { get; set; }
/// <summary>
/// 支付卡类型
/// </summary>
[JsonProperty("payCardType")]
public string PayCardType { get; set; }
/// <summary>
/// 支付卡名称
/// </summary>
[JsonProperty("payCardIssueName")]
public string PayCardIssueName { get; set; }
/// <summary>
/// 版本号
/// </summary>
[JsonProperty("version")]
public string Version { get; set; }
/// <summary>
/// 绑定标识号
/// </summary>
[JsonProperty("bindId")]
public string BindId { get; set; }
/// <summary>
/// 编码方式
/// </summary>
[JsonProperty("encoding")]
public string Encoding { get; set; }
/// <summary>
/// 产品类型
/// </summary>
[JsonProperty("bizType")]
public string BizType { get; set; }
/// <summary>
/// 订单发送时间
/// </summary>
[JsonProperty("txnTime")]
public string TxnTime { get; set; }
/// <summary>
/// 交易金额
/// </summary>
[JsonProperty("txnAmt")]
public string TxnAmt { get; set; }
/// <summary>
/// 交易类型
/// </summary>
[JsonProperty("txnType")]
public string TxnType { get; set; }
/// <summary>
/// 交易子类
/// </summary>
[JsonProperty("txnSubType")]
public string TxnSubType { get; set; }
/// <summary>
/// 接入类型
/// </summary>
[JsonProperty("accessType")]
public string AccessType { get; set; }
/// <summary>
/// 请求方保留域
/// </summary>
[JsonProperty("reqReserved")]
public string ReqReserved { get; set; }
/// <summary>
/// 商户代码
/// </summary>
[JsonProperty("merId")]
public string MerId { get; set; }
/// <summary>
/// 商户订单号
/// </summary>
[JsonProperty("orderId")]
public string OrderId { get; set; }
/// <summary>
/// 保留域
/// </summary>
[JsonProperty("reserved")]
public string Reserved { get; set; }
/// <summary>
/// 分账域
/// </summary>
[JsonProperty("accSplitData")]
public string AccSplitData { get; set; }
}
}
| 24.199029 | 85 | 0.469609 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.UnionPay/Notify/UnionPayForm_6_2_FrontConsumeNotifyResponse.cs | 5,265 | C# |
using System;
namespace _06._Wedding_Seats
{
class Program
{
static void Main(string[] args)
{
char lastSector = char.Parse(Console.ReadLine());
int rowsFirstSector = int.Parse(Console.ReadLine());
int oddRowCount = int.Parse(Console.ReadLine());
int counter = 0;
for (char a = 'A'; a <= lastSector; a++)
{
if (a > 'A')
{
rowsFirstSector++;
}
for (int b = 1; b <= rowsFirstSector; b++)
{
if (b % 2 != 0)
{
for (char c = 'a'; c < 'a' + oddRowCount; c++)
{
Console.WriteLine($"{a}{b}{c}");
counter++;
}
}
else
for (char c = 'a'; c < 'a' + oddRowCount + 2; c++)
{
Console.WriteLine($"{a}{b}{c}");
counter++;
}
}
}
Console.WriteLine(counter);
}
}
}
| 29.809524 | 74 | 0.316294 | [
"MIT"
] | GeorgiGradev/SoftUni | 01. Programming Basics/07.3. MORE - Nested Loops/06. Wedding Seats/Program.cs | 1,254 | C# |
// EarleCode
// Copyright 2016 Tim Potze
//
// 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.
namespace EarleCode.Runtime.Events
{
/// <summary>
/// Indicates this instance has an <see cref="IEarleEventManager" />
/// </summary>
public interface IEarleEventableObject : IEarleObject
{
/// <summary>
/// Gets the event manager.
/// </summary>
IEarleEventManager EventManager { get; }
}
} | 35.25 | 77 | 0.66464 | [
"Apache-2.0"
] | ikkentim/earlescript | src/EarleCode/Runtime/Events/IEarleEventableObject.cs | 989 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="">
//
// </copyright>
// <summary>
// AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Reflection;
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("ZKosior.TreeBuilder.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ZKosior.TreeBuilder.Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c36da09f-8e3a-4819-8ff6-aab36532e99c")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 41.780488 | 120 | 0.636894 | [
"MIT"
] | zkosior/KTreeBuilder | ZKosior.TreeBuilder.Test/Properties/AssemblyInfo.cs | 1,716 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.OWC10Api
{
/// <summary>
/// DispatchInterface PivotHyperlink
/// SupportByVersion OWC10, 1
/// </summary>
[SupportByVersion("OWC10", 1)]
[EntityType(EntityType.IsDispatchInterface)]
[TypeId("F5B39A9C-1480-11D3-8549-00C04FAC67D7")]
public interface PivotHyperlink : ICOMObject
{
#region Properties
/// <summary>
/// SupportByVersion OWC10 1
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("OWC10", 1), ProxyResult]
object Parent { get; }
/// <summary>
/// SupportByVersion OWC10 1
/// Get/Set
/// </summary>
[SupportByVersion("OWC10", 1)]
string Address { get; set; }
/// <summary>
/// SupportByVersion OWC10 1
/// Get/Set
/// </summary>
[SupportByVersion("OWC10", 1)]
string Name { get; set; }
/// <summary>
/// SupportByVersion OWC10 1
/// Get/Set
/// </summary>
[SupportByVersion("OWC10", 1)]
string SubAddress { get; set; }
#endregion
#region Methods
/// <summary>
/// SupportByVersion OWC10 1
/// </summary>
[SupportByVersion("OWC10", 1)]
void Delete();
/// <summary>
/// SupportByVersion OWC10 1
/// </summary>
/// <param name="newWindow">optional bool NewWindow = false</param>
[SupportByVersion("OWC10", 1)]
void Follow(object newWindow);
/// <summary>
/// SupportByVersion OWC10 1
/// </summary>
[CustomMethod]
[SupportByVersion("OWC10", 1)]
void Follow();
#endregion
}
}
| 20.466667 | 69 | 0.64886 | [
"MIT"
] | igoreksiz/NetOffice | Source/OWC10/DispatchInterfaces/PivotHyperlink.cs | 1,537 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net.Http;
using System.Web.Http.Hosting;
namespace System.Web.Http.WebHost.Routing
{
internal class HttpRequestMessageWrapper : HttpRequestBase
{
private readonly string _virtualPathRoot;
private readonly HttpRequestMessage _httpRequest;
public HttpRequestMessageWrapper(string virtualPathRoot, HttpRequestMessage httpRequest)
{
if (virtualPathRoot == null)
{
throw Http.Error.ArgumentNull("virtualPathRoot");
}
if (httpRequest == null)
{
throw Http.Error.ArgumentNull("httpRequest");
}
_virtualPathRoot = virtualPathRoot;
_httpRequest = httpRequest;
}
public override string ApplicationPath
{
get { return _virtualPathRoot; }
}
public override string AppRelativeCurrentExecutionFilePath
{
get
{
string absolutePath = _httpRequest.RequestUri.AbsolutePath;
if (absolutePath.StartsWith(_virtualPathRoot, StringComparison.OrdinalIgnoreCase))
{
string relativePath = _virtualPathRoot.Length == 1 ? absolutePath : absolutePath.Substring(_virtualPathRoot.Length);
return "~" + relativePath.TrimEnd('/');
}
return null;
}
}
public override string CurrentExecutionFilePath
{
get { return FilePath; }
}
public override string FilePath
{
get
{
string absolutePath = _httpRequest.RequestUri.AbsolutePath;
if (absolutePath.StartsWith(_virtualPathRoot, StringComparison.OrdinalIgnoreCase))
{
return absolutePath.TrimEnd('/');
}
return null;
}
}
public override string HttpMethod
{
get { return _httpRequest.Method.ToString(); }
}
public override bool IsLocal
{
get { return _httpRequest.IsLocal(); }
}
public override string Path
{
get
{
return _httpRequest.RequestUri.AbsolutePath;
}
}
public override string PathInfo
{
get { return String.Empty; }
}
public override NameValueCollection QueryString
{
get { return _httpRequest.RequestUri.ParseQueryString(); }
}
public override string RawUrl
{
get { return _httpRequest.RequestUri.PathAndQuery; }
}
public override string RequestType
{
get { return _httpRequest.Method.ToString(); }
}
public override Uri Url
{
get { return _httpRequest.RequestUri; }
}
}
}
| 28.133929 | 136 | 0.561092 | [
"Apache-2.0"
] | akornich/aspnetwebstack | src/System.Web.Http.WebHost/Routing/HttpRequestMessageWrapper.cs | 3,153 | C# |
using Discord.Commands;
using System.Text;
using System.Threading.Tasks;
using static DiscordScriptBot.Script.ScriptInterface;
namespace DiscordScriptBot.Command
{
[Group("interface")]
public class ListInterfaceCommands : ModuleBase<CommandManager.CommandContext>
{
[Group("describe")]
public class Describe : ModuleBase<CommandManager.CommandContext>
{
[RequireOwner]
[Command("event")]
public async Task ShowEvent(string name = null)
{
if (name == null)
{
// If no name provided, show all events
await ShowAll(Context.ScriptInterface.GetEvents());
return;
}
var @event = Context.ScriptInterface.GetEvent(name);
if (@event != null)
await ReplyAsync(GetInterfaceString(@event, "Event"));
else
await Context.Reply(nameof(ShowEvent), $"No event found for '{name}'.");
}
[RequireOwner]
[Command("object")]
public async Task ShowObject(string name = null)
{
if (name == null)
{
// If no name provided, show all objects/wrappers
await ShowAll(Context.ScriptInterface.GetWrappers());
return;
}
var wrapper = Context.ScriptInterface.GetWrapper(name);
if (wrapper != null)
await ReplyAsync(GetInterfaceString(wrapper, "Object"));
else
await Context.Reply(nameof(ShowObject), $"No object found for '{name}'.");
}
private async Task ShowAll(IWrapperInfo[] wrappers)
{
var b = new StringBuilder();
b.AppendLine("```");
foreach (IWrapperInfo w in wrappers)
b.AppendLine($"{w.Name}: {w.Description}");
b.AppendLine("```");
await ReplyAsync(b.ToString());
}
}
}
}
| 35.693548 | 95 | 0.491188 | [
"MIT"
] | ariddl/scriptbot | src/Command/ListInterfaceCommands.cs | 2,215 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace ProtoBase.Wpf.ValueConverters
{
public class BooleanToInvertedVisibilityValueConverter : IValueConverter
{
#region Public Methods
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value as bool? ?? false ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value as Visibility? != Visibility.Visible;
}
#endregion
}
}
| 26.96 | 103 | 0.68546 | [
"MIT"
] | elipriaulx/ProtoBase | ProtoBase.Wpf/ValueConverters/BooleanToInvertedVisibilityValueConverter.cs | 676 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ApolloInterop.Interfaces;
using ApolloInterop.Structs;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Collections.Concurrent;
using ApolloInterop.Structs.ApolloStructs;
using ApolloInterop.Types.Delegates;
using ApolloInterop.Classes.Core;
namespace ApolloInterop.Classes
{
public abstract class C2Profile
{
protected const int MAX_RETRIES = 10;
protected ISerializer Serializer;
protected IAgent Agent;
protected bool Connected = false;
protected ConcurrentDictionary<string, ChunkedMessageStore<IPCChunkedData>> MessageStore = new ConcurrentDictionary<string, ChunkedMessageStore<IPCChunkedData>>();
public C2Profile(Dictionary<string, string> parameters, ISerializer serializer, IAgent agent)
{
Agent = agent;
Serializer = serializer;
}
}
}
| 32.066667 | 171 | 0.745322 | [
"BSD-3-Clause"
] | getshellz/Apollo | Payload_Type/apollo/agent_code/ApolloInterop/Classes/Core/C2Profile.cs | 964 | 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("2.BonusScore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2.BonusScore")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c28311c6-5cb0-4897-a40b-b91677b6e327")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.743737 | [
"MIT"
] | KaloyanMarshalov/Telerik-Academy-Homeworks | Module One - Programming/CSharp Part One/5.Conditional-Statements/2.BonusScore/Properties/AssemblyInfo.cs | 1,400 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class MethodDeclarationOrganizer : AbstractSyntaxNodeOrganizer<MethodDeclarationSyntax>
{
protected override MethodDeclarationSyntax Organize(
MethodDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
attributeLists: syntax.AttributeLists,
modifiers: ModifiersOrganizer.Organize(syntax.Modifiers),
returnType: syntax.ReturnType,
explicitInterfaceSpecifier: syntax.ExplicitInterfaceSpecifier,
identifier: syntax.Identifier,
typeParameterList: syntax.TypeParameterList,
parameterList: syntax.ParameterList,
constraintClauses: syntax.ConstraintClauses,
body: syntax.Body,
expressionBody: syntax.ExpressionBody,
semicolonToken: syntax.SemicolonToken);
}
}
}
| 43.1875 | 161 | 0.696093 | [
"Apache-2.0"
] | AdamSpeight2008/roslyn-1 | src/Features/CSharp/Portable/Organizing/Organizers/MethodDeclarationOrganizer.cs | 1,384 | C# |
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Linq.Search;
using Lucene.Net.Linq.Util;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Version = Lucene.Net.Util.Version;
namespace Lucene.Net.Linq.Mapping
{
public class ReflectionFieldMapper<T> : IFieldMapper<T>, IDocumentFieldConverter
{
protected readonly PropertyInfo propertyInfo;
protected readonly StoreMode store;
protected readonly IndexMode index;
protected readonly TermVectorMode termVector;
protected readonly TypeConverter converter;
protected readonly string fieldName;
protected readonly QueryParser.Operator defaultParserOperator;
protected readonly bool caseSensitive;
protected readonly Analyzer analyzer;
protected readonly float boost;
protected readonly bool nativeSort;
public ReflectionFieldMapper(PropertyInfo propertyInfo, StoreMode store, IndexMode index, TermVectorMode termVector,
TypeConverter converter, string fieldName, bool caseSensitive, Analyzer analyzer)
: this(propertyInfo, store, index, termVector, converter, fieldName, caseSensitive, analyzer, 1f)
{
}
public ReflectionFieldMapper(PropertyInfo propertyInfo, StoreMode store, IndexMode index, TermVectorMode termVector, TypeConverter converter, string fieldName, bool caseSensitive, Analyzer analyzer, float boost)
: this(propertyInfo, store, index, termVector, converter, fieldName, QueryParser.Operator.OR, caseSensitive, analyzer, boost)
{
}
public ReflectionFieldMapper(PropertyInfo propertyInfo, StoreMode store, IndexMode index, TermVectorMode termVector, TypeConverter converter, string fieldName, QueryParser.Operator defaultParserOperator, bool caseSensitive, Analyzer analyzer, float boost, bool nativeSort = false)
{
this.propertyInfo = propertyInfo;
this.store = store;
this.index = index;
this.termVector = termVector;
this.converter = converter;
this.fieldName = fieldName;
this.defaultParserOperator = defaultParserOperator;
this.caseSensitive = caseSensitive;
this.analyzer = analyzer;
this.boost = boost;
this.nativeSort = nativeSort;
}
public virtual Analyzer Analyzer
{
get
{
return analyzer;
}
}
public virtual PropertyInfo PropertyInfo
{
get
{
return propertyInfo;
}
}
public virtual StoreMode Store
{
get
{
return store;
}
}
public virtual IndexMode IndexMode
{
get
{
return index;
}
}
public virtual TermVectorMode TermVector
{
get
{
return termVector;
}
}
public virtual TypeConverter Converter
{
get
{
return converter;
}
}
public virtual string FieldName
{
get
{
return fieldName;
}
}
public virtual bool CaseSensitive
{
get
{
return caseSensitive;
}
}
public virtual float Boost
{
get
{
return boost;
}
}
public virtual string PropertyName
{
get
{
return propertyInfo.Name;
}
}
public virtual QueryParser.Operator DefaultParseOperator
{
get
{
return defaultParserOperator;
}
}
public virtual bool NativeSort
{
get { return nativeSort; }
}
public virtual object GetPropertyValue(T source)
{
return propertyInfo.GetValue(source, null);
}
public virtual void CopyFromDocument(Document source, IQueryExecutionContext context, T target)
{
if (!propertyInfo.CanWrite) return;
var fieldValue = GetFieldValue(source);
propertyInfo.SetValue(target, fieldValue, null);
}
public object GetFieldValue(Document document)
{
var field = document.GetFieldable(fieldName);
if (field == null)
return null;
if (!propertyInfo.CanWrite)
return null;
return ConvertFieldValue(field);
}
public virtual void CopyToDocument(T source, Document target)
{
var value = propertyInfo.GetValue(source, null);
target.RemoveFields(fieldName);
AddField(target, value);
}
public virtual string ConvertToQueryExpression(object value)
{
if (converter != null)
{
return (string)converter.ConvertTo(value, typeof(string));
}
return (string)value;
}
public virtual string EscapeSpecialCharacters(string value)
{
return QueryParser.Escape(value ?? string.Empty);
}
public virtual Query CreateQuery(string pattern)
{
Query query;
if (TryParseKeywordContainingWhitespace(pattern, out query))
{
return query;
}
var queryParser = new QueryParser(Version.LUCENE_30, FieldName, analyzer)
{
AllowLeadingWildcard = true,
LowercaseExpandedTerms = !CaseSensitive,
DefaultOperator = defaultParserOperator
};
return queryParser.Parse(pattern);
}
/// <summary>
/// Attempt to determine if a given query pattern contains whitespace and
/// the analyzer does not tokenize on whitespace. This is a work-around
/// for cases when QueryParser would split a keyword that contains whitespace
/// into multiple tokens.
/// </summary>
protected virtual bool TryParseKeywordContainingWhitespace(string pattern, out Query query)
{
query = null;
if (pattern.IndexOfAny(new[] { ' ', '\t', '\r', '\n' }) < 0) return false;
var terms = Analyzer.GetTerms(FieldName, pattern).ToList();
if (terms.Count > 1) return false;
var termValue = Unescape(terms.Single());
var term = new Term(FieldName, termValue);
if (IsWildcardPattern(termValue))
{
query = new WildcardQuery(term);
}
else
{
query = new TermQuery(term);
}
return true;
}
/// <summary>
/// Determine if a (potentially escaped) pattern contains
/// any non-escaped wildcard characters such as <c>*</c> or <c>?</c>.
/// </summary>
protected virtual bool IsWildcardPattern(string pattern)
{
var unescaped = pattern.Replace(@"\\", "");
return unescaped.Replace(@"\*", "").Contains("*")
|| unescaped.Replace(@"\?", "").Contains("?");
}
/// <summary>
/// Remove escape characters from a pattern. This method
/// is called when a <see cref="Query"/> is being created without using
/// <see cref="QueryParser.Parse"/>.
/// </summary>
protected virtual string Unescape(string pattern)
{
return pattern.Replace(@"\", "");
}
public virtual Query CreateRangeQuery(object lowerBound, object upperBound, RangeType lowerRange, RangeType upperRange)
{
var minInclusive = lowerRange == RangeType.Inclusive;
var maxInclusive = upperRange == RangeType.Inclusive;
var lowerBoundStr = lowerBound == null ? null : EvaluateExpressionToStringAndAnalyze(lowerBound);
var upperBoundStr = upperBound == null ? null : EvaluateExpressionToStringAndAnalyze(upperBound);
return new TermRangeQuery(FieldName, lowerBoundStr, upperBoundStr, minInclusive, maxInclusive);
}
public virtual SortField CreateSortField(bool reverse)
{
if (Converter == null || NativeSort)
return new SortField(FieldName, SortField.STRING, reverse);
var propertyType = propertyInfo.PropertyType;
FieldComparatorSource source;
if (typeof(IComparable).IsAssignableFrom(propertyType))
{
source = new NonGenericConvertableFieldComparatorSource(propertyType, Converter);
}
else if (typeof(IComparable<>).MakeGenericType(propertyType).IsAssignableFrom(propertyType))
{
source = new GenericConvertableFieldComparatorSource(propertyType, Converter);
}
else
{
throw new NotSupportedException(string.Format("The type {0} does not implement IComparable or IComparable<T>. To use alphanumeric sorting, specify NativeSort=true on the mapping.",
propertyType));
}
return new SortField(FieldName, source, reverse);
}
private string EvaluateExpressionToStringAndAnalyze(object value)
{
return analyzer.Analyze(FieldName, ConvertToQueryExpression(value));
}
protected internal virtual object ConvertFieldValue(IFieldable field)
{
var fieldValue = (object)field.StringValue;
if (converter != null)
{
fieldValue = converter.ConvertFrom(fieldValue);
}
return fieldValue;
}
protected internal void AddField(Document target, object value)
{
if (value == null)
return;
var fieldValue = (string)null;
if (converter != null)
{
fieldValue = (string)converter.ConvertTo(value, typeof(string));
}
else if (value is string)
{
fieldValue = (string)value;
}
if (fieldValue != null)
{
var field = new Field(fieldName, fieldValue, FieldStore, (Field.Index)index, (Field.TermVector)TermVector);
field.Boost = Boost;
target.Add(field);
}
}
protected Field.Store FieldStore
{
get
{
return (Field.Store)store;
}
}
}
} | 31.943978 | 289 | 0.546387 | [
"Apache-2.0"
] | tamasflamich/Lucene.Net.Linq | source/Lucene.Net.Linq/Mapping/ReflectionFieldMapper.cs | 11,406 | C# |
using UnityEngine;
using System.Collections;
namespace CurvedUI {
/// <summary>
/// This script switches the hand controlling the UI when a click on the other controller's trigger is detected.
/// This emulates the functionality seen in SteamVR overlay or Oculus Home.
/// Works both for SteamVR and Oculus SDK.
/// </summary>
public class CurvedUIHandSwitcher : MonoBehaviour
{
#pragma warning disable 0649
#pragma warning disable 414
[SerializeField]
GameObject LaserBeam;
[SerializeField]
[Tooltip("If true, when player clicks the trigger on the other hand, we'll instantly set it as UI controlling hand and move the pointer to it.")]
bool autoSwitchHands = true;
#pragma warning restore 414
#pragma warning restore 0649
#if CURVEDUI_OCULUSVR
//variables
OVRInput.Controller activeCont;
bool initialized = false;
void Update()
{
if (CurvedUIInputModule.ControlMethod != CurvedUIInputModule.CUIControlMethod.OCULUSVR) return;
activeCont = OVRInput.GetActiveController();
if (!initialized && CurvedUIInputModule.Instance.OculusTouchUsedControllerTransform != null)
{
//Launch Hand Switch. This will place the laser pointer in the current hand.
SwitchHandTo(CurvedUIInputModule.Instance.UsedHand);
initialized = true;
}
//for Oculus Go and GearVR, switch automatically if a different controller is connected.
//This covers the case where User changes hand setting in Oculus Go menu and gets back to our app.
if (activeCont == OVRInput.Controller.LTrackedRemote && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Left)
SwitchHandTo(CurvedUIInputModule.Hand.Left);
else if (activeCont == OVRInput.Controller.RTrackedRemote && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Right)
SwitchHandTo(CurvedUIInputModule.Hand.Right);
if(autoSwitchHands){
//For Oculus Rift, we wait for the click before we change the pointer.
if (IsButtonDownOnController(OVRInput.Controller.LTouch) && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Left)
{
SwitchHandTo(CurvedUIInputModule.Hand.Left);
}
else if (IsButtonDownOnController(OVRInput.Controller.RTouch) && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Right)
{
SwitchHandTo(CurvedUIInputModule.Hand.Right);
}
}
}
bool IsButtonDownOnController(OVRInput.Controller cont, OVRInput.Controller cont2 = OVRInput.Controller.None)
{
return OVRInput.GetDown(CurvedUIInputModule.Instance.OculusTouchInteractionButton, cont) || (cont2 != OVRInput.Controller.None && OVRInput.GetDown(CurvedUIInputModule.Instance.OculusTouchInteractionButton, cont2));
}
#elif CURVEDUI_STEAMVR_LEGACY
void Start()
{
//connect to steamVR's OnModelLoaded events so we can update the pointer the moment controller is detected.
CurvedUIInputModule.Right.ModelLoaded += OnModelLoaded;
CurvedUIInputModule.Left.ModelLoaded += OnModelLoaded;
}
void OnModelLoaded(object sender)
{
SwitchHandTo(CurvedUIInputModule.Instance.UsedHand);
}
void Update()
{
if (CurvedUIInputModule.ControlMethod != CurvedUIInputModule.CUIControlMethod.STEAMVR_LEGACY) return;
if(autoSwitchHands){
if (CurvedUIInputModule.Right != null && CurvedUIInputModule.Right.IsTriggerDown && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Right)
{
SwitchHandTo(CurvedUIInputModule.Hand.Right);
}
else if (CurvedUIInputModule.Left != null && CurvedUIInputModule.Left.IsTriggerDown && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Left)
{
SwitchHandTo(CurvedUIInputModule.Hand.Left);
}
}
}
#elif CURVEDUI_STEAMVR_2
void Start()
{
//initial setup in proper hand
SwitchHandTo(CurvedUIInputModule.Instance.UsedHand);
}
void Update()
{
if (CurvedUIInputModule.ControlMethod != CurvedUIInputModule.CUIControlMethod.STEAMVR_2) return;
//Switch hands during runtime when user clicks the action button on another controller
if (autoSwitchHands && CurvedUIInputModule.Instance.SteamVRClickAction != null)
{
if (CurvedUIInputModule.Instance.SteamVRClickAction.GetState(Valve.VR.SteamVR_Input_Sources.RightHand) && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Right){
SwitchHandTo(CurvedUIInputModule.Hand.Right);
}
else if (CurvedUIInputModule.Instance.SteamVRClickAction.GetState(Valve.VR.SteamVR_Input_Sources.LeftHand) && CurvedUIInputModule.Instance.UsedHand != CurvedUIInputModule.Hand.Left ){
SwitchHandTo(CurvedUIInputModule.Hand.Left);
}
}
}
#endif
#region HELPER FUNCTIONS
void SwitchHandTo(CurvedUIInputModule.Hand newHand)
{
CurvedUIInputModule.Instance.UsedHand = newHand;
if (CurvedUIInputModule.Instance.ControllerTransform)
{
LaserBeam.transform.SetParent(CurvedUIInputModule.Instance.ControllerTransform);
LaserBeam.transform.ResetTransform();
LaserBeam.transform.LookAt(LaserBeam.transform.position + CurvedUIInputModule.Instance.ControllerPointingDirection);
}
else Debug.LogError("CURVEDUI: No Active controller that can be used as a parent of the pointer. Is the controller gameobject present on the scene and active?");
}
#endregion
}
}
| 41.181818 | 227 | 0.640019 | [
"Apache-2.0"
] | korgan00/Interaqtive-learning | Interaqtive-learning/Assets/CurvedUI/Scripts/CurvedUIHandSwitcher.cs | 6,344 | C# |
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class APIKey {
/// <summary>
/// Gets or Sets AccessKey
/// </summary>
[DataMember(Name="access_key", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "access_key")]
public string AccessKey { get; set; }
/// <summary>
/// Gets or Sets ExpireAt
/// </summary>
[DataMember(Name="expire_at", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "expire_at")]
public string ExpireAt { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class APIKey {\n");
sb.Append(" AccessKey: ").Append(AccessKey).Append("\n");
sb.Append(" ExpireAt: ").Append(ExpireAt).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
| 26.698113 | 68 | 0.636749 | [
"MIT"
] | 1042star/upbit-client | swg_generated/csharp/csharp-dotnet2/src/main/CsharpDotNet2/IO/Swagger/Model/APIKey.cs | 1,415 | C# |
using System.Collections.Generic;
using NBitcoin;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Tests.Common;
using Xunit;
namespace Stratis.Bitcoin.Tests.Consensus
{
public class CheckPointsTest
{
private readonly Network network;
public CheckPointsTest()
{
this.network = KnownNetworks.Main;
}
[Fact]
public void GetLastCheckPointHeight_WithoutConsensusSettings_ReturnsZero()
{
var checkpoints = new Checkpoints();
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(0, result);
}
[Fact]
public void GetLastCheckPointHeight_SettingsDisabledCheckpoints_DoesNotLoadCheckpoints()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = false });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(0, result);
}
[Fact]
public void GetLastCheckPointHeight_BitcoinMainnet_ReturnsLastCheckPointHeight()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(550000, result);
}
[Fact]
public void GetLastCheckPointHeight_BitcoinTestnet_ReturnsLastCheckPointHeight()
{
var checkpoints = new Checkpoints(KnownNetworks.TestNet, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(1400000, result);
}
[Fact]
public void GetLastCheckPointHeight_BitcoinRegTestNet_DoesNotLoadCheckpoints()
{
var checkpoints = new Checkpoints(KnownNetworks.RegTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(0, result);
}
[Fact]
public void GetLastCheckPointHeight_StratisMainnet_ReturnsLastCheckPointHeight()
{
var checkpoints = new Checkpoints(KnownNetworks.StratisMain, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(1620000, result);
}
[Fact]
public void GetLastCheckPointHeight_StratisTestnet_ReturnsLastCheckPointHeight()
{
var checkpoints = new Checkpoints(KnownNetworks.StratisTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(1150000, result);
}
[Fact()]
public void GetLastCheckPointHeight_StratisRegTestNet_DoesNotLoadCheckpoints()
{
var checkpoints = new Checkpoints(KnownNetworks.StratisRegTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(0, result);
}
[Fact]
public void GetLastCheckPointHeight_CheckpointsEnabledAfterLoad_RetrievesCheckpointsCorrectly()
{
var consensusSettings = new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = false };
var checkpoints = new Checkpoints(this.network, consensusSettings);
int result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(0, result);
consensusSettings.UseCheckpoints = true;
result = checkpoints.GetLastCheckpointHeight();
Assert.Equal(550000, result);
}
[Fact]
public void GetCheckPoint_WithoutConsensusSettings_ReturnsNull()
{
var checkpoints = new Checkpoints();
CheckpointInfo result = checkpoints.GetCheckpoint(11111);
Assert.Null(result);
}
[Fact]
public void GetCheckPoint_CheckpointExists_PoWChain_ReturnsCheckpoint()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
CheckpointInfo result = checkpoints.GetCheckpoint(11111);
Assert.Equal(new uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"), result.Hash);
Assert.Null(result.StakeModifierV2);
}
[Fact]
public void GetCheckPoint_CheckpointExists_PoSChain_ReturnsCheckpoint()
{
var checkpoints = new Checkpoints(KnownNetworks.StratisMain, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
CheckpointInfo result = checkpoints.GetCheckpoint(2);
Assert.Equal(new uint256("0xbca5936f638181e74a5f1e9999c95b0ce77da48c2688399e72bcc53a00c61eff"), result.Hash);
Assert.Equal(new uint256("0x7d61c139a471821caa6b7635a4636e90afcfe5e195040aecbc1ad7d24924db1e"), result.StakeModifierV2);
}
[Fact]
public void GetCheckPoint_CheckpointDoesNotExist_ReturnsNull()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
CheckpointInfo result = checkpoints.GetCheckpoint(11112);
Assert.Null(result);
}
[Fact]
public void GetCheckPoint_CheckpointsEnabledAfterLoad_RetrievesCheckpointsCorrectly()
{
var consensusSettings = new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = false };
var checkpoints = new Checkpoints(this.network, consensusSettings);
CheckpointInfo result = checkpoints.GetCheckpoint(11112);
Assert.Null(result);
consensusSettings.UseCheckpoints = true;
result = checkpoints.GetCheckpoint(11111);
Assert.Equal(new uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"), result.Hash);
Assert.Null(result.StakeModifierV2);
}
[Fact]
public void CheckHardened_CheckpointsEnabledAfterLoad_RetrievesCheckpointsCorrectly()
{
var consensusSettings = new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = false };
var checkpoints = new Checkpoints(this.network, consensusSettings);
bool result = checkpoints.CheckHardened(11111, new uint256("0x0000000059e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1e")); // invalid hash
Assert.True(result);
consensusSettings.UseCheckpoints = true;
result = checkpoints.CheckHardened(11111, new uint256("0x0000000059e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1e")); // invalid hash
Assert.False(result);
}
[Fact]
public void CheckHardened_CheckpointExistsWithHashAtHeight_ReturnsTrue()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
bool result = checkpoints.CheckHardened(11111, new uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"));
Assert.True(result);
}
[Fact]
public void CheckHardened_CheckpointExistsWithDifferentHashAtHeight_ReturnsTrue()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
bool result = checkpoints.CheckHardened(11111, new uint256("0x0000000059e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1e"));
Assert.False(result);
}
[Fact]
public void CheckHardened_CheckpointDoesNotExistAtHeight_ReturnsTrue()
{
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
bool result = checkpoints.CheckHardened(11112, new uint256("0x7d61c139a471821caa6b7635a4636e90afcfe5e195040aecbc1ad7d24924db1e"));
Assert.True(result);
}
[Fact]
public void CheckHardened_WithoutConsensusSettings_ReturnsTrue()
{
var checkpoints = new Checkpoints();
bool result = checkpoints.CheckHardened(11111, new uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"));
Assert.True(result);
}
[Fact]
public void VerifyCheckpoints_BitcoinMainnet()
{
var verifyableCheckpoints = new Dictionary<int, CheckpointInfo>
{
{ 11111, new CheckpointInfo(new uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) },
{ 33333, new CheckpointInfo(new uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) },
{ 74000, new CheckpointInfo(new uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) },
{ 105000, new CheckpointInfo(new uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) },
{ 134444, new CheckpointInfo(new uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) },
{ 168000, new CheckpointInfo(new uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) },
{ 193000, new CheckpointInfo(new uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) },
{ 210000, new CheckpointInfo(new uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) },
{ 216116, new CheckpointInfo(new uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")) },
{ 225430, new CheckpointInfo(new uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")) },
{ 250000, new CheckpointInfo(new uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")) },
{ 279000, new CheckpointInfo(new uint256("0x0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40")) },
{ 295000, new CheckpointInfo(new uint256("0x00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983")) },
{ 486000, new CheckpointInfo(new uint256("0x000000000000000000a2a8104d61651f76c666b70754d6e9346176385f7afa24")) },
{ 491800, new CheckpointInfo(new uint256("0x000000000000000000d80de1f855902b50941bc3a3d0f71064d9613fd3943dc4")) },
};
var checkpoints = new Checkpoints(this.network, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
VerifyCheckpoints(checkpoints, verifyableCheckpoints);
}
[Fact]
public void VerifyCheckpoints_BitcoinTestnet()
{
var verifyableCheckpoints = new Dictionary<int, CheckpointInfo>
{
{ 546, new CheckpointInfo(new uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) },
{ 1210000, new CheckpointInfo(new uint256("00000000461201277cf8c635fc10d042d6f0a7eaa57f6c9e8c099b9e0dbc46dc")) },
};
var checkpoints = new Checkpoints(KnownNetworks.TestNet, new ConsensusSettings(NodeSettings.Default(this.network)) { UseCheckpoints = true });
VerifyCheckpoints(checkpoints, verifyableCheckpoints);
}
[Fact]
public void VerifyCheckpoints_StratisMainnet()
{
var verifyableCheckpoints = new Dictionary<int, CheckpointInfo>
{
{ 0, new CheckpointInfo(new uint256("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972af"), new uint256("0x0000000000000000000000000000000000000000000000000000000000000000")) },
{ 2, new CheckpointInfo(new uint256("0xbca5936f638181e74a5f1e9999c95b0ce77da48c2688399e72bcc53a00c61eff"), new uint256("0x7d61c139a471821caa6b7635a4636e90afcfe5e195040aecbc1ad7d24924db1e")) }, // Premine
{ 50, new CheckpointInfo(new uint256("0x0353b43f4ce80bf24578e7c0141d90d7962fb3a4b4b4e5a17925ca95e943b816"), new uint256("0x7c2af3b10d13f9d2bc6063baaf7f0860d90d870c994378144f9bf85d0d555061")) },
{ 100, new CheckpointInfo(new uint256("0x688468a8aa48cd1c2197e42e7d8acd42760b7e2ac4bcab9d18ac149a673e16f6"), new uint256("0xcf2b1e9e76aaa3d96f255783eb2d907bf6ccb9c1deeb3617149278f0e4a1ab1b")) },
{ 150, new CheckpointInfo(new uint256("0xe4ae9663519abec15e28f68bdb2cb89a739aee22f53d1573048d69141db6ee5d"), new uint256("0xa6c17173e958dc716cc0892ce33dad8bc327963d78a16c436264ceae43d584ce")) },
{ 127500, new CheckpointInfo(new uint256("0x4773ca7512489df22de03aa03938412fab5b46154b05df004b97bcbeaa184078"), new uint256("0x619743c02ebaff06b90fcc5c60c52dba8aa3fdb6ba3800aae697cbb3c5483f17")) },
{ 128943, new CheckpointInfo(new uint256("0x36bcaa27a53d3adf22b2064150a297adb02ac39c24263a5ceb73856832d49679"), new uint256("0xa3a6fd04e41fcaae411a3990aaabcf5e086d2d06c72c849182b27b4de8c2c42a")) },
{ 136601, new CheckpointInfo(new uint256("0xf5c5210c55ff1ef9c04715420a82728e1647f3473e31dc478b3745a97b4a6d10"), new uint256("0x42058fabe21f7b118a9e358eaf9ef574dadefd024244899e71f2f6d618161e16")) }, // Hardfork to V2 - Drifting Bug Fix
{ 170000, new CheckpointInfo(new uint256("0x22b10952e0cf7e85bfc81c38f1490708f195bff34d2951d193cc20e9ca1fc9d5"), new uint256("0xa4942a6c99cba397cf2b18e4b912930fe1e64a7413c3d97c5a926c2af9073091")) },
{ 200000, new CheckpointInfo(new uint256("0x2391dd493be5d0ff0ef57c3b08c73eefeecc2701b80f983054bb262f7a146989"), new uint256("0x253152d129e82c30c584197deb6833502eff3ec2f30014008f75842d7bb48453")) },
{ 250000, new CheckpointInfo(new uint256("0x681c70fab7c1527246138f0cf937f0eb013838b929fbe9a831af02a60fc4bf55"), new uint256("0x24eed95e00c90618aa9d137d2ee273267285c444c9cde62a25a3e880c98a3685")) },
{ 300000, new CheckpointInfo(new uint256("0xd10ca8c2f065a49ae566c7c9d7a2030f4b8b7f71e4c6fc6b2a02509f94cdcd44"), new uint256("0x39c4dd765b49652935524248b4de4ccb604df086d0723bcd81faf5d1c2489304")) },
{ 350000, new CheckpointInfo(new uint256("0xe2b76d1a068c4342f91db7b89b66e0f2146d3a4706c21f3a262737bb7339253a"), new uint256("0xd1dd94985eaaa028c893687a7ddf89143dcf0176918f958c2d01f33d64910399")) },
{ 390000, new CheckpointInfo(new uint256("0x4682737abc2a3257fdf4c3c119deb09cbac75981969e2ffa998b4f76b7c657bb"), new uint256("0xd84b204ee94499ff65262328a428851fb4f4d2741e928cdd088fdf1deb5413b8")) },
{ 394000, new CheckpointInfo(new uint256("0x42857fa2bc15d45cdcaae83411f755b95985da1cb464ee23f6d40936df523e9f"), new uint256("0x2314b336906a2ed2a39cbdf6fc0622530709c62dbb3a3729de17154fc9d1a7c4")) },
{ 400000, new CheckpointInfo(new uint256("0x4938d5cf450b4e2d9072558971223555055aa3987b634a8bb2e97f95d1a3c501"), new uint256("0x1756c127f0ac7029cf095a6c3ed9b7d206d0e36744d8b3cef306002f9f901a31")) },
{ 450000, new CheckpointInfo(new uint256("0x7699e07ac18c25ac042deb6b985e2decfd6034cb6361de2152a2d704ef785bac"), new uint256("0xa140a86a03c4f852d8a651f6386a02a0262e7bbf841ede8b54541c011c51ba0e")) },
{ 500000, new CheckpointInfo(new uint256("0x558700d99239e64017d10910466719fe1edc6f863bd3de254b89ba828818ea47"), new uint256("0x6a0b7dab4a7aa9ea2477cddffe5a976c9423454835054a39c19d37613002638f")) },
{ 550000, new CheckpointInfo(new uint256("0x83d074957f509772b1fbbfaeb7bdc52932c540d54e205b92a7d4e92f68957eb4"), new uint256("0x012b63ad7d50606f2cafb1a7806ea90f4981c56b5407725aeeff34e3c584433c")) },
{ 600000, new CheckpointInfo(new uint256("0xcd05c75c0c47060d78508095c0766452f80e2defb6a4641ac603742a2ccf2207"), new uint256("0x1f25507e09b199a71d5879811376856e5fb3da1da3d522204c017eec3b6c4dad")) },
{ 650000, new CheckpointInfo(new uint256("0xa2814a439b33662f43bdbc8ab089d368524975bb53a08326395e57456cba8d39"), new uint256("0x192a2ef70e2280cf05aa5655f496a109b2445d0ddda62531e9bce9aaced1fe54")) },
{ 700000, new CheckpointInfo(new uint256("0x782b2506bb67bb448ff56aa946f7aad6b63a6b27d8c5818725a56b568f25b9ce"), new uint256("0xf23dc64b130d80790a83a86913f619afaeef10e1fd24e4b42af9387ec935edd6")) },
{ 750000, new CheckpointInfo(new uint256("0x4db98bd41a2f9ee845cc89ac03109686f615f4d0dcd81e0488005c1616fa692c"), new uint256("0x9f620af75bc27a0e4b503deaf7f052ba112a49bb74fb6446350642bc2ac9d93b")) },
{ 800000, new CheckpointInfo(new uint256("0x161da1d97d35d6897dbdae110617bb839805f8b02d33ac23d227a87cacbfac78"), new uint256("0xe95049a313345f26bfa90094ceb6400f43359fc43fc5f1471918d98bc4ab3bac")) },
{ 850000, new CheckpointInfo(new uint256("0xc3a249b01795b22858aa00fd0973471fcd769a14f4f9cf0abe6651ac3e6ade19"), new uint256("0x5de8766ed4cfcc3ce9d74f38196596c6f91b9ff62cbd20abbfa991dca54d2bd4")) }
};
var checkpoints = new Checkpoints(KnownNetworks.StratisMain, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
VerifyCheckpoints(checkpoints, verifyableCheckpoints);
}
[Fact]
public void VerifyCheckpoints_StratisTestnet()
{
var verifyableCheckpoints = new Dictionary<int, CheckpointInfo>
{
{ 0, new CheckpointInfo(new uint256("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"), new uint256("0x0000000000000000000000000000000000000000000000000000000000000000")) },
{ 2, new CheckpointInfo(new uint256("0x56959b1c8498631fb0ca5fe7bd83319dccdc6ac003dccb3171f39f553ecfa2f2"), new uint256("0x13f4c27ca813aefe2d9018077f8efeb3766796b9144fcc4cd51803bf4376ab02")) },
{ 50000, new CheckpointInfo(new uint256("0xb42c18eacf8fb5ed94eac31943bd364451d88da0fd44cc49616ffea34d530ad4"), new uint256("0x824934ddc5f935e854ac59ae7f5ed25f2d29a7c3914cac851f3eddb4baf96d78")) },
{ 100000, new CheckpointInfo(new uint256("0xf9e2f7561ee4b92d3bde400d251363a0e8924204c326da7f4ad9ccc8863aad79"), new uint256("0xdef8d92d20becc71f662ee1c32252aca129f1bf4744026b116d45d9bfe67e9fb")) },
{ 150000, new CheckpointInfo(new uint256("0x08b7c20a450252ddf9ce41dbeb92ecf54932beac9090dc8250e933ad3a175381"), new uint256("0xf05dad15f733ae0acbd34adc449be9429099dbee5fa9ecd8e524cf28e9153adb")) },
{ 200000, new CheckpointInfo(new uint256("0x8609cc873222a0573615788dc32e377b88bfd6a0015791f627d969ee3a415115"), new uint256("0xfa28c1f20a8162d133607c6a1c8997833befac3efd9076567258a7683ac181fa")) },
{ 250000, new CheckpointInfo(new uint256("0xdd664e15ac679a6f3b96a7176303956661998174a697ad8231f154f1e32ff4a3"), new uint256("0x19fc0fa29418f8b19cbb6557c1c79dfd0eff6779c0eaaec5d245c5cdf3c96d78")) },
{ 300000, new CheckpointInfo(new uint256("0x2409eb5ae72c80d5b37c77903d75a8e742a33843ab633935ce6e5264db962e23"), new uint256("0xf5ec7af55516b8e264ed280e9a5dba0180a4a9d3713351bfea275b18f3f1514e")) },
{ 350000, new CheckpointInfo(new uint256("0x36811041e9060f4b4c26dc20e0850dca5efaabb60618e3456992e9c0b1b2120e"), new uint256("0xbfda55ef0756bcee8485e15527a2b8ca27ca877aa09c88e363ef8d3253cdfd1c")) },
{ 400000, new CheckpointInfo(new uint256("0xb6abcb933d3e3590345ca5d3abb697461093313f8886568ac8ae740d223e56f6"), new uint256("0xfaf5fcebee3ec0df5155393a99da43de18b12e620fef5edb111a791ecbfaa63a")) }
};
var checkpoints = new Checkpoints(KnownNetworks.StratisTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest)) { UseCheckpoints = true });
VerifyCheckpoints(checkpoints, verifyableCheckpoints);
}
private void VerifyCheckpoints(Checkpoints checkpoints, Dictionary<int, CheckpointInfo> checkpointValues)
{
foreach (KeyValuePair<int, CheckpointInfo> checkpoint in checkpointValues)
{
CheckpointInfo result = checkpoints.GetCheckpoint(checkpoint.Key);
Assert.Equal(checkpoint.Value.Hash, result.Hash);
Assert.Equal(checkpoint.Value.StakeModifierV2, result.StakeModifierV2);
}
}
}
}
| 61.473529 | 250 | 0.735659 | [
"MIT"
] | CityChainFoundation/CityChainDaemon | src/Stratis.Bitcoin.Tests/Consensus/CheckpointsTest.cs | 20,903 | C# |
/*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JustLogic nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Camera/Viewport Point To Ray")]
[UnitFriendlyName("Camera.Viewport Point To Ray")]
[UnitUsage(typeof(Ray), HideExpressionInActionsList = true)]
public class JLCameraViewportPointToRay : JLExpression
{
[Parameter(ExpressionType = typeof(Camera))]
public JLExpression OperandValue;
[Parameter(ExpressionType = typeof(Vector3))]
public JLExpression Position;
public override object GetAnyResult(IExecutionContext context)
{
Camera opValue = OperandValue.GetResult<Camera>(context);
return opValue.ViewportPointToRay(Position.GetResult<Vector3>(context));
}
}
| 41.070175 | 80 | 0.779581 | [
"BSD-3-Clause"
] | AqlaSolutions/JustLogic | Assets/JustLogicUnits/Generated/Camera/JLCameraViewportPointToRay.cs | 2,341 | C# |
// Copyright 2020 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.V2.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using apis = Google.Cloud.Dialogflow.V2;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedAgentsClientSnippets
{
/// <summary>Snippet for SetAgentAsync</summary>
public async Task SetAgentAsync()
{
// Snippet: SetAgentAsync(Agent,CallSettings)
// Additional: SetAgentAsync(Agent,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
Agent agent = new Agent();
// Make the request
Agent response = await agentsClient.SetAgentAsync(agent);
// End snippet
}
/// <summary>Snippet for SetAgent</summary>
public void SetAgent()
{
// Snippet: SetAgent(Agent,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
Agent agent = new Agent();
// Make the request
Agent response = agentsClient.SetAgent(agent);
// End snippet
}
/// <summary>Snippet for SetAgentAsync</summary>
public async Task SetAgentAsync_RequestObject()
{
// Snippet: SetAgentAsync(SetAgentRequest,CallSettings)
// Additional: SetAgentAsync(SetAgentRequest,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
SetAgentRequest request = new SetAgentRequest
{
Agent = new Agent(),
};
// Make the request
Agent response = await agentsClient.SetAgentAsync(request);
// End snippet
}
/// <summary>Snippet for SetAgent</summary>
public void SetAgent_RequestObject()
{
// Snippet: SetAgent(SetAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
SetAgentRequest request = new SetAgentRequest
{
Agent = new Agent(),
};
// Make the request
Agent response = agentsClient.SetAgent(request);
// End snippet
}
/// <summary>Snippet for DeleteAgentAsync</summary>
public async Task DeleteAgentAsync()
{
// Snippet: DeleteAgentAsync(ProjectName,CallSettings)
// Additional: DeleteAgentAsync(ProjectName,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
await agentsClient.DeleteAgentAsync(parent);
// End snippet
}
/// <summary>Snippet for DeleteAgent</summary>
public void DeleteAgent()
{
// Snippet: DeleteAgent(ProjectName,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
agentsClient.DeleteAgent(parent);
// End snippet
}
/// <summary>Snippet for DeleteAgentAsync</summary>
public async Task DeleteAgentAsync_RequestObject()
{
// Snippet: DeleteAgentAsync(DeleteAgentRequest,CallSettings)
// Additional: DeleteAgentAsync(DeleteAgentRequest,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
DeleteAgentRequest request = new DeleteAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
await agentsClient.DeleteAgentAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteAgent</summary>
public void DeleteAgent_RequestObject()
{
// Snippet: DeleteAgent(DeleteAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
DeleteAgentRequest request = new DeleteAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
agentsClient.DeleteAgent(request);
// End snippet
}
/// <summary>Snippet for GetAgentAsync</summary>
public async Task GetAgentAsync()
{
// Snippet: GetAgentAsync(ProjectName,CallSettings)
// Additional: GetAgentAsync(ProjectName,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Agent response = await agentsClient.GetAgentAsync(parent);
// End snippet
}
/// <summary>Snippet for GetAgent</summary>
public void GetAgent()
{
// Snippet: GetAgent(ProjectName,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Agent response = agentsClient.GetAgent(parent);
// End snippet
}
/// <summary>Snippet for GetAgentAsync</summary>
public async Task GetAgentAsync_RequestObject()
{
// Snippet: GetAgentAsync(GetAgentRequest,CallSettings)
// Additional: GetAgentAsync(GetAgentRequest,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
GetAgentRequest request = new GetAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Agent response = await agentsClient.GetAgentAsync(request);
// End snippet
}
/// <summary>Snippet for GetAgent</summary>
public void GetAgent_RequestObject()
{
// Snippet: GetAgent(GetAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
GetAgentRequest request = new GetAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Agent response = agentsClient.GetAgent(request);
// End snippet
}
/// <summary>Snippet for SearchAgentsAsync</summary>
public async Task SearchAgentsAsync()
{
// Snippet: SearchAgentsAsync(ProjectName,string,int?,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<SearchAgentsResponse, Agent> response =
agentsClient.SearchAgentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Agent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAgentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Agent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Agent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Agent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAgents</summary>
public void SearchAgents()
{
// Snippet: SearchAgents(ProjectName,string,int?,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<SearchAgentsResponse, Agent> response =
agentsClient.SearchAgents(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Agent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAgentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Agent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Agent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Agent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAgentsAsync</summary>
public async Task SearchAgentsAsync_RequestObject()
{
// Snippet: SearchAgentsAsync(SearchAgentsRequest,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
SearchAgentsRequest request = new SearchAgentsRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<SearchAgentsResponse, Agent> response =
agentsClient.SearchAgentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Agent item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SearchAgentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Agent item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Agent> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Agent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for SearchAgents</summary>
public void SearchAgents_RequestObject()
{
// Snippet: SearchAgents(SearchAgentsRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
SearchAgentsRequest request = new SearchAgentsRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<SearchAgentsResponse, Agent> response =
agentsClient.SearchAgents(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Agent item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SearchAgentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Agent item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Agent> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Agent item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for TrainAgentAsync</summary>
public async Task TrainAgentAsync()
{
// Snippet: TrainAgentAsync(ProjectName,CallSettings)
// Additional: TrainAgentAsync(ProjectName,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Operation<Empty, Struct> response =
await agentsClient.TrainAgentAsync(parent);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await agentsClient.PollOnceTrainAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for TrainAgent</summary>
public void TrainAgent()
{
// Snippet: TrainAgent(ProjectName,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Operation<Empty, Struct> response =
agentsClient.TrainAgent(parent);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
agentsClient.PollOnceTrainAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for TrainAgentAsync</summary>
public async Task TrainAgentAsync_RequestObject()
{
// Snippet: TrainAgentAsync(TrainAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
TrainAgentRequest request = new TrainAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
await agentsClient.TrainAgentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await agentsClient.PollOnceTrainAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for TrainAgent</summary>
public void TrainAgent_RequestObject()
{
// Snippet: TrainAgent(TrainAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
TrainAgentRequest request = new TrainAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
agentsClient.TrainAgent(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
agentsClient.PollOnceTrainAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for ExportAgentAsync</summary>
public async Task ExportAgentAsync()
{
// Snippet: ExportAgentAsync(ProjectName,CallSettings)
// Additional: ExportAgentAsync(ProjectName,CancellationToken)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Operation<ExportAgentResponse, Struct> response =
await agentsClient.ExportAgentAsync(parent);
// Poll until the returned long-running operation is complete
Operation<ExportAgentResponse, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportAgentResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAgentResponse, Struct> retrievedResponse =
await agentsClient.PollOnceExportAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAgentResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportAgent</summary>
public void ExportAgent()
{
// Snippet: ExportAgent(ProjectName,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ProjectName parent = new ProjectName("[PROJECT]");
// Make the request
Operation<ExportAgentResponse, Struct> response =
agentsClient.ExportAgent(parent);
// Poll until the returned long-running operation is complete
Operation<ExportAgentResponse, Struct> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
ExportAgentResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAgentResponse, Struct> retrievedResponse =
agentsClient.PollOnceExportAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAgentResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportAgentAsync</summary>
public async Task ExportAgentAsync_RequestObject()
{
// Snippet: ExportAgentAsync(ExportAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ExportAgentRequest request = new ExportAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<ExportAgentResponse, Struct> response =
await agentsClient.ExportAgentAsync(request);
// Poll until the returned long-running operation is complete
Operation<ExportAgentResponse, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
ExportAgentResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAgentResponse, Struct> retrievedResponse =
await agentsClient.PollOnceExportAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAgentResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ExportAgent</summary>
public void ExportAgent_RequestObject()
{
// Snippet: ExportAgent(ExportAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ExportAgentRequest request = new ExportAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<ExportAgentResponse, Struct> response =
agentsClient.ExportAgent(request);
// Poll until the returned long-running operation is complete
Operation<ExportAgentResponse, Struct> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
ExportAgentResponse result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ExportAgentResponse, Struct> retrievedResponse =
agentsClient.PollOnceExportAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ExportAgentResponse retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for ImportAgentAsync</summary>
public async Task ImportAgentAsync_RequestObject()
{
// Snippet: ImportAgentAsync(ImportAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
ImportAgentRequest request = new ImportAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
await agentsClient.ImportAgentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await agentsClient.PollOnceImportAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for ImportAgent</summary>
public void ImportAgent_RequestObject()
{
// Snippet: ImportAgent(ImportAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
ImportAgentRequest request = new ImportAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
agentsClient.ImportAgent(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
agentsClient.PollOnceImportAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for RestoreAgentAsync</summary>
public async Task RestoreAgentAsync_RequestObject()
{
// Snippet: RestoreAgentAsync(RestoreAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = await AgentsClient.CreateAsync();
// Initialize request argument(s)
RestoreAgentRequest request = new RestoreAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
await agentsClient.RestoreAgentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
await agentsClient.PollOnceRestoreAgentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for RestoreAgent</summary>
public void RestoreAgent_RequestObject()
{
// Snippet: RestoreAgent(RestoreAgentRequest,CallSettings)
// Create client
AgentsClient agentsClient = AgentsClient.Create();
// Initialize request argument(s)
RestoreAgentRequest request = new RestoreAgentRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
Operation<Empty, Struct> response =
agentsClient.RestoreAgent(request);
// Poll until the returned long-running operation is complete
Operation<Empty, Struct> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, Struct> retrievedResponse =
agentsClient.PollOnceRestoreAgent(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
}
}
| 42.561558 | 120 | 0.593996 | [
"Apache-2.0"
] | bijalvakharia/google-cloud-dotnet | apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2.Snippets/AgentsClientSnippets.g.cs | 33,879 | 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.IO;
using System.Net.Http.Headers;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpMessageInvoker : IDisposable
{
private volatile bool _disposed;
private readonly bool _disposeHandler;
private readonly HttpMessageHandler _handler;
public HttpMessageInvoker(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
{
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Associate(this, handler);
_handler = handler;
_disposeHandler = disposeHandler;
}
[UnsupportedOSPlatformAttribute("browser")]
public virtual HttpResponseMessage Send(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri != null)
{
HttpTelemetry.Log.RequestStart(request);
try
{
return _handler.Send(request, cancellationToken);
}
catch when (LogRequestFailed(telemetryStarted: true))
{
// Unreachable as LogRequestFailed will return false
throw;
}
finally
{
HttpTelemetry.Log.RequestStop();
}
}
else
{
return _handler.Send(request, cancellationToken);
}
}
public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
if (HttpTelemetry.Log.IsEnabled() && !request.WasSentByHttpClient() && request.RequestUri != null)
{
return SendAsyncWithTelemetry(_handler, request, cancellationToken);
}
return _handler.SendAsync(request, cancellationToken);
static async Task<HttpResponseMessage> SendAsyncWithTelemetry(HttpMessageHandler handler, HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpTelemetry.Log.RequestStart(request);
try
{
return await handler.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
catch when (LogRequestFailed(telemetryStarted: true))
{
// Unreachable as LogRequestFailed will return false
throw;
}
finally
{
HttpTelemetry.Log.RequestStop();
}
}
}
internal static bool LogRequestFailed(bool telemetryStarted)
{
if (HttpTelemetry.Log.IsEnabled() && telemetryStarted)
{
HttpTelemetry.Log.RequestFailed();
}
return false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
if (_disposeHandler)
{
_handler.Dispose();
}
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
}
}
| 30.265734 | 166 | 0.532116 | [
"MIT"
] | ANISSARIZKY/runtime | src/libraries/System.Net.Http/src/System/Net/Http/HttpMessageInvoker.cs | 4,328 | C# |
using System.Threading.Tasks;
using Sinc.Spotify.Models;
namespace Sinc.Spotify.Services.SpotifyAPI
{
public interface ISpotifyAuthorization
{
Task<SpotifyAccess> GetTokenAsync();
}
} | 20.4 | 44 | 0.740196 | [
"MIT"
] | stysiok/Sinc | src/Sinc.Spotify/Services/SpotifyAPI/ISpotifyAuthorization.cs | 204 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Avalonia.Controls;
using Avalonia.Controls.Templates;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Threading;
namespace Avalonia.ExtendedToolkit.Controls
{
//ported from: https://github.com/punker76/MahApps.Metro.SimpleChildWindow/
public partial class ChildWindow : ContentControl
{
/// <summary>
/// style key of this control
/// </summary>
public Type StyleKey => typeof(ChildWindow);
private const string PART_Overlay = "PART_Overlay";
private const string PART_Window = "PART_Window";
private const string PART_Header = "PART_Header";
private const string PART_HeaderThumb = "PART_HeaderThumb";
private const string PART_Icon = "PART_Icon";
private const string PART_CloseButton = "PART_CloseButton";
private const string PART_Border = "PART_Border";
private const string PART_Content = "PART_Content";
private Animation.Animation _showAnimation = null;
private Task _showAnimationTask;
private Animation.Animation _hideAnimation = null;
private Task _hideAnimationTask;
private CancellationTokenSource _hideAnimationTokenSource;
private IMetroThumb _headerThumb;
private Button _closeButton;
private readonly TranslateTransform _moveTransform = new TranslateTransform();
private Grid _partWindow;
private Grid _partOverlay;
private ContentControl _icon;
DispatcherTimer _autoCloseTimer;
/// <summary>
/// Gets or sets AllowMove.
/// </summary>
public bool AllowMove
{
get { return (bool)GetValue(AllowMoveProperty); }
set { SetValue(AllowMoveProperty, value); }
}
/// <summary>
/// Defines the <see cref="AllowMove"/> property.
/// </summary>
public static readonly StyledProperty<bool> AllowMoveProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(AllowMove));
/// <summary>
/// Gets or sets OffsetX.
/// </summary>
public double OffsetX
{
get { return (double)GetValue(OffsetXProperty); }
set { SetValue(OffsetXProperty, value); }
}
/// <summary>
/// Defines the <see cref="OffsetX"/> property.
/// </summary>
public static readonly StyledProperty<double> OffsetXProperty =
AvaloniaProperty.Register<ChildWindow, double>(nameof(OffsetX), defaultValue: 0d);
/// <summary>
/// Gets or sets OffsetY.
/// </summary>
public double OffsetY
{
get { return (double)GetValue(OffsetYProperty); }
set { SetValue(OffsetYProperty, value); }
}
/// <summary>
/// Defines the <see cref="OffsetY"/> property.
/// </summary>
public static readonly StyledProperty<double> OffsetYProperty =
AvaloniaProperty.Register<ChildWindow, double>(nameof(OffsetY), defaultValue: 0d);
/// <summary>
/// Gets or sets IsModal.
/// </summary>
public bool IsModal
{
get { return (bool)GetValue(IsModalProperty); }
set { SetValue(IsModalProperty, value); }
}
/// <summary>
/// Defines the <see cref="IsModal"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsModalProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(IsModal), defaultValue: true);
/// <summary>
/// Gets or sets OverlayBrush.
/// </summary>
public IBrush OverlayBrush
{
get { return (IBrush)GetValue(OverlayBrushProperty); }
set { SetValue(OverlayBrushProperty, value); }
}
/// <summary>
/// Defines the <see cref="OverlayBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> OverlayBrushProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(OverlayBrush), defaultValue: (IBrush)Brushes.Transparent);
/// <summary>
/// Gets or sets CloseOnOverlay.
/// </summary>
public bool CloseOnOverlay
{
get { return (bool)GetValue(CloseOnOverlayProperty); }
set { SetValue(CloseOnOverlayProperty, value); }
}
/// <summary>
/// Defines the <see cref="CloseOnOverlay"/> property.
/// </summary>
public static readonly StyledProperty<bool> CloseOnOverlayProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(CloseOnOverlay));
/// <summary>
/// Gets or sets CloseByEscape.
/// </summary>
public bool CloseByEscape
{
get { return (bool)GetValue(CloseByEscapeProperty); }
set { SetValue(CloseByEscapeProperty, value); }
}
/// <summary>
/// Defines the <see cref="CloseByEscape"/> property.
/// </summary>
public static readonly StyledProperty<bool> CloseByEscapeProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(CloseByEscape), defaultValue: true);
/// <summary>
/// Gets or sets ShowTitleBar.
/// </summary>
public bool ShowTitleBar
{
get { return (bool)GetValue(ShowTitleBarProperty); }
set { SetValue(ShowTitleBarProperty, value); }
}
/// <summary>
/// Defines the <see cref="ShowTitleBar"/> property.
/// </summary>
public static readonly StyledProperty<bool> ShowTitleBarProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(ShowTitleBar), defaultValue: true);
/// <summary>
/// Gets or sets TitleBarHeight.
/// </summary>
public int TitleBarHeight
{
get { return (int)GetValue(TitleBarHeightProperty); }
set { SetValue(TitleBarHeightProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleBarHeight"/> property.
/// </summary>
public static readonly StyledProperty<int> TitleBarHeightProperty =
AvaloniaProperty.Register<ChildWindow, int>(nameof(TitleBarHeight), defaultValue: 30);
/// <summary>
/// Gets or sets TitleBarBackground.
/// </summary>
public IBrush TitleBarBackground
{
get { return (IBrush)GetValue(TitleBarBackgroundProperty); }
set { SetValue(TitleBarBackgroundProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleBarBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> TitleBarBackgroundProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(TitleBarBackground), defaultValue: (IBrush)Brushes.Transparent);
/// <summary>
/// Gets or sets TitleBarNonActiveBackground.
/// </summary>
public IBrush TitleBarNonActiveBackground
{
get { return (IBrush)GetValue(TitleBarNonActiveBackgroundProperty); }
set { SetValue(TitleBarNonActiveBackgroundProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleBarNonActiveBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> TitleBarNonActiveBackgroundProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(TitleBarNonActiveBackground), (IBrush)Brushes.Gray);
/// <summary>
/// Gets or sets NonActiveBorderBrush.
/// </summary>
public IBrush NonActiveBorderBrush
{
get { return (IBrush)GetValue(NonActiveBorderBrushProperty); }
set { SetValue(NonActiveBorderBrushProperty, value); }
}
/// <summary>
/// Defines the <see cref="NonActiveBorderBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> NonActiveBorderBrushProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(NonActiveBorderBrush), defaultValue: (IBrush)Brushes.Gray);
/// <summary>
/// Gets or sets TitleForeground.
/// </summary>
public IBrush TitleForeground
{
get { return (IBrush)GetValue(TitleForegroundProperty); }
set { SetValue(TitleForegroundProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> TitleForegroundProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(TitleForeground), (IBrush)Brushes.Black);
/// <summary>
/// Gets or sets Title.
/// </summary>
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
/// <summary>
/// Defines the <see cref="Title"/> property.
/// </summary>
public static readonly StyledProperty<string> TitleProperty =
AvaloniaProperty.Register<ChildWindow, string>(nameof(Title));
/// <summary>
/// Gets or sets TitleCharacterCasing.
/// </summary>
public CharacterCasing TitleCharacterCasing
{
get { return (CharacterCasing)GetValue(TitleCharacterCasingProperty); }
set { SetValue(TitleCharacterCasingProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleCharacterCasing"/> property.
/// </summary>
public static readonly StyledProperty<CharacterCasing> TitleCharacterCasingProperty =
AvaloniaProperty.Register<ChildWindow, CharacterCasing>(nameof(TitleCharacterCasing), defaultValue: CharacterCasing.Normal);
/// <summary>
/// Gets or sets TitleHorizontalAlignment.
/// </summary>
public HorizontalAlignment TitleHorizontalAlignment
{
get { return (HorizontalAlignment)GetValue(TitleHorizontalAlignmentProperty); }
set { SetValue(TitleHorizontalAlignmentProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleHorizontalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> TitleHorizontalAlignmentProperty =
AvaloniaProperty.Register<ChildWindow, HorizontalAlignment>(nameof(TitleHorizontalAlignment), defaultValue: HorizontalAlignment.Stretch);
/// <summary>
/// Gets or sets TitleVerticalAlignment.
/// </summary>
public VerticalAlignment TitleVerticalAlignment
{
get { return (VerticalAlignment)GetValue(TitleVerticalAlignmentProperty); }
set { SetValue(TitleVerticalAlignmentProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleVerticalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> TitleVerticalAlignmentProperty =
AvaloniaProperty.Register<ChildWindow, VerticalAlignment>(nameof(TitleVerticalAlignment), defaultValue: VerticalAlignment.Center);
/// <summary>
/// Gets or sets TitleTemplate.
/// </summary>
public IDataTemplate TitleTemplate
{
get { return (IDataTemplate)GetValue(TitleTemplateProperty); }
set { SetValue(TitleTemplateProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate> TitleTemplateProperty =
AvaloniaProperty.Register<ChildWindow, IDataTemplate>(nameof(TitleTemplate));
/// <summary>
/// Gets or sets TitleFontSize.
/// </summary>
public double TitleFontSize
{
get { return (double)GetValue(TitleFontSizeProperty); }
set { SetValue(TitleFontSizeProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleFontSize"/> property.
/// </summary>
public static readonly StyledProperty<double> TitleFontSizeProperty =
AvaloniaProperty.Register<ChildWindow, double>(nameof(TitleFontSize));
/// <summary>
/// Gets or sets TitleFontFamily.
/// </summary>
public FontFamily TitleFontFamily
{
get { return (FontFamily)GetValue(TitleFontFamilyProperty); }
set { SetValue(TitleFontFamilyProperty, value); }
}
/// <summary>
/// Defines the <see cref="TitleFontFamily"/> property.
/// </summary>
public static readonly StyledProperty<FontFamily> TitleFontFamilyProperty =
AvaloniaProperty.Register<ChildWindow, FontFamily>(nameof(TitleFontFamily));
/// <summary>
/// Gets or sets Icon.
/// </summary>
public object Icon
{
get { return (object)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// Defines the <see cref="Icon"/> property.
/// </summary>
public static readonly StyledProperty<object> IconProperty =
AvaloniaProperty.Register<ChildWindow, object>(nameof(Icon));
/// <summary>
/// Gets or sets IconTemplate.
/// </summary>
public IDataTemplate IconTemplate
{
get { return (IDataTemplate)GetValue(IconTemplateProperty); }
set { SetValue(IconTemplateProperty, value); }
}
/// <summary>
/// Defines the <see cref="IconTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate> IconTemplateProperty =
AvaloniaProperty.Register<ChildWindow, IDataTemplate>(nameof(IconTemplate));
/// <summary>
/// Gets or sets ShowCloseButton.
/// </summary>
public bool ShowCloseButton
{
get { return (bool)GetValue(ShowCloseButtonProperty); }
set { SetValue(ShowCloseButtonProperty, value); }
}
/// <summary>
/// Defines the <see cref="ShowCloseButton"/> property.
/// </summary>
public static readonly StyledProperty<bool> ShowCloseButtonProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(ShowCloseButton), defaultValue: true);
/// <summary>
/// Gets or sets CloseButtonCommand.
/// </summary>
public ICommand CloseButtonCommand
{
get { return (ICommand)GetValue(CloseButtonCommandProperty); }
set { SetValue(CloseButtonCommandProperty, value); }
}
/// <summary>
/// Defines the <see cref="CloseButtonCommand"/> property.
/// </summary>
public static readonly StyledProperty<ICommand> CloseButtonCommandProperty =
AvaloniaProperty.Register<ChildWindow, ICommand>(nameof(CloseButtonCommand));
/// <summary>
/// Gets or sets CloseButtonCommandParameter.
/// </summary>
public object CloseButtonCommandParameter
{
get { return (object)GetValue(CloseButtonCommandParameterProperty); }
set { SetValue(CloseButtonCommandParameterProperty, value); }
}
/// <summary>
/// Defines the <see cref="CloseButtonCommandParameter"/> property.
/// </summary>
public static readonly StyledProperty<object> CloseButtonCommandParameterProperty =
AvaloniaProperty.Register<ChildWindow, object>(nameof(CloseButtonCommandParameter));
/// <summary>
/// Gets or sets IsOpen.
/// </summary>
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
/// <summary>
/// Defines the <see cref="IsOpen"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsOpenProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(IsOpen));
/// <summary>
/// Gets or sets ChildWindowWidth.
/// </summary>
public double ChildWindowWidth
{
get { return (double)GetValue(ChildWindowWidthProperty); }
set { SetValue(ChildWindowWidthProperty, value); }
}
/// <summary>
/// Defines the <see cref="ChildWindowWidth"/> property.
/// </summary>
public static readonly StyledProperty<double> ChildWindowWidthProperty =
AvaloniaProperty.Register<ChildWindow, double>(nameof(ChildWindowWidth));
/// <summary>
/// Gets or sets ChildWindowHeight.
/// </summary>
public double ChildWindowHeight
{
get { return (double)GetValue(ChildWindowHeightProperty); }
set { SetValue(ChildWindowHeightProperty, value); }
}
/// <summary>
/// Defines the <see cref="ChildWindowHeight"/> property.
/// </summary>
public static readonly StyledProperty<double> ChildWindowHeightProperty =
AvaloniaProperty.Register<ChildWindow, double>(nameof(ChildWindowHeight));
/// <summary>
/// Gets or sets ChildWindowImage.
/// </summary>
public MessageBoxImage ChildWindowImage
{
get { return (MessageBoxImage)GetValue(ChildWindowImageProperty); }
set { SetValue(ChildWindowImageProperty, value); }
}
/// <summary>
/// Defines the <see cref="ChildWindowImage"/> property.
/// </summary>
public static readonly StyledProperty<MessageBoxImage> ChildWindowImageProperty =
AvaloniaProperty.Register<ChildWindow, MessageBoxImage>(nameof(ChildWindowImage), defaultValue: MessageBoxImage.None);
/// <summary>
/// Gets or sets EnableDropShadow.
/// </summary>
public bool EnableDropShadow
{
get { return (bool)GetValue(EnableDropShadowProperty); }
set { SetValue(EnableDropShadowProperty, value); }
}
/// <summary>
/// Defines the <see cref="EnableDropShadow"/> property.
/// </summary>
public static readonly StyledProperty<bool> EnableDropShadowProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(EnableDropShadow), defaultValue: true);
/// <summary>
/// Gets or sets AllowFocusElement.
/// </summary>
public bool AllowFocusElement
{
get { return (bool)GetValue(AllowFocusElementProperty); }
set { SetValue(AllowFocusElementProperty, value); }
}
/// <summary>
/// Defines the <see cref="AllowFocusElement"/> property.
/// </summary>
public static readonly StyledProperty<bool> AllowFocusElementProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(AllowFocusElement), defaultValue: true);
/// <summary>
/// Gets or sets FocusedElement.
/// </summary>
public IControl FocusedElement
{
get { return (IControl)GetValue(FocusedElementProperty); }
set { SetValue(FocusedElementProperty, value); }
}
/// <summary>
/// Defines the <see cref="FocusedElement"/> property.
/// </summary>
public static readonly StyledProperty<IControl> FocusedElementProperty =
AvaloniaProperty.Register<ChildWindow, IControl>(nameof(FocusedElement));
/// <summary>
/// Gets or sets GlowBrush.
/// </summary>
public IBrush GlowBrush
{
get { return (IBrush)GetValue(GlowBrushProperty); }
set { SetValue(GlowBrushProperty, value); }
}
/// <summary>
/// Defines the <see cref="GlowBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> GlowBrushProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(GlowBrush), defaultValue: (IBrush)Brushes.Black);
/// <summary>
/// Gets or sets NonActiveGlowBrush.
/// </summary>
public IBrush NonActiveGlowBrush
{
get { return (IBrush)GetValue(NonActiveGlowBrushProperty); }
set { SetValue(NonActiveGlowBrushProperty, value); }
}
/// <summary>
/// Defines the <see cref="NonActiveGlowBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> NonActiveGlowBrushProperty =
AvaloniaProperty.Register<ChildWindow, IBrush>(nameof(NonActiveGlowBrush), defaultValue: (IBrush)Brushes.Gray);
/// <summary>
/// Gets or sets IsAutoCloseEnabled.
/// </summary>
public bool IsAutoCloseEnabled
{
get { return (bool)GetValue(IsAutoCloseEnabledProperty); }
set { SetValue(IsAutoCloseEnabledProperty, value); }
}
/// <summary>
/// Defines the <see cref="IsAutoCloseEnabled"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsAutoCloseEnabledProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(IsAutoCloseEnabled));
/// <summary>
/// Gets or sets AutoCloseInterval.
/// </summary>
public long AutoCloseInterval
{
get { return (long)GetValue(AutoCloseIntervalProperty); }
set { SetValue(AutoCloseIntervalProperty, value); }
}
/// <summary>
/// Defines the <see cref="AutoCloseInterval"/> property.
/// </summary>
public static readonly StyledProperty<long> AutoCloseIntervalProperty =
AvaloniaProperty.Register<ChildWindow, long>(nameof(AutoCloseInterval), defaultValue: 5000L);
/// <summary>
/// Gets or sets IsWindowHostActive.
/// </summary>
public bool IsWindowHostActive
{
get { return (bool)GetValue(IsWindowHostActiveProperty); }
set { SetValue(IsWindowHostActiveProperty, value); }
}
/// <summary>
/// Defines the <see cref="IsWindowHostActive"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsWindowHostActiveProperty =
AvaloniaProperty.Register<ChildWindow, bool>(nameof(IsWindowHostActive), defaultValue: true);
/// <summary>
/// Defines the <see cref="CloseButtonToolTip"/> direct property.
/// </summary>
public static readonly DirectProperty<ChildWindow, string> CloseButtonToolTipProperty =
AvaloniaProperty.RegisterDirect<ChildWindow, string>(
nameof(CloseButtonToolTip),
o => o.CloseButtonToolTip);
private string _CloseButtonToolTip;
/// <summary>
/// Gets or sets CloseButtonToolTip.
/// </summary>
public string CloseButtonToolTip
{
get { return _CloseButtonToolTip; }
set
{
SetAndRaise(CloseButtonToolTipProperty, ref _CloseButtonToolTip, value);
}
}
/// <summary>
/// Defines the <see cref="IsOpenChanged"/> routed event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> IsOpenChangedEvent =
RoutedEvent.Register<ChildWindow, RoutedEventArgs>(nameof(IsOpenChangedEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets or sets IsOpenChanged eventhandler.
/// </summary>
public event EventHandler IsOpenChanged
{
add
{
AddHandler(IsOpenChangedEvent, value);
}
remove
{
RemoveHandler(IsOpenChangedEvent, value);
}
}
/// <summary>
/// An event that will be raised when the ChildWindow is closing.
/// </summary>
public event EventHandler<CancelEventArgs> Closing;
/// <summary>
/// Defines the <see cref="ClosingFinished"/> routed event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ClosingFinishedEvent =
RoutedEvent.Register<ChildWindow, RoutedEventArgs>(nameof(ClosingFinishedEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets or sets ClosingFinished eventhandler.
/// </summary>
public event EventHandler ClosingFinished
{
add
{
AddHandler(ClosingFinishedEvent, value);
}
remove
{
RemoveHandler(ClosingFinishedEvent, value);
}
}
/// <summary>
/// Gets the child window result when the dialog will be closed.
/// </summary>
public object ChildWindowResult { get; protected set; }
/// <summary>
/// Gets the dialog close reason.
/// </summary>
public CloseReason ClosedBy { get; private set; } = CloseReason.None;
}
}
| 32.900128 | 149 | 0.605993 | [
"MIT"
] | mameolan/Avalonia.ExtendedToolk | Avalonia.ExtendedToolkit/Controls/ChildWindow/ChildWindow.Attributes.cs | 25,698 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace VoipProjectEntities.Identity.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
CustomerName = table.Column<string>(nullable: true),
ISMigrated = table.Column<bool>(nullable: false),
CustomerTypeID = table.Column<int>(nullable: false),
ISTrialBalanceOpted = table.Column<bool>(nullable: false),
CreatedAt = table.Column<DateTime>(nullable: false),
UpdatedAt = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "RefreshToken",
columns: table => new
{
CustomerId = table.Column<string>(nullable: false),
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Token = table.Column<string>(nullable: true),
Expires = table.Column<DateTime>(nullable: false),
Created = table.Column<DateTime>(nullable: false),
Revoked = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RefreshToken", x => new { x.CustomerId, x.Id });
table.ForeignKey(
name: "FK_RefreshToken_AspNetUsers_CustomerId",
column: x => x.CustomerId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "b3538ce4-d7c3-4fca-af63-59f15a826db0", "6ae31e71-8367-4470-9f58-c5098a14a01d", "Viewer", "VIEWER" });
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "d7a0d7fd-f132-4723-b40e-5c3bbe4e8d9a", "0ddd6166-54ab-4027-ba41-7c6b456b3ab7", "Administrator", "ADMINISTRATOR" });
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "RefreshToken");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 44.179389 | 155 | 0.494168 | [
"Apache-2.0"
] | Anagha1009/VoIPCustomerWebPortal-1 | src/Infrastructure/VoipProjectEntities.Identity/Migrations/20211111060957_initial.cs | 11,577 | C# |
//-----------------------------------------------------------------------------
//
// <copyright file="AnchorInfo.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// IAnchorInfo is the public portion of IAttachedAnnotation.
//
// History:
// 03/09/2007: rruiz: Created a new public interface to expose parts of
// IAttachedAnnotation.
//
//-----------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Annotations;
using System.Windows.Annotations.Storage;
using System.Windows.Media;
using MS.Utility;
namespace System.Windows.Annotations
{
/// <summary>
/// IAnchorInfo represents an annotation's persisted and run-time anchor information.
/// </summary>
public interface IAnchorInfo
{
/// <summary>
/// The Annotation that this anchor information is for
/// </summary>
Annotation Annotation { get;}
/// <summary>
/// The specific anchor in the annotation object model that is represented
/// by this anchor information.
/// </summary>
AnnotationResource Anchor { get; }
/// <summary>
/// The part of the Avalon element tree to which this annotation is anchored.
/// If only a part of the annotations anchor is part of the tree at this moment,
/// then this may be a partial anchor. For instance, if the anchor is several
/// pages of text content, but only one page is currently visible, this would be
/// the visible page.
/// </summary>
Object ResolvedAnchor { get;}
}
}
| 32.981132 | 93 | 0.588101 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Framework/System/Windows/Annotations/AnchorInfo.cs | 1,748 | 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("etcetera")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("etcetera")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("efa7673a-e1e7-469a-bfca-9ff676c77686")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 85 | 0.724912 | [
"Apache-2.0"
] | drusellers/etcetera | etcetera/Properties/AssemblyInfo.cs | 1,428 | C# |
using BugTracker.Model;
namespace BugTracker.Commands
{
public class NotifyDevelopersAboutMissingEstimateCommand : ICommand
{
public NotifyDevelopersAboutMissingEstimateCommand(Bug bug)
{
Bug = bug;
}
public Bug Bug { get; }
}
} | 20.428571 | 71 | 0.646853 | [
"MIT"
] | nikitaignatov/BugTracker | BugTracker/Commands/NotifyDevelopersAboutMissingEstimateCommand.cs | 286 | 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("Gherkin.ParserTester")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Gherkin.ParserTester")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("b677a608-cb68-4277-927a-691e01aa5b37")]
// 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")]
| 39.162162 | 85 | 0.728088 | [
"MIT"
] | DmitryDomaiev/gherkin | dotnet/Gherkin.AstGenerator/Properties/AssemblyInfo.cs | 1,452 | C# |
namespace OpenHardwareMonitor
{
partial class AlapBeallito
{
/// <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(AlapBeallito));
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.trackBar2 = new System.Windows.Forms.TrackBar();
this.trackBar3 = new System.Windows.Forms.TrackBar();
this.trackBar4 = new System.Windows.Forms.TrackBar();
this.trackBar5 = new System.Windows.Forms.TrackBar();
this.trackBar6 = new System.Windows.Forms.TrackBar();
this.trackBar7 = new System.Windows.Forms.TrackBar();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown2 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown3 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown4 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown5 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown6 = new System.Windows.Forms.NumericUpDown();
this.numericUpDown7 = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.trackBar8 = new System.Windows.Forms.TrackBar();
this.numericUpDown8 = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown8)).BeginInit();
this.SuspendLayout();
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(14, 58);
this.trackBar1.Maximum = 100;
this.trackBar1.Name = "trackBar1";
this.trackBar1.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar1.Size = new System.Drawing.Size(45, 104);
this.trackBar1.TabIndex = 0;
this.trackBar1.TickFrequency = 10;
this.trackBar1.Value = 50;
this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
//
// trackBar2
//
this.trackBar2.Location = new System.Drawing.Point(65, 58);
this.trackBar2.Maximum = 100;
this.trackBar2.Name = "trackBar2";
this.trackBar2.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar2.Size = new System.Drawing.Size(45, 104);
this.trackBar2.TabIndex = 1;
this.trackBar2.TickFrequency = 10;
this.trackBar2.Value = 50;
this.trackBar2.Scroll += new System.EventHandler(this.trackBar2_Scroll);
//
// trackBar3
//
this.trackBar3.Location = new System.Drawing.Point(116, 58);
this.trackBar3.Maximum = 100;
this.trackBar3.Name = "trackBar3";
this.trackBar3.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar3.Size = new System.Drawing.Size(45, 104);
this.trackBar3.TabIndex = 2;
this.trackBar3.TickFrequency = 10;
this.trackBar3.Value = 50;
this.trackBar3.Scroll += new System.EventHandler(this.trackBar3_Scroll);
//
// trackBar4
//
this.trackBar4.Location = new System.Drawing.Point(167, 58);
this.trackBar4.Maximum = 100;
this.trackBar4.Name = "trackBar4";
this.trackBar4.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar4.Size = new System.Drawing.Size(45, 104);
this.trackBar4.TabIndex = 3;
this.trackBar4.TickFrequency = 10;
this.trackBar4.Value = 50;
this.trackBar4.Scroll += new System.EventHandler(this.trackBar4_Scroll);
//
// trackBar5
//
this.trackBar5.Location = new System.Drawing.Point(218, 58);
this.trackBar5.Maximum = 100;
this.trackBar5.Name = "trackBar5";
this.trackBar5.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar5.Size = new System.Drawing.Size(45, 104);
this.trackBar5.TabIndex = 4;
this.trackBar5.TickFrequency = 10;
this.trackBar5.Value = 50;
this.trackBar5.Scroll += new System.EventHandler(this.trackBar5_Scroll);
//
// trackBar6
//
this.trackBar6.Location = new System.Drawing.Point(269, 58);
this.trackBar6.Maximum = 100;
this.trackBar6.Name = "trackBar6";
this.trackBar6.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar6.Size = new System.Drawing.Size(45, 104);
this.trackBar6.TabIndex = 5;
this.trackBar6.TickFrequency = 10;
this.trackBar6.Value = 50;
this.trackBar6.Scroll += new System.EventHandler(this.trackBar6_Scroll);
//
// trackBar7
//
this.trackBar7.Location = new System.Drawing.Point(320, 58);
this.trackBar7.Maximum = 100;
this.trackBar7.Name = "trackBar7";
this.trackBar7.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar7.Size = new System.Drawing.Size(45, 104);
this.trackBar7.TabIndex = 6;
this.trackBar7.TickFrequency = 10;
this.trackBar7.Value = 50;
this.trackBar7.Scroll += new System.EventHandler(this.trackBar7_Scroll);
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(14, 168);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(42, 20);
this.numericUpDown1.TabIndex = 7;
this.numericUpDown1.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
//
// numericUpDown2
//
this.numericUpDown2.Location = new System.Drawing.Point(65, 168);
this.numericUpDown2.Name = "numericUpDown2";
this.numericUpDown2.Size = new System.Drawing.Size(42, 20);
this.numericUpDown2.TabIndex = 8;
this.numericUpDown2.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown2.ValueChanged += new System.EventHandler(this.numericUpDown2_ValueChanged);
//
// numericUpDown3
//
this.numericUpDown3.Location = new System.Drawing.Point(116, 168);
this.numericUpDown3.Name = "numericUpDown3";
this.numericUpDown3.Size = new System.Drawing.Size(42, 20);
this.numericUpDown3.TabIndex = 9;
this.numericUpDown3.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown3.ValueChanged += new System.EventHandler(this.numericUpDown3_ValueChanged);
//
// numericUpDown4
//
this.numericUpDown4.Location = new System.Drawing.Point(167, 168);
this.numericUpDown4.Name = "numericUpDown4";
this.numericUpDown4.Size = new System.Drawing.Size(42, 20);
this.numericUpDown4.TabIndex = 10;
this.numericUpDown4.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown4.ValueChanged += new System.EventHandler(this.numericUpDown4_ValueChanged);
//
// numericUpDown5
//
this.numericUpDown5.Location = new System.Drawing.Point(218, 168);
this.numericUpDown5.Name = "numericUpDown5";
this.numericUpDown5.Size = new System.Drawing.Size(42, 20);
this.numericUpDown5.TabIndex = 11;
this.numericUpDown5.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown5.ValueChanged += new System.EventHandler(this.numericUpDown5_ValueChanged);
//
// numericUpDown6
//
this.numericUpDown6.Location = new System.Drawing.Point(269, 168);
this.numericUpDown6.Name = "numericUpDown6";
this.numericUpDown6.Size = new System.Drawing.Size(42, 20);
this.numericUpDown6.TabIndex = 12;
this.numericUpDown6.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown6.ValueChanged += new System.EventHandler(this.numericUpDown6_ValueChanged);
//
// numericUpDown7
//
this.numericUpDown7.Location = new System.Drawing.Point(320, 168);
this.numericUpDown7.Name = "numericUpDown7";
this.numericUpDown7.Size = new System.Drawing.Size(42, 20);
this.numericUpDown7.TabIndex = 13;
this.numericUpDown7.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown7.ValueChanged += new System.EventHandler(this.numericUpDown7_ValueChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 47F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.label1.Location = new System.Drawing.Point(-9, -1);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(429, 72);
this.label1.TabIndex = 14;
this.label1.Text = "1 2 3 4 5 6 7 8";
//
// button1
//
this.button1.BackColor = System.Drawing.Color.Red;
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.Location = new System.Drawing.Point(397, 58);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(23, 104);
this.button1.TabIndex = 15;
this.button1.Text = "˄˄˄˄˄";
this.button1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// trackBar8
//
this.trackBar8.Location = new System.Drawing.Point(371, 58);
this.trackBar8.Maximum = 100;
this.trackBar8.Name = "trackBar8";
this.trackBar8.Orientation = System.Windows.Forms.Orientation.Vertical;
this.trackBar8.Size = new System.Drawing.Size(45, 104);
this.trackBar8.TabIndex = 16;
this.trackBar8.TickFrequency = 10;
this.trackBar8.Value = 50;
this.trackBar8.Scroll += new System.EventHandler(this.trackBar8_Scroll);
//
// numericUpDown8
//
this.numericUpDown8.Location = new System.Drawing.Point(371, 168);
this.numericUpDown8.Name = "numericUpDown8";
this.numericUpDown8.Size = new System.Drawing.Size(42, 20);
this.numericUpDown8.TabIndex = 17;
this.numericUpDown8.Value = new decimal(new int[] {
50,
0,
0,
0});
this.numericUpDown8.ValueChanged += new System.EventHandler(this.numericUpDown8_ValueChanged);
//
// AlapBeallito
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(421, 197);
this.Controls.Add(this.numericUpDown8);
this.Controls.Add(this.button1);
this.Controls.Add(this.numericUpDown7);
this.Controls.Add(this.numericUpDown6);
this.Controls.Add(this.numericUpDown5);
this.Controls.Add(this.numericUpDown4);
this.Controls.Add(this.numericUpDown3);
this.Controls.Add(this.numericUpDown2);
this.Controls.Add(this.numericUpDown1);
this.Controls.Add(this.trackBar8);
this.Controls.Add(this.trackBar7);
this.Controls.Add(this.trackBar6);
this.Controls.Add(this.trackBar5);
this.Controls.Add(this.trackBar4);
this.Controls.Add(this.trackBar3);
this.Controls.Add(this.trackBar2);
this.Controls.Add(this.trackBar1);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "AlapBeallito";
this.Text = "Indítási Fordulatszámok a Célhardveren";
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown8)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.TrackBar trackBar2;
private System.Windows.Forms.TrackBar trackBar3;
private System.Windows.Forms.TrackBar trackBar4;
private System.Windows.Forms.TrackBar trackBar5;
private System.Windows.Forms.TrackBar trackBar6;
private System.Windows.Forms.TrackBar trackBar7;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.NumericUpDown numericUpDown2;
private System.Windows.Forms.NumericUpDown numericUpDown3;
private System.Windows.Forms.NumericUpDown numericUpDown4;
private System.Windows.Forms.NumericUpDown numericUpDown5;
private System.Windows.Forms.NumericUpDown numericUpDown6;
private System.Windows.Forms.NumericUpDown numericUpDown7;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TrackBar trackBar8;
private System.Windows.Forms.NumericUpDown numericUpDown8;
}
} | 50.660221 | 238 | 0.610121 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gatsjanos/Feverkill | OHM/OHM FELD/GUI/AlapBeallito.Designer.cs | 18,350 | C# |
using System;
using System.Linq;
using Assets.Scripts.Models.Audio;
using Assets.Scripts.Models.GenericBehaviors;
using Assets.Scripts.Models.Powers;
using Assets.Scripts.Models.Powers.Effects;
using Assets.Scripts.Models.Towers;
using Assets.Scripts.Models.Towers.Behaviors;
using Assets.Scripts.Models.Towers.Projectiles;
using Assets.Scripts.Unity;
using Assets.Scripts.Unity.UI_New.InGame;
using MelonLoader;
using UnhollowerBaseLib;
using UnityEngine;
namespace PowersInShop
{
public class Utils
{
public static bool CanBeCast<T>(Il2CppObjectBase obj) where T : Il2CppObjectBase
{
IntPtr nativeClassPtr = Il2CppClassPointerStore<T>.NativeClassPtr;
IntPtr num = IL2CPP.il2cpp_object_get_class(obj.Pointer);
return IL2CPP.il2cpp_class_is_assignable_from(nativeClassPtr, num);
}
public static ProjectileModel GetProjectileModel(PowerBehaviorModel powerBehaviorModel)
{
ProjectileModel projectleModel = null;
if (CanBeCast<MoabMineModel>(powerBehaviorModel))
{
projectleModel = powerBehaviorModel.Cast<MoabMineModel>().projectileModel;
} else if (CanBeCast<GlueTrapModel>(powerBehaviorModel))
{
projectleModel = powerBehaviorModel.Cast<GlueTrapModel>().projectileModel;
} else if (CanBeCast<CamoTrapModel>(powerBehaviorModel))
{
projectleModel = powerBehaviorModel.Cast<CamoTrapModel>().projectileModel;
} else if (CanBeCast<RoadSpikesModel>(powerBehaviorModel))
{
projectleModel = powerBehaviorModel.Cast<RoadSpikesModel>().projectileModel;
}
return projectleModel;
}
public static TowerModel CreateTower(string power)
{
PowerModel powerModel = Game.instance.model.GetPowerWithName(power);
TowerModel towerModel =
Game.instance.model.GetTowerWithName("NaturesWardTotem").Clone().Cast<TowerModel>();
towerModel.name = power;
towerModel.icon = powerModel.icon;
towerModel.cost = Main.Powers[power];
towerModel.display = power;
towerModel.baseId = power;
towerModel.towerSet = "Support";
towerModel.radiusSquared = 9;
towerModel.radius = 3;
towerModel.range = 0;
towerModel.footprint = new CircleFootprintModel(power, 0, true, false, true);
towerModel.showPowerTowerBuffs = false;
towerModel.behaviors.First(b => b.name.Contains("OnExpire"))
.Cast<CreateEffectOnExpireModel>().effectModel = powerModel.behaviors
.First(b => b.name.Contains("Effect")).Cast<CreateEffectOnPowerModel>().effectModel;
towerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnTowerPlaceModel>()
.sound1.assetId = powerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnPowerModel>().sound.assetId;
towerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnTowerPlaceModel>()
.sound2.assetId = powerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnPowerModel>().sound.assetId;
towerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnTowerPlaceModel>()
.heroSound1 = new BlankSoundModel();
towerModel.behaviors.First(b => b.name.Contains("Sound")).Cast<CreateSoundOnTowerPlaceModel>()
.heroSound2 = new BlankSoundModel();
var displayModel = towerModel.behaviors.First(b => b.name.Contains("Display"))
.Cast<DisplayModel>();
displayModel.display = "8ab0e3fbb093a554d84a85e18fe2acac"; //tiny little caltrops
var powerBehaviorModel = powerModel.behaviors.First(b => !b.name.Contains("Create"));
var projectleModel = GetProjectileModel(powerBehaviorModel);
if (projectleModel != null)
{
projectleModel.pierce = Main.TrackPowers[power];
if (projectleModel.maxPierce != 0)
{
projectleModel.maxPierce = Main.TrackPowers[power];
}
}
//towerModel.behaviors = towerModel.behaviors.Where(b => !b.name.Contains("Display")).ToArray();
//towerModel.behaviors.First(b => b.name.Contains("Display")).Cast<DisplayModel>().display = powerModel.icon.GUID;
towerModel.behaviors = towerModel.behaviors.Where(b => !b.name.Contains("Slow")).ToArray();
return towerModel;
}
public static int RealRechargePrice()
{
var price = (float) Main.RechargePrice;
switch (InGame.instance.SelectedDifficulty)
{
case "Easy":
price *= .85f;
break;
case "Hard":
price *= 1.08f;
break;
case "Impoppable":
price *= 1.2f;
break;
}
price /= 5f;
price = (int)Math.Round(price);
return (int) (price * 5);
}
public static void RecursivelyLogGameObject(Transform gameObject, int depth = 0)
{
var str = gameObject.name;
for (int i = 0; i < depth; i++)
{
str = "| " + str;
}
MelonLogger.Log(str);
for (int i = 0; i < gameObject.childCount; i++)
{
RecursivelyLogGameObject(gameObject.transform.GetChild(i), depth + 1);
}
}
}
} | 42.323741 | 138 | 0.593235 | [
"MIT"
] | teddybearboo/BTD6-Mods | PowersInShop/Utils.cs | 5,885 | C# |
/*
Scenario for use Abstract Factory:
World regions (Africa,America,Asia) that have distinct food chains and animals,
the factory will return a concrete implementation of these rules.
For better reference, please visit https://www.dofactory.com/net/design-patterns
*/
using System;
namespace brunoedsm.creational.console
{
public static class AbstractFactoryPlayer
{
public static void PlayExample()
{
ContinentFactory africa = new AfricaFactory();
AnimalWorld world = new AnimalWorld(africa);
world.RunFoodChain();
ContinentFactory america = new AmericaFactory();
world = new AnimalWorld(america);
world.RunFoodChain();
ContinentFactory asia = new AsiaFactory();
world = new AnimalWorld(asia);
world.RunFoodChain();
}
}
// Abstracts
abstract class Herbivore
{
}
abstract class Carnivore
{
public abstract void Eat(Herbivore h);
}
abstract class ContinentFactory
{
public abstract Herbivore CreateHerbivore();
public abstract Carnivore CreateCarnivore();
}
// Concretes
class Bison : Herbivore
{
}
class Wildebeest : Herbivore
{
}
class Auroch : Herbivore
{
}
class Lion : Carnivore
{
public override void Eat(Herbivore h)
{
// Eat Wildebeest
Console.WriteLine(this.GetType().Name +
" eats " + h.GetType().Name);
}
}
class Wolf : Carnivore
{
public override void Eat(Herbivore h)
{
// Eat Bison
Console.WriteLine(this.GetType().Name +
" eats " + h.GetType().Name);
}
}
class Bear : Carnivore
{
public override void Eat(Herbivore h)
{
// Eat Bison
Console.WriteLine(this.GetType().Name +
" eats " + h.GetType().Name);
}
}
class AmericaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Bison();
}
public override Carnivore CreateCarnivore()
{
return new Wolf();
}
}
class AfricaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Wildebeest();
}
public override Carnivore CreateCarnivore()
{
return new Lion();
}
}
class AsiaFactory : ContinentFactory
{
public override Herbivore CreateHerbivore()
{
return new Auroch();
}
public override Carnivore CreateCarnivore()
{
return new Bear();
}
}
class AnimalWorld
{
private Herbivore _herbivore;
private Carnivore _carnivore;
public AnimalWorld(ContinentFactory factory)
{
_carnivore = factory.CreateCarnivore();
_herbivore = factory.CreateHerbivore();
}
public void RunFoodChain()
{
_carnivore.Eat(_herbivore);
}
}
} | 22.570423 | 87 | 0.556942 | [
"Apache-2.0"
] | brunoedsm/c-sharp-resources | design-patterns/creational/brunoedsm.creational.console/AbstractFactoryPlayer.cs | 3,205 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ARMClient.Authentication;
using ARMClient.Authentication.Contracts;
using ARMClient.Library;
using Azure.Functions.Cli.Arm.Models;
using Azure.Functions.Cli.Interfaces;
namespace Azure.Functions.Cli.Arm
{
internal partial class ArmManager : IArmManager
{
private readonly IAzureClient _client;
private readonly IAuthHelper _authHelper;
private readonly ISettings _settings;
public ArmManager(IAuthHelper authHelper, IAzureClient client, ISettings settings)
{
_authHelper = authHelper;
_client = client;
_settings = settings;
Task.Run(async () => await SelectTenantAsync(_settings.CurrentSubscription)).Wait();
}
public async Task<AuthenticationHeaderValue> GetAuthenticationHeader(string id)
{
var token = await _authHelper.GetToken(id);
return new AuthenticationHeaderValue("Bearer", token.AccessToken);
}
public async Task<IEnumerable<Site>> GetFunctionAppsAsync()
{
var subscription = await GetCurrentSubscriptionAsync();
return await GetFunctionAppsAsync(subscription);
}
public async Task<Site> GetFunctionAppAsync(string name)
{
var functionApps = await GetFunctionAppsAsync();
var functionApp = functionApps.FirstOrDefault(s => s.SiteName.Equals(name, StringComparison.OrdinalIgnoreCase));
if (functionApp == null)
{
throw new ArmResourceNotFoundException($"Can't find app with name \"{name}\" in current subscription.");
}
else
{
return await LoadAsync(functionApp);
}
}
public async Task<Site> CreateFunctionAppAsync(string subscriptionStr, string resourceGroupStr, string functionAppNameStr, string geoLocationStr)
{
var subscription = new Subscription(subscriptionStr, string.Empty);
var resourceGroup = await EnsureResourceGroupAsync(
new ResourceGroup(
subscription.SubscriptionId,
resourceGroupStr,
geoLocationStr)
);
var storageAccount = await EnsureAStorageAccountAsync(resourceGroup);
var functionApp = new Site(subscription.SubscriptionId, resourceGroup.ResourceGroupName, functionAppNameStr);
var keys = await GetStorageAccountKeysAsync(storageAccount);
var connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccount.StorageAccountName};AccountKey={keys.First().Value}";
await ArmHttpAsync<ArmWrapper<object>>(HttpMethod.Put, ArmUriTemplates.Site.Bind(functionApp),
new
{
properties = new
{
siteConfig = new
{
appSettings = new Dictionary<string, string> {
{ "AzureWebJobsStorage", connectionString },
{ "AzureWebJobsDashboard", connectionString },
{ "FUNCTIONS_EXTENSION_VERSION", "latest" },
{ "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING", connectionString },
{ "WEBSITE_CONTENTSHARE", storageAccount.StorageAccountName.ToLowerInvariant() },
{ $"{storageAccount.StorageAccountName}_STORAGE", connectionString },
{ "WEBSITE_NODE_DEFAULT_VERSION", "6.5.0" }
}
.Select(e => new { name = e.Key, value = e.Value})
},
sku = "Dynamic"
},
location = geoLocationStr,
kind = "functionapp"
});
return functionApp;
}
public Task LoginAsync()
{
_authHelper.ClearTokenCache();
return _authHelper.AcquireTokens();
}
public IEnumerable<string> DumpTokenCache()
{
return _authHelper.DumpTokenCache();
}
public async Task SelectTenantAsync(string id)
{
TokenCacheInfo token = null;
try
{
token = await _authHelper.GetToken(id);
}
catch { }
if (token == null || token.ExpiresOn < DateTimeOffset.Now)
{
await _authHelper.AcquireTokens();
}
await _authHelper.GetToken(id);
}
public void Logout()
{
_authHelper.ClearTokenCache();
}
public async Task<Site> EnsureScmTypeAsync(Site functionApp)
{
functionApp = await LoadSiteConfigAsync(functionApp);
if (string.IsNullOrEmpty(functionApp.ScmType) ||
functionApp.ScmType.Equals("None", StringComparison.OrdinalIgnoreCase))
{
await UpdateSiteConfigAsync(functionApp, new { properties = new { scmType = "LocalGit" } });
await Task.Delay(TimeSpan.FromSeconds(2));
}
return functionApp;
}
private async Task<T> ArmHttpAsync<T>(HttpMethod method, Uri uri, object payload = null)
{
var response = await _client.HttpInvoke(method, uri, payload);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T>();
}
public async Task<TenantCacheInfo> GetCurrentTenantAsync()
{
var token = await _authHelper.GetToken(id: string.Empty);
return _authHelper.GetTenantsInfo().FirstOrDefault(t => t.tenantId.Equals(token.TenantId, StringComparison.OrdinalIgnoreCase));
}
public IEnumerable<TenantCacheInfo> GetTenants()
{
return _authHelper.GetTenantsInfo();
}
private async Task ArmHttpAsync(HttpMethod method, Uri uri, object payload = null)
{
var response = await _client.HttpInvoke(method, uri, payload);
response.EnsureSuccessStatusCode();
}
public async Task<IEnumerable<StorageAccount>> GetStorageAccountsAsync()
{
var subscription = await GetCurrentSubscriptionAsync();
return await GetStorageAccountsAsync(subscription);
}
public async Task<IEnumerable<ArmWrapper<object>>> getAzureResourceAsync(string resourceName)
{
var subscription = await GetCurrentSubscriptionAsync();
return await GetResourcesByNameAsync(subscription, resourceName);
}
private async Task<IEnumerable<ArmWrapper<object>>> GetResourcesByNameAsync(Subscription subscription, string resourceName)
{
var armSubscriptionResourcesResponse = await _client.HttpInvoke(HttpMethod.Get, ArmUriTemplates.SubscriptionResourceByName.Bind(new { subscriptionId = subscription.SubscriptionId, resourceName = resourceName }));
armSubscriptionResourcesResponse.EnsureSuccessStatusCode();
var resources = await armSubscriptionResourcesResponse.Content.ReadAsAsync<ArmArrayWrapper<object>>();
return resources.Value;
}
public async Task<StorageAccount> GetStorageAccountsAsync(ArmWrapper<object> armWrapper)
{
var regex = new Regex("/subscriptions/(.*)/resourceGroups/(.*)/providers/Microsoft.Storage/storageAccounts/(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var match = regex.Match(armWrapper.Id);
if (match.Success)
{
var storageAccount = new StorageAccount(match.Groups[1].ToString(), match.Groups[2].ToString(), match.Groups[3].ToString(), string.Empty);
return await LoadAsync(storageAccount);
}
else
{
return null;
}
}
}
} | 40.726829 | 224 | 0.595161 | [
"MIT"
] | lukecolburn/azure-functions-cli | src/Azure.Functions.Cli/Arm/ArmManager.cs | 8,351 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Build.Tasks
{
using System;
using System.Linq;
using Cake.Common.IO;
using Cake.Frosting;
using DotNetNuke.Build;
/// <summary>A cake task to clean the website directory.</summary>
public sealed class CleanWebsite : FrostingTask<Context>
{
/// <inheritdoc/>
public override void Run(Context context)
{
context.CleanDirectory(context.WebsiteDir);
}
}
}
| 27.458333 | 71 | 0.675266 | [
"MIT"
] | Mariusz11711/DNN | Build/Tasks/CleanWebsite.cs | 661 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DCounter.Examples
{
class Program
{
static void Main(string[] args)
{
string key1 = "C10010/1";
string key2 = "C10011/10001";
var provider = DCounter.DCounterServiceFactory.Create((p)=> {
// 初始化各个计数器
for (var i= 1; i <= 10000; i++)
{
p.Set("C10010/" + i.ToString(), i % 100 + 2);
}
for (var i = 10001; i <= 20000; i++)
{
p.Set("C10011/" + i.ToString(), i % 100 + 3);
}
}).Provider;
// 打印初始值
Console.WriteLine(String.Format("{0}'s value is {1}", key1, provider.Get(key1)));
Console.WriteLine(String.Format("{0}'s value is {1}", key2, provider.Get(key2)));
// 增加 |-90|
provider.IncreaseBy(key1, -90);
Console.WriteLine(String.Format("{0}'s value is {1}", key1, provider.Get(key1)));
// 减少 |-90|
provider.DecreaseBy(key2, -90);
Console.WriteLine(String.Format("{0}'s value is {1}", key2, provider.Get(key2)));
}
}
}
| 30.707317 | 93 | 0.479746 | [
"MIT"
] | Berkaroad/Counter.Net | src/DCounter.Examples/Program.cs | 1,295 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Microting.WorkOrderBase.Migrations
{
public partial class AddingMissingAttributes : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "AssignedArea",
table: "WorkOrderVersions",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "AssignedWorker",
table: "WorkOrderVersions",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "AssignedArea",
table: "WorkOrders",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "AssignedWorker",
table: "WorkOrders",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AssignedArea",
table: "WorkOrderVersions");
migrationBuilder.DropColumn(
name: "AssignedWorker",
table: "WorkOrderVersions");
migrationBuilder.DropColumn(
name: "AssignedArea",
table: "WorkOrders");
migrationBuilder.DropColumn(
name: "AssignedWorker",
table: "WorkOrders");
}
}
}
| 29.78 | 71 | 0.541303 | [
"MIT"
] | microting/eform-workorder-base | Microting.WorkOrderBase/Migrations/20201111124415_AddingMissingAttributes.cs | 1,491 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExamplePatterns.Library.QueryPattern
{
public class NumberOfUsersQuery : IQuery<int>
{
}
public class NumberOfUsersQueryHandler : IQueryHandler<NumberOfUsersQuery, int>
{
//Encapsulates the functionality of the query
public int Handle(NumberOfUsersQuery query)
{
return 10;
}
}
}
| 21.681818 | 83 | 0.691824 | [
"MIT"
] | cjhoward92/ExamplePatterns | ExamplePatterns.Library/QueryPattern/NumberOfUsersQuery.cs | 479 | C# |
using System;
namespace AlgoSdk.WalletConnect
{
[AlgoApiObject]
public partial struct WalletConnectSessionRequest
: IEquatable<WalletConnectSessionRequest>
{
[AlgoApiField("peerId", null)]
public string PeerId;
[AlgoApiField("peerMeta", null)]
public ClientMeta PeerMeta;
[AlgoApiField("chainId", null)]
public Optional<int> ChainId;
public bool Equals(WalletConnectSessionRequest other)
{
return StringComparer.Equals(PeerId, other.PeerId)
&& PeerMeta.Equals(other.PeerMeta)
&& ChainId.Equals(other.ChainId)
;
}
}
}
| 25.074074 | 62 | 0.611521 | [
"MIT"
] | SpacePassport/unity-algorand-sdk | Runtime/CareBoo.AlgoSdk.WalletConnect/Models/WalletConnectSessionRequest.cs | 677 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See license.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Its.Validation
{
/// <summary>
/// Describes the dot-notation path through an object graph to a specific member.
/// </summary>
internal class MemberPath
{
/// <summary>
/// Initializes a new instance of the <see cref="MemberPath"/> class.
/// </summary>
/// <param name="value">The value.</param>
public MemberPath(string value)
{
Value = value ?? string.Empty;
}
/// <summary>
/// Gets the member path value.
/// </summary>
public string Value { get; private set; }
/// <summary>
/// Determines a member path given an Expression.
/// </summary>
internal static string FromExpression(LambdaExpression expression)
{
var nameParts = new Stack<string>();
var part = expression.Body;
while (part != null)
{
if (part.NodeType == ExpressionType.Call ||
part.NodeType == ExpressionType.ArrayIndex)
{
throw new NotSupportedException("MemberPath must consist only of member access sub-expressions");
}
if (part.NodeType == ExpressionType.MemberAccess)
{
var memberExpressionPart = (MemberExpression) part;
nameParts.Push("." + memberExpressionPart.Member.Name);
part = memberExpressionPart.Expression;
}
else
{
break;
}
}
return nameParts.Count > 0
? nameParts.Aggregate((left, right) => left + right).TrimStart('.')
: string.Empty;
}
}
} | 33.596774 | 123 | 0.515602 | [
"Apache-2.0"
] | jonsequitur/Its.Validation | Validation/MemberPath.cs | 2,085 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada con un ensamblado.
[assembly: AssemblyTitle("ShareTeam")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ShareTeam")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("9336785f-219a-42b9-9aa6-335e571cf817")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los números de compilación y de revisión predeterminados
// mediante el carácter "*", como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.621622 | 102 | 0.756487 | [
"MIT"
] | Khanx/ShareTeam | ShareTeam/ShareTeam/Properties/AssemblyInfo.cs | 1,521 | C# |
using PaymentContext.Domain.Enums;
using PaymentContext.Domain.ValueObjects;
using PaymentContext.Shared.Commands;
using System;
using System.Collections.Generic;
using System.Text;
namespace PaymentContext.Domain.Commands
{
public class CreatePayPalSubscriptionCommand : ICommand
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Document { get; set; }
public string Email { get; set; }
public string TransctionCode { get; set; }
public string PaymentNumber { get; set; }
public DateTime PaidDate { get; set; }
public DateTime ExpireDate { get; set; }
public decimal Total { get; set; }
public decimal TotalPaid { get; set; }
public string Payer { get; set; }
public string PayerDocument { get; set; }
public EDocumentType PayerDocumentType { get; set; }
public string PayerEmail { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string Neighborhood { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public void Validate()
{
throw new NotImplementedException();
}
}
}
| 32.465116 | 61 | 0.618195 | [
"MIT"
] | Ariosmaia/Modelando-Dominios-Ricos | PaymentContext.Domain/Commands/CreatePayPalSubscriptionCommand.cs | 1,398 | C# |
#region Copyright 2019-2021 C. Augusto Proiete & 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
//
// 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 Serilog.Core;
using Serilog.Events;
namespace ExcelDna.Diagnostics.Serilog.Tests.Support
{
public class DelegatingSink : ILogEventSink
{
private readonly Action<LogEvent> _write;
public DelegatingSink(Action<LogEvent> write)
{
_write = write ?? throw new ArgumentNullException(nameof(write));
}
public void Emit(LogEvent logEvent)
{
_write(logEvent);
}
}
}
| 29.157895 | 77 | 0.698556 | [
"Apache-2.0"
] | augustoproiete/exceldna-diagnostics-serilog | test/ExcelDna.Diagnostics.Serilog.Tests/Support/DelegatingSink.cs | 1,110 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsQuery.HtmlParser;
namespace CsQuery.Implementation
{
/// <summary>
/// An HTML option element.
/// </summary>
public class HTMLOptionElement : DomElement, IHTMLOptionElement
{
/// <summary>
/// Default constructor.
/// </summary>
public HTMLOptionElement()
: base(HtmlData.tagOPTION)
{
}
/// <summary>
/// The value of the OPTIOn element, or empty string if none specified.
/// </summary>
public override string Value
{
get
{
var attrValue = GetAttribute(HtmlData.ValueAttrId, null);
return attrValue ?? InnerText;
}
set
{
base.Value = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this object is disabled.
/// </summary>
public bool Disabled
{
get
{
if (HasAttribute(HtmlData.attrDISABLED)) {
return true;
} else {
if (ParentNode.NodeNameID == HtmlData.tagOPTION || ParentNode.NodeNameID == HtmlData.tagOPTGROUP)
{
var disabled = ((DomElement)ParentNode).HasAttribute(HtmlData.attrDISABLED);
if (disabled)
{
return true;
}
else
{
return ParentNode.ParentNode.NodeNameID == HtmlData.tagOPTGROUP &&
((DomElement)ParentNode.ParentNode).HasAttribute(HtmlData.attrDISABLED);
}
}
else
{
return false;
}
}
}
set
{
SetProp(HtmlData.attrDISABLED, value);
}
}
/// <summary>
/// The form with which the element is associated.
/// </summary>
public IDomElement Form
{
get { return Closest(HtmlData.tagFORM); }
}
/// <summary>
/// Gets or sets the label for this Option element
/// </summary>
public string Label
{
get
{
return GetAttribute(HtmlData.tagLABEL);
}
set
{
SetAttribute(HtmlData.tagLABEL,value);
}
}
/// <summary>
/// Indicates whether the element is selected or not. This value is read-only. To change the
/// selection, set either the selectedIndex or selectedItem property of the containing element.
/// </summary>
///
/// <url>
/// https://developer.mozilla.org/en/XUL/Attribute/selected
/// </url>
public override bool Selected
{
get
{
var owner = OptionOwner();
if (owner != null)
{
return ((DomElement)this).HasAttribute(HtmlData.SelectedAttrId) ||
OwnerSelectOptions(owner).SelectedItem == this;
}
else
{
return ((DomElement)this).HasAttribute(HtmlData.SelectedAttrId);
}
}
set
{
var owner = OptionOwner();
if (owner != null)
{
if (value)
{
OwnerSelectOptions(owner).SelectedItem = (DomElement)this;
}
else
{
((DomElement)this).RemoveAttribute(HtmlData.SelectedAttrId);
}
}
else
{
((DomElement)this).SetAttribute(HtmlData.SelectedAttrId);
}
}
}
private IDomElement OptionOwner()
{
var node = this.ParentNode == null ?
null :
this.ParentNode.NodeNameID == HtmlData.tagSELECT ?
this.ParentNode :
this.ParentNode.ParentNode == null ?
null :
this.ParentNode.ParentNode.NodeNameID == HtmlData.tagSELECT ?
this.ParentNode.ParentNode :
null;
return (IDomElement)node;
}
private HTMLOptionsCollection OwnerSelectOptions()
{
var node = OptionOwner();
if (node == null)
{
throw new InvalidOperationException("The selected property only applies to valid OPTION nodes within a SELECT node");
}
return OwnerSelectOptions(node);
}
private HTMLOptionsCollection OwnerSelectOptions(IDomElement owner)
{
return new HTMLOptionsCollection((IDomElement)owner);
}
}
}
| 29.898305 | 133 | 0.445767 | [
"MIT"
] | dturkenk/CsQuery | source/CsQuery/Dom/Implementation/HtmlElements/HTMLOptionElement.cs | 5,294 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Stripe
{
public class StripeChargeUpdateOptions
{
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("fraud_details")]
public Dictionary<string, string> FraudDetails { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
[JsonProperty("receipt_email")]
public string ReceiptEmail { get; set; }
}
} | 26.05 | 68 | 0.650672 | [
"Apache-2.0"
] | HilalRather/stripe.net | src/Stripe.net/Services/Charges/StripeChargeUpdateOptions.cs | 523 | C# |
#region License
//
// NodeStack.cs January 2010
//
// Copyright (C) 2010, Niall Gallagher <niallg@users.sf.net>
//
// 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
// 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
#region Using directives
using System;
using Enumeration = System.Collections.Generic.IEnumerable<String>;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>NodeStack</c> object is used to represent a stack
/// of DOM nodes. Stacking DOM nodes is required to determine where
/// within a stream of nodes you currently are. It allows a reader
/// to produce end events when a node is popped from the stack.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Stream.DocumentReader
/// </seealso>
class NodeStack : Stack<Node>{
/// <summary>
/// Constructor for the <c>NodeStack</c> object. This will
/// create a stack for holding DOM nodes. To ensure that the
/// initial size is enough to cope with typical XML documents it
/// is set large enough to cope with reasonably deep elements.
/// </summary>
public NodeStack() : base(6) {
}
public abstract Enumeration iterator();
}
}
| 35.755556 | 70 | 0.693599 | [
"Apache-2.0"
] | AMCON-GmbH/simplexml | port/src/main/Xml/Stream/NodeStack.cs | 1,609 | C# |
using System.IO;
using RimWorld;
namespace SaveStorageSettings.Dialog {
// Bills
public class LoadBillDialog : LoadDialog {
public enum LoadType {
Replace,
Append,
}
public BillStack BillStack { get; set; }
private readonly bool Append;
public LoadBillDialog(string type, BillStack billStack, bool append) : base(type) {
Append = append;
BillStack = billStack;
}
protected override void DoFileInteraction(FileInfo fi) {
if (!fi.Exists) return;
BillContainer container = new BillContainer(BillStack, Append);
container.Load(fi);
base.Close();
}
}
}
| 22.78125 | 91 | 0.580247 | [
"MIT"
] | Jay184/rimworld-SaveStorageSettings | Source/Dialog/LoadDialog/LoadBillDialog.cs | 731 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace SA
{
public abstract class BaseInstructionSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[Header("Raycast Target (Drops.)")]
public Image _raycastTargetImg;
[Header("Highlighter (Drops.)")]
public Image highlighterImg;
public Canvas highlighterCanvas;
[Header("Selector (Drops.)")]
public Canvas selectorCanvas;
[Header("Status.")]
[ReadOnlyInspector] public int slotNumber;
[ReadOnlyInspector] public bool isSelected;
#region Refs.
[Header("Ref.")]
[ReadOnlyInspector] public InstructionMenuManager _instructionMenuManager;
#endregion
#region On Current Slot.
public void OnCurrentSlot()
{
ShowHighlighter();
}
#endregion
#region Off Current Slot.
public void OffCurrentSlot()
{
if (!isSelected)
HideHighlighter();
}
#endregion
#region On Pointer Enter.
public void OnPointerEnter(PointerEventData eventData)
{
_instructionMenuManager.GetCurrentSlotByPointerEvent(this);
}
#endregion
#region On Pointer Exit.
public void OnPointerExit(PointerEventData eventData)
{
_instructionMenuManager.isCursorOverSelection = false;
}
#endregion
#region On Select Slot.
public void OnFirstSelectSlot()
{
highlighterImg.color = _instructionMenuManager._slotClickOutColor;
ShowHighlighter();
ShowSelector();
OnSelectSlot();
}
public abstract void OnSelectSlot();
protected void BaseOnSelectSlot()
{
isSelected = true;
DisableRaycastTarget();
}
#endregion
#region Off Select Slot.
public void OffSelectSlot()
{
isSelected = false;
highlighterImg.color = _instructionMenuManager._slotHoverColor;
HideHighlighter();
HideSelector();
EnableRaycastTarget();
}
#endregion
#region Show / Hide HighLighter.
void ShowHighlighter()
{
highlighterCanvas.enabled = true;
}
void HideHighlighter()
{
highlighterCanvas.enabled = false;
}
#endregion
#region Show / Hide Selector.
public void ShowSelector()
{
selectorCanvas.enabled = true;
}
public void HideSelector()
{
selectorCanvas.enabled = false;
}
#endregion
#region Enable / Disable Raycast.
void EnableRaycastTarget()
{
_raycastTargetImg.raycastTarget = true;
}
void DisableRaycastTarget()
{
_raycastTargetImg.raycastTarget = false;
}
#endregion
public abstract void SetCurrentInstructPage();
}
} | 25.222222 | 104 | 0.576778 | [
"MIT"
] | Amulet-Games/VolunsTale-Codes-Repository | Assets/Scripts/Managers/MultiScenes_Managers/Menu_Managers/SubSelectionMenus/InstructionMenu/InstructionSlots/BaseInstructionSlot.cs | 3,180 | C# |
namespace GUI
{
partial class frmConsultaCliente
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dgvDados = new System.Windows.Forms.DataGridView();
this.btLocalizar = new System.Windows.Forms.Button();
this.txtValor = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbCpf = new System.Windows.Forms.RadioButton();
this.rbNome = new System.Windows.Forms.RadioButton();
((System.ComponentModel.ISupportInitialize)(this.dgvDados)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// dgvDados
//
this.dgvDados.AllowUserToAddRows = false;
this.dgvDados.AllowUserToDeleteRows = false;
this.dgvDados.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvDados.Location = new System.Drawing.Point(11, 100);
this.dgvDados.Margin = new System.Windows.Forms.Padding(2);
this.dgvDados.Name = "dgvDados";
this.dgvDados.ReadOnly = true;
this.dgvDados.RowTemplate.Height = 24;
this.dgvDados.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvDados.Size = new System.Drawing.Size(724, 393);
this.dgvDados.TabIndex = 11;
this.dgvDados.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvDados_CellDoubleClick);
//
// btLocalizar
//
this.btLocalizar.BackColor = System.Drawing.SystemColors.ButtonHighlight;
this.btLocalizar.Image = global::GUI.Properties.Resources.localizar3_fw;
this.btLocalizar.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btLocalizar.Location = new System.Drawing.Point(147, 55);
this.btLocalizar.Margin = new System.Windows.Forms.Padding(2);
this.btLocalizar.Name = "btLocalizar";
this.btLocalizar.Size = new System.Drawing.Size(588, 40);
this.btLocalizar.TabIndex = 10;
this.btLocalizar.Text = "Localizar";
this.btLocalizar.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btLocalizar.UseVisualStyleBackColor = false;
this.btLocalizar.Click += new System.EventHandler(this.btLocalizar_Click);
//
// txtValor
//
this.txtValor.Location = new System.Drawing.Point(146, 29);
this.txtValor.Margin = new System.Windows.Forms.Padding(2);
this.txtValor.Name = "txtValor";
this.txtValor.Size = new System.Drawing.Size(589, 20);
this.txtValor.TabIndex = 9;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(144, 12);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(49, 13);
this.label1.TabIndex = 8;
this.label1.Text = "Localizar";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbCpf);
this.groupBox1.Controls.Add(this.rbNome);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(127, 83);
this.groupBox1.TabIndex = 31;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Consultar por";
//
// rbCpf
//
this.rbCpf.AutoSize = true;
this.rbCpf.Location = new System.Drawing.Point(15, 49);
this.rbCpf.Name = "rbCpf";
this.rbCpf.Size = new System.Drawing.Size(77, 17);
this.rbCpf.TabIndex = 0;
this.rbCpf.Text = "CPF/CNPJ";
this.rbCpf.UseVisualStyleBackColor = true;
//
// rbNome
//
this.rbNome.AutoSize = true;
this.rbNome.Checked = true;
this.rbNome.Location = new System.Drawing.Point(15, 22);
this.rbNome.Name = "rbNome";
this.rbNome.Size = new System.Drawing.Size(53, 17);
this.rbNome.TabIndex = 0;
this.rbNome.TabStop = true;
this.rbNome.Text = "Nome";
this.rbNome.UseVisualStyleBackColor = true;
//
// frmConsultaCliente
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(746, 501);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.dgvDados);
this.Controls.Add(this.btLocalizar);
this.Controls.Add(this.txtValor);
this.Controls.Add(this.label1);
this.Name = "frmConsultaCliente";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Consulta de Cliente";
this.Load += new System.EventHandler(this.frmConsultaCliente_Load);
((System.ComponentModel.ISupportInitialize)(this.dgvDados)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dgvDados;
private System.Windows.Forms.Button btLocalizar;
private System.Windows.Forms.TextBox txtValor;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbCpf;
private System.Windows.Forms.RadioButton rbNome;
}
} | 45.019355 | 130 | 0.593007 | [
"MIT"
] | AndreLucyo2/ControleDeEstoque_Estudo01 | GUI/frmConsultaCliente.Designer.cs | 6,980 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using NuGet.Shared;
namespace NuGet.Packaging.Core
{
/**
* It is important that this type remains immutable due to the cloning of package specs
**/
public class PackageType : IEquatable<PackageType>
{
public static readonly Version EmptyVersion = new Version(0, 0);
public static readonly PackageType Legacy = new PackageType("Legacy", version: EmptyVersion);
public static readonly PackageType DotnetCliTool = new PackageType("DotnetCliTool", version: EmptyVersion);
public static readonly PackageType Dependency = new PackageType("Dependency", version: EmptyVersion);
public PackageType(string name, Version version)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(Strings.StringCannotBeNullOrEmpty, nameof(name));
}
if (version == null)
{
throw new ArgumentNullException(nameof(version));
}
Name = name;
Version = version;
}
public string Name { get; }
public Version Version { get; }
public override bool Equals(object obj)
{
return Equals(obj as PackageType);
}
public static bool operator ==(PackageType a, PackageType b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (((object)a == null) || ((object)b == null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(PackageType a, PackageType b)
{
return !(a == b);
}
public bool Equals(PackageType other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return
Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) &&
Version == other.Version;
}
public override int GetHashCode()
{
var combiner = new HashCodeCombiner();
combiner.AddObject(Name, StringComparer.OrdinalIgnoreCase);
combiner.AddObject(Version);
return combiner.CombinedHash;
}
}
}
| 28.130435 | 115 | 0.547913 | [
"Apache-2.0"
] | clairernovotny/NuGet.Client | src/NuGet.Core/NuGet.Packaging.Core/PackageType.cs | 2,588 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Meshram.Core.Coder
{
public sealed class StandardGeoMeshCoderConfig : IModuleConfig
{
public GeoCode Corner1 { get; set; }
public GeoCode Corner2 { get; set; }
public IEnumerable<IntegerGeoElement> Dividers { get; set; }
private IEnumerable<GeoCode> _meshes = null;
public IEnumerable<GeoCode> Meshes
{
get
{
if (_meshes == null
&& new object[] { Corner1, Corner2, Dividers }.All(o => o != null))
{
_meshes = Dividers
.Aggregate(new List<GeoCode>(),
(lst, next) =>
{
var prevLongitude = !lst.Any() ?
Math.Abs(this.Corner1.Longitude - this.Corner2.Longitude) : lst.Last().Longitude;
var prevLatitude = !lst.Any() ?
Math.Abs(this.Corner1.Latitude - this.Corner2.Latitude) : lst.Last().Latitude;
var newMesh = new GeoCode
{
Longitude = prevLongitude / next.Longitude,
Latitude = prevLatitude / next.Latitude
};
lst.Add(newMesh);
return lst;
});
}
return _meshes;
}
}
public void Validate()
{
ValidationRuleAttribute.Validate(this, Array.Empty<object>());
}
[ValidationRule("Need Corners")]
public bool NeedConersRule()
{
return new[] { Corner1, Corner2 }.All(x => x != null);
}
[ValidationRule("Need Dividers")]
public bool NeedDividers()
{
return (Dividers != null) && Dividers.Any();
}
public IModuleConfig GetDefaultConfig()
{
return new StandardGeoMeshCoderConfig()
{
Corner1 = new GeoCode() { Longitude = 0, Latitude = 0 },
Corner2 = new GeoCode() { Longitude = 180, Latitude = 180 },
Dividers = new List<IntegerGeoElement>()
{
new IntegerGeoElement() { Latitude = 18, Longitude = 18 },
new IntegerGeoElement() { Latitude = 10, Longitude = 10 },
new IntegerGeoElement() { Latitude = 50, Longitude = 50 },
new IntegerGeoElement() { Latitude = 50, Longitude = 50 },
new IntegerGeoElement() { Latitude = 50, Longitude = 50 },
new IntegerGeoElement() { Latitude = 50, Longitude = 50 },
}
};
}
}
} | 39.479452 | 113 | 0.465649 | [
"MIT"
] | kazumatu981/Meshram | Meshram.Core/Coder/StandardGeoMeshCoderConfig.cs | 2,882 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using UnityEditor;
using UnityToCustomEngineExporter.Editor.Urho3D;
using Object = UnityEngine.Object;
namespace UnityToCustomEngineExporter.Editor
{
public abstract class AbstractDestinationEngine
{
private readonly CancellationToken _cancellationToken;
private readonly HashSet<string> _visitedAssetPaths = new HashSet<string>();
public AbstractDestinationEngine(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
}
public IEnumerable<ProgressBarReport> ExportAssets(string[] assetGUIDs, PrefabContext prefabContext)
{
yield return "Preparing " + assetGUIDs.Length + " assets to export";
foreach (var guid in assetGUIDs)
EditorTaskScheduler.Default.ScheduleForegroundTask(() =>
ExportAssetsAtPath(AssetDatabase.GUIDToAssetPath(guid), prefabContext));
}
public void ScheduleAssetExport(Object asset, PrefabContext prefabContext)
{
EditorTaskScheduler.Default.ScheduleForegroundTask(() => ExportAsset(asset, prefabContext));
}
public void ScheduleAssetExportAtPath(string assetPath, PrefabContext prefabContext)
{
EditorTaskScheduler.Default.ScheduleForegroundTask(() => ExportAssetsAtPath(assetPath, prefabContext));
}
protected abstract void ExportAssetBlock(string assetPath, Type mainType, Object[] assets,
PrefabContext prefabContext);
protected abstract IEnumerable<ProgressBarReport> ExportDynamicAsset(Object asset, PrefabContext prefabContext);
private IEnumerable<ProgressBarReport> ExportAsset(Object asset, PrefabContext prefabContext)
{
var assetPath = AssetDatabase.GetAssetPath(asset);
if (string.IsNullOrWhiteSpace(assetPath))
return ExportDynamicAsset(asset, prefabContext);
if (assetPath == "Library/unity default resources" || assetPath == "Resources/unity_builtin_extra")
return ExportUnityDefaultResource(asset, assetPath);
return ExportAssetsAtPath(assetPath, prefabContext);
}
private IEnumerable<ProgressBarReport> ExportUnityDefaultResource(Object asset, string assetPath)
{
yield return asset.name;
ExportAssetBlock(assetPath, asset.GetType(), new[] {asset}, null);
}
private IEnumerable<ProgressBarReport> ExportAssetsAtPath(string assetPath, PrefabContext prefabContext)
{
if (string.IsNullOrWhiteSpace(assetPath))
yield break;
if (_cancellationToken.IsCancellationRequested)
yield break;
if (!_visitedAssetPaths.Add(assetPath))
yield break;
if (!File.Exists(assetPath) && !Directory.Exists(assetPath))
yield break;
var attrs = File.GetAttributes(assetPath);
if (attrs.HasFlag(FileAttributes.Directory))
{
foreach (var guid in AssetDatabase.FindAssets("", new[] {assetPath}))
EditorTaskScheduler.Default.ScheduleForegroundTask(() =>
ExportAssetsAtPath(AssetDatabase.GUIDToAssetPath(guid), prefabContext));
yield break;
}
yield return "Loading " + assetPath;
var assets = ExportUtils.LoadAllAssetsAtPath(assetPath);
yield return "Exporting " + assetPath;
ExportAssetBlock(assetPath, AssetDatabase.GetMainAssetTypeAtPath(assetPath), assets, prefabContext);
}
}
} | 43.823529 | 120 | 0.669262 | [
"MIT"
] | elix22/Unity2Urho | Editor/AbstractDestinationEngine.cs | 3,727 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadROSoftDelete.Business.ERCLevel
{
/// <summary>
/// H11Level111111ReChild (read only object).<br/>
/// This is a generated base class of <see cref="H11Level111111ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="H10Level11111"/> collection.
/// </remarks>
[Serializable]
public partial class H11Level111111ReChild : ReadOnlyBase<H11Level111111ReChild>
{
#region Business Properties
/// <summary>
/// Gets or sets the Level_1_1_1_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1_1_1_1 Child Name.</value>
public string Level_1_1_1_1_1_1_Child_Name { get; private set; }
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="H11Level111111ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="cQarentID2">The CQarentID2 parameter of the H11Level111111ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="H11Level111111ReChild"/> object.</returns>
internal static H11Level111111ReChild GetH11Level111111ReChild(int cQarentID2)
{
return DataPortal.FetchChild<H11Level111111ReChild>(cQarentID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H11Level111111ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private H11Level111111ReChild()
{
// Prevent direct creation
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="H11Level111111ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="cQarentID2">The CQarent ID2.</param>
protected void Child_Fetch(int cQarentID2)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH11Level111111ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CQarentID2", cQarentID2).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, cQarentID2);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
BusinessRules.CheckRules();
}
}
/// <summary>
/// Loads a <see cref="H11Level111111ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
Level_1_1_1_1_1_1_Child_Name = dr.GetString("Level_1_1_1_1_1_1_Child_Name");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| 33.850394 | 109 | 0.567574 | [
"MIT"
] | CslaGenFork/CslaGenFork | tags/DeepLoad sample v.1.0.0/SelfLoadROSoftDelete.Business/ERCLevel/H11Level111111ReChild.Designer.cs | 4,299 | C# |
using System;
using Baseline.Dates;
using Timer = System.Timers.Timer;
namespace AdvisoryLockSpike.Election
{
public class LeaderSettings<T> where T : IActiveProcess
{
public TimeSpan OwnershipPollingTime { get; set; } = 5.Seconds();
// It's a random number here so that if you spin
// up multiple nodes at the same time, they won't
// all collide trying to grab ownership at the exact
// same time
public TimeSpan FirstPollingTime { get; set; }
= new Random().Next(100, 3000).Milliseconds();
// This would be something meaningful
public int LockId { get; set; }
public string ConnectionString { get; set; }
}
} | 32 | 73 | 0.620924 | [
"MIT"
] | jeremydmiller/AdvisoryLockSpike | Election/LeaderSettings.cs | 736 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.DirectX;
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE"]/*' />
public enum D2D1_BITMAPSOURCE_INTERPOLATION_MODE : uint
{
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_NEAREST_NEIGHBOR"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_NEAREST_NEIGHBOR = 0,
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_LINEAR"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_LINEAR = 1,
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_CUBIC"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_CUBIC = 2,
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_FANT"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_FANT = 6,
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_MIPMAP_LINEAR"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_MIPMAP_LINEAR = 7,
/// <include file='D2D1_BITMAPSOURCE_INTERPOLATION_MODE.xml' path='doc/member[@name="D2D1_BITMAPSOURCE_INTERPOLATION_MODE.D2D1_BITMAPSOURCE_INTERPOLATION_MODE_FORCE_DWORD"]/*' />
D2D1_BITMAPSOURCE_INTERPOLATION_MODE_FORCE_DWORD = 0xffffffff,
}
| 67.37931 | 187 | 0.815763 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/d2d1effects/D2D1_BITMAPSOURCE_INTERPOLATION_MODE.cs | 1,956 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Domain.Interfaces {
public interface IEntity {
public int? Id { get; }
public bool Deleted { get; set; }
}
}
| 18.692308 | 35 | 0.736626 | [
"MIT"
] | benjaminvanrenterghem/CQRS_Base | Domain/Interfaces/IEntity.cs | 245 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
var app = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = Environments.Development }).Build();
app.UseStatusCodePages();
app.MapGet("/", () =>
{
return Results.Text(@"
<html>
<head>
<link rel=""stylesheet"" href=""https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css"" decimalegrity=""sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU"" crossorigin=""anonymous"">
</head>
<body>
<h1>Sample for {decimal}, {float}, and {double} route constraints</h1>
<ul>
<li>/{id:decimal} <a href=""/decimal/10"">/decimal/10</a></li>
<li>/{id:decimal} <a href=""/decimal/-20"">/decimal/-20</a></li>
<li>/{id:decimal} <a href=""/decimal/10f"">/decimal/10f</a> (404)</li>
<li>/{id:decimal} <a href=""/decimal/10_000"">/decimal/10_000</a> (404)</li>
<li>/{id:decimal} <a href=""/decimal/10.4"">/decimal/10.4</a> (404)</li>
</ul>
<ul>
<li>/{id:float} <a href=""/float/10"">/float/10</a></li>
<li>/{id:float} <a href=""/float/-20"">/float/-20</a></li>
<li>/{id:float} <a href=""/float/10f"">/float/10f</a> (404)</li>
<li>/{id:float} <a href=""/float/10_000"">/float/10_000</a> (404)</li>
<li>/{id:float} <a href=""/float/10.4"">/float/10.4</a> (404)</li>
</ul>
<ul>
<li>/{id:double} <a href=""/double/10"">/double/10</a></li>
<li>/{id:double} <a href=""/double/-20"">/double/-20</a></li>
<li>/{id:double} <a href=""/double/10f"">/double/10f</a> (404)</li>
<li>/{id:double} <a href=""/double/10_000"">/double/10_000</a> (404)</li>
<li>/{id:double} <a href=""/double/10.4"">/double/10.4</a> (404)</li>
</ul>
</body>
</html>
", "text/html");
});
app.MapGet("decimal/{id:decimal}", (decimal id) => id.ToString());
app.MapGet("float/{yid:float}", (float id) => id.ToString());
app.MapGet("double/{id:double}", (double id) => id.ToString());
app.Run(); | 47.645833 | 234 | 0.530826 | [
"MIT"
] | BearerPipelineTest/practical-aspnetcore | projects/minimal-api/route-constraints-decimal/Program.cs | 2,287 | C# |
using Discord.Audio;
using Discord.Rest;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based voice channel in a guild.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketVoiceChannel : SocketGuildChannel, IVoiceChannel, ISocketAudioChannel
{
#region SocketVoiceChannel
/// <inheritdoc />
public int Bitrate { get; private set; }
/// <inheritdoc />
public int? UserLimit { get; private set; }
/// <inheritdoc />
public ulong? CategoryId { get; private set; }
/// <summary>
/// Gets the parent (category) channel of this channel.
/// </summary>
/// <returns>
/// A category channel representing the parent of this channel; <c>null</c> if none is set.
/// </returns>
public ICategoryChannel Category
=> CategoryId.HasValue ? Guild.GetChannel(CategoryId.Value) as ICategoryChannel : null;
/// <inheritdoc />
public string Mention => MentionUtils.MentionChannel(Id);
/// <inheritdoc />
public Task SyncPermissionsAsync(RequestOptions options = null)
=> ChannelHelper.SyncPermissionsAsync(this, Discord, options);
/// <summary>
/// Gets a collection of users that are currently connected to this voice channel.
/// </summary>
/// <returns>
/// A read-only collection of users that are currently connected to this voice channel.
/// </returns>
public override IReadOnlyCollection<SocketGuildUser> Users
=> Guild.Users.Where(x => x.VoiceChannel?.Id == Id).ToImmutableArray();
internal SocketVoiceChannel(DiscordSocketClient discord, ulong id, SocketGuild guild)
: base(discord, id, guild)
{
}
internal new static SocketVoiceChannel Create(SocketGuild guild, ClientState state, Model model)
{
var entity = new SocketVoiceChannel(guild.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
/// <inheritdoc />
internal override void Update(ClientState state, Model model)
{
base.Update(state, model);
CategoryId = model.CategoryId;
Bitrate = model.Bitrate.Value;
UserLimit = model.UserLimit.Value != 0 ? model.UserLimit.Value : (int?)null;
}
/// <inheritdoc />
public Task ModifyAsync(Action<VoiceChannelProperties> func, RequestOptions options = null)
=> ChannelHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc />
public async Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false)
{
return await Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task DisconnectAsync()
=> await Guild.DisconnectAudioAsync();
/// <inheritdoc />
public async Task ModifyAsync(Action<AudioChannelProperties> func, RequestOptions options = null)
{
await Guild.ModifyAudioAsync(Id, func, options).ConfigureAwait(false);
}
/// <inheritdoc />
public override SocketGuildUser GetUser(ulong id)
{
var user = Guild.GetUser(id);
if (user?.VoiceChannel?.Id == Id)
return user;
return null;
}
#endregion
#region Invites
/// <inheritdoc />
public async Task<IInviteMetadata> CreateInviteAsync(int? maxAge = 86400, int? maxUses = null, bool isTemporary = false, bool isUnique = false, RequestOptions options = null)
=> await ChannelHelper.CreateInviteAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, options).ConfigureAwait(false);
/// <inheritdoc />
public async Task<IInviteMetadata> CreateInviteToApplicationAsync(ulong applicationId, int? maxAge, int? maxUses = default(int?), bool isTemporary = false, bool isUnique = false, RequestOptions options = null)
=> await ChannelHelper.CreateInviteToApplicationAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, applicationId, options).ConfigureAwait(false);
/// <inheritdoc />
public virtual async Task<IInviteMetadata> CreateInviteToApplicationAsync(DefaultApplications application, int? maxAge = 86400, int? maxUses = default(int?), bool isTemporary = false, bool isUnique = false, RequestOptions options = null)
=> await ChannelHelper.CreateInviteToApplicationAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, (ulong)application, options);
/// <inheritdoc />
public async Task<IInviteMetadata> CreateInviteToStreamAsync(IUser user, int? maxAge, int? maxUses = default(int?), bool isTemporary = false, bool isUnique = false, RequestOptions options = null)
=> await ChannelHelper.CreateInviteToStreamAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, user, options).ConfigureAwait(false);
/// <inheritdoc />
public async Task<IReadOnlyCollection<IInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
=> await ChannelHelper.GetInvitesAsync(this, Discord, options).ConfigureAwait(false);
private string DebuggerDisplay => $"{Name} ({Id}, Voice)";
internal new SocketVoiceChannel Clone() => MemberwiseClone() as SocketVoiceChannel;
#endregion
#region IGuildChannel
/// <inheritdoc />
Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IGuildUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable();
#endregion
#region INestedChannel
/// <inheritdoc />
Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options)
=> Task.FromResult(Category);
#endregion
}
}
| 46.971014 | 245 | 0.656587 | [
"MIT"
] | Bakersbakebread/Discord.Net | src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs | 6,482 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Btn_LoadLevel : Btn_MainMenu
{
Button btn;
public int levelId;
public string levelName;
public string levelDescription;
public Sprite levelSprite;
public GameObject lockedFilter;
public bool unlocked;
new void Start()
{
base.Start();
btn = GetComponent<Button>();
btn.onClick.AddListener(OnClick);
text.text = levelName;
HandleLock();
}
public void OnClick()
{
if (unlocked)
{
Level level = new Level(levelName, levelDescription, levelId);
MainMenuManager.INSTANCE.OnLevelSelected(level);
}
}
void HandleLock()
{
int maxLevelCompleted = PlayerPrefs.GetInt("MaxLevelCompleted", 0); // level ID starts from 1
unlocked = maxLevelCompleted + 1 >= levelId;
lockedFilter.SetActive(!unlocked);
}
public void SetLevel(Level level) => text.text = level.levelName;
}
| 23.804348 | 101 | 0.649315 | [
"MIT"
] | timmychan97/HexagonTowerDefense | Assets/Scripts/MainMenu/Btn_LoadLevel.cs | 1,097 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Converters;
using Microsoft.Azure.WebJobs.Host.Protocols;
namespace Microsoft.Azure.WebJobs.Host.Bindings.Data
{
internal class ClassDataBinding<TBindingData> : IBinding
where TBindingData : class
{
private static readonly IObjectToTypeConverter<TBindingData> _converter =
ObjectToTypeConverterFactory.CreateForClass<TBindingData>();
private readonly string _parameterName;
private readonly IArgumentBinding<TBindingData> _argumentBinding;
public ClassDataBinding(string parameterName, IArgumentBinding<TBindingData> argumentBinding)
{
_parameterName = parameterName;
_argumentBinding = argumentBinding;
}
public bool FromAttribute
{
get { return false; }
}
private Task<IValueProvider> BindAsync(TBindingData bindingDataItem, ValueBindingContext context)
{
return _argumentBinding.BindAsync(bindingDataItem, context);
}
public Task<IValueProvider> BindAsync(object value, ValueBindingContext context)
{
TBindingData typedValue;
if (!_converter.TryConvert(value, out typedValue))
{
throw new InvalidOperationException("Unable to convert value to " + typeof(TBindingData).Name + ".");
}
return BindAsync(typedValue, context);
}
public Task<IValueProvider> BindAsync(BindingContext context)
{
IReadOnlyDictionary<string, object> bindingData = context.BindingData;
if (bindingData == null || !bindingData.ContainsKey(_parameterName))
{
throw new InvalidOperationException(
"Binding data does not contain expected value '" + _parameterName + "'.");
}
object untypedValue = bindingData[_parameterName];
if (!(untypedValue is TBindingData))
{
throw new InvalidOperationException("Binding data for '" + _parameterName +
"' is not of expected type " + typeof(TBindingData).Name + ".");
}
TBindingData typedValue = (TBindingData)untypedValue;
return BindAsync(typedValue, context.ValueContext);
}
public ParameterDescriptor ToParameterDescriptor()
{
return new BindingDataParameterDescriptor
{
Name = _parameterName
};
}
}
}
| 34.9625 | 117 | 0.641759 | [
"Apache-2.0"
] | alpaix/azure-jobs | src/Microsoft.Azure.WebJobs.Host/Bindings/Data/ClassDataBinding.cs | 2,799 | 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.Compute.V20191101.Inputs
{
/// <summary>
/// Encryption at rest settings for disk or snapshot
/// </summary>
public sealed class EncryptionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// ResourceId of the disk encryption set to use for enabling encryption at rest.
/// </summary>
[Input("diskEncryptionSetId")]
public Input<string>? DiskEncryptionSetId { get; set; }
/// <summary>
/// The type of key used to encrypt the data of the disk.
/// </summary>
[Input("type")]
public InputUnion<string, Pulumi.AzureNextGen.Compute.V20191101.EncryptionType>? Type { get; set; }
public EncryptionArgs()
{
}
}
}
| 30.314286 | 107 | 0.64656 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20191101/Inputs/EncryptionArgs.cs | 1,061 | C# |
namespace MapGeneration.Core.LayoutGenerators
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using ConfigurationSpaces;
using GeneralAlgorithms.Algorithms.Graphs;
using GeneralAlgorithms.DataStructures.Common;
using GeneralAlgorithms.DataStructures.Polygons;
using Interfaces.Core.ChainDecompositions;
using Interfaces.Core.ConfigurationSpaces;
using Interfaces.Core.GeneratorPlanners;
using Interfaces.Core.LayoutConverters;
using Interfaces.Core.LayoutEvolvers;
using Interfaces.Core.LayoutGenerator;
using Interfaces.Core.LayoutOperations;
using Interfaces.Core.Layouts;
using Interfaces.Core.MapDescriptions;
using Interfaces.Utils;
/// <inheritdoc cref="ILayoutGenerator{TMapDescription,TNode}" />
/// <summary>
/// Chain based layout generator.
/// </summary>
/// <typeparam name="TMapDescription">Type of the map description.</typeparam>
/// <typeparam name="TLayout">Type of the layout that will be used in the process.</typeparam>
/// <typeparam name="TNode">Type of nodes in the map description.</typeparam>
/// <typeparam name="TConfiguration">Type of configuration used.</typeparam>
public class ChainBasedGenerator<TMapDescription, TLayout, TNode, TConfiguration, TOutputLayout> : IBenchmarkableLayoutGenerator<TMapDescription, TOutputLayout>, IObservableGenerator<TMapDescription, TOutputLayout>, ICancellable
where TMapDescription : IMapDescription<TNode>
where TLayout : ILayout<TNode, TConfiguration>, ISmartCloneable<TLayout>
{
// Algorithms
private IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace> configurationSpaces;
private IChainDecomposition<TNode> chainDecomposition;
private ILayoutEvolver<TLayout, TNode> layoutEvolver;
private IChainBasedLayoutOperations<TLayout, TNode> layoutOperations;
private IGeneratorPlanner<TLayout> generatorPlanner;
private ILayoutConverter<TLayout, TOutputLayout> layoutConverter;
// Creators
private Func<
TMapDescription,
IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>
> configurationSpacesCreator;
private Func<
TMapDescription,
IChainDecomposition<TNode>
> chainDecompositionCreator;
private Func<
TMapDescription,
IChainBasedLayoutOperations<TLayout, TNode>,
ILayoutEvolver<TLayout, TNode>
> layoutEvolverCreator;
private Func<
TMapDescription,
IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>,
IChainBasedLayoutOperations<TLayout, TNode>
> layoutOperationsCreator;
private Func<
TMapDescription,
IGeneratorPlanner<TLayout>
> generatorPlannerCreator;
private Func<
TMapDescription,
IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>,
ILayoutConverter<TLayout, TOutputLayout>
> layoutConverterCreator;
private Func<
TMapDescription,
TLayout
> initialLayoutCreator;
// Debug and benchmark variables
private long timeFirst;
private long timeTotal;
private int layoutsCount;
private readonly Stopwatch stopwatch = new Stopwatch();
protected Random Random;
protected CancellationToken? CancellationToken;
private List<List<TNode>> chains;
private TLayout initialLayout;
private GeneratorContext context;
// Settings
protected bool BenchmarkEnabled;
protected bool LayoutValidityCheckEnabled;
protected Func<TLayout, object> EnergyDataGetter;
// Events
/// <inheritdoc />
public event Action<TOutputLayout> OnPerturbed;
/// <inheritdoc />
public event Action<TOutputLayout> OnPartialValid;
/// <inheritdoc />
public event Action<TOutputLayout> OnValid;
private readonly GraphUtils graphUtils = new GraphUtils();
public ChainBasedGenerator()
{
PrepareEnergyDataGetter();
}
public IList<TOutputLayout> GetLayouts(TMapDescription mapDescription, int numberOfLayouts)
{
var graph = mapDescription.GetGraph();
if (graph.VerticesCount < 2)
throw new ArgumentException("Given mapDescription must contain at least two nodes.", nameof(mapDescription));
if (!graphUtils.IsConnected(graph))
throw new ArgumentException("Given mapDescription must represent a connected graph.", nameof(mapDescription));
if (!graphUtils.IsPlanar(graph))
throw new ArgumentException("Given mapDescription must represent a planar graph.", nameof(mapDescription));
// Create instances and inject the random generator and the cancellation token if possible
configurationSpaces = configurationSpacesCreator(mapDescription);
TryInjectRandomAndCancellationToken(configurationSpaces);
chainDecomposition = chainDecompositionCreator(mapDescription);
TryInjectRandomAndCancellationToken(chainDecomposition);
initialLayout = initialLayoutCreator(mapDescription);
TryInjectRandomAndCancellationToken(initialLayout);
generatorPlanner = generatorPlannerCreator(mapDescription);
TryInjectRandomAndCancellationToken(generatorPlanner);
layoutOperations = layoutOperationsCreator(mapDescription, configurationSpaces);
TryInjectRandomAndCancellationToken(layoutOperations);
layoutConverter = layoutConverterCreator(mapDescription, configurationSpaces);
TryInjectRandomAndCancellationToken(layoutConverter);
layoutEvolver = layoutEvolverCreator(mapDescription, layoutOperations);
TryInjectRandomAndCancellationToken(layoutEvolver);
// Restart stopwatch
stopwatch.Restart();
chains = chainDecomposition.GetChains(graph);
context = new GeneratorContext();
RegisterEventHandlers();
// TODO: handle number of layouts to be evolved - who should control that? generator or planner?
// TODO: handle context.. this is ugly
var layouts = generatorPlanner.Generate(initialLayout, numberOfLayouts, chains.Count,
(layout, chainNumber, numOfLayouts) => layoutEvolver.Evolve(AddChain(layout, chainNumber), chains[chainNumber], numOfLayouts), context);
// Stop stopwatch and prepare benchmark info
stopwatch.Stop();
timeTotal = stopwatch.ElapsedMilliseconds;
layoutsCount = layouts.Count;
// Reset cancellation token if it was already used
if (CancellationToken.HasValue && CancellationToken.Value.IsCancellationRequested)
{
CancellationToken = null;
}
return layouts.Select(x => layoutConverter.Convert(x, true)).ToList();
}
/// <summary>
/// Adds a next chain to a given layout.
/// </summary>
/// <param name="layout"></param>
/// <param name="chainNumber"></param>
/// <returns></returns>
protected virtual TLayout AddChain(TLayout layout, int chainNumber)
{
if (chainNumber >= chains.Count)
throw new ArgumentException("Chain number is bigger than then number of chains.", nameof(chainNumber));
layout = layout.SmartClone();
layoutOperations.AddChain(layout, chains[chainNumber], true);
return layout;
}
#region Event handlers
private void RegisterEventHandlers()
{
// Register validity checks
layoutEvolver.OnPerturbed -= CheckLayoutValidity;
if (LayoutValidityCheckEnabled)
{
layoutEvolver.OnPerturbed += CheckLayoutValidity;
}
// Register iterations counting
layoutEvolver.OnPerturbed -= IterationsCounterHandler;
layoutEvolver.OnPerturbed += IterationsCounterHandler;
layoutEvolver.OnPerturbed -= PerturbedLayoutsHandler;
layoutEvolver.OnPerturbed += PerturbedLayoutsHandler;
layoutEvolver.OnValid -= PartialValidLayoutsHandler;
layoutEvolver.OnValid += PartialValidLayoutsHandler;
// Setup first layout timer
timeFirst = -1;
generatorPlanner.OnLayoutGenerated -= FirstLayoutTimeHandler;
generatorPlanner.OnLayoutGenerated += FirstLayoutTimeHandler;
generatorPlanner.OnLayoutGenerated -= ValidLayoutsHandler;
generatorPlanner.OnLayoutGenerated += ValidLayoutsHandler;
}
private void FirstLayoutTimeHandler(TLayout layout)
{
if (timeFirst == -1)
{
timeFirst = stopwatch.ElapsedMilliseconds;
}
}
private void IterationsCounterHandler(TLayout layout)
{
context.IterationsCount++;
}
private void ValidLayoutsHandler(TLayout layout)
{
OnValid?.Invoke(layoutConverter.Convert(layout, true));
}
private void PartialValidLayoutsHandler(TLayout layout)
{
OnPartialValid?.Invoke(layoutConverter.Convert(layout, true));
}
private void PerturbedLayoutsHandler(TLayout layout)
{
OnPerturbed?.Invoke(layoutConverter.Convert(layout, false));
}
#endregion
#region Creators
/// <summary>
/// Sets a function that can create a layout evolver.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetLayoutEvolverCreator(Func<TMapDescription, IChainBasedLayoutOperations<TLayout, TNode>, ILayoutEvolver<TLayout, TNode>> creator)
{
layoutEvolverCreator = creator;
}
/// <summary>
/// Sets a function that can create a layout converter.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetLayoutConverterCreator(Func<TMapDescription, IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>, ILayoutConverter<TLayout, TOutputLayout>> creator)
{
layoutConverterCreator = creator;
}
/// <summary>
/// Sets a function that can create a generator planner.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetGeneratorPlannerCreator(Func<TMapDescription, IGeneratorPlanner<TLayout>> creator)
{
generatorPlannerCreator = creator;
}
/// <summary>
/// Sets a function that can create an initial layout.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetInitialLayoutCreator(Func<TMapDescription, TLayout> creator)
{
initialLayoutCreator = creator;
}
/// <summary>
/// Sets a function that can create an instance of layout operations.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetLayoutOperationsCreator(Func<TMapDescription, IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>, IChainBasedLayoutOperations<TLayout, TNode>> creator)
{
layoutOperationsCreator = creator;
}
/// <summary>
/// Sets a function that can create configuration spaces.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetConfigurationSpacesCreator(Func<TMapDescription, IConfigurationSpaces<TNode, IntAlias<GridPolygon>, TConfiguration, ConfigurationSpace>> creator)
{
configurationSpacesCreator = creator;
}
/// <summary>
/// Sets a function that can create a chain decomposition.
/// </summary>
/// <remarks>
/// Will be called on every call to GetLayouts().
/// </remarks>
/// <param name="creator"></param>
public void SetChainDecompositionCreator(Func<TMapDescription, IChainDecomposition<TNode>> creator)
{
chainDecompositionCreator = creator;
}
#endregion
/// <summary>
/// Checks whether energies and validity vectors are the same as if they are all recomputed.
/// </summary>
/// <remarks>
/// This check significantly slows down the generator.
/// </remarks>
/// <param name="enable"></param>
public void SetLayoutValidityCheck(bool enable)
{
LayoutValidityCheckEnabled = enable;
}
private void CheckLayoutValidity(TLayout layout)
{
var copy = layout.SmartClone();
layoutOperations.UpdateLayout(copy);
foreach (var vertex in layout.Graph.Vertices)
{
var isInLayout = layout.GetConfiguration(vertex, out var configurationLayout);
var isInCopy = copy.GetConfiguration(vertex, out var configurationCopy);
if (isInLayout != isInCopy)
throw new InvalidOperationException("Vertices must be either set in both or absent in both");
// Skip the check if the configuration is not set
if (!isInLayout)
continue;
if (!configurationCopy.Equals(configurationLayout))
throw new InvalidOperationException("Configurations must be equal");
}
if (EnergyDataGetter != null)
{
var energyDataLayout = EnergyDataGetter(layout);
var energyDataCopy = EnergyDataGetter(copy);
if (!energyDataLayout.Equals(energyDataCopy))
throw new InvalidOperationException("Configurations must be equal");
}
}
private void PrepareEnergyDataGetter()
{
var isEnergyLayout = typeof(TLayout).GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IEnergyLayout<,,>));
if (!isEnergyLayout)
return;
var propertyInfo = typeof(TLayout).GetProperty(nameof(IEnergyLayout<object, object, object>.EnergyData));
EnergyDataGetter = (layout) => propertyInfo.GetValue(layout);
}
/// <summary>
/// Checks if a given object is IRandomInjectable and/or ICancellable
/// and tries to inject a random generator or a cancellation token.
/// </summary>
/// <param name="o"></param>
protected void TryInjectRandomAndCancellationToken(object o)
{
if (o is IRandomInjectable randomInjectable)
{
randomInjectable.InjectRandomGenerator(Random);
}
if (CancellationToken.HasValue && o is ICancellable cancellable)
{
cancellable.SetCancellationToken(CancellationToken.Value);
}
}
/// <inheritdoc />
long IBenchmarkableLayoutGenerator<TMapDescription, TOutputLayout>.TimeFirst => timeFirst;
/// <inheritdoc />
long IBenchmarkableLayoutGenerator<TMapDescription, TOutputLayout>.TimeTotal => timeTotal;
/// <inheritdoc />
int IBenchmarkableLayoutGenerator<TMapDescription, TOutputLayout>.IterationsCount => context.IterationsCount;
/// <inheritdoc />
int IBenchmarkableLayoutGenerator<TMapDescription, TOutputLayout>.LayoutsCount => layoutsCount;
/// <inheritdoc />
public void EnableBenchmark(bool enable)
{
BenchmarkEnabled = true;
}
/// <inheritdoc />
public void InjectRandomGenerator(Random random)
{
Random = random;
}
/// <inheritdoc />
public void SetCancellationToken(CancellationToken? cancellationToken)
{
CancellationToken = cancellationToken;
}
}
} | 31.804396 | 229 | 0.748462 | [
"MIT"
] | FrancisUsher/ProceduralLevelGenerator | MapGeneration/Core/LayoutGenerators/ChainBasedGenerator.cs | 14,473 | C# |
using UnityEngine;
using System.Collections;
namespace Model.Effects
{
public class Effect_021 : Effect
{
private int barrierCount;
public int BarrierCount
{
get => barrierCount;
set => barrierCount = value;
}
public Effect_021(Unit owner, int barrierCount, int turnCount) : base(owner, 21)
{
TurnCount = turnCount;
BarrierCount = barrierCount;
}
public override int BeforeGetDamage(int damage)
{
damage = 0;
BarrierCount--;
if (BarrierCount == 0) Common.UnitAction.RemoveEffect(Owner, this);
return base.BeforeGetDamage(damage);
}
public override void OnAddThisEffect()
{
base.OnAddThisEffect();
Debug.Log($"{Owner.Name}에게 {Name}효과 {TurnCount}턴 동안 추가됨");
}
public override void OnTurnStart()
{
TurnCount--;
Debug.Log($"{Name}효과 {TurnCount}턴 남음");
if (TurnCount == 0) Common.UnitAction.RemoveEffect(Owner, this);
}
}
} | 26.069767 | 88 | 0.550401 | [
"MIT"
] | TeamJelly/Dungeon-Chess | Assets/Scripts/Model/Effects/Effect_021.cs | 1,153 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/dxcapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved. Licensed under the University of Illinois Open Source License.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop.Windows;
namespace TerraFX.Interop.DirectX;
[Guid("A005A9D9-B8BB-4594-B5C9-0E633BEC4D37")]
[NativeTypeName("struct IDxcCompiler2 : IDxcCompiler")]
[NativeInheritance("IDxcCompiler")]
public unsafe partial struct IDxcCompiler2 : IDxcCompiler2.Interface
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(0)]
public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IDxcCompiler2*, Guid*, void**, int>)(lpVtbl[0]))((IDxcCompiler2*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(1)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IDxcCompiler2*, uint>)(lpVtbl[1]))((IDxcCompiler2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(2)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IDxcCompiler2*, uint>)(lpVtbl[2]))((IDxcCompiler2*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(3)]
public HRESULT Compile(IDxcBlob* pSource, [NativeTypeName("LPCWSTR")] ushort* pSourceName, [NativeTypeName("LPCWSTR")] ushort* pEntryPoint, [NativeTypeName("LPCWSTR")] ushort* pTargetProfile, [NativeTypeName("LPCWSTR *")] ushort** pArguments, [NativeTypeName("UINT32")] uint argCount, [NativeTypeName("const DxcDefine *")] DxcDefine* pDefines, [NativeTypeName("UINT32")] uint defineCount, IDxcIncludeHandler* pIncludeHandler, IDxcOperationResult** ppResult)
{
return ((delegate* unmanaged<IDxcCompiler2*, IDxcBlob*, ushort*, ushort*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, int>)(lpVtbl[3]))((IDxcCompiler2*)Unsafe.AsPointer(ref this), pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(4)]
public HRESULT Preprocess(IDxcBlob* pSource, [NativeTypeName("LPCWSTR")] ushort* pSourceName, [NativeTypeName("LPCWSTR *")] ushort** pArguments, [NativeTypeName("UINT32")] uint argCount, [NativeTypeName("const DxcDefine *")] DxcDefine* pDefines, [NativeTypeName("UINT32")] uint defineCount, IDxcIncludeHandler* pIncludeHandler, IDxcOperationResult** ppResult)
{
return ((delegate* unmanaged<IDxcCompiler2*, IDxcBlob*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, int>)(lpVtbl[4]))((IDxcCompiler2*)Unsafe.AsPointer(ref this), pSource, pSourceName, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(5)]
public HRESULT Disassemble(IDxcBlob* pSource, IDxcBlobEncoding** ppDisassembly)
{
return ((delegate* unmanaged<IDxcCompiler2*, IDxcBlob*, IDxcBlobEncoding**, int>)(lpVtbl[5]))((IDxcCompiler2*)Unsafe.AsPointer(ref this), pSource, ppDisassembly);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[VtblIndex(6)]
public HRESULT CompileWithDebug(IDxcBlob* pSource, [NativeTypeName("LPCWSTR")] ushort* pSourceName, [NativeTypeName("LPCWSTR")] ushort* pEntryPoint, [NativeTypeName("LPCWSTR")] ushort* pTargetProfile, [NativeTypeName("LPCWSTR *")] ushort** pArguments, [NativeTypeName("UINT32")] uint argCount, [NativeTypeName("const DxcDefine *")] DxcDefine* pDefines, [NativeTypeName("UINT32")] uint defineCount, IDxcIncludeHandler* pIncludeHandler, IDxcOperationResult** ppResult, [NativeTypeName("LPWSTR *")] ushort** ppDebugBlobName, IDxcBlob** ppDebugBlob)
{
return ((delegate* unmanaged<IDxcCompiler2*, IDxcBlob*, ushort*, ushort*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, ushort**, IDxcBlob**, int>)(lpVtbl[6]))((IDxcCompiler2*)Unsafe.AsPointer(ref this), pSource, pSourceName, pEntryPoint, pTargetProfile, pArguments, argCount, pDefines, defineCount, pIncludeHandler, ppResult, ppDebugBlobName, ppDebugBlob);
}
public interface Interface : IDxcCompiler.Interface
{
[VtblIndex(6)]
HRESULT CompileWithDebug(IDxcBlob* pSource, [NativeTypeName("LPCWSTR")] ushort* pSourceName, [NativeTypeName("LPCWSTR")] ushort* pEntryPoint, [NativeTypeName("LPCWSTR")] ushort* pTargetProfile, [NativeTypeName("LPCWSTR *")] ushort** pArguments, [NativeTypeName("UINT32")] uint argCount, [NativeTypeName("const DxcDefine *")] DxcDefine* pDefines, [NativeTypeName("UINT32")] uint defineCount, IDxcIncludeHandler* pIncludeHandler, IDxcOperationResult** ppResult, [NativeTypeName("LPWSTR *")] ushort** ppDebugBlobName, IDxcBlob** ppDebugBlob);
}
public partial struct Vtbl<TSelf>
where TSelf : unmanaged, Interface
{
[NativeTypeName("HRESULT (const IID &, void **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, Guid*, void**, int> QueryInterface;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> AddRef;
[NativeTypeName("ULONG () __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, uint> Release;
[NativeTypeName("HRESULT (IDxcBlob *, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR *, UINT32, const DxcDefine *, UINT32, IDxcIncludeHandler *, IDxcOperationResult **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IDxcBlob*, ushort*, ushort*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, int> Compile;
[NativeTypeName("HRESULT (IDxcBlob *, LPCWSTR, LPCWSTR *, UINT32, const DxcDefine *, UINT32, IDxcIncludeHandler *, IDxcOperationResult **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IDxcBlob*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, int> Preprocess;
[NativeTypeName("HRESULT (IDxcBlob *, IDxcBlobEncoding **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IDxcBlob*, IDxcBlobEncoding**, int> Disassemble;
[NativeTypeName("HRESULT (IDxcBlob *, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR *, UINT32, const DxcDefine *, UINT32, IDxcIncludeHandler *, IDxcOperationResult **, LPWSTR *, IDxcBlob **) __attribute__((stdcall))")]
public delegate* unmanaged<TSelf*, IDxcBlob*, ushort*, ushort*, ushort*, ushort**, uint, DxcDefine*, uint, IDxcIncludeHandler*, IDxcOperationResult**, ushort**, IDxcBlob**, int> CompileWithDebug;
}
}
| 69.686275 | 549 | 0.733118 | [
"MIT"
] | JeremyKuhne/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/dxcapi/IDxcCompiler2.cs | 7,110 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.StackFrame
{
internal class StackFrameTree : EmbeddedSyntaxTree<StackFrameKind, StackFrameNode, StackFrameCompilationUnit>
{
public StackFrameTree(VirtualCharSequence text, StackFrameCompilationUnit root)
: base(text, root, ImmutableArray<EmbeddedDiagnostic>.Empty)
{
}
}
}
| 38.473684 | 113 | 0.77565 | [
"MIT"
] | AlexanderSemenyak/roslyn | src/Features/Core/Portable/EmbeddedLanguages/StackFrame/StackFrameTree.cs | 733 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Uno.UI.Xaml.Controls;
using System.ComponentModel;
namespace Uno.UI
{
public static class FeatureConfiguration
{
public static class AutomationPeer
{
/// <summary>
/// Enable a mode that simplifies accessibility by automatically grouping accessible elements into top-level accessible elements. The default value is false.
/// </summary>
/// <remarks>
/// When enabled, the accessibility name of top-level accessible elements (elements that return a non-null AutomationPeer in <see cref="UIElement.OnCreateAutomationPeer()"/> and/or have <see cref="AutomationProperties.Name" /> set to a non-empty string)
/// will be an aggregate of the accessibility name of all child accessible elements.
///
/// For example, if you have a <see cref="Button"/> that contains 3 <see cref="TextBlock"/> "A" "B" "C", the accessibility name of the <see cref="Button"/> will be "A, B, C".
/// These 3 <see cref="TextBlock"/> will also be automatically excluded from accessibility focus.
///
/// This greatly facilitates accessibility, as you would need to do this manually on UWP.
///
/// A limitation of this strategy is that you can't nest interactive elements, as children of an accessible elements are excluded from accessibility focus.
/// For example, if you put a <see cref="Button"/> inside another <see cref="Button"/>, only the parent <see cref="Button"/> will be focusable.
/// This happens to match a limitation of iOS, which does this by default and forces developers to make elements as siblings instead of nesting them.
///
/// To prevent a top-level accessible element from being accessible and make its children accessibility focusable, you can set <see cref="AutomationProperties.AccessibilityViewProperty"/> to <see cref="AccessibilityView.Raw"/>.
///
/// Note: This is incompatible with the way accessibility works on UWP.
/// </remarks>
public static bool UseSimpleAccessibility { get; set; } = false;
}
public static class ComboBox
{
/// <summary>
/// This defines the default value of the <see cref="UI.Xaml.Controls.ComboBox.DropDownPreferredPlacementProperty"/>. (cf. Remarks.)
/// </summary>
/// <remarks>
/// As this value is read only once when initializing the dependency property,
/// make sure to define it in the early stages of you application initialization,
/// before any UI related initialization (like generic styles init) and even before
/// referencing the ** type ** ComboBox in any way.
/// </remarks>
public static Uno.UI.Xaml.Controls.DropDownPlacement DefaultDropDownPreferredPlacement { get; set; } = Uno.UI.Xaml.Controls.DropDownPlacement.Auto;
}
public static class CompositionTarget
{
/// <summary>
/// The delay between invocations of the <see cref="Windows.UI.Xaml.Media.CompositionTarget.Rendering"/> event, in milliseconds.
/// Lower values will increase the rate at which the event fires, at the expense of increased CPU usage.
///
/// This property is only used on WebAssembly.
/// </summary>
/// <remarks>The <see cref="Windows.UI.Xaml.Media.CompositionTarget.Rendering"/> event is used by Xamarin.Forms for WebAssembly for XF animations.</remarks>
public static int RenderEventThrottle { get; set; } = 30;
}
public static class ContentPresenter
{
/// <summary>
/// Enables the implicit binding Content of a ContentPresenter to the one of the TemplatedParent
/// when this one is a ContentControl.
/// It means you can put a `<ContentPresenter />` directly in the ControlTemplate and it will
/// be bound automatically to its TemplatedPatent's Content.
/// </summary>
public static bool UseImplicitContentFromTemplatedParent { get; set; } = false;
}
public static class Control
{
/// <summary>
/// Make the default value of VerticalContentAlignment and HorizontalContentAlignment be Stretch instead of Center
/// </summary>
public static bool UseLegacyContentAlignment { get; set; } = false;
/// <summary>
/// Enables the lazy materialization of <see cref="Windows.UI.Xaml.Controls.Control"/> template. This behavior
/// is not aligned with UWP, which materializes templates immediately, making x:Name controls available
/// in the constructor of a control.
/// </summary>
public static bool UseLegacyLazyApplyTemplate { get; set; } = false;
/// <summary>
/// If the call to "OnApplyTemplate" should be deferred to mimic UWP sequence of events.
/// </summary>
/// <remarks>
/// Will never be deferred when .ApplyTemplate() is called explicitly.
/// More information there: https://github.com/unoplatform/uno/issues/3519
/// </remarks>
public static bool UseDeferredOnApplyTemplate { get; set; }
#if __ANDROID__ || __IOS__ || __MACOS__
= false; // opt-in for iOS/Android/macOS
#else
= true;
#endif
}
public static class DataTemplateSelector
{
/// <summary>
/// When set the false (default value), a call to `SelectTemplateCore(object, DependencyObject)`
/// will be made as fallback when the `SelectTemplateCore(object)` returns null.
/// When set to true, only `SelectTemplateCore(object)` is called (Uno's legacy mode).
/// </summary>
public static bool UseLegacyTemplateSelectorOverload { get; set; } = false;
}
public static class Font
{
/// <summary>
/// Defines the default font to be used when displaying symbols, such as in SymbolIcon.
/// </summary>
public static string SymbolsFont { get; set; } =
#if __SKIA__
"ms-appx:///Assets/Fonts/uno-fluentui-assets.ttf#Symbols";
#elif !__ANDROID__
"Symbols";
#else
"ms-appx:///Assets/Fonts/uno-fluentui-assets.ttf#Symbols";
#endif
/// <summary>
/// Ignores text scale factor, resulting in a font size as dictated by the control.
/// </summary>
public static bool IgnoreTextScaleFactor { get; set; } = false;
}
public static class FrameworkElement
{
[Obsolete("This flag is no longer used.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool UseLegacyApplyStylePhase { get; set; }
[Obsolete("This flag is no longer used.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool ClearPreviousOnStyleChange { get; set; }
#if __ANDROID__
/// <summary>
/// Controls the propagation of <see cref="Windows.UI.Xaml.FrameworkElement.Loaded"/> and
/// <see cref="Windows.UI.Xaml.FrameworkElement.Unloaded"/> events through managed
/// or native visual tree traversal.
/// </summary>
/// <remarks>
/// This setting impacts significantly the loading performance of controls on Android.
/// Setting it to <see cref="true"/> avoids the use of costly Java->C# interop.
/// </remarks>
public static bool AndroidUseManagedLoadedUnloaded { get; set; } = true;
#endif
/// <summary>
/// [WebAssembly Only] Controls the propagation of <see cref="Windows.UI.Xaml.FrameworkElement.Loaded"/> and
/// <see cref="Windows.UI.Xaml.FrameworkElement.Unloaded"/> events through managed
/// or native visual tree traversal.
/// </summary>
/// <remarks>
/// This setting impacts significantly the loading performance of controls on Web Assembly.
/// Setting it to <see cref="true"/> avoids the use of costly JavaScript->C# interop.
/// </remarks>
public static bool WasmUseManagedLoadedUnloaded { get; set; } = true;
}
public static class Image
{
/// <summary>
/// Use the old way to align iOS images, using the "ContentMode".
/// New way is using the Layer to better position the image according to alignments.
/// </summary>
public static bool LegacyIosAlignment { get; set; } = false;
}
public static class Interop
{
/// <summary>
/// [WebAssembly Only] Used to control the behavior of the C#/Javascript interop. Setting this
/// flag to true forces the use of the Javascript eval mode, instead of binary interop.
/// This flag has no effect when running in hosted mode.
/// </summary>
public static bool ForceJavascriptInterop { get; set; } = false;
}
public static class Binding
{
/// <summary>
/// Determines if the binding engine should ignore identical references in binding paths.
/// </summary>
public static bool IgnoreINPCSameReferences { get; set; } = false;
}
public static class Popup
{
#if __ANDROID__
/// <summary>
/// Use a native popup to display the popup content. Otherwise use the <see cref="PopupRoot"/>.
/// </summary>
public static bool UseNativePopup { get; set; } = true;
#endif
}
public static class ProgressRing
{
public static Uri ProgressRingAsset { get; set; } = new Uri("embedded://Uno.UI/Uno.UI.Microsoft.UI.Xaml.Controls.ProgressRing.ProgressRingIntdeterminate.json");
}
public static class ListViewBase
{
/// <summary>
/// Sets the value to use for <see cref="ItemsStackPanel.CacheLength"/> and <see cref="ItemsWrapGrid.CacheLength"/> if not set
/// explicitly in Xaml or code. Higher values will cache more views either side of the visible window, improving list performance
/// at the expense of consuming more memory. Setting this to null will leave the default value at the UWP default of 4.0.
/// </summary>
public static double? DefaultCacheLength = 1.0;
}
#if __ANDROID__
public static class NativeListViewBase
{
/// <summary>
/// Sets this value to remove item animation for <see cref="UnoRecyclerView"/>. This prevents <see cref="UnoRecyclerView"/>
/// from crashing when pressured: Tmp detached view should be removed from RecyclerView before it can be recycled
/// </summary>
public static bool RemoveItemAnimator = true;
}
#endif
public static class Page
{
/// <summary>
/// Enables reuse of <see cref="Page"/> instances. Enabling can improve performance when using <see cref="Frame"/> navigation.
/// </summary>
public static bool IsPoolingEnabled { get; set; } = false;
}
public static class PointerRoutedEventArgs
{
#if __ANDROID__
/// <summary>
/// Defines if the PointerPoint.Timestamp retrieved from PointerRoutedEventArgs.GetCurrentPoint(relativeTo)
/// or PointerRoutedEventArgs.GetIntermediatePoints(relativeTo) can be relative using the Android's
/// "SystemClock.uptimeMillis()" or if they must be converted into an absolute scale
/// (using the "elapsedRealtime()", cf. https://developer.android.com/reference/android/os/SystemClock).
/// Disabling it negatively impacts the performance it requires to compute the "sleep time"
/// (i.e. [real elapsed time] - [up time]) for each event (as the up time is paused when device is in deep sleep).
/// By default this is `true`.
/// </summary>
public static bool AllowRelativeTimeStamp { get; set; } = true;
#endif
}
public static class SelectorItem
{
/// <summary>
/// <para>
/// Determines if the visual states "PointerOver", "PointerOverSelected"
/// are used or not. If disabled, those states will never be activated by the selector items.
/// </para>
/// <para>The default value is `true`.</para>
/// </summary>
public static bool UseOverStates { get; set; } = true;
}
public static class Style
{
/// <summary>
/// Determines if Uno.UI should be using native styles for controls that have
/// a native counterpart. (e.g. Button, Slider, ComboBox, ...)
///
/// By default this is true.
/// </summary>
public static bool UseUWPDefaultStyles { get; set; } = true;
/// <summary>
/// Override the native styles usage per control type.
/// </summary>
/// <remarks>
/// Usage: 'UseUWPDefaultStylesOverride[typeof(Frame)] = false;' will result in the native style always being the default for Frame, irrespective
/// of the value of <see cref="UseUWPDefaultStyles"/>. This is useful when an app uses the UWP default look for most controls but the native
/// appearance/comportment for a few particular controls, or vice versa.
/// </remarks>
public static IDictionary<Type, bool> UseUWPDefaultStylesOverride { get; } = new Dictionary<Type, bool>();
/// <summary>
/// This enables native frame navigation on Android and iOS by setting related classes (<see cref="Frame"/>, <see cref="CommandBar"/>
/// and <see cref="AppBarButton"/>) to use their native styles.
/// </summary>
public static void ConfigureNativeFrameNavigation()
{
SetUWPDefaultStylesOverride<Frame>(useUWPDefaultStyle: false);
SetUWPDefaultStylesOverride<CommandBar>(useUWPDefaultStyle: false);
SetUWPDefaultStylesOverride<AppBarButton>(useUWPDefaultStyle: false);
}
/// <summary>
/// Override the native styles useage for control type <typeparamref name="TControl"/>.
/// </summary>
/// <typeparam name="TControl"></typeparam>
/// <param name="useUWPDefaultStyle">
/// Whether instances of <typeparamref name="TControl"/> should use the UWP default style.
/// If false, the native default style (if one exists) will be used.
/// </param>
public static void SetUWPDefaultStylesOverride<TControl>(bool useUWPDefaultStyle) where TControl : Windows.UI.Xaml.Controls.Control
=> UseUWPDefaultStylesOverride[typeof(TControl)] = useUWPDefaultStyle;
}
public static class TextBlock
{
/// <summary>
/// [WebAssembly Only] Determines if the measure cache is enabled.
/// </summary>
public static bool IsMeasureCacheEnabled { get; set; } = true;
}
public static class TextBox
{
/// <summary>
/// Determines if the caret is visible or not.
/// </summary>
/// <remarks>This feature is used to avoid screenshot comparisons false positives</remarks>
public static bool HideCaret { get; set; } = false;
}
public static class ScrollViewer
{
/// <summary>
/// This defines the default value of the <see cref="Uno.UI.Xaml.Controls.ScrollViewer.UpdatesModeProperty"/>.
/// For backward compatibility, you should set it to Synchronous.
/// For better compatibility with Windows, you should keep the default value 'AsynchronousIdle'.
/// </summary>
/// <remarks>
/// As this value is read only once when initializing the dependency property,
/// make sure to define it in the early stages of you application initialization,
/// before any UI related initialization (like generic styles init) and even before
/// referencing the ** type ** ScrollViewer in any way.
/// </remarks>
public static ScrollViewerUpdatesMode DefaultUpdatesMode { get; set; } = ScrollViewerUpdatesMode.AsynchronousIdle;
#if __ANDROID__
/// <summary>
/// This value defines an optional delay to be set for native ScrollBar thumbs to disapear. The
/// platform default is 300ms, which can make the thumbs appear on screenshots, changing this value
/// to <see cref="TimeSpan.Zero"/> makes those disapear faster.
/// </summary>
public static TimeSpan? AndroidScrollbarFadeDelay { get; set; }
#endif
}
public static class ThemeAnimation
{
/// <summary>
/// Default duration for xxxThemeAnimation
/// </summary>
public static TimeSpan DefaultThemeAnimationDuration { get; set; } = TimeSpan.FromSeconds(0.75);
}
public static class ToolTip
{
public static bool UseToolTips { get; set; }
#if __WASM__
= true;
#endif
public static int ShowDelay { get; set; } = 1000;
public static int ShowDuration { get; set; } = 7000;
}
public static class UIElement
{
/// <summary>
/// [DEPRECATED]
/// Not used anymore, does nothing.
/// </summary>
[NotImplemented]
public static bool UseLegacyClipping { get; set; } = true;
/// <summary>
/// Enable the visualization of clipping bounds (intended for diagnostic purposes).
/// </summary>
/// <remarks>
/// This feature is only supported on iOS, for now.
/// </remarks>
public static bool ShowClippingBounds { get; set; } = false;
/// <summary>
/// [WebAssembly Only] Enable the assignation of the "xamlname", "xuid" and "xamlautomationid" attributes on DOM elements created
/// from the XAML visual tree. This enables tools such as Puppeteer to select elements
/// in the DOM for automation purposes.
/// </summary>
public static bool AssignDOMXamlName { get; set; } = false;
/// <summary>
/// [WebAssembly Only] Enable UIElement.ToString() to return the element's unique ID
/// </summary>
public static bool RenderToStringWithId { get; set; } = true;
/// <summary>
/// [WebAssembly Only] Enables the assignation of properties from the XAML visual tree as DOM attributes: Height -> "xamlheight",
/// HorizontalAlignment -> "xamlhorizontalalignment" etc.
/// </summary>
/// <remarks>
/// This should only be enabled for debug builds, but can greatly aid layout debugging.
///
/// Note: for release builds of Uno, if the flag is set, attributes will be set on loading and *not* updated if
/// the values change subsequently. This restriction doesn't apply to debug Uno builds.
/// </remarks>
public static bool AssignDOMXamlProperties { get; set; } = false;
#if __ANDROID__
/// <summary>
/// When this is set, non-UIElements will always be clipped to their bounds (<see cref="Android.Views.ViewGroup.ClipChildren"/> will
/// always be set to true on their parent).
/// </summary>
/// <remarks>
/// This is true by default as most native views assume that they will be clipped, and can display incorrectly otherwise.
/// </remarks>
public static bool AlwaysClipNativeChildren { get; set; } = true;
#endif
}
public static class WebView
{
#if __ANDROID__
/// <summary>
/// Prevent the WebView from using hardware rendering.
/// This was previously the default behavior in Uno to work around a keyboard-related visual glitch in Android 5.0 (http://stackoverflow.com/questions/27172217/android-systemui-glitches-in-lollipop), however it prevents video and 3d content from being rendered.
/// </summary>
/// <remarks>
/// See this for more info: https://github.com/unoplatform/uno/blob/26c5cc5992cae3c8c25adf51eb77ca4b0dd34e93/src/Uno.UI/UI/Xaml/Controls/WebView/WebView.Android.cs#L251_L255
/// </remarks>
public static bool ForceSoftwareRendering { get; set; } = false;
#endif
}
public static class Xaml
{
/// <summary>
/// Maximal "BasedOn" recursive resolution depth.
/// </summary>
/// <remarks>
/// This is a mechanism to prevent hard-to-diagnose stack overflow when a resource name is not found.
/// </remarks>
[Obsolete("This flag is no longer used.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static int MaxRecursiveResolvingDepth { get; set; } = 12;
}
}
}
| 41.531868 | 264 | 0.700852 | [
"Apache-2.0"
] | AnshSSonkhia/uno | src/Uno.UI/FeatureConfiguration.cs | 18,899 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using R5T.T0045;
namespace R5T.S0026.Library
{
public static partial class ICompilationUnitOperatorExtensions
{
}
}
| 16.631579 | 66 | 0.765823 | [
"MIT"
] | SafetyCone/R5T.S0026 | source/R5T.S0026.Library/Code/Bases/Extensions/ICompilationUnitOperatorExtensions-Temp.cs | 318 | C# |
using System.Reflection;
[assembly: AssemblyTitle("xUnit.BDDExtensions.Assertions.dll")]
| 22.75 | 63 | 0.802198 | [
"Apache-2.0"
] | BjRo/xunitbddextensions | Source/xUnit.BDDExtensions.Assertions/Properties/AssemblyInfo.cs | 93 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.