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
namespace DiscogsDesktop { sealed partial class FormDiscogsDesktop { /// <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(FormDiscogsDesktop)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripDropDownButtonSettings = new System.Windows.Forms.ToolStripDropDownButton(); this.tokenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.folderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.deleteFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panelView = new System.Windows.Forms.Panel(); this.maxItemsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripTextBoxMaxItems = new System.Windows.Forms.ToolStripTextBox(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripDropDownButtonSettings, this.toolStripDropDownButton1}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(851, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolStripDropDownButtonSettings // this.toolStripDropDownButtonSettings.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripDropDownButtonSettings.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tokenToolStripMenuItem, this.folderToolStripMenuItem, this.maxItemsToolStripMenuItem}); this.toolStripDropDownButtonSettings.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButtonSettings.Image"))); this.toolStripDropDownButtonSettings.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButtonSettings.Name = "toolStripDropDownButtonSettings"; this.toolStripDropDownButtonSettings.Size = new System.Drawing.Size(61, 22); this.toolStripDropDownButtonSettings.Text = "settings"; // // tokenToolStripMenuItem // this.tokenToolStripMenuItem.Name = "tokenToolStripMenuItem"; this.tokenToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.tokenToolStripMenuItem.Text = "token"; this.tokenToolStripMenuItem.Click += new System.EventHandler(this.tokenToolStripMenuItemClick); // // folderToolStripMenuItem // this.folderToolStripMenuItem.Name = "folderToolStripMenuItem"; this.folderToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.folderToolStripMenuItem.Text = "folder"; this.folderToolStripMenuItem.Click += new System.EventHandler(this.folderToolStripMenuItemClick); // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.deleteFilesToolStripMenuItem}); this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image"))); this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; this.toolStripDropDownButton1.Size = new System.Drawing.Size(58, 22); this.toolStripDropDownButton1.Text = "actions"; // // deleteFilesToolStripMenuItem // this.deleteFilesToolStripMenuItem.Name = "deleteFilesToolStripMenuItem"; this.deleteFilesToolStripMenuItem.Size = new System.Drawing.Size(130, 22); this.deleteFilesToolStripMenuItem.Text = "delete files"; this.deleteFilesToolStripMenuItem.Click += new System.EventHandler(this.deleteFilesToolStripMenuItemClick); // // panelView // this.panelView.Dock = System.Windows.Forms.DockStyle.Fill; this.panelView.Location = new System.Drawing.Point(0, 25); this.panelView.Name = "panelView"; this.panelView.Size = new System.Drawing.Size(851, 428); this.panelView.TabIndex = 1; // // maxItemsToolStripMenuItem // this.maxItemsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripTextBoxMaxItems}); this.maxItemsToolStripMenuItem.Name = "maxItemsToolStripMenuItem"; this.maxItemsToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.maxItemsToolStripMenuItem.Text = "max items"; this.maxItemsToolStripMenuItem.ToolTipText = "defines how many items will bei displayed when a search is submitted"; // // toolStripTextBoxMaxItems // this.toolStripTextBoxMaxItems.Name = "toolStripTextBoxMaxItems"; this.toolStripTextBoxMaxItems.Size = new System.Drawing.Size(100, 23); this.toolStripTextBoxMaxItems.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.toolStripTextBoxMaxItemsKeyPress); // // FormDiscogsDesktop // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(851, 453); this.Controls.Add(this.panelView); this.Controls.Add(this.toolStrip1); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.Name = "FormDiscogsDesktop"; this.Text = "DiscogsDesktop"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButtonSettings; private System.Windows.Forms.ToolStripMenuItem tokenToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem folderToolStripMenuItem; private System.Windows.Forms.Panel panelView; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem deleteFilesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem maxItemsToolStripMenuItem; private System.Windows.Forms.ToolStripTextBox toolStripTextBoxMaxItems; } }
53.770701
150
0.660981
[ "Apache-2.0" ]
wagnerluuv/DiscogsDektop
DiscogsDesktop/DiscogsDesktop/FormDiscogsDesktop.Designer.cs
8,444
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Text.Json; using Azure.Core; namespace Azure.Communication.CallingServer { /// <summary> /// The subscribe to tone event /// </summary> [CodeGenModel("ToneReceivedEvent", Usage = new string[] { "model", "output" }, Formats = new string[] { "json" })] public partial class ToneReceivedEvent : CallingServerEventBase { /// <summary> /// Deserialize <see cref="ToneReceivedEvent"/> event. /// </summary> /// <param name="content">The json content.</param> /// <returns>The new <see cref="ToneReceivedEvent"/> object.</returns> public static ToneReceivedEvent Deserialize(string content) { using var document = JsonDocument.Parse(content); JsonElement element = document.RootElement; return DeserializeToneReceivedEvent(element); } } }
33.551724
118
0.641316
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/communication/Azure.Communication.CallingServer/src/Models/Events/ToneReceivedEvent.cs
975
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; using EdFi.Ods.Api.Security.AuthorizationStrategies.NHibernateConfiguration; using EdFi.Ods.Common; using EdFi.Ods.Common.Infrastructure.Filtering; namespace EdFi.Ods.Api.Security.AuthorizationStrategies.Relationships.Filters { public class ViewFilterApplicationDetails : FilterApplicationDetails { public ViewFilterApplicationDetails( string filterName, string viewName, string viewTargetEndpointName, string subjectEndpointName) : base( filterName, $@"{subjectEndpointName} IN ( SELECT {{newAlias1}}.{viewTargetEndpointName} FROM auth.{viewName} {{newAlias1}} WHERE {{newAlias1}}.{RelationshipAuthorizationConventions.ViewSourceColumnName} IN (:{RelationshipAuthorizationConventions.ClaimsParameterName}))", $@"{{currentAlias}}.{subjectEndpointName} IN ( SELECT {{newAlias1}}.{viewTargetEndpointName} FROM " + GetFullNameForView($"auth_{viewName}") + $@" {{newAlias1}} WHERE {{newAlias1}}.{RelationshipAuthorizationConventions.ViewSourceColumnName} IN (:{RelationshipAuthorizationConventions.ClaimsParameterName}))", (c, w, p, jt) => c.ApplyJoinFilter( w, p, viewName, subjectEndpointName, viewTargetEndpointName, jt, Guid.NewGuid().ToString("N")), (t, p) => p.HasPropertyNamed(subjectEndpointName ?? viewTargetEndpointName)) { FilterName = filterName; ViewName = viewName; ViewTargetEndpointName = viewTargetEndpointName; SubjectEndpointName = subjectEndpointName ?? viewTargetEndpointName; } public string FilterName { get; } public string ViewName { get; } public string ViewTargetEndpointName { get; } public string SubjectEndpointName { get; } private static string GetFullNameForView(string viewName) { return Namespaces.Entities.NHibernate.QueryModels.GetViewNamespace(viewName); } } }
42.366667
168
0.626672
[ "Apache-2.0" ]
bptillman/Ed-Fi-ODS
Application/EdFi.Ods.Api/Security/AuthorizationStrategies/Relationships/Filters/ViewFilterAuthorizationDetails.cs
2,542
C#
namespace Adaptive.Agrona.Concurrent { public class Configuration { /// <summary> /// Spin on no activity before backing off to yielding. /// </summary> public const long IDLE_MAX_SPINS = 10; /// <summary> /// Yield the thread so others can run before backing off to parking. /// </summary> public const long IDLE_MAX_YIELDS = 20; /// <summary> /// Park for the minimum period of time which is typically 50-55 microseconds on 64-bit non-virtualised Linux. /// You will typically get 50-55 microseconds plus the number of nanoseconds requested if a core is available. /// On Windows expect to wait for at least 16ms or 1ms if the high-res timers are enabled. /// </summary> public const long IDLE_MIN_PARK_MS = 1; /// <summary> /// Maximum back-off park time which doubles on each interval stepping up from the min park idle. /// </summary> public static readonly long IDLE_MAX_PARK_MS = 1000; } }
37.75
118
0.630085
[ "Apache-2.0" ]
MatthiasWeiser/Aeron.NET
src/Adaptive.Agrona/Concurrent/Configuration.cs
1,059
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace Ocelot.OrleansHttpGateway.Requester { public class OrleansConnectionFailedException : Exception { /// <summary> /// Creates a new <see cref="OrleansConnectionFailedException"/> object. /// </summary> /// <param name="message">Exception message</param> public OrleansConnectionFailedException(string message) : base(message) { } /// <summary> /// Creates a new <see cref="OrleansConnectionFailedException"/> object. /// </summary> /// <param name="message">Exception message</param> /// <param name="innerException">Inner exception</param> public OrleansConnectionFailedException(string message, Exception innerException) : base(message, innerException) { } } }
29.21875
89
0.638503
[ "Apache-2.0" ]
AClumsy/Ocelot.OrleansHttpGateway
src/Ocelot.OrleansHttpGateway/Requester/Exception/OrleansConnectionFailedException.cs
937
C#
#if MSSQL_MICROSOFT using Microsoft.Data.SqlClient; #else using System.Data.SqlClient; #endif using System; namespace HS.DB.Data { public class DBDataMSSQL : DBDataSQL { protected DBDataMSSQL() { } public DBDataMSSQL(SqlCommand Command) : this(Command.ExecuteReader()) { this.Command = Command; } public DBDataMSSQL(SqlDataReader Reader) : base(Reader) { this.Reader = Reader; } public new SqlCommand Command { get; protected set; } public new SqlDataReader Reader { get; protected set; } /* public static string GetJSON(DBData data, bool Bracket = false) { if (data == null) return null; int cnt = data.Columns.Length; if (cnt > 0) { StringBuilder sb = new StringBuilder(Bracket ? "{" : ""); //"{\"status\":\"ok\",\"message\":\"목록을 불러왔습니다.\"," StringBuilder sb_type = new StringBuilder("\"types\":["); StringBuilder sb_name = new StringBuilder("\"cols\":["); sb_name.AppendFormat("\"{0}\"", data.Columns[0]); sb_type.AppendFormat("\"{0}\"", DBManager.GetTypeString(data.Columns[0].Type)); for (int i = 1; i < cnt; i++) { sb_type.AppendFormat(",\"{0}\"", DBManager.GetTypeString(data.Columns[0].Type)); sb_name.AppendFormat(",\"{0}\"", data.Columns[i].Value); } sb_name.Append("]"); sb_type.Append("],"); sb.Append(sb_type.ToString()).Append(sb_name.ToString()).Append(",\"rows\":["); if (cnt > 0) { bool first = true; for (int i = 0; i < data.Rows; i++) { object[] row = data[i]; sb.AppendFormat(first ? "[{0}" : ",[{0}", DBManager.GetString(row[0])); first = false; for (int j = 1; j < cnt; j++) sb.AppendFormat(",{0}", DBManager.GetString(row[j])); sb.Append("]"); } } if (Bracket) sb.Append("}"); return sb.ToString(); } else return Bracket ? "{}" : ""; } */ } }
35.424242
125
0.475192
[ "Apache-2.0" ]
HongSic/HS.DB
Data/DBDataMSSQL.cs
2,358
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestServer { /// <summary> /// Uses the Pseudo random generator as a source. /// </summary> public class RandomSource { /// <summary> /// Initializes the source with a time dependent seed. /// </summary> public RandomSource() { m_random = new Random(); } /// <summary> /// Initializes the source with a seed. /// </summary> /// <param name="seed">The number used to initialize the Pseudo random sequence.</param> public RandomSource(int seed) { m_random = new Random(seed); } /// <summary> /// Fills a range in array of bytes with random numbers. /// </summary> /// <param name="bytes">The array to update.</param> /// <param name="offset">The start of the range generate.</param> /// <param name="count">The number of bytes to generate.</param> /// <exception cref="ArgumentNullException">Thrown if the bytes parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if the offset or count parameters do not specify a valid range within the bytes parameter.</exception> public void NextBytes(byte[] bytes, int offset, int count) { if (bytes == null) throw new ArgumentNullException("bytes"); if (offset < 0 || (offset != 0 && offset >= bytes.Length)) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || offset + count > bytes.Length) throw new ArgumentOutOfRangeException("count"); if (bytes.Length == 0) { return; } if (offset == 0 && count == bytes.Length) { m_random.NextBytes(bytes); } else { byte[] buffer = new byte[count]; m_random.NextBytes(buffer); Array.Copy(buffer, 0, bytes, offset, count); } } /// <summary> /// Returns a random non-negative integer which does not exeed the specified maximum. /// </summary> /// <param name="max">The maximum value to return.</param> /// <returns>A random value greater than 0 but less than or equal to max.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown if the max parameter is less than zero.</exception> public int NextInt32(int max) { if (max < 0) throw new ArgumentOutOfRangeException("max"); if (max < Int32.MaxValue) { max++; } return m_random.Next(max); } private Random m_random; } }
28.518072
161
0.665822
[ "MIT" ]
Movares/OPC-Classic-SDK
development/NET/test_apps/C#/COM TestServer/RandomSource.cs
2,369
C#
using System; namespace svg_command.exception { public class MyException : ApplicationException { public string error; private Exception innerException; public MyException() { } public MyException(string msg) : base(msg) { this.error = msg; } public MyException(string msg, Exception innerException) : base(msg, innerException) { this.innerException = innerException; error = msg; } public string GetError() { return error; } } }
23.52
92
0.564626
[ "MIT" ]
longporo/svg-command
exception/MyException.cs
590
C#
using System; using System.Buffers; using Newtonsoft.Json; namespace ZeroReact.Utils { internal class JsonArrayPool<T> : IArrayPool<T> { public static JsonArrayPool<T> Instance = new JsonArrayPool<T>(); private readonly ArrayPool<T> _inner; public JsonArrayPool() { _inner = ArrayPool<T>.Shared; } public T[] Rent(int minimumLength) { return _inner.Rent(minimumLength); } public void Return(T[] array) { if (array == null) { throw new ArgumentNullException(nameof(array)); } _inner.Return(array); } } }
20.529412
73
0.541547
[ "MIT" ]
DaniilSokolyuk/ZeroReact
src/ZeroReact/Utils/JsonArrayPool.cs
700
C#
using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using Xunit; namespace NuDoq { public class XmlNormalizerFixture { [Theory] [InlineData("One tree is in default namespace. Other is in a namespace with a prefix.", @"<Root xmlns='http://www.northwind.com'> <Child>1</Child> </Root>", @"<n:Root xmlns:n='http://www.northwind.com'> <n:Child>1</n:Child> </n:Root>", null, true)] [InlineData("Variation on namespace prefixes.", @"<Root xmlns='http://www.northwind.com'> <a:Child xmlns:a='http://www.adventureworks.com'>1</a:Child> </Root>", @"<Root xmlns='http://www.northwind.com'> <Child xmlns='http://www.adventureworks.com'>1</Child> </Root>", null, true)] [InlineData("Attributes are not ordered.", @"<Root a='1' b='2'> <Child>1</Child> </Root>", @"<Root b='2' a='1'> <Child>1</Child> </Root>", null, true)] [InlineData("Attributes are not ordered, take 2.", @"<Root a='1' b='2'> <Child a='a' b='b' c='c' d='d'>1</Child> </Root>", @"<Root b='2' a='1'> <Child d='d' c='c' b='b' a='a'>1</Child> </Root>", null, true)] [InlineData("One tree has a comment. Other does not.", "<Root><!--Comment--></Root>", "<Root></Root>", null, true)] [InlineData("One element is self-closed, the other is empty.", @"<doc> <summary> <b>unknown tag</b> </summary> <remarks> <code /> </remarks> </doc>", @"<doc> <summary> <b>unknown tag</b> </summary> <remarks> <code> </code> </remarks> </doc>", null, true)] [InlineData("One tree has comment and PI., other does not.", @"<Root> <!--Comment--> <?xml-stylesheet href='mystyle.css' type='text/css'?> <Child></Child> </Root>", "<Root><Child></Child></Root>", null, true)] [InlineData("Element is data type of xsd:double, values are equal when normalized.", "<Root>25</Root>", "<Root>+25</Root>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root' type='xsd:double'/> </xsd:schema>", true)] [InlineData("Element is data type of xsd:double, values are equal when normalized.", @"<Root> <Child>+25e+01</Child> <Child>+50.0000</Child> </Root>", @"<Root> <Child>250</Child> <Child>5e1</Child> </Root>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root'> <xsd:complexType mixed='true'> <xsd:choice> <xsd:element name='Child' minOccurs='0' maxOccurs='unbounded' type='xsd:double'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>", true)] [InlineData("Variations in value representations.", @"<Root> <ABooleanElement>1</ABooleanElement> <ADateTimeElement>2009-01-21T18:50:59.0000000-08:00</ADateTimeElement> <ADecimalElement>1.0</ADecimalElement> <ADoubleElement>1.0</ADoubleElement> <AFloatElement>1.0</AFloatElement> </Root>", @"<Root> <ABooleanElement>true</ABooleanElement> <ADateTimeElement>2009-01-21T18:50:59-08:00</ADateTimeElement> <ADecimalElement>1.0</ADecimalElement> <ADoubleElement>1</ADoubleElement> <AFloatElement>1</AFloatElement> </Root>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root'> <xsd:complexType> <xsd:all> <xsd:element name='ABooleanElement' minOccurs='1' maxOccurs='1'> <xsd:complexType> <xsd:simpleContent> <xsd:extension base='xsd:boolean'> <xsd:attribute name='ADefaultBooleanAttribute' default='false'/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> <xsd:element name='ADateTimeElement' minOccurs='1' maxOccurs='1' type='xsd:dateTime'/> <xsd:element name='ADecimalElement' minOccurs='1' maxOccurs='1' type='xsd:decimal'/> <xsd:element name='ADoubleElement' minOccurs='1' maxOccurs='1' type='xsd:double'/> <xsd:element name='AFloatElement' minOccurs='1' maxOccurs='1' type='xsd:float'/> </xsd:all> </xsd:complexType> </xsd:element> </xsd:schema>", true)] [InlineData("Variations in value representations.", @"<Root> <Child> <A>1</A> <B>1.0</B> <C>1.0</C> <D>2009-01-21T18:50:59-08:00</D> </Child> <Child> <A>1</A> <B>1.0</B> <C>1.0</C> <D>2009-01-21T18:50:59-08:00</D> </Child> <Child> <A>1</A> <B>1.0</B> <C>1.0</C> <D>2009-01-21T18:50:59-08:00</D> </Child> </Root>", @"<Root> <Child> <A>1</A> <B>1.0</B> <C>1.0</C> <D>2009-01-21T18:50:59.0000000-08:00</D> </Child> <Child> <A>1</A> <B>1</B> <C>1</C> <D>2009-01-21T18:50:59.0000000-08:00</D> </Child> <Child> <A>1</A> <B>1.0</B> <C>1.0</C> <D>2009-01-21T18:50:59.0000000-08:00</D> </Child> </Root>", @"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element maxOccurs='unbounded' name='Child'> <xs:complexType> <xs:all> <xs:element name='B' type='xs:float' /> <xs:element name='A' type='xs:unsignedByte' /> <xs:element name='C' type='xs:float' /> <xs:element name='D' type='xs:dateTime' /> </xs:all> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>", true)] [InlineData("noNamespaceSchemaLocation", "<Text><b></b><i></i></Text>", @"<Text xsi:noNamespaceSchemaLocation='http://adventure-works.com/schemas/paragraph.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><b></b><i></i></Text>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Text'> <xsd:complexType> <xsd:all> <xsd:element name='b'/> <xsd:element name='i'/> </xsd:all> </xsd:complexType> </xsd:element> </xsd:schema>", true)] [InlineData("hexBinary and language data types", "<Text><b>3f3c6d78206c657673726f693d6e3122302e20226e</b><l>en-US</l></Text>", "<Text><b>3F3C6D78206C657673726F693D6E3122302E20226E</b><l>en-us</l></Text>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Text'> <xsd:complexType> <xsd:all> <xsd:element name='b' type='xsd:hexBinary'/> <xsd:element name='l' type='xsd:language'/> </xsd:all> </xsd:complexType> </xsd:element> </xsd:schema>", true)] [InlineData("Attributes of various types, values not normalized.", @"<Root ABoolean='true' AFloat='1.0' ADecimal='1.00' ADouble='1.0' ADateTime='2009-01-21T18:50:59-08:00' AHexBinary='abcd1234' ALanguage='en-us'> <Child XBoolean='true' XFloat='1.0' XDecimal='1.00' XDouble='1.0' XDateTime='2009-01-21T18:50:59-08:00' XHexBinary='abcd1234' XLanguage='en-us'/> </Root>", @"<Root ABoolean='true' AFloat='+1' ADecimal='1.00' ADouble='+1e+0' ADateTime='2009-01-21T18:50:59.00-08:00' AHexBinary='ABCD1234' ALanguage='EN-US'> <Child XBoolean='true' XFloat='1.0' XDecimal='1.00' XDouble='+1e+0' XDateTime='2009-01-21T18:50:59-08:00' XHexBinary='ABCD1234' XLanguage='en-US'/> </Root>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root'> <xsd:complexType> <xsd:all> <xsd:element name='Child' minOccurs='1' maxOccurs='1'> <xsd:complexType> <xsd:attribute name='XBoolean' type='xsd:boolean'/> <xsd:attribute name='XFloat' type='xsd:float'/> <xsd:attribute name='XDecimal' type='xsd:decimal'/> <xsd:attribute name='XDouble' type='xsd:double'/> <xsd:attribute name='XDateTime' type='xsd:dateTime'/> <xsd:attribute name='XHexBinary' type='xsd:hexBinary'/> <xsd:attribute name='XLanguage' type='xsd:language'/> </xsd:complexType> </xsd:element> </xsd:all> <xsd:attribute name='ABoolean' type='xsd:boolean'/> <xsd:attribute name='AFloat' type='xsd:float'/> <xsd:attribute name='ADecimal' type='xsd:decimal'/> <xsd:attribute name='ADouble' type='xsd:double'/> <xsd:attribute name='ADateTime' type='xsd:dateTime'/> <xsd:attribute name='AHexBinary' type='xsd:hexBinary'/> <xsd:attribute name='ALanguage' type='xsd:language'/> </xsd:complexType> </xsd:element> </xsd:schema>", true)] [InlineData("Element has a default attribute.", "<Root/>", "<Root ADefaultBooleanAttribute='false'/>", @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root'> <xsd:complexType> <xsd:simpleContent> <xsd:extension base='xsd:string'> <xsd:attribute name='ADefaultBooleanAttribute' default='false'/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:schema>", true)] public void when_comparing_documents_then_suceeds(string description, string doc1, string doc2, string schema, bool expectedEquals) { var schemaSet = default(XmlSchemaSet); if (schema != null) { schemaSet = new XmlSchemaSet(); schemaSet.Add("", XmlReader.Create(new StringReader(schema))); } var d1 = XDocument.Parse(doc1); var d2 = XDocument.Parse(doc2); if (expectedEquals == true) Assert.True(XmlNormalizer.NormalizedEquals(d1, d2, schemaSet), description); else Assert.False(XmlNormalizer.NormalizedEquals(d1, d2, schemaSet), description); } } }
48.305994
139
0.382028
[ "MIT" ]
aschuhardt/NuDoq
src/NuDoq.Tests/XmlNormalizerFixture.cs
15,315
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Runtime.Serialization; using Azure.Core; namespace Azure.Identity { /// <summary> /// An exception indicating that interactive authentication is required. /// </summary> [Serializable] public class AuthenticationRequiredException : CredentialUnavailableException { /// <summary> /// Creates a new <see cref="AuthenticationRequiredException"/> with the specified message and context. /// </summary> /// <param name="message">The message describing the authentication failure.</param> /// <param name="context">The details of the authentication request.</param> public AuthenticationRequiredException(string message, TokenRequestContext context) : this(message, context, default) { } /// <summary> /// Creates a new <see cref="AuthenticationRequiredException"/> with the specified message, context and inner exception. /// </summary> /// <param name="message">The message describing the authentication failure.</param> /// <param name="context">The details of the authentication request.</param> /// <param name="innerException">The exception underlying the authentication failure.</param> public AuthenticationRequiredException(string message, TokenRequestContext context, Exception innerException) : base(message, innerException) { TokenRequestContext = context; } /// <summary> /// A constructor used for serialization. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/>.</param> /// <param name="context">The <see cref="StreamingContext"/>.</param> /// <returns></returns> protected AuthenticationRequiredException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// The details of the authentication request which resulted in the authentication failure. /// </summary> public TokenRequestContext TokenRequestContext { get; } } }
41.296296
128
0.659641
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/identity/Azure.Identity/src/AuthenticationRequiredException.cs
2,232
C#
using System; namespace IqOptionApi.utilities { [AttributeUsage(AttributeTargets.Method)] public class SubscribeForTopicNameAttribute : Attribute { public SubscribeForTopicNameAttribute(string topicName, Type argumentType, bool Callback=false) { this.TopicName = topicName; this.ArgumentType = argumentType; this.Callback = Callback; } public string TopicName { get; } public Type ArgumentType { get; } public bool Callback { get; } } [AttributeUsage(AttributeTargets.Method)] public class PredisposableAttribute : Attribute { } }
24.148148
103
0.656442
[ "MIT" ]
AomDEV/IqOption.Net
src/IqOptionApi.NET/Utilities/SubscribeForTopicNameAttribute.cs
652
C#
extern alias Cocona_v1_1_0; using System; using System.Collections.Generic; using System.Text; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; namespace Cocona.Benchmark.Performance { [SimpleJob(RunStrategy.ColdStart, launchCount: 10)] [SimpleJob] [MemoryDiagnoser] public class CommandProviderBenchmark { [Benchmark] public void CommandProvider_v1_1_0() { var provider = new Cocona_v1_1_0::Cocona.Command.CoconaCommandProvider( new [] { typeof(TestCommand_v1_1_0) }, treatPublicMethodsAsCommands:true, enableConvertCommandNameToLowerCase:true, enableConvertOptionNameToLowerCase:true ); var commands = provider.GetCommandCollection(); } [Benchmark] public void BuiltInCommandProvider_v1_1_0() { var provider = new Cocona_v1_1_0::Cocona.Command.BuiltIn.CoconaBuiltInCommandProvider(new Cocona_v1_1_0::Cocona.Command.CoconaCommandProvider( new[] { typeof(TestCommand_v1_1_0) }, treatPublicMethodsAsCommands: true, enableConvertCommandNameToLowerCase: true, enableConvertOptionNameToLowerCase: true )); var commands = provider.GetCommandCollection(); } class TestCommand_v1_1_0 { public void Hello([Cocona_v1_1_0::Cocona.Option('b')]bool boolOption, [Cocona_v1_1_0::Cocona.Option('s')]string strOption, [Cocona_v1_1_0::Cocona.Argument]string arg0) { } } [Benchmark] public void CommandProvider_Current() { var provider = new global::Cocona.Command.CoconaCommandProvider( new[] { typeof(TestCommand_Current) }, treatPublicMethodsAsCommands: true, enableConvertCommandNameToLowerCase: true, enableConvertOptionNameToLowerCase: true ); var commands = provider.GetCommandCollection(); } [Benchmark] public void BuiltInCommandProvider_Current() { var provider = new global::Cocona.Command.BuiltIn.CoconaBuiltInCommandProvider(new global::Cocona.Command.CoconaCommandProvider( new[] { typeof(TestCommand_Current) }, treatPublicMethodsAsCommands: true, enableConvertCommandNameToLowerCase: true, enableConvertOptionNameToLowerCase: true )); var commands = provider.GetCommandCollection(); } class TestCommand_Current { public void Hello([global::Cocona.Option('b')]bool boolOption, [global::Cocona.Option('s')]string strOption, [global::Cocona.Argument]string arg0) { } } } }
35.962025
179
0.632524
[ "MIT" ]
benjiro/Cocona
perf/Cocona.Benchmark.Performance/CommandProviderBenchmark.cs
2,841
C#
using Audit.Core; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Audit.FileSystem { /// <summary> /// Monitor a folder in the file system generating en audit event for each change /// </summary> public class FileSystemMonitor { private FileSystemMonitorOptions _options; /// <summary> /// The FileSystemMonitor options. /// </summary> public FileSystemMonitorOptions Options { get => _options; set => _options = value; } private FileSystemWatcher _watcher; public FileSystemMonitor(string path) { _options = new FileSystemMonitorOptions(path); } public FileSystemMonitor(FileSystemMonitorOptions options) { _options = options; } public FileSystemMonitor() { _options = new FileSystemMonitorOptions(Directory.GetCurrentDirectory()); } /// <summary> /// Start monitoring the file system /// </summary> public void Start() { if (_watcher != null) { _watcher.Dispose(); } _watcher = new FileSystemWatcher(); _watcher.NotifyFilter = _options.NotifyFilters; _watcher.Filter = _options.Filter; _watcher.IncludeSubdirectories = _options.IncludeSubdirectories; _watcher.Path = _options.Path; _watcher.InternalBufferSize = _options.InternalBufferSize; if (_options.IncludedEventTypes == null || _options.IncludedEventTypes.Contains(FileSystemEventType.Change)) { _watcher.Changed += _watcher_Changed; } if (_options.IncludedEventTypes == null || _options.IncludedEventTypes.Contains(FileSystemEventType.Rename)) { _watcher.Renamed += _watcher_Renamed; } if (_options.IncludedEventTypes == null || _options.IncludedEventTypes.Contains(FileSystemEventType.Delete)) { _watcher.Deleted += _watcher_Deleted; } if (_options.IncludedEventTypes == null || _options.IncludedEventTypes.Contains(FileSystemEventType.Create)) { _watcher.Created += _watcher_Created; } _watcher.EnableRaisingEvents = true; } /// <summary> /// Stop monitoring the file system /// </summary> public void Stop() { _watcher.EnableRaisingEvents = false; } private void _watcher_Created(object sender, FileSystemEventArgs e) { if (IncludeObject(e)) { Task.Factory.StartNew(() => { ProcessEvent(e, FileSystemEventType.Create); }); } } private void _watcher_Deleted(object sender, FileSystemEventArgs e) { if (IncludeObject(e)) { Task.Factory.StartNew(() => { ProcessEvent(e, FileSystemEventType.Delete); }); } } private void _watcher_Renamed(object sender, RenamedEventArgs e) { if (IncludeObject(e)) { Task.Factory.StartNew(() => { ProcessEvent(e, FileSystemEventType.Rename); }); } } private void _watcher_Changed(object sender, FileSystemEventArgs e) { if (IncludeObject(e)) { Task.Factory.StartNew(() => { ProcessEvent(e, FileSystemEventType.Change); }); } } private bool IncludeObject(FileSystemEventArgs e) { return _options.CustomFilterPredicate != null ? _options.CustomFilterPredicate.Invoke(e) : true; } private void ProcessEvent(FileSystemEventArgs e, FileSystemEventType type) { var fsEvent = new FileSystemEvent() { Name = System.IO.Path.GetFileName(e.FullPath), Extension = System.IO.Path.GetExtension(e.FullPath), FullPath = e.FullPath, Event = type, OldName = (e is RenamedEventArgs) ? System.IO.Path.GetFileName((e as RenamedEventArgs).OldFullPath) : null }; var fsAuditEvent = new AuditEventFileSystem() { FileSystemEvent = fsEvent }; var eventType = (_options.EventTypeName ?? "[{type}] {name}").Replace("{name}", fsEvent.Name).Replace("{path}", fsEvent.FullPath).Replace("{type}", e.ChangeType.ToString()); using (var auditScope = AuditScope.Create(new AuditScopeOptions() { EventType = eventType, AuditEvent = fsAuditEvent, DataProvider = _options.AuditDataProvider, CreationPolicy = _options.CreationPolicy })) { if (type != FileSystemEventType.Delete) { fsEvent.Errors = new List<string>(); try { FillEvent(fsEvent, e); } catch (Exception ex) { fsEvent.Errors.Add($"{ex.GetType().Name}: {ex.Message})"); } if (fsEvent.Errors.Count == 0) { fsEvent.Errors = null; } (auditScope.Event as AuditEventFileSystem).FileSystemEvent = fsEvent; } } } private void FillEvent(FileSystemEvent fsEvent, FileSystemEventArgs e) { FileAttributes attr = FileAttributes.Archive; try { attr = File.GetAttributes(e.FullPath); } catch (IOException ex) { fsEvent.Errors.Add($"IOException when getting file attributes: {ex.Message}"); return; } bool isDir = (attr & FileAttributes.Directory) == FileAttributes.Directory; FileSystemInfo fsInfo; if (isDir) { var di = new DirectoryInfo(e.FullPath); fsInfo = di; fsEvent.Object = FileSystemObjectType.Directory; } else { var fi = new FileInfo(e.FullPath); fsInfo = fi; fsEvent.Length = fi.Length; fsEvent.ReadOnly = fi.IsReadOnly; fsEvent.Object = FileSystemObjectType.File; if (fi.Exists) { if (!_options.IgnoreMD5) { fsEvent.MD5 = ComputeMD5(e.FullPath); } if (_options.IncludeContentPredicate != null) { var contentType = _options.IncludeContentPredicate.Invoke(fi); if (contentType != ContentType.None) { try { if (contentType == ContentType.Binary) { fsEvent.FileContent = new FileBinaryContent() { Value = File.ReadAllBytes(e.FullPath) }; } else if (contentType == ContentType.Text) { fsEvent.FileContent = new FileTextualContent() { Value = File.ReadAllText(e.FullPath) }; } } catch (IOException ex) { fsEvent.Errors.Add($"IOException when getting file content: {ex.Message}"); } } } } } fsEvent.Attributes = attr.ToString(); fsEvent.CreationTime = fsInfo.CreationTime; fsEvent.LastAccessTime = fsInfo.LastAccessTime; fsEvent.LastWriteTime = fsInfo.LastWriteTime; } private string ComputeMD5(string filePath) { byte[] hash; using (var md5 = MD5.Create()) { try { using (var stream = File.OpenRead(filePath)) { hash = md5.ComputeHash(stream); } } catch (IOException ex) { return $"{{Error}} {ex.Message}"; } return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } }
36.215139
217
0.489989
[ "MIT" ]
Collabco/Audit.NET
src/Audit.FileSystem/FileSystemMonitor.cs
9,092
C#
using System.Runtime.Serialization; namespace Elasticsearch.Net { [DataContract] public class ShardFailure { [DataMember(Name = "index")] public string Index { get; set; } [DataMember(Name = "node")] public string Node { get; set; } [DataMember(Name = "reason")] public ErrorCause Reason { get; set; } [DataMember(Name = "shard")] public int? Shard { get; set; } [DataMember(Name = "status")] public string Status { get; set; } } }
19.25
40
0.658009
[ "Apache-2.0" ]
AnthAbou/elasticsearch-net
src/Elasticsearch.Net/Responses/ServerException/ShardFailure.cs
464
C#
using Foundation; namespace GraphicsTester.Skia { [global::Foundation.Register ("AppDelegate")] partial class AppDelegate { void ReleaseDesignerOutlets () { } } }
15.769231
49
0.614634
[ "MIT" ]
antonfirsov/Microsoft.Maui.Graphics
samples/GraphicsTester.Skia.Mac/AppDelegate.designer.cs
207
C#
using System.Threading.Tasks; namespace Hosting { public delegate Task RequestDelegate(HttpContext context); }
19.166667
62
0.8
[ "MIT" ]
AtwindYu/Asp.NetCore2
sources/Hosting/RequestDelegate.cs
115
C#
namespace AuditlogService { public class AuditlogManagerConfig { public string LogPath { get; set; } } }
17.714286
43
0.653226
[ "Apache-2.0" ]
BionStt/pitstop
src/AuditlogService/AuditlogManagerConfig.cs
124
C#
using System; using JetBrains.Annotations; using Vostok.Configuration.Abstractions.Attributes; using Vostok.Configuration.Abstractions.SettingsTree; using Vostok.Configuration.Helpers; namespace Vostok.Configuration.Binders { /// <summary> /// A binder wrapper that treats all models as if they were marked with a <see cref="SecretAttribute"/>. /// </summary> [PublicAPI] public class SecretBinder : ISettingsBinder { private readonly ISettingsBinder baseBinder; public SecretBinder([NotNull] ISettingsBinder baseBinder) => this.baseBinder = baseBinder ?? throw new ArgumentNullException(nameof(baseBinder)); public TSettings Bind<TSettings>(ISettingsNode rawSettings) { using (SecurityHelper.StartSecurityScope()) return baseBinder.Bind<TSettings>(rawSettings); } } }
33.846154
108
0.707955
[ "MIT" ]
levdimov/configuration
Vostok.Configuration/Binders/SecretBinder.cs
882
C#
/* * Copyright Cepheis Ltd 2022 * All rights reserves */ using EA.Gen.Model; using System.Collections.Generic; using System.Linq; namespace EA.Gen.Hub.Data { /// <summary> /// Helper class for copying Glossary /// </summary> internal static class Glossary_Data { /// <summary> /// Copy this Glossary to another object /// </summary> /// <param name="obj">current object</param> /// <param name="to">object to be populated</param> internal static void Copy (this Glossary obj, Glossary to) { if (obj.Term != to.Term) to.Term = obj.Term; if (obj.Type != to.Type) to.Type = obj.Type; if (obj.Meaning != to.Meaning) to.Meaning = obj.Meaning; } /// <summary> /// Copy this Glossary to another database /// </summary> /// <param name="obj">current object</param> /// <param name="db">target database</param> internal static void Copy (this Glossary obj, ISparx db) { var to = (from r in db.Glossaries where r.Id == obj.Id select r).FirstOrDefault(); if (to == null) { to = new Glossary(); db.Glossaries.Add(to); db.SaveChanges(); } obj.Copy(to); } /// <summary> /// Copy a collection of a parent object /// </summary> /// <param name="obj">current object</param> /// <param name="db">target database</param> internal static void Copy(this ICollection<Glossary> obj, ISparx db) { foreach (var v in obj.ToArray ()) { v.Copy(db); } } } }
28.887097
76
0.506979
[ "Apache-2.0" ]
channell/Ea.Gen
EA.Gen.Model.Helper/Glossary.cs
1,791
C#
using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Nexus.Core { #warning Records with IConfiguration: wait for issue https://github.com/dotnet/runtime/issues/43662 to be solved // template: https://grafana.com/docs/grafana/latest/administration/configuration/ internal abstract record NexusOptionsBase() { // for testing only public string? BlindSample { get; set; } internal static IConfiguration BuildConfiguration(string[] args) { var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json"); if (!string.IsNullOrWhiteSpace(environmentName)) { builder .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true); } var settingsPath = Environment.GetEnvironmentVariable("NEXUS_PATHS__SETTINGS"); if (settingsPath is null) settingsPath = PathsOptions.DefaultSettingsPath; if (settingsPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) builder.AddJsonFile(settingsPath, optional: true, /* for serilog */ reloadOnChange: true); builder .AddEnvironmentVariables(prefix: "NEXUS_") .AddCommandLine(args); return builder.Build(); } } internal record GeneralOptions() : NexusOptionsBase { public const string Section = "General"; public string? ApplicationName { get; set; } } internal record ServerOptions() : NexusOptionsBase { public const string Section = "Server"; public string? HttpScheme { get; set; } public string? HttpAddress { get; set; } public int HttpPort { get; set; } } internal record PathsOptions() : NexusOptionsBase { public const string Section = "Paths"; public string Config { get; set; } = Path.Combine(PathsOptions.PlatformSpecificRoot, "config"); public string Cache { get; set; } = Path.Combine(PathsOptions.PlatformSpecificRoot, "cache"); public string Catalogs { get; set; } = Path.Combine(PathsOptions.PlatformSpecificRoot, "catalogs"); public string Artifacts { get; set; } = Path.Combine(PathsOptions.PlatformSpecificRoot, "artifacts"); public string Users { get; set; } = Path.Combine(PathsOptions.PlatformSpecificRoot, "users"); public string Packages { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nexus", "packages"); // GetGlobalPackagesFolder: https://github.com/NuGet/NuGet.Client/blob/0fc58e13683565e7bdf30e706d49e58fc497bbed/src/NuGet.Core/NuGet.Configuration/Utility/SettingsUtility.cs#L225-L254 // GetFolderPath: https://github.com/NuGet/NuGet.Client/blob/1d75910076b2ecfbe5f142227cfb4fb45c093a1e/src/NuGet.Core/NuGet.Common/PathUtil/NuGetEnvironment.cs#L54-L57 #region Support public static string DefaultSettingsPath { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Nexus", "settings.json") : "/etc/nexus/settings.json"; private static string PlatformSpecificRoot { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Nexus") : "/var/lib/nexus"; #endregion } internal record OpenIdConnectProvider { #pragma warning disable CS8618 // Ein Non-Nullable-Feld muss beim Beenden des Konstruktors einen Wert ungleich NULL enthalten. Erwägen Sie die Deklaration als Nullable. public string Scheme { get; init; } public string DisplayName { get; init; } public string Authority { get; init; } public string ClientId { get; init; } public string ClientSecret { get; init; } #pragma warning restore CS8618 // Ein Non-Nullable-Feld muss beim Beenden des Konstruktors einen Wert ungleich NULL enthalten. Erwägen Sie die Deklaration als Nullable. } internal partial record SecurityOptions() : NexusOptionsBase { public const string Section = "Security"; public const string DefaultSigningKey = "WOE6/wiy6E4UQJefC03ffOsBnilijFOjhFUw1eUtzhD/8/YNR7auSUeH+5VcGfXU4pki7ZLCulmvNq8c03S96g=="; public string Base64JwtSigningKey { get; set; } = DefaultSigningKey; public TimeSpan AccessTokenLifetime { get; set; } public TimeSpan RefreshTokenLifetime { get; set; } public TimeSpan TokenAbuseDetectionPeriod { get; set; } public List<OpenIdConnectProvider> OidcProviders { get; set; } = new(); } }
46.207547
191
0.687015
[ "MIT" ]
Nexusforge/nexus
src/Nexus/Core/NexusOptions.cs
4,902
C#
namespace LostTech.Torch { using System; using System.Collections.Generic; using System.Linq; using static TorchSharp.torch; using static TorchSharp.torch.nn; static class TensorTools { public static (Tensor ins, Tensor outs) RandomBatch( this (Tensor ins, Tensor outs) pair, int batchSize, Device? device = null) { using var noGrad = no_grad(); using var indices = randint(high: pair.ins.shape[0], size: new long[] { batchSize }, dtype: ScalarType.Int64, device: device); var tensorIndices = TensorIndex.Tensor(indices); return (pair.ins[tensorIndices], pair.outs[tensorIndices]); } public static Tensor BatchForward(this Module module, Tensor ins, int batchSize) { var inChunks = ins.split(batchSize); var outChunks = inChunks.Select(c => { var tmpOut = module.forward(c); c.Dispose(); tmpOut.detach_().Dispose(); return tmpOut; }).ToList(); var output = cat(outChunks, dimension: 0); foreach (var chunk in outChunks) chunk.Dispose(); return output; } } }
35.25641
90
0.524364
[ "MIT" ]
losttech/Torch.MinGPT
app/TensorTools.cs
1,375
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataFactory.Inputs { /// <summary> /// A copy activity Parquet sink. /// </summary> public sealed class ParquetSinkArgs : Pulumi.ResourceArgs { /// <summary> /// Parquet format settings. /// </summary> [Input("formatSettings")] public Input<Inputs.ParquetWriteSettingsArgs>? FormatSettings { get; set; } /// <summary> /// The maximum concurrent connection count for the sink data store. Type: integer (or Expression with resultType integer). /// </summary> [Input("maxConcurrentConnections")] public Input<object>? MaxConcurrentConnections { get; set; } /// <summary> /// Sink retry count. Type: integer (or Expression with resultType integer). /// </summary> [Input("sinkRetryCount")] public Input<object>? SinkRetryCount { get; set; } /// <summary> /// Sink retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("sinkRetryWait")] public Input<object>? SinkRetryWait { get; set; } /// <summary> /// Parquet store settings. /// </summary> [Input("storeSettings")] public Input<object>? StoreSettings { get; set; } /// <summary> /// Copy sink type. /// Expected value is 'ParquetSink'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// Write batch size. Type: integer (or Expression with resultType integer), minimum: 0. /// </summary> [Input("writeBatchSize")] public Input<object>? WriteBatchSize { get; set; } /// <summary> /// Write batch timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> [Input("writeBatchTimeout")] public Input<object>? WriteBatchTimeout { get; set; } public ParquetSinkArgs() { } } }
34.333333
148
0.58212
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataFactory/Inputs/ParquetSinkArgs.cs
2,472
C#
using Sandbox; public class ViewModel : BaseViewModel { protected float SwingInfluence => 0.05f; protected float ReturnSpeed => 5.0f; protected float MaxOffsetLength => 10.0f; protected float BobCycleTime => 7; protected Vector3 BobDirection => new Vector3( 0.0f, 1.0f, 0.5f ); private Vector3 swingOffset; private float lastPitch; private float lastYaw; private float bobAnim; private bool activated = false; public override void UpdateCamera( Camera camera ) { if ( !Player.Local.IsValid() ) return; if ( !activated ) { lastPitch = camera.Rot.Pitch(); lastYaw = camera.Rot.Yaw(); activated = true; } WorldPos = camera.Pos; WorldRot = camera.Rot; camera.ViewModelFieldOfView = FieldOfView; var newPitch = WorldRot.Pitch(); var newYaw = WorldRot.Yaw(); var pitchDelta = Angles.NormalizeAngle( newPitch - lastPitch ); var yawDelta = Angles.NormalizeAngle( lastYaw - newYaw ); var playerVelocity = Player.Local.Velocity; var verticalDelta = playerVelocity.z * Time.Delta; var viewDown = Rotation.FromPitch( newPitch ).Up * -1.0f; verticalDelta *= (1.0f - System.MathF.Abs( viewDown.Cross( Vector3.Down ).y )); pitchDelta -= verticalDelta * 1; var offset = CalcSwingOffset( pitchDelta, yawDelta ); offset += CalcBobbingOffset( playerVelocity ); WorldPos += WorldRot * offset; lastPitch = newPitch; lastYaw = newYaw; } protected Vector3 CalcSwingOffset( float pitchDelta, float yawDelta ) { Vector3 swingVelocity = new Vector3( 0, yawDelta, pitchDelta ); swingOffset -= swingOffset * ReturnSpeed * Time.Delta; swingOffset += (swingVelocity * SwingInfluence); if ( swingOffset.Length > MaxOffsetLength ) { swingOffset = swingOffset.Normal * MaxOffsetLength; } return swingOffset; } protected Vector3 CalcBobbingOffset( Vector3 velocity ) { bobAnim += Time.Delta * BobCycleTime; var twoPI = System.MathF.PI * 2.0f; if ( bobAnim > twoPI ) { bobAnim -= twoPI; } var speed = new Vector2( velocity.x, velocity.y ).Length; speed = speed > 10.0 ? speed : 0.0f; var offset = BobDirection * (speed * 0.005f) * System.MathF.Cos( bobAnim ); offset = offset.WithZ( -System.MathF.Abs( offset.z ) ); return offset; } }
24.582418
81
0.699151
[ "MIT" ]
AdamSai/sandbox
code/ViewModel.cs
2,239
C#
 namespace SampleWopiHandler { class CheckFileInfoResponse { // This is a subset of all CheckFileInfo properties. // Use optional properties in accordance with the [MS-WOPI] Web Application Open Platform Interface Protocol specification. public string BaseFileName { get; set; } public string OwnerId { get; set; } public int Size { get; set; } public string Version { get; set; } public string BreadcrumbBrandName { get; set; } public string BreadcrumbBrandUrl { get; set; } public string BreadcrumbFolderName { get; set; } public string BreadcrumbFolderUrl { get; set; } public string BreadcrumbDocName { get; set; } public string BreadcrumbDocUrl { get; set; } public bool UserCanWrite { get; set; } public bool ReadOnly { get; set; } public bool SupportsLocks { get; set; } public bool SupportsUpdate { get; set; } public bool UserCanNotWriteRelative { get; set; } public string UserFriendlyName { get; set; } } class PutRelativeFileResponse { public string Name { get; set; } public string Url { get; set; } public string HostViewUrl { get; set; } public string HostEditUrl { get; set; } } }
35.189189
131
0.632873
[ "MIT" ]
CedarLogic/Office-Online-Test-Tools-and-Documentation
samples/SampleWopiHandler/SampleWopiHandler/WopiResponse.cs
1,304
C#
/*---------------------------------------------------------------- Copyright (C) 2018 Senparc 文件名:DepartmentResult.cs 文件功能描述:成员接口返回结果 创建标识:Senparc - 20150313 修改标识:Senparc - 20150313 修改描述:整理接口 修改标识:Senparc - 20180828 修改描述:v0.4.2 添加 GetMemberResult.order 属性 修改标识:Senparc - 20171017 修改描述:v1.2.0 部门id改为long类型 ----------------------------------------------------------------*/ using System.Collections.Generic; using Senparc.Weixin.Entities; using Senparc.Weixin.Work.AdvancedAPIs.MailList.Member; namespace Senparc.Weixin.Work.AdvancedAPIs.MailList { /// <summary> /// GetMemberResult【QY移植修改】 /// </summary> public class GetMemberResult : WorkJsonResult { /// <summary> /// 员工UserID /// </summary> public string userid { get; set; } /// <summary> /// 成员名称 /// </summary> public string name { get; set; } /// <summary> /// 成员所属部门id列表 /// </summary> public long[] department { get; set; } /// <summary> /// 部门内的排序值,默认为0。数量必须和department一致,数值越大排序越前面。值范围是[0, 2^32) /// </summary> public int[] order { get; set; } /// <summary> /// 职位信息 /// </summary> public string position { get; set; } /// <summary> /// 手机号码 /// </summary> public string mobile { get; set; } /// <summary> /// 性别。gender=0表示男,=1表示女 /// </summary> public int gender { get; set; } /// <summary> /// 邮箱 /// </summary> public string email { get; set; } /// <summary> /// 上级字段,标识是否为上级。第三方暂不支持 /// </summary> public int isleader { get; set; } /// <summary> /// 头像url。注:小图将url最后的"/0"改成"/64" /// </summary> public string avatar { get; set; } /// <summary> /// 激活状态: 1=已激活,2=已禁用,4=未激活 已激活代表已激活企业微信或已关注微信插件。未激活代表既未激活企业微信又未关注微信插件。 /// </summary> public int status { get; set; } /// <summary> /// 座机。第三方暂不支持 /// </summary> public string telephone { get; set; } /// <summary> /// 英文名。第三方暂不支持 /// </summary> public string english_name { get; set; } /// <summary> /// 扩展属性 /// </summary> public Extattr extattr { get; set; } /// <summary> /// 启用/禁用成员,第三方不可获取。1表示启用成员,0表示禁用成员 /// </summary> public int enable { get; set; } /// <summary> /// 关注微信插件的状态: 1=已关注,0=未关注 /// </summary> public string wxplugin_status { get; set; } } public class GetDepartmentMemberResult : WorkJsonResult { /// <summary> /// 成员列表 /// </summary> public List<UserList_Simple> userlist { get; set; } } /// <summary> /// UserList_Simple【QY移植修改】 /// </summary> public class UserList_Simple { /// <summary> /// 员工UserID /// </summary> public string userid { get; set; } /// <summary> /// 成员名称 /// </summary> public string name { get; set; } /// <summary> /// 成员所属部门 /// </summary> public long[] department { get; set; } } /// <summary> /// 获取部门成员(详情)返回结果 /// </summary> public class GetDepartmentMemberInfoResult : WorkJsonResult { /// <summary> /// 成员列表 /// </summary> public List<GetMemberResult> userlist { get; set; } } public class InviteMemberResult : WorkJsonResult { /// <summary> /// 1:微信邀请 2.邮件邀请 /// </summary> public int type { get; set; } } }
25.469388
79
0.483173
[ "Apache-2.0" ]
29366365/WeiXinMPSDK
src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/MailList/Member/MemberResult.cs
4,442
C#
using Kingmaker.Blueprints; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.Blueprints.Facts; using Kingmaker.Blueprints.JsonSystem; using Kingmaker.EntitySystem.Entities; using Kingmaker.Enums; using Kingmaker.PubSubSystem; using Kingmaker.RuleSystem.Rules; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Mechanics; using Kingmaker.Utility; using UnityEngine; using UnityEngine.Serialization; namespace TabletopTweaks.NewComponents { [TypeId("7faa8aa8ecb445629a804248ac4fdba1")] class SpellImmunityToSpellDescriptorAgainstAlignment: UnitFactComponentDelegate, IInitiatorRulebookHandler<RuleCanApplyBuff>, IRulebookHandler<RuleCanApplyBuff>, ISubscriber, IInitiatorRulebookSubscriber, IInitiatorRulebookHandler<RuleSavingThrow>, IRulebookHandler<RuleSavingThrow> { public BlueprintUnitFact IgnoreFeature { get { BlueprintUnitFactReference ignoreFeature = this.m_IgnoreFeature; if (ignoreFeature == null) { return null; } return ignoreFeature.Get(); } } public BlueprintUnitFact FactToCheck { get { BlueprintUnitFactReference factToCheck = this.m_FactToCheck; if (factToCheck == null) { return null; } return factToCheck.Get(); } } private bool IsImmune(MechanicsContext context) { UnitEntityData maybeCaster = context.MaybeCaster; if ((maybeCaster != null) ? maybeCaster.State.Features.MythicReduceResistances : null) { return false; } bool noCaster = context.MaybeCaster == null; bool hasDescriptor = this.Descriptor.HasAnyFlag(context.SpellDescriptor); bool noImmunityBypassFeature = this.IgnoreFeature == null || noCaster || !context.MaybeCaster.Descriptor.HasFact(this.IgnoreFeature); bool noImmunityFact = !this.CheckFact || (!noCaster && context.MaybeCaster.Descriptor.HasFact(this.FactToCheck)); bool casterHasAlignment = !noCaster && context.MaybeCaster.Descriptor.Alignment.ValueRaw.HasComponent(this.Alignment); bool spellHasAlignment = context.SpellDescriptor.HasAnyFlag(this.Alignment.GetAlignmentDescriptor()); return hasDescriptor && noImmunityBypassFeature && noImmunityFact && (casterHasAlignment || spellHasAlignment); } public void OnEventAboutToTrigger(RuleCanApplyBuff evt) { if (this.IsImmune(evt.Context)) { evt.Immunity = true; } } public void OnEventDidTrigger(RuleCanApplyBuff evt) { } public void OnEventAboutToTrigger(RuleSavingThrow evt) { if (evt.Buff != null) { MechanicsContext context = evt.Reason.Context; CountableFlag flag; if (context == null) { flag = null; } else { UnitEntityData maybeCaster = context.MaybeCaster; flag = ((maybeCaster != null) ? maybeCaster.State.Features.MythicReduceResistances : null); } if (flag && this.Descriptor.HasAnyFlag(evt.Buff.SpellDescriptor)) { evt.D20.AddReroll(1, true, base.Fact); } } } #pragma warning disable IDE0044 // Add readonly modifier public void OnEventDidTrigger(RuleSavingThrow evt) { } public AlignmentComponent Alignment; public SpellDescriptorWrapper Descriptor; [SerializeField] [FormerlySerializedAs("IgnoreFeature")] private BlueprintUnitFactReference m_IgnoreFeature = null; public bool CheckFact = false; [ShowIf("CheckFact")] [SerializeField] [FormerlySerializedAs("FactToCheck")] private BlueprintUnitFactReference m_FactToCheck = null; #pragma warning restore IDE0044 // Add readonly modifier } }
40.8
145
0.642402
[ "MIT" ]
justamblingalong/WrathMods-TabletopTweaks
TabletopTweaks/NewComponents/SpellImmunityToSpellDescriptorAgainstAlignment.cs
4,082
C#
using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace BTCPayServer.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20180106095215_DerivationStrategies")] public partial class DerivationStrategies : Migration { protected override void Up(MigrationBuilder migrationBuilder) { int? maxLength = this.IsMySql(migrationBuilder.ActiveProvider) ? (int?)255 : null; migrationBuilder.AddColumn<string>( name: "DerivationStrategies", table: "Stores", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "DerivationStrategies", table: "Stores"); } } }
31.433333
94
0.659597
[ "MIT" ]
Argoneum/btcpayserver
BTCPayServer.Data/Migrations/20180106095215_DerivationStrategies.cs
945
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // #if UNITY_WINRT && !UNITY_EDITOR #define USE_WINRT #endif using UnityEngine; using System.Collections; using System.Collections.Generic; using HUX.Utility; using System.Reflection; using HUX; using UnityEngine.VR; using HUX.Focus; /// <summary> /// InputShellMap is responsible for reading input from input sources and feeding it into InputShell. /// It performs the switching logic so that a particular input source can be "activated" for use and /// take precedence over /// /// A brief overview of the flow of input: /// Input APIs -> InputSourceBase -> InputShellMap -> InputShell -> HUX /// /// </summary> public class InputShellMap : Singleton<InputShellMap> { // Store a reference to the InputShell instance for convenient access InputShell inputShell; // InputSources gathers all the input sources public InputSources inputSources = new InputSources(); // Helper class to handle deciding when to switch between the types of input public InputSwitchLogic inputSwitchLogic = new InputSwitchLogic(); // Input states: Handle scaling for sources -> sematics // Hands public Vector2ControlState stateHandZoom = new Vector2ControlState(); // Mouse public Vector2ControlState stateMouseWheelZoom = new Vector2ControlState(new Vector2(0, 1f / 40f)); // 6dof public Vector2ControlState stateSixDOFZoom = new Vector2ControlState(); // controller public Vector2ControlState stateLeftJoyScroll = new Vector2ControlState(new Vector2(-0.1f, -0.1f)); public Vector2ControlState stateLeftJoyTranslate = new Vector2ControlState(new Vector2(1f, 1f)); public Vector2ControlState stateTrigZoom = new Vector2ControlState(new Vector2(1f, 0.01f)); public Vector2ControlState stateRightJoyRotate = new Vector2ControlState(new Vector2(0.75f, 0.75f)); public Vector2ControlState statePadTranslate = new Vector2ControlState(); public Vector2ControlState statePadCardinal = new Vector2ControlState(); public Vector2ControlState stateLeftJoyCardinal = new Vector2ControlState(); // Targeting scroll gesture public Vector2ControlState stateTargetScroll = new Vector2ControlState(false); #region Debug controls // If true, the gamepad will be used to control a world cursor [DebugTunable] public bool GamepadCursor = false; #endregion /// <summary> /// Awake and init components /// </summary> protected override void Awake() { base.Awake(); inputSources.Init(gameObject); inputSwitchLogic.Init(inputSources); // I don't like hooking everything up with just events. There could be too many situations where // a chain of subscribers is called all from one entry point, and the order of execution isn't very // clear. A polling method would reduce these situations. The only downside is that it's somewhat // convenient having events, especially if the input source is updating faster than the polling rate. // Input sources can provide events if they don't aggregate their data. InputShell can provide events // since it's convenient to use at the app level. A downside with using polling is that dependencies // between sources can also get complicated and make update order unclear... } /// <summary> /// Additional init, ensures that InputShell has instance allocated /// </summary> void Start() { inputShell = InputShell.Instance; // Shell control states don't need to generate events inputShell.ZoomVector.GenerateButtonEvents = false; inputShell.ScrollVector.GenerateButtonEvents = false; } /// <summary> /// MonoBehavior update. Updates the InputSources and InputSwitchLogic components, /// updates all input states, and then applies the input to the shell. Finally, /// updates InputShell. /// </summary> void Update() { // Apply debug tunes inputSources.gamepad.IsEnabled = !GamepadCursor; inputSources.worldCursorGamepad.IsEnabled = GamepadCursor; // Update all InputSources (manually, so we can control update order) inputSources.Update(); // Update the input switching logic inputSwitchLogic.Update(); // Update input states UpdateStates(); // Now apply to the shell and dev input states ApplyInputToShell(); ApplyInputToDev(); // Update shell input, synchronously. This will allow InputShell to do any necessary logic before reporting input events inputShell._Update(); } /// <summary> /// Maps input from sources and states to the shell input interface /// </summary> void ApplyInputToShell() { InputShell shell = inputShell; // Update select button bool selectButton = inputSwitchLogic.GetCurrentSelectPressed(); shell.SelectButton.ApplyState(selectButton); // Update menu button bool menuButton = inputSwitchLogic.GetAnyMenuPressed(); shell.MenuButton.ApplyState(menuButton); // Update the scroll vector shell.ScrollVector.AddState(inputSources.touch6D.touchState); if (inputSources.gamepad.IsActiveTargetingSource() && !inputSources.gamepad.JoystickDragging) { shell.ScrollVector.AddState(stateLeftJoyScroll); } shell.ScrollVector.AddState(stateTargetScroll); shell.ScrollVector.FinalizeState(); // Update the zoom vector shell.ZoomVector.AddState(stateHandZoom); shell.ZoomVector.AddState(stateSixDOFZoom); shell.ZoomVector.AddState(inputSources.editor.dragControl); shell.ZoomVector.AddState(stateMouseWheelZoom); shell.ZoomVector.AddState(stateTrigZoom); shell.ZoomVector.FinalizeState(); // Update the cardinal input vector shell.CardinalVector.AddState(stateLeftJoyCardinal); shell.CardinalVector.AddState(statePadCardinal); shell.CardinalVector.FinalizeState(); // Update targeting ray shell.TargetOrigin = inputSwitchLogic.GetTargetOrigin(); shell.TargetOrientation = inputSwitchLogic.GetTargetOrientation(); shell.TargetingReady = inputSwitchLogic.GetTargetingReady(); } /// <summary> /// Maps input from sources and states to the dev input interface /// </summary> void ApplyInputToDev() { InputDev dev = InputDev.Instance; #if UNITY_EDITOR // Update virtual cam input dev.VirtualCamMovementToggle.ApplyState(inputSources.gamepad.xButtonPressed); if (dev.VirtualCamMovementToggle.pressed) { dev.VirtualCamTranslate.AddState(false, inputSources.gamepad.leftJoyVector); } dev.VirtualCamTranslate.AddState(false, GetDevCameraVector(true)); dev.VirtualCamTranslate.FinalizeState(); if (dev.VirtualCamMovementToggle.pressed) { dev.VirtualCamVertAndRoll.AddState(false, new Vector2(-inputSources.gamepad.trigVector.x + inputSources.gamepad.trigVector.y, 0)); } dev.VirtualCamVertAndRoll.AddState(false, GetDevCameraVector(false)); dev.VirtualCamVertAndRoll.FinalizeState(); dev.VirtualCamRotate.AddState(stateRightJoyRotate); dev.VirtualCamRotate.FinalizeState(); #endif } Vector2 GetDevCameraVector(bool translate) { Vector2 vec = Vector2.zero; if (translate) { vec.x += (InputSourceKeyboard.GetKey(KeyCode.A) ? -1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.D) ? 1f : 0); vec.y += (InputSourceKeyboard.GetKey(KeyCode.S) ? -1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.W) ? 1f : 0); } else { vec.x += (InputSourceKeyboard.GetKey(KeyCode.E) ? 1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.Q) ? -1f : 0); } return vec; } /// <summary> /// Updates all control states. See InputControlState.cs. /// </summary> void UpdateStates() { // Hand zoom gesture stateHandZoom.ApplyState(inputSources.hands.dragControl); // Mouse wheel zoom stateMouseWheelZoom.AddState(false, new Vector2(0, inputSources.editor.mouseSource.ScrollWheelDelta)); stateMouseWheelZoom.AddState(false, new Vector2(0, inputSources.worldCursorMouse.mouseSource.ScrollWheelDelta)); stateMouseWheelZoom.FinalizeState(); // SixDOF zoom gesture stateSixDOFZoom.ApplyDelta(false, new Vector2(0, inputSources.touch6D.dragControl.delta.y)); // Controller input maps to scrolling, zooming, and freecam input stateLeftJoyScroll.ApplyDelta(false, inputSources.gamepad.leftJoyVector); stateLeftJoyTranslate.ApplyDelta(false, inputSources.gamepad.leftJoyVector); stateTrigZoom.ApplyDelta(false, new Vector2(0, -inputSources.gamepad.trigVector.x + inputSources.gamepad.trigVector.y)); stateRightJoyRotate.ApplyDelta(false, inputSources.gamepad.rightJoyVector); statePadTranslate.ApplyDelta(false, inputSources.gamepad.padVector); statePadCardinal.ApplyDelta(false, inputSources.gamepad.padVector); // Joystick cardinal state Vector2 joyPos = Vector2.zero; if (inputSources.gamepadCardinal.IsActiveTargetingSource()) { float mag = 0.7f; if (inputSources.gamepad.leftJoyVector.sqrMagnitude > mag * mag) { joyPos = inputSources.gamepad.leftJoyVector; // Quantize joyPos.x = (float)Mathf.RoundToInt(5f * joyPos.x) / 5f; joyPos.y = (float)Mathf.RoundToInt(5f * joyPos.y) / 5f; } } stateLeftJoyCardinal.ApplyDelta(false, joyPos); // Update drag gesture InputSourceBase curSource = inputSwitchLogic.CurrentTargetingSource as InputSourceBase; if (curSource != null && curSource.IsManipulating()) { stateTargetScroll.ApplyPos(true, curSource.GetManipulationPlaneProjection()); //Debug.Log("scroll state delta: " + stateTargetScroll.delta); } else { stateTargetScroll.ApplyPos(false, Vector2.zero); //Debug.Log("scroll (done) state delta: " + stateTargetScroll.delta); } } /// <summary> /// Returns true if a hold gesture can be completed. Hold gestures cannot be completed if the user /// is currently interacting with something. /// </summary> public bool CanCompleteHoldGesture() { return !InputShell.Instance.IsAnyManipulating(); } } /// <summary> /// InputSwitchLogic holds a list of all targeting input sources and provides very simple logic for /// activating and switching between inputs, and getting input from the current input. /// InputSwitchLogic is instantiated and used by InputShellMap. /// </summary> [System.Serializable] public class InputSwitchLogic { // Hold pointer to InputSources for convenient access InputSources inputSources; // The current targetin source public ITargetingInputSource CurrentTargetingSource; // List of all input sources which implement ITargetingInputSource public List<ITargetingInputSource> TargetingSources = new List<ITargetingInputSource>(); // The same list, but InputSourceBase pointers public List<InputSourceBase> TargetingSourceBases = new List<InputSourceBase>(); // Print to debug log when sources are activated or deactivated public bool debugPrint = false; /// <summary> /// Initialization. Stores all input sources from InputSources which implement ITargetingInputSource /// </summary> /// <param name="_inputSources"></param> public void Init(InputSources _inputSources) { inputSources = _inputSources; foreach (InputSourceBase source in inputSources.sources) { //if( source.GetType().IsAssignableFrom(typeof(ITargetingInputSource))) if (source is ITargetingInputSource) { TargetingSources.Add(source as ITargetingInputSource); TargetingSourceBases.Add(source); } } if (debugPrint) { Debug.Log("TargetingSources: " + TargetingSources.Count); } CurrentTargetingSource = inputSources.hands; } /// <summary> /// Returns true if the current input source has select pressed. /// </summary> public bool GetCurrentSelectPressed() { if (CurrentTargetingSource != null) { return CurrentTargetingSource.IsSelectPressed(); } return false; } /// <summary> /// Returns true if any enabled input source has menu pressed /// </summary> public bool GetAnyMenuPressed() { foreach (InputSourceBase source in inputSources.sources) { if (source.IsEnabled) { ITargetingInputSource targetSource = source as ITargetingInputSource; if (targetSource != null && targetSource.IsMenuPressed()) { return true; } } } return false; } /// <summary> /// Returns true if the specified source is the active targeting source /// </summary> public bool IsTargetingSourceActive(InputSourceBase source) { return CurrentTargetingSource == source as ITargetingInputSource; } /// <summary> /// Returns the origin of the current targeting source /// </summary> public Vector3 GetTargetOrigin() { if (CurrentTargetingSource != null) { return CurrentTargetingSource.GetTargetOrigin(); } return Veil.Instance.HeadTransform.position; } /// <summary> /// Returns the rotation of the current targeting source /// </summary> public Quaternion GetTargetOrientation() { if (CurrentTargetingSource != null) { return CurrentTargetingSource.GetTargetRotation(); } return Veil.Instance.HeadTransform.rotation; } /// <summary> /// Returns true if the current targeting source is in the 'ready' state /// </summary> public bool GetTargetingReady() { if (CurrentTargetingSource != null) { return CurrentTargetingSource.IsReady(); } return false; } /// <summary> /// Gets the focuser tied to the current active input source. /// </summary> /// <returns></returns> public AFocuser GetFocuserForCurrentTargetingSource() { AFocuser focuser = null; if (FocusManager.Instance != null) { for (int index = 0; index < FocusManager.Instance.Focusers.Length; index++) { InputSourceFocuser sourceFocuser = FocusManager.Instance.Focusers[index] as InputSourceFocuser; if (sourceFocuser != null && sourceFocuser.TargetingInputSource == CurrentTargetingSource) { focuser = FocusManager.Instance.Focusers[index]; break; } } //If we haven't found a specific focuser use the gaze. if (focuser == null) { focuser = FocusManager.Instance.GazeFocuser; } } return focuser; } /// <summary> /// Checks all enabled input sources and activates a new source if requested /// </summary> public void Update() { for (int i = 0; i < TargetingSources.Count; ++i) { ITargetingInputSource targetSource = TargetingSources[i]; if (TargetingSourceBases[i].IsEnabled) { if (targetSource != CurrentTargetingSource && targetSource.ShouldActivate()) { ActivateTargetingSource(targetSource); break; } } } } /// <summary> /// Deactivates the current source and activateds the new source /// </summary> public void ActivateTargetingSource(ITargetingInputSource targetSource) { if (CurrentTargetingSource != null && CurrentTargetingSource != targetSource) { CurrentTargetingSource.OnActivate(false); } CurrentTargetingSource = targetSource; if (CurrentTargetingSource != null) { if (debugPrint) { Debug.Log("Activating source " + CurrentTargetingSource); } CurrentTargetingSource.OnActivate(true); } } }
35.409664
142
0.65749
[ "MIT" ]
AllBecomesGood/Share-UpdateHolograms
ShareAndKeepSynced/Assets/MRDesignLab/HUX/Scripts/Input/InputShellMap.cs
16,855
C#
using System; using System.Linq; using System.Reflection; namespace Unity.Tests.v5.TestSupport { public static class TypeReflectionExtensions { public static ConstructorInfo GetMatchingConstructor(this Type type, Type[] constructorParamTypes) { return type.GetTypeInfo().DeclaredConstructors .Where(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(constructorParamTypes)) .FirstOrDefault(); } } }
29.176471
112
0.677419
[ "Apache-2.0" ]
DoctorVanGogh/container
tests/Unity.Tests/TestSupport/TypeReflectionExtensions.cs
498
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Max; namespace Max2Babylon.FlightSim { static class FlightSimExtensionUtility { public static float GetGizmoParameterFloat(IINode node, string gizmoClass, string paramName, bool IsSubClass = true) { string mxs = String.Empty; if (!IsSubClass) { mxs = $"(maxOps.getNodeByHandle {node.Handle}).{paramName}"; } else { mxs = $"(maxOps.getNodeByHandle {node.Handle}).{gizmoClass}.{paramName}"; } IFPValue mxsRetVal = Loader.Global.FPValue.Create(); ScriptsUtilities.ExecuteMAXScriptScript(mxs, true, mxsRetVal); var r= mxsRetVal.F; return r; } public static bool GetGizmoParameterBoolean(IINode node, string gizmoClass, string paramName, bool IsSubClass = true) { string mxs = String.Empty; if (!IsSubClass) { mxs = $"(maxOps.getNodeByHandle {node.Handle}).{paramName}"; } else { mxs = $"(maxOps.getNodeByHandle {node.Handle}).{gizmoClass}.{paramName}"; } IFPValue mxsRetVal = Loader.Global.FPValue.Create(); ScriptsUtilities.ExecuteMAXScriptScript(mxs, true, mxsRetVal); var r = mxsRetVal.B; return r; } public static float[] GetTranslation(IINode node,IINode renderedNode) { float[] res = new float[3]; //IPoint3 translation = node.GetNodeTM(0, Tools.Forever).Trans; //position relative to parent, translation IObject obj = node.ObjectRef; IBox3 bbox = obj.GetWorldBoundBox(0, node, Loader.Core.ActiveViewExp); IPoint3 bboxCenter = bbox.Center; IMatrix3 inverted = renderedNode.GetNodeTM(0, Tools.Forever); inverted.Invert(); IPoint3 bboxCenterInRenderNodeSpace = inverted.PointTransform(bboxCenter); res[0] = bboxCenterInRenderNodeSpace.X; res[1] = bboxCenterInRenderNodeSpace.Z; res[2] = -bboxCenterInRenderNodeSpace.Y; return res; } public static float[] GetRotation(IINode node,IINode renderedNode) { float[] res = new float[4]; IMatrix3 nodeTm = node.GetNodeTM(0, Tools.Forever); IMatrix3 inverted = renderedNode.GetNodeTM(0, Tools.Forever); inverted.Invert(); nodeTm = nodeTm.Multiply(inverted); IPoint3 p = Loader.Global.Point3.Create(0, 0, 0); IQuat q = Loader.Global.IdentQuat; IPoint3 s = Loader.Global.Point3.Create(0, 0, 0); Loader.Global.DecomposeMatrix(nodeTm,p,q,s); q.Normalize(); res[0] = q[0]; res[1] = q[2]; res[2] = -q[1]; res[3] = -q[3]; return res; } public static bool IsDefaultRotation(float[] rotation) { if (rotation[0] == 0 && rotation[1] == 0 && rotation[2] == 0 && (rotation[3] == 1.0f || rotation[3]==-1.0f )) return true; return false; } } }
35.306122
135
0.542197
[ "Apache-2.0" ]
AsoboStudio/FlightSim-glTF-exporter
3ds Max/Max2Babylon/FlightSim/FlightSimExtensionUtility.cs
3,460
C#
#region License //Ntreev Photoshop Document Parser for .Net // //Released under the MIT License. // //Copyright (c) 2015 Ntreev Soft co., Ltd. // //Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated //documentation files (the "Software"), to deal in the Software without restriction, including without limitation the //rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit //persons to whom the Software is furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all copies or substantial portions of the //Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE //WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ntreev.Library.Psd { public interface IChannel { byte[] Data { get; } ChannelType Type { get; } } }
35.595238
121
0.725753
[ "MIT" ]
FrankNine/Agugu
Unity/Agugu/Assets/Agugu/Editor/Ntreev.Library.Psd/IChannel.cs
1,497
C#
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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 System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using XenAPI; namespace XenAdminTests.UnitTests.UnitTestHelper.MockObjectBuilders { public class MockVdiWithVbds : MockObjectBuilder { public MockVdiWithVbds(MockObjectManager mom, string connectionId) : base(mom, connectionId) { NumberOfVbdsToAdd = 1; } public override Type MockedType { get { return typeof (VDI); } } public int NumberOfVbdsToAdd { private get; set; } public override Mock BuildObject() { Mock<VDI> vdi = ObjectManager.NewXenObject<VDI>(ConnectionId); List<XenRef<VBD>> vbdRefs = Enumerable.Repeat(new XenRef<VBD>("opaqueref"), NumberOfVbdsToAdd).ToList(); vdi.Setup(v => v.VBDs).Returns(vbdRefs); return vdi; } } }
37.40625
117
0.67878
[ "BSD-2-Clause" ]
ChrisH4rding/xenadmin
XenAdminTests/UnitTests/UnitTestHelper/MockObjectBuilders/MockVdiWithVbds.cs
2,396
C#
using System; using System.Xml.Serialization; namespace Top.Api.Response { /// <summary> /// FenxiaoDealerRequisitionorderRefuseResponse. /// </summary> public class FenxiaoDealerRequisitionorderRefuseResponse : TopResponse { /// <summary> /// 操作是否成功。true:成功;false:失败。 /// </summary> [XmlElement("is_success")] public bool IsSuccess { get; set; } } }
23.111111
74
0.627404
[ "MIT" ]
objectyan/MyTools
OY.Solution/OY.TopSdk/Response/FenxiaoDealerRequisitionorderRefuseResponse.cs
446
C#
using DragonSpark.Runtime.Execution; using System; namespace DragonSpark.Application.Entities; sealed class AmbientLock : Logical<IDisposable?> { public static AmbientLock Default { get; } = new(); AmbientLock() {} }
20.181818
52
0.761261
[ "MIT" ]
DragonSpark/Framework
DragonSpark.Application/Entities/AmbientLock.cs
224
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SoundSampler.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.6.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; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("null")] public string Port { get { return ((string)(this["Port"])); } set { this["Port"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool bassBased { get { return ((bool)(this["bassBased"])); } set { this["bassBased"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("2.5")] public double UpdateSpeed { get { return ((double)(this["UpdateSpeed"])); } set { this["UpdateSpeed"] = value; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("115200")] public int baud { get { return ((int)(this["baud"])); } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0.999")] public double entropy { get { return ((double)(this["entropy"])); } set { this["entropy"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0.85")] public double smoothing { get { return ((double)(this["smoothing"])); } set { this["smoothing"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public int portIndex { get { return ((int)(this["portIndex"])); } set { this["portIndex"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("3")] public int updateSpeedIndex { get { return ((int)(this["updateSpeedIndex"])); } set { this["updateSpeedIndex"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("1")] public int audioHandlingIndex { get { return ((int)(this["audioHandlingIndex"])); } set { this["audioHandlingIndex"] = value; } } } }
36.530303
151
0.550394
[ "MIT" ]
SirHawkinson/SoundSampler
SoundSampler/Properties/Settings.Designer.cs
4,824
C#
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Data.Entity; using System.Data.Entity.Core; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using Hotcakes.Web.Logging; namespace Hotcakes.Web.Data { [Serializable] public class DatabaseStrategy<T> : IRepositoryStrategy<T> where T : class, new() { private bool _AutoSubmit = true; private readonly DbContext _dbContext; private readonly ObjectContext _objectContext; private ObjectSet<T> _objectSet; public DatabaseStrategy(DbContext context) { Logger = new NullLogger(); _dbContext = context; _objectContext = (context as IObjectContextAdapter).ObjectContext; // Call this to force init on _objectset var obj = objectSet; } private IObjectSet<T> objectSet { get { if (_objectSet == null) { _objectSet = _objectContext .CreateObjectSet<T>(); } return _objectSet; } } public bool AutoSubmit { get { return _AutoSubmit; } set { _AutoSubmit = value; } } public ILogger Logger { get; set; } public bool SubmitChanges() { if (_objectContext != null) { try { _dbContext.SaveChanges(); return true; } catch (OptimisticConcurrencyException cex) { Logger.LogMessage("Hotcakes.Web.Data", "Concurrency exception while saving changes in EntityFrameworkRespository" + cex.Message + " " + cex.StackTrace, EventLogSeverity.Debug); } } return false; } public T FindByPrimaryKey(PrimaryKey id) { var setName = _objectSet.Context.DefaultContainerName + "." + _objectSet.EntitySet.Name; var key = new EntityKey(setName, id.KeyName, id.KeyAsObject()); try { var found = _objectContext.GetObjectByKey(key); if (found != null) { return (T) found; } } catch (ObjectNotFoundException) { } catch (Exception ex) { Logger.LogMessage("Hotcakes.Web.Data", "Find by Primary Key Failure: " + "KEY=" + id.KeyAsObject() + ", EntitySetName=" + _objectSet.EntitySet.Name + ", EXCEPTION=" + ex + " " + ex.StackTrace, EventLogSeverity.Debug); } return null; } public IQueryable<T> Find() { try { return objectSet; } catch (Exception ex) { Logger.LogException(ex, EventLogSeverity.Debug); } return null; } public bool Create(T item) { try { objectSet.AddObject(item); if (AutoSubmit) SubmitChanges(); return true; } catch (Exception ex) { Logger.LogException(ex, EventLogSeverity.Debug); } return false; } public bool Delete(PrimaryKey id) { var found = FindByPrimaryKey(id); if (found == null) return false; objectSet.DeleteObject(found); if (_AutoSubmit) SubmitChanges(); return true; } public void Detach(T item) { objectSet.Detach(item); } public int CountOfAll() { try { return objectSet.Count(); } catch (Exception ex) { Logger.LogException(ex, EventLogSeverity.Debug); } return -1; } } }
31.122905
120
0.518578
[ "MIT" ]
HotcakesCommerce/core
Libraries/Hotcakes.Web/Data/DatabaseStrategy.cs
5,573
C#
using System; using ByteDev.Pagination.Presentation; using ByteDev.Pagination.Presentation.PageOffSet; using NUnit.Framework; namespace ByteDev.Pagination.UnitTests.Presentation { [TestFixture] public class PageNumbersFactoryTests { private IPageOffSetStrategy _offSetZero; private IPageOffSetStrategy _offSetFive; [SetUp] public void SetUp() { _offSetZero = new PageOffSetStrategyFakeZero(); _offSetFive = new PageOffSetStrategyFakeFive(); } [TestFixture] public class Create : PageNumbersFactoryTests { [Test] public void WhenPagingInfoIsNull_ThenThrowException() { var classUnderTest = CreateClassUnderTest(); Assert.Throws<ArgumentNullException>(() => classUnderTest.Create(null)); } [TestCase(10, 3, 4)] // 10 / 3 = 3.33 [TestCase(10, 6, 2)] // 10 / 6 = 1.66 [TestCase(10, 2, 5)] // 10 / 2 = 5 [TestCase(110, 10, 11)] // 110 / 10 = 11 public void WhenZeroOffSet_ThenCreateCorrectSizeOfList(int totalItemsCount, int pageSize, int expected) { var pagingInfo = new PresentationPagingInfo(totalItemsCount, pageSize, 0, 1000); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); Assert.That(pageNumbers.Count, Is.EqualTo(expected)); } [Test] public void WhenZeroOffSet_AndPageNumberCountIsGreaterThanMaxPageNumbersToShow_ThenCreateListOfSizeMaxPageNumbersToShow() { const int maxPageNumbersToShow = 11; var pagingInfo = new PresentationPagingInfo(110, 10, 0, maxPageNumbersToShow); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); // 120 / 10 = 12 Assert.That(pageNumbers.Count, Is.EqualTo(maxPageNumbersToShow)); } [Test] public void WhenZeroOffSet_AndTotalItemCountIsZero_ThenCreateEmptyCollection() { var pagingInfo = new PresentationPagingInfo(0, 2, 0); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); Assert.That(pageNumbers.Count, Is.EqualTo(0)); } [Test] public void WhenZeroOffSet_ThenSetIsCurrentPageTo1stPage() { var pagingInfo = new PresentationPagingInfo(10, 3, 0); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); Assert.That(pageNumbers[0].IsCurrentPage, Is.True); Assert.That(pageNumbers[1].IsCurrentPage, Is.False); Assert.That(pageNumbers[2].IsCurrentPage, Is.False); Assert.That(pageNumbers[3].IsCurrentPage, Is.False); } [Test] public void WhenZeroOffSet_ThenSetIsCurrentPageTo4thPage() { var pagingInfo = new PresentationPagingInfo(10, 3, 3); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); Assert.That(pageNumbers[0].IsCurrentPage, Is.False); Assert.That(pageNumbers[1].IsCurrentPage, Is.False); Assert.That(pageNumbers[2].IsCurrentPage, Is.False); Assert.That(pageNumbers[3].IsCurrentPage, Is.True); } [Test] public void WhenZeroOffSet_ThenSetDisplayTextCorrectly() { var pagingInfo = new PresentationPagingInfo(10, 2, 0); var classUnderTest = CreateClassUnderTest(); var pageNumbers = classUnderTest.Create(pagingInfo); Assert.That(pageNumbers[0].DisplayNumber, Is.EqualTo("1")); Assert.That(pageNumbers[1].DisplayNumber, Is.EqualTo("2")); Assert.That(pageNumbers[2].DisplayNumber, Is.EqualTo("3")); Assert.That(pageNumbers[3].DisplayNumber, Is.EqualTo("4")); Assert.That(pageNumbers[4].DisplayNumber, Is.EqualTo("5")); } private PageNumbersFactory CreateClassUnderTest(IPageOffSetStrategy pageOffSet = null) { if (pageOffSet == null) { pageOffSet = _offSetZero; } return new PageNumbersFactory(pageOffSet); } } } public class PageOffSetStrategyFakeZero : IPageOffSetStrategy { public int GetPageOffSet(PresentationPagingInfo pagingInfo) { return 0; } } public class PageOffSetStrategyFakeFive : IPageOffSetStrategy { public int GetPageOffSet(PresentationPagingInfo pagingInfo) { return 5; } } }
37.258993
133
0.580807
[ "MIT" ]
ByteDev/ByteDev.Pagination
tests/ByteDev.Pagination.UnitTests/Presentation/PageNumbersFactoryTests.cs
5,181
C#
/// \file CreateRepo /// /// Major <b>CreateRepo.cs</b> /// \details <b>Details</b> /// - This file handles the building of all create/post stored procedure calls /// Executes the stored procedures and handles the return values and error /// message handling of the connected database. /// /// <ul><li>\author Geun Young Gil & Marcus Rankin</li> /// <li>\copyright Entanglo - BillClub</li>" /// </ul> /// using System; using System.Collections.Generic; using System.Text; using Npgsql; using System.Data; using DomainModels; using Newtonsoft.Json.Linq; using System.Diagnostics; using System.Net.Http; using Newtonsoft.Json; using DomainModels.AiModels; using NpgsqlTypes; namespace DataAccessLibrary { public class CreateRepo { private NpgsqlConnection Connection { get; set; } /// <summary> /// Constructor: Default constructor /// /// <param name="connection">NpgsqlConnection</param> /// <returns name="">CreateRepo</returns> /// /// </summary> public CreateRepo(NpgsqlConnection connection) { Connection = connection; } /// <summary> /// NewUser: Creates a new user based on the specified user object. /// Verifies prior existence of user within the stored procedure (createuser) /// before creating the new user as to not duplicate any users. /// </summary> /// /// <param name="newUser">User</param> /// <param name="user">User</param> /// /// <returns name="response">string</returns> public string NewUser(User newUser, User user) { string response = "NULL"; string userResponse = ""; /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createuser", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", newUser.UserKey)); procCommand.Parameters.Add(new NpgsqlParameter("", newUser.UserName)); procCommand.Parameters.Add(new NpgsqlParameter("", newUser.UserPassword)); procCommand.Parameters.Add(new NpgsqlParameter("", newUser.Email)); //procCommand.Parameters.Add(new NpgsqlParameter("", newUser.DatabaseName)); procCommand.Parameters.Add(new NpgsqlParameter("", newUser.Note)); procCommand.Parameters.Add(new NpgsqlParameter("", user.UserName)); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { userResponse = dataReader.GetString(0); } } if (userResponse == "") { userResponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = userResponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return user creation status } /// <summary> /// Database: Creates a new database based on the specified database name. /// Verified within stored procedure (createdatabase) which checks /// if the newly created database exists. /// </summary> /// /// <param name="database">Database</param> /// <param name="user">User</param> /// /// <returns name="response">string</returns> public string Database(Database database, User user) { //bool dbCreated = false; string response = "NULL"; string dBresponse = ""; /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createdatabase", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", database.DatabaseName)); procCommand.Parameters.Add(new NpgsqlParameter("", user.UserName)); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { dBresponse = dataReader.GetString(0); } } if (dBresponse == "") { dBresponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = dBresponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return database creation status } /// <summary> /// Table: Creates a new table based on the specified table name. /// Verifies existence of associated database before creating within the /// stored procedure (createtable) which checks if the database exists and /// afterwards if the newly created table was created and added successfully. /// </summary> /// /// <param name="table">Table</param> /// <param name="user">User</param> /// /// <returns name="response">string</returns> public string Table(NewTable table, User user) { string response = "NULL"; string tblResponse = ""; List<string> colNames = new List<string>(); List<string> colTypes = new List<string>(); List<string> colSizes = new List<string>(); List<string> colConstraints = new List<string>(); List<string> colDefaultValues = new List<string>(); string[] columnNames = { "" }; string[] columnTypes = { "" }; string[] columnSizes = { "" }; string[] columnConstraints = { "" }; string[] columnDefaultValues = { "" }; if (table.TableColumns.Count != 0) { foreach (Column col in table.TableColumns) { colNames.Add(col.ColumnName); colTypes.Add(col.ColumnDataType); colSizes.Add(col.ColumnSize); colConstraints.Add(col.ColumnConstraint); colDefaultValues.Add(col.ColumnDefaultValue); } columnNames = colNames.ToArray(); columnTypes = colTypes.ToArray(); columnSizes = colSizes.ToArray(); columnConstraints = colConstraints.ToArray(); columnDefaultValues = colDefaultValues.ToArray(); } //var JsonDataString = new StringContent(table.JsonData, System.Text.Encoding.UTF8, "application/json"); //var JsonDataString = JToken.Parse(table.JsonData).ToString(); //var RawDataProfileString = JToken.Parse(table.RawDataProfile).ToString(); //var DataProfileString = JToken.Parse(table.DataProfile).ToString(); var jsonDataString = table.JsonData;//.Replace(@"\", ""); //Console.WriteLine(JsonDataString); //var jsonDataString = JsonConvert.SerializeObject(table.JsonData); //var jsonDataString = JsonConvert.DeserializeObject(table.JsonData); //Console.WriteLine(JsonDataString); var rawDataProfileString = table.RawDataProfile.Replace(@"\", ""); var dataProfileString = table.DataProfile.Replace(@"\", ""); //var jsonDataString = JObject.Parse(table.JsonData).ToString().Replace(@"\", ""); //var rawDataProfileString = JObject.Parse(table.RawDataProfile).ToString(); //var dataProfileString = JObject.Parse(table.DataProfile).ToString(); //Debug.WriteLine(JsonDataString); /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createtable", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", table.Schema)); procCommand.Parameters.Add(new NpgsqlParameter("", table.TableName)); procCommand.Parameters.Add(new NpgsqlParameter("", table.TableUuid)); //procCommand.Parameters.Add(new NpgsqlParameter("", table.JsonData)); //procCommand.Parameters.Add(new NpgsqlParameter("", NpgsqlTypes.NpgsqlDbType.Jsonb, table.JsonData.Length, "", ParameterDirection.Input, false, 0, 0, DataRowVersion.Current, table.JsonData)); //procCommand.Parameters.Add(new NpgsqlParameter("", NpgsqlTypes.NpgsqlDbType.Jsonb, table.RawDataProfile.Length, "", ParameterDirection.Input, false, 0, 0, DataRowVersion.Current, table.RawDataProfile)); //procCommand.Parameters.Add(new NpgsqlParameter("", NpgsqlTypes.NpgsqlDbType.Jsonb, table.DataProfile.Length, "", ParameterDirection.Input, false, 0, 0, DataRowVersion.Current, table.DataProfile)); //procCommand.Parameters.Add(new NpgsqlParameter("", table.JsonData.Replace("\\", ""))); //procCommand.Parameters.Add(new NpgsqlParameter("", table.RawDataProfile.Replace("\\", ""))); //procCommand.Parameters.Add(new NpgsqlParameter("", table.DataProfile.Replace("\\", ""))); procCommand.Parameters.Add(new NpgsqlParameter("", jsonDataString)); procCommand.Parameters.Add(new NpgsqlParameter("", rawDataProfileString)); procCommand.Parameters.Add(new NpgsqlParameter("", dataProfileString)); procCommand.Parameters.Add(new NpgsqlParameter("", columnNames)); procCommand.Parameters.Add(new NpgsqlParameter("", columnTypes)); procCommand.Parameters.Add(new NpgsqlParameter("", columnSizes)); procCommand.Parameters.Add(new NpgsqlParameter("", columnConstraints)); procCommand.Parameters.Add(new NpgsqlParameter("", columnDefaultValues)); procCommand.Parameters.Add(new NpgsqlParameter("", user.UserName)); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { tblResponse = dataReader.GetString(0); } } if (tblResponse == "") { tblResponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = tblResponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return table creation status } /// <summary> /// Column: Creates a new column based on the specified column object. /// Verifies existence of associated database and table before creating within /// the stored procedure (createcolumn) which checks if the database and the /// table exists and afterwards if the newly created column was created and /// added successfully. /// </summary> /// /// <param name="column">Column</param> /// <param name="user">User</param> /// /// <returns name="response">string</returns> public string Column(Column column, User user) { string response = "NULL"; string colResponse = ""; /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createcolumn", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", column.DatabaseName)); procCommand.Parameters.Add(new NpgsqlParameter("", column.TableName)); procCommand.Parameters.Add(new NpgsqlParameter("", column.ColumnName)); procCommand.Parameters.Add(new NpgsqlParameter("", column.ColumnDataType)); procCommand.Parameters.Add(new NpgsqlParameter("", column.ColumnSize)); procCommand.Parameters.Add(new NpgsqlParameter("", column.ColumnConstraint)); procCommand.Parameters.Add(new NpgsqlParameter("", column.ColumnDefaultValue)); procCommand.Parameters.Add(new NpgsqlParameter("", user.UserName)); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { colResponse = dataReader.GetString(0); } } if (colResponse == "") { colResponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = colResponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return column creation status } public string Profile(Profile profile) { string response = "NULL"; string colResponse = ""; /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createprofile", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", profile.Name)); var jsonPara = new NpgsqlParameter("", profile.Pattern); jsonPara.NpgsqlDbType = NpgsqlDbType.Json; procCommand.Parameters.Add(jsonPara); procCommand.Parameters.Add(new NpgsqlParameter("", profile.User)); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { colResponse = dataReader.GetString(0); } } if (colResponse == "") { colResponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = colResponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return column creation status } public string ProfileData(ProfileData profileData) { string response = "NULL"; string colResponse = ""; /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { /// Execute a non returning data query using (var procCommand = new NpgsqlCommand("createprofiledata", Connection)) { procCommand.CommandType = System.Data.CommandType.StoredProcedure; procCommand.Parameters.Add(new NpgsqlParameter("", profileData.ProfileId)); procCommand.Parameters.Add(new NpgsqlParameter("", profileData.DataTableName)); var jsonPara = new NpgsqlParameter("", profileData.Recipe); jsonPara.NpgsqlDbType = NpgsqlDbType.Json; procCommand.Parameters.Add(jsonPara); using (var dataReader = procCommand.ExecuteReader()) { while (dataReader.Read()) { colResponse = dataReader.GetString(0); } } if (colResponse == "") { colResponse = "Returned Data Set is either NULL or Empty!"; } else { /// change to json object response = colResponse; } } } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return response; /// Return column creation status } /// <summary> /// Insert data to table /// </summary> /// <param name="data"></param> /// <returns>true: Success, false: Fail</returns> public bool InsertData(DataPoint data) { /// Using the passed in connection using (Connection) { Connection.Open(); /// Create postgres command using (var command = new NpgsqlCommand()) { /// Build command with passed in connection and user command.Connection = Connection; try { // ex. insert into "user".tblname5 (tableuuid, jsondata, rawdataprofile, colname1, colname2) values ('','{}','{}', 'aa', 'bb') // Build Sql query string colNames = ""; string colVals = ""; for (int i = 0; i < data.Columns.Count; ++i) { if (i < (data.Columns.Count - 1)) { colNames += data.Columns[i].Name + ", "; colVals += "'" + data.Columns[i].Value + "', "; } else { colNames += data.Columns[i].Name; colVals += "'" + data.Columns[i].Value + "'"; } } string sqlstr = "INSERT INTO \"user\"." + data.TableName + " (tableuuid, jsondata, rawdataprofile, " + colNames + ") VALUES ('', '{}', '{}', " + colVals + ")"; using (var cmd = new NpgsqlCommand(sqlstr, Connection)) if (cmd.ExecuteNonQuery() > 0) return true; } /// Error checking catch (NpgsqlException pgex) { throw pgex; } catch (Exception ex) { throw ex; } } } return false; /// Return column creation status } } }
42.761986
232
0.448364
[ "MIT" ]
gyGil/Entanglo
EntangloWebService/DataAccessLibrary/CreateRepo.cs
24,975
C#
using System; using System.Collections.Generic; using System.Linq; class A2 { static void Main() { var n = int.Parse(Console.ReadLine()); var a = new int[n].Select(_ => Console.ReadLine().Trim().Split().Select(int.Parse).ToArray()).ToArray(); var es = new List<int[]>(); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i][j] != -1) es.Add(new[] { i, j, a[i][j] }); var r = Prim(n, 0, es.ToArray()); Console.WriteLine(r.Sum(e => e[2])); } static int[][] Prim(int n, int root, int[][] ues) => Prim(n, root, ToMap(n, ues, false)); static int[][] Prim(int n, int root, List<int[]>[] map) { var u = new bool[n]; var q = PQ<int[]>.Create(e => e[2]); u[root] = true; q.PushRange(map[root].ToArray()); var mes = new List<int[]>(); // 実際の頂点数に注意。 while (q.Count > 0 && mes.Count < n - 1) { var e = q.Pop(); if (u[e[1]]) continue; u[e[1]] = true; mes.Add(e); foreach (var ne in map[e[1]]) if (ne[1] != e[0]) q.Push(ne); } return mes.ToArray(); } static List<int[]>[] ToMap(int n, int[][] es, bool directed) { var map = Array.ConvertAll(new bool[n], _ => new List<int[]>()); foreach (var e in es) { map[e[0]].Add(e); if (!directed) map[e[1]].Add(new[] { e[1], e[0], e[2] }); } return map; } } class PQ<T> : List<T> { public static PQ<T> Create<TKey>(Func<T, TKey> toKey, bool desc = false) { var c = Comparer<TKey>.Default; return desc ? new PQ<T>((x, y) => c.Compare(toKey(y), toKey(x))) : new PQ<T>((x, y) => c.Compare(toKey(x), toKey(y))); } public static PQ<T, TKey> CreateWithKey<TKey>(Func<T, TKey> toKey, bool desc = false) { var c = Comparer<TKey>.Default; return desc ? new PQ<T, TKey>(toKey, (x, y) => c.Compare(y.Key, x.Key)) : new PQ<T, TKey>(toKey, (x, y) => c.Compare(x.Key, y.Key)); } Comparison<T> c; public T First => this[0]; internal PQ(Comparison<T> _c) { c = _c; } void Swap(int i, int j) { var o = this[i]; this[i] = this[j]; this[j] = o; } void UpHeap(int i) { for (int j; i > 0 && c(this[j = (i - 1) / 2], this[i]) > 0; Swap(i, i = j)) ; } void DownHeap(int i) { for (int j; (j = 2 * i + 1) < Count;) { if (j + 1 < Count && c(this[j], this[j + 1]) > 0) j++; if (c(this[i], this[j]) > 0) Swap(i, i = j); else break; } } public void Push(T v) { Add(v); UpHeap(Count - 1); } public void PushRange(T[] vs) { foreach (var v in vs) Push(v); } public T Pop() { var r = this[0]; this[0] = this[Count - 1]; RemoveAt(Count - 1); DownHeap(0); return r; } } class PQ<T, TKey> : PQ<KeyValuePair<TKey, T>> { Func<T, TKey> ToKey; internal PQ(Func<T, TKey> toKey, Comparison<KeyValuePair<TKey, T>> c) : base(c) { ToKey = toKey; } public void Push(T v) => Push(new KeyValuePair<TKey, T>(ToKey(v), v)); public void PushRange(T[] vs) { foreach (var v in vs) Push(v); } }
25.878261
107
0.528562
[ "MIT" ]
sakapon/AtCoder-Contests
CSharp/AOJCourses/ALDS112/A2.cs
2,998
C#
using Kuromoji.NET.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Kuromoji.NET.Extentions; namespace Kuromoji.NET.Compile { public class ConnectionCostsCompiler : ICompiler, IDisposable { const int ShortBytes = sizeof(short); public int Cardinality { get; private set; } int BufferSize { get; set; } public short[] Costs { get; private set; } Stream Output { get; } bool LeaveOpen { get; } bool Disposed { get; set; } public ConnectionCostsCompiler(Stream output) : this(output, false) { } public ConnectionCostsCompiler(Stream output, bool leaveOpen) { Output = output; LeaveOpen = leaveOpen; } public void ReadCosts(Stream input) { using (var reader = new StreamReader(input)) { var line = reader.ReadLine().TrimEnd(); var cardinalities = Regexs.CustomSegmentationSpliter.Split(line); var forwardSize = int.Parse(cardinalities[0]); var backwardSize = int.Parse(cardinalities[1]); Cardinality = backwardSize; BufferSize = forwardSize * backwardSize; Costs = new short[BufferSize]; while ((line = reader.ReadLine()) != null) { var fields = Regexs.CustomSegmentationSpliter.Split(line); var forwardId = short.Parse(fields[0]); var backwardId = short.Parse(fields[1]); var cost = short.Parse(fields[2]); PutCost(forwardId, backwardId, cost); } } } public void PutCost(short forwardId, short backwardId, short cost) { Costs[backwardId + forwardId * Cardinality] = cost; } public void Compile() { Output.Write(Cardinality); Output.Write(BufferSize * ShortBytes); Output.Write(Costs); } public void Dispose() { if (!Disposed) { if (!LeaveOpen) { Output.Dispose(); } Disposed = true; } } } }
28.113636
82
0.511722
[ "Apache-2.0" ]
diggles/Kuromoji.NET
Kuromoji.NET/Compile/ConnectionCostsCompiler.cs
2,476
C#
namespace TarbikMap.DataSources.OsmOverpass { using System.Text.Json.Serialization; [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA1812", Justification = "Deserialized (input from external API)")] internal class OsmOverpassApiLatLon { [JsonPropertyName("lat")] public double Lat { get; set; } [JsonPropertyName("lon")] public double Lon { get; set; } } }
30.142857
130
0.675355
[ "MIT" ]
milan11/tarbikmap
TarbikMap/DataSources/OsmOverpass/OsmOverpassApiLatLon.cs
422
C#
// Copyright 2006-2010 Portland State University, USFS Northern Research Station, University of Wisconsin-Madison // Authors: Robert Scheller, Brian Miranda, Jimm Domingo namespace Landis.Extension.BiomassFuels { /// <summary> /// A forest type. /// </summary> public interface IFuelType { int Index {get;set;} BaseFuelType BaseFuel {get;set;} int MinAge {get;set;} int MaxAge {get;set;} bool[] Ecoregions {get;set;} //--------------------------------------------------------------------- /// <summary> /// Multiplier for a species /// </summary> int this[int speciesIndex] { get;set; } } }
26.035714
114
0.517147
[ "Apache-2.0" ]
derekmorr/Extension-Dynamic-Biomass-Fuels
src/IFuelType.cs
729
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Research.Science.FetchClimate2 { public class DataRepresentationDictionary { Dictionary<string, double> scaleFactors = new Dictionary<string, double>(); Dictionary<string, double> addOffsets = new Dictionary<string, double>(); public Dictionary<string, double> ScaleFactors { get { return scaleFactors; } } public Dictionary<string, double> AddOffsets { get { return addOffsets; } } public DataRepresentationDictionary(IDataStorageDefinition definition) { foreach (var var in definition.VariablesMetadata) { string name = var.Key; if (var.Value.ContainsKey("scale_factor")) scaleFactors.Add(name, Convert.ToDouble(var.Value["scale_factor"], CultureInfo.InvariantCulture)); else scaleFactors.Add(name, 1.0); if (var.Value.ContainsKey("add_offset")) addOffsets.Add(name, Convert.ToDouble(var.Value["add_offset"], CultureInfo.InvariantCulture)); else addOffsets.Add(name, 0.0); } } public DataRepresentationDictionary() { } /// <summary> /// Applies scaleFactor/addOffset transformation /// </summary> /// <param name="value"></param> /// <param name="variable"></param> /// <returns></returns> public double TransformToUsableForm(double value, string variable) { return value * scaleFactors[variable] + addOffsets[variable]; } } }
34.607843
118
0.613598
[ "MIT" ]
Bhaskers-Blu-Org2/FetchClimate
src/Libraries/FetchMath/Utils/DataRepresentationDictionary.cs
1,767
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Google.Apis.Auth; using Microsoft.IdentityModel.Tokens; namespace PredictionApi.Middleware { public class GoogleTokenValidator : ISecurityTokenValidator { private readonly JwtSecurityTokenHandler _tokenHandler; public GoogleTokenValidator() { _tokenHandler = new JwtSecurityTokenHandler(); } public bool CanValidateToken => true; public int MaximumTokenSizeInBytes { get; set; } = TokenValidationParameters.DefaultMaximumTokenSizeInBytes; public bool CanReadToken(string securityToken) { return _tokenHandler.CanReadToken(securityToken); } public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { validatedToken = null; var payload = GoogleJsonWebSignature.ValidateAsync(securityToken, new GoogleJsonWebSignature.ValidationSettings()).Result; // here is where I delegate to Google to validate var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, payload.Name), new Claim(ClaimTypes.Name, payload.Name), new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName), new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName), new Claim(JwtRegisteredClaimNames.Email, payload.Email), new Claim(JwtRegisteredClaimNames.Sub, payload.Subject), new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer), }; try { var principle = new ClaimsPrincipal(); principle.AddIdentity(new ClaimsIdentity(claims, "CustomGoogleJWT")); //, AuthenticationTypes.Password return principle; } catch (Exception e) { Console.WriteLine(e); throw; } } } }
37.224138
184
0.636869
[ "Apache-2.0" ]
grajakum/prediction-app
api/Middleware/GoogleTokenValidator.cs
2,159
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentQueueTests : ProducerConsumerCollectionTests { protected override IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>() => new ConcurrentQueue<T>(); protected override IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection) => new ConcurrentQueue<int>(collection); protected override bool IsEmpty(IProducerConsumerCollection<int> pcc) => ((ConcurrentQueue<int>)pcc).IsEmpty; protected override bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result) => ((ConcurrentQueue<T>)pcc).TryPeek(out result); protected override bool ResetImplemented => false; protected override IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection) => new QueueOracle(collection); protected override string CopyToNoLengthParamName => null; [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void Concurrent_Enqueue_TryDequeue_AllItemsReceived() { int items = 1000; var q = new ConcurrentQueue<int>(); // Consumer dequeues items until it gets as many as it expects Task consumer = Task.Run(() => { int lastReceived = 0; int item; while (true) { if (q.TryDequeue(out item)) { Assert.Equal(lastReceived + 1, item); lastReceived = item; if (item == items) break; } else { Assert.Equal(0, item); } } }); // Producer queues the expected number of items Task producer = Task.Run(() => { for (int i = 1; i <= items; i++) q.Enqueue(i); }); Task.WaitAll(producer, consumer); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void Concurrent_Enqueue_TryPeek_TryDequeue_AllItemsSeen() { int items = 1000; var q = new ConcurrentQueue<int>(); // Consumer peeks and then dequeues the expected number of items Task consumer = Task.Run(() => { int lastReceived = 0; int item; while (true) { if (q.TryPeek(out item)) { Assert.Equal(lastReceived + 1, item); Assert.True(q.TryDequeue(out item)); Assert.Equal(lastReceived + 1, item); lastReceived = item; if (item == items) break; } } }); // Producer queues the expected number of items Task producer = Task.Run(() => { for (int i = 1; i <= items; i++) q.Enqueue(i); }); Task.WaitAll(producer, consumer); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(1, 4, 1024)] [InlineData(4, 1, 1024)] [InlineData(3, 3, 1024)] public void MultipleProducerConsumer_AllItemsTransferred(int producers, int consumers, int itemsPerProducer) { var cq = new ConcurrentQueue<int>(); var tasks = new List<Task>(); int totalItems = producers * itemsPerProducer; int remainingItems = totalItems; int sum = 0; for (int i = 0; i < consumers; i++) { tasks.Add(Task.Factory.StartNew(() => { while (Volatile.Read(ref remainingItems) > 0) { int item; if (cq.TryDequeue(out item)) { Interlocked.Add(ref sum, item); Interlocked.Decrement(ref remainingItems); } } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } for (int i = 0; i < producers; i++) { tasks.Add(Task.Factory.StartNew(() => { for (int item = 1; item <= itemsPerProducer; item++) { cq.Enqueue(item); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); } Task.WaitAll(tasks.ToArray()); Assert.Equal(producers * (itemsPerProducer * (itemsPerProducer + 1) / 2), sum); } [Theory] [InlineData(1, false)] [InlineData(100, false)] [InlineData(512, false)] [InlineData(1, true)] [InlineData(100, true)] [InlineData(512, true)] public void CopyTo_AllItemsCopiedAtCorrectLocation(int count, bool viaInterface) { var q = new ConcurrentQueue<int>(Enumerable.Range(0, count)); var c = (ICollection)q; int[] arr = new int[count]; if (viaInterface) { c.CopyTo(arr, 0); } else { q.CopyTo(arr, 0); } Assert.Equal(q, arr); if (count > 1) { int toRemove = count / 2; int remaining = count - toRemove; for (int i = 0; i < toRemove; i++) { int item; Assert.True(q.TryDequeue(out item)); Assert.Equal(i, item); } if (viaInterface) { c.CopyTo(arr, 1); } else { q.CopyTo(arr, 1); } Assert.Equal(0, arr[0]); for (int i = 0; i < remaining; i++) { Assert.Equal(arr[1 + i], i + toRemove); } } } [Fact] public void IEnumerable_GetAllExpectedItems() { IEnumerable<int> enumerable1 = new ConcurrentQueue<int>(Enumerable.Range(1, 5)); IEnumerable enumerable2 = enumerable1; int expectedNext = 1; using (IEnumerator<int> enumerator1 = enumerable1.GetEnumerator()) { IEnumerator enumerator2 = enumerable2.GetEnumerator(); while (enumerator1.MoveNext()) { Assert.True(enumerator2.MoveNext()); Assert.Equal(expectedNext, enumerator1.Current); Assert.Equal(expectedNext, enumerator2.Current); expectedNext++; } Assert.False(enumerator2.MoveNext()); Assert.Equal(6, expectedNext); } } [Fact] [ActiveIssue("https://github.com/mono/mono/issues/16413", TestRuntimes.Mono)] public void ReferenceTypes_NulledAfterDequeue() { int iterations = 10; // any number <32 will do var mres = new ManualResetEventSlim[iterations]; // Separated out into another method to ensure that even in debug // the JIT doesn't force anything to be kept alive for longer than we need. var queue = ((Func<ConcurrentQueue<Finalizable>>)(() => { var q = new ConcurrentQueue<Finalizable>(); for (int i = 0; i < iterations; i++) { mres[i] = new ManualResetEventSlim(); q.Enqueue(new Finalizable(mres[i])); } for (int i = 0; i < iterations; i++) { Finalizable temp; Assert.True(q.TryDequeue(out temp)); } return q; }))(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(Array.TrueForAll(mres, e => e.IsSet)); GC.KeepAlive(queue); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void ManySegments_ConcurrentDequeues_RemainsConsistent() { var cq = new ConcurrentQueue<int>(); const int Iters = 10000; for (int i = 0; i < Iters; i++) { cq.Enqueue(i); cq.GetEnumerator().Dispose(); // force new segment } int dequeues = 0; Parallel.For(0, Environment.ProcessorCount, i => { while (!cq.IsEmpty) { int item; if (cq.TryDequeue(out item)) { Interlocked.Increment(ref dequeues); } } }); Assert.Equal(0, cq.Count); Assert.True(cq.IsEmpty); Assert.Equal(Iters, dequeues); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void ManySegments_ConcurrentEnqueues_RemainsConsistent() { var cq = new ConcurrentQueue<int>(); const int ItemsPerThread = 1000; int threads = Environment.ProcessorCount; Parallel.For(0, threads, i => { for (int item = 0; item < ItemsPerThread; item++) { cq.Enqueue(item + (i * ItemsPerThread)); cq.GetEnumerator().Dispose(); } }); Assert.Equal(ItemsPerThread * threads, cq.Count); Assert.Equal(Enumerable.Range(0, ItemsPerThread * threads), cq.OrderBy(i => i)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1000)] public void Clear_CountMatch(int count) { var q = new ConcurrentQueue<int>(Enumerable.Range(1, count)); Assert.Equal(count, q.Count); // Clear initial items q.Clear(); Assert.Equal(0, q.Count); Assert.True(q.IsEmpty); Assert.Equal(Enumerable.Empty<int>(), q); // Clear again has no effect q.Clear(); Assert.True(q.IsEmpty); // Add more items then clear and verify for (int i = 0; i < count; i++) { q.Enqueue(i); } Assert.Equal(Enumerable.Range(0, count), q); q.Clear(); Assert.Equal(0, q.Count); Assert.True(q.IsEmpty); Assert.Equal(Enumerable.Empty<int>(), q); // Add items and clear after each item for (int i = 0; i < count; i++) { q.Enqueue(i); Assert.Equal(1, q.Count); q.Clear(); Assert.Equal(0, q.Count); } } [Fact] public static void Clear_DuringEnumeration_DoesntAffectEnumeration() { const int ExpectedCount = 100; var q = new ConcurrentQueue<int>(Enumerable.Range(0, ExpectedCount)); using (IEnumerator<int> beforeClear = q.GetEnumerator()) { q.Clear(); using (IEnumerator<int> afterClear = q.GetEnumerator()) { int count = 0; while (beforeClear.MoveNext()) count++; Assert.Equal(ExpectedCount, count); count = 0; while (afterClear.MoveNext()) count++; Assert.Equal(0, count); } } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData(1, 10)] [InlineData(3, 100)] [InlineData(8, 1000)] public void Concurrent_Clear_NoExceptions(int threadsCount, int itemsPerThread) { var q = new ConcurrentQueue<int>(); Task.WaitAll((from i in Enumerable.Range(0, threadsCount) select Task.Run(() => { var random = new Random(); for (int j = 0; j < itemsPerThread; j++) { switch (random.Next(7)) { case 0: int c = q.Count; break; case 1: bool e = q.IsEmpty; break; case 2: q.Enqueue(random.Next(int.MaxValue)); break; case 3: q.ToArray(); break; case 4: int d; q.TryDequeue(out d); break; case 5: int p; q.TryPeek(out p); break; case 6: q.Clear(); break; } } })).ToArray()); } /// <summary>Sets an event when finalized.</summary> private sealed class Finalizable { private ManualResetEventSlim _mres; public Finalizable(ManualResetEventSlim mres) { _mres = mres; } ~Finalizable() { _mres.Set(); } } protected sealed class QueueOracle : IProducerConsumerCollection<int> { private readonly Queue<int> _queue; public QueueOracle(IEnumerable<int> collection) { _queue = new Queue<int>(collection); } public int Count => _queue.Count; public bool IsSynchronized => false; public object SyncRoot => null; public void CopyTo(Array array, int index) => ((ICollection)_queue).CopyTo(array, index); public void CopyTo(int[] array, int index) => _queue.CopyTo(array, index); public IEnumerator<int> GetEnumerator() => _queue.GetEnumerator(); public int[] ToArray() => _queue.ToArray(); public bool TryAdd(int item) { _queue.Enqueue(item); return true; } public bool TryTake(out int item) { if (_queue.Count > 0) { item = _queue.Dequeue(); return true; } else { item = 0; return false; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }
35.226757
162
0.476537
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Collections.Concurrent/tests/ConcurrentQueueTests.cs
15,535
C#
namespace Chartreuse.Today.Core.Shared.Tools.Text { /// <summary> /// Text item. Simple plain old C# object (POCO) to /// hold a string. /// </summary> public class TextItem { public string Text { get; private set; } public TextItem(string text) { this.Text = text; } } }
20.352941
55
0.540462
[ "MIT" ]
2DayApp/2day
src/2Day.Core.Shared/Tools/Text/TextItem.cs
348
C#
#pragma warning disable 1591, 618 // This file contains general utilities to aid in development. // Classes here generally shouldn't be exposed publicly since // they're not particular to any library functionality. // Because the classes here are internal, it's likely this file // might be included in multiple assemblies. namespace ControlzEx.Standard { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; internal static partial class Utility { private static readonly Version _presentationFrameworkVersion = Assembly.GetAssembly(typeof(Window)).GetName().Version; /// <summary> /// Is this using WPF4? /// </summary> /// <remarks> /// There are a few specific bugs in Window in 3.5SP1 and below that require workarounds /// when handling WM_NCCALCSIZE on the HWND. /// </remarks> public static bool IsPresentationFrameworkVersionLessThan4 { get { return _presentationFrameworkVersion < new Version(4, 0); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static byte[] GetBytesFromBitmapSource(BitmapSource bmp) { int width = bmp.PixelWidth; int height = bmp.PixelHeight; int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8); var pixels = new byte[height * stride]; bmp.CopyPixels(pixels, stride, 0); return pixels; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(ImageSource img) { return GenerateBitmapSource(img, img.Width, img.Height); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(ImageSource img, double renderWidth, double renderHeight) { var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { dc.DrawImage(img, new Rect(0, 0, renderWidth, renderHeight)); } var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); bmp.Render(dv); return bmp; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapSource GenerateBitmapSource(UIElement element, double renderWidth, double renderHeight, bool performLayout) { if (performLayout) { element.Measure(new Size(renderWidth, renderHeight)); element.Arrange(new Rect(new Size(renderWidth, renderHeight))); } var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { dc.DrawRectangle(new VisualBrush(element), null, new Rect(0, 0, renderWidth, renderHeight)); } bmp.Render(dv); return bmp; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void SaveToPng(BitmapSource source, string fileName) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); using (FileStream stream = File.Create(fileName)) { encoder.Save(stream); } } // This can be cached. It's not going to change under reasonable circumstances. private static int s_bitDepth; // = 0; [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _GetBitDepth() { if (s_bitDepth == 0) { using (SafeDC dc = SafeDC.GetDesktop()) { s_bitDepth = NativeMethods.GetDeviceCaps(dc, DeviceCap.BITSPIXEL) * NativeMethods.GetDeviceCaps(dc, DeviceCap.PLANES); } } return s_bitDepth; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static BitmapFrame GetBestMatch(IList<BitmapFrame> frames, int width, int height) { return _GetBestMatch(frames, _GetBitDepth(), width, height); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _MatchImage(BitmapFrame frame, int bitDepth, int width, int height, int bpp) { int score = 2 * _WeightedAbs(bpp, bitDepth, false) + _WeightedAbs(frame.PixelWidth, width, true) + _WeightedAbs(frame.PixelHeight, height, true); return score; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _WeightedAbs(int valueHave, int valueWant, bool fPunish) { int diff = (valueHave - valueWant); if (diff < 0) { diff = (fPunish ? -2 : -1) * diff; } return diff; } /// From a list of BitmapFrames find the one that best matches the requested dimensions. /// The methods used here are copied from Win32 sources. We want to be consistent with /// system behaviors. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static BitmapFrame _GetBestMatch(IList<BitmapFrame> frames, int bitDepth, int width, int height) { int bestScore = int.MaxValue; int bestBpp = 0; int bestIndex = 0; bool isBitmapIconDecoder = frames[0].Decoder is IconBitmapDecoder; for (int i = 0; i < frames.Count && bestScore != 0; ++i) { int currentIconBitDepth = isBitmapIconDecoder ? frames[i].Thumbnail.Format.BitsPerPixel : frames[i].Format.BitsPerPixel; if (currentIconBitDepth == 0) { currentIconBitDepth = 8; } int score = _MatchImage(frames[i], bitDepth, width, height, currentIconBitDepth); if (score < bestScore) { bestIndex = i; bestBpp = currentIconBitDepth; bestScore = score; } else if (score == bestScore) { // Tie breaker: choose the higher color depth. If that fails, choose first one. if (bestBpp < currentIconBitDepth) { bestIndex = i; bestBpp = currentIconBitDepth; } } } return frames[bestIndex]; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int RGB(Color c) { return c.B | (c.G << 8) | (c.R << 16); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int AlphaRGB(Color c) { return c.B | (c.G << 8) | (c.R << 16) | (c.A << 24); } /// <summary>Convert a native integer that represent a color with an alpha channel into a Color struct.</summary> /// <param name="color">The integer that represents the color. Its bits are of the format 0xAARRGGBB.</param> /// <returns>A Color representation of the parameter.</returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static Color ColorFromArgbDword(uint color) { return Color.FromArgb( (byte)((color & 0xFF000000) >> 24), (byte)((color & 0x00FF0000) >> 16), (byte)((color & 0x0000FF00) >> 8), (byte)((color & 0x000000FF) >> 0)); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool AreImageSourcesEqual(ImageSource left, ImageSource right) { if (null == left) { return right == null; } if (null == right) { return false; } BitmapSource leftBmp = GenerateBitmapSource(left); BitmapSource rightBmp = GenerateBitmapSource(right); byte[] leftPixels = GetBytesFromBitmapSource(leftBmp); byte[] rightPixels = GetBytesFromBitmapSource(rightBmp); if (leftPixels.Length != rightPixels.Length) { return false; } return MemCmp(leftPixels, rightPixels, leftPixels.Length); } // Caller is responsible for destroying the HICON // Caller is responsible to ensure that GDI+ has been initialized. [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static IntPtr GenerateHICON(ImageSource image, Size dimensions) { if (image == null) { return IntPtr.Zero; } // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame. // We can use leverage this as a shortcut to get the right 16x16 representation // because DrawImage doesn't do that for us. var bf = image as BitmapFrame; if (bf != null) { bf = GetBestMatch(bf.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height); } else { // Constrain the dimensions based on the aspect ratio. var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height); // There's no reason to assume that the requested image dimensions are square. double renderRatio = dimensions.Width / dimensions.Height; double aspectRatio = image.Width / image.Height; // If it's smaller than the requested size, then place it in the middle and pad the image. if (image.Width <= dimensions.Width && image.Height <= dimensions.Height) { drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height); } else if (renderRatio > aspectRatio) { double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width; drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height); } else if (renderRatio < aspectRatio) { double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height; drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight); } var dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); dc.DrawImage(image, drawingDimensions); dc.Close(); var bmp = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(dv); bf = BitmapFrame.Create(bmp); } // Using GDI+ to convert to an HICON. // I'd rather not duplicate their code. using (MemoryStream memstm = new MemoryStream()) { BitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(bf); enc.Save(memstm); using (var istm = new ManagedIStream(memstm)) { // We are not bubbling out GDI+ errors when creating the native image fails. IntPtr bitmap = IntPtr.Zero; try { Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap); if (Status.Ok != gpStatus) { return IntPtr.Zero; } IntPtr hicon; gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon); if (Status.Ok != gpStatus) { return IntPtr.Zero; } // Caller is responsible for freeing this. return hicon; } finally { SafeDisposeImage(ref bitmap); } } } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void AddDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener) { if (component == null) { return; } Assert.IsNotNull(property); Assert.IsNotNull(listener); DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType()); dpd.AddValueChanged(component, listener); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void RemoveDependencyPropertyChangeListener(object component, DependencyProperty property, EventHandler listener) { if (component == null) { return; } Assert.IsNotNull(property); Assert.IsNotNull(listener); DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, component.GetType()); dpd.RemoveValueChanged(component, listener); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsNonNegative(this Thickness thickness) { if (!thickness.Top.IsFiniteAndNonNegative()) { return false; } if (!thickness.Left.IsFiniteAndNonNegative()) { return false; } if (!thickness.Bottom.IsFiniteAndNonNegative()) { return false; } if (!thickness.Right.IsFiniteAndNonNegative()) { return false; } return true; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsValid(this CornerRadius cornerRadius) { if (!cornerRadius.TopLeft.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.TopRight.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.BottomLeft.IsFiniteAndNonNegative()) { return false; } if (!cornerRadius.BottomRight.IsFiniteAndNonNegative()) { return false; } return true; } } }
38.926829
154
0.561905
[ "Apache-2.0" ]
GeekCatPYG/SimpleRemote
MahApps.Metro/ControlzEx/Microsoft.Windows.Shell/Standard/Utilities.Wpf.cs
15,960
C#
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; using Attractor.Implementation.Common; namespace Attractor.Implementation { internal sealed class MessageProcessor : BackgroundService { private readonly IInbox inbox; private readonly IActorExecutorFactory factory; private readonly ILogger<MessageProcessor> logger; public MessageProcessor( IInbox inbox, IActorExecutorFactory factory, ILogger<MessageProcessor> logger) { this.inbox = inbox; this.factory = factory; this.logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { logger.LogTrace("Message processing has started"); while (!stoppingToken.IsCancellationRequested) { try { await ExecuteInternalAsync(stoppingToken); } catch (OperationCanceledException) { continue; } catch (Exception exception) { logger.LogError(exception, "Message processing has error"); } } logger.LogTrace("Message processing has stopped"); } private async ValueTask ExecuteInternalAsync(CancellationToken stoppingToken) { await foreach (var message in inbox.ReadMessagesAsync(stoppingToken)) { await using (var conditionDisposing = new ConditionDisposable(message, true)) { if (await factory.TryCreateByAddressAsync(message, stoppingToken) is TrueResult<IActorExecutor> createExecutorResult) { if (await createExecutorResult.Value.TryExecuteAsync(message, stoppingToken)) { conditionDisposing.Disable(); } } } } } } }
32.507463
137
0.559229
[ "MIT" ]
gendalf90/Attractor.Net
src/Attractor/Implementation/MessageProcessor.cs
2,180
C#
// <auto-generated /> using System; using ApiResume.Domain.Context; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ApiResume.Migrations { [DbContext(typeof(EFContext))] [Migration("20210125180007_UpdateKnowledgeSeed")] partial class UpdateKnowledgeSeed { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("ApiResume.Domain.Models.Knowledge", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("DateAdded") .HasColumnType("datetime2"); b.Property<DateTime>("DateModified") .HasColumnType("datetime2"); b.Property<string>("FilePathImage") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<string>("FirstDescription") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<bool>("FlagActive") .HasColumnType("bit"); b.Property<string>("SecondDescription") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<string>("Title") .HasMaxLength(25) .HasColumnType("nvarchar(25)"); b.HasKey("Id"); b.ToTable("Knowledges"); b.HasData( new { Id = new Guid("f08bbb57-138d-4712-b547-72dd01c5bd4b"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "csharp.png", FirstDescription = "C# é uma linguagem de programação, desenvolvida pela Microsoft como parte da plataforma .NET", FlagActive = true, SecondDescription = "A línguagem que estudo desde o começo na faculdade e a que atuo no mercado atualmente, me sinto confortável em dizer que é a com mais experiência e expertise atuando com diversos projetos.", Title = "C#" }, new { Id = new Guid("266fc120-1033-49c8-956f-14a30aaec5c0"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "netCoreIcon.png", FirstDescription = ".NET Core é um framework livre e de código aberto para os sistemas operacionais Windows, Linux e macOS. É um sucessor de código aberto do .NET Framework.", FlagActive = true, SecondDescription = "Framework ao qual posso dizer junto do C# que tenho mais expertise, apesar de estudar a mais tempo o .NET \"tradicional\", o .NET Core é o framework ao qual apliquei todo meu conhecimento de maneira profissional trazendo resoluções mais complexas.", Title = ".NET Core" }, new { Id = new Guid("c2278d25-4081-4fc4-b9dc-6d730bbc58a3"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "netIcon.png", FirstDescription = "O .NET Framework é uma iniciativa da empresa Microsoft, que visa uma plataforma única para desenvolvimento e execução de sistemas e aplicações. Todo e qualquer código gerado para .NET pode ser executado em qualquer dispositivo que possua um framework de tal plataforma.", FlagActive = true, SecondDescription = "Framework que tenho um longo estudo seja a nível acadêmico e com alguns projetos, desenvolvendo simples projetos em WinForms e manutenções em WCF.", Title = ".NET Framework" }, new { Id = new Guid("efae61c0-8e3d-42ad-ad4f-4e14c513b898"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "javaScript.png", FirstDescription = "JavaScript é uma linguagem de programação interpretada estruturada, Juntamente com HTML e CSS, o JavaScript é uma das três principais tecnologias da World Wide Web.", FlagActive = true, SecondDescription = "Linguagem a qual me sinto confortavel em prestar manutenção ou criar algum script para alguma necessidade web", Title = "JavaScript" }, new { Id = new Guid("1bd45a14-2176-49e5-abc3-317a03f37216"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "typescript.png", FirstDescription = "TypeScript é um superconjunto de JavaScript desenvolvido pela Microsoft que adiciona tipagem e alguns outros recursos a linguagem. Anders Hejlsberg, arquiteto da linguagem C# e criador das linguagens Delphi e Turbo Pascal, trabalhou no desenvolvimento do TypeScript.", FlagActive = true, SecondDescription = "Sigo da mesma maneira do JavaScript com relação ao TypeScript, já que comecei a imersão em frameworks front-end antes fui atrás de estudar um pouco sobre TS.", Title = "TypeScript" }, new { Id = new Guid("f151f5ad-09d4-48e5-a1e0-e7fe6d4a4ac4"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "jquery.png", FirstDescription = "JQuery é uma biblioteca de funções JavaScript que interage com o HTML, desenvolvida para simplificar os scripts interpretados no navegador do cliente.", FlagActive = true, SecondDescription = "Tenho bastante conhecimento em tal framework já que no meu início de carreira foi o que mais utilizei para auxiliar no front-end.", Title = "JQuery" }, new { Id = new Guid("e2623502-c2d5-46fc-83e7-6cc03fc06f2a"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "bootstrap.png", FirstDescription = "Bootstrap é um framework web com código-fonte aberto para desenvolvimento de componentes de interface e front-end para sites e aplicações web usando HTML, CSS e JavaScript.", FlagActive = true, SecondDescription = "Tenho conhecimento considerável por ser uma ferramenta que normalmente utilizo quando necessito criar uma página do \"zero\" para acelerar o processo de desenvolvimento, então me sinto confortável para trabalhar com a mesma.", Title = "Bootstrap" }, new { Id = new Guid("8247277f-0e28-4556-b0a2-412821548d85"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "azure.png", FirstDescription = "O Microsoft Azure é uma plataforma destinada à execução de aplicativos e serviços, baseada nos conceitos da computação em nuvem.", FlagActive = true, SecondDescription = "Uma ferramenta que comecei a conhecer no estágio, porém continuo os estudos por fora desde então, já que utilizo muito atualmente, pois os projetos Web estão armazenados na App Services, além de utilizarem o SQL no Azure, Blobs para armazenamento, e CDN para a página estática. Atualmente além de utilizar o portal Azure utilizo as ferramentas Azure Storage Explorer e Azure Storage Emulator.", Title = "Azure" }, new { Id = new Guid("a548b384-2661-47fe-b448-f48d0ba33a8b"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "sqlServer.png", FirstDescription = "O Microsoft SQL Server é um sistema gerenciador de Banco de dados relacional desenvolvido pela Sybase em parceria com a Microsoft. Esta parceria durou até 1994, com o lançamento da versão para Windows NT e desde então a Microsoft mantém a manutenção do produto.", FlagActive = true, SecondDescription = "Banco de dados ao qual tenho mais conhecimento, estudo e utilizo o mesmo desce o início da minha jornada, ao qual atualmente utilizo o SQL Server Management Studio para gerenciamento dos DBs.", Title = "SQL Server" }, new { Id = new Guid("235d392a-ed14-494f-b6b1-b107686c2292"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "git.png", FirstDescription = "Git é um sistema de controle de versões distribuído, usado principalmente no desenvolvimento de software, mas pode ser usado para registrar o histórico de edições de qualquer tipo de arquivo.", FlagActive = true, SecondDescription = "O sistema de versionamento ao qual estou habituado a trabalhar, sempre utilizei o Git, e fiz o versionamento ou pelo GitHub ou GitLab.", Title = "Git" }, new { Id = new Guid("9a286814-5bc9-4247-893a-4aaa216ba599"), DateAdded = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), DateModified = new DateTime(2021, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), FilePathImage = "angular.png", FirstDescription = "Angular é uma plataforma de aplicações web de código-fonte aberto e front-end baseado em TypeScript liderado pela Equipe Angular do Google e por uma comunidade de indivíduos e corporações. Angular é uma reescrita completa do AngularJS, feito pela mesma equipe que o construiu.", FlagActive = true, SecondDescription = "Framework front-end ao qual venho estudando e ganhando cada vez mais experiência, atualmente consigo construir aplicações para necessidades simples.", Title = "Angular" }); }); #pragma warning restore 612, 618 } } }
71.478495
443
0.543287
[ "MIT" ]
lucasvieiravicente/ApiResume
Migrations/20210125180007_UpdateKnowledgeSeed.Designer.cs
13,391
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace System.Fabric.Store { using System.Collections.Generic; using System.Threading; /// <summary> /// Lock hash table, one per lock manager. /// </summary> internal struct LockHashtable { #region Instance Members /// <summary> /// Provides concurrency control on this lock hash table. /// </summary> internal ReaderWriterLockSlim LockHashTableLock; /// <summary> /// Dictionary mapping a lock resource name hash to lock control blocks for that lock resource. /// </summary> internal Dictionary<ulong, LockHashValue> LockEntries; #endregion /// <summary> /// Create an initialized instance of a LockHashTable (C# does not support default constructors for struct). /// </summary> public static LockHashtable Create() { return new LockHashtable() { LockHashTableLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion), LockEntries = new Dictionary<ulong, LockHashValue>(), }; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources. /// </summary> public void Close() { if (null != this.LockHashTableLock) { this.LockHashTableLock.Dispose(); this.LockHashTableLock = null; } if (null != this.LockEntries) { foreach (var lockEntry in this.LockEntries) { lockEntry.Value.Close(); } this.LockEntries.Clear(); this.LockEntries = null; } } } }
32.369231
124
0.535171
[ "MIT" ]
AlkisFortuneFish/service-fabric
src/prod/src/managed/Microsoft.ServiceFabric.Data.Impl/ReplicatedStore/LockManager/LockHashTable.cs
2,104
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.Inputs { /// <summary> /// Disk input details. /// </summary> public sealed class InMageAzureV2DiskInputDetailsArgs : Pulumi.ResourceArgs { /// <summary> /// The DiskEncryptionSet ARM ID. /// </summary> [Input("diskEncryptionSetId")] public Input<string>? DiskEncryptionSetId { get; set; } /// <summary> /// The DiskId. /// </summary> [Input("diskId")] public Input<string>? DiskId { get; set; } /// <summary> /// The DiskType. /// </summary> [Input("diskType")] public InputUnion<string, Pulumi.AzureNative.RecoveryServices.DiskAccountType>? DiskType { get; set; } /// <summary> /// The LogStorageAccountId. /// </summary> [Input("logStorageAccountId")] public Input<string>? LogStorageAccountId { get; set; } public InMageAzureV2DiskInputDetailsArgs() { } } }
28.085106
110
0.607576
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/Inputs/InMageAzureV2DiskInputDetailsArgs.cs
1,320
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NotesClient.ServiceAccess; namespace NotesClient.UI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); services.Configure<NotesServiceOptions>(Configuration.GetSection("NotesService")); services.AddHttpClient<INotesService, NotesService>(); services.AddRouting(options => { options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer); }); services.AddControllersWithViews(options => { options.Conventions.Add( new RouteTokenTransformerConvention( new SlugifyParameterTransformer())); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller:slugify=Home}/{action:slugify=Index}/{id?}"); }); } } }
28.507246
94
0.579563
[ "MIT" ]
2002-feb24-net/nick-project2-mvc-notes-client
NotesClient/NotesClient.UI/Startup.cs
1,967
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: entrances/entrances.proto // </auto-generated> #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Mruv.Entrances { /// <summary> /// The MruV entrances service provides procedures for managing an entrances to estates and teleportation to locations. /// </summary> public static partial class MruVEntrancesService { static readonly string __ServiceName = "mruv.entrances.MruVEntrancesService"; static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (message is global::Google.Protobuf.IBufferMessage) { context.SetPayloadLength(message.CalculateSize()); global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); context.Complete(); return; } #endif context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); } static class __Helper_MessageCache<T> { public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); } static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T> { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (__Helper_MessageCache<T>.IsBufferMessage) { return parser.ParseFrom(context.PayloadAsReadOnlySequence()); } #endif return parser.ParseFrom(context.PayloadAsNewBuffer()); } static readonly grpc::Marshaller<global::Mruv.Entrances.CreateEntranceRequest> __Marshaller_mruv_entrances_CreateEntranceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.CreateEntranceRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.CreateEntranceResponse> __Marshaller_mruv_entrances_CreateEntranceResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.CreateEntranceResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.GetEntranceRequest> __Marshaller_mruv_entrances_GetEntranceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.GetEntranceRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.GetEntranceResponse> __Marshaller_mruv_entrances_GetEntranceResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.GetEntranceResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.UpdateEntranceRequest> __Marshaller_mruv_entrances_UpdateEntranceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.UpdateEntranceRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.UpdateEntranceResponse> __Marshaller_mruv_entrances_UpdateEntranceResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.UpdateEntranceResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.DeleteEntranceRequest> __Marshaller_mruv_entrances_DeleteEntranceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.DeleteEntranceRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.DeleteEntranceResponse> __Marshaller_mruv_entrances_DeleteEntranceResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.DeleteEntranceResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.LockRequest> __Marshaller_mruv_entrances_LockRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.LockRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.LockResponse> __Marshaller_mruv_entrances_LockResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.LockResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.UnlockRequest> __Marshaller_mruv_entrances_UnlockRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.UnlockRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.UnlockResponse> __Marshaller_mruv_entrances_UnlockResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.UnlockResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.FindNearestEntranceRequest> __Marshaller_mruv_entrances_FindNearestEntranceRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.FindNearestEntranceRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.FindNearestEntranceResponse> __Marshaller_mruv_entrances_FindNearestEntranceResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.FindNearestEntranceResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.EnterRequest> __Marshaller_mruv_entrances_EnterRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.EnterRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.EnterResponse> __Marshaller_mruv_entrances_EnterResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.EnterResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.ExitRequest> __Marshaller_mruv_entrances_ExitRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.ExitRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.ExitResponse> __Marshaller_mruv_entrances_ExitResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.ExitResponse.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.FetchAllEntrancesRequest> __Marshaller_mruv_entrances_FetchAllEntrancesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.FetchAllEntrancesRequest.Parser)); static readonly grpc::Marshaller<global::Mruv.Entrances.FetchAllEntrancesResponse> __Marshaller_mruv_entrances_FetchAllEntrancesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Mruv.Entrances.FetchAllEntrancesResponse.Parser)); static readonly grpc::Method<global::Mruv.Entrances.CreateEntranceRequest, global::Mruv.Entrances.CreateEntranceResponse> __Method_CreateEntrance = new grpc::Method<global::Mruv.Entrances.CreateEntranceRequest, global::Mruv.Entrances.CreateEntranceResponse>( grpc::MethodType.Unary, __ServiceName, "CreateEntrance", __Marshaller_mruv_entrances_CreateEntranceRequest, __Marshaller_mruv_entrances_CreateEntranceResponse); static readonly grpc::Method<global::Mruv.Entrances.GetEntranceRequest, global::Mruv.Entrances.GetEntranceResponse> __Method_GetEntrance = new grpc::Method<global::Mruv.Entrances.GetEntranceRequest, global::Mruv.Entrances.GetEntranceResponse>( grpc::MethodType.Unary, __ServiceName, "GetEntrance", __Marshaller_mruv_entrances_GetEntranceRequest, __Marshaller_mruv_entrances_GetEntranceResponse); static readonly grpc::Method<global::Mruv.Entrances.UpdateEntranceRequest, global::Mruv.Entrances.UpdateEntranceResponse> __Method_UpdateEntrance = new grpc::Method<global::Mruv.Entrances.UpdateEntranceRequest, global::Mruv.Entrances.UpdateEntranceResponse>( grpc::MethodType.Unary, __ServiceName, "UpdateEntrance", __Marshaller_mruv_entrances_UpdateEntranceRequest, __Marshaller_mruv_entrances_UpdateEntranceResponse); static readonly grpc::Method<global::Mruv.Entrances.DeleteEntranceRequest, global::Mruv.Entrances.DeleteEntranceResponse> __Method_DeleteEntrance = new grpc::Method<global::Mruv.Entrances.DeleteEntranceRequest, global::Mruv.Entrances.DeleteEntranceResponse>( grpc::MethodType.Unary, __ServiceName, "DeleteEntrance", __Marshaller_mruv_entrances_DeleteEntranceRequest, __Marshaller_mruv_entrances_DeleteEntranceResponse); static readonly grpc::Method<global::Mruv.Entrances.LockRequest, global::Mruv.Entrances.LockResponse> __Method_Lock = new grpc::Method<global::Mruv.Entrances.LockRequest, global::Mruv.Entrances.LockResponse>( grpc::MethodType.Unary, __ServiceName, "Lock", __Marshaller_mruv_entrances_LockRequest, __Marshaller_mruv_entrances_LockResponse); static readonly grpc::Method<global::Mruv.Entrances.UnlockRequest, global::Mruv.Entrances.UnlockResponse> __Method_Unlock = new grpc::Method<global::Mruv.Entrances.UnlockRequest, global::Mruv.Entrances.UnlockResponse>( grpc::MethodType.Unary, __ServiceName, "Unlock", __Marshaller_mruv_entrances_UnlockRequest, __Marshaller_mruv_entrances_UnlockResponse); static readonly grpc::Method<global::Mruv.Entrances.FindNearestEntranceRequest, global::Mruv.Entrances.FindNearestEntranceResponse> __Method_FindNearestEntrance = new grpc::Method<global::Mruv.Entrances.FindNearestEntranceRequest, global::Mruv.Entrances.FindNearestEntranceResponse>( grpc::MethodType.Unary, __ServiceName, "FindNearestEntrance", __Marshaller_mruv_entrances_FindNearestEntranceRequest, __Marshaller_mruv_entrances_FindNearestEntranceResponse); static readonly grpc::Method<global::Mruv.Entrances.EnterRequest, global::Mruv.Entrances.EnterResponse> __Method_Enter = new grpc::Method<global::Mruv.Entrances.EnterRequest, global::Mruv.Entrances.EnterResponse>( grpc::MethodType.Unary, __ServiceName, "Enter", __Marshaller_mruv_entrances_EnterRequest, __Marshaller_mruv_entrances_EnterResponse); static readonly grpc::Method<global::Mruv.Entrances.ExitRequest, global::Mruv.Entrances.ExitResponse> __Method_Exit = new grpc::Method<global::Mruv.Entrances.ExitRequest, global::Mruv.Entrances.ExitResponse>( grpc::MethodType.Unary, __ServiceName, "Exit", __Marshaller_mruv_entrances_ExitRequest, __Marshaller_mruv_entrances_ExitResponse); static readonly grpc::Method<global::Mruv.Entrances.FetchAllEntrancesRequest, global::Mruv.Entrances.FetchAllEntrancesResponse> __Method_FetchAll = new grpc::Method<global::Mruv.Entrances.FetchAllEntrancesRequest, global::Mruv.Entrances.FetchAllEntrancesResponse>( grpc::MethodType.ServerStreaming, __ServiceName, "FetchAll", __Marshaller_mruv_entrances_FetchAllEntrancesRequest, __Marshaller_mruv_entrances_FetchAllEntrancesResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Mruv.Entrances.EntrancesReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of MruVEntrancesService</summary> [grpc::BindServiceMethod(typeof(MruVEntrancesService), "BindService")] public abstract partial class MruVEntrancesServiceBase { /// <summary> /// Create an entrance to building or teleport to location. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.CreateEntranceResponse> CreateEntrance(global::Mruv.Entrances.CreateEntranceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Get an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.GetEntranceResponse> GetEntrance(global::Mruv.Entrances.GetEntranceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Update an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.UpdateEntranceResponse> UpdateEntrance(global::Mruv.Entrances.UpdateEntranceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Delete an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.DeleteEntranceResponse> DeleteEntrance(global::Mruv.Entrances.DeleteEntranceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lock entrance. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.LockResponse> Lock(global::Mruv.Entrances.LockRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Unload entrance. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.UnlockResponse> Unlock(global::Mruv.Entrances.UnlockRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Find gate that is closest to a specific position. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.FindNearestEntranceResponse> FindNearestEntrance(global::Mruv.Entrances.FindNearestEntranceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Enter an entrance (player teleport from in spot position to out spot position). /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.EnterResponse> Enter(global::Mruv.Entrances.EnterRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Exit from entrance (player teleport from out spot position to in spot position). /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Mruv.Entrances.ExitResponse> Exit(global::Mruv.Entrances.ExitRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="responseStream">Used for sending responses back to the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>A task indicating completion of the handler.</returns> public virtual global::System.Threading.Tasks.Task FetchAll(global::Mruv.Entrances.FetchAllEntrancesRequest request, grpc::IServerStreamWriter<global::Mruv.Entrances.FetchAllEntrancesResponse> responseStream, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for MruVEntrancesService</summary> public partial class MruVEntrancesServiceClient : grpc::ClientBase<MruVEntrancesServiceClient> { /// <summary>Creates a new client for MruVEntrancesService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public MruVEntrancesServiceClient(grpc::ChannelBase channel) : base(channel) { } /// <summary>Creates a new client for MruVEntrancesService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public MruVEntrancesServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MruVEntrancesServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected MruVEntrancesServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Create an entrance to building or teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.CreateEntranceResponse CreateEntrance(global::Mruv.Entrances.CreateEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateEntrance(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create an entrance to building or teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.CreateEntranceResponse CreateEntrance(global::Mruv.Entrances.CreateEntranceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateEntrance, null, options, request); } /// <summary> /// Create an entrance to building or teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.CreateEntranceResponse> CreateEntranceAsync(global::Mruv.Entrances.CreateEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateEntranceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create an entrance to building or teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.CreateEntranceResponse> CreateEntranceAsync(global::Mruv.Entrances.CreateEntranceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateEntrance, null, options, request); } /// <summary> /// Get an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.GetEntranceResponse GetEntrance(global::Mruv.Entrances.GetEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetEntrance(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.GetEntranceResponse GetEntrance(global::Mruv.Entrances.GetEntranceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetEntrance, null, options, request); } /// <summary> /// Get an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.GetEntranceResponse> GetEntranceAsync(global::Mruv.Entrances.GetEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetEntranceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.GetEntranceResponse> GetEntranceAsync(global::Mruv.Entrances.GetEntranceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetEntrance, null, options, request); } /// <summary> /// Update an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.UpdateEntranceResponse UpdateEntrance(global::Mruv.Entrances.UpdateEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateEntrance(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.UpdateEntranceResponse UpdateEntrance(global::Mruv.Entrances.UpdateEntranceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateEntrance, null, options, request); } /// <summary> /// Update an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.UpdateEntranceResponse> UpdateEntranceAsync(global::Mruv.Entrances.UpdateEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateEntranceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.UpdateEntranceResponse> UpdateEntranceAsync(global::Mruv.Entrances.UpdateEntranceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateEntrance, null, options, request); } /// <summary> /// Delete an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.DeleteEntranceResponse DeleteEntrance(global::Mruv.Entrances.DeleteEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteEntrance(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.DeleteEntranceResponse DeleteEntrance(global::Mruv.Entrances.DeleteEntranceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteEntrance, null, options, request); } /// <summary> /// Delete an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.DeleteEntranceResponse> DeleteEntranceAsync(global::Mruv.Entrances.DeleteEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteEntranceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete an entrance to building or a teleport to location. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.DeleteEntranceResponse> DeleteEntranceAsync(global::Mruv.Entrances.DeleteEntranceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteEntrance, null, options, request); } /// <summary> /// Lock entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.LockResponse Lock(global::Mruv.Entrances.LockRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Lock(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lock entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.LockResponse Lock(global::Mruv.Entrances.LockRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Lock, null, options, request); } /// <summary> /// Lock entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.LockResponse> LockAsync(global::Mruv.Entrances.LockRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return LockAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lock entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.LockResponse> LockAsync(global::Mruv.Entrances.LockRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Lock, null, options, request); } /// <summary> /// Unload entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.UnlockResponse Unlock(global::Mruv.Entrances.UnlockRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Unlock(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Unload entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.UnlockResponse Unlock(global::Mruv.Entrances.UnlockRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Unlock, null, options, request); } /// <summary> /// Unload entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.UnlockResponse> UnlockAsync(global::Mruv.Entrances.UnlockRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UnlockAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Unload entrance. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.UnlockResponse> UnlockAsync(global::Mruv.Entrances.UnlockRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Unlock, null, options, request); } /// <summary> /// Find gate that is closest to a specific position. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.FindNearestEntranceResponse FindNearestEntrance(global::Mruv.Entrances.FindNearestEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return FindNearestEntrance(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Find gate that is closest to a specific position. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.FindNearestEntranceResponse FindNearestEntrance(global::Mruv.Entrances.FindNearestEntranceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_FindNearestEntrance, null, options, request); } /// <summary> /// Find gate that is closest to a specific position. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.FindNearestEntranceResponse> FindNearestEntranceAsync(global::Mruv.Entrances.FindNearestEntranceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return FindNearestEntranceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Find gate that is closest to a specific position. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.FindNearestEntranceResponse> FindNearestEntranceAsync(global::Mruv.Entrances.FindNearestEntranceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_FindNearestEntrance, null, options, request); } /// <summary> /// Enter an entrance (player teleport from in spot position to out spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.EnterResponse Enter(global::Mruv.Entrances.EnterRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Enter(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Enter an entrance (player teleport from in spot position to out spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.EnterResponse Enter(global::Mruv.Entrances.EnterRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Enter, null, options, request); } /// <summary> /// Enter an entrance (player teleport from in spot position to out spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.EnterResponse> EnterAsync(global::Mruv.Entrances.EnterRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return EnterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Enter an entrance (player teleport from in spot position to out spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.EnterResponse> EnterAsync(global::Mruv.Entrances.EnterRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Enter, null, options, request); } /// <summary> /// Exit from entrance (player teleport from out spot position to in spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.ExitResponse Exit(global::Mruv.Entrances.ExitRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return Exit(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exit from entrance (player teleport from out spot position to in spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Mruv.Entrances.ExitResponse Exit(global::Mruv.Entrances.ExitRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Exit, null, options, request); } /// <summary> /// Exit from entrance (player teleport from out spot position to in spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.ExitResponse> ExitAsync(global::Mruv.Entrances.ExitRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ExitAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Exit from entrance (player teleport from out spot position to in spot position). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Mruv.Entrances.ExitResponse> ExitAsync(global::Mruv.Entrances.ExitRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Exit, null, options, request); } /// <summary> /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncServerStreamingCall<global::Mruv.Entrances.FetchAllEntrancesResponse> FetchAll(global::Mruv.Entrances.FetchAllEntrancesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return FetchAll(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncServerStreamingCall<global::Mruv.Entrances.FetchAllEntrancesResponse> FetchAll(global::Mruv.Entrances.FetchAllEntrancesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncServerStreamingCall(__Method_FetchAll, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override MruVEntrancesServiceClient NewInstance(ClientBaseConfiguration configuration) { return new MruVEntrancesServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(MruVEntrancesServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateEntrance, serviceImpl.CreateEntrance) .AddMethod(__Method_GetEntrance, serviceImpl.GetEntrance) .AddMethod(__Method_UpdateEntrance, serviceImpl.UpdateEntrance) .AddMethod(__Method_DeleteEntrance, serviceImpl.DeleteEntrance) .AddMethod(__Method_Lock, serviceImpl.Lock) .AddMethod(__Method_Unlock, serviceImpl.Unlock) .AddMethod(__Method_FindNearestEntrance, serviceImpl.FindNearestEntrance) .AddMethod(__Method_Enter, serviceImpl.Enter) .AddMethod(__Method_Exit, serviceImpl.Exit) .AddMethod(__Method_FetchAll, serviceImpl.FetchAll).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, MruVEntrancesServiceBase serviceImpl) { serviceBinder.AddMethod(__Method_CreateEntrance, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.CreateEntranceRequest, global::Mruv.Entrances.CreateEntranceResponse>(serviceImpl.CreateEntrance)); serviceBinder.AddMethod(__Method_GetEntrance, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.GetEntranceRequest, global::Mruv.Entrances.GetEntranceResponse>(serviceImpl.GetEntrance)); serviceBinder.AddMethod(__Method_UpdateEntrance, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.UpdateEntranceRequest, global::Mruv.Entrances.UpdateEntranceResponse>(serviceImpl.UpdateEntrance)); serviceBinder.AddMethod(__Method_DeleteEntrance, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.DeleteEntranceRequest, global::Mruv.Entrances.DeleteEntranceResponse>(serviceImpl.DeleteEntrance)); serviceBinder.AddMethod(__Method_Lock, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.LockRequest, global::Mruv.Entrances.LockResponse>(serviceImpl.Lock)); serviceBinder.AddMethod(__Method_Unlock, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.UnlockRequest, global::Mruv.Entrances.UnlockResponse>(serviceImpl.Unlock)); serviceBinder.AddMethod(__Method_FindNearestEntrance, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.FindNearestEntranceRequest, global::Mruv.Entrances.FindNearestEntranceResponse>(serviceImpl.FindNearestEntrance)); serviceBinder.AddMethod(__Method_Enter, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.EnterRequest, global::Mruv.Entrances.EnterResponse>(serviceImpl.Enter)); serviceBinder.AddMethod(__Method_Exit, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Mruv.Entrances.ExitRequest, global::Mruv.Entrances.ExitResponse>(serviceImpl.Exit)); serviceBinder.AddMethod(__Method_FetchAll, serviceImpl == null ? null : new grpc::ServerStreamingServerMethod<global::Mruv.Entrances.FetchAllEntrancesRequest, global::Mruv.Entrances.FetchAllEntrancesResponse>(serviceImpl.FetchAll)); } } } #endregion
72.94094
366
0.729799
[ "MIT" ]
MruV-RP/mruv-pb-csharp
EntrancesGrpc.cs
54,341
C#
using UnityEngine; using System.Collections.Generic; using System; namespace EA4S { public class LL_WordData : ILivingLetterData { public Db.WordData Data; public LivingLetterDataType DataType { get { return LivingLetterDataType.Word; } } public string Id { get { return Data.Id; } set { Data = AppManager.I.DB.GetWordDataById(value); } } public LL_WordData(string _id) : this(AppManager.I.DB.GetWordDataById(_id)) { } public LL_WordData(string _id, Db.WordData _data) : this(_data) { } public LL_WordData(Db.WordData _data) { Data = _data; } /// <summary> /// Living Letter Text To Display. /// </summary> public string TextForLivingLetter { get { return ArabicAlphabetHelper.PrepareArabicStringForDisplay(Data.Arabic); } } public string DrawingCharForLivingLetter { get { return AppManager.I.Teacher.wordHelper.GetWordDrawing(Data); } } /// <summary> /// Return draw of word. /// </summary> [Obsolete("Use DrawingCharForLivingLetter instead of this.")] public Sprite DrawForLivingLetter { get { return Resources.Load<Sprite>("Textures/LivingLetters/Drawings/drawing-" + Id); } } public bool Equals(ILivingLetterData data) { LL_WordData other = data as LL_WordData; if (other == null) return false; return other.Data.Id == Data.Id; } } }
26.046875
99
0.563287
[ "BSD-2-Clause" ]
Megapop/Norad-Eduapp4syria
Antura/EA4S_Antura_U3D/Assets/_app/_scripts/LivingLetter/Data/LL_WordData.cs
1,669
C#
using System; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.SessionState; namespace guestbook_cs { /// <summary> /// Summary description for Global. /// </summary> public class Global : System.Web.HttpApplication { public Global() { InitializeComponent(); } protected void Application_Start(Object sender, EventArgs e) { } protected void Session_Start(Object sender, EventArgs e) { } protected void Application_BeginRequest(Object sender, EventArgs e) { } protected void Application_EndRequest(Object sender, EventArgs e) { } protected void Application_AuthenticateRequest(Object sender, EventArgs e) { } protected void Application_Error(Object sender, EventArgs e) { } protected void Session_End(Object sender, EventArgs e) { } protected void Application_End(Object sender, EventArgs e) { } #region Web 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() { } #endregion } }
16.661972
76
0.703297
[ "MIT" ]
noenemy/Book-ASPNET-Bible-2nd-Edition
source/source/cs23/Global.asax.cs
1,183
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace CloudStack.Net { public class ListInternalLoadBalancerElementsRequest : APIListRequest { public ListInternalLoadBalancerElementsRequest() : base("listInternalLoadBalancerElements") {} /// <summary> /// list internal load balancer elements by enabled state /// </summary> public bool? Enabled { get { return GetParameterValue<bool?>(nameof(Enabled).ToLower()); } set { SetParameterValue(nameof(Enabled).ToLower(), value); } } /// <summary> /// list internal load balancer elements by id /// </summary> public Guid? Id { get { return GetParameterValue<Guid?>(nameof(Id).ToLower()); } set { SetParameterValue(nameof(Id).ToLower(), value); } } /// <summary> /// List by keyword /// </summary> public string Keyword { get { return GetParameterValue<string>(nameof(Keyword).ToLower()); } set { SetParameterValue(nameof(Keyword).ToLower(), value); } } /// <summary> /// list internal load balancer elements by network service provider id /// </summary> public Guid? NspId { get { return GetParameterValue<Guid?>(nameof(NspId).ToLower()); } set { SetParameterValue(nameof(NspId).ToLower(), value); } } } /// <summary> /// Lists all available Internal Load Balancer elements. /// </summary> public partial interface ICloudStackAPIClient { ListResponse<InternalLoadBalancerElementResponse> ListInternalLoadBalancerElements(ListInternalLoadBalancerElementsRequest request); Task<ListResponse<InternalLoadBalancerElementResponse>> ListInternalLoadBalancerElementsAsync(ListInternalLoadBalancerElementsRequest request); ListResponse<InternalLoadBalancerElementResponse> ListInternalLoadBalancerElementsAllPages(ListInternalLoadBalancerElementsRequest request); Task<ListResponse<InternalLoadBalancerElementResponse>> ListInternalLoadBalancerElementsAllPagesAsync(ListInternalLoadBalancerElementsRequest request); } public partial class CloudStackAPIClient : ICloudStackAPIClient { public ListResponse<InternalLoadBalancerElementResponse> ListInternalLoadBalancerElements(ListInternalLoadBalancerElementsRequest request) => _proxy.Request<ListResponse<InternalLoadBalancerElementResponse>>(request); public Task<ListResponse<InternalLoadBalancerElementResponse>> ListInternalLoadBalancerElementsAsync(ListInternalLoadBalancerElementsRequest request) => _proxy.RequestAsync<ListResponse<InternalLoadBalancerElementResponse>>(request); public ListResponse<InternalLoadBalancerElementResponse> ListInternalLoadBalancerElementsAllPages(ListInternalLoadBalancerElementsRequest request) => _proxy.RequestAllPages<InternalLoadBalancerElementResponse>(request); public Task<ListResponse<InternalLoadBalancerElementResponse>> ListInternalLoadBalancerElementsAllPagesAsync(ListInternalLoadBalancerElementsRequest request) => _proxy.RequestAllPagesAsync<InternalLoadBalancerElementResponse>(request); } }
51.734375
243
0.738146
[ "Apache-2.0" ]
mrehman29/cloudstack.net
src/CloudStack.Net/Generated/ListInternalLoadBalancerElements.cs
3,311
C#
namespace Teference.Zoho.Api { public enum ZsCouponDiscountBy { None, Flat, Percentage } }
14.111111
34
0.559055
[ "MIT" ]
teference/zoho-dotnet
source/Zoho.Api/Models/Enums/ZsCouponDiscountBy.cs
129
C#
using System; using FluentValidator; namespace DapperStore.Shared.Entities { public abstract class Entity : Notifiable { public Entity() { Id = Guid.NewGuid(); } public Guid Id { get; private set; } } }
17.333333
45
0.576923
[ "MIT" ]
thiagocruzrj/Dapper-Store
DapperStore.Shared/Entities/Entity.cs
260
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. namespace Microsoft.EntityFrameworkCore.Migrations { /// <summary> /// <para> /// The action that a database may take when handling a foreign key constraint as /// part of an update or delete. /// </para> /// <para> /// Note that some database engines do not support or correctly honor every action. /// </para> /// </summary> public enum ReferentialAction { /// <summary> /// Do nothing. That is, just ignore the constraint. /// </summary> NoAction, /// <summary> /// Don't perform the action if it would result in a constraint violation and instead generate an error. /// </summary> Restrict, /// <summary> /// Cascade the action to the constrained rows. /// </summary> Cascade, /// <summary> /// Set null on the constrained rows so that the constraint is not violated after the action completes. /// </summary> SetNull, /// <summary> /// Set a default value on the constrained rows so that the constraint is not violated after the action completes. /// </summary> SetDefault } }
33.069767
126
0.578762
[ "Apache-2.0" ]
0b01/efcore
src/EFCore.Relational/Migrations/ReferentialAction.cs
1,422
C#
// empty script attached to tiger gameobject // used for counting total number of tiger present in the game by script name type. using System.Collections; using System.Collections.Generic; using UnityEngine; public class tigercount : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
20.526316
84
0.694872
[ "Unlicense" ]
alokyadavnp/BaghLearn
codes/tigercount.cs
392
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("VVVV.DX11.Factories")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MrVux")] [assembly: AssemblyProduct("VVVV.DX11.Factories")] [assembly: AssemblyCopyright("Copyright © MrVux 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("aba87299-da42-4b13-9c88-f53979f440a2")] // 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.405405
84
0.746657
[ "BSD-3-Clause" ]
azeno/dx11-vvvv
Core/VVVV.DX11.Factories/Properties/AssemblyInfo.cs
1,424
C#
using System.Runtime.CompilerServices; #region Using directives using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; #endregion // 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("Aliyun.OSS.dll")] [assembly: AssemblyDescription("Aliyun OSS SDK for C#")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alibaba Cloud Computing")] [assembly: AssemblyProduct("Aliyun OSS SDK for C#")] [assembly: AssemblyCopyright("Copyright 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("zh-CN")] // This sets the default COM visibility of types in the assembly to invisible. // If you need to expose a type to COM, use [ComVisible(true)] on that type. [assembly: ComVisible(false)] // The assembly version has following format : // // Major.Minor.Build.Revision // [assembly: AssemblyVersion("2.4.0")] // The asembly is designed as CLS compliant to support CLS-compliant languages. //[assembly: CLSCompliant(true)] [assembly: InternalsVisibleTo("Aliyun.OSS.UnitTest, PublicKey=002400000480000094000000060200000024000052534131000400000100010045C2B8CBBFE7B414DEE24D990688805C04B57ABB8292CEC3CFBCF4C7F6BD8254C8DDEA76F8EA035D106914678AAE9DB8BA4BF1669637043DBE62E1DE2B978729CF6F3DD0080AC2209559371D26219B50309EFDA1D51800DE052B0A45C7C9238884EEA4E7DC3C595B4930785A33A90ED4A6869285C3C04AD95245C0DFC00D24CC")] [assembly: AssemblyFileVersion("2.4.0")]
39.738095
386
0.793289
[ "MIT" ]
NielJun/aliyun-oss-unity-sdk
sdk/Properties/AssemblyInfo.cs
1,671
C#
/******************************************************************************** Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ***********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MixERP.Net.FrontEnd.Finance { public partial class Index : MixERP.Net.BusinessLayer.BasePageClass { protected void Page_Load(object sender, EventArgs e) { string menu = MixERP.Net.BusinessLayer.Helpers.MenuHelper.GetPageMenu(this.Page); MenuLiteral.Text = menu; } } }
36.36
93
0.580858
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
gj86/mixerp2
MixERP.Net.FrontEnd/Finance/Index.aspx.cs
911
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Me.DerangedSenators.CopsAndRobbers { /// @authors Nisath Mohamed public class UIControls : MonoBehaviour { [SerializeField] private Canvas menuCanvas; private bool viewMenu; public class PauseMenuButtonHandler : IButtonListener { private UIControls _menu; public PauseMenuButtonHandler(UIControls menu) { this._menu = menu; } public void onButtonPressed() { if (!_menu.viewMenu) { _menu.viewMenu = true; } else { _menu.viewMenu = false; } } public void onButtonReleased() { // Do Nothing here } } private void Start() { if (ControlContext.Instance.Active) { ControlContext.Instance.OptionsButton.AddListener(new PauseMenuButtonHandler(this)); } } // Update is called once per frame void Update() { if (viewMenu) { menuCanvas.gameObject.SetActive(true); } else { menuCanvas.gameObject.SetActive(false); } if (Input.GetKeyDown(KeyCode.Escape) && !menuCanvas.gameObject.activeSelf) { viewMenu = true; return; } if (Input.GetKeyDown(KeyCode.Escape) && menuCanvas.gameObject.activeSelf) { viewMenu = false; return; } } /// <summary> /// Programatically set the visibility of the menu /// </summary> /// <param name="visibility"></param> public void SetMenuVisibility(bool visibility) { viewMenu = visibility; } } }
23.931034
100
0.476945
[ "Apache-2.0" ]
nisathnasar/copsandrobbers-1
CopsAndRobbers/Assets/Scripts/UI/UIControls.cs
2,084
C#
using SoulsFormats; using System.Collections.Generic; using System.Numerics; namespace HKX2 { public enum TokenType { TOKEN_TYPE_NONE = 0, TOKEN_TYPE_OPERATOR = 1, TOKEN_TYPE_NUMBER = 2, TOKEN_TYPE_VARIABLE_INDEX = 3, TOKEN_TYPE_OPENING_PAREN = 4, TOKEN_TYPE_CLOSING_PAREN = 5, TOKEN_TYPE_COMMA = 6, TOKEN_TYPE_CHARACTER_PROPERTY_INDEX = 7, } public enum Operator { OP_NOP = 0, OP_RAND01 = 1, OP_LOGICAL_NOT = 2, OP_UNARY_MINUS = 3, OP_UNARY_PLUS = 4, OP_SIN = 5, OP_COS = 6, OP_ASIN = 7, OP_ACOS = 8, OP_SQRT = 9, OP_FABS = 10, OP_CEIL = 11, OP_FLOOR = 12, OP_SQRTINV = 13, OP_MUL = 14, OP_DIV = 15, OP_ADD = 16, OP_SUB = 17, OP_LOGICAL_OR = 18, OP_LOGICAL_AND = 19, OP_EQ = 20, OP_NEQ = 21, OP_LT = 22, OP_GT = 23, OP_LEQ = 24, OP_GEQ = 25, OP_POW = 26, OP_MAX2 = 27, OP_MIN2 = 28, OP_RANDRANGE = 29, OP_ATAN2 = 30, OP_CLAMP = 31, OP_MOD = 32, OP_DEG2RAD = 33, OP_RAD2DEG = 34, OP_COSD = 35, OP_SIND = 36, OP_ACOSD = 37, OP_ASIND = 38, OP_ATAN2D = 39, OP_SIGN = 40, OP_LERP = 41, OP_CLERP = 42, OP_COND = 43, } public partial class hkbCompiledExpressionSetToken : IHavokObject { public virtual uint Signature { get => 3263667157; } public float m_data; public TokenType m_type; public Operator m_operator; public virtual void Read(PackFileDeserializer des, BinaryReaderEx br) { m_data = br.ReadSingle(); m_type = (TokenType)br.ReadSByte(); m_operator = (Operator)br.ReadSByte(); br.ReadUInt16(); } public virtual void Write(PackFileSerializer s, BinaryWriterEx bw) { bw.WriteSingle(m_data); bw.WriteSByte((sbyte)m_type); bw.WriteSByte((sbyte)m_operator); bw.WriteUInt16(0); } } }
24.434783
77
0.519573
[ "MIT" ]
SyllabusGames/DSMapStudio
HKX2/Autogen/hkbCompiledExpressionSetToken.cs
2,248
C#
using UnityEngine; using System.Collections; public abstract class InteractionGameObject : InteractionBase { [System.NonSerialized] public E_InteractionObjects InteractionType = E_InteractionObjects.None; public GameObject[] ObjectsToShow; public GameObject[] ObjectsToHide; public ParticleEmitter ActiveEffect; public AnimationClip CameraAnimation; public abstract Transform GetEntryTransform(); public Vector3 Position { get {return transform.position;}} public abstract float DoInteraction(E_InteractionType interaction); protected bool InteractionObjectUsable = true; protected bool Enabled = true; public bool IsActive { get { return InteractionObjectUsable; } } public bool IsEnabled { get { return Enabled; } } public void Enable(bool enable) { Enabled = enable; gameObject.SetActive(enable); if (ActiveEffect) ActiveEffect.emit = enable; // Debug.Log(name + enable); } protected void OnInteractionStart() { if (ActiveEffect) ActiveEffect.emit = false; if (CameraAnimation) CameraBehaviour.Instance.PlayCameraAnim(CameraAnimation.name, true, true); for (int i = 0; Emitters != null && i < Emitters.Length; i++) { InteractionParticle ip = Emitters[i]; MissionZone.Instance.StartCoroutine(PlayParticle(ip.Emitter, ip.Delay, ip.Life)); if (ip.LinkOnRoot) ip.Emitter.transform.parent = GetEntryTransform(); } for (int i = 0; Sounds != null && i < Sounds.Length; i++) { InteractionSound sound = Sounds[i]; MissionZone.Instance.StartCoroutine(PlaySound(sound.Audio, sound.Delay, sound.Life)); if (sound.Parent) sound.Audio.transform.parent = sound.Parent; } for (int i = 0; ObjectsToShow != null && i < ObjectsToShow.Length; i++) ObjectsToShow[i].SetActive(true); } protected void OnInteractionEnd() { for (int i = 0;ObjectsToHide != null && i < ObjectsToHide.Length; i++) ObjectsToHide[i].SetActive(false); } public virtual void Restart() { for (int i = 0; ObjectsToShow != null && i < ObjectsToShow.Length; i++) ObjectsToShow[i].SetActive(false); for (int i = 0;ObjectsToHide != null && i < ObjectsToHide.Length; i++) ObjectsToHide[i].SetActive(true); InteractionObjectUsable = true; } }
28.255556
97
0.631144
[ "MIT" ]
TastSong/Warrior
Warrior/Assets/Scripts/Objects/InteractionObject.cs
2,543
C#
using System.Resources; using System.Reflection; // 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("Demo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Demo")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
34
84
0.730223
[ "MIT" ]
69grad/mvvm-nano
demo/Demo/Properties/AssemblyInfo.cs
989
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using AutoMapper.Internal; using Shouldly; using Xunit; namespace AutoMapper.UnitTests.Mappers { public class TypeHelperTests { [Fact] public void CanReturnElementTypeOnCollectionThatImplementsTheSameGenericInterfaceMultipleTimes() { Type myType = typeof(ChargeCollection); Type elementType = ReflectionHelper.GetElementType(myType); elementType.ShouldNotBeNull(); } public class Charge { } public interface IChargeCollection : IEnumerable<object> { } public class ChargeCollection : Collection<Charge>, IChargeCollection { public new IEnumerator<object> GetEnumerator() { return null; } } } }
24.514286
104
0.652681
[ "MIT" ]
AutoMapper/AutoMapper
src/UnitTests/Mappers/TypeHelperTests.cs
858
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WumpusClicker.Interfaces { /// <summary> /// A monster to defeat /// </summary> public interface IMonster { /// <summary> /// The Monster's name /// </summary> public string Name { get; } /// <summary> /// The Monster's health /// </summary> public ulong Health { get; } /// <summary> /// The reward earned by killing the monster /// </summary> public ulong Reward { get; } /// <summary> /// Event raised then the monster dies /// </summary> public event Action<IMonster, ulong> OnDeath; /// <summary> /// Event raised when the monster takes damage /// </summary> public event Action<IMonster, ulong> TookDamage; /// <summary> /// Deal the specified <paramref name="dmg"/> to the monster /// </summary> /// <param name="dmg">The damage to deal</param> public void DoDamage(ulong dmg); } }
26
68
0.552448
[ "MIT" ]
LukasRH/SimpleGames
WumpusClicker/Interfaces/IMonster.cs
1,146
C#
namespace Gold_Resolver { partial class iptoskype { /// <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.validecaptcha = new System.Windows.Forms.Button(); this.labelcapcha = new System.Windows.Forms.Label(); this.captchaletter = new System.Windows.Forms.Label(); this.GoldResolver = new System.Windows.Forms.Label(); this.captcha = new ZBobb.AlphaBlendTextBox(); this.blacklisten = new System.Windows.Forms.Label(); this.blacklistfr = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.response = new ZBobb.AlphaBlendTextBox(); this.skype = new ZBobb.AlphaBlendTextBox(); this.button5 = new System.Windows.Forms.Button(); this.button9 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.exe = new System.Windows.Forms.Label(); this.responseclic = new theme.FlatContextMenuStrip(); this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.responseclic.SuspendLayout(); this.SuspendLayout(); // // validecaptcha // this.validecaptcha.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.validecaptcha.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.validecaptcha.FlatAppearance.BorderSize = 0; this.validecaptcha.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.validecaptcha.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.validecaptcha.ForeColor = System.Drawing.Color.LightGray; this.validecaptcha.Location = new System.Drawing.Point(286, 261); this.validecaptcha.Name = "validecaptcha"; this.validecaptcha.Size = new System.Drawing.Size(23, 25); this.validecaptcha.TabIndex = 41; this.validecaptcha.Text = "X"; this.validecaptcha.UseVisualStyleBackColor = false; this.validecaptcha.Click += new System.EventHandler(this.validecaptcha_Click); // // labelcapcha // this.labelcapcha.Anchor = System.Windows.Forms.AnchorStyles.Top; this.labelcapcha.AutoSize = true; this.labelcapcha.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelcapcha.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.labelcapcha.Location = new System.Drawing.Point(85, 289); this.labelcapcha.Name = "labelcapcha"; this.labelcapcha.Size = new System.Drawing.Size(61, 16); this.labelcapcha.TabIndex = 40; this.labelcapcha.Text = "Captcha:"; // // captchaletter // this.captchaletter.Anchor = System.Windows.Forms.AnchorStyles.Top; this.captchaletter.AutoSize = true; this.captchaletter.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.captchaletter.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.captchaletter.Location = new System.Drawing.Point(25, 289); this.captchaletter.Name = "captchaletter"; this.captchaletter.Size = new System.Drawing.Size(61, 16); this.captchaletter.TabIndex = 39; this.captchaletter.Text = "Captcha:"; // // GoldResolver // this.GoldResolver.Anchor = System.Windows.Forms.AnchorStyles.Top; this.GoldResolver.AutoSize = true; this.GoldResolver.Font = new System.Drawing.Font("Microsoft Sans Serif", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.GoldResolver.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.GoldResolver.Location = new System.Drawing.Point(213, 22); this.GoldResolver.Name = "GoldResolver"; this.GoldResolver.Size = new System.Drawing.Size(250, 39); this.GoldResolver.TabIndex = 38; this.GoldResolver.Text = "Gold Resolver"; // // captcha // this.captcha.BackAlpha = 100; this.captcha.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.captcha.BorderStyle = System.Windows.Forms.BorderStyle.None; this.captcha.Font = new System.Drawing.Font("Corbel", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.captcha.ForeColor = System.Drawing.Color.White; this.captcha.Location = new System.Drawing.Point(28, 261); this.captcha.Name = "captcha"; this.captcha.Size = new System.Drawing.Size(254, 25); this.captcha.TabIndex = 37; this.captcha.Tag = ""; this.captcha.Text = "Captcha"; this.captcha.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // blacklisten // this.blacklisten.Anchor = System.Windows.Forms.AnchorStyles.Top; this.blacklisten.AutoSize = true; this.blacklisten.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.blacklisten.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.blacklisten.Location = new System.Drawing.Point(4, 432); this.blacklisten.Name = "blacklisten"; this.blacklisten.Size = new System.Drawing.Size(467, 16); this.blacklisten.TabIndex = 36; this.blacklisten.Text = "Need that your account/ip/mail be blacklisted on all APIs. Contact OldModz95."; // // blacklistfr // this.blacklistfr.Anchor = System.Windows.Forms.AnchorStyles.Top; this.blacklistfr.AutoSize = true; this.blacklistfr.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.blacklistfr.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.blacklistfr.Location = new System.Drawing.Point(4, 451); this.blacklistfr.Name = "blacklistfr"; this.blacklistfr.Size = new System.Drawing.Size(580, 16); this.blacklistfr.TabIndex = 35; this.blacklistfr.Text = "Besoin que votre compte/ip/email soit mis sur liste noire sur toutes les API. Con" + "tacter OldModz95."; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(23)))), ((int)(((byte)(21)))), ((int)(((byte)(32))))); this.label2.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(454, 105); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(117, 19); this.label2.TabIndex = 34; this.label2.Text = "[+] Response"; // // response // this.response.BackAlpha = 100; this.response.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.response.BorderStyle = System.Windows.Forms.BorderStyle.None; this.response.ContextMenuStrip = this.responseclic; this.response.Cursor = System.Windows.Forms.Cursors.No; this.response.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.response.ForeColor = System.Drawing.Color.White; this.response.Location = new System.Drawing.Point(347, 127); this.response.Multiline = true; this.response.Name = "response"; this.response.ReadOnly = true; this.response.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal; this.response.Size = new System.Drawing.Size(324, 254); this.response.TabIndex = 33; this.response.Tag = ""; this.response.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // skype // this.skype.BackAlpha = 100; this.skype.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.skype.BorderStyle = System.Windows.Forms.BorderStyle.None; this.skype.Font = new System.Drawing.Font("Arial", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.skype.ForeColor = System.Drawing.Color.White; this.skype.Location = new System.Drawing.Point(28, 220); this.skype.Name = "skype"; this.skype.Size = new System.Drawing.Size(254, 23); this.skype.TabIndex = 32; this.skype.Tag = ""; this.skype.Text = "78.118.243.85"; this.skype.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // button5 // this.button5.FlatAppearance.BorderSize = 0; this.button5.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button5.ForeColor = System.Drawing.Color.LightGray; this.button5.Location = new System.Drawing.Point(676, 0); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(25, 25); this.button5.TabIndex = 31; this.button5.Text = "X"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // button9 // this.button9.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button9.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.button9.FlatAppearance.BorderSize = 0; this.button9.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button9.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button9.ForeColor = System.Drawing.Color.LightGray; this.button9.Location = new System.Drawing.Point(28, 337); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(254, 32); this.button9.TabIndex = 30; this.button9.Text = "Resolve User"; this.button9.UseVisualStyleBackColor = false; this.button9.Click += new System.EventHandler(this.button9_Click); // // label1 // this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top; this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(42)))), ((int)(((byte)(83))))); this.label1.Location = new System.Drawing.Point(50, 127); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(215, 39); this.label1.TabIndex = 29; this.label1.Text = "IP To Skype"; // // exe // this.exe.AutoSize = true; this.exe.Location = new System.Drawing.Point(642, 413); this.exe.Name = "exe"; this.exe.Size = new System.Drawing.Size(24, 13); this.exe.TabIndex = 42; this.exe.Text = "exe"; this.exe.Visible = false; // // responseclic // this.responseclic.Font = new System.Drawing.Font("Segoe UI", 8F); this.responseclic.ForeColor = System.Drawing.Color.White; this.responseclic.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.clearToolStripMenuItem}); this.responseclic.Name = "responseclic"; this.responseclic.ShowImageMargin = false; this.responseclic.Size = new System.Drawing.Size(156, 48); // // clearToolStripMenuItem // this.clearToolStripMenuItem.Name = "clearToolStripMenuItem"; this.clearToolStripMenuItem.Size = new System.Drawing.Size(155, 22); this.clearToolStripMenuItem.Text = "Clear"; this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click); // // iptoskype // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(32)))), ((int)(((byte)(30)))), ((int)(((byte)(45))))); this.ClientSize = new System.Drawing.Size(700, 470); this.Controls.Add(this.exe); this.Controls.Add(this.validecaptcha); this.Controls.Add(this.labelcapcha); this.Controls.Add(this.captchaletter); this.Controls.Add(this.GoldResolver); this.Controls.Add(this.captcha); this.Controls.Add(this.blacklisten); this.Controls.Add(this.blacklistfr); this.Controls.Add(this.label2); this.Controls.Add(this.response); this.Controls.Add(this.skype); this.Controls.Add(this.button5); this.Controls.Add(this.button9); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "iptoskype"; this.Text = "iptoskype"; this.responseclic.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button validecaptcha; private System.Windows.Forms.Label labelcapcha; private System.Windows.Forms.Label captchaletter; private System.Windows.Forms.Label GoldResolver; private ZBobb.AlphaBlendTextBox captcha; private System.Windows.Forms.Label blacklisten; private System.Windows.Forms.Label blacklistfr; private System.Windows.Forms.Label label2; private ZBobb.AlphaBlendTextBox response; private ZBobb.AlphaBlendTextBox skype; private System.Windows.Forms.Button button5; private System.Windows.Forms.Button button9; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label exe; private theme.FlatContextMenuStrip responseclic; private System.Windows.Forms.ToolStripMenuItem clearToolStripMenuItem; } }
57.03268
176
0.602624
[ "Apache-2.0" ]
OldModz95-YTB/Gold-Resolver-source
Gold Resolver/iptoskype.Designer.cs
17,454
C#
using NUnit.Framework; using Specification; using Specification.SpecificationTree; namespace SpecificationTests { public class LenientlyEqualsTests { [Test] public void LeafNodesAreEqualIfTheyAreOfTheSameType() { AssertEqual(new PassingSpecification<object>(), new PassingSpecification<object>()); } [Test] public void LeafNodesAreNotEqualIfTheyAreNotOfTheSameType() { AssertNotEqual(new PassingSpecification<object>(), new FailingSpecification<object>()); } [Test] public void LeafNodesAreAbleToOverrideEquals() { AssertEqual(new AlwaysEqualSpecification<object>(), new FailingSpecification<object>()); } [Test] public void AndNodesWithEqualChildrenAreEqual() { AssertEqual(new PassingSpecification<object>().And(new FailingSpecification<object>()), new PassingSpecification<object>().And(new FailingSpecification<object>())); } [Test] public void AndNodesWithFlippedChildrenAreEqual() { AssertEqual(new FailingSpecification<object>().And(new PassingSpecification<object>()), new PassingSpecification<object>().And(new FailingSpecification<object>())); } [Test] public void AndNodesWithDifferentChildrenAreNotEqual() { AssertNotEqual(new FailingSpecification<object>().And(new FailingSpecification<object>()), new PassingSpecification<object>().And(new FailingSpecification<object>())); } [Test] public void OrNodesWithEqualChildrenAreEqual() { AssertEqual(new PassingSpecification<object>().Or(new FailingSpecification<object>()), new PassingSpecification<object>().Or(new FailingSpecification<object>())); } [Test] public void OrNodesWithFlippedChildrenAreEqual() { AssertEqual(new FailingSpecification<object>().Or(new PassingSpecification<object>()), new PassingSpecification<object>().Or(new FailingSpecification<object>())); } [Test] public void OrNodesWithDifferentChildrenAreNotEqual() { AssertNotEqual(new FailingSpecification<object>().Or(new FailingSpecification<object>()), new PassingSpecification<object>().Or(new FailingSpecification<object>())); } [Test] public void NotNodesWithEqualChildrenAreEqual() { AssertEqual(Not.This(new PassingSpecification<object>()), Not.This(new PassingSpecification<object>())); } [Test] public void NotNodesWithDifferentChildrenAreNotEqual() { AssertNotEqual(Not.This(new PassingSpecification<object>()), Not.This(new FailingSpecification<object>())); } [Test] public void AndNodesAndOrNodesAreNotEqual() { AssertNotEqual(new PassingSpecification<object>().And(new FailingSpecification<object>()), new PassingSpecification<object>().Or(new FailingSpecification<object>())); } [Test] public void AndNodesAndNotNodesAreNotEqual() { AssertNotEqual(new FailingSpecification<object>().And(new PassingSpecification<object>()), Not.This(new FailingSpecification<object>())); } [Test] public void OrNodesAndNotNodesAreNotEqual() { AssertNotEqual(new FailingSpecification<object>().Or(new FailingSpecification<object>()), new PassingSpecification<object>().Or(new FailingSpecification<object>())); } static void AssertEqual(ISpecification<object> left, ISpecification<object> right) { Assert.True(left.LenientlyEquals(right)); } static void AssertNotEqual(ISpecification<object> left, ISpecification<object> right) { Assert.False(left.LenientlyEquals(right)); } } }
37.721154
179
0.659954
[ "MIT" ]
HuddleEng/Specification
SpecificationTests/LenientlyEqualsTests.cs
3,925
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableSingle.Single{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Single>; using T_DATA2 =System.Single; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__01__VV public static class TestSet_504__param__01__VV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { 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_001__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=4; var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=4; T_DATA2 vv2=3; var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_003__greater //----------------------------------------------------------------------- [Test] public static void Test_ZA01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA01NV //----------------------------------------------------------------------- [Test] public static void Test_ZA02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA02VN //----------------------------------------------------------------------- [Test] public static void Test_ZA03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZA03NN //----------------------------------------------------------------------- [Test] public static void Test_ZB01NV() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB01NV //----------------------------------------------------------------------- [Test] public static void Test_ZB02VN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=3; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB02VN //----------------------------------------------------------------------- [Test] public static void Test_ZB03NN() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { object vv1__null_obj=null; object vv2__null_obj=null; var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_ZB03NN };//class TestSet_504__param__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableSingle.Single
24.712042
137
0.531886
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LessThan/Complete/NullableSingle/Single/TestSet_504__param__01__VV.cs
9,442
C#
//---------------------------------------------------------------------------- // <auto-generated> // This is autogenerated code by CppSharp. // Do not edit this file or all your changes will be lost after re-generation. // </auto-generated> //---------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Security; namespace LLDB { public unsafe partial class TypeSummaryOptions : IDisposable { [StructLayout(LayoutKind.Explicit, Size = 4)] public partial struct Internal { [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSummaryOptions@lldb@@QAE@XZ")] internal static extern global::System.IntPtr ctor_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSummaryOptions@lldb@@QAE@ABV01@@Z")] internal static extern global::System.IntPtr cctor_1(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??1SBTypeSummaryOptions@lldb@@QAE@XZ")] internal static extern void dtor_0(global::System.IntPtr instance, int delete); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsValid@SBTypeSummaryOptions@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsValid_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetLanguage@SBTypeSummaryOptions@lldb@@QAE?AW4LanguageType@2@XZ")] internal static extern LLDB.LanguageType GetLanguage_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetLanguage@SBTypeSummaryOptions@lldb@@QAEXW4LanguageType@2@@Z")] internal static extern void SetLanguage_0(global::System.IntPtr instance, LLDB.LanguageType _0); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetCapping@SBTypeSummaryOptions@lldb@@QAE?AW4TypeSummaryCapping@2@XZ")] internal static extern LLDB.TypeSummaryCapping GetCapping_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetCapping@SBTypeSummaryOptions@lldb@@QAEXW4TypeSummaryCapping@2@@Z")] internal static extern void SetCapping_0(global::System.IntPtr instance, LLDB.TypeSummaryCapping _0); } public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; public static readonly System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSummaryOptions> NativeToManagedMap = new System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSummaryOptions>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; public static TypeSummaryOptions __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new TypeSummaryOptions(native.ToPointer(), skipVTables); } public static TypeSummaryOptions __CreateInstance(TypeSummaryOptions.Internal native, bool skipVTables = false) { return new TypeSummaryOptions(native, skipVTables); } private static void* __CopyValue(TypeSummaryOptions.Internal native) { var ret = Marshal.AllocHGlobal(4); LLDB.TypeSummaryOptions.Internal.cctor_1(ret, new global::System.IntPtr(&native)); return ret.ToPointer(); } private TypeSummaryOptions(TypeSummaryOptions.Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected TypeSummaryOptions(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public TypeSummaryOptions() { __Instance = Marshal.AllocHGlobal(4); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; Internal.ctor_0((__Instance + __PointerAdjustment)); } public TypeSummaryOptions(LLDB.TypeSummaryOptions rhs) { __Instance = Marshal.AllocHGlobal(4); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; if (ReferenceEquals(rhs, null)) throw new global::System.ArgumentNullException("rhs", "Cannot be null because it is a C++ reference (&)."); var arg0 = rhs.__Instance; Internal.cctor_1((__Instance + __PointerAdjustment), arg0); } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { LLDB.TypeSummaryOptions __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); Internal.dtor_0((__Instance + __PointerAdjustment), 0); if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); } public bool IsValid() { var __ret = Internal.IsValid_0((__Instance + __PointerAdjustment)); return __ret; } public LLDB.LanguageType Language { get { var __ret = Internal.GetLanguage_0((__Instance + __PointerAdjustment)); return __ret; } set { var arg0 = value; Internal.SetLanguage_0((__Instance + __PointerAdjustment), arg0); } } public LLDB.TypeSummaryCapping Capping { get { var __ret = Internal.GetCapping_0((__Instance + __PointerAdjustment)); return __ret; } set { var arg0 = value; Internal.SetCapping_0((__Instance + __PointerAdjustment), arg0); } } } public unsafe partial class TypeSummary : IDisposable { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct Internal { [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSummary@lldb@@QAE@XZ")] internal static extern global::System.IntPtr ctor_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0SBTypeSummary@lldb@@QAE@ABV01@@Z")] internal static extern global::System.IntPtr cctor_1(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??1SBTypeSummary@lldb@@QAE@XZ")] internal static extern void dtor_0(global::System.IntPtr instance, int delete); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithSummaryString@SBTypeSummary@lldb@@SA?AV12@PBDI@Z")] internal static extern void CreateWithSummaryString_0(global::System.IntPtr @return, global::System.IntPtr data, uint options); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithFunctionName@SBTypeSummary@lldb@@SA?AV12@PBDI@Z")] internal static extern void CreateWithFunctionName_0(global::System.IntPtr @return, global::System.IntPtr data, uint options); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithScriptCode@SBTypeSummary@lldb@@SA?AV12@PBDI@Z")] internal static extern void CreateWithScriptCode_0(global::System.IntPtr @return, global::System.IntPtr data, uint options); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl, EntryPoint="?CreateWithCallback@SBTypeSummary@lldb@@SA?AV12@P6A_NVSBValue@2@VSBTypeSummaryOptions@2@AAVSBStream@2@@ZIPBD@Z")] internal static extern void CreateWithCallback_0(global::System.IntPtr @return, global::System.IntPtr cb, uint options, global::System.IntPtr description); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsValid@SBTypeSummary@lldb@@QBE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsValid_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsFunctionCode@SBTypeSummary@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsFunctionCode_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsFunctionName@SBTypeSummary@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsFunctionName_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsSummaryString@SBTypeSummary@lldb@@QAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsSummaryString_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetDescription@SBTypeSummary@lldb@@QAE_NAAVSBStream@2@W4DescriptionLevel@2@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool GetDescription_0(global::System.IntPtr instance, global::System.IntPtr description, LLDB.DescriptionLevel description_level); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?DoesPrintValue@SBTypeSummary@lldb@@QAE_NVSBValue@2@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool DoesPrintValue_0(global::System.IntPtr instance, LLDB.Value.Internal value); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?IsEqualTo@SBTypeSummary@lldb@@QAE_NAAV12@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool IsEqualTo_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??8SBTypeSummary@lldb@@QAE_NAAV01@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool OperatorEqualEqual_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??9SBTypeSummary@lldb@@QAE_NAAV01@@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool OperatorExclaimEqual_0(global::System.IntPtr instance, global::System.IntPtr rhs); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?CopyOnWrite_Impl@SBTypeSummary@lldb@@IAE_NXZ")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool CopyOnWrite_Impl_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?ChangeSummaryType@SBTypeSummary@lldb@@IAE_N_N@Z")] [return: MarshalAsAttribute(UnmanagedType.I1)] internal static extern bool ChangeSummaryType_0(global::System.IntPtr instance, bool want_script); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetData@SBTypeSummary@lldb@@QAEPBDXZ")] internal static extern global::System.IntPtr GetData_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetSummaryString@SBTypeSummary@lldb@@QAEXPBD@Z")] internal static extern void SetSummaryString_0(global::System.IntPtr instance, global::System.IntPtr data); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetFunctionName@SBTypeSummary@lldb@@QAEXPBD@Z")] internal static extern void SetFunctionName_0(global::System.IntPtr instance, global::System.IntPtr data); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetFunctionCode@SBTypeSummary@lldb@@QAEXPBD@Z")] internal static extern void SetFunctionCode_0(global::System.IntPtr instance, global::System.IntPtr data); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?GetOptions@SBTypeSummary@lldb@@QAEIXZ")] internal static extern uint GetOptions_0(global::System.IntPtr instance); [SuppressUnmanagedCodeSecurity] [DllImport("lldb", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?SetOptions@SBTypeSummary@lldb@@QAEXI@Z")] internal static extern void SetOptions_0(global::System.IntPtr instance, uint _0); } [SuppressUnmanagedCodeSecurity, UnmanagedFunctionPointerAttribute(global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public unsafe delegate bool FormatCallback(LLDB.Value.Internal _0, LLDB.TypeSummaryOptions.Internal _1, global::System.IntPtr _2); public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; public static readonly System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSummary> NativeToManagedMap = new System.Collections.Concurrent.ConcurrentDictionary<IntPtr, TypeSummary>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; public static TypeSummary __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new TypeSummary(native.ToPointer(), skipVTables); } public static TypeSummary __CreateInstance(TypeSummary.Internal native, bool skipVTables = false) { return new TypeSummary(native, skipVTables); } private static void* __CopyValue(TypeSummary.Internal native) { var ret = Marshal.AllocHGlobal(8); LLDB.TypeSummary.Internal.cctor_1(ret, new global::System.IntPtr(&native)); return ret.ToPointer(); } private TypeSummary(TypeSummary.Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected TypeSummary(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public TypeSummary() { __Instance = Marshal.AllocHGlobal(8); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; Internal.ctor_0((__Instance + __PointerAdjustment)); } public TypeSummary(LLDB.TypeSummary rhs) { __Instance = Marshal.AllocHGlobal(8); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; if (ReferenceEquals(rhs, null)) throw new global::System.ArgumentNullException("rhs", "Cannot be null because it is a C++ reference (&)."); var arg0 = rhs.__Instance; Internal.cctor_1((__Instance + __PointerAdjustment), arg0); } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { LLDB.TypeSummary __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); Internal.dtor_0((__Instance + __PointerAdjustment), 0); if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); } public bool IsValid() { var __ret = Internal.IsValid_0((__Instance + __PointerAdjustment)); return __ret; } public bool IsFunctionCode() { var __ret = Internal.IsFunctionCode_0((__Instance + __PointerAdjustment)); return __ret; } public bool IsFunctionName() { var __ret = Internal.IsFunctionName_0((__Instance + __PointerAdjustment)); return __ret; } public bool IsSummaryString() { var __ret = Internal.IsSummaryString_0((__Instance + __PointerAdjustment)); return __ret; } public bool GetDescription(LLDB.Stream description, LLDB.DescriptionLevel description_level) { if (ReferenceEquals(description, null)) throw new global::System.ArgumentNullException("description", "Cannot be null because it is a C++ reference (&)."); var arg0 = description.__Instance; var arg1 = description_level; var __ret = Internal.GetDescription_0((__Instance + __PointerAdjustment), arg0, arg1); return __ret; } public bool DoesPrintValue(LLDB.Value value) { var arg0 = ReferenceEquals(value, null) ? new LLDB.Value.Internal() : *(LLDB.Value.Internal*) (value.__Instance); var __ret = Internal.DoesPrintValue_0((__Instance + __PointerAdjustment), arg0); return __ret; } public bool IsEqualTo(LLDB.TypeSummary rhs) { if (ReferenceEquals(rhs, null)) throw new global::System.ArgumentNullException("rhs", "Cannot be null because it is a C++ reference (&)."); var arg0 = rhs.__Instance; var __ret = Internal.IsEqualTo_0((__Instance + __PointerAdjustment), arg0); return __ret; } public static bool operator ==(LLDB.TypeSummary __op, LLDB.TypeSummary rhs) { bool __opNull = ReferenceEquals(__op, null); bool rhsNull = ReferenceEquals(rhs, null); if (__opNull || rhsNull) return __opNull && rhsNull; var arg0 = __op.__Instance; var arg1 = rhs.__Instance; var __ret = Internal.OperatorEqualEqual_0(arg0, arg1); return __ret; } public override bool Equals(object obj) { return this == obj as TypeSummary; } public override int GetHashCode() { if (__Instance == global::System.IntPtr.Zero) return global::System.IntPtr.Zero.GetHashCode(); return (*(Internal*) __Instance).GetHashCode(); } public static bool operator !=(LLDB.TypeSummary __op, LLDB.TypeSummary rhs) { bool __opNull = ReferenceEquals(__op, null); bool rhsNull = ReferenceEquals(rhs, null); if (__opNull || rhsNull) return !(__opNull && rhsNull); var arg0 = __op.__Instance; var arg1 = rhs.__Instance; var __ret = Internal.OperatorExclaimEqual_0(arg0, arg1); return __ret; } protected bool CopyOnWrite_Impl() { var __ret = Internal.CopyOnWrite_Impl_0((__Instance + __PointerAdjustment)); return __ret; } protected bool ChangeSummaryType(bool want_script) { var __ret = Internal.ChangeSummaryType_0((__Instance + __PointerAdjustment), want_script); return __ret; } public static LLDB.TypeSummary CreateWithSummaryString(string data, uint options) { var arg0 = Marshal.StringToHGlobalAnsi(data); var __ret = new LLDB.TypeSummary.Internal(); Internal.CreateWithSummaryString_0(new IntPtr(&__ret), arg0, options); Marshal.FreeHGlobal(arg0); return LLDB.TypeSummary.__CreateInstance(__ret); } public static LLDB.TypeSummary CreateWithFunctionName(string data, uint options) { var arg0 = Marshal.StringToHGlobalAnsi(data); var __ret = new LLDB.TypeSummary.Internal(); Internal.CreateWithFunctionName_0(new IntPtr(&__ret), arg0, options); Marshal.FreeHGlobal(arg0); return LLDB.TypeSummary.__CreateInstance(__ret); } public static LLDB.TypeSummary CreateWithScriptCode(string data, uint options) { var arg0 = Marshal.StringToHGlobalAnsi(data); var __ret = new LLDB.TypeSummary.Internal(); Internal.CreateWithScriptCode_0(new IntPtr(&__ret), arg0, options); Marshal.FreeHGlobal(arg0); return LLDB.TypeSummary.__CreateInstance(__ret); } public static LLDB.TypeSummary CreateWithCallback(LLDB.TypeSummary.FormatCallback cb, uint options, string description) { var arg0 = cb == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(cb); var arg2 = Marshal.StringToHGlobalAnsi(description); var __ret = new LLDB.TypeSummary.Internal(); Internal.CreateWithCallback_0(new IntPtr(&__ret), arg0, options, arg2); Marshal.FreeHGlobal(arg2); return LLDB.TypeSummary.__CreateInstance(__ret); } public string Data { get { var __ret = Internal.GetData_0((__Instance + __PointerAdjustment)); return Marshal.PtrToStringAnsi(__ret); } } public string SummaryString { set { var arg0 = Marshal.StringToHGlobalAnsi(value); Internal.SetSummaryString_0((__Instance + __PointerAdjustment), arg0); Marshal.FreeHGlobal(arg0); } } public string FunctionName { set { var arg0 = Marshal.StringToHGlobalAnsi(value); Internal.SetFunctionName_0((__Instance + __PointerAdjustment), arg0); Marshal.FreeHGlobal(arg0); } } public string FunctionCode { set { var arg0 = Marshal.StringToHGlobalAnsi(value); Internal.SetFunctionCode_0((__Instance + __PointerAdjustment), arg0); Marshal.FreeHGlobal(arg0); } } public uint Options { get { var __ret = Internal.GetOptions_0((__Instance + __PointerAdjustment)); return __ret; } set { Internal.SetOptions_0((__Instance + __PointerAdjustment), value); } } } }
46.236842
216
0.643407
[ "MIT" ]
tritao/LLDBSharp
LLDBSharp/i686-pc-windows-msvc/SBTypeSummary.cs
26,355
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Stairway.Domain")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Stairway.Domain")] [assembly: System.Reflection.AssemblyTitleAttribute("Stairway.Domain")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.458333
80
0.649246
[ "MIT" ]
jsanjuan2016/Stairway
Stairway.Pattern/Stairway.Domain/obj/Debug/netcoreapp3.1/Stairway.Domain.AssemblyInfo.cs
995
C#
using System.ComponentModel.DataAnnotations; namespace Experimentation.Logic.ViewModels { public class FeatureViewModel : BaseFeatureViewModel { [Required(AllowEmptyStrings = false, ErrorMessage = "A feature ID cannot be an empty string and must be a valid meaningful unique ID.")] public string Id { get; set; } } }
32.454545
111
0.705882
[ "MIT" ]
iby-dev/Experimentation-API
src/Services/Experimentation/Experimentation.Logic/ViewModels/FeatureViewModel.cs
357
C#
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace BangBang.Data.Models.Mapping { public class CompanyMap : EntityTypeConfiguration<Company> { public CompanyMap() { // Primary Key this.HasKey(t => t.Id); // Properties this.Property(t => t.Domain) .HasMaxLength(50); this.Property(t => t.Abbreviation) .IsRequired() .HasMaxLength(50); this.Property(t => t.CompanyName) .IsRequired() .HasMaxLength(150); this.Property(t => t.Address) .HasMaxLength(500); this.Property(t => t.Logo) .HasMaxLength(500); this.Property(t => t.Phone) .HasMaxLength(50); this.Property(t => t.Fax) .HasMaxLength(50); this.Property(t => t.Email) .HasMaxLength(50); this.Property(t => t.QQ) .HasMaxLength(20); this.Property(t => t.Weixin) .HasMaxLength(150); this.Property(t => t.Homepage) .HasMaxLength(150); // Table & Column Mappings this.ToTable("Companies"); this.Property(t => t.Id).HasColumnName("Id"); this.Property(t => t.CompanyNo).HasColumnName("CompanyNo"); this.Property(t => t.Domain).HasColumnName("Domain"); this.Property(t => t.Abbreviation).HasColumnName("Abbreviation"); this.Property(t => t.CompanyName).HasColumnName("CompanyName"); this.Property(t => t.AddressId).HasColumnName("AddressId"); this.Property(t => t.Address).HasColumnName("Address"); this.Property(t => t.Logo).HasColumnName("Logo"); this.Property(t => t.CompanyType).HasColumnName("CompanyType"); this.Property(t => t.Phone).HasColumnName("Phone"); this.Property(t => t.Fax).HasColumnName("Fax"); this.Property(t => t.Email).HasColumnName("Email"); this.Property(t => t.QQ).HasColumnName("QQ"); this.Property(t => t.Weixin).HasColumnName("Weixin"); this.Property(t => t.Homepage).HasColumnName("Homepage"); this.Property(t => t.Active).HasColumnName("Active"); this.Property(t => t.Deleted).HasColumnName("Deleted"); this.Property(t => t.AdminUserId).HasColumnName("AdminUserId"); this.Property(t => t.CreatedOnUtc).HasColumnName("CreatedOnUtc"); this.Property(t => t.CreatedBy).HasColumnName("CreatedBy"); } } }
37.702703
78
0.534409
[ "MIT" ]
don59/Ebboy
src/Libraries/Ebboy.Data/Models/Mapping/CompanyMap.cs
2,790
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Yarp.ReverseProxy.Utilities; namespace Yarp.ReverseProxy.Forwarder; /// <summary> /// Custom <see cref="HttpContent"/> /// used to proxy the incoming request body to the upstream server. /// </summary> /// <remarks> /// <para> /// By implementing a custom <see cref="HttpContent"/>, we are able to execute /// our custom code for all HTTP protocol versions. /// See the remarks section of <see cref="SerializeToStreamAsync(Stream, TransportContext)"/> /// for more details. /// </para> /// <para> /// <see cref="HttpContent"/> declares an internal property `AllowDuplex` /// which, when set to true, causes <see cref="HttpClient"/> and friends /// to NOT tie up the request body stream operations to the same cancellation token /// that is passed to <see cref="HttpClient.SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken)"/>. /// </para> /// <para> /// When proxying duplex channels such as HTTP/2, gRPC, /// we need `HttpContent.AllowDuplex` to be true. /// It so happens to be by default on .NET Core 3.1. Should that ever change, /// this class will need to be updated. /// </para> /// </remarks> internal sealed class StreamCopyHttpContent : HttpContent { private readonly Stream _source; private readonly bool _autoFlushHttpClientOutgoingStream; private readonly IClock _clock; private readonly ActivityCancellationTokenSource _activityToken; private readonly TaskCompletionSource<(StreamCopyResult, Exception?)> _tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _started; public StreamCopyHttpContent(Stream source, bool autoFlushHttpClientOutgoingStream, IClock clock, ActivityCancellationTokenSource activityToken) { _source = source ?? throw new ArgumentNullException(nameof(source)); _autoFlushHttpClientOutgoingStream = autoFlushHttpClientOutgoingStream; _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _activityToken = activityToken; } /// <summary> /// Gets a <see cref="System.Threading.Tasks.Task"/> that completes in successful or failed state /// mimicking the result of SerializeToStreamAsync. /// </summary> public Task<(StreamCopyResult, Exception?)> ConsumptionTask => _tcs.Task; /// <summary> /// Gets a value indicating whether consumption of this content has begun. /// Property <see cref="ConsumptionTask"/> can be used to track the asynchronous outcome of the operation. /// </summary> /// <remarks> /// When used as an outgoing request content with <see cref="HttpClient"/>, /// this should always be true by the time the task returned by /// <see cref="HttpClient.SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken)"/> /// completes, even when using <see cref="HttpCompletionOption.ResponseHeadersRead"/>. /// </remarks> public bool Started => Volatile.Read(ref _started) == 1; public bool InProgress => Started && !ConsumptionTask.IsCompleted; /// <summary> /// Copies bytes from the stream provided in our constructor into the target <paramref name="stream"/>. /// </summary> /// <remarks> /// This is used internally by HttpClient.SendAsync to send the request body. /// Here's the sequence of events as of commit 17300169760c61a90cab8d913636c1058a30a8c1 (https://github.com/dotnet/corefx -- tag v3.1.1). /// /// <code> /// HttpClient.SendAsync --> /// HttpMessageInvoker.SendAsync --> /// HttpClientHandler.SendAsync --> /// SocketsHttpHandler.SendAsync --> /// HttpConnectionHandler.SendAsync --> /// HttpConnectionPoolManager.SendAsync --> /// HttpConnectionPool.SendAsync --> ... --> /// { /// HTTP/1.1: HttpConnection.SendAsync --> /// HttpConnection.SendAsyncCore --> /// HttpConnection.SendRequestContentAsync --> /// HttpContent.CopyToAsync /// /// HTTP/2: Http2Connection.SendAsync --> /// Http2Stream.SendRequestBodyAsync --> /// HttpContent.CopyToAsync /// /// /* Only in .NET 5: /// HTTP/3: Http3Connection.SendAsync --> /// Http3Connection.SendWithoutWaitingAsync --> /// Http3RequestStream.SendAsync --> /// Http3RequestStream.SendContentAsync --> /// HttpContent.CopyToAsync /// */ /// } /// /// HttpContent.CopyToAsync --> /// HttpContent.SerializeToStreamAsync (bingo!) /// </code> /// /// Conclusion: by overriding HttpContent.SerializeToStreamAsync, /// we have full control over pumping bytes to the target stream for all protocols /// (except Web Sockets, which is handled separately). /// </remarks> protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) { return SerializeToStreamAsync(stream, context, CancellationToken.None); } #if NET protected override #else private #endif async Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { if (Interlocked.Exchange(ref _started, 1) == 1) { throw new InvalidOperationException("Stream was already consumed."); } // The cancellationToken that is passed to this method is: // On HTTP/1.1: Linked HttpContext.RequestAborted + Request Timeout // On HTTP/2.0: SocketsHttpHandler error / the server wants us to stop sending content / H2 connection closed // _cancellation will be the same as cancellationToken for HTTP/1.1, so we can avoid the overhead of linking them CancellationTokenSource? linkedCts = null; #if NET if (_activityToken.Token != cancellationToken) { Debug.Assert(cancellationToken.CanBeCanceled); linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_activityToken.Token, cancellationToken); cancellationToken = linkedCts.Token; } #else // On .NET Core 3.1, cancellationToken will always be CancellationToken.None Debug.Assert(!cancellationToken.CanBeCanceled); cancellationToken = _activityToken.Token; #endif try { if (_autoFlushHttpClientOutgoingStream) { // HttpClient's machinery keeps an internal buffer that doesn't get flushed to the socket on every write. // Some protocols (e.g. gRPC) may rely on specific bytes being sent, and HttpClient's buffering would prevent it. // AutoFlushingStream delegates to the provided stream, adding calls to FlushAsync on every WriteAsync. // Note that HttpClient does NOT call Flush on the underlying socket, so the perf impact of this is expected to be small. // This statement is based on current knowledge as of .NET Core 3.1.201. stream = new AutoFlushingStream(stream); } // Immediately flush request stream to send headers // https://github.com/dotnet/corefx/issues/39586#issuecomment-516210081 try { await stream.FlushAsync(cancellationToken); } catch (OperationCanceledException oex) { _tcs.TrySetResult((StreamCopyResult.Canceled, oex)); return; } catch (Exception ex) { _tcs.TrySetResult((StreamCopyResult.OutputError, ex)); return; } var (result, error) = await StreamCopier.CopyAsync(isRequest: true, _source, stream, _clock, _activityToken, cancellationToken); _tcs.TrySetResult((result, error)); // Check for errors that weren't the result of the destination failing. // We have to throw something here so the transport knows the body is incomplete. // We can't re-throw the original exception since that would cause concurrency issues. // We need to wrap it. if (result == StreamCopyResult.InputError) { throw new IOException("An error occurred when reading the request body from the client.", error); } if (result == StreamCopyResult.Canceled) { throw new OperationCanceledException("The request body copy was canceled.", error); } } finally { linkedCts?.Dispose(); } } // this is used internally by HttpContent.ReadAsStreamAsync(...) protected override Task<Stream> CreateContentReadStreamAsync() { // Nobody should be calling this... throw new NotImplementedException(); } protected override bool TryComputeLength(out long length) { // We can't know the length of the content being pushed to the output stream. length = -1; return false; } }
42.068182
148
0.656186
[ "MIT" ]
LaudateCorpus1/reverse-proxy
src/ReverseProxy/Forwarder/StreamCopyHttpContent.cs
9,255
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AverageCharacterDelimiter { class Program { static void Main(string[] args) { var arrayOfStrings = Console.ReadLine().Split(' ').ToArray(); var sum = 0; var divider = 0; for (int i = 0; i < arrayOfStrings.Length; i++) { foreach (var item in arrayOfStrings[i]) { sum += item; divider++; } } var character = (sum / divider); var toUpper = Char.ToUpper((char)character); Console.WriteLine(string.Join($"{toUpper}", arrayOfStrings)); } } }
25.709677
73
0.508156
[ "MIT" ]
uagg/SoftwareUniversity
2. Tech Module/Programming Fundamentals/8. Array and list algorithms/Exercise2/AverageCharacterDelimiter/AverageCharacterDelimiter/Program.cs
799
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("Palette Editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Palette Editor")] [assembly: AssemblyCopyright("Copyright © 2018 - 2020")] [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("5ea4522d-b13c-45b1-9bc6-13e29587248a")] // 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("5.461.1091.0")] [assembly: AssemblyFileVersion("5.461.1091.0")]
38.189189
84
0.748054
[ "BSD-3-Clause" ]
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
Source/Krypton Toolkit Suite Extended/Applications/Palette Editor/Properties/AssemblyInfo.cs
1,416
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/MsHTML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DispIHTMLInputButtonElement" /> struct.</summary> public static unsafe partial class DispIHTMLInputButtonElementTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="DispIHTMLInputButtonElement" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(DispIHTMLInputButtonElement).GUID, Is.EqualTo(IID_DispIHTMLInputButtonElement)); } /// <summary>Validates that the <see cref="DispIHTMLInputButtonElement" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DispIHTMLInputButtonElement>(), Is.EqualTo(sizeof(DispIHTMLInputButtonElement))); } /// <summary>Validates that the <see cref="DispIHTMLInputButtonElement" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DispIHTMLInputButtonElement).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DispIHTMLInputButtonElement" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(DispIHTMLInputButtonElement), Is.EqualTo(8)); } else { Assert.That(sizeof(DispIHTMLInputButtonElement), Is.EqualTo(4)); } } } }
39.730769
145
0.661181
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/MsHTML/DispIHTMLInputButtonElementTests.cs
2,068
C#
using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)] namespace Ocelot.Provider.Consul.AcceptanceTests { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Cache; using Configuration.File; using global::Consul; using Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Shouldly; using TestStack.BDDfy; using Xunit; public class ConfigurationInConsulTests : IDisposable { private IWebHost _builder; private readonly Steps _steps; private IWebHost _fakeConsulBuilder; private FileConfiguration _config; private readonly List<ServiceEntry> _consulServices; public ConfigurationInConsulTests() { _consulServices = new List<ServiceEntry>(); _steps = new Steps(); } [Fact] public void should_return_response_200_with_simple_url() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51779, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = 9500 } } }; var fakeConsulServiceDiscoveryUrl = "http://localhost:9500"; this.Given(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:51779", "", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_load_configuration_out_of_consul() { var consulPort = 8500; var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var consulConfig = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51779, } }, UpstreamPathTemplate = "/cs/status", UpstreamHttpMethod = new List<string> {"Get"} } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:51779", "/status", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/cs/status")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } [Fact] public void should_load_configuration_out_of_consul_if_it_is_changed() { var consulPort = 8506; var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var consulConfig = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51780, } }, UpstreamPathTemplate = "/cs/status", UpstreamHttpMethod = new List<string> {"Get"} } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; var secondConsulConfig = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51780, } }, UpstreamPathTemplate = "/cs/status/awesome", UpstreamHttpMethod = new List<string> {"Get"} } }, GlobalConfiguration = new FileGlobalConfiguration() { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() { Host = "localhost", Port = consulPort } } }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:51780", "/status", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/cs/status")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .When(x => GivenTheConsulConfigurationIs(secondConsulConfig)) .Then(x => ThenTheConfigIsUpdatedInOcelot()) .BDDfy(); } [Fact] public void should_handle_request_to_consul_for_downstream_service_and_make_request_no_re_routes_and_rate_limit() { const int consulPort = 8523; const string serviceName = "web"; const int downstreamServicePort = 8187; var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; var serviceEntryOne = new ServiceEntry() { Service = new AgentService() { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", Tags = new[] { "version-v1" } }, }; var consulConfig = new FileConfiguration { DynamicReRoutes = new List<FileDynamicReRoute> { new FileDynamicReRoute { ServiceName = serviceName, RateLimitRule = new FileRateLimitRule() { EnableRateLimiting = true, ClientWhitelist = new List<string>(), Limit = 3, Period = "1s", PeriodTimespan = 1000 } } }, GlobalConfiguration = new FileGlobalConfiguration { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = consulPort }, RateLimitOptions = new FileRateLimitOptions() { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, QuotaExceededMessage = "", RateLimitCounterPrefix = "", HttpStatusCode = 428 }, DownstreamScheme = "http", } }; var configuration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = consulPort } } }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) .And(x => GivenTheConsulConfigurationIs(consulConfig)) .And(x => x.GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, serviceName)) .And(x => x.GivenTheServicesAreRegisteredWithConsul(serviceEntryOne)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 2)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/web/something", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(428)) .BDDfy(); } private void ThenTheConfigIsUpdatedInOcelot() { var result = Wait.WaitFor(20000).Until(() => { try { _steps.WhenIGetUrlOnTheApiGateway("/cs/status/awesome"); _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK); _steps.ThenTheResponseBodyShouldBe("Hello from Laura"); return true; } catch (Exception) { return false; } }); result.ShouldBeTrue(); } private void GivenTheConsulConfigurationIs(FileConfiguration config) { _config = config; } private void GivenTheServicesAreRegisteredWithConsul(params ServiceEntry[] serviceEntries) { foreach (var serviceEntry in serviceEntries) { _consulServices.Add(serviceEntry); } } private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName) { _fakeConsulBuilder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(url) .Configure(app => { app.Run(async context => { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { var json = JsonConvert.SerializeObject(_config); var bytes = Encoding.UTF8.GetBytes(json); var base64 = Convert.ToBase64String(bytes); var kvp = new FakeConsulGetResponse(base64); json = JsonConvert.SerializeObject(new FakeConsulGetResponse[] { kvp }); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); } else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { try { var reader = new StreamReader(context.Request.Body); var json = reader.ReadToEnd(); _config = JsonConvert.DeserializeObject<FileConfiguration>(json); var response = JsonConvert.SerializeObject(true); await context.Response.WriteAsync(response); } catch (Exception e) { Console.WriteLine(e); throw; } } else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { var json = JsonConvert.SerializeObject(_consulServices); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); } }); }) .Build(); _fakeConsulBuilder.Start(); } public class FakeConsulGetResponse { public FakeConsulGetResponse(string value) { Value = value; } public int CreateIndex => 100; public int ModifyIndex => 200; public int LockIndex => 200; public string Key => "InternalConfiguration"; public int Flags => 0; public string Value { get; private set; } public string Session => "adf4238a-882b-9ddc-4a9d-5b6758e4159e"; } private void GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody) { _builder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(url) .Configure(app => { app.UsePathBase(basePath); app.Run(async context => { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); }) .Build(); _builder.Start(); } public void Dispose() { _builder?.Dispose(); _steps.Dispose(); } class FakeCache : IOcelotCache<FileConfiguration> { public void Add(string key, FileConfiguration value, TimeSpan ttl, string region) { throw new NotImplementedException(); } public FileConfiguration Get(string key, string region) { throw new NotImplementedException(); } public void ClearRegion(string region) { throw new NotImplementedException(); } public void AddAndDelete(string key, FileConfiguration value, TimeSpan ttl, string region) { throw new NotImplementedException(); } } } }
40.698947
151
0.464308
[ "MIT" ]
ThreeMammals/Ocelot.Provider.Consul
test/Ocelot.Provider.Consul.AcceptanceTests/ConfigurationInConsulTests.cs
19,334
C#
namespace ILLightenComparer.Variables { internal sealed class Arg { public const int This = 0; public const int Context = 0; public const int X = 1; public const int Y = 2; public const int SetX = 3; public const int SetY = 4; public const int Input = 1; public const int CycleSet = 2; } }
24.466667
38
0.574932
[ "MIT" ]
sgaliamov/ILLightenComparer
src/ILLightenComparer/Variables/Arg.cs
369
C#
using System.Threading.Tasks; using TsinghuaNet.XF.iOS.Services; using TsinghuaNet.XF.Services; using Xamarin.Forms; [assembly: Dependency(typeof(BackgroundManager))] namespace TsinghuaNet.XF.iOS.Services { public class BackgroundManager : IBackgroundManager { public Task<bool> RequestAccessAsync() => Task.FromResult(false); public void RegisterLiveTile(bool reg) { } public void RegisterLogin(bool reg) { } } }
23.947368
73
0.727473
[ "MIT" ]
Berrysoft/TsinghuaNet
TsinghuaNet.XF/TsinghuaNet.XF.iOS/Services/BackgroundManager.cs
457
C#
using System.Collections.Generic; namespace KeyMapSync { public class Table : TableNameInfo { public Table(TableNameInfo nameInfo) { SchemaName = nameInfo.SchemaName; TableName = nameInfo.TableName; } public IEnumerable<string> Columns { get; set; } public SequenceColumn SequenceColumn { get; set; } } }
22.588235
58
0.622396
[ "MIT" ]
mk3008/KeyMapSync
src/KeyMapSync/_database/Table.cs
386
C#
//********************************************************* // // Copyright (c) Microsoft Corporation. All rights reserved. // // // // // // //********************************************************* using System; namespace Bio.IO.SAM { /// <summary> /// This class holds tag persent in the header lines. /// For example, consider the following header line. /// @HD VN:1.0 /// In this example VN:1.0 is the SAMRecordFieldTag. /// Where VN is stored in Tag property and 1.0 is stored /// in the value property of this class. /// </summary> [Serializable] public class SAMRecordFieldTag { /// <summary> /// Creates new SAMRecordFieldTag instance. /// </summary> /// <param name="tag">Record field tag.</param> /// <param name="value">Record field value.</param> public SAMRecordFieldTag(string tag, string value) { Tag = tag; Value = value; } /// <summary> /// Record field tag. /// </summary> public string Tag { get; set; } /// <summary> /// Record field tag. /// </summary> public string Value { get; set; } } }
23.960784
61
0.489362
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
eLMM/CodePlex/MBF/IO/SAM/SAMRecordFieldTag.cs
1,222
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.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines { /// <summary> /// CA2109: Review visible event handlers /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class ReviewVisibleEventHandlersAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2109"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.ReviewVisibleEventHandlersTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.ReviewVisibleEventHandlersMessageDefault), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.ReviewVisibleEventHandlersDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, s_localizableMessageDefault, DiagnosticCategory.Security, RuleLevel.Disabled, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(context => { var eventArgsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); context.RegisterSymbolAction(context => { var method = (IMethodSymbol)context.Symbol; if (!method.IsExternallyVisible()) { return; } if (!method.HasEventHandlerSignature(eventArgsType)) { return; } if (method.IsOverride || method.IsImplementationOfAnyInterfaceMember()) { return; } context.ReportDiagnostic(method.CreateDiagnostic(Rule, method.Name)); }, SymbolKind.Method); }); } } }
48.115942
303
0.697892
[ "Apache-2.0" ]
Atrejoe/roslyn-analyzers
src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/ReviewVisibleEventHandlers.cs
3,320
C#
using System; using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Text; using System.Drawing; using System.Linq; using System.ComponentModel; namespace Pro_Swapper { public partial class swap : Form { private static Items.Item ThisItem { get; set; } public swap(int item) { InitializeComponent(); ThisItem = global.items.Items[item]; BackColor = global.MainMenu; logbox.BackColor = global.MainMenu; ConvertB.ForeColor = global.TextColor; ConvertB.BackColor = global.Button; ConvertB.Activecolor = global.Button; ConvertB.Normalcolor = global.Button; RevertB.ForeColor = global.TextColor; RevertB.BackColor = global.Button; RevertB.Activecolor = global.Button; RevertB.Normalcolor = global.Button; logbox.ForeColor = global.TextColor; if (global.ReadSetting(global.Setting.swaplogs).Contains(ThisItem.SwapsFrom + " To " + ThisItem.SwapsTo + ",")) { label3.ForeColor = Color.Lime; label3.Text = "ON"; } else { label3.ForeColor = Color.Red; label3.Text = "OFF"; if (ThisItem.Note != null) MessageBox.Show("Warning for " + ThisItem.SwapsTo + ": "+ ThisItem.Note, ThisItem.SwapsFrom + " - " + ThisItem.SwapsTo, MessageBoxButtons.OK, MessageBoxIcon.Warning); } string swaptext = ThisItem.SwapsFrom + " --> " + ThisItem.SwapsTo; Text = swaptext; label1.Text = swaptext; image.Image = global.ItemIcon(ThisItem.FromImage); swapsfrom.Image = global.ItemIcon(ThisItem.ToImage); Region = Region.FromHrgn(Main.CreateRoundRectRgn(0, 0, Width, Height, 30, 30)); } private bool Converting { get; set; } private void SwapWork(object sender, DoWorkEventArgs e) { CheckForIllegalCrossThreadCalls = false; try { Stopwatch s = new Stopwatch(); s.Start(); string pakslocation = global.ReadSetting(global.Setting.Paks) + "\\"; foreach (Items.Swap swap in ThisItem.Swaps) { string filepath = pakslocation + swap.File; //Checking if file is readonly coz we wouldn't be able to do shit with it File.SetAttributes(filepath, global.RemoveAttribute(File.GetAttributes(filepath), FileAttributes.ReadOnly)); //Make it support hex as well coz fuck it byte[] searchbyte, replacebyte; if (swap.Search.StartsWith("hex=") && swap.Replace.StartsWith("hex=")) { searchbyte = global.HexToByte(swap.Search.Replace("hex=", "")); replacebyte = global.HexToByte(swap.Replace.Replace("hex=", "")); } else//eww using text but atleast we can read it { searchbyte = Encoding.Default.GetBytes(swap.Search); replacebyte = Encoding.Default.GetBytes(swap.Replace); } //Checks if the ucas file is at right offset byte[] currentfile = global.ReadBytes(filepath, searchbyte.Length, swap.Offset); //Checks to see if the next bytes are the same as api /* bool rightoffset = false; if (currentfile.SequenceEqual(searchbyte)) rightoffset = true; else if (currentfile.SequenceEqual(replacebyte)) rightoffset = true; else rightoffset = false; if (rightoffset == false) { MessageBox.Show("Error! Pro Swapper has not been updated for the most recent update. Please wait for Kye to update it! Join the Discord server for more information. You can also try verifying Fortnite if you were using another swapper or modifying Fortnite beforehand", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }*/ //Decides to either Convert/Revert byte[] towrite = searchbyte; if (Converting) towrite = replacebyte; if (!currentfile.SequenceEqual(towrite))//If already swapped skip coz we don't want the 9yo cpu to blow for unnessary shit ReplaceBytes(filepath, swap.Offset, towrite); } s.Stop(); logbox.Clear(); Log("===="); if (Converting) { Log($"[+] Converted item in {s.Elapsed.TotalMilliseconds}ms"); label3.Text = "ON"; label3.ForeColor = Color.Lime; s.Stop(); global.WriteSetting(global.ReadSetting(global.Setting.swaplogs) + ThisItem.SwapsFrom + " To " + ThisItem.SwapsTo + ",", global.Setting.swaplogs); } else { Log($"[+] Reverted item in {s.Elapsed.TotalMilliseconds}ms"); label3.Text = "OFF"; label3.ForeColor = Color.Red; global.WriteSetting(global.ReadSetting(global.Setting.swaplogs).Replace(ThisItem.SwapsFrom + " To " + ThisItem.SwapsTo + ",", ""), global.Setting.swaplogs); } Log("===="); } catch (Exception ex) { Log($"Restart the swapper or refer to this error: {ex.Message}"); } } private void Log(string text) => logbox.Text += $"{text}{Environment.NewLine}"; private void SwapButton_Click(object sender, EventArgs e) { string path = global.ReadSetting(global.Setting.Paks) + @"\pakchunk0-WindowsClient.sig"; if (!File.Exists(path)) { MessageBox.Show("Select your paks folder in Settings", "Pro Swapper"); return; } logbox.Clear(); Log("Loading..."); if (((Bunifu.Framework.UI.BunifuFlatButton)sender).Text == "Convert") Converting = true; else //Revert Converting = false; using (BackgroundWorker swapbg = new BackgroundWorker()) { swapbg.DoWork += new DoWorkEventHandler(SwapWork); swapbg.RunWorkerAsync(); } } public void ReplaceBytes(string file, long Offset, byte[] towrite) { using (BinaryWriter writer = new BinaryWriter(File.Open(file, FileMode.Open, FileAccess.ReadWrite))) { writer.BaseStream.Seek(Offset, SeekOrigin.Begin); writer.Write(towrite); writer.Close(); } } private void ExitButton_Click(object sender, EventArgs e) => Close(); private void button2_Click(object sender, EventArgs e) => WindowState = FormWindowState.Minimized; private void swap_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) Main.FormMove(Handle); button2.Focus(); } } }
44.088889
351
0.511341
[ "MIT" ]
Antuan005/ProSwapper
src/UI/swap.cs
7,938
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PacketDotNet; namespace MLIDS.UnitTests.lib.ML.Objects { [TestClass] public class PayloadItem { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void PayloadItem_NullTest() { new MLIDS.lib.ML.Objects.PayloadItem(ProtocolType.IPv6NoNextHeader, null, payloadPacket: null, false); } } }
24.888889
114
0.689732
[ "MIT" ]
jcapellman/jcIDS
src/MLIDS.UnitTests/lib/ML/Objects/PayloadItem.cs
450
C#
//----------------------------------------------------------------------------- // (c) 2020 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using Moq; using NUnit.Framework; namespace ExpressionEngine.Tests { [TestFixture] public class DerivateTests { private ExpressionParser _sut; [SetUp] public void Setup() { _sut = new ExpressionParser(); } //Constants [TestCase("3", "0")] [TestCase("99", "0")] [TestCase("360", "0")] //1st order [TestCase("x", "1")] [TestCase("3x", "3")] [TestCase("3x+55", "3")] //2nd order [TestCase("x^2", "(2 * x)")] [TestCase("x^2+3x", "((2 * x) + 3)")] [TestCase("x^2+3x+22", "((2 * x) + 3)")] [TestCase("x^3", "(3 * (x ^ 2))")] //inverse [TestCase("1/x", "(-1 / (x ^ 2))")] //exponent [TestCase("2^x", "(0.6931471805599453 * (2 ^ x))")] //trigonometry [TestCase("sin(x)", "cos(x)")] [TestCase("cos(x)", "(-sin(x))")] [TestCase("tan(x)", "(cos(x) ^ -2)")] [TestCase("ctg(x)", "(-(sin(x) ^ -2))")] //Root [TestCase("root(x,2)", "(0.5 * (x ^ -0.5))")] //Logarithms [TestCase("ln(x)", "(1 / x)")] [TestCase("Log(x, e)", "(1 / x)")] [TestCase("Log(x, 4)", "(0.72134752044448171348 * (1 / x))")] public void TestDerivatives(string expression, string expected) { IExpression derived = _sut.Parse(expression, Mocks.CreateVariableMock()).Differentiate("x").Simplify(); Assert.AreEqual(expected, derived.ToString()); } } }
31.172414
115
0.436947
[ "MIT" ]
webmaster442/ExpressionEngine
ExpressionEngine.Tests/DerivateTests.cs
1,811
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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.ExternalAccess.LiveShare { [ExportLanguageServiceFactory(typeof(ISyntaxFactsService), StringConstants.CSharpLspLanguageName), Shared] internal class CSharpLspSyntaxFactsServiceFactory : ILanguageServiceFactory { public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return languageServices.GetOriginalLanguageService<ISyntaxFactsService>(); } } }
40.842105
161
0.792526
[ "Apache-2.0" ]
GigabyteUB1B1/roslyn
src/Tools/ExternalAccess/LiveShare/LocalForwarders/CSharpRemoteSyntaxFactsService.cs
778
C#
using NHSCovidPassVerifier.Configuration; using NHSCovidPassVerifier.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace NHSCovidPassVerifier.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ApprovePage : ContentPage { public ApprovePage() { InitializeComponent(); BindingContext = IoCContainer.Resolve<ApprovePageViewModel>(); } } }
24.478261
74
0.73357
[ "MIT" ]
0x00null/covid-pass-verifier
NHSCovidPassVerifier/Views/ApprovePage.xaml.cs
565
C#
using Lotech.Data.Descriptors; using Lotech.Data.Operations; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Lotech.Data.SqlServers { class SqlServerExpressionVisitor<TEntity> : SqlExpressionVisitor<TEntity> where TEntity : class { // 函数调用映射 static readonly Dictionary<MethodInfo, Action<SqlExpressionVisitor<TEntity>, MethodCallExpression>> methodCallVisitors = new Dictionary<MethodInfo, Action<SqlExpressionVisitor<TEntity>, MethodCallExpression>> { {Methods.ToUpper, VisitToUpper }, {Methods.ToLower, VisitToLower }, {Methods.StartsWith, VisitStartsWith }, {Methods.EndsWith, VisitEndsWith }, {Methods.Contains, VisitContains }, {Methods.Substring, VisitSubstring }, {Methods.SubstringLength, VisitSubstring2 }, {Methods.IsNullOrEmpty, VisitIsNullOrEmpty }, }; static void VisitIsNullOrEmpty(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.AddFragment("("); visitor.Visit(call.Arguments[0]); visitor.AddFragment(" IS NULL OR '' = "); visitor.Visit(call.Arguments[0]); visitor.AddFragment(")"); } #region Method Visitors static void VisitToUpper(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.AddFragment("UPPER("); visitor.Visit(call.Object); visitor.AddFragment(")"); } static void VisitToLower(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.AddFragment("LOWER("); visitor.Visit(call.Object); visitor.AddFragment(")"); } static void VisitStartsWith(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.Visit(call.Object); visitor.AddFragment(" LIKE "); visitor.Visit(call.Arguments[0]); visitor.AddFragment(" + '%'"); } static void VisitEndsWith(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.Visit(call.Object); visitor.AddFragment(" LIKE '%' + "); visitor.Visit(call.Arguments[0]); } static void VisitContains(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.Visit(call.Object); visitor.AddFragment(" LIKE '%' + "); visitor.Visit(call.Arguments[0]); visitor.AddFragment(" + '%'"); } static void VisitSubstring(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.AddFragment("SUBSTRING("); visitor.Visit(call.Object); visitor.AddFragment(", "); visitor.Visit(call.Arguments[0]); visitor.AddFragment(", 8000)"); } static void VisitSubstring2(SqlExpressionVisitor<TEntity> visitor, MethodCallExpression call) { visitor.AddFragment("SUBSTRING("); visitor.Visit(call.Object); visitor.AddFragment(", "); visitor.Visit(call.Arguments[0]); visitor.AddFragment(", "); visitor.Visit(call.Arguments[1]); visitor.AddFragment(")"); } #endregion public SqlServerExpressionVisitor(IDatabase database, Operation operation) : base(database, operation) { } protected override Expression VisitMethodCall(MethodCallExpression node) { Action<SqlExpressionVisitor<TEntity>, MethodCallExpression> visitor; if (methodCallVisitors.TryGetValue(node.Method, out visitor)) { visitor(this, node); } else if (node.Method.Name == "ToString" && node.Arguments.Count == 0) { if (node.Method.DeclaringType == typeof(string)) // 忽略 string.ToString转换 { Visit(node.Object); } else { AddFragment("CONVERT(NVARCHAR(4000), "); Visit(node.Object); AddFragment(")"); } } else { return base.VisitMethodCall(node); } return null; } } }
38.208333
120
0.579935
[ "MIT" ]
cnsicau/Lotech.Data.Core
Lotech.Data/SqlServers/SqlServerExpressionVisitor.cs
4,607
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2021 Ingo Herbote * https://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * 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. */ namespace YAF.Types.Models.Identity { using System; using Microsoft.AspNet.Identity; using ServiceStack.DataAnnotations; using ServiceStack.Model; using YAF.Types.Interfaces.Data; /// <summary> /// The asp net roles. /// </summary> public class AspNetRoles : AspNetRoles<string> { /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles"/> class. /// </summary> public AspNetRoles() { this.Id = Guid.NewGuid().ToString(); } /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles"/> class. /// </summary> /// <param name="name"> /// The name. /// </param> public AspNetRoles(string name) : base(Guid.NewGuid().ToString(), name) { } /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles"/> class. /// </summary> /// <param name="id"> /// The id. /// </param> /// <param name="name"> /// The name. /// </param> public AspNetRoles(string id, string name) : base(id, name) { } } /// <summary> /// The asp net roles. /// </summary> /// <typeparam name="TKey"> /// </typeparam> public class AspNetRoles<TKey> : IRole<TKey>, IEntity, IHasId<TKey> { /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles{TKey}"/> class. /// Default constructor for Role /// </summary> public AspNetRoles() { } /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles{TKey}"/> class. /// Constructor that takes names as argument /// </summary> /// <param name="name"> /// The name. /// </param> public AspNetRoles(string name) : this() { this.Name = name; } /// <summary> /// Initializes a new instance of the <see cref="AspNetRoles{TKey}"/> class. /// </summary> /// <param name="id"> /// The id. /// </param> /// <param name="name"> /// The name. /// </param> public AspNetRoles(TKey id, string name) : this(name) { this.Id = id; } /// <summary> /// Gets or sets the Role ID /// </summary> [StringLength(56)] public TKey Id { get; set; } /// <summary> /// Gets or sets the Role name /// </summary> [StringLength(50)] [Index(Unique = true)] [Required] public string Name { get; set; } } }
29.469697
86
0.534447
[ "Apache-2.0" ]
10by10pixel/YAFNET
yafsrc/YAF.Types/Models/Identity/AspNetRoles.cs
3,762
C#
using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using System; using System.Threading; using System.Threading.Tasks; using WingtipToys.Domain.Exceptions; using WingtipToys.Domain.Interfaces; using WingtipToys.Domain.Models; using Xunit; namespace WingtipToys.Data.Tests { public class ProductRepositoryTests : IDisposable { private SqliteConnection _connection; private WingtiptoysContext _context; public ProductRepositoryTests() { _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); var options = new DbContextOptionsBuilder<WingtiptoysContext>() .UseSqlite(_connection) .Options; _context = new WingtiptoysContext(options); _context.Database.EnsureCreated(); _context.Categories.Add(new Category() { CategoryId = 1, CategoryName = "N1", Description = "D" }); _context.Categories.Add(new Category() { CategoryId = 2, CategoryName = "N2", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 1, ProductName = "ProductName1", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 1, ProductName = "ProductName2", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 1, ProductName = "ProductName3", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 1, ProductName = "ProductName4", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 1, ProductName = "ProductName5", Description = "D" }); _context.Products.Add(new Product() { CategoryId = 2, ProductName = "ProductName6", Description = "D" }); _context.SaveChanges(); } public void Dispose() { _context.Dispose(); _connection.Dispose(); } [Theory] [InlineData(1, 1, 1, 5, 5, 1)] [InlineData(1, 5, 1, 5, 5, 1)] [InlineData(1, 3, 2, 5, 3, 1)] [InlineData(2, 1, 1, 1, 1, 1)] [InlineData(3, 1, 1, 0, 0, 0)] public async Task GetProductsForCategoryAsync_PositiveTests(int categoryID, int pageNo, int pageSize, int expectedTotalCount, int expectedTotalPages, int expectedItemCount) { CancellationToken cancellationToken = default(CancellationToken); var repo = new ProductRepository(_context); IPageResult<Product> result = await repo.GetProductsForCategoryAsync(categoryID, pageNo, pageSize, cancellationToken); Assert.True(result.PageSize == pageSize); Assert.True(result.PageNo == pageNo); Assert.True(result.TotalCount == expectedTotalCount); Assert.True(result.TotalPages == expectedTotalPages); Assert.True(result.Items.Count == expectedItemCount); } [Theory] [InlineData(1, -1, 1, typeof(DomainException))] [InlineData(1, 1, -1, typeof(DomainException))] [InlineData(1, 6, 1, typeof(DomainException))] public async Task GetProductsForCategoryAsync_NegativeTests(int categoryID, int pageNo, int pageSize, Type exceptionType) { CancellationToken cancellationToken = default(CancellationToken); var repo = new ProductRepository(_context); await Assert.ThrowsAsync(exceptionType,() => { return repo.GetProductsForCategoryAsync(categoryID, pageNo, pageSize, cancellationToken); }); } } }
42.583333
180
0.639922
[ "MIT" ]
vaibhav-goyal/wingtip-toys
tests/WingtipToys.Data.Tests/ProductRepositoryTests.cs
3,577
C#
// // Unit tests for DoNotUseLockedRegionOutsideMethodRule // // Authors: // Andres G. Aragoneses <aaragoneses@novell.com> // // Copyright (C) 2008 Andres G. Aragoneses // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Gendarme.Rules.Concurrency; using NUnit.Framework; using Test.Rules.Definitions; using Test.Rules.Fixtures; namespace Test.Rules.Concurrency { [TestFixture] public class DoNotUseLockedRegionOutsideMethodTest : MethodRuleTestFixture<DoNotUseLockedRegionOutsideMethodRule> { [Test] public void DoesNotApply () { // no IL for p/invokes AssertRuleDoesNotApply (SimpleMethods.ExternalMethod); // no calls[virt] AssertRuleDoesNotApply (SimpleMethods.EmptyMethod); } public class Monitors { private Monitors () { } public static void WithLockStatement () { lock ( new object () ) { // do something... WithLockStatement (); } } public static void WithoutConcurrency () { // do something... WithoutConcurrency (); } public static void WithoutThreadExit () { // do something... WithoutThreadExit (); System.Threading.Monitor.Enter ( new object () ); // do something... WithoutThreadExit (); } public static void TwoEnterOneExit () { lock (new object ()) { System.Threading.Monitor.Enter (new object ()); } } } [Test] public void Check () { AssertRuleSuccess<Monitors> ("WithLockStatement"); AssertRuleSuccess<Monitors> ("WithoutConcurrency"); AssertRuleFailure<Monitors> ("WithoutThreadExit"); AssertRuleFailure<Monitors> ("TwoEnterOneExit"); } } }
27.770833
116
0.712678
[ "MIT" ]
JAD-SVK/Gendarme
rules/Gendarme.Rules.Concurrency/Test/DoNotUseLockedRegionOutsideMethodTest.cs
2,666
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace System.Windows { /// <summary> /// Provides loosely-coupled messaging between various colleague objects. All references to objects are stored weakly, to prevent memory leaks. /// 提供松散耦合的消息通知机制,为防止内存泄漏,所有对象都使用了弱引用(WeakReference) /// </summary> public class Messenger { #region Constructor public Messenger() { } #endregion // Constructor #region Register /// <summary> /// Registers a callback method, with no parameter, to be invoked when a specific message is broadcasted. /// 注册消息监听 /// </summary> /// <param name="message">The message to register for.</param> /// <param name="callback">The callback to be called when this message is broadcasted.</param> public void Register(string message, Action callback) { this.Register(message, callback, null); } /// <summary> /// Registers a callback method, with a parameter, to be invoked when a specific message is broadcasted. /// 注册消息监听 /// </summary> /// <param name="message">The message to register for.</param> /// <param name="callback">The callback to be called when this message is broadcasted.</param> public void Register<T>(string message, Action<T> callback) { this.Register(message, callback, typeof(T)); } void Register(string message, Delegate callback, Type parameterType) { if (String.IsNullOrEmpty(message)) throw new ArgumentException("'message' cannot be null or empty."); if (callback == null) throw new ArgumentNullException("callback"); this.VerifyParameterType(message, parameterType); _messageToActionsMap.AddAction(message, callback.Target, callback.Method, parameterType); } [Conditional("DEBUG")] void VerifyParameterType(string message, Type parameterType) { Type previouslyRegisteredParameterType = null; if (_messageToActionsMap.TryGetParameterType(message, out previouslyRegisteredParameterType)) { if (previouslyRegisteredParameterType != null && parameterType != null) { if (!previouslyRegisteredParameterType.Equals(parameterType)) throw new InvalidOperationException(string.Format( "The registered action's parameter type is inconsistent with the previously registered actions for message '{0}'.\nExpected: {1}\nAdding: {2}", message, previouslyRegisteredParameterType.FullName, parameterType.FullName)); } else { // One, or both, of previouslyRegisteredParameterType or callbackParameterType are null. if (previouslyRegisteredParameterType != parameterType) // not both null? { throw new TargetParameterCountException(string.Format( "The registered action has a number of parameters inconsistent with the previously registered actions for message \"{0}\".\nExpected: {1}\nAdding: {2}", message, previouslyRegisteredParameterType == null ? 0 : 1, parameterType == null ? 0 : 1)); } } } } #endregion // Register #region Notify /// <summary> /// Notifies all registered parties that a message is being broadcasted. /// 发送消息通知,触发监听执行 /// </summary> /// <param name="message">The message to broadcast.</param> /// <param name="parameter">The parameter to pass together with the message.</param> public void Notify(string message, object parameter) { if (String.IsNullOrEmpty(message)) throw new ArgumentException("'message' cannot be null or empty."); Type registeredParameterType; if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType)) { if (registeredParameterType == null) throw new TargetParameterCountException(string.Format("Cannot pass a parameter with message '{0}'. Registered action(s) expect no parameter.", message)); } var actions = _messageToActionsMap.GetActions(message); if (actions != null) actions.ForEach(action => action.DynamicInvoke(parameter)); } /// <summary> /// Notifies all registered parties that a message is being broadcasted. /// 发送消息通知,触发监听执行 /// </summary> /// <param name="message">The message to broadcast.</param> public void Notify(string message) { if (String.IsNullOrEmpty(message)) throw new ArgumentException("'message' cannot be null or empty."); Type registeredParameterType; if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType)) { if (registeredParameterType != null) throw new TargetParameterCountException(string.Format("Must pass a parameter of type {0} with this message. Registered action(s) expect it.", registeredParameterType.FullName)); } var actions = _messageToActionsMap.GetActions(message); if (actions != null) actions.ForEach(action => action.DynamicInvoke()); } #endregion // NotifyColleauges #region MessageToActionsMap [nested class] /// <summary> /// This class is an implementation detail of the Messenger class. /// </summary> private class MessageToActionsMap { #region Constructor internal MessageToActionsMap() { } #endregion // Constructor #region AddAction /// <summary> /// Adds an action to the list. /// </summary> /// <param name="message">The message to register.</param> /// <param name="target">The target object to invoke, or null.</param> /// <param name="method">The method to invoke.</param> /// <param name="actionType">The type of the Action delegate.</param> internal void AddAction(string message, object target, MethodInfo method, Type actionType) { if (message == null) throw new ArgumentNullException("message"); if (method == null) throw new ArgumentNullException("method"); lock (_map) { if (!_map.ContainsKey(message)) _map[message] = new List<WeakAction>(); _map[message].Add(new WeakAction(target, method, actionType)); } } #endregion // AddAction #region GetActions /// <summary> /// Gets the list of actions to be invoked for the specified message /// </summary> /// <param name="message">The message to get the actions for</param> /// <returns>Returns a list of actions that are registered to the specified message</returns> internal List<Delegate> GetActions(string message) { if (message == null) throw new ArgumentNullException("message"); List<Delegate> actions; lock (_map) { if (!_map.ContainsKey(message)) return null; List<WeakAction> weakActions = _map[message]; actions = new List<Delegate>(weakActions.Count); for (int i = weakActions.Count - 1; i > -1; --i) { WeakAction weakAction = weakActions[i]; if (weakAction == null) continue; Delegate action = weakAction.CreateAction(); if (action != null) { actions.Add(action); } else { // The target object is dead, so get rid of the weak action. weakActions.Remove(weakAction); } } // Delete the list from the map if it is now empty. if (weakActions.Count == 0) _map.Remove(message); } // Reverse the list to ensure the callbacks are invoked in the order they were registered. actions.Reverse(); return actions; } #endregion // GetActions #region TryGetParameterType /// <summary> /// Get the parameter type of the actions registered for the specified message. /// </summary> /// <param name="message">The message to check for actions.</param> /// <param name="parameterType"> /// When this method returns, contains the type for parameters /// for the registered actions associated with the specified message, if any; otherwise, null. /// This will also be null if the registered actions have no parameters. /// This parameter is passed uninitialized. /// </param> /// <returns>true if any actions were registered for the message</returns> internal bool TryGetParameterType(string message, out Type parameterType) { if (message == null) throw new ArgumentNullException("message"); parameterType = null; List<WeakAction> weakActions; lock (_map) { if (!_map.TryGetValue(message, out weakActions) || weakActions.Count == 0) return false; } parameterType = weakActions[0].ParameterType; return true; } #endregion // TryGetParameterType #region Fields // Stores a hash where the key is the message and the value is the list of callbacks to invoke. readonly Dictionary<string, List<WeakAction>> _map = new Dictionary<string, List<WeakAction>>(); #endregion // Fields } #endregion // MessageToActionsMap [nested class] #region WeakAction [nested class] /// <summary> /// This class is an implementation detail of the MessageToActionsMap class. /// </summary> private class WeakAction { #region Constructor /// <summary> /// Constructs a WeakAction. /// </summary> /// <param name="target">The object on which the target method is invoked, or null if the method is static.</param> /// <param name="method">The MethodInfo used to create the Action.</param> /// <param name="parameterType">The type of parameter to be passed to the action. Pass null if there is no parameter.</param> internal WeakAction(object target, MethodInfo method, Type parameterType) { if (target == null) { _targetRef = null; } else { _targetRef = new WeakReference(target); } _method = method; this.ParameterType = parameterType; if (parameterType == null) { _delegateType = typeof(Action); } else { _delegateType = typeof(Action<>).MakeGenericType(parameterType); } } #endregion // Constructor #region CreateAction /// <summary> /// Creates a "throw away" delegate to invoke the method on the target, or null if the target object is dead. /// </summary> internal Delegate CreateAction() { // Rehydrate into a real Action object, so that the method can be invoked. if (_targetRef == null) { return Delegate.CreateDelegate(_delegateType, _method); } else { try { object target = _targetRef.Target; if (target != null) return Delegate.CreateDelegate(_delegateType, target, _method); } catch { } } return null; } #endregion // CreateAction #region Fields internal readonly Type ParameterType; readonly Type _delegateType; readonly MethodInfo _method; readonly WeakReference _targetRef; #endregion // Fields } #endregion // WeakAction [nested class] #region Fields readonly MessageToActionsMap _messageToActionsMap = new MessageToActionsMap(); #endregion // Fields } }
37.948087
197
0.532508
[ "Apache-2.0" ]
Egoily/iLawyer
01.Framework/Util.Controls/{Core}/Messenger.cs
14,037
C#
using System.Reflection; using System.Runtime.CompilerServices; using Android.App; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ButtonClicker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("${AuthorCopyright}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
36.285714
82
0.746063
[ "Apache-2.0" ]
Reiss-Cashmore/xamarin-basic-sample
ButtonClicker/ButtonClicker/Properties/AssemblyInfo.cs
1,018
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController controller; public float speed = 12f; public float gravity = -9.81f; public float jumpHeight = 3f; public Transform groundCheck; public float groundDistance = .4f; public LayerMask groundMask; Vector3 velocity; bool isGrounded; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if(isGrounded && velocity.y < 0) { velocity.y = -2f; } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; controller.Move(move * speed * Time.deltaTime); if(Input.GetButtonDown("Jump") && isGrounded ) { velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity); } velocity.y += gravity * Time.deltaTime; controller.Move(velocity); } }
22.90566
91
0.620264
[ "MIT" ]
NCSUVGDC/PumpkinAction
PumpkinAction/Assets/Scripts/PlayerMovement.cs
1,216
C#
// <copyright file="IdentityProviderCredentialsClient.Generated.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> // This file was automatically generated. Don't modify it directly. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Okta.Sdk.Internal; namespace Okta.Sdk { /// <inheritdoc/> public sealed partial class IdentityProviderCredentialsClient : Resource, IIdentityProviderCredentialsClient { /// <inheritdoc/> public string ClientId { get => GetStringProperty("client_id"); set => this["client_id"] = value; } /// <inheritdoc/> public string ClientSecret { get => GetStringProperty("client_secret"); set => this["client_secret"] = value; } } }
29.428571
112
0.649515
[ "Apache-2.0" ]
Christian-Oleson/okta-sdk-dotnet
src/Okta.Sdk/Generated/IdentityProviderCredentialsClient.Generated.cs
1,030
C#