content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CognitoIdentity")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Cognito Identity. Amazon Cognito is a service that makes it easy to save user data, such as app preferences or game state, in the AWS Cloud without writing any backend code or managing any infrastructure. With Amazon Cognito, you can focus on creating great app experiences instead of having to worry about building and managing a backend solution to handle identity management, network state, storage, and sync.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.0.28")] | 55.25 | 499 | 0.761312 | [
"Apache-2.0"
] | augustoproiete-forks/aws--aws-sdk-net | sdk/code-analysis/ServiceAnalysis/CognitoIdentity/Properties/AssemblyInfo.cs | 1,768 | C# |
namespace AutoUI
{
partial class EnvironmentEditor
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EnvironmentEditor));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.addTestToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panel1 = new System.Windows.Forms.Panel();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.tableLayoutPanel1.SuspendLayout();
this.contextMenuStrip1.SuspendLayout();
this.statusStrip1.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.listView1, 0, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 25);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(800, 403);
this.tableLayoutPanel1.TabIndex = 0;
//
// listView1
//
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.tableLayoutPanel1.SetColumnSpan(this.listView1, 2);
this.listView1.ContextMenuStrip = this.contextMenuStrip1;
this.listView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.HideSelection = false;
this.listView1.Location = new System.Drawing.Point(3, 204);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(794, 196);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listView1_MouseDoubleClick);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.addTestToolStripMenuItem,
this.deleteToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(117, 48);
//
// addTestToolStripMenuItem
//
this.addTestToolStripMenuItem.Name = "addTestToolStripMenuItem";
this.addTestToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.addTestToolStripMenuItem.Text = "add test";
this.addTestToolStripMenuItem.Click += new System.EventHandler(this.addTestToolStripMenuItem_Click);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
this.deleteToolStripMenuItem.Text = "delete";
//
// panel1
//
this.tableLayoutPanel1.SetColumnSpan(this.panel1, 2);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(3, 3);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(794, 195);
this.panel1.TabIndex = 1;
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel1});
this.statusStrip1.Location = new System.Drawing.Point(0, 428);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(800, 22);
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(118, 17);
this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton1});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(800, 25);
this.toolStrip1.TabIndex = 2;
this.toolStrip1.Text = "toolStrip1";
this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked);
//
// toolStripButton1
//
this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(29, 22);
this.toolStripButton1.Text = "run";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// EnvironmentEditor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.toolStrip1);
this.Name = "EnvironmentEditor";
this.Text = "Test set editor";
this.tableLayoutPanel1.ResumeLayout(false);
this.contextMenuStrip1.ResumeLayout(false);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem addTestToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton toolStripButton1;
}
} | 52.526042 | 149 | 0.642043 | [
"MIT"
] | fel88/AutoUI | AutoUI/EnvironmentEditor.Designer.cs | 10,087 | C# |
// Copyright (c) 2021 ICT Cube, doWhile, and Eiffel Community collaborators.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using EiffelEvents.Net.Events.Core;
using EiffelEvents.Net.Events.Edition_Lyon.Shared;
namespace EiffelEvents.Net.Events.Edition_Lyon
{
/// <summary>
/// The <a href="https://github.com/eiffel-community/eiffel/blob/edition-lyon/eiffel-vocabulary/EiffelTestCaseStartedEvent.md">
/// EiffelTestCaseStartedEvent
/// </a> declares that the execution of a test case has commenced. This event SHALL be
/// preceded by a EiffelTestCaseTriggeredEvent, and appropriately linked to via TEST_CASE_EXECUTION.
/// </summary>
public record EiffelTestCaseStartedEvent :
EiffelEvent<EiffelTestCaseStartedData, EiffelTestCaseStartedMeta, EiffelTestCaseStartedLinks>
{
/// <inheritdoc/>
public override EiffelTestCaseStartedData Data { get; init; } = new();
/// <inheritdoc/>
public override EiffelTestCaseStartedMeta Meta { get; init; } = new();
/// <inheritdoc/>
public override EiffelTestCaseStartedLinks Links { get; init; } = new();
/// <inheritdoc/>
public override IEiffelEvent FromJson(string json)
{
return Deserialize<EiffelTestCaseStartedEvent>(json);
}
}
} | 42.636364 | 131 | 0.692431 | [
"Apache-2.0"
] | eiffel-community/eiffelevents-sdk-dotnet | src/EiffelEvents.Net/Events/Edition-Lyon/EiffelTestCaseStartedEvent/EiffelTestCaseStartedEvent.cs | 1,878 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace FullContact.Infrastructure
{
public class FullcontactPersonService : BasePersonService, IPersonService
{
private readonly HttpClient _httpClient;
public FullcontactPersonService(string name, string baseUrl, string apiKey = null)
: base(name, baseUrl, apiKey)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
_httpClient.BaseAddress = new Uri(baseUrl);
}
public override async Task<IPersonResponse> Get(string identifier)
{
identifier = identifier ?? throw new ArgumentNullException(nameof(identifier));
var endpointUrl = "/v3/person.enrich";
var values = new Dictionary<string, string>
{
{ GetIdentifier(), identifier}
};
var json = JsonConvert.SerializeObject(values);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(endpointUrl, content);
if (!response.IsSuccessStatusCode)
{
//todo throw matching error
throw new HttpRequestException("the person not found");
}
var personJson = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<FullContactPersonResponse>(personJson);
}
public string GetIdentifier()
{
return "email";
}
}
}
| 35.14 | 110 | 0.63745 | [
"MIT"
] | mottibec/FullContact | FullContact.Infrastructure/PersonServices/FullContact/FullcontactPersonService.cs | 1,759 | C# |
/*
Copyright (C) 2020 Jean-Camille Tournier (mail@tournierjc.fr)
This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore
QLCore is free software: you can redistribute it and/or modify it
under the terms of the QLCore and QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at https://github.com/OpenDerivatives/QLCore/LICENSE.
QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source
library for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml and the
QLNet license is available online at https://github.com/amaggiulli/QLNet/blob/develop/LICENSE.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICAR PURPOSE. See the license for more details.
*/
using System;
using System.Collections.Generic;
namespace QLCore
{
// exchange-rate repository
// test lookup of direct, triangulated, and derived exchange rates is tested
public class ExchangeRateManager : Singleton<ExchangeRateManager>
{
public ExchangeRateManager()
{
addKnownRates();
}
private Dictionary<int, List<Entry>> data_ = new Dictionary<int, List<Entry>>();
public class Entry
{
public Entry(ExchangeRate r, Date s, Date e)
{
rate = r;
startDate = s;
endDate = e;
}
public ExchangeRate rate { get; set; }
public Date startDate { get; set; }
public Date endDate { get; set; }
}
private void addKnownRates()
{
// currencies obsoleted by Euro
add
(new ExchangeRate(new EURCurrency(), new ATSCurrency(), 13.7603), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new BEFCurrency(), 40.3399), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new DEMCurrency(), 1.95583), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new ESPCurrency(), 166.386), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new FIMCurrency(), 5.94573), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new FRFCurrency(), 6.55957), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new GRDCurrency(), 340.750), new Date(1, Month.January, 2001), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new IEPCurrency(), 0.787564), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new ITLCurrency(), 1936.27), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new LUFCurrency(), 40.3399), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new NLGCurrency(), 2.20371), new Date(1, Month.January, 1999), Date.maxDate());
add
(new ExchangeRate(new EURCurrency(), new PTECurrency(), 200.482), new Date(1, Month.January, 1999), Date.maxDate());
// other obsoleted currencies
add
(new ExchangeRate(new TRYCurrency(), new TRLCurrency(), 1000000.0), new Date(1, Month.January, 2005), Date.maxDate());
add
(new ExchangeRate(new RONCurrency(), new ROLCurrency(), 10000.0), new Date(1, Month.July, 2005), Date.maxDate());
add
(new ExchangeRate(new PENCurrency(), new PEICurrency(), 1000000.0), new Date(1, Month.July, 1991), Date.maxDate());
add
(new ExchangeRate(new PEICurrency(), new PEHCurrency(), 1000.0), new Date(1, Month.February, 1985), Date.maxDate());
}
public void add
(ExchangeRate rate)
{
add
(rate, Date.minDate(), Date.maxDate());
}
public void add
(ExchangeRate rate, Date startDate)
{
add
(rate, startDate, Date.maxDate());
}
// Add an exchange rate.
// The given rate is valid between the given dates.
// If two rates are given between the same currencies
// and with overlapping date ranges, the latest one
// added takes precedence during lookup.
private void add
(ExchangeRate rate, Date startDate, Date endDate)
{
int k = hash(rate.source, rate.target);
if (data_.ContainsKey(k))
{
data_[k].Insert(0, new Entry(rate, startDate, endDate));
}
else
{
data_[k] = new List<Entry>();
data_[k].Add(new Entry(rate, startDate, endDate));
}
}
private int hash(Currency c1, Currency c2)
{
return Math.Min(c1.numericCode, c2.numericCode) * 1000
+ Math.Max(c1.numericCode, c2.numericCode);
}
private bool hashes(int k, Currency c)
{
if (c.numericCode == k % 1000 ||
c.numericCode == k / 1000)
return true;
return false;
}
public ExchangeRate lookup(Currency source, Currency target)
{
return lookup(source, target, new Date(), ExchangeRate.Type.Derived);
}
public ExchangeRate lookup(Currency source, Currency target, Date date)
{
return lookup(source, target, date, ExchangeRate.Type.Derived);
}
// Lookup the exchange rate between two currencies at a given
// date. If the given type is Direct, only direct exchange
// rates will be returned if available; if Derived, direct
// rates are still preferred but derived rates are allowed.
// if two or more exchange-rate chains are possible
// which allow to specify a requested rate, it is
// unspecified which one is returned.
public ExchangeRate lookup(Currency source, Currency target, Date date, ExchangeRate.Type type)
{
if (source == target)
return new ExchangeRate(source, target, 1.0);
if (date == new Date())
date = Settings.Instance.evaluationDate();
if (type == ExchangeRate.Type.Direct)
{
return directLookup(source, target, date);
}
if (!source.triangulationCurrency.empty())
{
Currency link = source.triangulationCurrency;
if (link == target)
return directLookup(source, link, date);
return ExchangeRate.chain(directLookup(source, link, date), lookup(link, target, date));
}
if (!target.triangulationCurrency.empty())
{
Currency link = target.triangulationCurrency;
if (source == link)
return directLookup(link, target, date);
return ExchangeRate.chain(lookup(source, link, date), directLookup(link, target, date));
}
return smartLookup(source, target, date);
}
private ExchangeRate directLookup(Currency source, Currency target, Date date)
{
ExchangeRate rate = fetch(source, target, date);
if (rate.rate.IsNotEqual(0.0))
return rate;
Utils.QL_FAIL("no direct conversion available from " + source.code + " to " + target.code + " for " + date);
return null;
}
private ExchangeRate smartLookup(Currency source, Currency target, Date date)
{
return smartLookup(source, target, date, new List<int>());
}
private ExchangeRate smartLookup(Currency source, Currency target, Date date, List<int> forbidden)
{
// direct exchange rates are preferred.
ExchangeRate direct = fetch(source, target, date);
if (direct.HasValue)
return direct;
// if none is found, turn to smart lookup. The source currency
// is forbidden to subsequent lookups in order to avoid cycles.
forbidden.Add(source.numericCode);
foreach (KeyValuePair<int, List<Entry>> i in data_)
{
// we look for exchange-rate data which involve our source
// currency...
if (hashes(i.Key, source) && (i.Value.Count != 0))
{
// ...whose other currency is not forbidden...
Entry e = i.Value[0];
Currency other = source == e.rate.source ? e.rate.target : e.rate.source;
if (!forbidden.Contains(other.numericCode))
{
// ...and which carries information for the requested date.
ExchangeRate head = fetch(source, other, date);
if (((double?) head.rate).HasValue)
{
// if we can get to the target from here...
try
{
ExchangeRate tail = smartLookup(other, target, date, forbidden);
// ..we're done.
return ExchangeRate.chain(head, tail);
}
catch (Exception)
{
// otherwise, we just discard this rate.
}
}
}
}
}
// if the loop completed, we have no way to return the requested rate.
Utils.QL_FAIL("no conversion available from " + source.code + " to " + target.code + " for " + date);
return null;
}
private ExchangeRate fetch(Currency source, Currency target, Date date)
{
if (data_.ContainsKey(hash(source, target)))
{
List<Entry> rates = data_[hash(source, target)];
foreach (Entry e in rates)
{
if (date >= e.startDate && date <= e.endDate)
return e.rate;
}
}
return new ExchangeRate();
}
// remove the added exchange rates
public void clear()
{
data_.Clear();
addKnownRates();
}
}
}
| 39.014981 | 130 | 0.585581 | [
"BSD-3-Clause"
] | tournierjc/QLCore | QLCore/Currencies/ExchangeRateManager.cs | 10,417 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Anvil.API;
using Anvil.Tests.Resources;
using NUnit.Framework;
// ReSharper disable UnusedMember.Local
namespace Anvil.Tests.API
{
[TestFixture(Category = "API.Variable")]
public sealed class LocalVariableTests
{
private readonly List<NwGameObject> createdTestObjects = new List<NwGameObject>();
[Test(Description = "Getting a non-existing variable on an object returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetMissingLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature);
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "string"));
}
[Test(Description = "Setting/getting a variable on an object returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetValidLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature);
creature.GetObjectVariable<LocalVariableBool>(variableName + "bool").Value = true;
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Value = ValidEnum.TestA;
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Value = 999f;
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Value = Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f");
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Value = 506;
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Value = "test_string";
ExampleSerializable serializable = new ExampleSerializable
{
Value = 1,
Value2 = "test",
};
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Value = serializable;
VariableAssert(true, true, creature.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(true, ValidEnum.TestA, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(true, 999f, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(true, Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f"), creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(true, 506, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(true, "test_string", creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(true, serializable, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct"));
}
[Test(Description = "Setting a variable on an object and deleting it returns a variable object with the correct properties.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void DeleteLocalVariablePropertiesValid(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature);
creature.GetObjectVariable<LocalVariableBool>(variableName + "bool").Value = true;
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Value = ValidEnum.TestA;
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Value = 999f;
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Value = Guid.Parse("81a130d2-502f-4cf1-a376-63edeb000e9f");
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Value = 506;
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Value = "test_string";
ExampleSerializable serializable = new ExampleSerializable
{
Value = 1,
Value2 = "test",
};
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Value = serializable;
creature.GetObjectVariable<LocalVariableBool>(variableName + "bool").Delete();
creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum").Delete();
creature.GetObjectVariable<LocalVariableFloat>(variableName + "float").Delete();
creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid").Delete();
creature.GetObjectVariable<LocalVariableInt>(variableName + "int").Delete();
creature.GetObjectVariable<LocalVariableString>(variableName + "string").Delete();
creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct").Delete();
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableBool>(variableName + "bool"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableEnum<ValidEnum>>(variableName + "enum"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableFloat>(variableName + "float"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableGuid>(variableName + "guid"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableInt>(variableName + "int"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableString>(variableName + "string"));
VariableAssert(false, default, creature.GetObjectVariable<LocalVariableStruct<ExampleSerializable>>(variableName + "struct"));
}
[Test(Description = "Attempting to create an object enum variable with an incorrect size throws an exception.")]
[TestCase("aaabbb")]
[TestCase("123")]
[TestCase(",;'.-2=,'\"")]
[TestCase("__\n")]
public void GetInvalidEnumVariableThrowsException(string variableName)
{
Location startLocation = NwModule.Instance.StartingLocation;
NwCreature creature = NwCreature.Create(StandardResRef.Creature.nw_bandit001, startLocation);
Assert.That(creature, Is.Not.Null);
createdTestObjects.Add(creature);
Assert.That(() =>
{
creature.GetObjectVariable<LocalVariableEnum<InvalidEnumA>>(variableName + "enum").Value = InvalidEnumA.TestA;
}, Throws.TypeOf<TargetInvocationException>());
Assert.That(() =>
{
creature.GetObjectVariable<LocalVariableEnum<InvalidEnumB>>(variableName + "enum").Value = InvalidEnumB.TestB;
}, Throws.TypeOf<TargetInvocationException>());
}
private void VariableAssert<T>(bool expectHasValue, T expectedValue, ObjectVariable<T> variable)
{
Assert.That(variable, Is.Not.Null, "Created variable was null.");
if (expectHasValue)
{
Assert.That(variable.HasValue, Is.True, "Expected variable to have value, but HasValue returned false.");
Assert.That(variable.HasNothing, Is.False, "Expected variable to have value, but HasNothing returned true.");
}
else
{
Assert.That(variable.HasNothing, Is.True, "Expected variable to have no value, but HasNothing returned false.");
Assert.That(variable.HasValue, Is.False, "Expected variable to have no value, but HasValue returned true.");
}
Assert.That(expectedValue, Is.EqualTo(variable.Value));
}
private enum ValidEnum
{
Default = 0,
TestA = 1,
TestB = 2,
}
private enum InvalidEnumA : long
{
Default = 0,
TestA = 1,
TestB = 2,
}
private enum InvalidEnumB : byte
{
Default = 0,
TestA = 1,
TestB = 2,
}
[Serializable]
private record ExampleSerializable
{
public int Value { get; set; }
public string Value2 { get; set; }
}
[TearDown]
public void CleanupTestObject()
{
foreach (NwGameObject testObject in createdTestObjects)
{
testObject.PlotFlag = false;
testObject.Destroy();
}
createdTestObjects.Clear();
}
}
}
| 46.889447 | 149 | 0.721037 | [
"MIT"
] | Aschent89/Anvil | NWN.Anvil.Tests/src/main/API/Variable/LocalVariableTests.cs | 9,331 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由T4模板自动生成
// 生成时间 2019-10-08 14:34:31
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失
// 作者:Harbour CTS
// </auto-generated>
//------------------------------------------------------------------------------
using ZXYL.Model;
using ZXYL.DAL;
namespace ZXYL.BLL
{
public partial class V_PubUser_DeptBLL:BaseServiceDapperContrib<Model.V_PubUser_Dept>
{
}
}
| 20.75 | 86 | 0.449799 | [
"MIT"
] | zxtname/ZXYl | ZXYL.BLL/T4.DapperExt/V_PubUser_DeptBLL.cs | 608 | C# |
using NextGenSoftware.OASIS.API.Providers.SOLANAOASIS.Infrastructure.Models.Common;
namespace NextGenSoftware.OASIS.API.Providers.SOLANAOASIS.Infrastructure.Models.Responses
{
public sealed class SendTransactionResult : BaseTransactionResult
{
public SendTransactionResult(string transactionHash) : base(transactionHash)
{
}
public SendTransactionResult()
{
}
}
} | 27.375 | 89 | 0.703196 | [
"CC0-1.0"
] | HirenBodhi/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK | NextGenSoftware.OASIS.API.Providers.SOLANAOASIS/Infrastructure/Models/Responses/SendTransactionResult.cs | 438 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp;
using Abp.Extensions;
using Abp.Notifications;
using Abp.Timing;
using Volo.SqliteDemo.Controllers;
namespace Volo.SqliteDemo.Web.Host.Controllers
{
public class HomeController : SqliteDemoControllerBase
{
private readonly INotificationPublisher _notificationPublisher;
public HomeController(INotificationPublisher notificationPublisher)
{
_notificationPublisher = notificationPublisher;
}
public IActionResult Index()
{
return Redirect("/swagger");
}
/// <summary>
/// This is a demo code to demonstrate sending notification to default tenant admin and host admin uers.
/// Don't use this code in production !!!
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task<ActionResult> TestNotification(string message = "")
{
if (message.IsNullOrEmpty())
{
message = "This is a test notification, created at " + Clock.Now;
}
var defaultTenantAdmin = new UserIdentifier(1, 2);
var hostAdmin = new UserIdentifier(null, 1);
await _notificationPublisher.PublishAsync(
"App.SimpleMessage",
new MessageNotificationData(message),
severity: NotificationSeverity.Info,
userIds: new[] { defaultTenantAdmin, hostAdmin }
);
return Content("Sent notification: " + message);
}
}
}
| 31.153846 | 112 | 0.61358 | [
"MIT"
] | OzBob/aspnetboilerplate-samples | SqliteDemo/aspnet-core/src/Volo.SqliteDemo.Web.Host/Controllers/HomeController.cs | 1,620 | C# |
using System.Collections.Generic;
using System.Data;
namespace ALE.ETLBox.ConnectionManager {
public interface IDbConnectionManager : IConnectionManager {
int ExecuteNonQuery(string command, IEnumerable<QueryParameter> parameterList = null);
object ExecuteScalar(string command, IEnumerable<QueryParameter> parameterList = null);
IDataReader ExecuteReader(string command, IEnumerable<QueryParameter> parameterList = null);
void BulkInsert(ITableData data, string tableName);
void BeforeBulkInsert();
void AfterBulkInsert();
IDbConnectionManager Clone();
}
}
| 42.066667 | 100 | 0.736926 | [
"MIT"
] | mukundnc/etlbox | ETLBox/src/Definitions/ConnectionManager/IDbConnectionManager.cs | 633 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Windows.Foundation;
[assembly: InternalsVisibleTo("Tests")]
namespace Environment
{
public class World
{
internal const float RotationalFactor = 4f; // 4 for rapidly rotating bodies (Earth), 2 for slowly rotating bodies.
internal const float SolarLuminosity = 3.828e26f;
internal const float DistanceToTheSun = 1.495978707e11f;
public World(IController controller, int Size)
{
Controller = controller;
this.Size = Size;
Cells = new Cell[Size, Size];
controller.CurrentWorld = this; // must come before Controller.CreateViewport()
Viewport = Controller.CreateViewport();
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
var cell = new Cell(this, x, y);
cell.Terrain = new Terrain(TerrainKind.Rock);
Cells[x, y] = cell;
}
}
IsInited = true;
}
public bool IsInited { get; private set; } = false;
public IViewport Viewport { get; private set; }
private double age;
private int energy;
public IController Controller { get; set; }
public string Name { get => name; set { name = value; Controller.RaisePropertyChanged("CurrentWorld"); } }
public int Size { get; private set; }
public int Width { get => Size; }
public int Height { get => Width; }
public double Age
{
get => age;
set
{
age = value;
Controller.RaisePropertyChanged("CurrentWorld");
}
}
public double Radius { get; set; }
private string GetAge()
{
string[] prefixes = new string[] { "", "k", "M", "G", "T" };
int index = 0;
double age = Age;
while (age >= 1000 && index < prefixes.Length - 1)
{
index++;
age /= 1000;
}
return $"{age:N2} {prefixes[index]}";
}
public override sealed string ToString()
{
return $"{Name}: {GetAge()}yr";
}
private long tick = 0;
public long CurrentTick { get => tick; }
internal Queue<Census> CensusHistory = new Queue<Census>();
private const int MaxCensusHistory = 30;
public Census CurrentCensus { get; set; }
public void Tick()
{
var start = DateTime.Now;
Age += YearsFromSpeed(Controller.Speed);
Energy = Math.Min(MaxEnergy, Energy + GetProducedEnergy());
CurrentCensus = new Census();
if (CensusHistory.Count == MaxCensusHistory)
{
CensusHistory.Dequeue();
}
foreach (var cell in Cells)
{
cell.TickAnimal();
TickTerrain(cell);
}
CensusHistory.Enqueue(CurrentCensus);
var duration = DateTime.Now - start;
//Controller.SetStatus($"Tick {tick}: {duration.TotalMilliseconds} ms");
tick++;
}
private double YearsFromSpeed(Speed speed)
{
switch (speed)
{
case Speed.Slow: return 1e2;
case Speed.Medium: return 1e3;
case Speed.Fast: return 1e4;
case Speed.Paused: return 0;
}
throw new InvalidOperationException();
}
private void TickTerrain(Cell cell)
{
cell.TickTerrain();
if (cell.Terrain != null)
{
CurrentCensus.AddTerrain(cell.Terrain);
}
}
private Random rand = new Random();
private string name;
internal Random Random { get => rand; }
public int LatitudeToY(Angle latitude)
{
double y = -(2 * latitude.Radians / Math.PI) * (Height / 2) + (Height / 2);
return (int)(y + .5);
}
public Angle YToLatitude(int y)
{
if (y < 0 || y > Height) throw new ArgumentException($"Y must be between 0 and {Height}");
double a = (y - Height / 2.0) / (-2 * Math.PI);
return new Angle(a);
}
public int GetProducedEnergy()
{
// TODO: Calculate produced energy
return 5;
}
public int MaxEnergy { get; } = 5000;
public int Energy
{
get => energy;
set
{
energy = value;
Controller.RaisePropertyChanged("Energy");
}
}
public Cell[,] Cells { get; private set; }
public Cell CorrectCellForAnimalMicroMovement(double px, double py)
{
Cell minCell = null;
float minDist = float.PositiveInfinity;
for (double y = py - Viewport.CellSize; y < py + Viewport.CellSize; y++)
{
for (double x = px - Viewport.CellSize; x < px + Viewport.CellSize; x++)
{
Cell c = Viewport.GetCellAtPoint(new Point(x, y));
Point animalPos = c.Animal != null ? c.Animal.Location : new Point();
float effectiveX = (float)(c.X + .5f + animalPos.X);
float effectiveY = (float)(c.Y + .5f + animalPos.Y);
// Now convert the effective X, Y into screen coordinates
Point screenCoords = Viewport.CellIndexToScreenCoords(effectiveX, effectiveY);
float newDist = DistanceSq(px, py, screenCoords);
if (newDist < minDist)
{
minCell = c;
minDist = newDist;
}
}
}
return minCell;
}
private static float DistanceSq(double px, double py, Point screenCoords)
{
return (float)((px - screenCoords.X).Squared() + (py - screenCoords.Y).Squared());
}
}
}
| 32.528497 | 123 | 0.498089 | [
"MIT"
] | asklar/SimEarth2020 | src/Environment/World.cs | 6,280 | C# |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* NotifyPropertyChangedUtility.cs --
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#if !WINMOBILE && !PocketPC && !UAP
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AM;
using CodeJam;
using JetBrains.Annotations;
using MoonSharp.Interpreter;
using Newtonsoft.Json;
#endregion
namespace AM.ComponentModel
{
/// <summary>
/// Helpers for <see cref="INotifyPropertyChanged"/>.
/// </summary>
[PublicAPI]
public static class PropertyChangedUtility
{
#region Public methods
/// <summary>
/// Borrowed from ReactiveUI
/// </summary>
public static TRet RaiseAndSetIfChanged<TObj, TRet>
(
this TObj This,
ref TRet backingField,
TRet newValue,
[NotNull] string propertyName
)
where TObj : INotifyPropertyChanged
{
Code.NotNull(propertyName, "propertyName");
if (EqualityComparer<TRet>.Default.Equals
(
backingField,
newValue
))
{
return newValue;
}
//This.raisePropertyChanging(propertyName);
backingField = newValue;
//This.raisePropertyChanged(propertyName);
return newValue;
}
/// <summary>
/// Notifies the property changed.
/// </summary>
public static void NotifyPropertyChanged<T, TProperty>
(
this T propertyChangedBase,
Expression<Func<T, TProperty>> expression,
object newValue
)
where T : NotifyProperty
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression != null)
{
string propertyName = memberExpression.Member.Name;
if (newValue != null)
{
typeof(T).GetProperty(propertyName)
.SetValue
(
propertyChangedBase,
newValue,
null
);
}
propertyChangedBase.NotifyPropertyChanged(propertyName);
}
}
#endregion
}
}
#endif
| 25.178571 | 84 | 0.52695 | [
"MIT"
] | amironov73/ManagedClient.45 | Source/Classic/Libs/AM.Core/AM/ComponentModel/PropertyChangedUtility.cs | 2,824 | C# |
using System;
using System.Linq;
using BrotliLib.Markers.Serialization;
using BrotliLib.Numbers;
using BrotliLib.Serialization;
namespace BrotliLib.Brotli.Components{
/// <summary>
/// Describes Brotli window size specified in the stream header.
/// https://tools.ietf.org/html/rfc7932#section-9.1
/// </summary>
public sealed class WindowSize{
public const int MinBits = 10;
public const int MaxBits = 24;
public const int MarginBytes = 16;
public static readonly IntRange BitsRange = new IntRange(MinBits, MaxBits);
public static WindowSize Default => new WindowSize(16);
public static WindowSize ForFileSize(int fileBytes){
return BitsRange.Values.Select(bits => new WindowSize(bits)).FirstOrDefault(ws => ws.Bytes >= fileBytes) ?? new WindowSize(MaxBits);
}
// Data
public int Bytes => (1 << Bits) - MarginBytes;
public int Bits { get; }
public WindowSize(int wbits){
if (!BitsRange.Contains(wbits)){
throw new ArgumentOutOfRangeException(nameof(wbits), wbits, "Window size bits must be in the range " + BitsRange + ".");
}
this.Bits = wbits;
}
// Object
public override bool Equals(object obj){
return obj is WindowSize size &&
Bits == size.Bits;
}
public override int GetHashCode(){
return HashCode.Combine(Bits);
}
public override string ToString(){
return "Bits = " + Bits + " (Bytes = " + Bytes + ")";
}
// Serialization
public static readonly BitDeserializer<WindowSize, NoContext> Deserialize = MarkedBitDeserializer.Title<WindowSize, NoContext>(
"Window Size",
(reader, context) => {
int wbits = reader.MarkValue("WBITS", () => {
if (!reader.NextBit()){ // [0]
return 16;
}
else{
int next = reader.NextChunk(3); // [1xxx]
if (next != 0){
return 17 + next;
}
else{
next = reader.NextChunk(3); // [1000xxx]
return next switch{
1 => throw new InvalidOperationException("Invalid window size, 1000001 is a reserved value."),
0 => 17,
_ => 8 + next,
};
}
}
});
return new WindowSize(wbits);
}
);
public static readonly BitSerializer<WindowSize, NoContext> Serialize = (writer, obj, context) => {
switch(obj.Bits){
case 10: writer.WriteChunk(7, 0b_010_000_1); break;
case 11: writer.WriteChunk(7, 0b_011_000_1); break;
case 12: writer.WriteChunk(7, 0b_100_000_1); break;
case 13: writer.WriteChunk(7, 0b_101_000_1); break;
case 14: writer.WriteChunk(7, 0b_110_000_1); break;
case 15: writer.WriteChunk(7, 0b_111_000_1); break;
case 16: writer.WriteChunk(1, 0b_0); break;
case 17: writer.WriteChunk(7, 0b_000_000_1); break;
case 18: writer.WriteChunk(4, 0b_001_1); break;
case 19: writer.WriteChunk(4, 0b_010_1); break;
case 20: writer.WriteChunk(4, 0b_011_1); break;
case 21: writer.WriteChunk(4, 0b_100_1); break;
case 22: writer.WriteChunk(4, 0b_101_1); break;
case 23: writer.WriteChunk(4, 0b_110_1); break;
case 24: writer.WriteChunk(4, 0b_111_1); break;
default: throw new InvalidOperationException("Window size object has an invalid window size parameter (WBITS): " + obj.Bits);
}
};
}
}
| 37.731481 | 144 | 0.52319 | [
"MIT"
] | chylex/Brotli-Builder | BrotliLib/Brotli/Components/WindowSize.cs | 4,077 | C# |
using System;
using System.Collections.Generic;
namespace _0202
{
public class Solution
{
public bool IsHappy(int n)
{
var set = new HashSet<int>();
while (true)
{
var newn = 0;
while (n > 0)
{
newn += (int)Math.Pow(n % 10, 2);
n /= 10;
}
if (newn == 1)
{
return true;
}
if (set.Contains(newn))
{
return false;
}
set.Add(newn);
n = newn;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 19.204545 | 53 | 0.331361 | [
"Apache-2.0"
] | twilightgod/PlayLeetcode | 0202/Program.cs | 847 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2014 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
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 FluentAssertions;
using Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles;
using Polly.Registry;
using Microsoft.Extensions.DependencyInjection;
using Paramore.Brighter.Extensions.DependencyInjection;
using Xunit;
namespace Paramore.Brighter.Core.Tests.CommandProcessors
{
[Collection("CommandProcessor")]
public class CommandProcessorNoHandlersMatchTests : IDisposable
{
private readonly CommandProcessor _commandProcessor;
private readonly MyCommand _myCommand = new MyCommand();
private Exception _exception;
public CommandProcessorNoHandlersMatchTests()
{
var container = new ServiceCollection();
container.AddSingleton<IBrighterOptions>(new BrighterOptions() {HandlerLifetime = ServiceLifetime.Transient});
_commandProcessor = new CommandProcessor(
new SubscriberRegistry(),
(IAmAHandlerFactory)new ServiceProviderHandlerFactory(container.BuildServiceProvider()),
new InMemoryRequestContextFactory(),
new PolicyRegistry());
}
[Fact]
public void When_There_Are_No_Command_Handlers()
{
_exception = Catch.Exception(() => _commandProcessor.Send(_myCommand));
//_should_fail_because_multiple_receivers_found
_exception.Should().BeOfType<ArgumentException>();
//_should_have_an_error_message_that_tells_you_why
_exception.Should().NotBeNull();
_exception.Message.Should().Contain("No command handler was found");
}
public void Dispose()
{
CommandProcessor.ClearExtServiceBus();
}
}
}
| 40.013889 | 122 | 0.728566 | [
"MIT"
] | Elizabethhanson/Brighter | tests/Paramore.Brighter.Core.Tests/CommandProcessors/When_there_are_no_command_handlers.cs | 2,892 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Shipping_Easy.Partner
{
[Serializable]
public class Isn
{
public Event Event { get; set; }
public string order_number { get; set; }
public string refund_url { get; set; }
public string tracking_url { get; set; }
public string tracking_number { get; set; }
public string ship_date { get; set; }
public string carrier { get; set; }
public string status { get; set; }
public string carrier_service { get; set; }
public Dictionary<string, object> shipper { get; set; }
}
}
| 25.538462 | 63 | 0.628012 | [
"Unlicense"
] | mithereal/asp_shipping_easy_models | Partner/Isn.cs | 664 | C# |
namespace AutoMapper
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Impl;
using Internal;
/// <summary>
/// Main configuration object holding all mapping configuration for a source and destination type
/// </summary>
[DebuggerDisplay("{_sourceType.Type.Name} -> {_destinationType.Type.Name}")]
public class TypeMap
{
private readonly IList<Action<object, object>> _afterMapActions = new List<Action<object, object>>();
private readonly IList<Action<object, object>> _beforeMapActions = new List<Action<object, object>>();
private readonly TypeInfo _destinationType;
private readonly ISet<TypePair> _includedDerivedTypes = new HashSet<TypePair>();
private readonly ThreadSafeList<PropertyMap> _propertyMaps = new ThreadSafeList<PropertyMap>();
private readonly ThreadSafeList<SourceMemberConfig> _sourceMemberConfigs =
new ThreadSafeList<SourceMemberConfig>();
private readonly IList<PropertyMap> _inheritedMaps = new List<PropertyMap>();
private PropertyMap[] _orderedPropertyMaps;
private readonly TypeInfo _sourceType;
private bool _sealed;
private Func<ResolutionContext, bool> _condition;
private ConstructorMap _constructorMap;
private int _maxDepth = Int32.MaxValue;
public TypeMap(TypeInfo sourceType, TypeInfo destinationType, MemberList memberList)
{
_sourceType = sourceType;
_destinationType = destinationType;
Profile = ConfigurationStore.DefaultProfileName;
ConfiguredMemberList = memberList;
}
public ConstructorMap ConstructorMap
{
get { return _constructorMap; }
}
public Type SourceType
{
get { return _sourceType.Type; }
}
public Type DestinationType
{
get { return _destinationType.Type; }
}
public string Profile { get; set; }
public Func<ResolutionContext, object> CustomMapper { get; private set; }
public LambdaExpression CustomProjection { get; private set; }
public Action<object, object> BeforeMap
{
get
{
return (src, dest) =>
{
foreach (var action in _beforeMapActions)
action(src, dest);
};
}
}
public Action<object, object> AfterMap
{
get
{
return (src, dest) =>
{
foreach (var action in _afterMapActions)
action(src, dest);
};
}
}
public Func<ResolutionContext, object> DestinationCtor { get; set; }
public List<string> IgnorePropertiesStartingWith { get; set; }
public Type DestinationTypeOverride { get; set; }
public bool ConstructDestinationUsingServiceLocator { get; set; }
public MemberList ConfiguredMemberList { get; private set; }
public IEnumerable<TypePair> IncludedDerivedTypes
{
get { return _includedDerivedTypes; }
}
public int MaxDepth
{
get { return _maxDepth; }
set
{
_maxDepth = value;
SetCondition(o => PassesDepthCheck(o, value));
}
}
public Func<object, object> Substitution { get; set; }
public LambdaExpression ConstructExpression { get; set; }
public IEnumerable<PropertyMap> GetPropertyMaps()
{
if (_sealed)
return _orderedPropertyMaps;
return _propertyMaps.Concat(_inheritedMaps);
}
public IEnumerable<PropertyMap> GetCustomPropertyMaps()
{
return _propertyMaps;
}
public void AddPropertyMap(PropertyMap propertyMap)
{
_propertyMaps.Add(propertyMap);
}
protected void AddInheritedMap(PropertyMap propertyMap)
{
_inheritedMaps.Add(propertyMap);
}
public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IValueResolver> resolvers)
{
var propertyMap = new PropertyMap(destProperty);
resolvers.Each(propertyMap.ChainResolver);
AddPropertyMap(propertyMap);
}
public string[] GetUnmappedPropertyNames()
{
var autoMappedProperties = _propertyMaps.Where(pm => pm.IsMapped())
.Select(pm => pm.DestinationProperty.Name);
var inheritedProperties = _inheritedMaps.Where(pm => pm.IsMapped())
.Select(pm => pm.DestinationProperty.Name);
IEnumerable<string> properties;
if (ConfiguredMemberList == MemberList.Destination)
properties = _destinationType.GetPublicWriteAccessors()
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(inheritedProperties);
else
{
var redirectedSourceMembers = _propertyMaps
.Where(pm => pm.IsMapped())
.Where(pm => pm.CustomExpression != null)
.Where(pm => pm.SourceMember != null)
.Select(pm => pm.SourceMember.Name);
var ignoredSourceMembers = _sourceMemberConfigs
.Where(smc => smc.IsIgnored())
.Select(pm => pm.SourceMember.Name);
properties = _sourceType.GetPublicReadAccessors()
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(inheritedProperties)
.Except(redirectedSourceMembers)
.Except(ignoredSourceMembers)
;
}
return properties.Where(memberName => !IgnorePropertiesStartingWith.Any(memberName.StartsWith)).ToArray();
}
public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty)
{
var propertyMap = GetExistingPropertyMapFor(destinationProperty);
if (propertyMap == null)
{
propertyMap = new PropertyMap(destinationProperty);
AddPropertyMap(propertyMap);
}
return propertyMap;
}
public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType)
{
_includedDerivedTypes.Add(new TypePair(derivedSourceType, derivedDestinationType));
}
public Type GetDerivedTypeFor(Type derivedSourceType)
{
// This might need to be fixed for multiple derived source types to different dest types
var match = _includedDerivedTypes.FirstOrDefault(tp => tp.SourceType == derivedSourceType);
return match.Equals(default(TypePair)) ? DestinationType : match.DestinationType;
}
public bool TypeHasBeenIncluded(Type derivedSourceType, Type derivedDestinationType)
{
return _includedDerivedTypes.Contains(new TypePair(derivedSourceType, derivedDestinationType));
}
public bool HasDerivedTypesToInclude()
{
return _includedDerivedTypes.Any();
}
public void UseCustomMapper(Func<ResolutionContext, object> customMapper)
{
CustomMapper = customMapper;
_propertyMaps.Clear();
}
public void AddBeforeMapAction(Action<object, object> beforeMap)
{
_beforeMapActions.Add(beforeMap);
}
public void AddAfterMapAction(Action<object, object> afterMap)
{
_afterMapActions.Add(afterMap);
}
public void Seal()
{
if (_sealed)
return;
_orderedPropertyMaps =
_propertyMaps
.Union(_inheritedMaps)
.OrderBy(map => map.GetMappingOrder()).ToArray();
_orderedPropertyMaps.Each(pm => pm.Seal());
_sealed = true;
}
public bool Equals(TypeMap other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other._sourceType, _sourceType) && Equals(other._destinationType, _destinationType);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (TypeMap)) return false;
return Equals((TypeMap) obj);
}
public override int GetHashCode()
{
unchecked
{
return (_sourceType.GetHashCode()*397) ^ _destinationType.GetHashCode();
}
}
public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty)
{
var propertyMap =
_propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name));
if (propertyMap != null)
return propertyMap;
propertyMap =
_inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name));
if (propertyMap == null)
return null;
var propertyInfo = propertyMap.DestinationProperty.MemberInfo as PropertyInfo;
if (propertyInfo == null)
return propertyMap;
var baseAccessor = propertyInfo.GetAccessors()[0];
if (baseAccessor.IsAbstract || baseAccessor.IsVirtual)
return propertyMap;
var accessor = ((PropertyInfo)destinationProperty.MemberInfo).GetAccessors()[0];
if (baseAccessor.DeclaringType == accessor.DeclaringType)
return propertyMap;
return null;
}
public void AddInheritedPropertyMap(PropertyMap mappedProperty)
{
_inheritedMaps.Add(mappedProperty);
}
public void InheritTypes(TypeMap inheritedTypeMap)
{
foreach (var includedDerivedType in inheritedTypeMap._includedDerivedTypes
.Where(includedDerivedType => !_includedDerivedTypes.Contains(includedDerivedType)))
{
_includedDerivedTypes.Add(includedDerivedType);
}
}
public void SetCondition(Func<ResolutionContext, bool> condition)
{
_condition = condition;
}
public bool ShouldAssignValue(ResolutionContext resolutionContext)
{
return _condition == null || _condition(resolutionContext);
}
public void AddConstructorMap(ConstructorInfo constructorInfo, IEnumerable<ConstructorParameterMap> parameters)
{
var ctorMap = new ConstructorMap(constructorInfo, parameters);
_constructorMap = ctorMap;
}
public SourceMemberConfig FindOrCreateSourceMemberConfigFor(MemberInfo sourceMember)
{
var config = _sourceMemberConfigs.FirstOrDefault(smc => smc.SourceMember == sourceMember);
if (config == null)
{
config = new SourceMemberConfig(sourceMember);
_sourceMemberConfigs.Add(config);
}
return config;
}
private static bool PassesDepthCheck(ResolutionContext context, int maxDepth)
{
if (context.InstanceCache.ContainsKey(context))
{
// return true if we already mapped this value and it's in the cache
return true;
}
ResolutionContext contextCopy = context;
int currentDepth = 1;
// walk parents to determine current depth
while (contextCopy.Parent != null)
{
if (contextCopy.SourceType == context.TypeMap.SourceType &&
contextCopy.DestinationType == context.TypeMap.DestinationType)
{
// same source and destination types appear higher up in the hierarchy
currentDepth++;
}
contextCopy = contextCopy.Parent;
}
return currentDepth <= maxDepth;
}
public void UseCustomProjection(LambdaExpression projectionExpression)
{
CustomProjection = projectionExpression;
_propertyMaps.Clear();
}
}
}
| 34.860892 | 120 | 0.570245 | [
"MIT"
] | jakard76/AutoMapper | src/AutoMapper/TypeMap.cs | 13,282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.Core;
namespace Cosmos.Core.IOGroup {
public class Keyboard : IOGroup {
public readonly IOPort Port60 = new IOPort(0x60);
}
}
| 20.25 | 57 | 0.72428 | [
"BSD-3-Clause"
] | Dark-Tater/Cosmos | source/Cosmos.Core/IOGroup/Keyboard.cs | 245 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/***************************************************************************\
*
* File: BamlDump.cs
*
* Dump baml file to Console.
*
*
\***************************************************************************/
using System;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Windows.Markup;
using MS.Internal;
using System.Windows.Media;
using System.Xml;
using System.Globalization;
namespace DRT
{
// Baml dumper
[System.Runtime.InteropServices.ComVisible(false)]
public class BamlDump
{
static BamlReaderWrapper Reader;
static bool Verbose = false;
static bool ConvertOnly = false;
static bool Roundtrip = false;
static Assembly assemblyPBT;
[STAThread]
public static int Main(string[] args)
{
if (args.Length > 2 ||
(args.Length == 1 &&
(args[0] == "/?" || args[0] == "?")))
{
Console.WriteLine("Usage: BamlDump filename [v|c|r]");
Console.WriteLine(" Dump of Baml file to console using BamlReader.");
Console.WriteLine(" If Xaml file is given, it will first be converted to BAML");
Console.WriteLine(" 'v' dumps more verbose output");
Console.WriteLine(" 'c' converts xaml to baml only");
Console.WriteLine(" 'r' reads baml and writes out a new baml file using BamlWriter");
Console.WriteLine(" The new file has '_' appended to base name");
return 0;
}
assemblyPBT = WrapperUtil.FindAssemblyInDomain("PresentationBuildTasks");
if (args.Length == 0)
{
args = new string[1];
args[0] = "test.xaml";
}
else
{
Verbose = (args.Length == 2 && args[1] == "v");
ConvertOnly = (args.Length == 2 && args[1] == "c");
Roundtrip = (args.Length == 2 && args[1] == "r");
}
string filename = args[0];
if (filename.Length < 6)
{
Console.WriteLine("Illegal filename : " + filename);
return 1;
}
try
{
if (filename.ToUpper(new CultureInfo("en-us", false)).LastIndexOf(".XAML") ==
filename.Length-5)
{
if (!ConvertOnly && !Roundtrip && Verbose)
{
ParseXml(filename);
}
WrapperUtil.ConvertToBaml(filename);
filename = filename.Substring(0,filename.Length-5) + ".baml";
}
if (Roundtrip)
{
DumpToNewBaml(filename);
}
else if (!ConvertOnly)
{
DumpText(filename);
}
}
catch (Exception e)
{
Console.WriteLine("BamlDump failed!!!\nOwner is Microsoft\n" + e);
// PreSharp Complaint 6500 - do not handle null-ref or SEH exceptions.
//
// This should be CriticalExceptions.IsCriticalException, but that requires
// linking to WindowsBase, which is a heavy requirement for "shared" code.
//
if(e is NullReferenceException || e is System.Runtime.InteropServices.SEHException)
{
throw;
}
else
{
return 1;
}
}
return 0;
}
// Read in one baml file using BamlReader and write to another baml file using BamlWriter
private static void DumpToNewBaml(string filename)
{
// Load the baml file using the BamlReader and display its contents to the console.
Stream fs = LoadTestFile(filename);
Reader = new BamlReaderWrapper(fs);
string outFile = filename.Substring(0,filename.Length-5) + "_.baml";
System.IO.Stream stream = File.OpenWrite(outFile);
BamlWriterWrapper writer = new BamlWriterWrapper(stream);
while (Reader.Read())
{
switch (Reader.NodeType)
{
case "StartDocument":
writer.WriteStartDocument();
break;
case "EndDocument":
writer.WriteEndDocument();
break;
case "StartElement":
writer.WriteStartElement(Reader.AssemblyName, Reader.Name, Reader.IsInjected, Reader.CreateUsingTypeConverter);
break;
case "StartComplexProperty":
writer.WriteStartComplexProperty(
Reader.AssemblyName,
Reader.Name.Substring(0, Reader.Name.LastIndexOf('.')),
Reader.LocalName);
break;
case "EndElement":
writer.WriteEndElement();
break;
case "EndComplexProperty":
writer.WriteEndComplexProperty();
break;
case "StartConstructor":
writer.WriteStartConstructor();
break;
case "EndConstructor":
writer.WriteEndConstructor();
break;
case "LiteralContent":
writer.WriteLiteralContent(Reader.Value);
break;
case "IncludeReference":
Console.Write(" \"" + Reader.Value + "\"");
break;
case "Text":
writer.WriteText(Reader.Value, Reader.TypeConverterAssemblyName, Reader.TypeConverterName);
break;
case "Event":
writer.WriteEvent(Reader.Name, Reader.Value);
break;
case "RoutedEvent":
writer.WriteRoutedEvent(
Reader.AssemblyName,
Reader.Name.Substring(0, Reader.Name.LastIndexOf('.')),
Reader.LocalName,
Reader.Value);
break;
case "PIMapping":
writer.WritePIMapping(Reader.XmlNamespace,
Reader.ClrNamespace,
Reader.AssemblyName);
break;
}
if (Reader.HasProperties)
{
Reader.MoveToFirstProperty();
do
{
if (Reader.NodeType == "ConnectionId")
{
writer.WriteConnectionId(Reader.ConnectionId);
}
else if (Reader.NodeType == "Property")
{
writer.WriteProperty(Reader.AssemblyName,
Reader.Name.Substring(0, Reader.Name.LastIndexOf('.')),
Reader.LocalName,
Reader.Value,
Reader.AttributeUsage);
}
else if (Reader.NodeType == "DefAttribute")
{
writer.WriteDefAttribute(Reader.Name,
Reader.Value);
}
else if (Reader.NodeType == "PresentationOptionsAttribute")
{
writer.WritePresentationOptionsAttribute(Reader.Name,
Reader.Value);
}
else if (Reader.NodeType == "ContentProperty")
{
writer.WriteContentProperty(Reader.AssemblyName,
Reader.Name.Substring(0, Reader.Name.LastIndexOf('.')),
Reader.LocalName);
}
else
{
writer.WriteXmlnsProperty(Reader.LocalName,
Reader.Value);
}
}
while (Reader.MoveToNextProperty());
}
}
Reader.Close();
writer.Close();
}
// Dump text representation of baml file to console
private static void DumpText(string filename)
{
// Load the baml file using the BamlReader and display its contents to the console.
Stream fs = LoadTestFile(filename);
Reader = new BamlReaderWrapper(fs);
int depth = 0;
while (Reader.Read())
{
// Set depth and indent accordingly
switch (Reader.NodeType)
{
case "StartElement":
case "StartComplexProperty":
case "StartConstructor":
depth++;
break;
}
Indent(depth);
Console.Write(Reader.NodeType.ToString());
// Write additional information
switch (Reader.NodeType)
{
case "StartElement":
case "StartComplexProperty":
case "StartConstructor":
Console.Write(" ");
WritePrefixedName();
break;
case "EndElement":
case "EndComplexProperty":
case "EndConstructor":
depth--;
Console.Write(" ");
WritePrefixedName();
break;
case "LiteralContent":
case "Text":
Console.Write(" \"" + Reader.Value + "\"");
break;
case "PIMapping":
Console.Write(" XmlNamespace=" + Reader.XmlNamespace +
" ClrNamespace=" + Reader.ClrNamespace +
" Assembly=" + Reader.AssemblyName);
break;
}
Console.WriteLine("");
if (Reader.HasProperties)
{
Reader.MoveToFirstProperty();
do
{
Indent(depth+2);
Console.Write(Reader.NodeType.ToString());
Console.Write(" ");
WritePrefixedName();
if (Verbose)
Console.WriteLine(" Value=" + Reader.Value);
else
Console.WriteLine(" = " + Reader.Value);
}
while (Reader.MoveToNextProperty());
}
}
Reader.Close();
}
// Indent a number of spaces
private static void Indent(int indent)
{
for (int i=0; i<indent; i++)
Console.Write(" ");
}
// Write current reader name plus prefix, if there is one.
private static void WritePrefixedName()
{
if (Verbose)
{
Console.Write("XmlNamespace=" + Reader.XmlNamespace);
Console.Write(" ClrNamespace=" + Reader.ClrNamespace);
Console.Write(" Assembly=" + Reader.AssemblyName);
Console.Write(" Prefix=" + Reader.Prefix);
Console.Write(" Name=" + Reader.Name);
Console.Write(" LocalName=" + Reader.LocalName);
//Console.Write(" ReadState=" + Reader.ReadState);
}
else
{
Console.Write(Reader.Name);
}
}
// Loads up a test file.
// File is relative to the TestFileDir
private static Stream LoadTestFile(string fileName)
{
string testFile = fileName;
System.IO.Stream stream = File.OpenRead(testFile);
return stream;
}
// Read the passed xmlfile using XmlTextReader and display contents
private static void ParseXml(string filename)
{
XmlTextReader xmlrdr = new XmlTextReader(filename);
while (xmlrdr.Read())
{
Indent(xmlrdr.Depth);
Console.Write(xmlrdr.NodeType.ToString());
Console.Write(" " + xmlrdr.NamespaceURI + " | " + xmlrdr.Prefix + " > " + xmlrdr.Name + " - " + xmlrdr.LocalName + " = " + xmlrdr.Value);
Console.WriteLine("");
if (xmlrdr.HasAttributes)
{
xmlrdr.MoveToFirstAttribute();
do
{
Indent(xmlrdr.Depth+1);
Console.Write(" " + xmlrdr.NamespaceURI + " | " + xmlrdr.Prefix + " > " + xmlrdr.Name + " - " + xmlrdr.LocalName + " = " + xmlrdr.Value);
Console.WriteLine("");
}
while (xmlrdr.MoveToNextAttribute());
}
}
xmlrdr.Close();
}
}
}
| 36.378109 | 161 | 0.424371 | [
"MIT"
] | batzen/wpf-test | src/Test/Common/DRT/BamlDump/BamlDump.cs | 14,624 | C# |
#region CopyrightHeader
//
// Copyright by Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace gov.va.medora.mdo
{
public class PatientRecordFlag
{
string id;
string name;
string actionId;
string actionName;
string actionTimestamp;
string noteId;
public PatientRecordFlag() { }
public string Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string ActionId
{
get { return actionId; }
set { actionId = value; }
}
public string ActionName
{
get { return actionName; }
set { actionName = value; }
}
public string ActionTimestamp
{
get { return actionTimestamp; }
set { actionTimestamp = value; }
}
public string NoteId
{
get { return noteId; }
set { noteId = value; }
}
}
}
| 23.739726 | 76 | 0.571841 | [
"Apache-2.0"
] | marcsommer/mdo | mdo/src/mdo/PatientRecordFlag.cs | 1,733 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace samples.tpl
{
public class AppTest
{
async static Task ProcessAsynchronously()
{
var cts = new CancellationTokenSource();
Task.Run(() =>
{
if (Console.ReadKey().KeyChar == 'c')
{
cts.Cancel();
}
});
var inputBlock = new BufferBlock<int>(new DataflowBlockOptions
{
BoundedCapacity = 5,
CancellationToken = cts.Token
});
var filter1Block = new TransformBlock<int, decimal>(n =>
{
decimal result = Convert.ToDecimal(n * 0.97);
Console.WriteLine("{0} {1} {2}", result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromMilliseconds(100));
return result;
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4,
CancellationToken = cts.Token
});
var filter2Block = new TransformBlock<decimal, string>(n =>
{
string result = string.Format("--{0}--", n);
Console.WriteLine("{0} {1} {2}", result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromMilliseconds(100));
return result;
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4,
CancellationToken = cts.Token
});
var outputBlock = new ActionBlock<string>(a =>
{
Console.WriteLine("{0} {1} {2}", a, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4,
CancellationToken = cts.Token
});
inputBlock.LinkTo(filter1Block, new DataflowLinkOptions { PropagateCompletion = true });
filter1Block.LinkTo(filter2Block, new DataflowLinkOptions { PropagateCompletion = true });
filter2Block.LinkTo(outputBlock, new DataflowLinkOptions { PropagateCompletion = true });
try
{
Parallel.For(0, 20, new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = cts.Token },
i =>
{
Console.WriteLine("add {0} to source data on threadid {1}", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromMilliseconds(100));
});
inputBlock.Complete();
await outputBlock.Completion;
}
catch (OperationCanceledException e)
{
Console.WriteLine("取消");
}
}
public static void Run()
{
var t = ProcessAsynchronously();
t.GetAwaiter().GetResult();
}
}
}
| 35.333333 | 136 | 0.539562 | [
"MIT"
] | shenhx/DotNetAll | 02CSharp/DotNet_Theads/MultiThread/samples/tpl/AppTest.cs | 3,292 | C# |
using System;
namespace Charlotte.Games
{
// Token: 0x02000011 RID: 17
public static class GameCommon
{
}
}
| 11.4 | 31 | 0.710526 | [
"MIT"
] | soleil-taruto/Hatena | a20201226/Decompile/BeforeConfuse/Elsa20200001/Games/GameCommon.cs | 116 | C# |
using System;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace SimpleHTTPServer
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
string path = Directory.GetCurrentDirectory();
string portStr = args.ElementAtOrDefault(0);
int port = String.IsNullOrEmpty(portStr) ? 8000 : Int32.Parse(portStr);
string privkeyPath = args.ElementAtOrDefault(1);
string privkeySecret = args.ElementAtOrDefault(2);
if (String.IsNullOrWhiteSpace(privkeyPath))
return WebHost.CreateDefaultBuilder(args)
.UseUrls($"http://*:{port}")
.UseContentRoot(path)
.UseKestrel()
.UseStartup<Startup>();
else
return WebHost.CreateDefaultBuilder(args)
.UseContentRoot(path)
.UseKestrel(options =>
{
options.Listen(IPAddress.Any, port, listenOptions => {
listenOptions.UseHttps(privkeyPath, privkeySecret);
});
})
.UseStartup<Startup>();
}
}
}
| 33.840909 | 84 | 0.533244 | [
"MIT"
] | ijat/SimpleHTTPServer-.NET | SimpleHTTPServer/Program.cs | 1,491 | C# |
using ctci.Contracts;
using ctci.Library;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Chapter10
{
public class Q10_02_Group_Anagrams : Question
{
private class AnagramComparator : IComparer
{
private string SortChars(string s)
{
char[] content = s.ToCharArray();
Array.Sort<char>(content);
return new string(content);
}
int IComparer.Compare(Object x, Object y)
{
return SortChars((string)x).CompareTo(SortChars((string)y));
}
}
private string SortChars(string s)
{
char[] content = s.ToCharArray();
Array.Sort<char>(content);
return new string(content);
}
private void Sort(string[] array)
{
Dictionary<string, LinkedList<string>> hash = new Dictionary<string, LinkedList<string>>();
/* Group words by anagram */
foreach (string s in array)
{
string key = SortChars(s);
if (!hash.ContainsKey(key))
{
hash.Add(key, new LinkedList<string>());
}
LinkedList<string> anagrams = hash[key];
anagrams.AddLast(s);
}
/* Convert hash table to array */
int index = 0;
foreach (string key in hash.Keys)
{
LinkedList<string> list = hash[key];
foreach (string t in list)
{
array[index] = t;
index++;
}
}
}
public override void Run()
{
string[] array = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
Console.WriteLine(AssortedMethods.StringArrayToString(array));
Array.Sort(array, new AnagramComparator());
Console.WriteLine(AssortedMethods.StringArrayToString(array));
string[] array2 = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
Sort(array);
Console.WriteLine(AssortedMethods.StringArrayToString(array));
}
}
} | 31.594595 | 118 | 0.502566 | [
"Apache-2.0"
] | Kiandr/CrackingCodingInterview | CSharp/Ch 10. Sorting and Searching/Q10_02_Group_Anagrams.cs | 2,340 | C# |
using Pims.Api.Models.Parcel;
using System;
using System.Collections.Generic;
namespace Pims.Api.Areas.Project.Models.Dispose
{
public class BuildingModel : PropertyModel
{
#region Properties
public int ParcelId { get; set; }
public int BuildingConstructionTypeId { get; set; }
public string BuildingConstructionType { get; set; }
public int BuildingFloorCount { get; set; }
public int BuildingPredominateUseId { get; set; }
public string BuildingPredominateUse { get; set; }
public int BuildingOccupantTypeId { get; set; }
public string BuildingOccupantType { get; set; }
public DateTime? LeaseExpiry { get; set; }
public string OccupantName { get; set; }
public bool TransferLeaseOnSale { get; set; }
public string BuildingTenancy { get; set; }
public float RentableArea { get; set; }
public float LandArea { get; set; }
public string Zoning { get; set; }
public string ZoningPotential { get; set; }
public override string SubAgency { get; set; }
public IEnumerable<BuildingEvaluationModel> Evaluations { get; set; } = new List<BuildingEvaluationModel>();
public IEnumerable<BuildingFiscalModel> Fiscals { get; set; } = new List<BuildingFiscalModel>();
#endregion
}
}
| 27.38 | 116 | 0.655223 | [
"Apache-2.0"
] | Bruce451/PIMS | backend/api/Areas/Project/Models/Dispose/BuildingModel.cs | 1,369 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.ComponentModel.DataAnnotations;
namespace IdentityServer4.Quickstart.UI
{
public class RedirecAfterSuccessfullLoginModel
{
public string PersonId { get; set; }
public string ReturnUrl { get; set; }
}
} | 30.071429 | 107 | 0.731591 | [
"MIT"
] | karsten-kuepper/bcc-identity-server-dummy | src/Bcc.Members.Identity.Domain/Quickstart/Account/RedirecAfterSuccessfullLogin.cs | 421 | C# |
namespace TestHelper
{
using Microsoft.CodeAnalysis;
using System;
/// <summary>
/// Location where the diagnostic appears, as determined by path, line number, and column number.
/// </summary>
public struct DiagnosticResultLocation
{
public DiagnosticResultLocation(string path, int line, int column)
{
if (line < -1)
{
throw new ArgumentOutOfRangeException(nameof(line), "line must be >= -1");
}
if (column < -1)
{
throw new ArgumentOutOfRangeException(nameof(column), "column must be >= -1");
}
this.Path = path;
this.Line = line;
this.Column = column;
}
public string Path { get; }
public int Line { get; }
public int Column { get; }
}
/// <summary>
/// Struct that stores information about a Diagnostic appearing in a source
/// </summary>
public struct DiagnosticResult
{
private DiagnosticResultLocation[] locations;
public DiagnosticResultLocation[] Locations
{
get
{
if (this.locations == null)
{
this.locations = new DiagnosticResultLocation[] { };
}
return this.locations;
}
set
{
this.locations = value;
}
}
public DiagnosticSeverity Severity { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public string Path
{
get
{
return this.Locations.Length > 0 ? this.Locations[0].Path : "";
}
}
public int Line
{
get
{
return this.Locations.Length > 0 ? this.Locations[0].Line : -1;
}
}
public int Column
{
get
{
return this.Locations.Length > 0 ? this.Locations[0].Column : -1;
}
}
}
} | 24.551724 | 101 | 0.47706 | [
"MIT"
] | MSledzinski/DataContractAnalyzers | source/DataContractAnalyzer/DataContractAnalyzer.Test/Helpers/DiagnosticResult.cs | 2,138 | C# |
using FrontEnd.Data;
using FrontEnd.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FrontEnd.Repositories
{
[ExcludeFromCodeCoverage]
public class Repository<T> : IRepository<T> where T : class
{
protected ApplicationDbContext RepositoryContext { get; set; }
// dependency injection - inject the class here
public Repository(ApplicationDbContext repositoryContext)
{
RepositoryContext = repositoryContext;
}
public T Create(T entity)
{
return RepositoryContext.Set<T>().Add(entity).Entity;
}
public IEnumerable<T> FindAll()
{
// asnotracking added not to receive notifications every time we change something
return RepositoryContext.Set<T>().AsNoTracking();
}
public IEnumerable<T> FindByCondition(Expression<Func<T, bool>> expression)
{
return RepositoryContext.Set<T>().Where(expression).AsNoTracking();
}
}
} | 29.575 | 93 | 0.672866 | [
"MIT"
] | Andra1609/Magic8Ball | code/FrontEnd/Repositories/Repository.cs | 1,185 | C# |
using System;
using Xunit;
namespace tests.xunit.failing
{
public class FailingTheoryTests
{
// TEST: Should run all 3 tests, and should fail for all of them
[Theory]
[InlineData("fails", 6)]
[InlineData("failing", 1)]
[InlineData("fail as well", 13)]
public void EachTheoryThrowsAnException(string value, int expectedLength)
{
Console.WriteLine("OneFailingTheoryTest(" + value + ") with expected length of " + expectedLength);
Assert.Equal(expectedLength, value.Length);
}
// TEST: Should run all 3 tests
// TEST: "failing" should fail, all others should pass
[Theory]
[InlineData("works", 5)]
[InlineData("failing", 1)]
[InlineData("works as well", 13)]
public void OneFailingTheoryTest(string value, int expectedLength)
{
Console.WriteLine("OneFailingTheoryTest(" + value + ") with expected length of " + expectedLength);
Assert.Equal(expectedLength, value.Length);
}
}
} | 34.83871 | 111 | 0.606481 | [
"Apache-2.0"
] | derigel23/resharper-xunit | resharper/tests.manual/tests.xunit/FailingTheoryTests.cs | 1,080 | 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 BoletoNet {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Html {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Html() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BoletoNet.Html", typeof(Html).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap barra {
get {
object obj = ResourceManager.GetObject("barra", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap barrainterna {
get {
object obj = ResourceManager.GetObject("barrainterna", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to
/// <table class="w666">
/// <tr class="rBb">
/// <td class="Ac ld" colspan="4">Demonstrativo</td>
/// </tr>
/// <tr class="ct">
/// <td class="w62"></td>
/// <td class="w62"></td>
/// <td class="w62"></td>
/// <td class="w62"></td>
/// @ITENSDEMONSTRATIVO
/// </tr>
/// </table class="rBb td">
/// <table class="ctN w666">
/// <tr class="h13"><td /></tr>
/// <tr><td class="Ar">Corte na linha pontilhada</td></tr>
/// <tr><td class="cut" /></tr>
/// </table>
/// .
/// </summary>
internal static string CabecalhoTabelaDemonstrativo {
get {
return ResourceManager.GetString("CabecalhoTabelaDemonstrativo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table cellpadding="0" cellspacing="0">
/// <tr>
/// <td valign="top">
/// <table class="150">
/// <tr class="BHead">
/// <td class="imgLogo Al">
/// <img src="@URLIMAGEMLOGO" />
/// </td>
/// </tr>
/// </table>
/// <table class="w150">
/// <tr class="ct h13 At">
/// <td class="w298">
/// Beneficiário
/// </td>
/// </tr>
/// <tr class="cp h12 At rBb">
/// [rest of string was truncated]";.
/// </summary>
internal static string Carne {
get {
return ResourceManager.GetString("Carne", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr>
/// <td class="cpN BT1 Ar">Comprovante de Entrega</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega1 {
get {
return ResourceManager.GetString("ComprovanteEntrega1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="BHead">
/// <td class="imgLogo Al"><img src="@URLIMAGEMLOGO" /></td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w65 Ab bc Ac">@CODIGOBANCO-@DIGITOBANCO</td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w500 Ar ld" valign="bottom">Comprovante de Entrega</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega2 {
get {
return ResourceManager.GetString("ComprovanteEntrega2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w298">Beneficiário</td>
/// <td class="w126">Agência / Código do Cedente</td>
/// <td class="w106">Vencimento</td>
/// <td class="w106">Nº do Documento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@CEDENTE</td>
/// <td>@AGENCIACODIGOCEDENTE</td>
/// <td>@DATAVENCIMENTO</td>
/// <td class="Ar">@NUMERODOCUMENTO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega3 {
get {
return ResourceManager.GetString("ComprovanteEntrega3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w298">Pagador</td>
/// <td class="w126">Carteira / Nosso Número</td>
/// <td class="w106">Espécie</td>
/// <td class="w106">Valor do Documento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@SACADO</td>
/// <td>@NOSSONUMERO</td>
/// <td>@ESPECIE</td>
/// <td class="Ar">@=VALORDOCUMENTO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega4 {
get {
return ResourceManager.GetString("ComprovanteEntrega4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w544">Local de pagamento</td>
/// <td class="w106">Data de Processamento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@LOCALPAGAMENTO</td>
/// <td class="Ar">@DATAPROCESSAMENTO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega5 {
get {
return ResourceManager.GetString("ComprovanteEntrega5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w150">Recebi(emos) o bloqueto</td>
/// <td class="w104">Data</td>
/// <td class="w164">Assinatura</td>
/// <td class="w105">Data</td>
/// <td class="w106">Entregador</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td />
/// <td />
/// <td />
/// <td />
/// <td>&nbsp;</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ComprovanteEntrega6 {
get {
return ResourceManager.GetString("ComprovanteEntrega6", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ctN">
/// <td class="w666 pL6">Motivo de não entrega (para uso da empresa entregadora)</td>
/// </tr>
/// <tr>
/// <td>
/// <table class="cpN w666">
/// <tr>
/// <td class="w104 pL6">(&nbsp;&nbsp;)&nbsp;Mudou-se</td>
/// <td class="w104">(&nbsp;&nbsp;)&nbsp;Ausente</td>
/// <td>(&nbsp;&nbsp;)&nbsp;Não existe n. indicado</td>
/// <td>(&nbsp;&nbsp;)&nbsp;Recusado</td>
/// <td class="w104">(&nbsp;&nbsp;)&nbsp; [rest of string was truncated]";.
/// </summary>
internal static string ComprovanteEntrega7 {
get {
return ResourceManager.GetString("ComprovanteEntrega7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ctN">
/// <td class="w666 pL6">Observações (para uso da empresa entregadora)</td>
/// </tr>
/// <tr>
/// <td>
/// <table class="cpN w666">
/// <tr>
/// <td class="w104 pL6">&nbsp;</td>
/// <td class="w104">&nbsp;</td>
/// <td>&nbsp;</td>
/// <td>&nbsp;</td>
/// <td class="w104">&nbsp;</td>
/// </tr>
/// <tr>
/// <td class="pL6">&nbsp;</td>
/// <td>&nbsp;</td>
/// <td>&nbsp;</td>
/// <td>&nbsp;</td>
/// <td>&nbsp;</ [rest of string was truncated]";.
/// </summary>
internal static string ComprovanteEntrega71 {
get {
return ResourceManager.GetString("ComprovanteEntrega71", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap corte {
get {
object obj = ResourceManager.GetObject("corte", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to
/// <tr class="ct">
/// <td class="cp">@DESCRICAOGRUPO</td>
/// <td>@DESCRICAOITEM</td>
/// <td>@REFERENCIAITEM</td>
/// <td>@VALORITEM</td>
/// </tr>
/// .
/// </summary>
internal static string GrupoDemonstrativo {
get {
return ResourceManager.GetString("GrupoDemonstrativo", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="cpN">
/// <td class="At Ac">@TITULO</td>
/// </tr>
/// <tr class="ti">
/// <td class="At Ac">@INSTRUCAO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string Instrucoes {
get {
return ResourceManager.GetString("Instrucoes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap ponto {
get {
object obj = ResourceManager.GetObject("ponto", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to <table class="ctN w666">
/// <tr>
/// <td class="w666" />
/// </tr>
/// <tr>
/// <td class="Ar">Corte na linha pontilhada</td>
/// </tr>
/// <tr>
/// <td class="cut" />
/// </tr>
/// </table>
/// <br />.
/// </summary>
internal static string ReciboCedenteParte0 {
get {
return ResourceManager.GetString("ReciboCedenteParte0", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="BHead">
/// <td class="imgLogo Al"><img src="@URLIMAGEMLOGO" /></td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w65 Ab bc Ac">@CODIGOBANCO-@DIGITOBANCO</td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w500 Ar ld" valign="bottom">@LINHADIGITAVEL</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte1 {
get {
return ResourceManager.GetString("ReciboCedenteParte1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666 ctN">
/// <tr>
/// <td class="pL6 w409">Sacador / Avalista: @AVALISTA</td>
/// <td class="w250 Ar">Autenticação mecânica - <b class="cpN">Ficha de Compensação</b></td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte10 {
get {
return ResourceManager.GetString("ReciboCedenteParte10", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr>
/// <td class="EcdBar Al pL10">@IMAGEMCODIGOBARRA</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte11 {
get {
return ResourceManager.GetString("ReciboCedenteParte11", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="ctN w666">
/// <tr><td class="Ar">Corte na linha pontilhada</td></tr>
/// <tr><td class="cut" /></tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte12 {
get {
return ResourceManager.GetString("ReciboCedenteParte12", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w472">Beneficiário</td>
/// <td class="w180">Agência / Código Beneficiário</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@DADOSCEDENTE</td>
/// <td class="Ar">@AGENCIACONTA</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte13 {
get {
return ResourceManager.GetString("ReciboCedenteParte13", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w472">Local de pagamento</td>
/// <td class="w180">Vencimento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@LOCALPAGAMENTO</td>
/// <td class="Ar">@DATAVENCIMENTO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte2 {
get {
return ResourceManager.GetString("ReciboCedenteParte2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w472">Beneficiário</td>
/// <td class="w180">Agência / Código do Beneficiário</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@CEDENTE_BOLETO</td>
/// <td class="Ar">@AGENCIACONTA</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte3 {
get {
return ResourceManager.GetString("ReciboCedenteParte3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w113">Data do documento</td>
/// <td class="w163">N<u>o</u> documento</td>
/// <td class="w62">Espécie doc.</td>
/// <td class="w34">Aceite</td>
/// <td class="w72">Data processamento</td>
/// <td class="w180">Carteira / Nosso número</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@DATADOCUMENTO</td>
/// <td>@NUMERODOCUMENTO</td>
/// <td>@ESPECIEDOCUMENTO</td>
/// <td>@ACEITE</td>
/// <td>@DATAPROCESSAMENTO</t [rest of string was truncated]";.
/// </summary>
internal static string ReciboCedenteParte4 {
get {
return ResourceManager.GetString("ReciboCedenteParte4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w113">Uso do banco</td>
/// <td class="w83">Carteira</td>
/// <td class="w53">Espécie</td>
/// <td class="w123">Quantidade</td>
/// <td class="w72">(x) Valor</td>
/// <td class="w180">(=) Valor documento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@USODOBANCO</td>
/// <td class="Al">@CARTEIRA</td>
/// <td class="Al">@ESPECIE</td>
/// <td>@QUANTIDADE</td>
/// <td>@VALORDOCUMENTO</td>
/// <td class="Ar">@ [rest of string was truncated]";.
/// </summary>
internal static string ReciboCedenteParte5 {
get {
return ResourceManager.GetString("ReciboCedenteParte5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="rc6">
/// <td class="w478">
/// <div class="ctN pL10">Instruções (Texto de responsabilidade do beneficiário)</div>
/// <div class="cpN pL10 it" style="height:105px; overflow:hidden">@INSTRUCOES</div>
/// </td>
/// <td class="w186">
/// <div class="t">(-) Desconto / Abatimentos</div>
/// <div class="c BB">@DESCONTOS</div>
/// <div class="t">(-) Outras deduções</div>
/// <div class="c BB">@OUTRASDEDUCOES</div>
/// [rest of string was truncated]";.
/// </summary>
internal static string ReciboCedenteParte6 {
get {
return ResourceManager.GetString("ReciboCedenteParte6", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string ReciboCedenteParte7 {
get {
return ResourceManager.GetString("ReciboCedenteParte7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w659">Pagador</td>
/// </tr>
/// <tr class="cp h12">
/// <td class="At">@SACADO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte8 {
get {
return ResourceManager.GetString("ReciboCedenteParte8", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="rBb">
/// <td class="w478 BL">
/// <div class="cpN pL6">@INFOSACADO</div>
/// </td>
/// <td class="Ab BL">
/// <div class="ctN pL6">Cód. baixa</div>
/// </td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboCedenteParte9 {
get {
return ResourceManager.GetString("ReciboCedenteParte9", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to
/// <table class="w666">
/// <tr class="BHead BT2">
/// <td class="imgLogo Al"><img src="@URLIMAGEMLOGO" /></td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w65 Ab bc Ac">@CODIGOBANCO-@DIGITOBANCO</td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w500 Ar ld" valign="bottom">RECIBO DO SACADO</td>
/// </tr>
/// </table>
/// <table class="w666">
/// <tr class="ct h13">
/// <td>Local de pagamento</td>
/// <td></td>
/// </tr> [rest of string was truncated]";.
/// </summary>
internal static string ReciboCedenteRelatorioValores {
get {
return ResourceManager.GetString("ReciboCedenteRelatorioValores", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr>
/// <td class="ctN cut" />
/// </tr>
/// <tr>
/// <td class="cpN Ar">Recibo do Pagador</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte1 {
get {
return ResourceManager.GetString("ReciboSacadoParte1", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w659">Beneficiário Endereço / Sacador Avalista: @AVALISTA</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td class="At">@ENDERECOCEDENTE</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte10 {
get {
return ResourceManager.GetString("ReciboSacadoParte10", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w659">Beneficiário Endereço</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td class="At">@ENDERECOCEDENTE</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte10SemSacador {
get {
return ResourceManager.GetString("ReciboSacadoParte10SemSacador", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="BHead">
/// <td class="imgLogo Al"><img src="@URLIMGCEDENTE" /></td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w65 Ab bc Ac">@CODIGOBANCO-@DIGITOBANCO</td>
/// <td class="barra"><img src="@URLIMAGEMBARRA" /></td>
/// <td class="w500 Ar Ab ld">@LINHADIGITAVEL</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte2 {
get {
return ResourceManager.GetString("ReciboSacadoParte2", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13 At">
/// <td class="w298">Beneficiário</td>
/// <td class="w126">Agência / Código do Beneficiário</td>
/// <td class="w34">Espécie</td>
/// <td class="w45">Quantidade</td>
/// <td class="w128">Carteira / Nosso número</td>
/// </tr>
/// <tr class="cp h12 At rBb">
/// <td>@CEDENTE</td>
/// <td>@AGENCIACODIGOCEDENTE</td>
/// <td>@ESPECIE</td>
/// <td>@QUANTIDADE</td>
/// <td class="Ar">@NOSSONUMERO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte3 {
get {
return ResourceManager.GetString("ReciboSacadoParte3", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13 At">
/// <td class="w298">Beneficiário</td>
/// <td class="w126">Agência / Código do Beneficiário</td>
/// <td class="w34">Espécie</td>
/// <td class="w45">Quantidade</td>
/// <td class="w128">Nosso número</td>
/// </tr>
/// <tr class="cp h12 At rBb">
/// <td>@CEDENTE</td>
/// <td>@AGENCIACODIGOCEDENTE</td>
/// <td>@ESPECIE</td>
/// <td>@QUANTIDADE</td>
/// <td class="Ar">@NOSSONUMERO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte3SemCarteira {
get {
return ResourceManager.GetString("ReciboSacadoParte3SemCarteira", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w192">Número do documento</td>
/// <td class="w132">CPF/CNPJ</td>
/// <td class="w134">Vencimento</td>
/// <td class="w180">Valor documento</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@NUMERODOCUMENTO</td>
/// <td>@CPFCNPJ</td>
/// <td>@DATAVENCIMENTO</td>
/// <td class="Ar">@=VALORDOCUMENTO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte4 {
get {
return ResourceManager.GetString("ReciboSacadoParte4", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w113">(-) Desconto / Abatimentos</td>
/// <td class="w112">(-) Outras deduções</td>
/// <td class="w113">(+) Mora / Multa</td>
/// <td class="w113">(+) Outros acréscimos</td>
/// <td class="w180">(=) Valor cobrado</td>
/// </tr>
/// <tr class="cp h12 rBb Ab">
/// <td>@DESCONTOS</td>
/// <td>@OUTRASDEDUCOES</td>
/// <td>@MORAMULTA</td>
/// <td>@OUTROSACRESCIMOS</td>
/// <td class="Ar">&nbsp;@VALORCOBRADO</td>
/// </ [rest of string was truncated]";.
/// </summary>
internal static string ReciboSacadoParte5 {
get {
return ResourceManager.GetString("ReciboSacadoParte5", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ct h13">
/// <td class="w659">Pagador</td>
/// </tr>
/// <tr class="cp h12">
/// <td>@SACADO</td>
/// </tr>
/// <tr class="cp h12 rBb">
/// <td>@INFOSACADO</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte6 {
get {
return ResourceManager.GetString("ReciboSacadoParte6", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="w666">
/// <tr class="ctN h13">
/// <td class="pL6">Instruções</td>
/// <td class="w180 Ar">Autenticação mecânica</td>
/// </tr>
/// <tr class="cpN h12">
/// <td class="pL6 it">@INSTRUCOES</td>
/// <td class="pL6 Ar">@AUTENTICACAOMECANICA</td>
/// </tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte7 {
get {
return ResourceManager.GetString("ReciboSacadoParte7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to <table class="ctN w666">
/// <tr class="h13"><td /></tr>
/// <tr class="h13"><td /></tr>
/// <tr><td class="Ar">Corte na linha pontilhada</td></tr>
/// <tr><td class="cut" /></tr>
/// <tr class="h13"><td /></tr>
/// <tr class="h13"><td /></tr>
/// </table>.
/// </summary>
internal static string ReciboSacadoParte8 {
get {
return ResourceManager.GetString("ReciboSacadoParte8", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to
/// <tr class="cp h13 rBb">
/// <td>Total</td>
/// <td></td>
/// <td></td>
/// <td>@VALORTOTALGRUPO</td>
/// </tr>
/// .
/// </summary>
internal static string TotalDemonstrativo {
get {
return ResourceManager.GetString("TotalDemonstrativo", resourceCulture);
}
}
}
}
| 47.295374 | 156 | 0.497065 | [
"Apache-2.0"
] | TronInformatica/boletonet | src/Boleto.Net/Html.Designer.cs | 39,930 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.Salesforce
{
public class SalesforceAuthenticationOptions : AuthenticationOptions
{
public class SalesforceAuthenticationEndpoints
{
/// <summary>
/// Endpoint which is used to redirect users to request Salesforce access
/// </summary>
public string AuthorizationEndpoint { get; set; }
/// <summary>
/// Endpoint which is used to exchange code for access token
/// </summary>
public string TokenEndpoint { get; set; }
}
private const string AuthorizationEndPoint = "";
private const string TokenEndpoint = "";
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to Salesforce.
/// </summary>
/// <value>
/// The pinned certificate validator.
/// </value>
/// <remarks>
/// If this property is null then the default certificate checks are performed,
/// validating the subject name and if the signing chain is a trusted party.
/// </remarks>
public ICertificateValidator BackchannelCertificateValidator { get; set; }
/// <summary>
/// The HttpMessageHandler used to communicate with Salesforce.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with Salesforce.
/// </summary>
/// <value>
/// The back channel timeout in milliseconds.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// Default value is "/signin-Salesforce".
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string Caption
{
get { return Description.Caption; }
set { Description.Caption = value; }
}
/// <summary>
/// Gets or sets the Salesforce supplied Client ID
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the Salesforce supplied Client Secret
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// Gets the sets of OAuth endpoints used to authenticate against Salesforce. Overriding these endpoints allows you to use Salesforce Enterprise for
/// authentication.
/// </summary>
public SalesforceAuthenticationEndpoints Endpoints { get; set; }
/// <summary>
/// Gets or sets the <see cref="ISalesforceAuthenticationProvider" /> used in the authentication events
/// </summary>
public ISalesforceAuthenticationProvider Provider { get; set; }
/// <summary>
/// A list of permissions to request.
/// </summary>
public IList<string> Scope { get; private set; }
/// <summary>
/// Specifies how the authorization server prompts the user for reauthentication and reapproval. This parameter is optional.
/// The only values Salesforce supports are:
/// login—The authorization server must prompt the user for reauthentication, forcing the user to log in again.
/// consent—The authorization server must prompt the user for reapproval before returning information to the client.
/// It is valid to pass both values, separated by a space, to require the user to both log in and reauthorize.
/// </summary>
public string Prompt { get; set; }
/// <summary>
/// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user
/// <see cref="System.Security.Claims.ClaimsIdentity" />.
/// </summary>
public string SignInAsAuthenticationType { get; set; }
/// <summary>
/// Gets or sets the type used to secure data handled by the middleware.
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
/// <summary>
/// Initializes a new <see cref="SalesforceAuthenticationOptions" />
/// </summary>
public SalesforceAuthenticationOptions()
: base("Salesforce")
{
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-salesforce");
AuthenticationMode = AuthenticationMode.Passive;
Scope = new List<string> { "id" };
BackchannelTimeout = TimeSpan.FromSeconds(60);
Endpoints = new SalesforceAuthenticationEndpoints
{
AuthorizationEndpoint = AuthorizationEndPoint,
TokenEndpoint = TokenEndpoint
};
}
}
} | 41.6 | 157 | 0.609509 | [
"MIT"
] | gavinharriss/OwinOAuthProviders | src/Owin.Security.Providers.Salesforce/SalesforceAuthenticationOptions.cs | 5,622 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codebuild-2016-10-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CodeBuild.Model
{
/// <summary>
/// Information about a build.
/// </summary>
public partial class Build
{
private string _arn;
private BuildArtifacts _artifacts;
private string _buildBatchArn;
private bool? _buildComplete;
private long? _buildNumber;
private StatusType _buildStatus;
private ProjectCache _cache;
private string _currentPhase;
private DebugSession _debugSession;
private string _encryptionKey;
private DateTime? _endTime;
private ProjectEnvironment _environment;
private List<ExportedEnvironmentVariable> _exportedEnvironmentVariables = new List<ExportedEnvironmentVariable>();
private List<ProjectFileSystemLocation> _fileSystemLocations = new List<ProjectFileSystemLocation>();
private string _id;
private string _initiator;
private LogsLocation _logs;
private NetworkInterface _networkInterface;
private List<BuildPhase> _phases = new List<BuildPhase>();
private string _projectName;
private int? _queuedTimeoutInMinutes;
private List<string> _reportArns = new List<string>();
private string _resolvedSourceVersion;
private List<BuildArtifacts> _secondaryArtifacts = new List<BuildArtifacts>();
private List<ProjectSource> _secondarySources = new List<ProjectSource>();
private List<ProjectSourceVersion> _secondarySourceVersions = new List<ProjectSourceVersion>();
private string _serviceRole;
private ProjectSource _source;
private string _sourceVersion;
private DateTime? _startTime;
private int? _timeoutInMinutes;
private VpcConfig _vpcConfig;
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The Amazon Resource Name (ARN) of the build.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Artifacts.
/// <para>
/// Information about the output artifacts for the build.
/// </para>
/// </summary>
public BuildArtifacts Artifacts
{
get { return this._artifacts; }
set { this._artifacts = value; }
}
// Check to see if Artifacts property is set
internal bool IsSetArtifacts()
{
return this._artifacts != null;
}
/// <summary>
/// Gets and sets the property BuildBatchArn.
/// <para>
/// The ARN of the batch build that this build is a member of, if applicable.
/// </para>
/// </summary>
public string BuildBatchArn
{
get { return this._buildBatchArn; }
set { this._buildBatchArn = value; }
}
// Check to see if BuildBatchArn property is set
internal bool IsSetBuildBatchArn()
{
return this._buildBatchArn != null;
}
/// <summary>
/// Gets and sets the property BuildComplete.
/// <para>
/// Whether the build is complete. True if complete; otherwise, false.
/// </para>
/// </summary>
public bool BuildComplete
{
get { return this._buildComplete.GetValueOrDefault(); }
set { this._buildComplete = value; }
}
// Check to see if BuildComplete property is set
internal bool IsSetBuildComplete()
{
return this._buildComplete.HasValue;
}
/// <summary>
/// Gets and sets the property BuildNumber.
/// <para>
/// The number of the build. For each project, the <code>buildNumber</code> of its first
/// build is <code>1</code>. The <code>buildNumber</code> of each subsequent build is
/// incremented by <code>1</code>. If a build is deleted, the <code>buildNumber</code>
/// of other builds does not change.
/// </para>
/// </summary>
public long BuildNumber
{
get { return this._buildNumber.GetValueOrDefault(); }
set { this._buildNumber = value; }
}
// Check to see if BuildNumber property is set
internal bool IsSetBuildNumber()
{
return this._buildNumber.HasValue;
}
/// <summary>
/// Gets and sets the property BuildStatus.
/// <para>
/// The current status of the build. Valid values include:
/// </para>
/// <ul> <li>
/// <para>
/// <code>FAILED</code>: The build failed.
/// </para>
/// </li> <li>
/// <para>
/// <code>FAULT</code>: The build faulted.
/// </para>
/// </li> <li>
/// <para>
/// <code>IN_PROGRESS</code>: The build is still in progress.
/// </para>
/// </li> <li>
/// <para>
/// <code>STOPPED</code>: The build stopped.
/// </para>
/// </li> <li>
/// <para>
/// <code>SUCCEEDED</code>: The build succeeded.
/// </para>
/// </li> <li>
/// <para>
/// <code>TIMED_OUT</code>: The build timed out.
/// </para>
/// </li> </ul>
/// </summary>
public StatusType BuildStatus
{
get { return this._buildStatus; }
set { this._buildStatus = value; }
}
// Check to see if BuildStatus property is set
internal bool IsSetBuildStatus()
{
return this._buildStatus != null;
}
/// <summary>
/// Gets and sets the property Cache.
/// <para>
/// Information about the cache for the build.
/// </para>
/// </summary>
public ProjectCache Cache
{
get { return this._cache; }
set { this._cache = value; }
}
// Check to see if Cache property is set
internal bool IsSetCache()
{
return this._cache != null;
}
/// <summary>
/// Gets and sets the property CurrentPhase.
/// <para>
/// The current build phase.
/// </para>
/// </summary>
public string CurrentPhase
{
get { return this._currentPhase; }
set { this._currentPhase = value; }
}
// Check to see if CurrentPhase property is set
internal bool IsSetCurrentPhase()
{
return this._currentPhase != null;
}
/// <summary>
/// Gets and sets the property DebugSession.
/// <para>
/// Contains information about the debug session for this build.
/// </para>
/// </summary>
public DebugSession DebugSession
{
get { return this._debugSession; }
set { this._debugSession = value; }
}
// Check to see if DebugSession property is set
internal bool IsSetDebugSession()
{
return this._debugSession != null;
}
/// <summary>
/// Gets and sets the property EncryptionKey.
/// <para>
/// The AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for
/// encrypting the build output artifacts.
/// </para>
/// <note>
/// <para>
/// You can use a cross-account KMS key to encrypt the build output artifacts if your
/// service role has permission to that key.
/// </para>
/// </note>
/// <para>
/// You can specify either the Amazon Resource Name (ARN) of the CMK or, if available,
/// the CMK's alias (using the format <code>alias/<alias-name></code>).
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string EncryptionKey
{
get { return this._encryptionKey; }
set { this._encryptionKey = value; }
}
// Check to see if EncryptionKey property is set
internal bool IsSetEncryptionKey()
{
return this._encryptionKey != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// When the build process ended, expressed in Unix time format.
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property Environment.
/// <para>
/// Information about the build environment for this build.
/// </para>
/// </summary>
public ProjectEnvironment Environment
{
get { return this._environment; }
set { this._environment = value; }
}
// Check to see if Environment property is set
internal bool IsSetEnvironment()
{
return this._environment != null;
}
/// <summary>
/// Gets and sets the property ExportedEnvironmentVariables.
/// <para>
/// A list of exported environment variables for this build.
/// </para>
/// </summary>
public List<ExportedEnvironmentVariable> ExportedEnvironmentVariables
{
get { return this._exportedEnvironmentVariables; }
set { this._exportedEnvironmentVariables = value; }
}
// Check to see if ExportedEnvironmentVariables property is set
internal bool IsSetExportedEnvironmentVariables()
{
return this._exportedEnvironmentVariables != null && this._exportedEnvironmentVariables.Count > 0;
}
/// <summary>
/// Gets and sets the property FileSystemLocations.
/// <para>
/// An array of <code>ProjectFileSystemLocation</code> objects for a CodeBuild build
/// project. A <code>ProjectFileSystemLocation</code> object specifies the <code>identifier</code>,
/// <code>location</code>, <code>mountOptions</code>, <code>mountPoint</code>, and <code>type</code>
/// of a file system created using Amazon Elastic File System.
/// </para>
/// </summary>
public List<ProjectFileSystemLocation> FileSystemLocations
{
get { return this._fileSystemLocations; }
set { this._fileSystemLocations = value; }
}
// Check to see if FileSystemLocations property is set
internal bool IsSetFileSystemLocations()
{
return this._fileSystemLocations != null && this._fileSystemLocations.Count > 0;
}
/// <summary>
/// Gets and sets the property Id.
/// <para>
/// The unique ID for the build.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property Initiator.
/// <para>
/// The entity that started the build. Valid values include:
/// </para>
/// <ul> <li>
/// <para>
/// If AWS CodePipeline started the build, the pipeline's name (for example, <code>codepipeline/my-demo-pipeline</code>).
/// </para>
/// </li> <li>
/// <para>
/// If an AWS Identity and Access Management (IAM) user started the build, the user's
/// name (for example, <code>MyUserName</code>).
/// </para>
/// </li> <li>
/// <para>
/// If the Jenkins plugin for AWS CodeBuild started the build, the string <code>CodeBuild-Jenkins-Plugin</code>.
/// </para>
/// </li> </ul>
/// </summary>
public string Initiator
{
get { return this._initiator; }
set { this._initiator = value; }
}
// Check to see if Initiator property is set
internal bool IsSetInitiator()
{
return this._initiator != null;
}
/// <summary>
/// Gets and sets the property Logs.
/// <para>
/// Information about the build's logs in Amazon CloudWatch Logs.
/// </para>
/// </summary>
public LogsLocation Logs
{
get { return this._logs; }
set { this._logs = value; }
}
// Check to see if Logs property is set
internal bool IsSetLogs()
{
return this._logs != null;
}
/// <summary>
/// Gets and sets the property NetworkInterface.
/// <para>
/// Describes a network interface.
/// </para>
/// </summary>
public NetworkInterface NetworkInterface
{
get { return this._networkInterface; }
set { this._networkInterface = value; }
}
// Check to see if NetworkInterface property is set
internal bool IsSetNetworkInterface()
{
return this._networkInterface != null;
}
/// <summary>
/// Gets and sets the property Phases.
/// <para>
/// Information about all previous build phases that are complete and information about
/// any current build phase that is not yet complete.
/// </para>
/// </summary>
public List<BuildPhase> Phases
{
get { return this._phases; }
set { this._phases = value; }
}
// Check to see if Phases property is set
internal bool IsSetPhases()
{
return this._phases != null && this._phases.Count > 0;
}
/// <summary>
/// Gets and sets the property ProjectName.
/// <para>
/// The name of the AWS CodeBuild project.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string ProjectName
{
get { return this._projectName; }
set { this._projectName = value; }
}
// Check to see if ProjectName property is set
internal bool IsSetProjectName()
{
return this._projectName != null;
}
/// <summary>
/// Gets and sets the property QueuedTimeoutInMinutes.
/// <para>
/// The number of minutes a build is allowed to be queued before it times out.
/// </para>
/// </summary>
public int QueuedTimeoutInMinutes
{
get { return this._queuedTimeoutInMinutes.GetValueOrDefault(); }
set { this._queuedTimeoutInMinutes = value; }
}
// Check to see if QueuedTimeoutInMinutes property is set
internal bool IsSetQueuedTimeoutInMinutes()
{
return this._queuedTimeoutInMinutes.HasValue;
}
/// <summary>
/// Gets and sets the property ReportArns.
/// <para>
/// An array of the ARNs associated with this build's reports.
/// </para>
/// </summary>
public List<string> ReportArns
{
get { return this._reportArns; }
set { this._reportArns = value; }
}
// Check to see if ReportArns property is set
internal bool IsSetReportArns()
{
return this._reportArns != null && this._reportArns.Count > 0;
}
/// <summary>
/// Gets and sets the property ResolvedSourceVersion.
/// <para>
/// An identifier for the version of this build's source code.
/// </para>
/// <ul> <li>
/// <para>
/// For AWS CodeCommit, GitHub, GitHub Enterprise, and BitBucket, the commit ID.
/// </para>
/// </li> <li>
/// <para>
/// For AWS CodePipeline, the source revision provided by AWS CodePipeline.
/// </para>
/// </li> <li>
/// <para>
/// For Amazon Simple Storage Service (Amazon S3), this does not apply.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Min=1)]
public string ResolvedSourceVersion
{
get { return this._resolvedSourceVersion; }
set { this._resolvedSourceVersion = value; }
}
// Check to see if ResolvedSourceVersion property is set
internal bool IsSetResolvedSourceVersion()
{
return this._resolvedSourceVersion != null;
}
/// <summary>
/// Gets and sets the property SecondaryArtifacts.
/// <para>
/// An array of <code>ProjectArtifacts</code> objects.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=12)]
public List<BuildArtifacts> SecondaryArtifacts
{
get { return this._secondaryArtifacts; }
set { this._secondaryArtifacts = value; }
}
// Check to see if SecondaryArtifacts property is set
internal bool IsSetSecondaryArtifacts()
{
return this._secondaryArtifacts != null && this._secondaryArtifacts.Count > 0;
}
/// <summary>
/// Gets and sets the property SecondarySources.
/// <para>
/// An array of <code>ProjectSource</code> objects.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=12)]
public List<ProjectSource> SecondarySources
{
get { return this._secondarySources; }
set { this._secondarySources = value; }
}
// Check to see if SecondarySources property is set
internal bool IsSetSecondarySources()
{
return this._secondarySources != null && this._secondarySources.Count > 0;
}
/// <summary>
/// Gets and sets the property SecondarySourceVersions.
/// <para>
/// An array of <code>ProjectSourceVersion</code> objects. Each <code>ProjectSourceVersion</code>
/// must be one of:
/// </para>
/// <ul> <li>
/// <para>
/// For AWS CodeCommit: the commit ID, branch, or Git tag to use.
/// </para>
/// </li> <li>
/// <para>
/// For GitHub: the commit ID, pull request ID, branch name, or tag name that corresponds
/// to the version of the source code you want to build. If a pull request ID is specified,
/// it must use the format <code>pr/pull-request-ID</code> (for example, <code>pr/25</code>).
/// If a branch name is specified, the branch's HEAD commit ID is used. If not specified,
/// the default branch's HEAD commit ID is used.
/// </para>
/// </li> <li>
/// <para>
/// For Bitbucket: the commit ID, branch name, or tag name that corresponds to the version
/// of the source code you want to build. If a branch name is specified, the branch's
/// HEAD commit ID is used. If not specified, the default branch's HEAD commit ID is used.
/// </para>
/// </li> <li>
/// <para>
/// For Amazon Simple Storage Service (Amazon S3): the version ID of the object that represents
/// the build input ZIP file to use.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Min=0, Max=12)]
public List<ProjectSourceVersion> SecondarySourceVersions
{
get { return this._secondarySourceVersions; }
set { this._secondarySourceVersions = value; }
}
// Check to see if SecondarySourceVersions property is set
internal bool IsSetSecondarySourceVersions()
{
return this._secondarySourceVersions != null && this._secondarySourceVersions.Count > 0;
}
/// <summary>
/// Gets and sets the property ServiceRole.
/// <para>
/// The name of a service role used for this build.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string ServiceRole
{
get { return this._serviceRole; }
set { this._serviceRole = value; }
}
// Check to see if ServiceRole property is set
internal bool IsSetServiceRole()
{
return this._serviceRole != null;
}
/// <summary>
/// Gets and sets the property Source.
/// <para>
/// Information about the source code to be built.
/// </para>
/// </summary>
public ProjectSource Source
{
get { return this._source; }
set { this._source = value; }
}
// Check to see if Source property is set
internal bool IsSetSource()
{
return this._source != null;
}
/// <summary>
/// Gets and sets the property SourceVersion.
/// <para>
/// Any version identifier for the version of the source code to be built. If <code>sourceVersion</code>
/// is specified at the project level, then this <code>sourceVersion</code> (at the build
/// level) takes precedence.
/// </para>
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/sample-source-version.html">Source
/// Version Sample with CodeBuild</a> in the <i>AWS CodeBuild User Guide</i>.
/// </para>
/// </summary>
[AWSProperty(Min=1)]
public string SourceVersion
{
get { return this._sourceVersion; }
set { this._sourceVersion = value; }
}
// Check to see if SourceVersion property is set
internal bool IsSetSourceVersion()
{
return this._sourceVersion != null;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// When the build process started, expressed in Unix time format.
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
/// <summary>
/// Gets and sets the property TimeoutInMinutes.
/// <para>
/// How long, in minutes, for AWS CodeBuild to wait before timing out this build if it
/// does not get marked as completed.
/// </para>
/// </summary>
public int TimeoutInMinutes
{
get { return this._timeoutInMinutes.GetValueOrDefault(); }
set { this._timeoutInMinutes = value; }
}
// Check to see if TimeoutInMinutes property is set
internal bool IsSetTimeoutInMinutes()
{
return this._timeoutInMinutes.HasValue;
}
/// <summary>
/// Gets and sets the property VpcConfig.
/// <para>
/// If your AWS CodeBuild project accesses resources in an Amazon VPC, you provide this
/// parameter that identifies the VPC ID and the list of security group IDs and subnet
/// IDs. The security groups and subnets must belong to the same VPC. You must provide
/// at least one security group and one subnet ID.
/// </para>
/// </summary>
public VpcConfig VpcConfig
{
get { return this._vpcConfig; }
set { this._vpcConfig = value; }
}
// Check to see if VpcConfig property is set
internal bool IsSetVpcConfig()
{
return this._vpcConfig != null;
}
}
} | 33.360892 | 137 | 0.548405 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeBuild/Generated/Model/Build.cs | 25,421 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TitleParent : MonoBehaviour
{
public GameObject parent;
public List<TitleAnim> children;
void Update()
{
if (parent.activeInHierarchy == false)
{
foreach (TitleAnim i in children)
{
i.gameObject.SetActive(false);
i.localscale = i.startscale;
i.xreached = false;
i.yreached = false;
i.finished = false;
i.delay = i.dc;
}
}
if (parent.activeInHierarchy != false)
{
foreach (TitleAnim i in children)
{
i.gameObject.SetActive(true);
}
}
}
}
| 23.088235 | 46 | 0.505732 | [
"MIT"
] | AGGP-NHTI/Capstone2021-RocketJump | Assets/Core/Scripts/Menu Scripts/TitleParent.cs | 787 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HotChocolate.Validation.Properties {
using System;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static System.Resources.ResourceManager resourceMan;
private static System.Globalization.CultureInfo resourceCulture;
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Resources.ResourceManager ResourceManager {
get {
if (object.Equals(null, resourceMan)) {
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("HotChocolate.Validation.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string ServiceCollectionExtensions_Schema_Name_Is_Mandatory {
get {
return ResourceManager.GetString("ServiceCollectionExtensions_Schema_Name_Is_Mandatory", resourceCulture);
}
}
internal static string DefaultDocumentValidatorFactory_Schema_Name_Is_Mandatory {
get {
return ResourceManager.GetString("DefaultDocumentValidatorFactory_Schema_Name_Is_Mandatory", resourceCulture);
}
}
internal static string DocumentValidatorContext_Context_Invalid_State {
get {
return ResourceManager.GetString("DocumentValidatorContext_Context_Invalid_State", resourceCulture);
}
}
internal static string ErrorHelper_VariableIsNotCompatible {
get {
return ResourceManager.GetString("ErrorHelper_VariableIsNotCompatible", resourceCulture);
}
}
internal static string ErrorHelper_DirectiveNotValidInLocation {
get {
return ResourceManager.GetString("ErrorHelper_DirectiveNotValidInLocation", resourceCulture);
}
}
internal static string ErrorHelper_DirectiveNotSupported {
get {
return ResourceManager.GetString("ErrorHelper_DirectiveNotSupported", resourceCulture);
}
}
internal static string ErrorHelper_TypeSystemDefinitionNotAllowed {
get {
return ResourceManager.GetString("ErrorHelper_TypeSystemDefinitionNotAllowed", resourceCulture);
}
}
internal static string ErrorHelper_UnionFieldError {
get {
return ResourceManager.GetString("ErrorHelper_UnionFieldError", resourceCulture);
}
}
internal static string ErrorHelper_FieldDoesNotExist {
get {
return ResourceManager.GetString("ErrorHelper_FieldDoesNotExist", resourceCulture);
}
}
internal static string ErrorHelper_LeafFieldsCannotHaveSelections {
get {
return ResourceManager.GetString("ErrorHelper_LeafFieldsCannotHaveSelections", resourceCulture);
}
}
internal static string ErrorHelper_ArgumentValueIsNotCompatible {
get {
return ResourceManager.GetString("ErrorHelper_ArgumentValueIsNotCompatible", resourceCulture);
}
}
internal static string ErrorHelper_FieldValueIsNotCompatible {
get {
return ResourceManager.GetString("ErrorHelper_FieldValueIsNotCompatible", resourceCulture);
}
}
internal static string ErrorHelper_VariableDefaultValueIsNotCompatible {
get {
return ResourceManager.GetString("ErrorHelper_VariableDefaultValueIsNotCompatible", resourceCulture);
}
}
internal static string ErrorHelper_NoSelectionOnCompositeField {
get {
return ResourceManager.GetString("ErrorHelper_NoSelectionOnCompositeField", resourceCulture);
}
}
internal static string ErrorHelper_FieldIsRequiredButNull {
get {
return ResourceManager.GetString("ErrorHelper_FieldIsRequiredButNull", resourceCulture);
}
}
internal static string ErrorHelper_FieldsAreNotMergable {
get {
return ResourceManager.GetString("ErrorHelper_FieldsAreNotMergable", resourceCulture);
}
}
internal static string ErrorHelper_FragmentNameNotUnique {
get {
return ResourceManager.GetString("ErrorHelper_FragmentNameNotUnique", resourceCulture);
}
}
internal static string ErrorHelper_FragmentNotUsed {
get {
return ResourceManager.GetString("ErrorHelper_FragmentNotUsed", resourceCulture);
}
}
internal static string ErrorHelper_FragmentCycleDetected {
get {
return ResourceManager.GetString("ErrorHelper_FragmentCycleDetected", resourceCulture);
}
}
internal static string ErrorHelper_FragmentDoesNotExist {
get {
return ResourceManager.GetString("ErrorHelper_FragmentDoesNotExist", resourceCulture);
}
}
internal static string ErrorHelper_FragmentNotPossible {
get {
return ResourceManager.GetString("ErrorHelper_FragmentNotPossible", resourceCulture);
}
}
internal static string ErrorHelper_FragmentTypeConditionUnknown {
get {
return ResourceManager.GetString("ErrorHelper_FragmentTypeConditionUnknown", resourceCulture);
}
}
internal static string ErrorHelper_FragmentOnlyCompositeType {
get {
return ResourceManager.GetString("ErrorHelper_FragmentOnlyCompositeType", resourceCulture);
}
}
internal static string ErrorHelper_InputFieldAmbiguous {
get {
return ResourceManager.GetString("ErrorHelper_InputFieldAmbiguous", resourceCulture);
}
}
internal static string ErrorHelper_InputFieldDoesNotExist {
get {
return ResourceManager.GetString("ErrorHelper_InputFieldDoesNotExist", resourceCulture);
}
}
internal static string ErrorHelper_InputFieldRequired {
get {
return ResourceManager.GetString("ErrorHelper_InputFieldRequired", resourceCulture);
}
}
internal static string ErrorHelper_OperationNameNotUnique {
get {
return ResourceManager.GetString("ErrorHelper_OperationNameNotUnique", resourceCulture);
}
}
internal static string ErrorHelper_OperationAnonymousMoreThanOne {
get {
return ResourceManager.GetString("ErrorHelper_OperationAnonymousMoreThanOne", resourceCulture);
}
}
internal static string ErrorHelper_VariableNotInputType {
get {
return ResourceManager.GetString("ErrorHelper_VariableNotInputType", resourceCulture);
}
}
internal static string ErrorHelper_VariableNameNotUnique {
get {
return ResourceManager.GetString("ErrorHelper_VariableNameNotUnique", resourceCulture);
}
}
internal static string ErrorHelper_ArgumentNotUnique {
get {
return ResourceManager.GetString("ErrorHelper_ArgumentNotUnique", resourceCulture);
}
}
internal static string ErrorHelper_ArgumentRequired {
get {
return ResourceManager.GetString("ErrorHelper_ArgumentRequired", resourceCulture);
}
}
internal static string ErrorHelper_ArgumentDoesNotExist {
get {
return ResourceManager.GetString("ErrorHelper_ArgumentDoesNotExist", resourceCulture);
}
}
internal static string ErrorHelper_SubscriptionSingleRootField {
get {
return ResourceManager.GetString("ErrorHelper_SubscriptionSingleRootField", resourceCulture);
}
}
internal static string ErrorHelper_MaxOperationComplexity {
get {
return ResourceManager.GetString("ErrorHelper_MaxOperationComplexity", resourceCulture);
}
}
internal static string HotChocolateValidationBuilderExtensions_MinimumAllowedValue {
get {
return ResourceManager.GetString("HotChocolateValidationBuilderExtensions_MinimumAllowedValue", resourceCulture);
}
}
}
}
| 38.516981 | 173 | 0.612619 | [
"MIT"
] | GraemeF/hotchocolate | src/HotChocolate/Core/src/Validation/Properties/Resources.Designer.cs | 10,209 | C# |
using Microsoft.Win32;
using Playnite.SDK;
using Playnite.Native;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Playnite.Common
{
public class SystemInfo
{
public bool Is64Bit { get; set; }
public string WindowsVersion { get; set; }
public string WindowsEdition { get; set; }
public int WindowsBuildVersion { get; set; }
public string Cpu { get; set; }
public int Ram { get; set; }
public List<string> Gpus { get; set; }
public List<ComputerScreen> Screens { get; set; }
}
public class ComputerScreen
{
public System.Drawing.Rectangle WorkingArea { get; private set; }
public bool Primary { get; private set; }
public string DeviceName { get; private set; }
public System.Drawing.Rectangle Bounds { get; private set; }
public int BitsPerPixel { get; private set; }
public ComputerScreen()
{
}
public ComputerScreen(Screen screen)
{
WorkingArea = screen.WorkingArea;
Primary = screen.Primary;
DeviceName = screen.DeviceFriendlyName();
Bounds = screen.Bounds;
BitsPerPixel = screen.BitsPerPixel;
}
}
public enum WindowsVersion
{
Unknown,
Win7,
Win8,
Win10
}
public enum HwCompany
{
Intel,
AMD,
Nvidia,
VMware,
Uknown
}
public static class Computer
{
private static readonly ILogger logger = LogManager.GetLogger();
public static WindowsVersion WindowsVersion
{
get
{
var version = Environment.OSVersion.Version;
if (version.Major == 6 && version.Major == 1)
{
return WindowsVersion.Win7;
}
else if (version.Major == 6 && (version.Major == 2 || version.Major == 3))
{
return WindowsVersion.Win8;
}
else if (version.Major == 10)
{
return WindowsVersion.Win10;
}
else
{
return WindowsVersion.Unknown;
}
}
}
public static bool IsTLS13SystemWideEnabled()
{
try
{
using (var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.3\Client"))
{
if (key != null)
{
var isEnabled = key.GetValue("Enabled");
if (isEnabled != null)
{
return Convert.ToBoolean(isEnabled);
}
}
}
}
catch (Exception e)
{
logger.Error(e, "Failed to test TLS 1.3 state.");
}
return false;
}
public static int GetWindowsReleaseId()
{
var relVal = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "");
if (relVal?.ToString().IsNullOrEmpty() == true)
{
return 0;
}
else
{
return Convert.ToInt32(relVal);
}
}
public static string GetWindowsProductName()
{
return Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString();
}
public static Guid GetMachineGuid()
{
RegistryKey root = null;
if (Environment.Is64BitOperatingSystem)
{
root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
}
else
{
root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
}
try
{
using (var cryptography = root.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography"))
{
return Guid.Parse((string)cryptography.GetValue("MachineGuid"));
}
}
finally
{
root.Dispose();
}
}
public static SystemInfo GetSystemInfo()
{
var info = new SystemInfo
{
Is64Bit = Environment.Is64BitOperatingSystem,
WindowsVersion = Environment.OSVersion.VersionString,
WindowsBuildVersion = GetWindowsReleaseId(),
WindowsEdition = GetWindowsProductName()
};
using (var win32Proc = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"))
{
foreach (var obj in win32Proc.Get())
{
info.Cpu = obj["Name"].ToString().Trim();
break;
}
}
using (var memory = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory"))
{
double totalCapacity = 0;
foreach (var obj in memory.Get())
{
totalCapacity += Convert.ToDouble(obj["Capacity"]);
}
info.Ram = Convert.ToInt32(totalCapacity / 1048576);
}
using (var video = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"))
{
info.Gpus = new List<string>();
foreach (var obj in video.Get())
{
info.Gpus.Add(obj["Name"].ToString());
}
}
info.Screens = GetScreens();
return info;
}
public static List<ComputerScreen> GetScreens()
{
return Screen.AllScreens.Select(a => a.ToComputerScreen()).ToList();
}
public static ComputerScreen GetPrimaryScreen()
{
return Screen.PrimaryScreen?.ToComputerScreen();
}
public static int GetGetPrimaryScreenIndex()
{
var allScreens = Screen.AllScreens;
for (int i = 0; i < allScreens.Length; i++)
{
if (allScreens[i].Primary)
{
return i;
}
}
return 0;
}
public static void SetMouseCursorVisibility(bool show)
{
if (show)
{
while (User32.ShowCursor(true) < 0)
{
}
}
else
{
while (User32.ShowCursor(false) >= 0)
{
}
}
}
public static void Shutdown()
{
ProcessStarter.StartProcess("shutdown.exe", "-s -t 0");
}
public static void Restart()
{
ProcessStarter.StartProcess("shutdown.exe", "-r -t 0");
}
public static bool Sleep()
{
return Powrprof.SetSuspendState(false, true, false);
}
public static bool Hibernate()
{
return Powrprof.SetSuspendState(true, true, false);
}
public static ComputerScreen ToComputerScreen(this Screen screen)
{
if (screen == null)
{
return null;
}
else
{
return new ComputerScreen(screen);
}
}
public static List<HwCompany> GetGpuVendors()
{
var gpus = new List<string>();
var vendors = new List<HwCompany>();
try
{
using (var video = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"))
{
foreach (var obj in video.Get())
{
gpus.Add(obj["Name"].ToString());
}
}
foreach (var gpu in gpus)
{
if (gpu.Contains("intel", StringComparison.OrdinalIgnoreCase))
{
vendors.AddMissing(HwCompany.Intel);
}
else if (gpu.Contains("nvidia", StringComparison.OrdinalIgnoreCase))
{
vendors.AddMissing(HwCompany.Nvidia);
}
else if (gpu.Contains("amd", StringComparison.OrdinalIgnoreCase))
{
vendors.AddMissing(HwCompany.AMD);
}
else if (gpu.Contains("vmware", StringComparison.OrdinalIgnoreCase))
{
vendors.AddMissing(HwCompany.VMware);
}
else
{
return new List<HwCompany> { HwCompany.Uknown };
}
}
if (vendors.Count > 0)
{
return vendors;
}
}
catch (Exception e)
{
logger.Error(e, "Failed to get GPU vendor.");
}
return new List<HwCompany> { HwCompany.Uknown };
}
private static string GetMonitorFriendlyName(LUID adapterId, uint targetId)
{
var deviceName = new DISPLAYCONFIG_TARGET_DEVICE_NAME
{
header =
{
size = (uint)Marshal.SizeOf(typeof (DISPLAYCONFIG_TARGET_DEVICE_NAME)),
adapterId = adapterId,
id = targetId,
type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME
}
};
var error = User32.DisplayConfigGetDeviceInfo(ref deviceName);
if (error != WinError.ERROR_SUCCESS)
{
throw new Win32Exception(error);
}
return deviceName.monitorFriendlyDeviceName;
}
private static IEnumerable<string> GetAllMonitorsFriendlyNames()
{
var error = User32.GetDisplayConfigBufferSizes(
QUERY_DEVICE_CONFIG_FLAGS.QDC_ONLY_ACTIVE_PATHS,
out uint pathCount,
out uint modeCount);
if (error != WinError.ERROR_SUCCESS)
{
throw new Win32Exception(error);
}
var displayPaths = new DISPLAYCONFIG_PATH_INFO[pathCount];
var displayModes = new DISPLAYCONFIG_MODE_INFO[modeCount];
error = User32.QueryDisplayConfig(
QUERY_DEVICE_CONFIG_FLAGS.QDC_ONLY_ACTIVE_PATHS,
ref pathCount,
displayPaths,
ref modeCount,
displayModes,
IntPtr.Zero);
if (error != WinError.ERROR_SUCCESS)
{
throw new Win32Exception(error);
}
for (var i = 0; i < modeCount; i++)
{
if (displayModes[i].infoType == DISPLAYCONFIG_MODE_INFO_TYPE.DISPLAYCONFIG_MODE_INFO_TYPE_TARGET)
{
yield return GetMonitorFriendlyName(displayModes[i].adapterId, displayModes[i].id);
}
}
}
public static string DeviceFriendlyName(this Screen screen)
{
try
{
var allFriendlyNames = GetAllMonitorsFriendlyNames();
for (var index = 0; index < Screen.AllScreens.Length; index++)
{
if (Equals(screen, Screen.AllScreens[index]))
{
return allFriendlyNames.ToArray()[index];
}
}
}
catch (Exception e)
{
logger.Error(e, "Failed to get display name.");
}
return screen.DeviceName;
}
}
}
| 31.279805 | 156 | 0.466086 | [
"MIT"
] | JosefNemec/Playnite | source/Playnite/Common/Computer.cs | 12,858 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 0.1.0-559
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// IamLdapBasePropertiesRef
/// </summary>
[DataContract]
public partial class IamLdapBasePropertiesRef : IEquatable<IamLdapBasePropertiesRef>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="IamLdapBasePropertiesRef" /> class.
/// </summary>
[JsonConstructorAttribute]
public IamLdapBasePropertiesRef()
{
}
/// <summary>
/// Gets or Sets Moid
/// </summary>
[DataMember(Name="Moid", EmitDefaultValue=false)]
public string Moid { get; private set; }
/// <summary>
/// Gets or Sets ObjectType
/// </summary>
[DataMember(Name="ObjectType", EmitDefaultValue=false)]
public string ObjectType { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class IamLdapBasePropertiesRef {\n");
sb.Append(" Moid: ").Append(Moid).Append("\n");
sb.Append(" ObjectType: ").Append(ObjectType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as IamLdapBasePropertiesRef);
}
/// <summary>
/// Returns true if IamLdapBasePropertiesRef instances are equal
/// </summary>
/// <param name="other">Instance of IamLdapBasePropertiesRef to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IamLdapBasePropertiesRef other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Moid == other.Moid ||
this.Moid != null &&
this.Moid.Equals(other.Moid)
) &&
(
this.ObjectType == other.ObjectType ||
this.ObjectType != null &&
this.ObjectType.Equals(other.ObjectType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Moid != null)
hash = hash * 59 + this.Moid.GetHashCode();
if (this.ObjectType != null)
hash = hash * 59 + this.ObjectType.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 32.521127 | 140 | 0.564747 | [
"Apache-2.0"
] | CiscoUcs/intersight-powershell | csharp/swaggerClient/src/intersight/Model/IamLdapBasePropertiesRef.cs | 4,618 | C# |
using System.Xml.Serialization;
namespace Instagraph.DataProcessor.DtoModels.Import
{
public class ImportCommentPostDto
{
[XmlAttribute("id")]
public int Id { get; set; }
}
} | 20.4 | 51 | 0.666667 | [
"MIT"
] | Mithras11/SoftUni-Software-Engineering | C_Sharp/CSharp DataBases/Entity Framework Core/Exams/04.12.2017/Instagraph.DataProcessor/DtoModels/Import/ImportCommentPostDto.cs | 206 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
// ReSharper disable once CheckNamespace
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// In electromagnetism, permeability is the measure of the ability of a material to support the formation of a magnetic field within itself.
/// </summary>
/// <remarks>
/// https://en.wikipedia.org/wiki/Permeability_(electromagnetism)
/// </remarks>
public partial struct Permeability : IQuantity<PermeabilityUnit>, IEquatable<Permeability>, IComparable, IComparable<Permeability>, IConvertible, IFormattable
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly PermeabilityUnit? _unit;
static Permeability()
{
BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0);
Info = new QuantityInfo<PermeabilityUnit>(QuantityType.Permeability,
new UnitInfo<PermeabilityUnit>[] {
new UnitInfo<PermeabilityUnit>(PermeabilityUnit.HenryPerMeter, BaseUnits.Undefined),
},
BaseUnit, Zero, BaseDimensions);
}
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unit">The unit representation to contruct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public Permeability(double numericValue, PermeabilityUnit unit)
{
if(unit == PermeabilityUnit.Undefined)
throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit));
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = unit;
}
/// <summary>
/// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>.
/// </summary>
/// <param name="numericValue">The numeric value to contruct this quantity with.</param>
/// <param name="unitSystem">The unit system to create the quantity with.</param>
/// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception>
/// <exception cref="InvalidOperationException">No unit was found for the given <see cref="UnitSystem"/>.</exception>
/// <exception cref="InvalidOperationException">More than one unit was found for the given <see cref="UnitSystem"/>.</exception>
public Permeability(double numericValue, UnitSystem unitSystem)
{
if(unitSystem == null) throw new ArgumentNullException(nameof(unitSystem));
_value = Guard.EnsureValidNumber(numericValue, nameof(numericValue));
_unit = Info.GetUnitInfoFor(unitSystem.BaseUnits).Value;
}
#region Static Properties
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
public static QuantityInfo<PermeabilityUnit> Info { get; }
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions { get; }
/// <summary>
/// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value.
/// </summary>
public static PermeabilityUnit BaseUnit { get; } = PermeabilityUnit.HenryPerMeter;
/// <summary>
/// Represents the largest possible value of Permeability
/// </summary>
public static Permeability MaxValue { get; } = new Permeability(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of Permeability
/// </summary>
public static Permeability MinValue { get; } = new Permeability(double.MinValue, BaseUnit);
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public static QuantityType QuantityType { get; } = QuantityType.Permeability;
/// <summary>
/// All units of measurement for the Permeability quantity.
/// </summary>
public static PermeabilityUnit[] Units { get; } = Enum.GetValues(typeof(PermeabilityUnit)).Cast<PermeabilityUnit>().Except(new PermeabilityUnit[]{ PermeabilityUnit.Undefined }).ToArray();
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter.
/// </summary>
public static Permeability Zero { get; } = new Permeability(0, BaseUnit);
#endregion
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<PermeabilityUnit> QuantityInfo => Info;
/// <inheritdoc cref="IQuantity.QuantityInfo"/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref="QuantityType" /> of this quantity.
/// </summary>
public QuantityType Type => Permeability.QuantityType;
/// <summary>
/// The <see cref="BaseDimensions" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => Permeability.BaseDimensions;
#endregion
#region Conversion Properties
/// <summary>
/// Get Permeability in HenriesPerMeter.
/// </summary>
public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter);
#endregion
#region Static Methods
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation(PermeabilityUnit unit)
{
return GetAbbreviation(unit, null);
}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name="unit">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
/// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static string GetAbbreviation(PermeabilityUnit unit, [CanBeNull] IFormatProvider provider)
{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}
#endregion
#region Static Factory Methods
/// <summary>
/// Get Permeability from HenriesPerMeter.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static Permeability FromHenriesPerMeter(QuantityValue henriespermeter)
{
double value = (double) henriespermeter;
return new Permeability(value, PermeabilityUnit.HenryPerMeter);
}
/// <summary>
/// Dynamically convert from value and unit enum <see cref="PermeabilityUnit" /> to <see cref="Permeability" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>Permeability unit value.</returns>
public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit)
{
return new Permeability((double)value, fromUnit);
}
#endregion
#region Static Parse Methods
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static Permeability Parse(string str)
{
return Parse(str, null);
}
/// <summary>
/// Parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="ArgumentException">
/// Expected string to have one or two pairs of quantity and unit in the format
/// "<quantity> <unit>". Eg. "5.5 m" or "1ft 2in"
/// </exception>
/// <exception cref="AmbiguousUnitParseException">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse("1 cup") will throw, because it can refer to any of
/// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />.
/// </exception>
/// <exception cref="UnitsNetException">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static Permeability Parse(string str, [CanBeNull] IFormatProvider provider)
{
return QuantityParser.Default.Parse<Permeability, PermeabilityUnit>(
str,
provider,
From);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
public static bool TryParse([CanBeNull] string str, out Permeability result)
{
return TryParse(str, null, out result);
}
/// <summary>
/// Try to parse a string with one or two quantities of the format "<quantity> <unit>".
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="result">Resulting unit quantity if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.Parse("5.5 m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParse([CanBeNull] string str, [CanBeNull] IFormatProvider provider, out Permeability result)
{
return QuantityParser.Default.TryParse<Permeability, PermeabilityUnit>(
str,
provider,
From,
out result);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
public static PermeabilityUnit ParseUnit(string str)
{
return ParseUnit(str, null);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <example>
/// Length.ParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static PermeabilityUnit ParseUnit(string str, IFormatProvider provider = null)
{
return UnitParser.Default.Parse<PermeabilityUnit>(str, provider);
}
/// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.PermeabilityUnit)"/>
public static bool TryParseUnit(string str, out PermeabilityUnit unit)
{
return TryParseUnit(str, null, out unit);
}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
/// <param name="unit">The parsed unit if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.TryParseUnit("m", new CultureInfo("en-US"));
/// </example>
/// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public static bool TryParseUnit(string str, IFormatProvider provider, out PermeabilityUnit unit)
{
return UnitParser.Default.TryParse<PermeabilityUnit>(str, provider, out unit);
}
#endregion
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static Permeability operator -(Permeability right)
{
return new Permeability(-right.Value, right.Unit);
}
/// <summary>Get <see cref="Permeability"/> from adding two <see cref="Permeability"/>.</summary>
public static Permeability operator +(Permeability left, Permeability right)
{
return new Permeability(left.Value + right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="Permeability"/> from subtracting two <see cref="Permeability"/>.</summary>
public static Permeability operator -(Permeability left, Permeability right)
{
return new Permeability(left.Value - right.GetValueAs(left.Unit), left.Unit);
}
/// <summary>Get <see cref="Permeability"/> from multiplying value and <see cref="Permeability"/>.</summary>
public static Permeability operator *(double left, Permeability right)
{
return new Permeability(left * right.Value, right.Unit);
}
/// <summary>Get <see cref="Permeability"/> from multiplying value and <see cref="Permeability"/>.</summary>
public static Permeability operator *(Permeability left, double right)
{
return new Permeability(left.Value * right, left.Unit);
}
/// <summary>Get <see cref="Permeability"/> from dividing <see cref="Permeability"/> by value.</summary>
public static Permeability operator /(Permeability left, double right)
{
return new Permeability(left.Value / right, left.Unit);
}
/// <summary>Get ratio value from dividing <see cref="Permeability"/> by <see cref="Permeability"/>.</summary>
public static double operator /(Permeability left, Permeability right)
{
return left.HenriesPerMeter / right.HenriesPerMeter;
}
#endregion
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=(Permeability left, Permeability right)
{
return left.Value <= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=(Permeability left, Permeability right)
{
return left.Value >= right.GetValueAs(left.Unit);
}
/// <summary>Returns true if less than.</summary>
public static bool operator <(Permeability left, Permeability right)
{
return left.Value < right.GetValueAs(left.Unit);
}
/// <summary>Returns true if greater than.</summary>
public static bool operator >(Permeability left, Permeability right)
{
return left.Value > right.GetValueAs(left.Unit);
}
/// <summary>Returns true if exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator ==(Permeability left, Permeability right)
{
return left.Equals(right);
}
/// <summary>Returns true if not exactly equal.</summary>
/// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public static bool operator !=(Permeability left, Permeability right)
{
return !(left == right);
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if(obj is null) throw new ArgumentNullException(nameof(obj));
if(!(obj is Permeability objPermeability)) throw new ArgumentException("Expected type Permeability.", nameof(obj));
return CompareTo(objPermeability);
}
/// <inheritdoc />
public int CompareTo(Permeability other)
{
return _value.CompareTo(other.GetValueAs(this.Unit));
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public override bool Equals(object obj)
{
if(obj is null || !(obj is Permeability objPermeability))
return false;
return Equals(objPermeability);
}
/// <inheritdoc />
/// <remarks>Consider using <see cref="Equals(Permeability, double, ComparisonType)"/> for safely comparing floating point values.</remarks>
public bool Equals(Permeability other)
{
return _value.Equals(other.GetValueAs(this.Unit));
}
/// <summary>
/// <para>
/// Compare equality to another Permeability within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating point operations and using System.Double internally.
/// </para>
/// </summary>
/// <param name="other">The other quantity to compare to.</param>
/// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name="comparisonType">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType)
{
if(tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0.");
double thisValue = (double)this.Value;
double otherValueInThisUnits = other.As(this.Unit);
return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current Permeability.</returns>
public override int GetHashCode()
{
return new { QuantityType, Value, Unit }.GetHashCode();
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(PermeabilityUnit unit)
{
if(Unit == unit)
return Convert.ToDouble(Value);
var converted = GetValueAs(unit);
return Convert.ToDouble(converted);
}
/// <inheritdoc />
double IQuantity.As(Enum unit)
{
if(!(unit is PermeabilityUnit unitAsPermeabilityUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit));
return As(unitAsPermeabilityUnit);
}
/// <summary>
/// Converts this Permeability to another Permeability with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A Permeability with the specified unit.</returns>
public Permeability ToUnit(PermeabilityUnit unit)
{
var convertedValue = GetValueAs(unit);
return new Permeability(convertedValue, unit);
}
/// <inheritdoc />
IQuantity IQuantity.ToUnit(Enum unit)
{
if(!(unit is PermeabilityUnit unitAsPermeabilityUnit))
throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit));
return ToUnit(unitAsPermeabilityUnit);
}
/// <inheritdoc />
IQuantity<PermeabilityUnit> IQuantity<PermeabilityUnit>.ToUnit(PermeabilityUnit unit) => ToUnit(unit);
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double GetValueInBaseUnit()
{
switch(Unit)
{
case PermeabilityUnit.HenryPerMeter: return _value;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
private double GetValueAs(PermeabilityUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = GetValueInBaseUnit();
switch(unit)
{
case PermeabilityUnit.HenryPerMeter: return baseUnitValue;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
#region ToString Methods
/// <summary>
/// Gets the default string representation of value and unit.
/// </summary>
/// <returns>String representation.</returns>
public override string ToString()
{
return ToString("g");
}
/// <summary>
/// Gets the default string representation of value and unit using the given format provider.
/// </summary>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
public string ToString([CanBeNull] IFormatProvider provider)
{
return ToString("g", provider);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")]
public string ToString([CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix)
{
var value = Convert.ToDouble(Value);
var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);
return ToString(provider, format);
}
/// <summary>
/// Get string representation of value and unit.
/// </summary>
/// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param>
/// <param name="args">Arguments for string format. Value and unit are implictly included as arguments 0 and 1.</param>
/// <returns>String representation.</returns>
/// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
[Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")]
public string ToString([CanBeNull] IFormatProvider provider, [NotNull] string format, [NotNull] params object[] args)
{
if (format == null) throw new ArgumentNullException(nameof(format));
if (args == null) throw new ArgumentNullException(nameof(args));
provider = provider ?? CultureInfo.CurrentUICulture;
var value = Convert.ToDouble(Value);
var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args);
return string.Format(provider, format, formatArgs);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />.
/// </summary>
/// <param name="format">The format string.</param>
/// <returns>The string representation.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentUICulture);
}
/// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/>
/// <summary>
/// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="formatProvider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <returns>The string representation.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return QuantityFormatter.Format<PermeabilityUnit>(this, format, formatProvider);
}
#endregion
#region IConvertible Methods
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(Permeability)} to bool is not supported.");
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(Permeability)} to char is not supported.");
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException($"Converting {typeof(Permeability)} to DateTime is not supported.");
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(_value);
}
string IConvertible.ToString(IFormatProvider provider)
{
return ToString("g", provider);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if(conversionType == typeof(Permeability))
return this;
else if(conversionType == typeof(PermeabilityUnit))
return Unit;
else if(conversionType == typeof(QuantityType))
return Permeability.QuantityType;
else if(conversionType == typeof(BaseDimensions))
return Permeability.BaseDimensions;
else
throw new InvalidCastException($"Converting {typeof(Permeability)} to {conversionType} is not supported.");
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
#endregion
}
}
| 43.419154 | 222 | 0.608611 | [
"MIT-feh"
] | Sonan1994/UnitsNet | UnitsNet/GeneratedCode/Quantities/Permeability.NetFramework.g.cs | 34,911 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DotLogix.Core.Extensions;
using DotLogix.Core.Rest.Server.Http.Headers;
using DotLogix.Core.Utils;
namespace DotLogix.Core.Rest.Server.Http {
public class MultiPartParser {
public static MultiPartParser Instance { get; } = new MultiPartParser();
private MultiPartParser(){}
public MultiPartData Parse(Stream stream, string boundary, Encoding encoding = null) {
if(encoding == null)
encoding = Encoding.UTF8;
var boundaryBytes = encoding.GetBytes("--"+boundary);
var headerSplitBytes = encoding.GetBytes("\r\n\r\n");
var parts = stream.SplitByArray(boundaryBytes, boundaryBytes.Length+2, stream.Length-2-boundaryBytes.Length).ToArray();
var partData = new MultiPartData(boundary, stream);
var headerSeperators = new[]{"\r\n", ": "};
for(var index = 0; index < parts.Length-1; index++) {
var part = parts[index];
var headerEnd = part.IndexOfArray(headerSplitBytes, 0, part.Length);
var headerData = (new StreamSegment(stream, part.Offset, headerEnd)).ToByteArray();
var headerStr = encoding.GetString(headerData).Split(headerSeperators, StringSplitOptions.RemoveEmptyEntries);
ContentDisposition disposition = null;
MimeType contentType = null;
for(int i = 0; i < headerStr.Length; i += 2) {
switch(headerStr[i].ToLower()) {
case "content-disposition":
disposition = ContentDisposition.Parse(headerStr[1]);
break;
case "content-type":
contentType = MimeType.Parse(headerStr[1]);
break;
}
}
var data = new StreamSegment(stream, part.Offset + headerEnd + 4, part.Length - headerEnd - 6);
var value = ParseValue(disposition, contentType, data);
partData.Values.Add(value);
if(value.Name != null) {
if(partData.NamedValues.TryGetValue(value.Name, out var collection) == false) {
collection = new List<MultiPartDataValue>();
partData.NamedValues.Add(value.Name, collection);
}
collection.Add(value);
}
}
return partData;
}
public MultiPartData Parse(byte[] data, string boundary, Encoding encoding = null) {
var memoryStream = new MemoryStream(data);
return Parse(memoryStream, boundary, encoding);
}
private MultiPartDataValue ParseValue(ContentDisposition disposition, MimeType contentType, StreamSegment data) {
object dataValue = null;
if(disposition.HasAttribute("filename", true)) {
dataValue = data;
}else if(disposition.HasAttribute("boundary", true)) {
dataValue = Parse(data, disposition.GetAttribute("boundary").Value);
} else {
using(var reader = new StreamReader(data, Encoding.UTF8, false, 1024, false)) {
dataValue = reader.ReadToEnd();
}
}
return new MultiPartDataValue(disposition, contentType, dataValue);
}
}
} | 43.901235 | 131 | 0.568054 | [
"MIT"
] | dotlogix/DotlogixCore | Rest/Server/Http/MultiPartParser.cs | 3,558 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.Beverage_Labels
{
class Program
{
static void Main(string[] args)
{
var name = Console.ReadLine();
var volume = double.Parse(Console.ReadLine());
var energy = double.Parse(Console.ReadLine());
var sugar = double.Parse(Console.ReadLine());
var totalSugar = (volume * sugar) / 100;
var totalEnergy = (volume * energy) / 100;
Console.WriteLine($"{volume}ml {name}:");
Console.WriteLine($"{totalEnergy}kcal, {totalSugar}g sugars");
}
}
}
| 26.923077 | 74 | 0.594286 | [
"MIT"
] | paykova/TEST | ProgrammingFundamentals/CSharp Intro and Basic Syntax EX/04. Beverage Labels/04. Beverage Labels.cs | 702 | C# |
using Commons;
namespace SourceGenerator
{
public partial class Employee
{
[Identifier]
public int Id { get; set; }
}
}
| 13.636364 | 35 | 0.593333 | [
"MIT"
] | nuitsjp/CodeGenerationOverviewIn2021 | Completed/SourceGenerator/Employee.cs | 152 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UI.WIN
{
public partial class Form1 : Form
{
public Mars.Robots robots = new Mars.Robots();
public Form1()
{
InitializeComponent();
}
private void AddRobot_Click(object sender, EventArgs e)
{
try
{
var direction = Direction.SelectedItem;
var xcoord = int.Parse(XCoord.Text);
var ycoord = int.Parse(YCoord.Text);
var roamcoords = RoamCoords.Text;
var plateau_x = int.Parse(Plateau_X.Text);
var plateau_y = int.Parse(Plateau_Y.Text);
var plateau = new Mars.Plateau(0, 0, plateau_x, plateau_y);
var robot = new Mars.Robot(plateau);
Mars.Compass compassVal = new Mars.Compass();
compassVal = (Mars.Compass)Enum.Parse(typeof(Mars.Compass), direction.ToString());
robot.ExceptCommand(xcoord, ycoord, compassVal, roamcoords);
robots.Add(robot);
populateAssignedRobots();
}
catch (Exception ex)
{
Error.Text = ex.Message;
}
}
private void populateAssignedRobots()
{
RobotsAssigned.Items.Clear();
IEnumerable<Mars.Robot> robotList = (IEnumerable<Mars.Robot>)robots.Get();
foreach (Mars.Robot item in robotList)
{
RobotsAssigned.Items.Add(String.Format(" X:{0} Y:{1} Direction:{2} Roam:{3}",
item.X, item.Y, item.Direction, String.Concat<char>(item.RoamCoordinates)));
}
}
private void StartExplore_Click(object sender, EventArgs e)
{
RobotResults.Items.Clear();
IEnumerable<Mars.Robot> robotList = (IEnumerable<Mars.Robot>)robots.Get();
foreach (Mars.Robot item in robotList)
{
item.ProcessCommand();
Thread.Sleep(600);
RobotResults.Items.Add(item.Status);
}
}
private void Reset_Click(object sender, EventArgs e)
{
robots = new Mars.Robots();
RobotsAssigned.Items.Clear();
RobotResults.Items.Clear();
}
}
}
| 27.27551 | 99 | 0.528245 | [
"MIT"
] | shimon-uk/Mars | UI.WIN/Form1.cs | 2,675 | C# |
using Jarvis.Core.Api.Slack;
using Jarvis.Core.Models;
using System.Threading.Tasks;
namespace Jarvis.Core.Services
{
public class IdentityManager
{
IUsersIdentityApi Api;
public IdentityManager(IUsersIdentityApi api)
{
Api = api;
}
public IdentityManager()
{
Api = new UsersIdentityApi();
}
public Task<Identity> GetIdentityAsync(string token)
{
return Api.GetIdentity(token);
}
}
}
| 19.185185 | 60 | 0.583012 | [
"MIT"
] | aliostad/deep-learning-lang-detection | data/test/csharp/49572a657ea678a679d0b02006deb32a4e56fbb2IdentityManager.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Mod.CatsV3.Application.Dtos;
using Mod.CatsV3.Application.Services;
using Mod.CatsV3.Domain.Entities;
using Mod.Framework.WebApi.Controllers;
namespace Mod.CatsV3.WebApi.Controllers
{
public class FYIUserController : CrudControllerBase<FYIUserDto, FYIUser>
{
IFYIUserAppService _service;
public FYIUserController(ILogger<FYIUser> logger, IFYIUserAppService service) : base(logger, service)
{
_service = service;
}
[HttpGet]
[Route("filterbystatus")]
public virtual ActionResult<FYIUserDto> GetCompletedItems(string catsid, string status, string round)
{
dynamic item = new ExpandoObject();
item.CATSID = catsid;
item.Round = round;
var list = (IEnumerable<FYIUserDto>)_service.GetAll(item);
//list.ToList().ForEach(x =>
//{
// x.Collaboration.Originators.ToList().ForEach(d => { d.Collaboration = null; });
// x.Collaboration.Reviewers.ToList().ForEach(d => { d.Collaboration = null; });
// x.Collaboration.fYIUsers.ToList().ForEach(d => { d.Collaboration = null; });
//});
//group by the user upn
var groups = list
.GroupBy(a => (a.FYIUpn))
.SelectMany(a => a.Where(b => b.Id == a.Max(c => c.Id))).ToList();
return Json(groups.OrderBy(x => x.Id));
}
}
}
| 33.038462 | 109 | 0.622817 | [
"MIT"
] | EOP-OMB/CATSV3 | Server/Mod.CatsV3.Server/Mod.CatsV3.WebApi/Controllers/FYIUserController.cs | 1,720 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Poplawap.Backend.Model
{
public class Comments
{
public int Id { get; set; }
[Required]
[MaxLength]
public string CommentMessage { get; set; }
[Required]
public DateTime Date { get; set; }
public int? ParentComment { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
public int SaleId { get; set; }
public virtual Sales Sale { get; set; }
}
}
| 21.75 | 57 | 0.599343 | [
"MIT"
] | Rubsanchez/Poplawap | Poplawap/Poplawap.Backend/Model/Comments.cs | 611 | C# |
using System.Linq;
using ESFA.DC.ILR.Model.Mapper.Interface;
using FluentAssertions;
using Moq;
using Xunit;
namespace ESFA.DC.ILR.FileValidationService.Service.Tests
{
public class LooseToTightSchemaMapperTests
{
[Fact]
public void Map()
{
var loose = new Model.Loose.Message();
var tight = new Model.Message();
var messageMapperMock = new Mock<IModelMapper<Model.Loose.Message, Model.Message>>();
messageMapperMock.Setup(m => m.Map(loose)).Returns(tight).Verifiable();
var service = new LooseToTightSchemaMapper(messageMapperMock.Object);
service.MapTo(loose).Should().BeSameAs(tight);
}
}
}
| 26.035714 | 97 | 0.63786 | [
"MIT"
] | SkillsFundingAgency/DC-ILR-1819-FileValidationService | src/ESFA.DC.ILR.FileValidationService.Service.Tests/LooseToTightSchemaMapperTests.cs | 731 | C# |
using System;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Buffers.Binary;
namespace RSocket
{
using System.Buffers;
using System.Threading;
using Microsoft.AspNetCore.Internal;
public partial class RSocketProtocol
{
private const int INT24SIZE = (sizeof(UInt32) - 1);
public const int FRAMELENGTHSIZE = INT24SIZE;
private const int METADATALENGTHSIZE = INT24SIZE;
//Memory Buffer Builders: ArrayPool<byte>
//https://github.com/aspnet/SignalR/blob/2d4fb0af6fd2ef2e3a059a2a15a56484d8800d35/src/Common/MemoryBufferWriter.cs
//TODO FEATURE TEST for Backpressure support with policy
//TODO FEATURE KeepAlive
//TODO FEATURE Lowest latency server support from client with heuristics.
//TODO Feature Docs.
//TODO Feature TLS for WebSockets, other?
//TODO Feature QuickStart in the fashion of the existing ones
//TODO Test Both WS and TCP with >Memory<T> buffer size. Since they don't accumulate in the state machine, they probably can overflow.
public const int MESSAGEFRAMESIZE = INT24SIZE; //This may be large than the FRAMELENGTHSIZE if the messages are padded inside of pipelines.
//static public int MessageFrame(int length, bool isEndOfMessage) => isEndOfMessage ? length | (0b1 << sizeof(int) * 8 - 1) : length; //High bit is EoM mark. Can't use twos-complement because negative zero is a legal value.
//static public (int length, bool isEndofMessage) MessageFrame(int frame) => ((frame & ~(0b1 << sizeof(int) * 8 - 1)), (frame & (0b1 << sizeof(int) * 8 - 1)) != 0);
static public (int Length, bool IsEndofMessage) MessageFrame(int frame) => (frame, true);
static public int MessageFrame(int length, bool isEndOfMessage) => length;
static public void MessageFrameWrite(int length, bool isEndOfMessage, Span<byte> target) { target[2] = (byte)((length >> 8 * 0) & 0xFF); target[1] = (byte)((length >> 8 * 1) & 0xFF); target[0] = (byte)((length >> 8 * 2) & 0xFF); }
static public (int Length, bool IsEndOfMessage) MessageFramePeek(ReadOnlySequence<byte> sequence) { var reader = new SequenceReader<byte>(sequence); return reader.TryRead(out byte b1) && reader.TryRead(out byte b2) && reader.TryRead(out byte b3) ? ((b1 << 8 * 2) | (b2 << 8 * 1) | (b3 << 8 * 0), true) : (0, false); }
static Task Flush(PipeWriter pipe, CancellationToken cancel) { var result = pipe.FlushAsync(cancel); return result.IsCompleted ? Task.CompletedTask : result.AsTask(); }
static bool TryReadRemaining(in Header header, int innerlength, ref SequenceReader<byte> reader, out int metadatalength)
{
//TODO Should assert that mdl = header.remain == 0;
if (!header.HasMetadata) { metadatalength = 0; return true; } else { metadatalength = header.Remaining - innerlength; return true; }
}
static bool TryReadRemaining(in Header header, int innerlength, ref SequenceReader<byte> reader, out int metadatalength, out int datalength)
{
if (!header.HasMetadata) { metadatalength = 0; }// datalength = header.Remaining - innerlength - header.HasMetadataHeaderLength - metadatalength; return true; }
else if (reader.TryReadUInt24BigEndian(out int length)) { metadatalength = length; }// datalength = header.Remaining - innerlength - METADATALENGTHSIZE - metadatalength; return true; }
else { metadatalength = default; datalength = default; return false; }
datalength = header.Remaining - innerlength - header.MetadataHeaderLength - metadatalength;
return true;
}
public ref struct Payload
{
public const ushort FLAG_FOLLOWS = 0b____00_10000000;
public const ushort FLAG_COMPLETE = 0b___00_01000000;
public const ushort FLAG_NEXT = 0b_______00_00100000;
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasFollows { get => (Header.Flags & FLAG_FOLLOWS) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_FOLLOWS) : (ushort)(Header.Flags & ~FLAG_FOLLOWS); }
public bool IsComplete { get => (Header.Flags & FLAG_COMPLETE) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_COMPLETE) : (ushort)(Header.Flags & ~FLAG_COMPLETE); }
public bool IsNext { get => (Header.Flags & FLAG_NEXT) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_NEXT) : (ushort)(Header.Flags & ~FLAG_NEXT); }
private Header Header;
public Int32 Stream => Header.Stream;
public int MetadataLength;
public int DataLength;
private const int InnerLength = 0;
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public Payload(int stream, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, bool follows = false, bool complete = false, bool next = false) //TODO Parameter ordering, isn't Next much more likely than C or F?
{
Header = new Header(Types.Payload, stream, metadata: metadata);
DataLength = (int)data.Length;
MetadataLength = (int)metadata.Length;
//TODO Assign HasMetadata based on this??? And everywhere.
HasFollows = follows;
IsComplete = complete;
IsNext = next;
}
public Payload(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
//if (header.HasMetadata)
//{
// reader.TryReadUInt24BigEndian(out int length);
// MetadataLength = length;
// DataLength = framelength - header.Length - (sizeof(int) - 1) - MetadataLength;
//}
//else { MetadataLength = 0; DataLength = framelength - header.Length - MetadataLength; }
}
public bool Validate(bool canContinue = false)
{
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(Payload)} Message."); }
//if (DataLength > MaxDataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(DataLength), DataLength, $"Invalid {nameof(Payload)} Message."); }
//if (metadatalength != framelength - (Header.Length + payloadlength)) { } //SPEC: Metadata Length MUST be equal to the Frame Length minus the sum of the length of the Frame Header and the length of the Frame Payload, if present.
//Not sure how to assert this. If the frame has a length, then the payload length is computed from the frame length, resulting in a tautology. If the frame has no length, then the payload length is just what is, so the "frame length" is just this formula in reverse. So can it ever be false?
if (!IsComplete && !IsNext) { throw new InvalidOperationException($"{nameof(Payload)} Messages must have {nameof(IsNext)} or {nameof(IsComplete)}."); } //SPEC: A PAYLOAD MUST NOT have both (C)complete and (N)ext empty (false).
return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); } //TODO Should this be UInt24? Probably, but not sure if it can actually overflow...
written += writer.Write(data);
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
public override string ToString() => $"{Header.ToString()} {ToStringFlags()}, Metadata[{MetadataLength}], Data[{DataLength}]";
string ToStringFlags() => Header.ToStringFlags(new[] { (HasFollows, nameof(HasFollows), string.Empty), (IsComplete, nameof(IsComplete), string.Empty), (IsNext, nameof(IsNext), string.Empty) });
}
public ref struct RequestChannel
{
public const ushort FLAG_FOLLOWS = 0b___00_10000000;
public const ushort FLAG_COMPLETE = 0b___00_01000000;
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasFollows { get => (Header.Flags & FLAG_FOLLOWS) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_FOLLOWS) : (ushort)(Header.Flags & ~FLAG_FOLLOWS); }
public bool IsComplete { get => (Header.Flags & FLAG_COMPLETE) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_COMPLETE) : (ushort)(Header.Flags & ~FLAG_COMPLETE); }
private Header Header;
public Int32 Stream => Header.Stream;
public Int32 InitialRequest;
public int MetadataLength;
public int DataLength;
private const int InnerLength = sizeof(Int32);
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public RequestChannel(Int32 id, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default, Int32 initialRequest = 0, bool follows = false, bool complete = false)
{
Header = new Header(Types.Request_Channel, stream: id, metadata: metadata);
InitialRequest = initialRequest;
DataLength = (int)data.Length;
MetadataLength = (int)metadata.Length;
HasFollows = follows;
}
public RequestChannel(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryReadBigEndian(out int initialRequest); InitialRequest = initialRequest;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(RequestChannel)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(RequestChannel)} Message."); }
if (InitialRequest <= 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(InitialRequest), InitialRequest, $"Invalid {nameof(RequestChannel)} Message."); } //SPEC: Value MUST be > 0.
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
int Write(BufferWriter writer, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian(InitialRequest);
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); }
written += writer.Write(data);
return written;
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
}
public ref struct RequestStream
{
public const ushort FLAG_FOLLOWS = 0b___00_10000000; //TODO Consider standard flag positions... They aren't specced this way, but in practice they are always in the same spot...
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasFollows { get => (Header.Flags & FLAG_FOLLOWS) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_FOLLOWS) : (ushort)(Header.Flags & ~FLAG_FOLLOWS); }
private Header Header;
public Int32 Stream => Header.Stream;
public Int32 InitialRequest;
public int MetadataLength;
public int DataLength;
private const int InnerLength = sizeof(Int32);
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public RequestStream(Int32 id, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default, Int32 initialRequest = 0, bool follows = false)
{
Header = new Header(Types.Request_Stream, stream: id, metadata: metadata);
InitialRequest = initialRequest;
DataLength = (int)data.Length;
MetadataLength = (int)metadata.Length;
HasFollows = follows;
}
public RequestStream(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryReadBigEndian(out int initialRequest); InitialRequest = initialRequest;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(RequestStream)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(RequestStream)} Message."); }
if (InitialRequest <= 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(InitialRequest), InitialRequest, $"Invalid {nameof(RequestStream)} Message."); } //SPEC: Value MUST be > 0.
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
int Write(BufferWriter writer, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian(InitialRequest);
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); } //TODO Should this be UInt24? Probably, but not sure if it can actually overflow...
written += writer.Write(data);
return written;
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
}
public ref struct RequestResponse
{
public const ushort FLAG_FOLLOWS = 0b___00_10000000;
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasFollows { get => (Header.Flags & FLAG_FOLLOWS) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_FOLLOWS) : (ushort)(Header.Flags & ~FLAG_FOLLOWS); }
private Header Header;
public Int32 Stream => Header.Stream;
public int MetadataLength;
public int DataLength;
private const int InnerLength = 0;
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public RequestResponse(Int32 id, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default, Int32 initialRequest = 0, bool follows = false)
{
Header = new Header(Types.Request_Response, stream: id, metadata: metadata);
DataLength = (int)data.Length;
MetadataLength = (int)metadata.Length;
HasFollows = follows;
}
public RequestResponse(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(RequestResponse)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(RequestResponse)} Message."); }
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
int Write(BufferWriter writer, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); } //TODO Should this be UInt24? Probably, but not sure if it can actually overflow...
written += writer.Write(data);
return written;
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
}
public ref struct RequestFireAndForget
{
public const ushort FLAG_FOLLOWS = 0b___00_10000000;
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasFollows { get => (Header.Flags & FLAG_FOLLOWS) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_FOLLOWS) : (ushort)(Header.Flags & ~FLAG_FOLLOWS); }
private Header Header;
public Int32 Stream => Header.Stream;
public int MetadataLength;
public int DataLength;
private const int InnerLength = 0;
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public RequestFireAndForget(Int32 id, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default, Int32 initialRequest = 0, bool follows = false)
{
Header = new Header(Types.Request_Fire_And_Forget, stream: id, metadata: metadata);
DataLength = (int)data.Length;
MetadataLength = (int)metadata.Length;
HasFollows = follows;
}
public RequestFireAndForget(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(RequestFireAndForget)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(RequestFireAndForget)} Message."); }
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
int Write(BufferWriter writer, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); } //TODO Should this be UInt24? Probably, but not sure if it can actually overflow...
written += writer.Write(data);
return written;
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
}
public ref struct RequestN
{
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
private Header Header;
public Int32 Stream => Header.Stream;
public Int32 RequestNumber;
private const int InnerLength = sizeof(Int32);
public int Length => Header.Length + InnerLength;
public RequestN(Int32 id, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default, Int32 initialRequest = 0, bool follows = false)
{
Header = new Header(Types.Request_N, stream: id, metadata: metadata);
RequestNumber = initialRequest;
}
public RequestN(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryReadBigEndian(out int requestNumber); RequestNumber = requestNumber;
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(RequestN)} Message."); }
if (HasMetadata) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(HasMetadata), HasMetadata, $"Invalid {nameof(RequestN)} Message."); }
if (RequestNumber <= 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(RequestNumber), RequestNumber, $"Invalid {nameof(RequestN)} Message."); } //SPEC: Value MUST be > 0.
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata: metadata); return Flush(pipe, cancel); }
int Write(BufferWriter writer, ReadOnlySequence<byte> data, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian(RequestNumber);
return written;
}
}
public ref struct Cancel
{
private Header Header;
public int Length => Header.Length;
public Cancel(Int32 request)
{
Header = new Header(Types.Cancel);
}
public Cancel(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
}
public bool Validate(bool canContinue = false)
{
return true;
}
public void Write(PipeWriter pipe) { var writer = BufferWriter.Get(pipe); this.Write(writer); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, CancellationToken cancel = default) { Write(pipe); return Flush(pipe, cancel); }
void Write(BufferWriter writer)
{
var written = Header.Write(writer, Length);
}
}
public ref struct KeepAlive
{
public const ushort FLAG_RESPOND = 0b__00_10000000;
public bool Respond { get => (Header.Flags & FLAG_RESPOND) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_RESPOND) : (ushort)(Header.Flags & ~FLAG_RESPOND); }
private Header Header;
public Int64 LastReceivedPosition;
public int DataLength;
private const int InnerLength = sizeof(Int64);
public int Length => Header.Length + InnerLength + DataLength;
public KeepAlive(Int32 lastReceivedPosition, bool respond, ReadOnlySequence<byte> data = default)
{
Header = new Header(Types.KeepAlive);
LastReceivedPosition = lastReceivedPosition;
DataLength = (int)data.Length;
Respond = respond;
}
public KeepAlive(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryRead(out long lastReceivedPosition); LastReceivedPosition = lastReceivedPosition;
//TODO Check this: DataLength = framelength - header.Length - sizeof(long);
TryReadRemaining(header, InnerLength, ref reader, out _, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), $"Invalid {nameof(KeepAlive)} Message."); } //SPEC: KEEPALIVE frames MUST always use Stream ID 0 as they pertain to the Connection.
if (LastReceivedPosition < 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(LastReceivedPosition), LastReceivedPosition, $"Invalid {nameof(KeepAlive)} Message."); } //SPEC: Value MUST be > 0. (optional. Set to all 0s when not supported.)
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, CancellationToken cancel = default) { Write(pipe, data: data); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> data)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt64BigEndian(LastReceivedPosition);
written += writer.Write(data);
}
}
public ref struct Lease
{
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
private Header Header;
public Int32 TimeToLive;
public Int32 NumberOfRequests;
public int MetadataLength;
private const int InnerLength = sizeof(Int32) + sizeof(Int32);
public int Length => Header.Length + InnerLength + MetadataLength;
public Lease(Int32 timeToLive, Int32 numberOfRequests, ReadOnlySequence<byte> metadata)
{
Header = new Header(Types.Lease, metadata: metadata);
TimeToLive = timeToLive;
NumberOfRequests = numberOfRequests;
MetadataLength = (int)metadata.Length;
}
public Lease(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryRead(out int timeToLive); TimeToLive = timeToLive;
reader.TryRead(out int numberOfRequests); NumberOfRequests = numberOfRequests;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength); //SPEC: This frame only supports Metadata, so the Metadata Length header MUST NOT be included, even if the(M)etadata flag is set true.
//MetadataLength = header.HasMetadata ? MetadataLength = framelength - header.Length - sizeof(int) - sizeof(int) : 0; //SPEC: This frame only supports Metadata, so the Metadata Length header MUST NOT be included, even if the(M)etadata flag is set true.
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), $"Invalid {nameof(Lease)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(Lease)} Message."); }
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> metadata) { var writer = BufferWriter.Get(pipe); this.Write(writer, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, metadata: metadata); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> metadata)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian(TimeToLive);
written += writer.WriteInt32BigEndian(NumberOfRequests);
if (HasMetadata) { written += writer.Write(metadata); }
}
}
public ref struct Extension
{
public bool CanIgnore { get => Header.CanIgnore; set => Header.CanIgnore = value; }
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
private Header Header;
public Int32 ExtendedType;
public int ExtraLength;
private const int InnerLength = sizeof(Int64);
public int Length => Header.Length + InnerLength + ExtraLength;
public Extension(Int32 extendedtype, bool ignore = false)
{
Header = new Header(Types.Extension);
ExtendedType = extendedtype;
ExtraLength = 0;
}
public Extension(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryRead(out Int32 extendedType); ExtendedType = extendedType;
TryReadRemaining(header, InnerLength, ref reader, out _, out ExtraLength);
}
public bool Validate(bool canContinue = false)
{
if (ExtendedType <= 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(ExtendedType), $"Invalid {nameof(Extension)} Message."); }
return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> extra) { var writer = BufferWriter.Get(pipe); this.Write(writer, extra: extra); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> extra, CancellationToken cancel = default) { Write(pipe, extra: extra); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> extra)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian(ExtendedType);
written += writer.Write(extra);
}
}
public ref struct MetadataPush
{
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
private Header Header;
public int MetadataLength;
private const int InnerLength = 0;
public int Length => Header.Length + InnerLength + MetadataLength;
public MetadataPush(ReadOnlySequence<byte> metadata)
{
Header = new Header(Types.Metadata_Push, metadata: metadata);
MetadataLength = (int)metadata.Length;
}
public MetadataPush(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength); //SPEC: This frame only supports Metadata, so the Metadata Length header MUST NOT be included.
//MetadataLength = header.HasMetadata ? MetadataLength = framelength - header.Length : 0; //SPEC: This frame only supports Metadata, so the Metadata Length header MUST NOT be included.
}
public bool Validate(bool canContinue = false)
{
if (Header.Stream == 0) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(Header.Stream), Header.Stream, $"Invalid {nameof(MetadataPush)} Message."); }
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(MetadataPush)} Message."); }
else return true;
}
public void Write(PipeWriter pipe, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, metadata: metadata); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
if (HasMetadata) { written += writer.Write(metadata); }
}
}
public ref struct Error
{
private Header Header;
public ErrorCodes ErrorCode;
public int DataLength;
public string ErrorText;
private const int InnerLength = sizeof(Int32);
public int Length => Header.Length + InnerLength + DataLength;
public Error(ErrorCodes code, Int32 stream = Header.DEFAULT_STREAM, ReadOnlySequence<byte> data = default)
{
Header = new Header(Types.Error, stream: stream);
ErrorCode = code;
DataLength = (int)data.Length;
ErrorText = null;
}
public Error(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryReadBigEndian(out Int32 errorCode); ErrorCode = (ErrorCodes)errorCode;
TryReadRemaining(header, InnerLength, ref reader, out _, out DataLength);
reader.TryRead(out string text, DataLength); ErrorText = text;
}
public bool Validate(bool canContinue = false) => true;
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, CancellationToken cancel = default) { Write(pipe, data: data); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> data = default)
{
var written = Header.Write(writer, Length);
written += writer.WriteInt32BigEndian((int)ErrorCode);
written += writer.Write(data);
}
public override string ToString() => $"{Header.ToString()} {ToStringFlags()}: [{ErrorCode:X}] {ErrorText}";
string ToStringFlags() => Header.ToStringFlags();
}
public ref struct Setup
{
public const ushort FLAG_METADATA = 0b__01_00000000;
public const ushort FLAG_RESUME = 0b____00_10000000;
public const ushort FLAG_LEASE = 0b_____00_01000000;
public bool HasMetadata { get => Header.HasMetadata; set => Header.HasMetadata = value; }
public bool HasResume { get => (Header.Flags & FLAG_RESUME) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_RESUME) : (ushort)(Header.Flags & ~FLAG_RESUME); }
public bool CanLease { get => (Header.Flags & FLAG_LEASE) != 0; set => Header.Flags = value ? (ushort)(Header.Flags | FLAG_LEASE) : (ushort)(Header.Flags & ~FLAG_LEASE); }
private Header Header;
public Int32 Stream => Header.Stream;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public Int32 KeepAlive;
public Int32 Lifetime;
public byte[] ResumeToken;
public string MetadataMimeType;
public string DataMimeType;
public int MetadataLength;
public int DataLength;
private int InnerLength => sizeof(UInt16) + sizeof(UInt16) + sizeof(Int32) + sizeof(Int32)
+ (HasResume ? ResumeToken.Length : 0)
+ sizeof(byte) + Encoding.ASCII.GetByteCount(MetadataMimeType)
+ sizeof(byte) + Encoding.ASCII.GetByteCount(DataMimeType);
public int Length => Header.Length + InnerLength + Header.MetadataHeaderLength + MetadataLength + DataLength;
public Setup(TimeSpan keepalive, TimeSpan lifetime, string metadataMimeType = null, string dataMimeType = null, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default) : this((int)keepalive.TotalMilliseconds, (int)lifetime.TotalMilliseconds, string.IsNullOrEmpty(metadataMimeType) ? string.Empty : metadataMimeType, string.IsNullOrEmpty(dataMimeType) ? string.Empty : dataMimeType, data: data, metadata: metadata) { }
public Setup(Int32 keepalive, Int32 lifetime, string metadataMimeType, string dataMimeType, byte[] resumeToken = default, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default)
{
Header = new Header(Types.Setup, metadata: metadata);
MajorVersion = MAJOR_VERSION;
MinorVersion = MINOR_VERSION;
KeepAlive = keepalive;
Lifetime = lifetime;
ResumeToken = resumeToken;
MetadataMimeType = metadataMimeType;
DataMimeType = dataMimeType;
ResumeToken = resumeToken; //TODO Two of these?
MetadataLength = (int)metadata.Length;
DataLength = (int)data.Length;
HasResume = resumeToken != default && resumeToken.Length > 0;
}
public Setup(in Header header, ref SequenceReader<byte> reader)
{
Header = header;
reader.TryReadBigEndian(out UInt16 majorVersion); MajorVersion = majorVersion;
reader.TryReadBigEndian(out UInt16 minorVersion); MinorVersion = minorVersion;
reader.TryReadBigEndian(out Int32 keepAlive); KeepAlive = keepAlive;
reader.TryReadBigEndian(out Int32 lifetime); Lifetime = lifetime;
if ((header.Flags & FLAG_RESUME) != 0) //TODO Duplicate test logic here
{
reader.TryReadBigEndian(out UInt16 resumeTokenLength);
ResumeToken = new byte[resumeTokenLength];
reader.TryRead(ResumeToken.AsSpan());
}
else { ResumeToken = Array.Empty<byte>(); }
var mmtr = reader.TryReadPrefix(out MetadataMimeType);
var dmtr = reader.TryReadPrefix(out DataMimeType);
MetadataLength = DataLength = 0; //Initialize so we can use InnerLength.
TryReadRemaining(header, InnerLength, ref reader, out MetadataLength, out DataLength);
}
public bool Validate(bool canContinue = false)
{
if (MetadataLength > MaxMetadataLength) { return canContinue ? false : throw new ArgumentOutOfRangeException(nameof(MetadataLength), MetadataLength, $"Invalid {nameof(Setup)} Message."); }
//TODO More validation here. See spec.
return true;
}
//TODO So common, should be library..?
public void Write(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default) { var writer = BufferWriter.Get(pipe); this.Write(writer, data: data, metadata: metadata); writer.Flush(); BufferWriter.Return(writer); }
public Task WriteFlush(PipeWriter pipe, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default, CancellationToken cancel = default) { Write(pipe, data: data, metadata:metadata); return Flush(pipe, cancel); }
void Write(BufferWriter writer, ReadOnlySequence<byte> data = default, ReadOnlySequence<byte> metadata = default)
{
var written = Header.Write(writer, Length);
written += writer.WriteUInt16BigEndian(MajorVersion);
written += writer.WriteUInt16BigEndian(MinorVersion);
written += writer.WriteInt32BigEndian(KeepAlive);
written += writer.WriteInt32BigEndian(Lifetime);
if (HasResume) { written += writer.WriteUInt16BigEndian(ResumeToken.Length) + writer.Write(ResumeToken); }
written += writer.WritePrefixByte(MetadataMimeType); //TODO THIS IS ASCII!!! See Spec!!
written += writer.WritePrefixByte(DataMimeType); //TODO THIS IS ASCII!!! See Spec!!
if (HasMetadata) { written += writer.WriteInt24BigEndian(MetadataLength) + writer.Write(metadata); } //TODO Should this be UInt24? Probably, but not sure if it can actually overflow...
written += writer.Write(data);
}
public ReadOnlySequence<byte> ReadMetadata(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Position, MetadataLength);
public ReadOnlySequence<byte> ReadData(in SequenceReader<byte> reader) => reader.Sequence.Slice(reader.Sequence.GetPosition(MetadataLength, reader.Position), DataLength);
public void Read(ref SequenceReader<byte> reader, out ReadOnlySequence<byte> metadata, out ReadOnlySequence<byte> data) { metadata = ReadMetadata(reader); data = ReadData(reader); reader.Advance(metadata.Length + data.Length); }
}
public ref struct Header
{
public const Int32 DEFAULT_STREAM = 0;
internal const int FRAMETYPE_OFFSET = 10;
internal const ushort FRAMETYPE_TYPE = 0b_111111 << FRAMETYPE_OFFSET;
internal const ushort FLAGS = 0b__________11_11111111;
internal const ushort FLAG_IGNORE = 0b____10_00000000;
internal const ushort FLAG_METADATA = 0b__01_00000000;
public bool CanIgnore { get => (Flags & FLAG_IGNORE) != 0; set => Flags = value ? (ushort)(Flags | FLAG_IGNORE) : (ushort)(Flags & ~FLAG_IGNORE); }
public bool HasMetadata { get => (Flags & FLAG_METADATA) != 0; set => Flags = value ? (ushort)(Flags | FLAG_METADATA) : (ushort)(Flags & ~FLAG_METADATA); }
public int MetadataHeaderLength => HasMetadata ? METADATALENGTHSIZE : 0; //TODO Only here?
public Int32 Stream;
public Types Type;
public UInt16 Flags;
static public Types MakeType(ushort flags) => (Types)((flags & Header.FRAMETYPE_TYPE) >> Header.FRAMETYPE_OFFSET);
static public ushort MakeFlags(ushort flags) => (ushort)(flags & Header.FLAGS);
public int Length => sizeof(Int32) + sizeof(UInt16);
private int FrameLength;
public int Remaining => FrameLength - Length; //TODO Temporary refactoring
public Header(Types type, Int32 stream = 0, in ReadOnlySequence<byte> metadata = default)
{
FrameLength = 0;
Type = type;
Stream = stream;
Flags = 0;
HasMetadata = metadata.Length > 0;
}
public Header(ref SequenceReader<byte> reader, int framelength = 0)
{
FrameLength = framelength;
reader.TryReadBigEndian(out Stream);
reader.TryReadBigEndian(out UInt16 flags);
Type = MakeType(flags);
Flags = MakeFlags(flags);
}
public int Write(BufferWriter writer, int length)
{
writer.WriteInt24BigEndian(length); //Not included in total length.
writer.WriteInt32BigEndian(Stream);
writer.WriteUInt16BigEndian((((int)Type << FRAMETYPE_OFFSET) & FRAMETYPE_TYPE) | (Flags & FLAGS));// (Ignore ? FLAG_IGNORE : 0) | (Metadata ? FLAG_METADATA : 0));
return Length;
}
public override string ToString() => $"{Stream:0000} {Type}";
public string ToStringFlags(IEnumerable<(bool, string, string)> flags = default) => new[] { (CanIgnore, nameof(CanIgnore), string.Empty), (HasMetadata, nameof(HasMetadata), string.Empty) }.Concat<(bool Condition, string True, string False)>(flags ?? Enumerable.Empty<(bool, string, string)>()).Aggregate(new StringBuilder($"{{{Flags:X3}"), (s, i) => s.Append(i.Condition ? "|" + i.True : i.False)).ToString().TrimEnd(',') + "}";
}
}
}
| 54.024081 | 446 | 0.730065 | [
"Apache-2.0"
] | Giorgi/rsocket-net | RSocket.Core/RSocketProtocol.cs | 42,625 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using CraftAI.Gate.Logic.Abstractions;
using Microsoft.Extensions.DependencyInjection;
namespace CraftAI.Gate.Logic.EventHandler.Collection
{
public class EventHandlers : IEventHandlersCollection
{
private static Type[] types = Array.Empty<Type>();
private readonly IEventHandler[] _eventHandlers;
IEventHandler[] IEventHandlersCollection.EventHandlers => _eventHandlers;
public EventHandlers(IServiceProvider serviceProvider)
{
if (!types.Any()) throw new InvalidOperationException(
$"Event handlers not found. " +
$"Call {nameof(EventHandlers)}{nameof(EventHandlers.RegisterCollections)} first");
List<IEventHandler> list = new(types.Length);
foreach (var type in types)
{
var obj = (IEventHandler)serviceProvider.GetRequiredService(type);
if (obj is null) throw new ArgumentNullException($"Object {type.Name} is not {nameof(IEventHandler)}");
list.Add(obj);
}
_eventHandlers = list.ToArray();
}
public static IServiceCollection RegisterCollections(IServiceCollection services)
{
services.AddSingleton<IEventHandlersCollection, EventHandlers>();
var assembly = typeof(EventHandlers).Assembly
.GetTypes()
.Where(e => e.IsClass)
.Where(e => !e.IsAbstract)
.Where(e => e.GetInterface(nameof(IEventHandler)) is not null)
.ToArray();
foreach (var type in assembly)
{
services.AddSingleton(type);
}
types = assembly;
return services;
}
}
}
| 29.686275 | 107 | 0.733818 | [
"MIT"
] | SlenderEmpire/CraftAI | gate/SEGate.Logic/EventHandler.Collection/EventCollection.cs | 1,516 | C# |
using Xamarin.Forms;
namespace CardboardKnight.UI.Converters
{
public static class ColourHelper
{
public static string CurrentThemeToString()
{
OSAppTheme currentTheme = Application.Current.RequestedTheme;
if (currentTheme == OSAppTheme.Light)
return "Light";
else
return "Dark";
}
public static Color GetColour(string s)
{
Application.Current.Resources.TryGetValue(s, out var result);
return (Color)result;
}
}
} | 24.73913 | 73 | 0.578207 | [
"MIT"
] | TheCardboardKnight/App | CardboardKnight.UI/Converters/ColourHelper.cs | 571 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AElf.Kernel;
using AElf.Kernel.Blockchain.Application;
using AElf.Kernel.Blockchain.Domain;
using AElf.Kernel.Blockchain.Events;
using AElf.Kernel.SmartContractExecution.Application;
using AElf.Kernel.TransactionPool.Infrastructure;
using AElf.Types;
namespace AElf.OS
{
public class MockTxHub : ITxHub
{
private readonly ITransactionManager _transactionManager;
private readonly IBlockchainService _blockchainService;
private readonly Dictionary<Hash, Transaction> _allTransactions =
new Dictionary<Hash, Transaction>();
private long _bestChainHeight = Constants.GenesisBlockHeight - 1;
private Hash _bestChainHash = Hash.Empty;
public MockTxHub(ITransactionManager transactionManager, IBlockchainService blockchainService)
{
_transactionManager = transactionManager;
_blockchainService = blockchainService;
}
public async Task<ExecutableTransactionSet> GetExecutableTransactionSetAsync(int transactionCount = 0)
{
var executableTransactionSet = await Task.FromResult(new ExecutableTransactionSet
{
PreviousBlockHash = _bestChainHash,
PreviousBlockHeight = _bestChainHeight,
Transactions = _allTransactions.Values.ToList()
});
return executableTransactionSet;
}
public async Task HandleTransactionsReceivedAsync(TransactionsReceivedEvent eventData)
{
foreach (var transaction in eventData.Transactions)
{
if (_allTransactions.ContainsKey(transaction.GetHash()))
continue;
_allTransactions.Add(transaction.GetHash(), transaction);
await _transactionManager.AddTransactionAsync(transaction);
}
}
public Task HandleBlockAcceptedAsync(BlockAcceptedEvent eventData)
{
CleanTransactions(eventData.Block.Body.TransactionIds.ToList());
return Task.CompletedTask;
}
public async Task HandleBestChainFoundAsync(BestChainFoundEventData eventData)
{
_bestChainHeight = eventData.BlockHeight;
_bestChainHash = eventData.BlockHash;
await Task.CompletedTask;
}
public async Task HandleNewIrreversibleBlockFoundAsync(NewIrreversibleBlockFoundEvent eventData)
{
await Task.CompletedTask;
}
public async Task HandleUnexecutableTransactionsFoundAsync(UnexecutableTransactionsFoundEvent eventData)
{
CleanTransactions(eventData.Transactions);
await Task.CompletedTask;
}
public async Task<QueuedTransaction> GetQueuedTransactionAsync(Hash transactionId)
{
if (!_allTransactions.TryGetValue(transactionId, out var transaction))
{
return null;
}
var queuedTransaction = await Task.FromResult(new QueuedTransaction
{
TransactionId = transactionId,
Transaction = transaction
});
return queuedTransaction;
}
public Task<int> GetAllTransactionCountAsync()
{
return Task.FromResult(_allTransactions.Count);
}
public Task<int> GetValidatedTransactionCountAsync()
{
return Task.FromResult(_allTransactions.Count);
}
public Task<bool> IsTransactionExistsAsync(Hash transactionId)
{
throw new System.NotImplementedException();
}
private void CleanTransactions(IEnumerable<Hash> transactionIds)
{
foreach (var transactionId in transactionIds)
{
_allTransactions.Remove(transactionId, out _);
}
}
}
} | 33.728814 | 112 | 0.649497 | [
"MIT"
] | 380086154/AElf | test/AElf.OS.TestBase/MockTxHub.cs | 3,980 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Globalization;
using Microsoft.Extensions.Options;
using Microsoft.Identity.Web.Test.Common;
using Xunit;
namespace Microsoft.Identity.Web.Test
{
public class MicrosoftIdentityOptionsTests
{
private MicrosoftIdentityOptions microsoftIdentityOptions;
private const string AzureAd = "AzureAd";
private const string AzureAdB2C = "AzureAdB2C";
[Fact]
public void IsB2C_NotNullOrEmptyUserFlow_ReturnsTrue()
{
var options = new MicrosoftIdentityOptions()
{
SignUpSignInPolicyId = TestConstants.B2CSignUpSignInUserFlow,
};
Assert.True(options.IsB2C);
}
[Fact]
public void IsB2C_NullOrEmptyUserFlow_ReturnsFalse()
{
var options = new MicrosoftIdentityOptions();
Assert.False(options.IsB2C);
options.SignUpSignInPolicyId = string.Empty;
Assert.False(options.IsB2C);
}
[Theory]
[InlineData(TestConstants.ClientId, TestConstants.AadInstance, TestConstants.TenantId, null, AzureAd, null)]
[InlineData(null, TestConstants.AadInstance, TestConstants.TenantId, null, null, AzureAd, MissingParam.ClientId)]
[InlineData("", TestConstants.AadInstance, TestConstants.TenantId, null, null, AzureAd, MissingParam.ClientId)]
[InlineData(TestConstants.ClientId, null, TestConstants.TenantId, null, null, AzureAd, MissingParam.Instance)]
[InlineData(TestConstants.ClientId, "", TestConstants.TenantId, null, null, AzureAd, MissingParam.Instance)]
[InlineData(TestConstants.ClientId, TestConstants.AadInstance, null, null, null, AzureAd, MissingParam.TenantId)]
[InlineData(TestConstants.ClientId, TestConstants.AadInstance, "", null, null, AzureAd, MissingParam.TenantId)]
[InlineData(TestConstants.ClientId, TestConstants.B2CInstance, null, TestConstants.B2CSignUpSignInUserFlow, TestConstants.B2CTenant, AzureAdB2C)]
[InlineData(TestConstants.ClientId, TestConstants.B2CInstance, null, TestConstants.B2CSignUpSignInUserFlow, null, AzureAdB2C, MissingParam.Domain)]
[InlineData(TestConstants.ClientId, TestConstants.B2CInstance, null, TestConstants.B2CSignUpSignInUserFlow, "", AzureAdB2C, MissingParam.Domain)]
public void ValidateRequiredMicrosoftIdentityOptions(
string clientId,
string instance,
string tenantid,
string signUpSignInPolicyId,
string domain,
string optionsName,
MissingParam missingParam = MissingParam.None)
{
microsoftIdentityOptions = new MicrosoftIdentityOptions
{
ClientId = clientId,
Instance = instance,
TenantId = tenantid,
};
if (optionsName == AzureAdB2C)
{
microsoftIdentityOptions.SignUpSignInPolicyId = signUpSignInPolicyId;
microsoftIdentityOptions.Domain = domain;
}
MicrosoftIdentityOptionsValidation microsoftIdentityOptionsValidation = new MicrosoftIdentityOptionsValidation();
ValidateOptionsResult result = microsoftIdentityOptionsValidation.Validate(optionsName, microsoftIdentityOptions);
CheckReturnValueAgainstExpectedMissingParam(missingParam, result);
}
private void CheckReturnValueAgainstExpectedMissingParam(MissingParam missingParam, ValidateOptionsResult result)
{
if (result.Failed == true)
{
string msg = string.Format(CultureInfo.InvariantCulture, "The '{0}' option must be provided.", missingParam);
Assert.Equal(msg, result.FailureMessage);
}
else
{
Assert.True(result.Succeeded);
}
}
public enum MissingParam
{
None = 0,
ClientId = 1,
Instance = 2,
TenantId = 3,
Domain = 4,
}
}
}
| 40.735294 | 155 | 0.660168 | [
"MIT"
] | jg11jg/microsoft-identity-web | tests/Microsoft.Identity.Web.Test/MicrosoftIdentityOptionsTests.cs | 4,157 | C# |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// 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.Text;
namespace OpenTK.Compute
{
}
| 36.25 | 83 | 0.760153 | [
"BSD-3-Clause"
] | 1975781737/xamarin-macios | src/OpenGLES/OpenTK/Compute/CLHelper.cs | 1,305 | C# |
using System.CodeDom.Compiler;
using System.Threading;
using System.Threading.Tasks;
//------------------------------------------------------------------------------
// This code was auto-generated by ApiGenerator x.x.x.x.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//------------------------------------------------------------------------------
namespace Scenario2.Api.Generated.Contracts.Files
{
/// <summary>
/// Domain Interface for RequestHandler.
/// Description: Get File By Id.
/// Operation: GetFileById.
/// Area: Files.
/// </summary>
[GeneratedCode("ApiGenerator", "x.x.x.x")]
public interface IGetFileByIdHandler
{
/// <summary>
/// Execute method.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="cancellationToken">The cancellation token.</param>
Task<GetFileByIdResult> ExecuteAsync(GetFileByIdParameters parameters, CancellationToken cancellationToken = default);
}
} | 36.965517 | 126 | 0.572761 | [
"MIT"
] | atc-net/atc-rest-api-generator | test/Atc.Rest.ApiGenerator.Tests/IntegrationTests/Scenarios/Scenario2/Verify/src/Scenario2.Api.Generated/Contracts/Files/Interfaces/IGetFileByIdHandler.verified.cs | 1,074 | C# |
using UnityEngine;
public class CameraController : MonoBehaviour {
public GameObject player;
Vector3 offset;
// Use this for initialization
void Start() {
offset = transform.position - player.transform.position;
}
// `LateUpdate` invokes after `Update`.
void LateUpdate() {
transform.position = player.transform.position + offset;
}
}
| 20.277778 | 60 | 0.706849 | [
"MIT"
] | jkereako/RollABall | Assets/Scripts/CameraController.cs | 367 | C# |
namespace NxBRE.Test.InferenceEngine {
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using NxBRE.InferenceEngine;
using NxBRE.InferenceEngine.Core;
using NxBRE.InferenceEngine.Rules;
using NxBRE.Util;
[TestFixture]
public class TestCore {
private Fact fact1;
private Fact fact2;
private Fact fact3;
private Fact fact3bis;
private Fact factX;
private Atom imp2;
private Atom imp2bis;
private Atom impX;
private Atom atom2_2;
private Atom atom3;
private Atom atomF;
[TestFixtureSetUp]
public void Init() {
atom2_2 = new Atom("luxury", new Variable("product"));
atom3 = new Atom("spending", new Variable("customer"), new Individual("min(5000,EUR)"), new Individual("previous year"));
atomF = new Atom("spending", new Variable("customer"), new Function(Function.FunctionResolutionType.Binder, "min(5000,EUR)", null, "min", new string[]{"5000","EUR"}), new Individual("previous year"));
fact1 = new Fact("premium", new Individual("Peter Miller"));
fact2 = new Fact("spending", new Individual("Peter Miller"), new Individual("min(5000,EUR)"));
fact3 = new Fact("spending", new Individual("Peter Miller"), new Individual("min(5000,EUR)"), new Individual("previous year"));
fact3bis = new Fact("spending", new Individual("Peter Miller"), new Individual("min(5000,EUR)"), new Individual("previous year"));
factX = new Fact("spending", new Individual("John Q. Doe"), new Individual("min(5000,EUR)"), new Individual("previous year"));
imp2 = new Atom("discount", new Variable("customer"), new Variable("product"), new Individual("7.5 percent"));
imp2bis = new Atom("discount", new Variable("buyer"), new Variable("product"), new Individual("7.5 percent"));
impX = new Atom("discount", new Variable("buyer"), new Variable("product"), new Individual("6.5 percent"));
}
[Test]
public void Predicates()
{
IPredicate v1 = new Variable("one");
IPredicate v2 = new Variable("two");
IPredicate i1 = new Individual("one");
IPredicate i2 = new Individual("two");
Assert.AreEqual(v1, new Variable("one"), "Similar Variables");
Assert.IsFalse(v1.Equals(v2), "Different Variables");
Assert.IsFalse(v1.Equals(i2), "Variable differs from Individual");
Assert.AreEqual(i1, new Individual("one"), "Similar Individuals");
Assert.IsFalse(i1.Equals(i2), "Different Variables");
Assert.IsFalse(i2.Equals(v1), "Individual differs from Variable");
}
[Test]
public void FactSlots() {
Fact fact = new Fact("spending", new Slot("client", new Individual("Peter Miller")), new Individual("min(5000,EUR)"));
Assert.AreEqual("Peter Miller", fact.GetPredicateValue("client"), "Slot predicate value");
Fact clone = (Fact)fact.Clone();
fact = null;
Assert.AreEqual("Peter Miller", clone.GetPredicateValue("client"), "Slot predicate value after cloning");
}
[Test]
public void AtomSlots() {
Atom atom = new Atom("spending", new Slot("client", new Variable("buyer")), new Function(Function.FunctionResolutionType.Binder, "min(5000,EUR)", null, "min", new string[]{"5000","EUR"}));
Assert.AreEqual(typeof(Variable), atom.GetPredicate("client").GetType(), "Slot predicate");
Atom clone = (Atom)atom.Clone();
atom = null;
Assert.AreEqual(typeof(Variable), clone.GetPredicate("client").GetType(), "Slot predicate after cloning");
}
[Test][ExpectedException(typeof(ArgumentException))]
public void SlotInSlot() {
new Slot("error", new Slot("test", new Individual("44")));
}
[Test]
public void TypedRelationMatching() {
Assert.IsTrue(new Atom("test", new Individual("true"), new Variable("foo"))
.Matches(new Fact("test", new Individual(true), new Individual("foo"))),
"Boolean");
Assert.IsFalse(new Atom("test", new Individual("false"), new Variable("foo"))
.Matches(new Fact("test", new Individual(true), new Individual("foo"))),
"Boolean");
Assert.IsTrue(new Atom("test", new Individual("44"), new Variable("foo"))
.Matches(new Fact("test", new Individual((SByte) 44), new Individual("foo"))),
"SByte");
Assert.IsTrue(new Atom("test", new Individual("11"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Int16) 11), new Individual("foo"))),
"Int16");
Assert.IsTrue(new Atom("test", new Individual("22"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Int32) 22), new Individual("foo"))),
"Int32");
Assert.IsTrue(new Atom("test", new Individual("33"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Int64) 33), new Individual("foo"))),
"Int64");
Assert.IsTrue(new Atom("test", new Individual("3.14"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Single) 3.14), new Individual("foo"))),
"Single");
Assert.IsTrue(new Atom("test", new Individual("6.28"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Double) 6.28), new Individual("foo"))),
"Double");
Assert.IsTrue(new Atom("test", new Individual("9.42"), new Variable("foo"))
.Matches(new Fact("test", new Individual((Decimal) 9.42), new Individual("foo"))),
"Decimal");
Assert.IsTrue(new Atom("test", new Individual("2003-12-25"), new Variable("foo"))
.Matches(new Fact("test", new Individual(new DateTime(2003, 12, 25)), new Individual("foo"))),
"Date");
Assert.IsTrue(new Atom("test", new Individual("1969-07-21T02:56:00"), new Variable("foo"))
.Matches(new Fact("test", new Individual(new DateTime(1969, 07, 21, 02, 56, 00)), new Individual("foo"))),
"DateTime");
Assert.IsTrue(new Atom("test", new Individual("07:15:30"), new Variable("foo"))
.Matches(new Fact("test", new Individual(DateTime.Today.Add(new TimeSpan(7, 15, 30))), new Individual("foo"))),
"Time");
}
[Test]
public void Implications()
{
Assert.IsFalse(imp2.Equals(imp2bis), "Different (2 vars, 1 ind)");
Assert.IsFalse(impX.Equals(imp2), "Different (2 vars, 1 ind)");
Assert.IsTrue(imp2.Matches(imp2bis), "Matches (2 vars, 1 ind)");
Assert.IsFalse(impX.Matches(imp2), "Non-matches (2 vars, 1 ind)");
Assert.IsTrue(imp2.IsIntersecting(imp2bis), "Non-similar (2 vars, 1 ind)");
Assert.IsFalse(impX.IsIntersecting(imp2), "Non-similar bis (2 vars, 1 ind)");
}
[Test][ExpectedException(typeof(ArgumentOutOfRangeException))]
public void WrongImplicationLowPriority() {
new Implication(null, -1, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(ArgumentOutOfRangeException))]
public void WrongImplicationHiPriority() {
new Implication(null, 101, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(ArgumentOutOfRangeException))]
public void WrongImplicationLowSalience() {
Implication i = new Implication(null, ImplicationPriority.Medium, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
i.Salience = -1;
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(ArgumentOutOfRangeException))]
public void WrongImplicationHiSalience() {
Implication i = new Implication(null, ImplicationPriority.Medium, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
i.Salience = 100;
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(BREException))]
public void ImplicationBaseDuplicatedLabel() {
ImplicationBase ib = new ImplicationBase();
ib.Add(new Implication("impMedLow", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3)));
ib.Add(new Implication("impMedLow", 75, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3)));
Assert.Fail("Should never reach me!");
}
[Test]
public void ImplicationBase() {
ImplicationBase ib = new ImplicationBase();
Implication imp = new Implication("impMedLow", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(imp);
ib.Add(new Implication("impMedHi", 75, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3)));
Assert.AreEqual(imp, ib.Get("impMedLow"), "Get");
Assert.IsNull(ib.Get("missing bit"), "Failed Get");
}
[Test][ExpectedException(typeof(BREException))]
public void MutexMissing() {
ImplicationBase ib = new ImplicationBase();
Implication imp = new Implication("impMedLow", 25, "missing", String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(imp);
ib.Add(new Implication("impMedHi", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3)));
new MutexManager(ib).AnalyzeImplications();
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(BREException))]
public void PreconditionMissing() {
ImplicationBase ib = new ImplicationBase();
Implication impMedLow = new Implication("impMedLow", 25, String.Empty, "missing", imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(impMedLow);
ib.Add(new Implication("impMedHi", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3)));
new PreconditionManager(ib).AnalyzeImplications();
Assert.Fail("Should never reach me!");
}
[Test]
public void GetPreconditionChildren() {
ImplicationBase ib = new ImplicationBase();
Implication impMedLow = new Implication("impMedLow", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(impMedLow);
Implication impMedHi = new Implication("impMedHi", 25, String.Empty, "impMedLow", imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(impMedHi);
new PreconditionManager(ib).AnalyzeImplications();
IList<Implication> preconditionChildren = ib.GetPreconditionChildren(impMedLow);
Assert.AreEqual(1, preconditionChildren.Count, "preconditionChildren size");
Assert.IsTrue(preconditionChildren.Contains(impMedHi), "preconditionChildren content");
}
[Test][ExpectedException(typeof(BREException))]
public void PreconditionIsMutex() {
ImplicationBase ib = new ImplicationBase();
Implication impMedLow = new Implication("impMedLow", 25, "impMedHi", String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(impMedLow);
Implication impMedHi = new Implication("impMedHi", 25, String.Empty, "impMedLow", imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
ib.Add(impMedHi);
new MutexManager(ib).AnalyzeImplications();
new PreconditionManager(ib).AnalyzeImplications();
Assert.Fail("Should never reach me!");
}
[Test]
public void Matching()
{
Assert.IsTrue(atom3.Matches(fact3), "Matching");
Assert.IsFalse(atom2_2.Matches(fact3), "Non-Matching");
}
[Test]
public void VariableTranslation() {
Atom template = new Atom("own", new Variable("person"), new Variable("object"));
Atom source = new Atom("own", new Variable("person"), new Variable("stuff"));
Atom target = new Atom("belongs", new Variable("person"), new Variable("stuff"));
Atom expected = new Atom("belongs", new Variable("person"), new Variable("object"));
Assert.AreEqual(expected, RulesUtil.TranslateVariables(template, source, target));
}
private static int CountEnumerator(IEnumerator<Fact> e) {
int result = 0;
while(e.MoveNext()) result++;
return result;
}
private int RunStrictTypingFactBaseTest(bool strictTyping) {
FactBase fb = new FactBase();
fb.strictTyping = strictTyping;
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("foo"),
new Individual(7000))), "Assert 'foo Spending'");
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("bar"),
new Individual("7000"))), "Assert 'bar Spending'");
Atom filter = new Atom("spending",
new Variable("name"),
new Individual("7000"));
return CountEnumerator(fb.Select(filter, null));
}
[Test]
public void StrictTypingFactBase() {
Assert.AreEqual(1, RunStrictTypingFactBaseTest(true), "Strict typing selection");
}
[Test]
public void NonStrictTypingFactBase() {
Assert.AreEqual(2, RunStrictTypingFactBaseTest(false), "Non-Strict typing selection");
}
[Test]
public void ExcludeFactsFromSelection() {
FactBase fb = new FactBase();
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("Peter Miller"),
new Individual(5000),
new Individual("previous year"))), "Assert 'P.Miller Spending'");
Fact jqdSpending = new Fact("JQD Spending",
"spending",
new Individual("John Q.Clone Doe"),
new Individual(7000),
new Individual("previous year"));
Assert.IsTrue(fb.Assert(jqdSpending), "Assert 'JQD Spending'");
Atom filter = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThanEqualTo", "5000"),
new Individual("previous year"));
Assert.AreEqual(2, CountEnumerator(fb.Select(filter, null)), "Query with NxBRE function and no fact exclusion");
IList<Fact> excludedFacts = new List<Fact>();
excludedFacts.Add(jqdSpending);
Assert.AreEqual(1, CountEnumerator(fb.Select(filter, excludedFacts)), "Query with NxBRE function with fact exclusion");
}
private void PopulateFactBase(FactBase fb) {
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("foo"),
new Individual(7000))), "Assert 'foo Spending'");
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("Peter Miller"),
new Individual(5000),
new Individual("previous year"))), "Assert 'P.Miller Spending'");
Assert.IsTrue(fb.Assert(new Fact("JQD Spending",
"spending",
new Individual("John Q.Clone Doe"),
new Individual(7000),
new Individual("previous year"))), "Assert 'JQD Spending'");
Assert.IsTrue(fb.Assert(new Fact("lending",
new Individual("John Q.Clone Doe"),
new Individual(7000),
new Individual("previous year"))), "Assert 'JQD Lending'");
}
[Test]
public void PredicateNxBREFunction() {
FactBase fb = new FactBase();
PopulateFactBase(fb);
Atom filter = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "5000"),
new Individual("previous year"));
Assert.AreEqual(1, CountEnumerator(fb.Select(filter, null)), "Query with NxBRE function");
}
[Test]
public void ProcessAnd() {
FactBase fb = new FactBase();
PopulateFactBase(fb);
Atom atom1 = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "5000"),
new Individual("previous year"));
Atom atom2 = new Atom("lending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "5000"),
new Individual("previous year"));
IList<IList<FactBase.PositiveMatchResult>> result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.And, atom1, atom2));
Assert.AreEqual(1, result.Count, "2 positive atoms");
atom2 = new Atom("lending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "15000"),
new Individual("previous year"));
result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.And, atom1, atom2));
Assert.AreEqual(0, result.Count, "1 positive and 1 negative atoms");
atom2 = new Atom("spending", new Variable("otherName"), new Variable("whateverAmount"), new Individual("previous year"));
result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.And, atom1, atom2));
Assert.AreEqual(2, result.Count, "2 positive combinatorial atoms");
atom2 = new Atom("spending", new Variable("otherName"), new Variable("whateverAmount"), new Individual("unknown year"));
result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.And, atom1, atom2));
Assert.AreEqual(0, result.Count, "1 positive and 1 negative combinatorial atoms");
}
[Test]
public void ProcessOr() {
FactBase fb = new FactBase();
PopulateFactBase(fb);
Atom atom1 = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "1000"),
new Individual("previous year"));
Atom atom2 = new Atom("lending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "5000"),
new Individual("previous year"));
IList<IList<FactBase.PositiveMatchResult>> result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.Or, atom1, atom2));
Assert.AreEqual(3, result.Count, "2 positive atoms");
atom1 = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "9999"),
new Individual("previous year"));
result = fb.ProcessAtomGroup(new AtomGroup(AtomGroup.LogicalOperator.Or, atom1, atom2));
Assert.AreEqual(1, result.Count, "1 positive atom");
}
[Test]
public void FactBaseCloning() {
FactBase fb = new FactBase();
PopulateFactBase(fb);
FactBase clone = (FactBase)fb.Clone();
Assert.AreEqual(fb.Count, clone.Count, "Same number of facts");
Fact jqdSpending = clone.GetFact("JQD Spending");
Assert.AreEqual("JQD Spending", jqdSpending.Label, "Correct fact label");
int countBefore = clone.Count;
Assert.IsTrue(clone.Retract(jqdSpending), "Retracted 'JQD Spending'");
Assert.AreEqual(countBefore-1, clone.Count, "Count after retraction");
Assert.IsFalse(clone.Exists(jqdSpending), "'JQD Spending' really retracted");
Assert.IsTrue(fb.Exists(jqdSpending), "'JQD Spending' still in original");
Atom filter = new Atom("spending",
new Variable("name"),
new Function(Function.FunctionResolutionType.NxBRE, "foo", null, "GreaterThan", "5000"),
new Individual("previous year"));
Assert.AreEqual(1, CountEnumerator(fb.Select(filter, null)), "Query on the original");
Assert.AreEqual(0, CountEnumerator(clone.Select(filter, null)), "Query on the clone");
}
[Test]
public void AtomFunctionBinder() {
Assert.IsTrue(new AtomFunction(AtomFunction.RelationResolutionType.NxBRE, false, null, "nxbre:Equals", new Individual(123), new Individual(123)).PositiveRelation, "AtomFunction: true PositiveRelation");
Assert.IsFalse(new AtomFunction(AtomFunction.RelationResolutionType.NxBRE, false, null, "nxbre:Equals", new Individual(123), new Individual(321)).PositiveRelation, "AtomFunction: false PositiveRelation");
}
[Test][ExpectedException(typeof(BREException))]
public void AtomFunctionWithFunctionPredicate() {
new AtomFunction(AtomFunction.RelationResolutionType.NxBRE, false, null, "nxbre:Equals", new Individual(123), new Function(Function.FunctionResolutionType.Binder, "123", null, "Test", new string[0]));
Assert.Fail("Should never reach me!");
}
[Test]
public void Facts()
{
Assert.AreEqual(fact3, fact3bis, "Equal (3 ind)");
Assert.IsTrue(fact3.IsFact, "fact3 IsFact");
Assert.IsFalse(factX.Equals(fact3), "Different (3 ind)");
Assert.IsFalse(atom3.IsFact, "atom3 Is Not Fact");
Assert.IsFalse(new Fact("spouse", new Individual("Man"), new Individual("Woman"))
.Equals(new Fact("spouse", new Individual("Woman"), new Individual("Man"))),
"Same type non-equal facts");
}
[Test][ExpectedException(typeof(BREException))]
public void FactNonFact() {
new Fact("luxury", new Variable("product"));
Assert.Fail("Should never reach me!");
}
[Test]
public void RenameFact()
{
Fact spendingPM1 = new Fact("Spending of Peter Miller",
"spending",
new Individual("Peter Miller"),
new Individual("min(5000,EUR)"),
new Individual("previous year"));
String newLabel = "Expenses of Peter Miller";
Fact spendingPM2 = spendingPM1.ChangeLabel(newLabel);
Assert.AreEqual(spendingPM2.Label, newLabel, "Fact has been renamed");
Assert.AreEqual(spendingPM1, spendingPM2, "Renamed facts are equals");
}
[Test]
public void FactBaseAssertRetract()
{
FactBase fb = new FactBase();
Assert.IsTrue(fb.Assert(new Fact("spending",
new Individual("Peter Miller"),
new Individual("min(5000,EUR)"),
new Individual("previous year"))), "Assert 'P.Miller Spending'");
Assert.IsTrue(fb.Assert(new Fact("JQD Spending",
"spending",
new Individual("John Q.Clone Doe"),
new Individual("min(7000,EUR)"),
new Individual("previous year"))), "Assert 'JQD Spending'");
Assert.IsNotNull(fb.GetFact("JQD Spending"), "Exist 'JQD Spending'");
Assert.IsFalse(fb.Assert(fact3bis), "Assert fact3bis");
Assert.IsTrue(fb.Assert(factX), "Assert factX");
Fact jqdSpending = fb.GetFact("JQD Spending");
Assert.IsTrue(fb.Exists(jqdSpending));
Assert.IsTrue(fb.Retract(jqdSpending));
Assert.IsFalse(fb.Exists(jqdSpending));
Assert.IsNull(fb.GetFact("JQD Spending"), "Get Retracted 'JQD Spending'");
}
[Test]
public void FactBaseAssertModify()
{
FactBase fb = new FactBase();
Fact spendingPM1 = new Fact("Spending of Peter Miller",
"spending",
new Individual("Peter Miller"),
new Individual("min(5000,EUR)"),
new Individual("previous year"));
Assert.IsTrue(fb.Assert(spendingPM1), "Assert 'P.Miller Spending' v1");
Assert.IsFalse(fb.Assert(spendingPM1), "Can not assert 'P.Miller Spending' v1 twice!");
Assert.IsTrue(fb.Exists(spendingPM1), "Exists 'P.Miller Spending' v1");
Fact spendingJQD = new Fact("Spending of John Q. Doe",
"spending",
new Individual("John Q.Clone Doe"),
new Individual("min(7000,EUR)"),
new Individual("previous year"));
Assert.IsTrue(fb.Assert(spendingJQD), "Assert 'JQD Spending'");
Fact spendingPM2 = new Fact("spending",
new Individual("Peter Miller"),
new Individual("min(9999,EUR)"),
new Individual("previous year"));
Assert.IsTrue(fb.Modify(spendingPM1, spendingPM2), "Modify 'P.Miller Spending' v1 to v2");
Assert.IsNotNull(fb.GetFact(spendingPM1.Label), "(1) Label has been maintained");
Assert.AreEqual(2, fb.Count, "(1) FactBase size");
Assert.IsFalse(fb.Exists(spendingPM1), "(1) Not Exists 'P.Miller Spending' v1");
Assert.IsTrue(fb.Exists(spendingPM2), "(1) Exists 'P.Miller Spending' v2");
Assert.IsTrue(fb.Exists(spendingJQD), "(1) Exists 'JQD Spending'");
Assert.IsFalse(fb.Modify(spendingPM1, spendingPM2), "Can not modify an inexistant fact");
Assert.AreEqual(2, fb.Count, "(2) FactBase size");
Assert.IsFalse(fb.Exists(spendingPM1), "(2) Not Exists 'P.Miller Spending' v1");
Assert.IsTrue(fb.Exists(spendingPM2), "(2) Exists 'P.Miller Spending' v2");
Assert.IsTrue(fb.Exists(spendingJQD), "(2) Exists 'JQD Spending'");
Assert.IsTrue(fb.Modify(spendingPM2, spendingPM2), "Can modify a fact to itself");
Assert.AreEqual(2, fb.Count, "(3) FactBase size");
Assert.IsFalse(fb.Exists(spendingPM1), "(3) Not Exists 'P.Miller Spending' v1");
Assert.IsTrue(fb.Exists(spendingPM2), "(3) Exists 'P.Miller Spending' v2");
Assert.IsTrue(fb.Exists(spendingJQD), "(3) Exists 'JQD Spending'");
Assert.IsTrue(fb.Modify(spendingJQD, spendingPM2), "Modify 'JQD Spending' to 'P.Miller Spending' v2");
Assert.IsNotNull(fb.GetFact(spendingJQD.Label), "(4) Label has been maintained");
Assert.AreEqual(1, fb.Count, "(4) FactBase size");
Assert.IsFalse(fb.Exists(spendingPM1), "(4) Not Exists 'P.Miller Spending' v1");
Assert.IsTrue(fb.Exists(spendingPM2), "(4) Exists 'P.Miller Spending' v2");
Assert.IsFalse(fb.Exists(spendingJQD), "(4) Not Exists 'JQD Spending'");
}
[Test]
public void Agenda() {
Agenda a = new Agenda();
Implication impLow = new Implication("impLow", ImplicationPriority.Minimum, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Implication impLowMed = new Implication("impLowMed", 25, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Implication impMed = new Implication("impMed", ImplicationPriority.Medium, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Implication impMedSaLo = new Implication("impMedSaLo", ImplicationPriority.Medium, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
impMedSaLo.Salience = 1;
Assert.AreEqual(5101, impMedSaLo.Weight, "Weight impMedSaLo");
Implication impMedSaHi = new Implication("impMedSaHi", ImplicationPriority.Medium, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
impMedSaHi.Salience = 99;
Assert.AreEqual(5199, impMedSaHi.Weight, "Weight impMedSaLo");
Implication impMedHi = new Implication("impMedHi", 75, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
Implication impHi = new Implication("impHi", ImplicationPriority.Maximum, String.Empty, String.Empty, imp2, new AtomGroup(AtomGroup.LogicalOperator.And, atom2_2, atom3));
// schedule in any order
a.Schedule(impMedSaHi);
a.Schedule(impLow);
a.Schedule(impMed);
a.Schedule(impMedHi);
a.Schedule(impMedSaLo);
a.Schedule(impLowMed);
a.Schedule(impHi);
// prepare for execution, which should sort this mess out
a.PrepareExecution();
Implication[] expected = new Implication[] {impHi, impMedHi, impMedSaHi, impMedSaLo, impMed, impLowMed, impLow};
int i = 0;
Implication implicationParser;
while (a.HasMoreToExecute) {
implicationParser = a.NextToExecute;
Assert.IsTrue(implicationParser.Equals(expected[i]),
"Agenda not ordered: " +
implicationParser.Label +
"::" +
implicationParser.Weight +
" != " +
expected[i].Label +
"::" +
expected[i].Weight);
i++;
}
}
[Test]
public void QueryIsNotImplication() {
Query query = new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(5000,EUR)"),
new Individual("previous year"))));
Implication implication = new Implication("get spending",
ImplicationPriority.Medium,
String.Empty,
String.Empty,
atom2_2,
query.AtomGroup);
Assert.IsFalse(query.Equals(implication), "QueryIsNotImplication");
}
[Test][ExpectedException(typeof(BREException))]
public void QueryBaseDuplicatedLabel() {
QueryBase qb = new QueryBase();
qb.Add(new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(5000,EUR)"),
new Individual("previous year")))));
qb.Add(new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(7000,EUR)"),
new Individual("previous year")))));
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(IndexOutOfRangeException))]
public void QueryBaseIndexSubZero() {
QueryBase qb = new QueryBase();
qb.Add(new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(5000,EUR)"),
new Individual("previous year")))));
qb.Get(-1);
Assert.Fail("Should never reach me!");
}
[Test][ExpectedException(typeof(IndexOutOfRangeException))]
public void QueryBaseIndexTooHigh() {
QueryBase qb = new QueryBase();
qb.Add(new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(5000,EUR)"),
new Individual("previous year")))));
qb.Get(2);
Assert.Fail("Should never reach me!");
}
[Test]
public void QueryBase() {
QueryBase qb = new QueryBase();
Query query1 = new Query("get spending",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("spending",
new Variable("customer"),
new Individual("min(5000,EUR)"),
new Individual("previous year"))));
qb.Add(query1);
Assert.AreEqual(1, qb.Count, "(1) QueriesCount");
Query getQ1 = qb.Get("get spending");
Assert.AreEqual(query1, getQ1, "Get Query Is Equal");
Assert.IsTrue(((Atom)query1.AtomGroup.Members[0]).IsIntersecting((Atom)getQ1.AtomGroup.Members[0]), "Get Query Is Similar");
Assert.IsNull(qb.Get("find me if you can"), "Missing query");
Query query2 = new Query("get earning",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("earning",
new Variable("customer"),
new Individual("min(99999,EUR)"),
new Individual("previous year"))));
qb.Add(query2);
Assert.AreEqual(2, qb.Count, "(2) QueriesCount");
qb.Remove(qb.Get(0));
Assert.AreEqual(1, qb.Count, "(3) QueriesCount");
Query getQ2 = qb.Get(0);
Assert.AreEqual(query2, getQ2, "(3) Get Query Is Equal");
Assert.IsTrue(((Atom)query2.AtomGroup.Members[0]).IsIntersecting((Atom)getQ2.AtomGroup.Members[0]), "(3) Get Query Is Similar");
qb.Add(new Query("to be killed",
new AtomGroup(AtomGroup.LogicalOperator.And, new Atom("victim",
new Variable("test"),
new Individual("whatsoever")))));
Assert.AreEqual(2, qb.Count, "(4) QueriesCount");
qb.Remove(qb.Get("to be killed"));
Assert.AreEqual(1, qb.Count, "(5) QueriesCount");
qb.Remove(query2);
Assert.AreEqual(0, qb.Count, "(6) QueriesCount");
}
[Test]
public void AtomResolveFunctions() {
Assert.AreEqual(atom3, RulesUtil.ResolveFunctions(atom3), "Atom without functions");
Assert.IsTrue(atomF.HasFunction, "atom Hasfunction");
Atom atomNoF = RulesUtil.ResolveFunctions(atomF);
Assert.IsFalse(atomF.Equals(atomNoF), "Atom with functions");
Assert.IsFalse(atomNoF.HasFunction, "atomNoF Hasfunction");
Assert.IsTrue(fact3.Matches(atomNoF), "Fact and Atom match");
}
[Test]
public void FactResolve() {
Fact fact2bis = new Fact("spending", new Individual("Peter Miller"), new Individual(35000));
Fact fact2ter = RulesUtil.Resolve(fact2bis, atomF);
Assert.IsFalse(fact2.Equals(fact2bis));
Assert.IsTrue(fact2.Equals(fact2ter));
}
[Test]
public void AtomGroupMemberOrdering() {
AtomGroup child = new AtomGroup(AtomGroup.LogicalOperator.Or, atom2_2, atomF);
AtomGroup parent = new AtomGroup(AtomGroup.LogicalOperator.And, child, atom3);
Assert.AreEqual(child, parent.Members[0], "First member match");
Assert.AreEqual(atom3, parent.Members[1], "Second member match");
}
[Test]
public void AtomGroupOrderedMemberOrdering() {
AtomGroup child = new AtomGroup(AtomGroup.LogicalOperator.Or, atom2_2, atomF);
AtomGroup parent = new AtomGroup(AtomGroup.LogicalOperator.And, child, atom3);
Assert.AreEqual(child, parent.OrderedMembers[1], "First member match");
Assert.AreEqual(atom3, parent.OrderedMembers[0], "Second member match");
}
}
}
| 46.432468 | 208 | 0.616703 | [
"MIT"
] | Peidyen/NxBRE | NxBRE3/Test/InferenceEngine/TestCore.cs | 35,753 | 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("Displays.LCD.CharacterDisplay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Displays.LCD.CharacterDisplay")]
[assembly: AssemblyCopyright("Copyright © Wilderness Labs 2019")]
[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("a62994bb-886d-4c3f-a8e8-6f39af96f648")]
// 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("0.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
| 38.945946 | 84 | 0.752949 | [
"Apache-2.0"
] | patridge/Meadow.Foundation | Source/Peripheral_Libs/Displays.LCD.CharacterDisplay/Properties/AssemblyInfo.cs | 1,444 | C# |
// Copyright (c) Geta Digital. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System.Linq;
using System.Web.Mvc;
using EPiServer.ServiceLocation;
using Geta.Tags.Interfaces;
namespace Geta.Tags.Controllers
{
public class GetaTagsController : Controller
{
private readonly ITagService _tagService;
public GetaTagsController() : this (ServiceLocator.Current.GetInstance<ITagService>())
{
}
public GetaTagsController(ITagService tagService)
{
_tagService = tagService;
}
public JsonResult Index(string term, string groupKey = null)
{
var normalized = Normalize(term);
var tags = _tagService.GetAllTags();
if (IsNotEmpty(normalized))
{
tags = tags.Where(t => t.Name.ToLower().StartsWith(normalized.ToLower()));
if (IsNotEmpty(groupKey))
{
tags = tags.Where(t => t.GroupKey.Equals(groupKey));
}
}
var items = tags.OrderBy(t => t.Name)
.Select(t => t.Name)
.Take(10)
.ToList();
return Json(items, JsonRequestBehavior.AllowGet);
}
private static string Normalize(string term)
{
return string.IsNullOrWhiteSpace(term) ? string.Empty : term;
}
private static bool IsNotEmpty(string name)
{
return !string.IsNullOrEmpty(name);
}
}
} | 28.035088 | 94 | 0.571965 | [
"Apache-2.0"
] | Geta/Tags | src/Controllers/GetaTagsController.cs | 1,600 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using VkNet.Abstractions;
using VkNet.Extensions.Polling.Models.Configuration;
using VkNet.Extensions.Polling.Models.State;
using VkNet.Extensions.Polling.Models.Update;
using VkNet.Model;
using VkNet.Model.RequestParams;
namespace VkNet.Extensions.Polling
{
public class UserLongPoll :
LongPollBase<LongPollHistoryResponse, UserUpdate, UserLongPollServerState, UserLongPollConfiguration>
{
public UserLongPoll(IVkApi vkApi) : base(vkApi)
{
}
protected override bool Validate(IVkApi vkApi)
{
return vkApi.Users.Get(new long[] { }).Any();
}
protected override async Task<UserLongPollServerState> GetServerInformationAsync(IVkApi vkApi,
UserLongPollConfiguration longPollConfiguration, CancellationToken cancellationToken = default)
{
return await vkApi.Messages.GetLongPollServerAsync(true)
.ContinueWith(_ => new UserLongPollServerState(Convert.ToUInt64(_.Result.Ts), _.Result?.Pts ?? throw new InvalidOperationException("Не удалось получить Pts. Проблема при получении информации о сервере.")),
cancellationToken);
}
protected override Task<LongPollHistoryResponse> GetUpdatesAsync(IVkApi vkApi,
UserLongPollConfiguration userLongPollConfiguration,
UserLongPollServerState longPollServerInformation,
CancellationToken cancellationToken = default)
{
return vkApi.Messages.GetLongPollHistoryAsync(new MessagesGetLongPollHistoryParams
{
Pts = longPollServerInformation.Pts,
Ts = longPollServerInformation.Ts,
Fields = userLongPollConfiguration.Fields
}).ContinueWith(_ =>
{
longPollServerInformation.Update(_.Result.NewPts);
return _.Result;
}, cancellationToken);
}
protected override IEnumerable<UserUpdate> ConvertLongPollResponse(
LongPollHistoryResponse longPollResponse)
{
foreach (var message in longPollResponse.Messages)
{
UserUpdateSender updateSender;
if (message.FromId < 0)
updateSender = new UserUpdateSender(longPollResponse.Groups.First(_ => _.Id == message.FromId));
else
updateSender = new UserUpdateSender(longPollResponse.Profiles.First(_ => _.Id == message.FromId));
var userUpdate = new UserUpdate(message, updateSender);
yield return userUpdate;
}
}
}
} | 38.887324 | 221 | 0.66063 | [
"MIT"
] | vknet/VkNet.Extensions.Polling | src/VkNet.Extensions.Polling/UserLongPoll.cs | 2,818 | C# |
namespace Papu.Entities
{
public class ProductGroup
{
public int ProductId { get; set; }
public Product Product { get; set; }
public int GroupId { get; set; }
public Group Group { get; set; }
}
}
| 18.692308 | 44 | 0.567901 | [
"Unlicense"
] | dawidkurant/applications | Projekt Web API/Papu/Papu/Entities/Product/ProductGroup.cs | 245 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Relay
{
using System;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Client WebSocket Interface.
/// </summary>
public interface IClientWebSocket
{
/// <summary>
/// Client Websocket Options.
/// </summary>
IClientWebSocketOptions Options { get; }
/// <summary>
/// Http Response Message.
/// </summary>
HttpResponseMessage Response { get; }
/// <summary>
/// Websocket object.
/// </summary>
WebSocket WebSocket { get; }
/// <summary>
/// Connect to a WebSocket server as an asynchronous operation.
/// </summary>
/// <param name="uri">The URI of the WebSocket server to connect to.</param>
/// <param name="cancellationToken">A cancellation token used to propagate notification that the operation should be canceled.</param>
/// <returns></returns>
Task ConnectAsync(Uri uri, CancellationToken cancellationToken);
}
/// <summary>
/// Client Websocket Options interface.
/// </summary>
public interface IClientWebSocketOptions
{
/// <summary>
/// Gets or sets the proxy for WebSocket requests.
/// </summary>
IWebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the WebSocket protocol keep-alive interval.
/// </summary>
TimeSpan KeepAliveInterval { get; set; }
/// <summary>
/// Adds a sub-protocol to be negotiated during the WebSocket connection handshake.
/// </summary>
/// <param name="subProtocol">The WebSocket sub-protocol to add.</param>
void AddSubProtocol(string subProtocol);
/// <summary>
/// Sets the client buffer parameters.
/// </summary>
/// <param name="receiveBufferSize">The size, in bytes, of the client receive buffer.</param>
/// <param name="sendBufferSize">The size, in bytes, of the client send buffer.</param>
void SetBuffer(int receiveBufferSize, int sendBufferSize);
/// <summary>
/// Creates a HTTP request header and its value.
/// </summary>
/// <param name="name">The name of the HTTP header.</param>
/// <param name="value">The value of the HTTP header.</param>
void SetRequestHeader(string name, string value);
}
/// <summary>
/// Client WebSocket Factory interface.
/// </summary>
public interface IClientWebSocketFactory
{
/// <summary>
/// Create a ClientWebSocket.
/// </summary>
/// <returns></returns>
IClientWebSocket Create();
}
sealed class ClientWebSocketFactory : IClientWebSocketFactory
{
public static readonly ClientWebSocketFactory Default = new ClientWebSocketFactory(false);
public static readonly ClientWebSocketFactory DefaultBuiltIn = new ClientWebSocketFactory(true);
readonly bool useBuiltInWebSocket;
private ClientWebSocketFactory(bool useBuiltInWebSocket)
{
this.useBuiltInWebSocket = useBuiltInWebSocket;
}
public IClientWebSocket Create()
{
#if NETSTANDARD
if (!this.useBuiltInWebSocket)
{
if (Microsoft.Azure.Relay.WebSockets.NetCore21.ClientWebSocket.IsSupported())
{
return new Microsoft.Azure.Relay.WebSockets.NetCore21.ClientWebSocket();
}
return new Microsoft.Azure.Relay.WebSockets.NetStandard20.ClientWebSocket();
}
#endif // NETSTANDARD
return new FrameworkClientWebSocket(new System.Net.WebSockets.ClientWebSocket());
}
class FrameworkClientWebSocket : IClientWebSocket
{
readonly System.Net.WebSockets.ClientWebSocket client;
public FrameworkClientWebSocket(System.Net.WebSockets.ClientWebSocket client)
{
this.client = client;
this.Options = new FrameworkClientWebSocketOptions(this.client.Options);
}
public IClientWebSocketOptions Options { get; }
public HttpResponseMessage Response { get { return null; } }
public WebSocket WebSocket { get { return this.client; } }
public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
{
return this.client.ConnectAsync(uri, cancellationToken);
}
class FrameworkClientWebSocketOptions : IClientWebSocketOptions
{
readonly System.Net.WebSockets.ClientWebSocketOptions options;
public FrameworkClientWebSocketOptions(System.Net.WebSockets.ClientWebSocketOptions options)
{
this.options = options;
}
public IWebProxy Proxy
{
get { return this.options.Proxy; }
set { this.options.Proxy = value; }
}
public TimeSpan KeepAliveInterval
{
get { return this.options.KeepAliveInterval; }
set { this.options.KeepAliveInterval = value; }
}
public void AddSubProtocol(string subProtocol)
{
this.options.AddSubProtocol(subProtocol);
}
public void SetBuffer(int receiveBufferSize, int sendBufferSize)
{
this.options.SetBuffer(receiveBufferSize, sendBufferSize);
}
public void SetRequestHeader(string name, string value)
{
this.options.SetRequestHeader(name, value);
}
}
}
}
}
| 34.519774 | 142 | 0.589362 | [
"MIT"
] | Azure/azure-relay-dotnet | src/Microsoft.Azure.Relay/ClientWebSocketFactory.cs | 6,112 | C# |
using RPServerClient.Client.Util;
using RPServerClient.Util;
using Player = RAGE.Elements.Player;
using Vector3 = RAGE.Vector3;
namespace RPServerClient.Client
{
internal class CamHandler : RAGE.Events.Script
{
public readonly int CameraID;
public CamHandler()
{
CameraID = RAGE.Game.Cam.CreateCam(CameraType.DefaultScriptedCamera, false);
}
public void SetPos(Vector3 pos, Vector3 lookAt, bool setActive = false)
{
RAGE.Game.Cam.SetCamCoord(CameraID, pos.X, pos.Y, pos.Z);
RAGE.Game.Cam.PointCamAtCoord(CameraID, lookAt.X, lookAt.Y, lookAt.Z);
if(setActive) SetActive(true);
}
public static void SetPosWithInterp(CamHandler destCamId, CamHandler origCamId, int durationInMs, int easeLocation, int easeRotation)
{
RAGE.Game.Cam.SetCamActiveWithInterp(destCamId.CameraID, origCamId.CameraID, durationInMs, easeLocation, easeRotation);
RAGE.Game.Cam.RenderScriptCams(true, false, 0, true, true, 0);
}
/// <summary>
/// Sets the Camera to point at some Player's Pedbone
/// </summary>
/// <param name="player">De playa whom bone you are interested</param>
/// <param name="bone">Teh boneID</param>
/// <param name="heading">Teh Direction around the bone to place the camera towards</param>
/// <param name="distance">Some distance</param>
/// <param name="setActive">Whether or not to set the camera active</param>
public void PointAtBone(Player player, Shared.Enums.Bone bone, float heading, float distance, bool setActive = false)
{
var boneCoords = player.GetBoneCoords((int)bone, 0, 0, 0);
var cameraPos = Helper.GetPosInFrontOfVector3(boneCoords, heading, distance);
SetPos(cameraPos, boneCoords);
if (setActive) SetActive(true);
}
public void SetActive(bool state)
{
RAGE.Game.Cam.SetCamActive(CameraID, state);
RAGE.Game.Cam.RenderScriptCams(state, false, 0, true, true, 0);
}
public Vector3 GetPosition(int camera)
{
return RAGE.Game.Cam.GetCamCoord(camera);
}
public Vector3 GetPointingAt(int camera)
{
return RAGE.Game.Cam.GetCamRot(camera, 2);
}
}
} | 38.483871 | 141 | 0.631182 | [
"MIT"
] | TryStatic/RPServer | RPServerClient/Client/CamHandler.cs | 2,388 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class ClusterDasAamNodeState : DynamicData
{
protected ManagedObjectReference _host;
protected string _name;
protected string _configState;
protected string _runtimeState;
protected ClusterDasAamNodeState_LinkedView _linkedView;
public ManagedObjectReference Host
{
get
{
return this._host;
}
set
{
this._host = value;
}
}
public string Name
{
get
{
return this._name;
}
set
{
this._name = value;
}
}
public string ConfigState
{
get
{
return this._configState;
}
set
{
this._configState = value;
}
}
public string RuntimeState
{
get
{
return this._runtimeState;
}
set
{
this._runtimeState = value;
}
}
public ClusterDasAamNodeState_LinkedView LinkedView
{
get
{
return this._linkedView;
}
}
}
}
| 14.444444 | 58 | 0.646154 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/C/ClusterDasAamNodeState.cs | 910 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Web;
using BForms.Models;
using Hesira.Areas.Common.Models;
using Hesira.Entities;
using Hesira.Models;
using Hesira.Repositories;
using Hesira.Resources;
namespace Hesira.Areas.Common.Repositories
{
public class UserProfileRepository : BaseRepository
{
#region Constructor
public UserProfileRepository(HesiraEntities db)
: base(db)
{
}
#endregion
#region CRUD
#region Read
public UserProfileModel GetUserProfile(long userId)
{
var user = db.Users.FirstOrDefault(x => x.Id == userId);
if (user != null)
{
var profile = user.UsersProfiles.FirstOrDefault();
if (profile != null)
{
var address = profile.Address;
return new UserProfileModel
{
Basic = new UserProfileBasicModel
{
Citizenship = ReturnCitizenshipForUser(profile.Id_Citizenship),
CNP = user.CNP,
Gender = profile.Gender == (int)GenderEnum.Female ? GenderEnum.Female : GenderEnum.Male,
Role = user.IsAdmin ? Resource.Admin : (user.IsDoctor ? Resource.Doctor : Resource.Patient),
Id = user.Id,
Country = address != null && address.Country != null ? address.Country.CountryNameLowerCase : string.Empty
},
UserInfo = new UserProfileInfoModel
{
BirthDay = profile.Birthday,
Firstname = user.Firstname,
Lastname = user.Lastname,
Profession = profile.Profession,
State = profile.UsersState != null ? profile.UsersState.State : string.Empty
},
Contact = new UserProfileContactModel
{
Email = user.Email,
PhoneNumber = profile.PhoneNumber,
PhysicalAddress = address != null ? address.PhysicalAddress : string.Empty
}
};
}
}
return new UserProfileModel();
}
public UserProfileEditableModel GetEditableUserProfile(long objId, PanelComponentsEnum componentId)
{
var model = db.Users.FirstOrDefault(x => x.Id == objId);
var result = new UserProfileEditableModel
{
Id = model.Id,
Contact = new UserProfileContactEditableModel
{
Email = model.Email
}
};
if (componentId == PanelComponentsEnum.Contact)
{
var profile = model.UsersProfiles.FirstOrDefault();
if (profile != null && profile.Address != null)
{
result.Contact.PhoneNumber = profile.PhoneNumber;
result.Contact.PhysicalAddress = profile.Address.PhysicalAddress;
}
}
else if (componentId == PanelComponentsEnum.UserInfo)
{
var profile = model.UsersProfiles.FirstOrDefault();
if (profile != null)
{
var states = new BsSelectList<int?>
{
Items = db.UsersStates.Select(x => new BsSelectListItem
{
Text = x.Code,
Value = x.Id.ToString()
}).ToList(),
SelectedValues = profile.Id_State
};
result.UserInfo = new UserProfileInfoEditableModel
{
Firstname = model.Firstname,
Lastname = model.Lastname,
BirthDay = new BsDateTime
{
DateValue = profile.Birthday
},
Profession = profile.Profession,
StateDropdown = states
};
}
}
return result;
}
#endregion
#region Update
public UserProfileModel Update(UserProfileEditableModel model, long objId)
{
var userProfile = db.UsersProfiles.FirstOrDefault(x => x.Id_User == objId);
if (userProfile != null)
{
if (model.UserInfo != null)
{
userProfile.User.Firstname = model.UserInfo.Firstname;
userProfile.User.Lastname = model.UserInfo.Lastname;
userProfile.Profession = model.UserInfo.Profession;
if (model.UserInfo.BirthDay.DateValue != null)
{
userProfile.Birthday = model.UserInfo.BirthDay.DateValue.Value;
}
userProfile.Id_State = model.UserInfo.StateDropdown != null &&
model.UserInfo.StateDropdown.SelectedValues != null
? model.UserInfo.StateDropdown.SelectedValues
: null;
}
if (model.Contact != null)
{
userProfile.PhoneNumber = model.Contact.PhoneNumber;
userProfile.Address.PhysicalAddress = model.Contact.PhysicalAddress;
userProfile.User.Email = model.Contact.Email;
}
userProfile.Timestamp = DateTime.Now;
db.SaveChanges();
return GetUserProfile(objId);
}
return null;
}
#endregion
#endregion
#region Helpers
public string ReturnCitizenshipForUser(int countryId)
{
return db.Countries.FirstOrDefault(x => x.Id == countryId).ISO_ALPHA3;
}
#endregion
}
} | 31.165854 | 134 | 0.477226 | [
"MIT"
] | alrazex/Hesira | src/Hesira/Areas/Common/Repositories/UserProfileRepository.cs | 6,391 | C# |
namespace Aspose.Cells.Demos.databind
{
}
namespace Aspose.Cells.Demos.databind
{
}
namespace Aspose.Cells.GridWeb.Demos._2008.JavaEE.databind
{
}
namespace Aspose.Cells.Demos.databind
{
}
| 14.615385 | 58 | 0.789474 | [
"MIT"
] | Aspose/Aspose.Cells-for-.NET | Examples.GridWeb/CSharp/databind/Aspose.Cells.GridWeb.DemosCS.DataBind.dataset2.cs | 192 | C# |
/*
* Copyright 2012-2020 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System.Runtime.InteropServices;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.LowLevelAPI81.MechanismParams
{
/// <summary>
/// Structure that provides the parameters to the general-length MACing mechanisms (DES, DES3, CAST, CAST3, CAST128 (CAST5), IDEA, CDMF and AES), the general length HMACing mechanisms (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512, RIPEMD-128 and RIPEMD-160) and the two SSL 3.0 MACing mechanisms (MD5 and SHA-1)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct CK_MAC_GENERAL_PARAMS
{
/// <summary>
/// Length of the MAC produced, in bytes
/// </summary>
public NativeULong MacLength;
}
}
| 37.243902 | 313 | 0.709234 | [
"Apache-2.0"
] | ConnectionMaster/Pkcs11Interop | src/Pkcs11Interop/LowLevelAPI81/MechanismParams/CK_MAC_GENERAL_PARAMS.cs | 1,529 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractAlgebraMathSet;
using AbstractAlgebraGroup;
using AbstractAlgebraGapPerm;
using AbstractAlgebraCoset;
using AbstractAlgebraCosetGrouping;
using AbstractAlgebraQuotientGroup;
using static System.Console;
namespace pinter_15_A_3_D4
{
class Program
{
static void Main(string[] args)
{
// A C B
// \ | /
// 1---2
// | | - D
// 4---3
var R0 = new GapPerm(0); // R0
var R1 = new GapPerm("(1234)"); // R90
var R2 = new GapPerm("(13)(24)"); // R180
var R3 = new GapPerm("(4321)"); // R270
var R4 = new GapPerm("(24)"); // FA
var R5 = new GapPerm("(13)"); // FB
var R6 = new GapPerm("(12)(34)"); // FC
var R7 = new GapPerm("(14)(23)"); // FD
string lookup(GapPerm f)
{
var items = new[] {
(R0, "R0"),
(R1, "R1"),
(R2, "R2"),
(R3, "R3"),
(R4, "R4"),
(R5, "R5"),
(R6, "R6"),
(R7, "R7")
};
return items.First(elt => f == elt.Item1).Item2;
}
var D4 = new Group<GapPerm>
{
Identity = R0,
Set = new MathSet<GapPerm>(new[] { R0, R1, R2, R3, R4, R5, R6, R7 }),
Op = (a, b) => a.Compose(b),
Lookup = lookup,
OpString = "·"
};
Write("D4 "); D4.ShowOperationTableColored(); WriteLine();
var H = D4.Subgroup(new[] { R0, R2 });
WriteLine("Elements of H: {0}\n", H.Set.ConvertAll(H.Lookup));
WriteLine("Elements of quotient group D4/H:\n");
foreach (var elt in D4.CosetGrouping(H, "H"))
WriteLine($"{ elt.ToMathSet() } { elt.Key.ConvertAll(lookup) }");
WriteLine();
Write("D4/{R0 R2} ");
D4.QuotientGroup(H).ShowOperationTableColored();
}
}
}
| 28.481481 | 85 | 0.433897 | [
"Apache-2.0"
] | dharmatech/AbstractAlgebraCs | pinter-15-A-3-D4/Program.cs | 2,310 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System
{
internal static partial class Number
{
// This is a port of the `Grisu3` implementation here: https://github.com/google/double-conversion/blob/a711666ddd063eb1e4b181a6cb981d39a1fc8bac/double-conversion/fast-dtoa.cc
// The backing algorithm and the proofs behind it are described in more detail here: http://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf
// ========================================================================================================================================
//
// Overview:
//
// The general idea behind Grisu3 is to leverage additional bits and cached powers of ten to generate the correct digits.
// The algorithm is imprecise for some numbers. Fortunately, the algorithm itself can determine this scenario and gives us
// a result indicating success or failure. We must fallback to a different algorithm for the failing scenario.
internal static class Grisu3
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static unsafe bool IsNegative(double d)
{
return BitConverter.DoubleToInt64Bits(d) < 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static unsafe bool IsNegativeInfinity(float f)
{
return f == float.NegativeInfinity;
}
private const int CachedPowersDecimalExponentDistance = 8;
private const int CachedPowersMinDecimalExponent = -348;
private const int CachedPowersPowerMaxDecimalExponent = 340;
private const int CachedPowersOffset = -CachedPowersMinDecimalExponent;
// 1 / Log2(10)
private const double D1Log210 = 0.301029995663981195;
// The minimal and maximal target exponents define the range of w's binary exponent,
// where w is the result of multiplying the input by a cached power of ten.
//
// A different range might be chosen on a different platform, to optimize digit generation,
// but a smaller range requires more powers of ten to be cached.
private const int MaximalTargetExponent = -32;
private const int MinimalTargetExponent = -60;
private static readonly short[] s_CachedPowersBinaryExponent = new short[]
{
-1220,
-1193,
-1166,
-1140,
-1113,
-1087,
-1060,
-1034,
-1007,
-980,
-954,
-927,
-901,
-874,
-847,
-821,
-794,
-768,
-741,
-715,
-688,
-661,
-635,
-608,
-582,
-555,
-529,
-502,
-475,
-449,
-422,
-396,
-369,
-343,
-316,
-289,
-263,
-236,
-210,
-183,
-157,
-130,
-103,
-77,
-50,
-24,
3,
30,
56,
83,
109,
136,
162,
189,
216,
242,
269,
295,
322,
348,
375,
402,
428,
455,
481,
508,
534,
561,
588,
614,
641,
667,
694,
720,
747,
774,
800,
827,
853,
880,
907,
933,
960,
986,
1013,
1039,
1066,
};
private static readonly short[] s_CachedPowersDecimalExponent = new short[]
{
CachedPowersMinDecimalExponent,
-340,
-332,
-324,
-316,
-308,
-300,
-292,
-284,
-276,
-268,
-260,
-252,
-244,
-236,
-228,
-220,
-212,
-204,
-196,
-188,
-180,
-172,
-164,
-156,
-148,
-140,
-132,
-124,
-116,
-108,
-100,
-92,
-84,
-76,
-68,
-60,
-52,
-44,
-36,
-28,
-20,
-12,
-4,
4,
12,
20,
28,
36,
44,
52,
60,
68,
76,
84,
92,
100,
108,
116,
124,
132,
140,
148,
156,
164,
172,
180,
188,
196,
204,
212,
220,
228,
236,
244,
252,
260,
268,
276,
284,
292,
300,
308,
316,
324,
332,
CachedPowersPowerMaxDecimalExponent,
};
private static readonly ulong[] s_CachedPowersSignificand = new ulong[]
{
0xFA8FD5A0081C0288,
0xBAAEE17FA23EBF76,
0x8B16FB203055AC76,
0xCF42894A5DCE35EA,
0x9A6BB0AA55653B2D,
0xE61ACF033D1A45DF,
0xAB70FE17C79AC6CA,
0xFF77B1FCBEBCDC4F,
0xBE5691EF416BD60C,
0x8DD01FAD907FFC3C,
0xD3515C2831559A83,
0x9D71AC8FADA6C9B5,
0xEA9C227723EE8BCB,
0xAECC49914078536D,
0x823C12795DB6CE57,
0xC21094364DFB5637,
0x9096EA6F3848984F,
0xD77485CB25823AC7,
0xA086CFCD97BF97F4,
0xEF340A98172AACE5,
0xB23867FB2A35B28E,
0x84C8D4DFD2C63F3B,
0xC5DD44271AD3CDBA,
0x936B9FCEBB25C996,
0xDBAC6C247D62A584,
0xA3AB66580D5FDAF6,
0xF3E2F893DEC3F126,
0xB5B5ADA8AAFF80B8,
0x87625F056C7C4A8B,
0xC9BCFF6034C13053,
0x964E858C91BA2655,
0xDFF9772470297EBD,
0xA6DFBD9FB8E5B88F,
0xF8A95FCF88747D94,
0xB94470938FA89BCF,
0x8A08F0F8BF0F156B,
0xCDB02555653131B6,
0x993FE2C6D07B7FAC,
0xE45C10C42A2B3B06,
0xAA242499697392D3,
0xFD87B5F28300CA0E,
0xBCE5086492111AEB,
0x8CBCCC096F5088CC,
0xD1B71758E219652C,
0x9C40000000000000,
0xE8D4A51000000000,
0xAD78EBC5AC620000,
0x813F3978F8940984,
0xC097CE7BC90715B3,
0x8F7E32CE7BEA5C70,
0xD5D238A4ABE98068,
0x9F4F2726179A2245,
0xED63A231D4C4FB27,
0xB0DE65388CC8ADA8,
0x83C7088E1AAB65DB,
0xC45D1DF942711D9A,
0x924D692CA61BE758,
0xDA01EE641A708DEA,
0xA26DA3999AEF774A,
0xF209787BB47D6B85,
0xB454E4A179DD1877,
0x865B86925B9BC5C2,
0xC83553C5C8965D3D,
0x952AB45CFA97A0B3,
0xDE469FBD99A05FE3,
0xA59BC234DB398C25,
0xF6C69A72A3989F5C,
0xB7DCBF5354E9BECE,
0x88FCF317F22241E2,
0xCC20CE9BD35C78A5,
0x98165AF37B2153DF,
0xE2A0B5DC971F303A,
0xA8D9D1535CE3B396,
0xFB9B7CD9A4A7443C,
0xBB764C4CA7A44410,
0x8BAB8EEFB6409C1A,
0xD01FEF10A657842C,
0x9B10A4E5E9913129,
0xE7109BFBA19C0C9D,
0xAC2820D9623BF429,
0x80444B5E7AA7CF85,
0xBF21E44003ACDD2D,
0x8E679C2F5E44FF8F,
0xD433179D9C8CB841,
0x9E19DB92B4E31BA9,
0xEB96BF6EBADF77D9,
0xAF87023B9BF0EE6B,
};
private static readonly uint[] s_SmallPowersOfTen = new uint[]
{
1, // 10^0
10, // 10^1
100, // 10^2
1000, // 10^3
10000, // 10^4
100000, // 10^5
1000000, // 10^6
10000000, // 10^7
100000000, // 10^8
1000000000, // 10^9
};
public static bool TryRunDouble(double value, int requestedDigits, ref NumberBuffer number)
{
double v = IsNegative(value) ? -value : value;
Debug.Assert(v > 0);
//Debug.Assert(double.IsFinite(v));
int length;
int decimalExponent;
bool result;
if (requestedDigits == -1)
{
DiyFp w = DiyFp.CreateAndGetBoundaries(v, out DiyFp boundaryMinus, out DiyFp boundaryPlus).Normalize();
result = TryRunShortest(in boundaryMinus, in w, in boundaryPlus, number.Digits, out length, out decimalExponent);
}
else
{
DiyFp w = new DiyFp(v).Normalize();
result = TryRunCounted(in w, requestedDigits, number.Digits, out length, out decimalExponent);
}
if (result)
{
Debug.Assert((requestedDigits == -1) || (length == requestedDigits));
number.Scale = length + decimalExponent;
number.Digits[length] = (byte)('\0');
number.DigitsCount = length;
}
return result;
}
public static bool TryRunSingle(float value, int requestedDigits, ref NumberBuffer number)
{
float v = IsNegative(value) ? -value : value;
Debug.Assert(v > 0);
//Debug.Assert(float.IsFinite(v));
int length;
int decimalExponent;
bool result;
if (requestedDigits == -1)
{
DiyFp w = DiyFp.CreateAndGetBoundaries(v, out DiyFp boundaryMinus, out DiyFp boundaryPlus).Normalize();
result = TryRunShortest(in boundaryMinus, in w, in boundaryPlus, number.Digits, out length, out decimalExponent);
}
else
{
DiyFp w = new DiyFp(v).Normalize();
result = TryRunCounted(in w, requestedDigits, number.Digits, out length, out decimalExponent);
}
if (result)
{
Debug.Assert((requestedDigits == -1) || (length == requestedDigits));
number.Scale = length + decimalExponent;
number.Digits[length] = (byte)('\0');
number.DigitsCount = length;
}
return result;
}
// The counted version of Grisu3 only generates requestedDigits number of digits.
// This version does not generate the shortest representation, and with enough requested digits 0.1 will at some point print as 0.9999999...
// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and therefore the rounding strategy for halfway cases is irrelevant.
private static bool TryRunCounted(in DiyFp w, int requestedDigits, Span<byte> buffer, out int length, out int decimalExponent)
{
Debug.Assert(requestedDigits > 0);
int tenMkMinimalBinaryExponent = MinimalTargetExponent - (w.e + DiyFp.SignificandSize);
int tenMkMaximalBinaryExponent = MaximalTargetExponent - (w.e + DiyFp.SignificandSize);
DiyFp tenMk = GetCachedPowerForBinaryExponentRange(tenMkMinimalBinaryExponent, tenMkMaximalBinaryExponent, out int mk);
Debug.Assert(MinimalTargetExponent <= (w.e + tenMk.e + DiyFp.SignificandSize));
Debug.Assert(MaximalTargetExponent >= (w.e + tenMk.e + DiyFp.SignificandSize));
// Note that tenMk is only an approximation of 10^-k.
// A DiyFp only contains a 64-bit significand and tenMk is thus only precise up to 64-bits.
// The DiyFp.Multiply procedure rounds its result and tenMk is approximated too.
// The variable scaledW (as well as scaledBoundaryMinus/Plus) are now off by a small amount.
//
// In fact, scaledW - (w * 10^k) < 1ulp (unit in last place) of scaledW.
// In other words, let f = scaledW.f and e = scaledW.e, then:
// (f - 1) * 2^e < (w * 10^k) < (f + 1) * 2^e
DiyFp scaledW = w.Multiply(in tenMk);
// We now have (double)(scaledW * 10^-mk).
//
// DigitGenCounted will generate the first requestedDigits of scaledW and return together with a kappa such that:
// scaledW ~= buffer * 10^kappa.
//
// It will not always be exactly the same since DigitGenCounted only produces a limited number of digits.
bool result = TryDigitGenCounted(in scaledW, requestedDigits, buffer, out length, out int kappa);
decimalExponent = -mk + kappa;
return result;
}
// Provides a decimal representation of v.
// Returns true if it succeeds; otherwise, the result cannot be trusted.
//
// There will be length digits inside the buffer (not null-terminated).
// If the function returns true then:
// v == (double)(buffer * 10^decimalExponent)
//
// The digits in the buffer are the shortest represenation possible (no 0.09999999999999999 instead of 0.1).
// The shorter representation will even be chosen if the longer one would be closer to v.
//
// The last digit will be closest to the actual v.
// That is, even if several digits might correctly yield 'v' when read again, the closest will be computed.
private static bool TryRunShortest(in DiyFp boundaryMinus, in DiyFp w, in DiyFp boundaryPlus, Span<byte> buffer, out int length, out int decimalExponent)
{
// boundaryMinus and boundaryPlus are the boundaries between v and its closest floating-point neighbors.
// Any number strictly between boundaryMinus and boundaryPlus will round to v when converted to a double.
// Grisu3 will never output representations that lie exactly on a boundary.
Debug.Assert(boundaryPlus.e == w.e);
int tenMkMinimalBinaryExponent = MinimalTargetExponent - (w.e + DiyFp.SignificandSize);
int tenMkMaximalBinaryExponent = MaximalTargetExponent - (w.e + DiyFp.SignificandSize);
DiyFp tenMk = GetCachedPowerForBinaryExponentRange(tenMkMinimalBinaryExponent, tenMkMaximalBinaryExponent, out int mk);
Debug.Assert(MinimalTargetExponent <= (w.e + tenMk.e + DiyFp.SignificandSize));
Debug.Assert(MaximalTargetExponent >= (w.e + tenMk.e + DiyFp.SignificandSize));
// Note that tenMk is only an approximation of 10^-k.
// A DiyFp only contains a 64-bit significan and tenMk is thus only precise up to 64-bits.
// The DiyFp.Multiply procedure rounds its result and tenMk is approximated too.
// The variable scaledW (as well as scaledBoundaryMinus/Plus) are now off by a small amount.
//
// In fact, scaledW - (w * 10^k) < 1ulp (unit in last place) of scaledW.
// In other words, let f = scaledW.f and e = scaledW.e, then:
// (f - 1) * 2^e < (w * 10^k) < (f + 1) * 2^e
DiyFp scaledW = w.Multiply(in tenMk);
Debug.Assert(scaledW.e == (boundaryPlus.e + tenMk.e + DiyFp.SignificandSize));
// In theory, it would be possible to avoid some recomputations by computing the difference between w
// and boundaryMinus/Plus (a power of 2) and to compute scaledBoundaryMinus/Plus by subtracting/adding
// from scaledW. However, the code becomes much less readable and the speed enhancements are not terrific.
DiyFp scaledBoundaryMinus = boundaryMinus.Multiply(in tenMk);
DiyFp scaledBoundaryPlus = boundaryPlus.Multiply(in tenMk);
// DigitGen will generate the digits of scaledW. Therefore, we have:
// v == (double)(scaledW * 10^-mk)
//
// Set decimalExponent == -mk and pass it to DigitGen and if scaledW is not an integer than it will be updated.
// For instance, if scaledW == 1.23 then the buffer will be filled with "123" and the decimalExponent will be decreased by 2.
bool result = TryDigitGenShortest(in scaledBoundaryMinus, in scaledW, in scaledBoundaryPlus, buffer, out length, out int kappa);
decimalExponent = -mk + kappa;
return result;
}
// Returns the biggest power of ten that is less than or equal to the given number.
// We furthermore receive the maximum number of bits 'number' has.
//
// Returns power == 10^(exponent) such that
// power <= number < power * 10
// If numberBits == 0, then 0^(0-1) is returned.
// The number of bits must be <= 32.
//
// Preconditions:
// number < (1 << (numberBits + 1))
private static uint BiggestPowerTen(uint number, int numberBits, out int exponentPlusOne)
{
// Inspired by the method for finding an integer log base 10 from here:
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
Debug.Assert(number < (1U << (numberBits + 1)));
// 1233/4096 is approximately 1/log2(10)
int exponentGuess = ((numberBits + 1) * 1233) >> 12;
Debug.Assert((uint)(exponentGuess) < s_SmallPowersOfTen.Length);
uint power = s_SmallPowersOfTen[exponentGuess];
// We don't have any guarantees that 2^numberBits <= number
if (number < power)
{
exponentGuess--;
power = s_SmallPowersOfTen[exponentGuess];
}
exponentPlusOne = exponentGuess + 1;
return power;
}
// Generates (at most) requestedDigits of input number w.
//
// w is a floating-point number (DiyFp), consisting of a significand and an exponent.
// Its exponent is bounded by MinimalTargetExponent and MaximalTargetExponent, hence:
// -60 <= w.e <= -32
//
// Returns false if it fails, in which case the generated digits in the buffer should not be used.
//
// Preconditions:
// w is correct up to 1 ulp (unit in last place). That is, its error must be strictly less than a unit of its last digit.
// MinimalTargetExponent <= w.e <= MaximalTargetExponent
//
// Postconditions:
// Returns false if the procedure fails; otherwise:
// * buffer is not null-terminated, but length contains the number of digits.
// * The representation in buffer is the most precise representation of requestedDigits digits.
// * buffer contains at most requestedDigits digits of w. If there are less than requestedDigits digits then some trailing '0's have been removed.
// * kappa is such that w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
//
// This procedure takes into account the imprecision of its input numbers.
// If the precision is not enough to guarantee all the postconditions, then false is returned.
// This usually happens rarely, but the failure-rate increases with higher requestedDigits
private static bool TryDigitGenCounted(in DiyFp w, int requestedDigits, Span<byte> buffer, out int length, out int kappa)
{
Debug.Assert(MinimalTargetExponent <= w.e);
Debug.Assert(w.e <= MaximalTargetExponent);
Debug.Assert(MinimalTargetExponent >= -60);
Debug.Assert(MaximalTargetExponent <= -32);
// w is assumed to have an error less than 1 unit.
// Whenever w is scaled we also scale its error.
ulong wError = 1;
// We cut the input number into two parts: the integral digits and the fractional digits.
// We don't emit any decimal separator, but adapt kapp instead.
// For example: instead of writing "1.2", we put "12" into the buffer and increase kappa by 1.
var one = new DiyFp(1UL << -w.e, w.e);
// Division by one is a shift.
uint integrals = (uint)(w.f >> -one.e);
// Modulo by one is an and.
ulong fractionals = w.f & (one.f - 1);
// We deviate from the original algorithm here and do some early checks to determine if we can satisfy requestedDigits.
// If we determine that we can't, we exit early and avoid most of the heavy lifting that the algorithm otherwise does.
//
// When fractionals is zero, we can easily determine if integrals can satisfy requested digits:
// If requestedDigits >= 11, integrals is not able to exhaust the count by itself since 10^(11 -1) > uint.MaxValue >= integrals.
// If integrals < 10^(requestedDigits - 1), integrals cannot exhaust the count.
// Otherwise, integrals might be able to exhaust the count and we need to execute the rest of the code.
if ((fractionals == 0) && ((requestedDigits >= 11) || (integrals < s_SmallPowersOfTen[requestedDigits - 1])))
{
Debug.Assert(buffer[0] == '\0');
length = 0;
kappa = 0;
return false;
}
uint divisor = BiggestPowerTen(integrals, DiyFp.SignificandSize - (-one.e), out kappa);
length = 0;
// Loop invariant:
// buffer = w / 10^kappa (integer division)
// These invariants hold for the first iteration:
// kappa has been initialized with the divisor exponent + 1
// The divisor is the biggest power of ten that is smaller than integrals
while (kappa > 0)
{
uint digit = MathEx.DivRem(integrals, divisor, out integrals);
Debug.Assert(digit <= 9);
buffer[length] = (byte)('0' + digit);
length++;
requestedDigits--;
kappa--;
// Note that kappa now equals the exponent of the
// divisor and that the invariant thus holds again.
if (requestedDigits == 0)
{
break;
}
divisor /= 10;
}
if (requestedDigits == 0)
{
ulong rest = ((ulong)(integrals) << -one.e) + fractionals;
return TryRoundWeedCounted(
buffer,
length,
rest,
tenKappa: ((ulong)(divisor)) << -one.e,
unit: wError,
ref kappa
);
}
// The integrals have been generated and we are at the point of the decimal separator.
// In the following loop, we simply multiply the remaining digits by 10 and divide by one.
// We just need to pay attention to multiply associated data (the unit), too.
// Note that the multiplication by 10 does not overflow because:
// w.e >= -60 and thus one.e >= -60
Debug.Assert(one.e >= MinimalTargetExponent);
Debug.Assert(fractionals < one.f);
Debug.Assert((ulong.MaxValue / 10) >= one.f);
while ((requestedDigits > 0) && (fractionals > wError))
{
fractionals *= 10;
wError *= 10;
// Integer division by one.
uint digit = (uint)(fractionals >> -one.e);
Debug.Assert(digit <= 9);
buffer[length] = (byte)('0' + digit);
length++;
requestedDigits--;
kappa--;
// Modulo by one.
fractionals &= (one.f - 1);
}
if (requestedDigits != 0)
{
buffer[0] = (byte)('\0');
length = 0;
kappa = 0;
return false;
}
return TryRoundWeedCounted(
buffer,
length,
rest: fractionals,
tenKappa: one.f,
unit: wError,
ref kappa
);
}
// Generates the digits of input number w.
//
// w is a floating-point number (DiyFp), consisting of a significand and an exponent.
// Its exponent is bounded by kMinimalTargetExponent and kMaximalTargetExponent, hence:
// -60 <= w.e() <= -32.
//
// Returns false if it fails, in which case the generated digits in the buffer should not be used.
//
// Preconditions:
// low, w and high are correct up to 1 ulp (unit in the last place). That is, their error must be less than a unit of their last digits.
// low.e() == w.e() == high.e()
// low < w < high, and taking into account their error: low~ <= high~
// kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
//
// Postconditions:
// Returns false if procedure fails; otherwise:
// * buffer is not null-terminated, but len contains the number of digits.
// * buffer contains the shortest possible decimal digit-sequence such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the correct values of low and high (without their error).
// * If more than one decimal representation gives the minimal number of decimal digits then the one closest to W (where W is the correct value of w) is chosen.
//
// This procedure takes into account the imprecision of its input numbers.
// If the precision is not enough to guarantee all the postconditions then false is returned.
// This usually happens rarely (~0.5%).
//
// Say, for the sake of example, that:
// w.e() == -48, and w.f() == 0x1234567890abcdef
//
// w's value can be computed by w.f() * 2^w.e()
//
// We can obtain w's integral digits by simply shifting w.f() by -w.e().
// -> w's integral part is 0x1234
// w's fractional part is therefore 0x567890abcdef.
//
// Printing w's integral part is easy (simply print 0x1234 in decimal).
//
// In order to print its fraction we repeatedly multiply the fraction by 10 and get each digit.
// For example, the first digit after the point would be computed by
// (0x567890abcdef * 10) >> 48. -> 3
//
// The whole thing becomes slightly more complicated because we want to stop once we have enough digits.
// That is, once the digits inside the buffer represent 'w' we can stop.
//
// Everything inside the interval low - high represents w.
// However we have to pay attention to low, high and w's imprecision.
private static bool TryDigitGenShortest(in DiyFp low, in DiyFp w, in DiyFp high, Span<byte> buffer, out int length, out int kappa)
{
Debug.Assert(low.e == w.e);
Debug.Assert(w.e == high.e);
Debug.Assert((low.f + 1) <= (high.f - 1));
Debug.Assert(MinimalTargetExponent <= w.e);
Debug.Assert(w.e <= MaximalTargetExponent);
// low, w, and high are imprecise, but by less than one ulp (unit in the last place).
//
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that the new numbers
// are outside of the interval we want the final representation to lie in.
//
// Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield numbers that
// are certain to lie in the interval. We will use this fact later on.
//
// We will now start by generating the digits within the uncertain interval.
// Later, we will weed out representations that lie outside the safe interval and thus might lie outside the correct interval.
ulong unit = 1;
var tooLow = new DiyFp(low.f - unit, low.e);
var tooHigh = new DiyFp(high.f + unit, high.e);
// tooLow and tooHigh are guaranteed to lie outside the interval we want the generated number in.
DiyFp unsafeInterval = tooHigh.Subtract(in tooLow);
// We now cut the input number into two parts: the integral digits and the fractional digits.
// We will not write any decimal separator, but adapt kappa instead.
//
// Reminder: we are currently computing the digits (Stored inside the buffer) such that:
// tooLow < buffer * 10^kappa < tooHigh
//
// We use tooHigh for the digitGeneration and stop as soon as possible.
// If we stop early, we effectively round down.
var one = new DiyFp(1UL << -w.e, w.e);
// Division by one is a shift.
uint integrals = (uint)(tooHigh.f >> -one.e);
// Modulo by one is an and.
ulong fractionals = tooHigh.f & (one.f - 1);
uint divisor = BiggestPowerTen(integrals, DiyFp.SignificandSize - (-one.e), out kappa);
length = 0;
// Loop invariant:
// buffer = tooHigh / 10^kappa (integer division)
// These invariants hold for the first iteration:
// kappa has been initialized with the divisor exponent + 1
// The divisor is the biggest power of ten that is smaller than integrals
while (kappa > 0)
{
uint digit = MathEx.DivRem(integrals, divisor, out integrals);
Debug.Assert(digit <= 9);
buffer[length] = (byte)('0' + digit);
length++;
kappa--;
// Note that kappa now equals the exponent of the
// divisor and that the invariant thus holds again.
ulong rest = ((ulong)(integrals) << -one.e) + fractionals;
// Invariant: tooHigh = buffer * 10^kappa + DiyFp(rest, one.e)
// Reminder: unsafeInterval.e == one.e
if (rest < unsafeInterval.f)
{
// Rounding down (by not emitting the remaining digits)
// yields a number that lies within the unsafe interval
return TryRoundWeedShortest(
buffer,
length,
tooHigh.Subtract(w).f,
unsafeInterval.f,
rest,
tenKappa: ((ulong)(divisor)) << -one.e,
unit
);
}
divisor /= 10;
}
// The integrals have been generated and we are at the point of the decimal separator.
// In the following loop, we simply multiply the remaining digits by 10 and divide by one.
// We just need to pay attention to multiply associated data (the unit), too.
// Note that the multiplication by 10 does not overflow because:
// w.e >= -60 and thus one.e >= -60
Debug.Assert(one.e >= MinimalTargetExponent);
Debug.Assert(fractionals < one.f);
Debug.Assert((ulong.MaxValue / 10) >= one.f);
while (true)
{
fractionals *= 10;
unit *= 10;
unsafeInterval = new DiyFp(unsafeInterval.f * 10, unsafeInterval.e);
// Integer division by one.
uint digit = (uint)(fractionals >> -one.e);
Debug.Assert(digit <= 9);
buffer[length] = (byte)('0' + digit);
length++;
kappa--;
// Modulo by one.
fractionals &= (one.f - 1);
if (fractionals < unsafeInterval.f)
{
return TryRoundWeedShortest(
buffer,
length,
tooHigh.Subtract(w).f * unit,
unsafeInterval.f,
rest: fractionals,
tenKappa: one.f,
unit
);
}
}
}
// Returns a cached power-of-ten with a binary exponent in the range [minExponent; maxExponent] (boundaries included).
private static DiyFp GetCachedPowerForBinaryExponentRange(int minExponent, int maxExponent, out int decimalExponent)
{
Debug.Assert(s_CachedPowersSignificand.Length == s_CachedPowersBinaryExponent.Length);
Debug.Assert(s_CachedPowersSignificand.Length == s_CachedPowersDecimalExponent.Length);
double k = Math.Ceiling((minExponent + DiyFp.SignificandSize - 1) * D1Log210);
int index = ((CachedPowersOffset + (int)(k) - 1) / CachedPowersDecimalExponentDistance) + 1;
Debug.Assert((uint)(index) < s_CachedPowersSignificand.Length);
Debug.Assert(minExponent <= s_CachedPowersBinaryExponent[index]);
Debug.Assert(s_CachedPowersBinaryExponent[index] <= maxExponent);
decimalExponent = s_CachedPowersDecimalExponent[index];
return new DiyFp(s_CachedPowersSignificand[index], s_CachedPowersBinaryExponent[index]);
}
// Rounds the buffer upwards if the result is closer to v by possibly adding 1 to the buffer.
// If the precision of the calculation is not sufficient to round correctly, return false.
//
// The rounding might shift the whole buffer, in which case, the kappy is adjusted.
// For example "99", kappa = 3 might become "10", kappa = 4.
//
// If (2 * rest) > tenKappa then the buffer needs to be round up.
// rest can have an error of +/- 1 unit.
// This function accounts for the imprecision and returns false if the rounding direction cannot be unambiguously determined.
//
// Preconditions:
// rest < tenKappa
private static bool TryRoundWeedCounted(Span<byte> buffer, int length, ulong rest, ulong tenKappa, ulong unit, ref int kappa)
{
Debug.Assert(rest < tenKappa);
// The following tests are done in a specific order to avoid overflows.
// They will work correctly with any ulong values of rest < tenKappa and unit.
//
// If the unit is too big, then we don't know which way to round.
// For example, a unit of 50 means that the real number lies within rest +/- 50.
// If 10^kappa == 40, then there is no way to tell which way to round.
//
// Even if unit is just half the size of 10^kappa we are already completely lost.
// And after the previous test, we know that the expression will not over/underflow.
if ((unit >= tenKappa) || ((tenKappa - unit) <= unit))
{
return false;
}
// If 2 * (rest + unit) <= 10^kappa, we can safely round down.
if (((tenKappa - rest) > rest) && ((tenKappa - (2 * rest)) >= (2 * unit)))
{
return true;
}
// If 2 * (rest - unit) >= 10^kappa, we can safely round up.
if ((rest > unit) && (tenKappa <= (rest - unit) || ((tenKappa - (rest - unit)) <= (rest - unit))))
{
// Increment the last digit recursively until we find a non '9' digit.
buffer[length - 1]++;
for (int i = (length - 1); i > 0; i--)
{
if (buffer[i] != ('0' + 10))
{
break;
}
buffer[i] = (byte)('0');
buffer[i - 1]++;
}
// If the first digit is now '0'+10, we had a buffer with all '9's.
// With the exception of the first digit, all digits are now '0'.
// Simply switch the first digit to '1' and adjust the kappa.
// For example, "99" becomes "10" and the power (the kappa) is increased.
if (buffer[0] == ('0' + 10))
{
buffer[0] = (byte)('1');
kappa++;
}
return true;
}
return false;
}
// Adjusts the last digit of the generated number and screens out generated solutions that may be inaccurate.
// A solution may be inaccurate if it is outside the safe interval or if we cannot provide that it is closer to the input than a neighboring representation of the same length.
//
// Input:
// buffer containing the digits of tooHigh / 10^kappa
// the buffer's length
// distanceTooHighW == (tooHigh - w).f * unit
// unsafeInterval == (tooHigh - tooLow).f * unit
// rest = (tooHigh - buffer * 10^kapp).f * unit
// tenKappa = 10^kappa * unit
// unit = the common multiplier
//
// Output:
// Returns true if the buffer is guaranteed to contain the closest representable number to the input.
//
// Modifies the generated digits in the buffer to approach (round towards) w.
private static bool TryRoundWeedShortest(Span<byte> buffer, int length, ulong distanceTooHighW, ulong unsafeInterval, ulong rest, ulong tenKappa, ulong unit)
{
ulong smallDistance = distanceTooHighW - unit;
ulong bigDistance = distanceTooHighW + unit;
// Let wLow = tooHigh - bigDistance, and wHigh = tooHigh - smallDistance.
//
// Note: wLow < w < wHigh
//
// The real w * unit must lie somewhere inside the interval
// ]w_low; w_high[ (often written as "(w_low; w_high)")
// Basically the buffer currently contains a number in the unsafe interval
// ]too_low; too_high[ with too_low < w < too_high
//
// tooHigh - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ^v 1 unit ^ ^ ^ ^
// boundaryHigh --------------------- . . . .
// ^v 1 unit . . . .
// - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
// . . ^ . .
// . bigDistance . . .
// . . . . rest
// smallDistance . . . .
// v . . . .
// wHigh - - - - - - - - - - - - - - - - - - . . . .
// ^v 1 unit . . . .
// w --------------------------------------- . . . .
// ^v 1 unit v . . .
// wLow - - - - - - - - - - - - - - - - - - - - - . . .
// . . v
// buffer -------------------------------------------------+-------+--------
// . .
// safeInterval .
// v .
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
// ^v 1 unit .
// boundaryLow ------------------------- unsafeInterval
// ^v 1 unit v
// tooLow - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
//
// Note that the value of buffer could lie anywhere inside the range tooLow to tooHigh.
//
// boundaryLow, boundaryHigh and w are approximations of the real boundaries and v (the input number).
// They are guaranteed to be precise up to one unit.
// In fact the error is guaranteed to be strictly less than one unit.
//
// Anything that lies outside the unsafe interval is guaranteed not to round to v when read again.
// Anything that lies inside the safe interval is guaranteed to round to v when read again.
//
// If the number inside the buffer lies inside the unsafe interval but not inside the safe interval
// then we simply do not know and bail out (returning false).
//
// Similarly we have to take into account the imprecision of 'w' when finding the closest representation of 'w'.
// If we have two potential representations, and one is closer to both wLow and wHigh, then we know it is closer to the actual value v.
//
// By generating the digits of tooHigh we got the largest (closest to tooHigh) buffer that is still in the unsafe interval.
// In the case where wHigh < buffer < tooHigh we try to decrement the buffer.
// This way the buffer approaches (rounds towards) w.
//
// There are 3 conditions that stop the decrementation process:
// 1) the buffer is already below wHigh
// 2) decrementing the buffer would make it leave the unsafe interval
// 3) decrementing the buffer would yield a number below wHigh and farther away than the current number.
//
// In other words:
// (buffer{-1} < wHigh) && wHigh - buffer{-1} > buffer - wHigh
//
// Instead of using the buffer directly we use its distance to tooHigh.
//
// Conceptually rest ~= tooHigh - buffer
//
// We need to do the following tests in this order to avoid over- and underflows.
Debug.Assert(rest <= unsafeInterval);
while ((rest < smallDistance) && ((unsafeInterval - rest) >= tenKappa) && (((rest + tenKappa) < smallDistance) || ((smallDistance - rest) >= (rest + tenKappa - smallDistance))))
{
buffer[length - 1]--;
rest += tenKappa;
}
// We have approached w+ as much as possible.
// We now test if approaching w- would require changing the buffer.
// If yes, then we have two possible representations close to w, but we cannot decide which one is closer.
if ((rest < bigDistance) && ((unsafeInterval - rest) >= tenKappa) && (((rest + tenKappa) < bigDistance) || ((bigDistance - rest) > (rest + tenKappa - bigDistance))))
{
return false;
}
// Weeding test.
//
// The safe interval is [tooLow + 2 ulp; tooHigh - 2 ulp]
// Since tooLow = tooHigh - unsafeInterval this is equivalent to
// [tooHigh - unsafeInterval + 4 ulp; tooHigh - 2 ulp]
//
// Conceptually we have: rest ~= tooHigh - buffer
return ((2 * unit) <= rest) && (rest <= (unsafeInterval - 4 * unit));
}
}
}
} | 45.802249 | 205 | 0.478607 | [
"Apache-2.0"
] | 654306663/BDFramework.Core | Packages/ZString/Number/Number.Grisu3.cs | 48,873 | C# |
using System;
using JetBrains.Annotations;
namespace BudgetAnalyser.Engine.Statement
{
/// <summary>
/// An exception to report that an attempt was made to import the same exact bank export twice.
/// </summary>
/// <seealso cref="System.Exception" />
public class TransactionsAlreadyImportedException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="TransactionsAlreadyImportedException" /> class.
/// </summary>
public TransactionsAlreadyImportedException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TransactionsAlreadyImportedException" /> class.
/// </summary>
/// <param name="message">The message.</param>
public TransactionsAlreadyImportedException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TransactionsAlreadyImportedException" /> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
[UsedImplicitly]
public TransactionsAlreadyImportedException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 35.710526 | 108 | 0.623434 | [
"MIT"
] | Benrnz/BudgetAnalyser | BudgetAnalyser.Engine/Statement/TransactionsAlreadyImportedException.cs | 1,357 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type IosUpdateDeviceStatusRequest.
/// </summary>
public partial class IosUpdateDeviceStatusRequest : BaseRequest, IIosUpdateDeviceStatusRequest
{
/// <summary>
/// Constructs a new IosUpdateDeviceStatusRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public IosUpdateDeviceStatusRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified IosUpdateDeviceStatus using POST.
/// </summary>
/// <param name="iosUpdateDeviceStatusToCreate">The IosUpdateDeviceStatus to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created IosUpdateDeviceStatus.</returns>
public async System.Threading.Tasks.Task<IosUpdateDeviceStatus> CreateAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToCreate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
var newEntity = await this.SendAsync<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Creates the specified IosUpdateDeviceStatus using POST and returns a <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object.
/// </summary>
/// <param name="iosUpdateDeviceStatusToCreate">The IosUpdateDeviceStatus to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<IosUpdateDeviceStatus>> CreateResponseAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToCreate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToCreate, cancellationToken);
}
/// <summary>
/// Deletes the specified IosUpdateDeviceStatus.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.DELETE;
await this.SendAsync<IosUpdateDeviceStatus>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes the specified IosUpdateDeviceStatus and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse"/> to await.</returns>
public System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.DELETE;
return this.SendAsyncWithGraphResponse(null, cancellationToken);
}
/// <summary>
/// Gets the specified IosUpdateDeviceStatus.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The IosUpdateDeviceStatus.</returns>
public async System.Threading.Tasks.Task<IosUpdateDeviceStatus> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var retrievedEntity = await this.SendAsync<IosUpdateDeviceStatus>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Gets the specified IosUpdateDeviceStatus and returns a <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<IosUpdateDeviceStatus>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<IosUpdateDeviceStatus>(null, cancellationToken);
}
/// <summary>
/// Updates the specified IosUpdateDeviceStatus using PATCH.
/// </summary>
/// <param name="iosUpdateDeviceStatusToUpdate">The IosUpdateDeviceStatus to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated IosUpdateDeviceStatus.</returns>
public async System.Threading.Tasks.Task<IosUpdateDeviceStatus> UpdateAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PATCH;
var updatedEntity = await this.SendAsync<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Updates the specified IosUpdateDeviceStatus using PATCH and returns a <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object.
/// </summary>
/// <param name="iosUpdateDeviceStatusToUpdate">The IosUpdateDeviceStatus to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse<IosUpdateDeviceStatus>> UpdateResponseAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PATCH;
return this.SendAsyncWithGraphResponse<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToUpdate, cancellationToken);
}
/// <summary>
/// Updates the specified IosUpdateDeviceStatus using PUT.
/// </summary>
/// <param name="iosUpdateDeviceStatusToUpdate">The IosUpdateDeviceStatus object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task<IosUpdateDeviceStatus> PutAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PUT;
var updatedEntity = await this.SendAsync<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Updates the specified IosUpdateDeviceStatus using PUT and returns a <see cref="GraphResponse{IosUpdateDeviceStatus}"/> object.
/// </summary>
/// <param name="iosUpdateDeviceStatusToUpdate">The IosUpdateDeviceStatus object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await of <see cref="GraphResponse{IosUpdateDeviceStatus}"/>.</returns>
public System.Threading.Tasks.Task<GraphResponse<IosUpdateDeviceStatus>> PutResponseAsync(IosUpdateDeviceStatus iosUpdateDeviceStatusToUpdate, CancellationToken cancellationToken = default)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.Method = HttpMethods.PUT;
return this.SendAsyncWithGraphResponse<IosUpdateDeviceStatus>(iosUpdateDeviceStatusToUpdate, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IIosUpdateDeviceStatusRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IIosUpdateDeviceStatusRequest Expand(Expression<Func<IosUpdateDeviceStatus, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IIosUpdateDeviceStatusRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IIosUpdateDeviceStatusRequest Select(Expression<Func<IosUpdateDeviceStatus, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="iosUpdateDeviceStatusToInitialize">The <see cref="IosUpdateDeviceStatus"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(IosUpdateDeviceStatus iosUpdateDeviceStatusToInitialize)
{
}
}
}
| 52.728 | 200 | 0.661129 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IosUpdateDeviceStatusRequest.cs | 13,182 | C# |
namespace ET
{
public class LoginFinish_CreateLobbyUI: AEvent<EventType.LoginFinish>
{
protected override async ETTask Run(EventType.LoginFinish args)
{
args.ZoneScene.GetComponent<UIComponent>().HideWindow(WindowID.WindowID_Login);
await args.ZoneScene.GetComponent<UIComponent>().ShowWindowAsync(WindowID.WindowID_Lobby);
}
}
} | 35.454545 | 102 | 0.702564 | [
"MIT"
] | 752636090/ET | Unity/Codes/HotfixView/Demo/UI/DlgLobby/Event/LoginFinish_CreateLobbyUI.cs | 392 | C# |
using Microsoft.AspNetCore.Http;
using System.Text.RegularExpressions;
/// <summary>
/// <see cref="HttpRequest"/> extension methods.
/// </summary>
public static partial class HttpRequestExtensions
{
//regex from http://detectmobilebrowsers.com/
private static readonly Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
private static readonly Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
/// <summary>
/// This function returns if the request validates as a mobile browser
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static bool IsMobileBrowser(this HttpRequest request)
{
string userAgent = request.UserAgent();
if (userAgent != null && (b.IsMatch(userAgent) || v.IsMatch(userAgent.Substring(0, 4))))
{
return true;
}
return false;
}
/// <summary>
/// This function returns the current requests browser agent
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static string UserAgent(this HttpRequest request)
{
return request.Headers["User-Agent"];
}
} | 82.684211 | 1,709 | 0.632081 | [
"MIT"
] | lilpug/ModFrame | projects/ASP.NET Core 2.1 - Full Framework/ModFrame/Core/Extension Methods/HttpRequest/IsMobileBrowser.cs | 3,144 | C# |
// Keypear Security Tool.
// Copyright (C) Eugene Bekker.
using System.Numerics;
using Keypear.Shared.PAKE.ScottBradySRP;
namespace Keypear.Shared.Tests.SRP;
public class ScottBradySRPTests
{
[Fact]
public void Test_TestVectors()
{
var client = new SrpClient(TestVectors.H, TestVectors.g, TestVectors.N);
var server = new SrpServer(TestVectors.H, TestVectors.g, TestVectors.N);
// generate password verifier to store
BigInteger v = client.GenerateVerifier(TestVectors.I, TestVectors.P, TestVectors.s);
Assert.Equal(TestVectors.expected_v, v);
var A = client.GenerateTestVectorAValues(TestVectors.a);
Assert.Equal(TestVectors.expected_A, A);
var B = server.GenerateTestVectorBValues(v, TestVectors.b);
Assert.Equal(TestVectors.expected_B, B);
var clientS = client.ComputeSessionKey(TestVectors.I, TestVectors.P, TestVectors.s, B);
var serverS = server.ComputeSessionKey(v, A);
Assert.Equal(clientS, serverS);
Assert.Equal(TestVectors.expected_S, clientS);
var M1 = client.GenerateClientProof(B, clientS);
Assert.True(server.ValidateClientProof(M1, A, serverS));
var M2 = server.GenerateServerProof(A, M1, serverS);
Assert.True(client.ValidateServerProof(M2, M1, clientS));
}
[Fact]
public void Test_WithSha256Hasher()
{
var hasher = (byte[] data) => Sodium.CryptoHash.Sha256(data);
var g = SRPGroupParameters.Group1024bit.g;
var N = SRPGroupParameters.Group1024bit.N;
var I = "jdoe@example.com";
var P = "foo bar non";
var s = Sodium.SodiumCore.GetRandomBytes(32);
var client = new SrpClient(hasher, g, N);
var server = new SrpServer(hasher, g, N);
// generate password verifier to store
BigInteger v = client.GenerateVerifier(I, P, s);
var A = client.GenerateAValues(out var clientSrpState);
var B = server.GenerateBValues(v, out var serverSrpState);
var clientS = client.ComputeSessionKey(I, P, s, B);
var serverS = server.ComputeSessionKey(v, A);
Assert.Equal(clientS, serverS);
// Restore state in new client and server
client = new SrpClient(hasher, g, N, A, clientSrpState);
server = new SrpServer(hasher, g, N, B, serverSrpState);
var clientS2 = client.ComputeSessionKey(I, P, s, B);
var serverS2 = server.ComputeSessionKey(v, A);
Assert.Equal(clientS2, serverS);
Assert.Equal(clientS, serverS2);
var M1 = client.GenerateClientProof(B, clientS);
Assert.True(server.ValidateClientProof(M1, A, serverS));
var M2 = server.GenerateServerProof(A, M1, serverS);
Assert.True(client.ValidateServerProof(M2, M1, clientS));
}
[Theory]
[MemberData(nameof(_allSrpGroups))]
internal void Test_WithArgon2Hasher(string groupName, SRPGroupParameters gp)
{
Console.WriteLine("Testing with SRP Group [{0}]", groupName);
var salt = Sodium.PasswordHash.ArgonGenerateSalt();
var hasher = (byte[] data) => Sodium.PasswordHash.ArgonHashBinary(data, salt);
var g = gp.g; // SRPGroupParameters.Group1024bit.g; //
var N = gp.N; // SRPGroupParameters.Group1024bit.N; //
var I = "jdoe@example.com";
var P = "foo bar non";
var s = Sodium.SodiumCore.GetRandomBytes(32);
var client = new SrpClient(hasher, g, N);
var server = new SrpServer(hasher, g, N);
// generate password verifier to store
BigInteger v = client.GenerateVerifier(I, P, s);
var A = client.GenerateAValues(out var clientSrpState);
Assert.True(A >= BigInteger.Zero);
//var A = client.GenerateTestVectorAValues(
// BigInteger.Negate(BigInteger.Abs(new BigInteger(Sodium.SodiumCore.GetRandomBytes(32)))));
var B = server.GenerateBValues(v, out var serverSrpState);
Assert.True(B >= BigInteger.Zero);
//var B = server.GenerateTestVectorBValues(v,
// BigInteger.Negate(BigInteger.Abs(new BigInteger(Sodium.SodiumCore.GetRandomBytes(32)))));
var clientS = client.ComputeSessionKey(I, P, s, B);
var serverS = server.ComputeSessionKey(v, A);
Assert.Equal(clientS, serverS);
// Restore state in new client and server
client = new SrpClient(hasher, g, N, A, clientSrpState);
server = new SrpServer(hasher, g, N, B, serverSrpState);
var clientS2 = client.ComputeSessionKey(I, P, s, B);
var serverS2 = server.ComputeSessionKey(v, A);
Assert.Equal(clientS2, serverS);
Assert.Equal(clientS, serverS2);
var M1 = client.GenerateClientProof(B, clientS);
Assert.True(server.ValidateClientProof(M1, A, serverS));
var M2 = server.GenerateServerProof(A, M1, serverS);
Assert.True(client.ValidateServerProof(M2, M1, clientS));
}
public static readonly IEnumerable<object[]> _allSrpGroups = new[]
{
new object[] { nameof(SRPGroupParameters.Group1024bit), SRPGroupParameters.Group1024bit, },
new object[] { nameof(SRPGroupParameters.Group1536bit), SRPGroupParameters.Group1536bit, },
new object[] { nameof(SRPGroupParameters.Group2048bit), SRPGroupParameters.Group2048bit, },
new object[] { nameof(SRPGroupParameters.Group3072bit), SRPGroupParameters.Group3072bit, },
new object[] { nameof(SRPGroupParameters.Group4096bit), SRPGroupParameters.Group4096bit, },
new object[] { nameof(SRPGroupParameters.Group6144bit), SRPGroupParameters.Group6144bit, },
new object[] { nameof(SRPGroupParameters.Group8192bit), SRPGroupParameters.Group8192bit, },
};
}
| 40.765957 | 103 | 0.665797 | [
"MIT"
] | ebekker/keypear | test/Keypear.Shared.Tests/PAKE/SRP/ScottBradySRPTests.cs | 5,750 | C# |
using System;
using System.Xml.Linq;
using Gench.Utils;
using Gench.Business;
namespace Gench.Loaders
{
public class ModelSvgLoader : SvgLoader
{
public ModelSvgLoader()
{
}
public XDocument LoadFullModel(ModelPart fullbody)
{
XDocument svg = null;
System.Reflection.MethodBase currentMethod = null;
try
{
if (fullbody.RelativePath)
{
svg = LoadDocument(AppContext.BaseDirectory.ToString() + fullbody.Path);
}
else
{
svg = LoadDocument(fullbody.Path);
}
}
catch (System.IO.FileNotFoundException e)
{
currentMethod = System.Reflection.MethodBase.GetCurrentMethod();
Logger.LogException(this, currentMethod, e);
}
catch (System.NullReferenceException e)
{
e.ToString();
currentMethod = System.Reflection.MethodBase.GetCurrentMethod();
Logger.LogText(this, currentMethod, "ModelPart is null");
}
return svg;
}
}
} | 26.847826 | 92 | 0.512551 | [
"Apache-2.0"
] | arxflay/Gench | Loaders/ModelSvgLoader.cs | 1,235 | C# |
// Copyright (c) 2016 AgileObjects Ltd
// Licensed under the MIT license. See LICENSE file in the ReadableExpressions directory for more information.
namespace LinkIt.ReadableExpressions.Translators.Formatting
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Extensions;
using static System.Environment;
internal class ParameterSet : FormattableExpressionBase
{
private const int SplitArgumentsThreshold = 3;
private readonly IEnumerable<Func<string, string>> _parameterModifiers;
private readonly Expression[] _arguments;
private readonly TranslationContext _context;
private readonly IEnumerable<Func<Expression, string>> _argumentTranslators;
public ParameterSet(
IMethodInfo method,
IEnumerable<Expression> arguments,
TranslationContext context)
{
_parameterModifiers = GetParameterModifers(method);
_arguments = arguments.ToArray();
_context = context;
_argumentTranslators = GetArgumentTranslators(
method,
_arguments,
TranslateArgumentAsCodeBlock);
}
private static IEnumerable<Func<string, string>> GetParameterModifers(IMethodInfo method)
{
if (method == null)
{
return Enumerable.Empty<Func<string, string>>();
}
return method
.GetParameters()
.Select(GetParameterModifier)
.ToArray();
}
private static Func<string, string> GetParameterModifier(ParameterInfo parameter)
{
if (parameter.IsOut)
{
return p => "out " + p;
}
if (parameter.ParameterType.IsByRef)
{
return p => "ref " + p;
}
if (parameter.GetCustomAttribute<ParamArrayAttribute>(inherit: false) != null)
{
return FormatParamsArray;
}
return default(Func<string, string>);
}
private static string FormatParamsArray(string array)
{
var arrayValuesStart = array.IndexOf('{') + 1;
if (arrayValuesStart == 0)
{
return string.Empty;
}
var arrayValuesEnd = array.LastIndexOf('}');
var arrayValues = array
.Substring(arrayValuesStart, arrayValuesEnd - arrayValuesStart)
.SplitToLines(StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim(' '));
var arrayValuesString = string.Join(NewLine, arrayValues);
return arrayValuesString;
}
private IEnumerable<Func<Expression, string>> GetArgumentTranslators(
IMethodInfo method,
IEnumerable<Expression> arguments,
Func<Expression, string> defaultArgumentTranslator)
{
if (method == null)
{
return arguments.Select(argument => defaultArgumentTranslator).ToArray();
}
var parameters = method.GetParameters();
if (method.IsExtensionMethod)
{
parameters = parameters.Skip(1).ToArray();
}
return arguments
.Select((argument, i) =>
{
var parameter = parameters.ElementAtOrDefault(i);
if (IsNotFuncType(parameter, method))
{
return defaultArgumentTranslator;
}
return CanBeConvertedToMethodGroup(argument)
? MethodGroupTranslator
: defaultArgumentTranslator;
})
.ToArray();
}
private static bool IsNotFuncType(ParameterInfo parameter, IMethodInfo method)
{
if (parameter == null)
{
return true;
}
if (parameter.ParameterType.BaseType == typeof(MulticastDelegate))
{
return false;
}
var parameterType = parameter.ParameterType;
if (parameterType.FullName == null)
{
if (!method.IsGenericMethod)
{
return true;
}
parameterType = method.GetGenericArgumentFor(parameter.ParameterType);
}
return
!(parameterType.FullName.StartsWith("System.Action", StringComparison.Ordinal) ||
parameterType.FullName.StartsWith("System.Func", StringComparison.Ordinal)) ||
// ReSharper disable once PossibleUnintendedReferenceComparison
(parameter.ParameterType.Assembly != typeof(Action).Assembly);
}
private static bool CanBeConvertedToMethodGroup(Expression argument)
{
if (argument.NodeType != ExpressionType.Lambda)
{
return false;
}
var argumentLambda = (LambdaExpression)argument;
if (argumentLambda.Body.NodeType != ExpressionType.Call)
{
return false;
}
var lambdaBodyMethodCall = (MethodCallExpression)argumentLambda.Body;
var lambdaBodyMethodCallArguments = lambdaBodyMethodCall.Arguments.ToArray();
if (lambdaBodyMethodCall.Method.IsExtensionMethod())
{
lambdaBodyMethodCallArguments = lambdaBodyMethodCallArguments.Skip(1).ToArray();
}
if (lambdaBodyMethodCallArguments.Length != argumentLambda.Parameters.Count)
{
return false;
}
var i = 0;
var allArgumentTypesMatch = argumentLambda
.Parameters
.All(lambdaParameter => lambdaBodyMethodCallArguments[i++] == lambdaParameter);
return allArgumentTypesMatch;
}
private Func<Expression, string> MethodGroupTranslator
{
get
{
return argument =>
{
var methodCall = (MethodCallExpression)((LambdaExpression)argument).Body;
var subject = MethodCallExpressionTranslator
.GetMethodCallSubject(methodCall, _context);
return subject + "." + methodCall.Method.Name;
};
}
}
private string TranslateArgumentAsCodeBlock(Expression argument)
{
var argumentBlock = _context.TranslateCodeBlock(argument);
var translated = argumentBlock.WithCurlyBracesIfMultiStatement();
return translated;
}
protected override bool SplitToMultipleLines(string translation)
{
return (_arguments.Length > SplitArgumentsThreshold) || base.SplitToMultipleLines(translation);
}
protected override Func<string> SingleLineTranslationFactory => () => FormatParameters(", ");
protected override Func<string> MultipleLineTranslationFactory
{
get
{
return () =>
{
bool hasSingleBlockArgument, hasSingleLambdaArgument;
if (_arguments.Length == 1)
{
hasSingleBlockArgument = IsSingleArgumentABlock();
hasSingleLambdaArgument = !hasSingleBlockArgument && IsSingleArgumentALambda();
}
else
{
hasSingleBlockArgument = hasSingleLambdaArgument = false;
}
var compensateForQuotedLambda =
_context.Settings.CommentQuotedLambdas &&
(_arguments[0].NodeType == ExpressionType.Quote);
var parameters = FormatParameters(
"," + NewLine,
a =>
{
hasSingleBlockArgument = hasSingleBlockArgument && a.IsMultiLine();
if (hasSingleBlockArgument || compensateForQuotedLambda)
{
return a;
}
if (a.StartsWithNewLine())
{
a = a.Substring(NewLine.Length);
}
return a.Indented();
});
if (hasSingleBlockArgument)
{
return parameters;
}
if (hasSingleLambdaArgument)
{
if (compensateForQuotedLambda)
{
return NewLine + parameters
.Substring(NewLine.Length)
.Substring(parameters.IndexOf(NewLine, StringComparison.Ordinal));
}
return parameters.TrimStart();
}
return NewLine + parameters;
};
}
}
private bool IsSingleArgumentABlock()
{
switch (_arguments[0].NodeType)
{
case ExpressionType.Block:
case ExpressionType.Switch:
case ExpressionType.Conditional:
case ExpressionType.Try:
return true;
}
return false;
}
private bool IsSingleArgumentALambda()
{
var argument = _arguments[0];
if (argument.NodeType == ExpressionType.Quote)
{
argument = ((UnaryExpression)argument).Operand;
}
if (argument.NodeType != ExpressionType.Lambda)
{
return false;
}
var argumentLambda = (LambdaExpression)argument;
return argumentLambda.Parameters.Count <= SplitArgumentsThreshold;
}
private string FormatParameters(
string separator,
Func<string, string> extraFormatter = null)
{
if (extraFormatter == null)
{
extraFormatter = s => s;
}
return string.Join(
separator,
_arguments
.Select(TranslateArgument)
.Select(extraFormatter)
.Where(arg => arg != string.Empty));
}
private string TranslateArgument(Expression argument, int parameterIndex)
{
var argumentTranslator = _argumentTranslators.ElementAt(parameterIndex);
var argumentString = argumentTranslator.Invoke(argument).Unterminated();
var modifier = _parameterModifiers.ElementAtOrDefault(parameterIndex);
return (modifier != null) ? modifier.Invoke(argumentString) : argumentString;
}
public string WithParenthesesIfNecessary()
{
return (_arguments.Length == 1) ? WithoutParentheses() : WithParentheses();
}
public string WithoutParentheses()
{
return GetFormattedTranslation();
}
public string WithParentheses()
{
return _arguments.Any() ? GetFormattedTranslation().WithSurroundingParentheses() : "()";
}
}
} | 32.590028 | 110 | 0.523332 | [
"MIT"
] | fynnen/LinkIt | src/LinkIt/ReadableExpressions/Translators/Formatting/ParameterSet.cs | 11,767 | C# |
using System;
//Declare two string variables and assing them with "Hello" and "World"
//Declare an object variable and assing it with the concatenation of the two strings
//Declare a third string variable and assing it with the object value
class StringToObjectToString
{
static void Main()
{
string firstName, secondName; //Declaring two string variables
object firstAndSecond; //Declaring an object variable
firstName = "Hello"; //Assinging the first variable with the value "Hello"
secondName = "World"; //Assinging the second variable with the value "World"
firstAndSecond = firstName + " " + secondName; //Assinging the object variable with the value of the two string variables, separeted by space
string twoNames; //Declaring a third string variable
twoNames = (string)firstAndSecond; //Assinging the third string variable with the object's value by casting the object to string
Console.WriteLine(twoNames); //Writing the third string variable's value on the Console
}
}
| 55.363636 | 150 | 0.633005 | [
"MIT"
] | hackohackob/TelerikAcademy | C#1/VariablesLessonHomework/07.StringToObjectToString/07.StringToObjectToString.cs | 1,220 | C# |
using Autofac;
using Azure.Cosmos.Repositories;
using Azure.Cosmos.Services;
using Microsoft.Azure.Cosmos;
using Serilog;
using Serilog.Extensions.Logging;
using Serilog.Sinks.SystemConsole.Themes;
namespace Autofac
{
public static class ContainerBuilderCustomExtensions
{
public static ContainerBuilder RegisterDependencies(this ContainerBuilder containerBuilder)
{
RegisterServices(containerBuilder);
RegisterRepositories(containerBuilder);
RegisterLogging(containerBuilder);
RegisterCosmosClient(containerBuilder);
return containerBuilder;
}
private static void RegisterServices(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterType<CosmosExecutionService>().As<IExecutionService>();
}
private static void RegisterRepositories(ContainerBuilder containerBuilder)
{
containerBuilder.RegisterGeneric(typeof(CosmosRepository<>)).As(typeof(ICosmosRepository<>));
}
private static void RegisterLogging(ContainerBuilder containerBuilder)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(theme: AnsiConsoleTheme.Code)
.CreateLogger();
containerBuilder.RegisterInstance<Microsoft.Extensions.Logging.ILogger>(new SerilogLoggerProvider().CreateLogger("Happy logging"));
}
private static void RegisterCosmosClient(ContainerBuilder containerBuilder)
{
containerBuilder.Register(_ =>
{
var connectionString = "AccountEndpoint=https://dotnetcosmosdb0242a.documents.azure.com:443/;AccountKey=EEyAZiyka1aHzZE00wWhVhJgmH2Kn8nQGtcW9Y59VQ0cm7GQKPLWNtNVwEC0KwHYEz1OSaSp7u6uLfdXu052XQ==;";//TODO: Refactor this to use keyvault
return new CosmosClient(connectionString);
});
}
}
}
| 37.596154 | 248 | 0.688491 | [
"Apache-2.0"
] | DavidLeonardoGutierrez/dotnet-azure-examples | cosmosdb/src/ContainerBuilderCustomExtensions.cs | 1,955 | 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("EntityFrameworkExtras.EF5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EntityFrameworkExtras.EF5")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("52fa590e-f879-4875-b106-2178043ff15a")]
// 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.459459 | 84 | 0.748419 | [
"MIT"
] | mykiep/EntityFrameworkExtras | EntityFrameworkExtras.EF5/Properties/AssemblyInfo.cs | 1,426 | C# |
using Recipes.SingleModelCrudAsync;
using RepoDb.Attributes;
using System.ComponentModel.DataAnnotations.Schema;
namespace Recipes.RepoDb.SingleModelCrudAsync
{
[Map("HR.EmployeeClassification")]
public class EmployeeClassification : IEmployeeClassification
{
[Primary]
public int EmployeeClassificationKey { get; set; }
/// <exclude />
public string? EmployeeClassificationName { get; set; }
}
}
| 26.352941 | 65 | 0.71875 | [
"Unlicense"
] | lukevp/DotNet-ORM-Cookbook | ORM Cookbook/Recipes.RepoDb/SingleModelCrudAsync/EmployeeClassification.cs | 450 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/automl/v1/model.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.AutoML.V1 {
/// <summary>Holder for reflection information generated from google/cloud/automl/v1/model.proto</summary>
public static partial class ModelReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/automl/v1/model.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ModelReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiJnb29nbGUvY2xvdWQvYXV0b21sL3YxL21vZGVsLnByb3RvEhZnb29nbGUu",
"Y2xvdWQuYXV0b21sLnYxGhlnb29nbGUvYXBpL3Jlc291cmNlLnByb3RvGiJn",
"b29nbGUvY2xvdWQvYXV0b21sL3YxL2ltYWdlLnByb3RvGiFnb29nbGUvY2xv",
"dWQvYXV0b21sL3YxL3RleHQucHJvdG8aKGdvb2dsZS9jbG91ZC9hdXRvbWwv",
"djEvdHJhbnNsYXRpb24ucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90aW1lc3Rh",
"bXAucHJvdG8aHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i8QgKBU1v",
"ZGVsElYKGnRyYW5zbGF0aW9uX21vZGVsX21ldGFkYXRhGA8gASgLMjAuZ29v",
"Z2xlLmNsb3VkLmF1dG9tbC52MS5UcmFuc2xhdGlvbk1vZGVsTWV0YWRhdGFI",
"ABJnCiNpbWFnZV9jbGFzc2lmaWNhdGlvbl9tb2RlbF9tZXRhZGF0YRgNIAEo",
"CzI4Lmdvb2dsZS5jbG91ZC5hdXRvbWwudjEuSW1hZ2VDbGFzc2lmaWNhdGlv",
"bk1vZGVsTWV0YWRhdGFIABJlCiJ0ZXh0X2NsYXNzaWZpY2F0aW9uX21vZGVs",
"X21ldGFkYXRhGA4gASgLMjcuZ29vZ2xlLmNsb3VkLmF1dG9tbC52MS5UZXh0",
"Q2xhc3NpZmljYXRpb25Nb2RlbE1ldGFkYXRhSAASagolaW1hZ2Vfb2JqZWN0",
"X2RldGVjdGlvbl9tb2RlbF9tZXRhZGF0YRgUIAEoCzI5Lmdvb2dsZS5jbG91",
"ZC5hdXRvbWwudjEuSW1hZ2VPYmplY3REZXRlY3Rpb25Nb2RlbE1ldGFkYXRh",
"SAASXQoedGV4dF9leHRyYWN0aW9uX21vZGVsX21ldGFkYXRhGBMgASgLMjMu",
"Z29vZ2xlLmNsb3VkLmF1dG9tbC52MS5UZXh0RXh0cmFjdGlvbk1vZGVsTWV0",
"YWRhdGFIABJbCh10ZXh0X3NlbnRpbWVudF9tb2RlbF9tZXRhZGF0YRgWIAEo",
"CzIyLmdvb2dsZS5jbG91ZC5hdXRvbWwudjEuVGV4dFNlbnRpbWVudE1vZGVs",
"TWV0YWRhdGFIABIMCgRuYW1lGAEgASgJEhQKDGRpc3BsYXlfbmFtZRgCIAEo",
"CRISCgpkYXRhc2V0X2lkGAMgASgJEi8KC2NyZWF0ZV90aW1lGAcgASgLMhou",
"Z29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIvCgt1cGRhdGVfdGltZRgLIAEo",
"CzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASRwoQZGVwbG95bWVudF9z",
"dGF0ZRgIIAEoDjItLmdvb2dsZS5jbG91ZC5hdXRvbWwudjEuTW9kZWwuRGVw",
"bG95bWVudFN0YXRlEgwKBGV0YWcYCiABKAkSOQoGbGFiZWxzGCIgAygLMiku",
"Z29vZ2xlLmNsb3VkLmF1dG9tbC52MS5Nb2RlbC5MYWJlbHNFbnRyeRotCgtM",
"YWJlbHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIlEK",
"D0RlcGxveW1lbnRTdGF0ZRIgChxERVBMT1lNRU5UX1NUQVRFX1VOU1BFQ0lG",
"SUVEEAASDAoIREVQTE9ZRUQQARIOCgpVTkRFUExPWUVEEAI6WOpBVQobYXV0",
"b21sLmdvb2dsZWFwaXMuY29tL01vZGVsEjZwcm9qZWN0cy97cHJvamVjdH0v",
"bG9jYXRpb25zL3tsb2NhdGlvbn0vbW9kZWxzL3ttb2RlbH1CEAoObW9kZWxf",
"bWV0YWRhdGFCqgEKGmNvbS5nb29nbGUuY2xvdWQuYXV0b21sLnYxUAFaPGdv",
"b2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQvYXV0",
"b21sL3YxO2F1dG9tbKoCFkdvb2dsZS5DbG91ZC5BdXRvTUwuVjHKAhZHb29n",
"bGVcQ2xvdWRcQXV0b01sXFYx6gIZR29vZ2xlOjpDbG91ZDo6QXV0b01MOjpW",
"MWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.ResourceReflection.Descriptor, global::Google.Cloud.AutoML.V1.ImageReflection.Descriptor, global::Google.Cloud.AutoML.V1.TextReflection.Descriptor, global::Google.Cloud.AutoML.V1.TranslationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.AutoML.V1.Model), global::Google.Cloud.AutoML.V1.Model.Parser, new[]{ "TranslationModelMetadata", "ImageClassificationModelMetadata", "TextClassificationModelMetadata", "ImageObjectDetectionModelMetadata", "TextExtractionModelMetadata", "TextSentimentModelMetadata", "Name", "DisplayName", "DatasetId", "CreateTime", "UpdateTime", "DeploymentState", "Etag", "Labels" }, new[]{ "ModelMetadata" }, new[]{ typeof(global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState) }, null, new pbr::GeneratedClrTypeInfo[] { null, })
}));
}
#endregion
}
#region Messages
/// <summary>
/// API proto representing a trained machine learning model.
/// </summary>
public sealed partial class Model : pb::IMessage<Model>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Model> _parser = new pb::MessageParser<Model>(() => new Model());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Model> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.AutoML.V1.ModelReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Model() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Model(Model other) : this() {
name_ = other.name_;
displayName_ = other.displayName_;
datasetId_ = other.datasetId_;
createTime_ = other.createTime_ != null ? other.createTime_.Clone() : null;
updateTime_ = other.updateTime_ != null ? other.updateTime_.Clone() : null;
deploymentState_ = other.deploymentState_;
etag_ = other.etag_;
labels_ = other.labels_.Clone();
switch (other.ModelMetadataCase) {
case ModelMetadataOneofCase.TranslationModelMetadata:
TranslationModelMetadata = other.TranslationModelMetadata.Clone();
break;
case ModelMetadataOneofCase.ImageClassificationModelMetadata:
ImageClassificationModelMetadata = other.ImageClassificationModelMetadata.Clone();
break;
case ModelMetadataOneofCase.TextClassificationModelMetadata:
TextClassificationModelMetadata = other.TextClassificationModelMetadata.Clone();
break;
case ModelMetadataOneofCase.ImageObjectDetectionModelMetadata:
ImageObjectDetectionModelMetadata = other.ImageObjectDetectionModelMetadata.Clone();
break;
case ModelMetadataOneofCase.TextExtractionModelMetadata:
TextExtractionModelMetadata = other.TextExtractionModelMetadata.Clone();
break;
case ModelMetadataOneofCase.TextSentimentModelMetadata:
TextSentimentModelMetadata = other.TextSentimentModelMetadata.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Model Clone() {
return new Model(this);
}
/// <summary>Field number for the "translation_model_metadata" field.</summary>
public const int TranslationModelMetadataFieldNumber = 15;
/// <summary>
/// Metadata for translation models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.TranslationModelMetadata TranslationModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata ? (global::Google.Cloud.AutoML.V1.TranslationModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.TranslationModelMetadata;
}
}
/// <summary>Field number for the "image_classification_model_metadata" field.</summary>
public const int ImageClassificationModelMetadataFieldNumber = 13;
/// <summary>
/// Metadata for image classification models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata ImageClassificationModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata ? (global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.ImageClassificationModelMetadata;
}
}
/// <summary>Field number for the "text_classification_model_metadata" field.</summary>
public const int TextClassificationModelMetadataFieldNumber = 14;
/// <summary>
/// Metadata for text classification models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata TextClassificationModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata ? (global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.TextClassificationModelMetadata;
}
}
/// <summary>Field number for the "image_object_detection_model_metadata" field.</summary>
public const int ImageObjectDetectionModelMetadataFieldNumber = 20;
/// <summary>
/// Metadata for image object detection models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata ImageObjectDetectionModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata ? (global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.ImageObjectDetectionModelMetadata;
}
}
/// <summary>Field number for the "text_extraction_model_metadata" field.</summary>
public const int TextExtractionModelMetadataFieldNumber = 19;
/// <summary>
/// Metadata for text extraction models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata TextExtractionModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata ? (global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.TextExtractionModelMetadata;
}
}
/// <summary>Field number for the "text_sentiment_model_metadata" field.</summary>
public const int TextSentimentModelMetadataFieldNumber = 22;
/// <summary>
/// Metadata for text sentiment models.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata TextSentimentModelMetadata {
get { return modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata ? (global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata) modelMetadata_ : null; }
set {
modelMetadata_ = value;
modelMetadataCase_ = value == null ? ModelMetadataOneofCase.None : ModelMetadataOneofCase.TextSentimentModelMetadata;
}
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Output only. Resource name of the model.
/// Format: `projects/{project_id}/locations/{location_id}/models/{model_id}`
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 2;
private string displayName_ = "";
/// <summary>
/// Required. The name of the model to show in the interface. The name can be
/// up to 32 characters long and can consist only of ASCII Latin letters A-Z
/// and a-z, underscores
/// (_), and ASCII digits 0-9. It must start with a letter.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "dataset_id" field.</summary>
public const int DatasetIdFieldNumber = 3;
private string datasetId_ = "";
/// <summary>
/// Required. The resource ID of the dataset used to create the model. The dataset must
/// come from the same ancestor project and location.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DatasetId {
get { return datasetId_; }
set {
datasetId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "create_time" field.</summary>
public const int CreateTimeFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Timestamp createTime_;
/// <summary>
/// Output only. Timestamp when the model training finished and can be used for prediction.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp CreateTime {
get { return createTime_; }
set {
createTime_ = value;
}
}
/// <summary>Field number for the "update_time" field.</summary>
public const int UpdateTimeFieldNumber = 11;
private global::Google.Protobuf.WellKnownTypes.Timestamp updateTime_;
/// <summary>
/// Output only. Timestamp when this model was last updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime {
get { return updateTime_; }
set {
updateTime_ = value;
}
}
/// <summary>Field number for the "deployment_state" field.</summary>
public const int DeploymentStateFieldNumber = 8;
private global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState deploymentState_ = global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified;
/// <summary>
/// Output only. Deployment state of the model. A model can only serve
/// prediction requests after it gets deployed.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState DeploymentState {
get { return deploymentState_; }
set {
deploymentState_ = value;
}
}
/// <summary>Field number for the "etag" field.</summary>
public const int EtagFieldNumber = 10;
private string etag_ = "";
/// <summary>
/// Used to perform a consistent read-modify-write updates. If not set, a blind
/// "overwrite" update happens.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Etag {
get { return etag_; }
set {
etag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 34;
private static readonly pbc::MapField<string, string>.Codec _map_labels_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 274);
private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>();
/// <summary>
/// Optional. The labels with user-defined metadata to organize your model.
///
/// Label keys and values can be no longer than 64 characters
/// (Unicode codepoints), can only contain lowercase letters, numeric
/// characters, underscores and dashes. International characters are allowed.
/// Label values are optional. Label keys must start with a letter.
///
/// See https://goo.gl/xmQnxf for more information on and examples of labels.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Labels {
get { return labels_; }
}
private object modelMetadata_;
/// <summary>Enum of possible cases for the "model_metadata" oneof.</summary>
public enum ModelMetadataOneofCase {
None = 0,
TranslationModelMetadata = 15,
ImageClassificationModelMetadata = 13,
TextClassificationModelMetadata = 14,
ImageObjectDetectionModelMetadata = 20,
TextExtractionModelMetadata = 19,
TextSentimentModelMetadata = 22,
}
private ModelMetadataOneofCase modelMetadataCase_ = ModelMetadataOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ModelMetadataOneofCase ModelMetadataCase {
get { return modelMetadataCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearModelMetadata() {
modelMetadataCase_ = ModelMetadataOneofCase.None;
modelMetadata_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Model);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Model other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(TranslationModelMetadata, other.TranslationModelMetadata)) return false;
if (!object.Equals(ImageClassificationModelMetadata, other.ImageClassificationModelMetadata)) return false;
if (!object.Equals(TextClassificationModelMetadata, other.TextClassificationModelMetadata)) return false;
if (!object.Equals(ImageObjectDetectionModelMetadata, other.ImageObjectDetectionModelMetadata)) return false;
if (!object.Equals(TextExtractionModelMetadata, other.TextExtractionModelMetadata)) return false;
if (!object.Equals(TextSentimentModelMetadata, other.TextSentimentModelMetadata)) return false;
if (Name != other.Name) return false;
if (DisplayName != other.DisplayName) return false;
if (DatasetId != other.DatasetId) return false;
if (!object.Equals(CreateTime, other.CreateTime)) return false;
if (!object.Equals(UpdateTime, other.UpdateTime)) return false;
if (DeploymentState != other.DeploymentState) return false;
if (Etag != other.Etag) return false;
if (!Labels.Equals(other.Labels)) return false;
if (ModelMetadataCase != other.ModelMetadataCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) hash ^= TranslationModelMetadata.GetHashCode();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) hash ^= ImageClassificationModelMetadata.GetHashCode();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) hash ^= TextClassificationModelMetadata.GetHashCode();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) hash ^= ImageObjectDetectionModelMetadata.GetHashCode();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) hash ^= TextExtractionModelMetadata.GetHashCode();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) hash ^= TextSentimentModelMetadata.GetHashCode();
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
if (DatasetId.Length != 0) hash ^= DatasetId.GetHashCode();
if (createTime_ != null) hash ^= CreateTime.GetHashCode();
if (updateTime_ != null) hash ^= UpdateTime.GetHashCode();
if (DeploymentState != global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified) hash ^= DeploymentState.GetHashCode();
if (Etag.Length != 0) hash ^= Etag.GetHashCode();
hash ^= Labels.GetHashCode();
hash ^= (int) modelMetadataCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(DisplayName);
}
if (DatasetId.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DatasetId);
}
if (createTime_ != null) {
output.WriteRawTag(58);
output.WriteMessage(CreateTime);
}
if (DeploymentState != global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified) {
output.WriteRawTag(64);
output.WriteEnum((int) DeploymentState);
}
if (Etag.Length != 0) {
output.WriteRawTag(82);
output.WriteString(Etag);
}
if (updateTime_ != null) {
output.WriteRawTag(90);
output.WriteMessage(UpdateTime);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) {
output.WriteRawTag(106);
output.WriteMessage(ImageClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) {
output.WriteRawTag(114);
output.WriteMessage(TextClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) {
output.WriteRawTag(122);
output.WriteMessage(TranslationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) {
output.WriteRawTag(154, 1);
output.WriteMessage(TextExtractionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) {
output.WriteRawTag(162, 1);
output.WriteMessage(ImageObjectDetectionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) {
output.WriteRawTag(178, 1);
output.WriteMessage(TextSentimentModelMetadata);
}
labels_.WriteTo(output, _map_labels_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(18);
output.WriteString(DisplayName);
}
if (DatasetId.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DatasetId);
}
if (createTime_ != null) {
output.WriteRawTag(58);
output.WriteMessage(CreateTime);
}
if (DeploymentState != global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified) {
output.WriteRawTag(64);
output.WriteEnum((int) DeploymentState);
}
if (Etag.Length != 0) {
output.WriteRawTag(82);
output.WriteString(Etag);
}
if (updateTime_ != null) {
output.WriteRawTag(90);
output.WriteMessage(UpdateTime);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) {
output.WriteRawTag(106);
output.WriteMessage(ImageClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) {
output.WriteRawTag(114);
output.WriteMessage(TextClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) {
output.WriteRawTag(122);
output.WriteMessage(TranslationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) {
output.WriteRawTag(154, 1);
output.WriteMessage(TextExtractionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) {
output.WriteRawTag(162, 1);
output.WriteMessage(ImageObjectDetectionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) {
output.WriteRawTag(178, 1);
output.WriteMessage(TextSentimentModelMetadata);
}
labels_.WriteTo(ref output, _map_labels_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TranslationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ImageClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TextClassificationModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(ImageObjectDetectionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(TextExtractionModelMetadata);
}
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(TextSentimentModelMetadata);
}
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
if (DatasetId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DatasetId);
}
if (createTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(CreateTime);
}
if (updateTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime);
}
if (DeploymentState != global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DeploymentState);
}
if (Etag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Etag);
}
size += labels_.CalculateSize(_map_labels_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Model other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
if (other.DatasetId.Length != 0) {
DatasetId = other.DatasetId;
}
if (other.createTime_ != null) {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
CreateTime.MergeFrom(other.CreateTime);
}
if (other.updateTime_ != null) {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
UpdateTime.MergeFrom(other.UpdateTime);
}
if (other.DeploymentState != global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState.Unspecified) {
DeploymentState = other.DeploymentState;
}
if (other.Etag.Length != 0) {
Etag = other.Etag;
}
labels_.Add(other.labels_);
switch (other.ModelMetadataCase) {
case ModelMetadataOneofCase.TranslationModelMetadata:
if (TranslationModelMetadata == null) {
TranslationModelMetadata = new global::Google.Cloud.AutoML.V1.TranslationModelMetadata();
}
TranslationModelMetadata.MergeFrom(other.TranslationModelMetadata);
break;
case ModelMetadataOneofCase.ImageClassificationModelMetadata:
if (ImageClassificationModelMetadata == null) {
ImageClassificationModelMetadata = new global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata();
}
ImageClassificationModelMetadata.MergeFrom(other.ImageClassificationModelMetadata);
break;
case ModelMetadataOneofCase.TextClassificationModelMetadata:
if (TextClassificationModelMetadata == null) {
TextClassificationModelMetadata = new global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata();
}
TextClassificationModelMetadata.MergeFrom(other.TextClassificationModelMetadata);
break;
case ModelMetadataOneofCase.ImageObjectDetectionModelMetadata:
if (ImageObjectDetectionModelMetadata == null) {
ImageObjectDetectionModelMetadata = new global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata();
}
ImageObjectDetectionModelMetadata.MergeFrom(other.ImageObjectDetectionModelMetadata);
break;
case ModelMetadataOneofCase.TextExtractionModelMetadata:
if (TextExtractionModelMetadata == null) {
TextExtractionModelMetadata = new global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata();
}
TextExtractionModelMetadata.MergeFrom(other.TextExtractionModelMetadata);
break;
case ModelMetadataOneofCase.TextSentimentModelMetadata:
if (TextSentimentModelMetadata == null) {
TextSentimentModelMetadata = new global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata();
}
TextSentimentModelMetadata.MergeFrom(other.TextSentimentModelMetadata);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
DisplayName = input.ReadString();
break;
}
case 26: {
DatasetId = input.ReadString();
break;
}
case 58: {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(CreateTime);
break;
}
case 64: {
DeploymentState = (global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState) input.ReadEnum();
break;
}
case 82: {
Etag = input.ReadString();
break;
}
case 90: {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(UpdateTime);
break;
}
case 106: {
global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) {
subBuilder.MergeFrom(ImageClassificationModelMetadata);
}
input.ReadMessage(subBuilder);
ImageClassificationModelMetadata = subBuilder;
break;
}
case 114: {
global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) {
subBuilder.MergeFrom(TextClassificationModelMetadata);
}
input.ReadMessage(subBuilder);
TextClassificationModelMetadata = subBuilder;
break;
}
case 122: {
global::Google.Cloud.AutoML.V1.TranslationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TranslationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) {
subBuilder.MergeFrom(TranslationModelMetadata);
}
input.ReadMessage(subBuilder);
TranslationModelMetadata = subBuilder;
break;
}
case 154: {
global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) {
subBuilder.MergeFrom(TextExtractionModelMetadata);
}
input.ReadMessage(subBuilder);
TextExtractionModelMetadata = subBuilder;
break;
}
case 162: {
global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) {
subBuilder.MergeFrom(ImageObjectDetectionModelMetadata);
}
input.ReadMessage(subBuilder);
ImageObjectDetectionModelMetadata = subBuilder;
break;
}
case 178: {
global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) {
subBuilder.MergeFrom(TextSentimentModelMetadata);
}
input.ReadMessage(subBuilder);
TextSentimentModelMetadata = subBuilder;
break;
}
case 274: {
labels_.AddEntriesFrom(input, _map_labels_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
DisplayName = input.ReadString();
break;
}
case 26: {
DatasetId = input.ReadString();
break;
}
case 58: {
if (createTime_ == null) {
CreateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(CreateTime);
break;
}
case 64: {
DeploymentState = (global::Google.Cloud.AutoML.V1.Model.Types.DeploymentState) input.ReadEnum();
break;
}
case 82: {
Etag = input.ReadString();
break;
}
case 90: {
if (updateTime_ == null) {
UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(UpdateTime);
break;
}
case 106: {
global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.ImageClassificationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageClassificationModelMetadata) {
subBuilder.MergeFrom(ImageClassificationModelMetadata);
}
input.ReadMessage(subBuilder);
ImageClassificationModelMetadata = subBuilder;
break;
}
case 114: {
global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextClassificationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextClassificationModelMetadata) {
subBuilder.MergeFrom(TextClassificationModelMetadata);
}
input.ReadMessage(subBuilder);
TextClassificationModelMetadata = subBuilder;
break;
}
case 122: {
global::Google.Cloud.AutoML.V1.TranslationModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TranslationModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TranslationModelMetadata) {
subBuilder.MergeFrom(TranslationModelMetadata);
}
input.ReadMessage(subBuilder);
TranslationModelMetadata = subBuilder;
break;
}
case 154: {
global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextExtractionModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextExtractionModelMetadata) {
subBuilder.MergeFrom(TextExtractionModelMetadata);
}
input.ReadMessage(subBuilder);
TextExtractionModelMetadata = subBuilder;
break;
}
case 162: {
global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.ImageObjectDetectionModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.ImageObjectDetectionModelMetadata) {
subBuilder.MergeFrom(ImageObjectDetectionModelMetadata);
}
input.ReadMessage(subBuilder);
ImageObjectDetectionModelMetadata = subBuilder;
break;
}
case 178: {
global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata subBuilder = new global::Google.Cloud.AutoML.V1.TextSentimentModelMetadata();
if (modelMetadataCase_ == ModelMetadataOneofCase.TextSentimentModelMetadata) {
subBuilder.MergeFrom(TextSentimentModelMetadata);
}
input.ReadMessage(subBuilder);
TextSentimentModelMetadata = subBuilder;
break;
}
case 274: {
labels_.AddEntriesFrom(ref input, _map_labels_codec);
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the Model message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Deployment state of the model.
/// </summary>
public enum DeploymentState {
/// <summary>
/// Should not be used, an un-set enum has this value by default.
/// </summary>
[pbr::OriginalName("DEPLOYMENT_STATE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Model is deployed.
/// </summary>
[pbr::OriginalName("DEPLOYED")] Deployed = 1,
/// <summary>
/// Model is not deployed.
/// </summary>
[pbr::OriginalName("UNDEPLOYED")] Undeployed = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 45.148387 | 591 | 0.685267 | [
"Apache-2.0"
] | Global19/google-cloud-dotnet | apis/Google.Cloud.AutoML.V1/Google.Cloud.AutoML.V1/Model.cs | 41,988 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollisionWithEnemy : MonoBehaviour
{
public static bool collided = false;
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.tag == "Enemy")
{
collided = true;
}
}
} | 21.8 | 54 | 0.651376 | [
"MIT"
] | sanjaykaswan/Space-shooter | Shooter/Assets/scripts/CollisionWithEnemy.cs | 329 | C# |
// <auto-generated />
namespace ZureRoom.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class blaasl : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(blaasl));
string IMigrationMetadata.Id
{
get { return "201802021145339_blaasl"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.6 | 89 | 0.611529 | [
"Unlicense"
] | dakkafex/Bon-tempes | ZureRoom/Migrations/201802021145339_blaasl.Designer.cs | 798 | C# |
using UnityEngine;
using System.Collections;
public class QuickSwitcher : MonoBehaviour {
public bool m_enabled = false;
[SerializeField]
private float m_minProgressToStartTransition;
[SerializeField]
private float m_percentageToLockTransition;
[SerializeField]
private Vector3 m_wipeOutPosition;
private Vector3 m_startPosition;
private enum TransitionState { ON, OFF, MANUAL, TWEENING };
private TransitionState m_currentTransitionState;
// Know what the last locked state was so we know what we're transitioning to.
private TransitionState m_lastLockedState;
// Where are we transitioning to and from
private Vector3 m_from;
private Vector3 m_to;
private delegate void TweenCompleteDelegate();
// Use this for initialization
void Start () {
m_startPosition = transform.localPosition;
m_wipeOutPosition = m_startPosition + m_wipeOutPosition;
m_from = m_startPosition;
m_to = m_wipeOutPosition;
m_lastLockedState = TransitionState.ON;
SystemWipeRecognizerListener.Instance.SystemWipeUpdate += onWipeUpdate;
}
// Update is called once per frame
void Update () {
}
private void onWipeUpdate(object sender, SystemWipeArgs eventArgs) {
if ( !m_enabled ) { return; }
string debugLine = "Debug";
if ( eventArgs.WipeInfo.Status == Leap.Util.Status.SwipeAbort ) {
debugLine += " | Abort";
// If the user aborts, tween back to original location
if ( m_lastLockedState == TransitionState.ON ) {
TweenToOnPosition();
}
else {
TweenToOffPosition();
}
}
if ( m_currentTransitionState == TransitionState.MANUAL ) {
debugLine += " | Manual Control";
float percentage = Mathf.Clamp01(eventArgs.WipeInfo.Progress);
debugLine += ": " + percentage;
transform.localPosition = Vector3.Lerp(m_from, m_to, percentage);
// If we're sure of the gesture, just go make the transition
if ( percentage >= m_percentageToLockTransition ) {
debugLine += " | Transition Cofirmed";
if ( m_lastLockedState == TransitionState.OFF ) {
TweenToOnPosition();
}
else {
TweenToOffPosition();
}
}
}
else if ( m_currentTransitionState == TransitionState.TWEENING ) {
debugLine += " | Currently Tweening";
//Debug.Log(debugLine);
return;
}
else { // We're either on or off
debugLine += " | Locked";
if ( eventArgs.WipeInfo.Progress >= m_minProgressToStartTransition ) {
debugLine += " | Go To Manual";
m_currentTransitionState = TransitionState.MANUAL;
}
}
//Debug.Log(debugLine);
}
private void onOnPosition() {
//Debug.Log("onOnPosition");
m_currentTransitionState = TransitionState.ON;
m_lastLockedState = TransitionState.ON;
m_from = m_startPosition;
m_to = m_wipeOutPosition;
}
private void onOffPosition() {
//Debug.Log("onOffPosition");
m_currentTransitionState = TransitionState.OFF;
m_lastLockedState = TransitionState.OFF;
m_from = m_wipeOutPosition;
m_to = m_startPosition;
}
public void TweenToOnPosition() {
//Debug.Log("tweenToOnPosition");
StopAllCoroutines();
StartCoroutine(doPositionTween(0.0f, 0.1f, onOnPosition));
}
public void TweenToOffPosition() {
//Debug.Log("tweenToOffPosition");
StopAllCoroutines();
StartCoroutine(doPositionTween(1.0f, 0.1f, onOffPosition));
}
public void TweenToPosition(float percentage, float time = 0.4f) {
m_currentTransitionState = TransitionState.TWEENING;
StopAllCoroutines();
StartCoroutine(doPositionTween(percentage, time));
}
private IEnumerator doPositionTween(float goalPercent, float transitionTime, TweenCompleteDelegate onComplete = null) {
//Debug.Log("doPositionTween: " + goalPercent);
float startTime = Time.time;
Vector3 from = transform.localPosition;
Vector3 to = Vector3.Lerp(m_startPosition, m_wipeOutPosition, goalPercent);
while ( true ) {
float percentage = Mathf.Clamp01((Time.time - startTime)/transitionTime);
//Debug.Log("Tween step: " + percentage);
transform.localPosition = Vector3.Lerp(from, to, percentage);
// Kick out of the loop if we're done
if ( percentage == 1 ) {
break;
} else { // otherwise continue
yield return 1;
}
}
if ( onComplete != null ) {
onComplete();
}
}
}
| 27.86755 | 120 | 0.719819 | [
"MIT"
] | ice-blaze/LeapulousReturn | Assets/LeapMotion+OVR/SystemWipe/QuickSwitcher.cs | 4,210 | C# |
using Advanced.Algorithms.DataStructures;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.Sorting
{
public class TreeSort
{
public static IEnumerable<T> Sort<T>(IEnumerable<T> enumerable, SortDirection sortDirection = SortDirection.Ascending)
where T : IComparable<T>
{
return TreeSort<T>.Sort(enumerable, Comparer<T>.Default, sortDirection);
}
}
/// <summary>
/// A tree sort implementation.
/// </summary>
public class TreeSort<T>
{
/// <summary>
/// Time complexity: O(nlog(n)).
/// </summary>
public static IEnumerable<T> Sort(IEnumerable<T> enumerable, IComparer<T> order, SortDirection sortDirection = SortDirection.Ascending)
{
//create BST
var tree = new RedBlackTree<T>(comparer: order);
foreach (var item in enumerable)
{
tree.Insert(item);
}
return sortDirection == SortDirection.Ascending ? tree.AsEnumerable() : tree.AsEnumerableDesc();
}
}
}
| 29.710526 | 143 | 0.607617 | [
"MIT"
] | Jmerk523/Advanced-Algorithms | src/Advanced.Algorithms/Sorting/TreeSort.cs | 1,131 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ScriptMenu : MonoBehaviour
{
public void MudarScene(int idScene)
{
SceneManager.LoadScene(idScene);
}
}
| 19.461538 | 40 | 0.750988 | [
"MIT"
] | SrMeuNome/XPStudentes | Assets/Scripts/ScriptMenu.cs | 255 | C# |
namespace Application.Features.OperationClaims.Dtos;
public class CreatedOperationClaimDto
{
public int Id { get; set; }
public string Name { get; set; }
} | 23.428571 | 52 | 0.737805 | [
"MIT"
] | ahmet-cetinkaya/rentacar-project-backend-dotnet | src/rentACar/Application/Features/OperationClaims/Dtos/CreatedOperationClaimDto.cs | 164 | C# |
// Copyright (C) 2012 Xamarin, Inc. All rights reserved.
using System;
using System.Linq;
using System.IO;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Xamarin.Android.Build.Utilities;
namespace Xamarin.Android.Tasks
{
public class JarToXml : ToolTask
{
[Required]
public string AndroidSdkDirectory { get; set; }
[Required]
public string MonoAndroidToolsDirectory { get; set; }
[Required]
public string JavaSdkDirectory { get; set; }
[Required]
public string AndroidApiLevel { get; set; }
[Required]
public string OutputFile { get; set; }
[Required]
public ITaskItem[] SourceJars { get; set; }
public ITaskItem[] ReferenceJars { get; set; }
public string DroidDocPaths { get; set; }
public string JavaDocPaths { get; set; }
public string Java7DocPaths { get; set; }
public string Java8DocPaths { get; set; }
public ITaskItem[] JavaDocs { get; set; }
public ITaskItem[] LibraryProjectJars { get; set; }
public string JavaOptions { get; set; }
public string JavaMaximumHeapSize { get; set; }
public override bool Execute ()
{
Log.LogDebugMessage ("JarToXml Task");
Log.LogDebugMessage (" JavaOptions: {0}", JavaOptions);
Log.LogDebugMessage (" JavaMaximumHeapSize: {0}", JavaMaximumHeapSize);
Log.LogDebugMessage (" AndroidSdkDirectory: {0}", AndroidSdkDirectory);
Log.LogDebugMessage (" AndroidApiLevel: {0}", AndroidApiLevel);
Log.LogDebugMessage (" MonoAndroidToolsDirectory: {0}", MonoAndroidToolsDirectory);
Log.LogDebugMessage (" JavaSdkDirectory: {0}", JavaSdkDirectory);
Log.LogDebugMessage (" OutputFile: {0}", OutputFile);
Log.LogDebugMessage (" DroidDocPaths: {0}", DroidDocPaths);
Log.LogDebugMessage (" JavaDocPaths: {0}", JavaDocPaths);
Log.LogDebugMessage (" Java7DocPaths: {0}", Java7DocPaths);
Log.LogDebugMessage (" Java8DocPaths: {0}", Java8DocPaths);
Log.LogDebugTaskItems (" JavaDocs: {0}", JavaDocs);
Log.LogDebugMessage (" AndroidApiLevel: {0}", AndroidApiLevel);
Log.LogDebugTaskItems (" LibraryProjectJars:", LibraryProjectJars);
Log.LogDebugTaskItems (" SourceJars:", SourceJars);
Log.LogDebugTaskItems (" ReferenceJars:", ReferenceJars);
if (SourceJars == null || SourceJars.Count () == 0) {
Log.LogError ("At least one Java library is required for binding, this must be either 'EmbeddedJar', 'InputJar' (for jar), 'LibraryProjectZip' (for aar or zip) or 'LibraryProjectProperties' (project.properties) build action.");
return false;
}
// Ensure that the user has the platform they are targeting installed
var jarpath = Path.Combine (AndroidSdkDirectory, "platforms", "android-" + MonoAndroidHelper.GetPlatformApiLevelName (AndroidApiLevel), "android.jar");
if (!File.Exists (jarpath)) {
Log.LogError ("Could not find android.jar for API Level {0}. This means the Android SDK platform for API Level {0} is not installed. Either install it in the Android SDK Manager, or change your Android Bindings project to target an API version that is installed. ({1} missing.)", AndroidApiLevel, jarpath);
return false;
}
// Ensure that all requested jars exist
foreach (var jar in SourceJars)
if (!File.Exists (jar.ItemSpec))
Log.LogError ("Specified source jar not found: {0}", jar.ItemSpec);
if (ReferenceJars != null)
foreach (var jar in ReferenceJars)
if (!File.Exists (jar.ItemSpec))
Log.LogError ("Specified reference jar not found: {0}", jar.ItemSpec);
if (Log.HasLoggedErrors)
return false;
// Ensure our output directory exists
Directory.CreateDirectory (Path.GetDirectoryName (OutputFile));
return base.Execute ();
}
protected override string GenerateCommandLineCommands ()
{
var cmd = new CommandLineBuilder ();
// Add the JavaOptions if they are not null
// These could be any of the additional options
if (!string.IsNullOrEmpty (JavaOptions)) {
cmd.AppendSwitch (JavaOptions);
}
// Add the specific -XmxN to override the default heap size for the JVM
// N can be in the form of Nm or NGB (e.g 100m or 1GB )
cmd.AppendSwitchIfNotNull("-Xmx", JavaMaximumHeapSize);
// See https://bugzilla.xamarin.com/show_bug.cgi?id=21096
cmd.AppendSwitch ("-XX:-UseSplitVerifier");
// Arguments sent to java.exe
cmd.AppendSwitchIfNotNull ("-jar ", Path.Combine (MonoAndroidToolsDirectory, "jar2xml.jar"));
foreach (var jar in SourceJars)
cmd.AppendSwitchIfNotNull ("--jar=", Path.GetFullPath (jar.ItemSpec));
var libraryProjectJars = MonoAndroidHelper.ExpandFiles (LibraryProjectJars);
foreach (var jar in libraryProjectJars) {
if (MonoAndroidHelper.IsEmbeddedReferenceJar (jar))
cmd.AppendSwitchIfNotNull ("--ref=", Path.GetFullPath (jar));
else
cmd.AppendSwitchIfNotNull ("--jar=", Path.GetFullPath (jar));
}
// Arguments sent to jar2xml
var jarpath = Path.Combine (AndroidSdkDirectory, "platforms", "android-" + MonoAndroidHelper.GetPlatformApiLevelName (AndroidApiLevel), "android.jar");
cmd.AppendSwitchIfNotNull ("--ref=", Path.GetFullPath (jarpath));
cmd.AppendSwitchIfNotNull ("--out=", Path.GetFullPath (OutputFile));
if (ReferenceJars != null)
foreach (var jar in ReferenceJars)
cmd.AppendSwitchIfNotNull ("--ref=", Path.GetFullPath (jar.ItemSpec));
if (DroidDocPaths != null)
foreach (var path in DroidDocPaths.Split (';'))
cmd.AppendSwitchIfNotNull ("--droiddocpath=", Path.GetFullPath (path));
if (JavaDocPaths != null)
foreach (var path in JavaDocPaths.Split (';'))
cmd.AppendSwitchIfNotNull ("--javadocpath=", Path.GetFullPath (path));
if (Java7DocPaths != null)
foreach (var path in Java7DocPaths.Split (';'))
cmd.AppendSwitchIfNotNull ("--java7docpath=", Path.GetFullPath (path));
if (Java8DocPaths != null)
foreach (var path in Java8DocPaths.Split (';'))
cmd.AppendSwitchIfNotNull ("--java8docpath=", Path.GetFullPath (path));
if (JavaDocs != null)
foreach (var doc in JavaDocs) {
var opt = GetJavadocOption (doc.ItemSpec);
if (opt != null)
cmd.AppendSwitchIfNotNull (opt, Path.GetFullPath (Path.GetDirectoryName (doc.ItemSpec)));
}
return cmd.ToString ();
}
string GetJavadocOption (string file)
{
string rawHTML = File.ReadAllText (file);
if (rawHTML.Length < 500)
return null;
if (rawHTML.Substring (0, 500).IndexOf ("Generated by javadoc (build 1.6", StringComparison.Ordinal) > 0)
return "--javadocpath=";
if (rawHTML.Substring (0, 500).IndexOf ("Generated by javadoc (version 1.7", StringComparison.Ordinal) > 0)
return "--java7docpath=";
return "--droiddocpath=";
}
protected override string ToolName { get { return "jar2xml"; } }
public override string ToolExe {
get { return OS.IsWindows ? "java.exe" : "java"; }
set { base.ToolExe = value; }
}
protected override string GenerateFullPathToTool ()
{
return Path.Combine (JavaSdkDirectory, "bin", ToolExe);
}
private string GetMsBuildDirectory ()
{
return Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location);
}
}
}
| 36.758974 | 312 | 0.702846 | [
"BSD-3-Clause"
] | LvxlongSir/xamarin-android | src/Xamarin.Android.Build.Tasks/Tasks/JarToXml.cs | 7,170 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using SimpleMapper.Benchmark.Models;
namespace SimpleMapper.Benchmark
{
[SimpleJob(RuntimeMoniker.CoreRt31)]
public class SimpleBenchmark
{
private SimpleModel[] _models;
private int _count = 10000;
[GlobalSetup]
public void Setup()
{
var dateTime = DateTime.Now;
_models = new SimpleModel[_count];
for (var c = 0; c < _count; c++)
{
_models[c] = new SimpleModel
{
Id = c,
Date = dateTime,
Decimal = c,
Name = $"Item {c}"
};
}
}
[Benchmark]
public void MapSimpleModels() => Consume(_models.MapCollection<SimpleModel, SimpleOutput>());
private readonly Consumer _consumer = new Consumer();
private void Consume(IEnumerable<SimpleOutput> outputs)
{
foreach (var simpleOutput in outputs)
{
_consumer.Consume(simpleOutput);
}
}
}
public class Program
{
public static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<SimpleBenchmark>();
}
}
} | 26.363636 | 101 | 0.550345 | [
"MIT"
] | mbrewerton/SimpleMapper | SimpleMapper.Benchmark/Program.cs | 1,452 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.As.V20180419.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeLaunchConfigurationsRequest : AbstractModel
{
/// <summary>
/// 按照一个或者多个启动配置ID查询。启动配置ID形如:`asc-ouy1ax38`。每次请求的上限为100。参数不支持同时指定`LaunchConfigurationIds`和`Filters`
/// </summary>
[JsonProperty("LaunchConfigurationIds")]
public string[] LaunchConfigurationIds{ get; set; }
/// <summary>
/// 过滤条件。
/// <li> launch-configuration-id - String - 是否必填:否 -(过滤条件)按照启动配置ID过滤。</li>
/// <li> launch-configuration-name - String - 是否必填:否 -(过滤条件)按照启动配置名称过滤。</li>
/// <li> vague-launch-configuration-name - String - 是否必填:否 -(过滤条件)按照启动配置名称模糊搜索。</li>
/// 每次请求的`Filters`的上限为10,`Filter.Values`的上限为5。参数不支持同时指定`LaunchConfigurationIds`和`Filters`。
/// </summary>
[JsonProperty("Filters")]
public Filter[] Filters{ get; set; }
/// <summary>
/// 返回数量,默认为20,最大值为100。关于`Limit`的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节。
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// 偏移量,默认为0。关于`Offset`的更进一步介绍请参考 API [简介](https://cloud.tencent.com/document/api/213/15688)中的相关小节。
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "LaunchConfigurationIds.", this.LaunchConfigurationIds);
this.SetParamArrayObj(map, prefix + "Filters.", this.Filters);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
}
}
}
| 38.246377 | 116 | 0.642668 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/As/V20180419/Models/DescribeLaunchConfigurationsRequest.cs | 3,051 | C# |
using System.Threading.Tasks;
namespace SheepIt.Api.Infrastructure.Handlers
{
public interface IHandler<in TRequest, TResponse>
{
Task<TResponse> Handle(TRequest request);
}
public interface IHandler<in TRequest>
{
Task Handle(TRequest request);
}
public class Nothing
{
public static Nothing Value { get; } = new Nothing();
private Nothing()
{
}
}
} | 19.043478 | 61 | 0.614155 | [
"MIT"
] | sheepit/sheepit | source/SheepIt.Api/Infrastructure/Handlers/IHandler.cs | 438 | C# |
namespace Sitecore.FakeDb.Data.Engines.DataCommands.Prototypes
{
using System;
using Sitecore.Collections;
using Sitecore.Data;
public class GetChildrenCommandPrototype : Sitecore.Data.Engines.DataCommands.GetChildrenCommand
{
private readonly DataEngineCommand innerCommand;
public GetChildrenCommandPrototype(Database database)
{
this.innerCommand = new DataEngineCommand(database);
}
protected override Sitecore.Data.Engines.DataCommands.GetChildrenCommand CreateInstance()
{
return new GetChildrenCommand(this.innerCommand.DataStorage);
}
protected override ItemList DoExecute()
{
throw new NotSupportedException();
}
}
} | 26.884615 | 98 | 0.756795 | [
"MIT"
] | mikeedwards83/Sitecore.FakeDb | src/Sitecore.FakeDb/Data/Engines/DataCommands/Prototypes/GetChildrenCommandPrototype.cs | 699 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Vpc-VserverGroup
* 与服务器组相关的接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Jdfusion.Apis
{
/// <summary>
/// 删除服务器组
/// </summary>
public class DeleteVserverGroupResult : JdcloudResult
{
}
} | 24.853659 | 76 | 0.71737 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Jdfusion/Apis/DeleteVserverGroupResult.cs | 1,051 | C# |
using System;
using System.Collections.Generic;
using MilitiaDataParsing;
using System.Reflection;
namespace Example
{
class Program
{
static void Main(string[] args)
{
ParserHandler parser = new ParserHandler(ParserOnOutput);
Organization org = new Organization("Parsing \" Inc", true, new Person("Donna", "Kearney", 33, Gender.Female, new Details("3572 Poling Farm Road", "402-354-7168", "donna.kearney@parsing.inc")), new Details("2891 Jessie Street", "740-663-1757", "business@parsing.inc"));
org.Owner.Devices.Add(new Device("UPhone 80E", "2017-03-21"));
org.Owner.Devices.Add(new Device("PakBook 13", "2016-07-30"));
org.Employees.Add(new Person("Dawn", "Mack", 46, Gender.Male, new Details("2725 Giraffe Hill Drive", "972-252-3109", "DawnGMack@jourrapide.com")));
org.Employees[0].Devices.Add(new Device("MePad", "2016-11-09"));
org.Employees.Add(new Person("Christina", "Bates", 32, Gender.Female, new Details("2714 Heavner Avenue", "770-762-5351", "ChristinaCBates@dayrep.com")));
org.Employees.Add(new Person("Shane", "Osborne", 35, Gender.Male, new Details("1880 Timber Oak Drive", "805-926-2039", "ShaneKOsborne@teleworm.us")));
string orgData = parser.Export(org);
Console.WriteLine("--orgData:");
Console.WriteLine(orgData);
string orgData2 = parser.Export(org);
Console.WriteLine("--orgData2:");
Console.WriteLine(orgData2);
Organization org2 = parser.Import<Organization>(orgData2) as Organization;
string orgData3 = parser.Export(org2);
Console.WriteLine("--orgData3:");
Console.WriteLine(orgData3);
if (orgData == orgData2 && orgData == orgData3)
{
Console.WriteLine("All data is identical.");
}
Console.ReadLine();
}
private static void ParserOnOutput(object sender, OutputEventArgs e)
{
Console.WriteLine(e.Message);
}
public enum Gender { Male, Female }
public class Details : IParsable
{
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public Details() { }
public Details(string address, string phone, string email)
{
Address = address;
Phone = phone;
Email = email;
}
public virtual string Header { get { return "details"; } }
public virtual void Parsing(Parser parse)
{
Address = parse.Auto("address", Address);
Phone = parse.Auto("phone", Phone);
Email = parse.Auto("email", Email);
}
}
public class Device : IParsable
{
public string Title { get; set; }
public string Date { get; set; }
public Device() { }
public Device(string title, string date)
{
Title = title;
Date = date;
}
public string Header { get { return "device"; } }
public void Parsing(Parser p)
{
Title = p.Auto("title", Title);
Date = p.Auto("date", Date);
}
}
public class Person : IParsable
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
public Details Details { get; set; }
public List<Device> Devices { get; set; }
public Person()
{
Devices = new List<Device>();
}
public Person(string firstName, string lastName, int age, Gender gender, Details details, List<Device> devices)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Gender = gender;
Details = details;
Devices = devices;
}
public Person(string firstName, string lastName, int age, Gender gender, Details details) : this(firstName, lastName, age, gender, details, new List<Device>()) { }
public string Header { get { return "person"; } }
public void Parsing(Parser p)
{
FirstName = p.Auto("first_name", FirstName);
LastName = p.Auto("last_name", LastName);
Age = p.Auto("age", Age);
Gender = p.Auto("gender", Gender);
Details = p.Auto("details", Details);
Devices = p.List("devices", Devices);
}
}
public class Organization : IParsable
{
public string Title { get; set; }
public bool Active { get; set; }
public Person Owner { get; set; }
public List<Person> Employees { get; set; }
public Details Details { get; set; }
public Organization()
{
Employees = new List<Person>();
}
public Organization(string title, bool active, Person owner, Details details) : this()
{
Title = title;
Active = active;
Owner = owner;
Details = details;
}
public string Header { get { return "organization"; } }
public void Parsing(Parser p)
{
Title = p.Auto("title", Title);
Active = p.Auto("active", Active);
Owner = p.Auto("owner", Owner);
Details = p.Auto("details", Details);
Employees = p.List("employees", Employees);
}
}
}
}
| 34.953216 | 281 | 0.518655 | [
"MIT"
] | 01c/MilitiaDataParsing | Example/Program.cs | 5,979 | C# |
/**
* Copyright 2016 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using IBM.Watson.DeveloperCloud.Logging;
using UnityEngine;
using UnityEngine.UI;
public class OctopusController : MonoBehaviour
{
public GameObject octopus;
public OctopusMovement octopusMovement;
public GameObject debugPanel;
Animator octopusAnimator;
void Start()
{
octopusAnimator = octopus.GetComponent<Animator>();
}
// perform the logic on the octopus. In our case this is only called from the ConversationHandler, but could be called from other controllers.
public void processIntent(string intent)
{
Log.Debug("OctopusLogic.processIntent()", "Intent: {0}", intent);
switch (intent.ToLower())
{
case ("wave"):
{
Log.Debug("OctopusLogic.processIntent()", "Setting Octopus to Wave");
octopusAnimator.CrossFade("Wave", 0); // With a crossFade of >0, it seems to take too long to respond to the command.
octopusMovement.StopForwardMotion();
break;
}
case ("walk"):
{
Log.Debug("OctopusLogic.processIntent()", "Setting Octopus to Walk");
octopusAnimator.CrossFade("Walk", 0); // With a crossFade of >0, it seems to take too long to respond to the command.
octopusMovement.StartForwardMotion();
break;
}
case ("jump"):
{
Log.Debug("OctopusLogic.processIntent()", "Setting Octopus to Jump");
octopusAnimator.CrossFade("Jump", 0); // With a crossFade of >0, it seems to take too long to respond to the command.
octopusMovement.StopForwardMotion();
break;
}
case ("bigger"):
{
Log.Debug("OctopusLogic.processIntent()", "Increasing Octopus size");
octopus.transform.localScale = new Vector3(octopus.transform.localScale.x * 1.2f, octopus.transform.localScale.y * 1.2f, octopus.transform.localScale.z * 1.2f);
break;
}
case ("smaller"):
{
Log.Debug("OctopusLogic.processIntent()", "Decreasing Octopus size");
octopus.transform.localScale = new Vector3(octopus.transform.localScale.x * 0.8f, octopus.transform.localScale.y * 0.8f, octopus.transform.localScale.z * 0.8f);
break;
}
case ("clockwise"):
{
Log.Debug("OctopusLogic.processIntent()", "Turning 90 degrees Clockwise");
octopusMovement.Turn(90);
break;
}
case ("anticlockwise"):
{
Log.Debug("OctopusLogic.processIntent()", "Turning 90 degrees Anticlockwise");
octopusMovement.Turn(-90);
break;
}
case ("debug"):
{
Log.Debug("OctopusLogic.processIntent()", "Toggling the debug window");
//if (debugPanel.alpha == 1f) debugPanel.alpha = 0f;
//else debugPanel.alpha = 1f;
if (debugPanel.activeSelf) debugPanel.SetActive(false);
else debugPanel.SetActive(true);
break;
}
case ("idle"):
{
Log.Debug("OctopusLogic.processIntent()", "Setting Octopus to idle");
octopusAnimator.CrossFade("Idle1", 0);
octopusMovement.StopForwardMotion();
break;
}
default:
break;
}
}
}
| 31.456897 | 165 | 0.675253 | [
"Apache-2.0"
] | ThinhPhan/rainbow-octopus | RainbowOctopus/Assets/RainbowOctopus/Scripts/OctopusController.cs | 3,649 | C# |
using NAudio.Wave;
using System;
namespace synthesizer
{
public class DelaySampleProvider : ISampleProvider
{
private readonly ISampleProvider _source;
private float _delayPosition = 0.0f;
private float _delayLength;
private float _delay;
private float _resamplePosition;
private int _resamplePositionIntPart;
private float _delayResamplePosition;
private int _pos;
private float[] _delayBuffer = new float[500000];
public WaveFormat WaveFormat => _source.WaveFormat;
// Resample if the delay length changes?
private bool resample;
public bool Resample
{
get => resample;
set
{
resample = value;
SetSlide();
}
}
// Delay in milliseconds, 0 - 4000ms
private double delayMs;
public double DelayMs
{
get => delayMs;
set
{
delayMs = value;
_delayPosition = 0;
SetSlide();
}
}
// Amount of feedback, 0.0 - 0.95
private float feedback;
public float Feedback
{
get => feedback;
set
{
feedback = value;
SetSlide();
}
}
// Amount of dry signal to feed into the delay effect, 0.0 - 1.0
private float mix;
public float Mix
{
get => mix;
set
{
mix = value;
SetSlide();
}
}
// Output wet mix gain, 0.0 - 1.0
private float outputWet;
public float OutputWet
{
get => outputWet;
set
{
outputWet = value;
SetSlide();
}
}
// Output dry mix gain, 0.0 - 1.0
private float outputDry;
public float OutputDry
{
get => outputDry;
set
{
outputDry = value;
SetSlide();
}
}
public DelaySampleProvider(ISampleProvider source)
{
_source = source;
_delayPosition = 0;
Resample = true;
SetSlide();
}
public int Read(float[] buffer, int offset, int count)
{
var read = _source.Read(buffer, offset, count);
for (var i = 0; i < read; i++)
{
buffer[offset + i] = Process(buffer[offset + i]);
}
return read;
}
private float Process(float inputSample)
{
var delayPosition = (int)_delayPosition;
var outputSample = _delayBuffer[delayPosition];
_delayBuffer[delayPosition + 0] = Math.Min(Math.Max((inputSample * Mix) + (outputSample * Feedback), -4), 4);
if ((_delayPosition += 1) >= _delayLength)
{
_delayPosition = 0;
}
return (inputSample * OutputDry) + (outputSample * OutputWet);
}
private void SetSlide()
{
_delay = _delayLength;
_delayLength = (float)Math.Min((DelayMs * WaveFormat.SampleRate) / 1000, _delayBuffer.Length);
if (_delay != _delayLength)
{
if (Resample && (_delay > _delayLength))
{
_resamplePosition = 0;
_resamplePositionIntPart = 0;
_delayResamplePosition = _delay / _delayLength;
for (var i = 0; i < _delayLength; i++)
{
_pos = ((int)_resamplePosition) * 2;
_delayBuffer[_resamplePositionIntPart] = _delayBuffer[_pos];
_delayBuffer[_resamplePositionIntPart + 1] = _delayBuffer[_pos + 1];
_resamplePositionIntPart += 2;
_resamplePosition += _delayResamplePosition;
}
_delayPosition = _delayResamplePosition != 0.0f
? _delayPosition / _delayResamplePosition
: _delayPosition;
_delayPosition = (_delayPosition < 0) ? 0 : (int)_delayPosition;
}
else
{
if (Resample && (_delay < _delayLength))
{
_delayResamplePosition = _delay / _delayLength;
_resamplePosition = _delay;
_resamplePositionIntPart = ((int)_delayLength) * 2;
for (var i = 0; i < (int)_delayLength; i++)
{
_resamplePosition -= _delayResamplePosition;
_resamplePositionIntPart -= 2;
_pos = Math.Abs(((int)_resamplePosition) * 2);
_delayBuffer[_resamplePositionIntPart] = _delayBuffer[_pos];
_delayBuffer[_resamplePositionIntPart + 1] = _delayBuffer[_pos + 1];
}
_delayPosition = _delayResamplePosition != 0.0f
? _delayPosition / _delayResamplePosition
: _delayPosition;
_delayPosition = (_delayPosition < 0) ? 0 : (int)_delayPosition;
}
else
{
if (Resample && (_delayPosition >= _delayLength))
{
_delayPosition = 0;
}
}
}
}
}
}
}
| 30.883598 | 121 | 0.453315 | [
"MIT"
] | essenbee/synthesizer | src/synthesizer/DelaySampleProvider.cs | 5,839 | C# |
//-----------------------------------------------------------------------
// <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
// Copyright (c) 2011, The Outercurve Foundation.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.opensource.org/licenses/mit-license.php
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
// <website>https://github.com/facebook-csharp-sdk/simple-json</website>
//-----------------------------------------------------------------------
// VERSION: 0.38.0
// NOTE: uncomment the following line to make SimpleJson class internal.
//#define SIMPLE_JSON_INTERNAL
// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.
//#define SIMPLE_JSON_OBJARRAYINTERNAL
// NOTE: uncomment the following line to enable dynamic support.
#define SIMPLE_JSON_DYNAMIC
// NOTE: uncomment the following line to enable DataContract support.
//#define SIMPLE_JSON_DATACONTRACT
// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.
//#define SIMPLE_JSON_READONLY_COLLECTIONS
// NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke().
// define if you are using .net framework <= 3.0 or < WP7.5
//#define SIMPLE_JSON_NO_LINQ_EXPRESSION
// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
// usually already defined in properties
//#define NETFX_CORE;
// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;
// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
#if NETFX_CORE
#define SIMPLE_JSON_TYPEINFO
#endif
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
using System.Linq.Expressions;
#endif
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#if SIMPLE_JSON_DYNAMIC
using System.Dynamic;
#endif
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Conduit.Reflection;
// ReSharper disable LoopCanBeConvertedToQuery
// ReSharper disable RedundantExplicitArrayCreation
// ReSharper disable SuggestUseVarKeywordEvident
namespace Conduit
{
/// <summary>
/// Represents the json array.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonArray : List<object>
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
public JsonArray() { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonArray"/> class.
/// </summary>
/// <param name="capacity">The capacity of the json array.</param>
public JsonArray(int capacity) : base(capacity) { }
/// <summary>
/// The json representation of the array.
/// </summary>
/// <returns>The json representation of the array.</returns>
public override string ToString()
{
return SimpleJson.SerializeObject(this) ?? string.Empty;
}
}
/// <summary>
/// Represents the json object.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
#if SIMPLE_JSON_OBJARRAYINTERNAL
internal
#else
public
#endif
class JsonObject :
#if SIMPLE_JSON_DYNAMIC
DynamicObject,
#endif
IDictionary<string, object>
{
/// <summary>
/// The internal member dictionary.
/// </summary>
private readonly Dictionary<string, object> _members;
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
public JsonObject()
{
_members = new Dictionary<string, object>();
}
/// <summary>
/// Initializes a new instance of <see cref="JsonObject"/>.
/// </summary>
/// <param name="comparer">The <see cref="T:System.Collections.Generic.IEqualityComparer`1"/> implementation to use when comparing keys, or null to use the default <see cref="T:System.Collections.Generic.EqualityComparer`1"/> for the type of the key.</param>
public JsonObject(IEqualityComparer<string> comparer)
{
_members = new Dictionary<string, object>(comparer);
}
/// <summary>
/// Gets the <see cref="System.Object"/> at the specified index.
/// </summary>
/// <value></value>
public object this[int index]
{
get { return GetAtIndex(_members, index); }
}
internal static object GetAtIndex(IDictionary<string, object> obj, int index)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (index >= obj.Count)
throw new ArgumentOutOfRangeException("index");
int i = 0;
foreach (KeyValuePair<string, object> o in obj)
if (i++ == index) return o.Value;
return null;
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add(string key, object value)
{
_members.Add(key, value);
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool ContainsKey(string key)
{
return _members.ContainsKey(key);
}
/// <summary>
/// Gets the keys.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys
{
get { return _members.Keys; }
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public bool Remove(string key)
{
return _members.Remove(key);
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGetValue(string key, out object value)
{
return _members.TryGetValue(key, out value);
}
/// <summary>
/// Gets the values.
/// </summary>
/// <value>The values.</value>
public ICollection<object> Values
{
get { return _members.Values; }
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public object this[string key]
{
get { return _members[key]; }
set { _members[key] = value; }
}
/// <summary>
/// Adds the specified item.
/// </summary>
/// <param name="item">The item.</param>
public void Add(KeyValuePair<string, object> item)
{
_members.Add(item.Key, item.Value);
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
_members.Clear();
}
/// <summary>
/// Determines whether [contains] [the specified item].
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.
/// </returns>
public bool Contains(KeyValuePair<string, object> item)
{
return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException("array");
int num = Count;
foreach (KeyValuePair<string, object> kvp in this)
{
array[arrayIndex++] = kvp;
if (--num <= 0)
return;
}
}
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
public int Count
{
get { return _members.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value>
/// <c>true</c> if this instance is read only; otherwise, <c>false</c>.
/// </value>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns></returns>
public bool Remove(KeyValuePair<string, object> item)
{
return _members.Remove(item.Key);
}
/// <summary>
/// Gets the enumerator.
/// </summary>
/// <returns></returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _members.GetEnumerator();
}
/// <summary>
/// Returns a json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A json <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return SimpleJson.SerializeObject(this);
}
#if SIMPLE_JSON_DYNAMIC
/// <summary>
/// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
/// </summary>
/// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>
/// <param name="result">The result of the type conversion operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryConvert(ConvertBinder binder, out object result)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
Type targetType = binder.Type;
if ((targetType == typeof(IEnumerable)) ||
(targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
(targetType == typeof(IDictionary<string, object>)) ||
(targetType == typeof(IDictionary)))
{
result = this;
return true;
}
return base.TryConvert(binder, out result);
}
/// <summary>
/// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
/// </summary>
/// <param name="binder">Provides information about the deletion.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryDeleteMember(DeleteMemberBinder binder)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
return _members.Remove(binder.Name);
}
/// <summary>
/// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="result">The result of the index operation.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
result = ((IDictionary<string, object>)this)[(string)indexes[0]];
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
/// <returns>
/// Alwasy returns true.
/// </returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
object value;
if (_members.TryGetValue(binder.Name, out value))
{
result = value;
return true;
}
result = null;
return true;
}
/// <summary>
/// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="indexes"/> is equal to 3.</param>
/// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
/// </returns>
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes == null) throw new ArgumentNullException("indexes");
if (indexes.Length == 1)
{
((IDictionary<string, object>)this)[(string)indexes[0]] = value;
return true;
}
return base.TrySetIndex(binder, indexes, value);
}
/// <summary>
/// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
// <pex>
if (binder == null)
throw new ArgumentNullException("binder");
// </pex>
_members[binder.Name] = value;
return true;
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>
/// A sequence that contains dynamic member names.
/// </returns>
public override IEnumerable<string> GetDynamicMemberNames()
{
foreach (var key in Keys)
yield return key;
}
#endif
}
}
namespace Conduit
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>).
/// All numbers are parsed to doubles.
/// </summary>
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
static class SimpleJson
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
private static readonly char[] EscapeTable;
private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
private static readonly string EscapeCharactersString = new string(EscapeCharacters);
static SimpleJson()
{
EscapeTable = new char[93];
EscapeTable['"'] = '"';
EscapeTable['\\'] = '\\';
EscapeTable['\b'] = 'b';
EscapeTable['\f'] = 'f';
EscapeTable['\n'] = 'n';
EscapeTable['\r'] = 'r';
EscapeTable['\t'] = 't';
}
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false</returns>
public static object DeserializeObject(string json)
{
object obj;
if (TryDeserializeObject(json, out obj))
return obj;
throw new SerializationException("Invalid JSON string");
}
/// <summary>
/// Try parsing the json string into a value.
/// </summary>
/// <param name="json">
/// A JSON string.
/// </param>
/// <param name="obj">
/// The object.
/// </param>
/// <returns>
/// Returns true if successfull otherwise false.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
public static bool TryDeserializeObject(string json, out object obj)
{
bool success = true;
if (json != null)
{
char[] charArray = json.ToCharArray();
int index = 0;
obj = ParseValue(charArray, ref index, ref success);
}
else
obj = null;
return success;
}
public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)
{
object jsonObject = DeserializeObject(json);
return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)
? jsonObject
: (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);
}
public static object DeserializeObject(string json, Type type)
{
return DeserializeObject(json, type, null);
}
public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)
{
return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);
}
public static T DeserializeObject<T>(string json)
{
return (T)DeserializeObject(json, typeof(T), null);
}
/// <summary>
/// Converts a IDictionary<string,object> / IList<object> object into a JSON string
/// </summary>
/// <param name="json">A IDictionary<string,object> / IList<object></param>
/// <param name="jsonSerializerStrategy">Serializer strategy to use</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(jsonSerializerStrategy, json, builder);
return (success ? builder.ToString() : null);
}
public static string SerializeObject(object json)
{
return SerializeObject(json, CurrentJsonSerializerStrategy);
}
public static string EscapeToJavascriptString(string jsonString)
{
if (string.IsNullOrEmpty(jsonString))
return jsonString;
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < jsonString.Length;)
{
c = jsonString[i++];
if (c == '\\')
{
int remainingLength = jsonString.Length - i;
if (remainingLength >= 2)
{
char lookahead = jsonString[i];
if (lookahead == '\\')
{
sb.Append('\\');
++i;
}
else if (lookahead == '"')
{
sb.Append("\"");
++i;
}
else if (lookahead == 't')
{
sb.Append('\t');
++i;
}
else if (lookahead == 'b')
{
sb.Append('\b');
++i;
}
else if (lookahead == 'n')
{
sb.Append('\n');
++i;
}
else if (lookahead == 'r')
{
sb.Append('\r');
++i;
}
}
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
{
IDictionary<string, object> table = new JsonObject();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done)
{
token = LookAhead(json, index);
if (token == TOKEN_NONE)
{
success = false;
return null;
}
else if (token == TOKEN_COMMA)
NextToken(json, ref index);
else if (token == TOKEN_CURLY_CLOSE)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TOKEN_COLON)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
static JsonArray ParseArray(char[] json, ref int index, ref bool success)
{
JsonArray array = new JsonArray();
// [
NextToken(json, ref index);
bool done = false;
while (!done)
{
int token = LookAhead(json, index);
if (token == TOKEN_NONE)
{
success = false;
return null;
}
else if (token == TOKEN_COMMA)
NextToken(json, ref index);
else if (token == TOKEN_SQUARED_CLOSE)
{
NextToken(json, ref index);
break;
}
else
{
object value = ParseValue(json, ref index, ref success);
if (!success)
return null;
array.Add(value);
}
}
return array;
}
static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index))
{
case TOKEN_STRING:
return ParseString(json, ref index, ref success);
case TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case TOKEN_TRUE:
NextToken(json, ref index);
return true;
case TOKEN_FALSE:
NextToken(json, ref index);
return false;
case TOKEN_NULL:
NextToken(json, ref index);
return null;
case TOKEN_NONE:
break;
}
success = false;
return null;
}
static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete)
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
{
complete = true;
break;
}
else if (c == '\\')
{
if (index == json.Length)
break;
c = json[index++];
if (c == '"')
s.Append('"');
else if (c == '\\')
s.Append('\\');
else if (c == '/')
s.Append('/');
else if (c == 'b')
s.Append('\b');
else if (c == 'f')
s.Append('\f');
else if (c == 'n')
s.Append('\n');
else if (c == 'r')
s.Append('\r');
else if (c == 't')
s.Append('\t');
else if (c == 'u')
{
int remainingLength = json.Length - index;
if (remainingLength >= 4)
{
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
return "";
// convert the integer codepoint to a unicode char and add to string
if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate
{
index += 4; // skip 4 chars
remainingLength = json.Length - index;
if (remainingLength >= 6)
{
uint lowCodePoint;
if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
{
if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate
{
s.Append((char)codePoint);
s.Append((char)lowCodePoint);
index += 6; // skip 6 chars
continue;
}
}
}
success = false; // invalid surrogate pair
return "";
}
s.Append(ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
else
break;
}
}
else
s.Append(c);
}
if (!complete)
{
success = false;
return null;
}
return s.ToString();
}
private static string ConvertFromUtf32(int utf32)
{
// http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm
if (utf32 < 0 || utf32 > 0x10FFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
if (0xD800 <= utf32 && utf32 <= 0xDFFF)
throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
if (utf32 < 0x10000)
return new string((char)utf32, 1);
utf32 -= 0x10000;
return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
}
static object ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
object returnNumber;
string str = new string(json, index, charLength);
if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
{
double number;
success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
}
else
{
long number;
success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
returnNumber = number;
if (!success)
{
ulong unumber;
success = ulong.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out unumber);
returnNumber = unumber;
}
}
index = lastIndex + 1;
return returnNumber;
}
static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++)
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
return lastIndex - 1;
}
static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++)
if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
}
static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length)
return TOKEN_NONE;
char c = json[index];
index++;
switch (c)
{
case '{':
return TOKEN_CURLY_OPEN;
case '}':
return TOKEN_CURLY_CLOSE;
case '[':
return TOKEN_SQUARED_OPEN;
case ']':
return TOKEN_SQUARED_CLOSE;
case ',':
return TOKEN_COMMA;
case '"':
return TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN_NUMBER;
case ':':
return TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
{
index += 5;
return TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
{
index += 4;
return TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
{
index += 4;
return TOKEN_NULL;
}
}
return TOKEN_NONE;
}
static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
{
bool success = true;
string stringValue = value as string;
if (stringValue != null)
success = SerializeString(stringValue, builder);
else
{
IDictionary<string, object> dict = value as IDictionary<string, object>;
if (dict != null)
{
success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);
}
else
{
IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;
if (stringDictionary != null)
{
success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);
}
else
{
IEnumerable enumerableValue = value as IEnumerable;
if (enumerableValue != null)
success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);
else if (IsNumeric(value))
success = SerializeNumber(value, builder);
else if (value is bool)
builder.Append((bool)value ? "true" : "false");
else if (value == null)
builder.Append("null");
else
{
object serializedObject;
success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);
if (success)
SerializeValue(jsonSerializerStrategy, serializedObject, builder);
}
}
}
}
return success;
}
static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
{
builder.Append("{");
IEnumerator ke = keys.GetEnumerator();
IEnumerator ve = values.GetEnumerator();
bool first = true;
while (ke.MoveNext() && ve.MoveNext())
{
object key = ke.Current;
object value = ve.Current;
if (!first)
builder.Append(",");
string stringKey = key as string;
if (stringKey != null)
SerializeString(stringKey, builder);
else
if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
builder.Append(":");
if (!SerializeValue(jsonSerializerStrategy, value, builder))
return false;
first = false;
}
builder.Append("}");
return true;
}
static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
foreach (object value in anArray)
{
if (!first)
builder.Append(",");
if (!SerializeValue(jsonSerializerStrategy, value, builder))
return false;
first = false;
}
builder.Append("]");
return true;
}
static bool SerializeString(string aString, StringBuilder builder)
{
// Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)
if (aString.IndexOfAny(EscapeCharacters) == -1)
{
builder.Append('"');
builder.Append(aString);
builder.Append('"');
return true;
}
builder.Append('"');
int safeCharacterCount = 0;
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
char c = charArray[i];
// Non ascii characters are fine, buffer them up and send them to the builder
// in larger chunks if possible. The escape table is a 1:1 translation table
// with \0 [default(char)] denoting a safe character.
if (c >= EscapeTable.Length || EscapeTable[c] == default(char))
{
safeCharacterCount++;
}
else
{
if (safeCharacterCount > 0)
{
builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);
safeCharacterCount = 0;
}
builder.Append('\\');
builder.Append(EscapeTable[c]);
}
}
if (safeCharacterCount > 0)
{
builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);
}
builder.Append('"');
return true;
}
static bool SerializeNumber(object number, StringBuilder builder)
{
if (number is long)
builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
else if (number is ulong)
builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
else if (number is int)
builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
else if (number is uint)
builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
else if (number is decimal)
builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
else if (number is float)
builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
else
builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
return true;
}
/// <summary>
/// Determines if a given object is numeric in any way
/// (can be integer, double, null, etc).
/// </summary>
static bool IsNumeric(object value)
{
if (value is sbyte) return true;
if (value is byte) return true;
if (value is short) return true;
if (value is ushort) return true;
if (value is int) return true;
if (value is uint) return true;
if (value is long) return true;
if (value is ulong) return true;
if (value is float) return true;
if (value is double) return true;
if (value is decimal) return true;
return false;
}
private static IJsonSerializerStrategy _currentJsonSerializerStrategy;
public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
{
get
{
return _currentJsonSerializerStrategy ??
(_currentJsonSerializerStrategy =
#if SIMPLE_JSON_DATACONTRACT
DataContractJsonSerializerStrategy
#else
PocoJsonSerializerStrategy
#endif
);
}
set
{
_currentJsonSerializerStrategy = value;
}
}
private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy
{
get
{
return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());
}
}
#if SIMPLE_JSON_DATACONTRACT
private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
{
get
{
return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
}
}
#endif
}
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
interface IJsonSerializerStrategy
{
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
bool TrySerializeNonPrimitiveObject(object input, out object output);
object DeserializeObject(object value, Type type);
}
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
class PocoJsonSerializerStrategy : IJsonSerializerStrategy
{
internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;
internal IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;
internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;
internal static readonly Type[] EmptyTypes = new Type[0];
internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };
private static readonly string[] Iso8601Format = new string[]
{
@"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
@"yyyy-MM-dd\THH:mm:ssK"
};
public PocoJsonSerializerStrategy()
{
ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);
GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
}
protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
{
return clrPropertyName;
}
internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)
{
return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);
}
internal virtual IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
{
IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanRead)
{
MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
if (getMethod.IsStatic || !getMethod.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = ReflectionUtils.GetGetMethod(propertyInfo);
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (fieldInfo.IsStatic || !fieldInfo.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = ReflectionUtils.GetGetMethod(fieldInfo);
}
return result;
}
internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
{
IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanWrite)
{
MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
if (setMethod.IsStatic || !setMethod.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic)
continue;
result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
}
return result;
}
public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)
{
return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public virtual object DeserializeObject(object value, Type type)
{
if (type == null) throw new ArgumentNullException("type");
string str = value as string;
if (type == typeof(Guid) && string.IsNullOrEmpty(str))
return default(Guid);
if (value == null)
return null;
object obj = null;
if (str != null)
{
if (str.Length != 0) // We know it can't be null now.
{
if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))
return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))
return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))
return new Guid(str);
if (type == typeof(Uri))
{
bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute);
Uri result;
if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result))
return result;
return null;
}
if (type == typeof(string))
return str;
return Convert.ChangeType(str, type, CultureInfo.InvariantCulture);
}
else
{
if (type == typeof(Guid))
obj = default(Guid);
else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
obj = null;
else
obj = str;
}
// Empty string case
if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))
return str;
}
else if (value is bool)
return value;
bool valueIsLong = value is long;
bool valueIsDouble = value is double;
if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double)))
return value;
if ((valueIsDouble && type != typeof(double)) || (valueIsLong && type != typeof(long)))
{
obj = type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(float) || type == typeof(bool) || type == typeof(decimal) || type == typeof(byte) || type == typeof(short)
? Convert.ChangeType(value, type, CultureInfo.InvariantCulture)
: value;
}
else
{
IDictionary<string, object> objects = value as IDictionary<string, object>;
if (objects != null)
{
IDictionary<string, object> jsonObject = objects;
if (ReflectionUtils.IsTypeDictionary(type))
{
// if dictionary then
Type[] types = ReflectionUtils.GetGenericTypeArguments(type);
Type keyType = types[0];
Type valueType = types[1];
Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);
IDictionary dict = (IDictionary)ConstructorCache[genericType]();
foreach (KeyValuePair<string, object> kvp in jsonObject)
dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));
obj = dict;
}
else
{
if (type == typeof(object))
obj = value;
else
{
obj = ConstructorCache[type]();
foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type])
{
object jsonValue;
if (jsonObject.TryGetValue(setter.Key, out jsonValue))
{
jsonValue = DeserializeObject(jsonValue, setter.Value.Key);
setter.Value.Value(obj, jsonValue);
}
}
}
}
}
else
{
IList<object> valueAsList = value as IList<object>;
if (valueAsList != null)
{
IList<object> jsonObject = valueAsList;
IList list = null;
if (type.IsArray)
{
list = (IList)ConstructorCache[type](jsonObject.Count);
int i = 0;
foreach (object o in jsonObject)
list[i++] = DeserializeObject(o, type.GetElementType());
}
else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type))
{
Type innerType = ReflectionUtils.GetGenericListElementType(type);
list = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count);
foreach (object o in jsonObject)
list.Add(DeserializeObject(o, innerType));
}
obj = list;
}
}
return obj;
}
if (ReflectionUtils.IsNullableType(type))
return ReflectionUtils.ToNullableType(obj, type);
return obj;
}
protected virtual object SerializeEnum(Enum p)
{
return Convert.ToDouble(p, CultureInfo.InvariantCulture);
}
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
protected virtual bool TrySerializeKnownTypes(object input, out object output)
{
bool returnValue = true;
if (input is DateTime)
output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
else if (input is DateTimeOffset)
output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
else if (input is Guid)
output = ((Guid)input).ToString("D");
else if (input is Uri)
output = input.ToString();
else
{
Enum inputEnum = input as Enum;
if (inputEnum != null)
output = SerializeEnum(inputEnum);
else
{
returnValue = false;
output = null;
}
}
return returnValue;
}
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")]
protected virtual bool TrySerializeUnknownTypes(object input, out object output)
{
if (input == null) throw new ArgumentNullException("input");
output = null;
Type type = input.GetType();
if (type.FullName == null)
return false;
IDictionary<string, object> obj = new JsonObject();
IDictionary<string, ReflectionUtils.GetDelegate> getters = GetCache[type];
foreach (KeyValuePair<string, ReflectionUtils.GetDelegate> getter in getters)
{
if (getter.Value != null)
obj.Add(MapClrMemberNameToJsonFieldName(getter.Key), getter.Value(input));
}
output = obj;
return true;
}
}
#if SIMPLE_JSON_DATACONTRACT
[GeneratedCode("simple-json", "1.0.0")]
#if SIMPLE_JSON_INTERNAL
internal
#else
public
#endif
class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
{
public DataContractJsonSerializerStrategy()
{
GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
}
internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
{
bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
if (!hasDataContract)
return base.GetterValueFactory(type);
string jsonKey;
IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanRead)
{
MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);
}
return result;
}
internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
{
bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
if (!hasDataContract)
return base.SetterValueFactory(type);
string jsonKey;
IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
{
if (propertyInfo.CanWrite)
{
MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
}
}
foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
{
if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
}
// todo implement sorting for DATACONTRACT.
return result;
}
private static bool CanAdd(MemberInfo info, out string jsonKey)
{
jsonKey = null;
if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
return false;
DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
if (dataMemberAttribute == null)
return false;
jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
return true;
}
}
#endif
namespace Reflection
{
// This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules
// that might be in place in the target project.
[GeneratedCode("reflection-utils", "1.0.0")]
#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC
public
#else
internal
#endif
class ReflectionUtils
{
private static readonly object[] EmptyObjects = new object[] { };
public delegate object GetDelegate(object source);
public delegate void SetDelegate(object source, object value);
public delegate object ConstructorDelegate(params object[] args);
public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);
#if SIMPLE_JSON_TYPEINFO
public static TypeInfo GetTypeInfo(Type type)
{
return type.GetTypeInfo();
}
#else
public static Type GetTypeInfo(Type type)
{
return type;
}
#endif
public static Attribute GetAttribute(MemberInfo info, Type type)
{
#if SIMPLE_JSON_TYPEINFO
if (info == null || type == null || !info.IsDefined(type))
return null;
return info.GetCustomAttribute(type);
#else
if (info == null || type == null || !Attribute.IsDefined(info, type))
return null;
return Attribute.GetCustomAttribute(info, type);
#endif
}
public static Type GetGenericListElementType(Type type)
{
IEnumerable<Type> interfaces;
#if SIMPLE_JSON_TYPEINFO
interfaces = type.GetTypeInfo().ImplementedInterfaces;
#else
interfaces = type.GetInterfaces();
#endif
foreach (Type implementedInterface in interfaces)
{
if (IsTypeGeneric(implementedInterface) &&
implementedInterface.GetGenericTypeDefinition() == typeof(IList<>))
{
return GetGenericTypeArguments(implementedInterface)[0];
}
}
return GetGenericTypeArguments(type)[0];
}
public static Attribute GetAttribute(Type objectType, Type attributeType)
{
#if SIMPLE_JSON_TYPEINFO
if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
return null;
return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
#else
if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))
return null;
return Attribute.GetCustomAttribute(objectType, attributeType);
#endif
}
public static Type[] GetGenericTypeArguments(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static bool IsTypeGeneric(Type type)
{
return GetTypeInfo(type).IsGenericType;
}
public static bool IsTypeGenericeCollectionInterface(Type type)
{
if (!IsTypeGeneric(type))
return false;
Type genericDefinition = type.GetGenericTypeDefinition();
return (genericDefinition == typeof(IList<>)
|| genericDefinition == typeof(ICollection<>)
|| genericDefinition == typeof(IEnumerable<>)
#if SIMPLE_JSON_READONLY_COLLECTIONS
|| genericDefinition == typeof(IReadOnlyCollection<>)
|| genericDefinition == typeof(IReadOnlyList<>)
#endif
);
}
public static bool IsAssignableFrom(Type type1, Type type2)
{
return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));
}
public static bool IsTypeDictionary(Type type)
{
#if SIMPLE_JSON_TYPEINFO
if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
return true;
#else
if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))
return true;
#endif
if (!GetTypeInfo(type).IsGenericType)
return false;
Type genericDefinition = type.GetGenericTypeDefinition();
return genericDefinition == typeof(IDictionary<,>);
}
public static bool IsNullableType(Type type)
{
return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static object ToNullableType(object obj, Type nullableType)
{
return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);
}
public static bool IsValueType(Type type)
{
return GetTypeInfo(type).IsValueType;
}
public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().DeclaredConstructors;
#else
return type.GetConstructors();
#endif
}
public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)
{
IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);
int i;
bool matches;
foreach (ConstructorInfo constructorInfo in constructorInfos)
{
ParameterInfo[] parameters = constructorInfo.GetParameters();
if (argsType.Length != parameters.Length)
continue;
i = 0;
matches = true;
foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())
{
if (parameterInfo.ParameterType != argsType[i])
{
matches = false;
break;
}
}
if (matches)
return constructorInfo;
}
return null;
}
public static IEnumerable<PropertyInfo> GetProperties(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetRuntimeProperties();
#else
return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
public static IEnumerable<FieldInfo> GetFields(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetRuntimeFields();
#else
return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.GetMethod;
#else
return propertyInfo.GetGetMethod(true);
#endif
}
public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.SetMethod;
#else
return propertyInfo.GetSetMethod(true);
#endif
}
public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetConstructorByReflection(constructorInfo);
#else
return GetConstructorByExpression(constructorInfo);
#endif
}
public static ConstructorDelegate GetContructor(Type type, params Type[] argsType)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetConstructorByReflection(type, argsType);
#else
return GetConstructorByExpression(type, argsType);
#endif
}
public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)
{
return delegate (object[] args) { return constructorInfo.Invoke(args); };
}
public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)
{
ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);
}
#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo)
{
ParameterInfo[] paramsInfo = constructorInfo.GetParameters();
ParameterExpression param = Expression.Parameter(typeof(object[]), "args");
Expression[] argsExp = new Expression[paramsInfo.Length];
for (int i = 0; i < paramsInfo.Length; i++)
{
Expression index = Expression.Constant(i);
Type paramType = paramsInfo[i].ParameterType;
Expression paramAccessorExp = Expression.ArrayIndex(param, index);
Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);
argsExp[i] = paramCastExp;
}
NewExpression newExp = Expression.New(constructorInfo, argsExp);
Expression<Func<object[], object>> lambda = Expression.Lambda<Func<object[], object>>(newExp, param);
Func<object[], object> compiledLambda = lambda.Compile();
return delegate (object[] args) { return compiledLambda(args); };
}
public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType)
{
ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);
return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo);
}
#endif
public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetGetMethodByReflection(propertyInfo);
#else
return GetGetMethodByExpression(propertyInfo);
#endif
}
public static GetDelegate GetGetMethod(FieldInfo fieldInfo)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetGetMethodByReflection(fieldInfo);
#else
return GetGetMethodByExpression(fieldInfo);
#endif
}
public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);
return delegate (object source) { return methodInfo.Invoke(source, EmptyObjects); };
}
public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source) { return fieldInfo.GetValue(source); };
}
#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo)
{
MethodInfo getMethodInfo = GetGetterMethodInfo(propertyInfo);
ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);
Func<object, object> compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile();
return delegate (object source) { return compiled(source); };
}
public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo)
{
ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
MemberExpression member = Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo);
GetDelegate compiled = Expression.Lambda<GetDelegate>(Expression.Convert(member, typeof(object)), instance).Compile();
return delegate (object source) { return compiled(source); };
}
#endif
public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetSetMethodByReflection(propertyInfo);
#else
return GetSetMethodByExpression(propertyInfo);
#endif
}
public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
{
#if SIMPLE_JSON_NO_LINQ_EXPRESSION
return GetSetMethodByReflection(fieldInfo);
#else
return GetSetMethodByExpression(fieldInfo);
#endif
}
public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);
return delegate (object source, object value) { methodInfo.Invoke(source, new object[] { value }); };
}
public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source, object value) { fieldInfo.SetValue(source, value); };
}
#if !SIMPLE_JSON_NO_LINQ_EXPRESSION
public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo)
{
MethodInfo setMethodInfo = GetSetterMethodInfo(propertyInfo);
ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
ParameterExpression value = Expression.Parameter(typeof(object), "value");
UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);
UnaryExpression valueCast = (!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType);
Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, setMethodInfo, valueCast), new ParameterExpression[] { instance, value }).Compile();
return delegate (object source, object val) { compiled(source, val); };
}
public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo)
{
ParameterExpression instance = Expression.Parameter(typeof(object), "instance");
ParameterExpression value = Expression.Parameter(typeof(object), "value");
Action<object, object> compiled = Expression.Lambda<Action<object, object>>(
Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile();
return delegate (object source, object val) { compiled(source, val); };
}
public static BinaryExpression Assign(Expression left, Expression right)
{
#if SIMPLE_JSON_TYPEINFO
return Expression.Assign(left, right);
#else
MethodInfo assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod("Assign");
BinaryExpression assignExpr = Expression.Add(left, right, assign);
return assignExpr;
#endif
}
private static class Assigner<T>
{
public static T Assign(ref T left, T right)
{
return (left = right);
}
}
#endif
public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly object _lock = new object();
private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;
private Dictionary<TKey, TValue> _dictionary;
public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)
{
_valueFactory = valueFactory;
}
private TValue Get(TKey key)
{
if (_dictionary == null)
return AddValue(key);
TValue value;
if (!_dictionary.TryGetValue(key, out value))
return AddValue(key);
return value;
}
private TValue AddValue(TKey key)
{
TValue value = _valueFactory(key);
lock (_lock)
{
if (_dictionary == null)
{
_dictionary = new Dictionary<TKey, TValue>();
_dictionary[key] = value;
}
else
{
TValue val;
if (_dictionary.TryGetValue(key, out val))
return val;
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(_dictionary);
dict[key] = value;
_dictionary = dict;
}
}
return value;
}
public void Add(TKey key, TValue value)
{
throw new NotImplementedException();
}
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
public ICollection<TKey> Keys
{
get { return _dictionary.Keys; }
}
public bool Remove(TKey key)
{
throw new NotImplementedException();
}
public bool TryGetValue(TKey key, out TValue value)
{
value = this[key];
return true;
}
public ICollection<TValue> Values
{
get { return _dictionary.Values; }
}
public TValue this[TKey key]
{
get { return Get(key); }
set { throw new NotImplementedException(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return _dictionary.Count; }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
}
}
}
}
// ReSharper restore LoopCanBeConvertedToQuery
// ReSharper restore RedundantExplicitArrayCreation
// ReSharper restore SuggestUseVarKeywordEvident | 40.947048 | 621 | 0.540381 | [
"MIT"
] | andrevctr12/Mimic-macOS | conduit.macOS/Util/SimpleJson.cs | 87,381 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents initializing members of a member of a newly created object.
/// </summary>
/// <remarks>
/// Use the <see cref="Expression.MemberBind(MemberInfo, MemberBinding[])"/> factory methods to create a <see cref="MemberMemberBinding"/>.
/// The value of the <see cref="MemberBinding.BindingType"/> property of a <see cref="MemberMemberBinding"/> object is <see cref="MemberBinding"/>.
/// </remarks>
public sealed class MemberMemberBinding : MemberBinding
{
internal MemberMemberBinding(MemberInfo member, ReadOnlyCollection<MemberBinding> bindings)
#pragma warning disable 618
: base(MemberBindingType.MemberBinding, member)
{
#pragma warning restore 618
Bindings = bindings;
}
/// <summary>
/// Gets the bindings that describe how to initialize the members of a member.
/// </summary>
public ReadOnlyCollection<MemberBinding> Bindings { get; }
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="bindings">The <see cref="Bindings"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public MemberMemberBinding Update(IEnumerable<MemberBinding> bindings)
{
if (bindings != null)
{
if (ExpressionUtils.SameElements(ref bindings!, Bindings))
{
return this;
}
}
return Expression.MemberBind(Member, bindings!);
}
internal override void ValidateAsDefinedHere(int index)
{
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a field or property.
/// </summary>
/// <param name="member">The <see cref="MemberInfo"/> to set the <see cref="MemberBinding.Member"/> property equal to.</param>
/// <param name="bindings">An array of <see cref="MemberBinding"/> objects to use to populate the <see cref="MemberMemberBinding.Bindings"/> collection.</param>
/// <returns>A <see cref="MemberMemberBinding"/> that has the <see cref="MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/> and the <see cref="MemberBinding.Member"/> and <see cref="MemberMemberBinding.Bindings"/> properties set to the specified values.</returns>
public static MemberMemberBinding MemberBind(MemberInfo member, params MemberBinding[] bindings)
{
return MemberBind(member, (IEnumerable<MemberBinding>)bindings);
}
/// <summary>
/// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a field or property.
/// </summary>
/// <param name="member">The <see cref="MemberInfo"/> to set the <see cref="MemberBinding.Member"/> property equal to.</param>
/// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="MemberMemberBinding.Bindings"/> collection.</param>
/// <returns>A <see cref="MemberMemberBinding"/> that has the <see cref="MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/> and the <see cref="MemberBinding.Member"/> and <see cref="MemberMemberBinding.Bindings"/> properties set to the specified values.</returns>
public static MemberMemberBinding MemberBind(MemberInfo member, IEnumerable<MemberBinding> bindings)
{
ContractUtils.RequiresNotNull(member, nameof(member));
ContractUtils.RequiresNotNull(bindings, nameof(bindings));
ReadOnlyCollection<MemberBinding> roBindings = bindings.ToReadOnly();
Type memberType;
ValidateGettableFieldOrPropertyMember(member, out memberType);
ValidateMemberInitArgs(memberType, roBindings);
return new MemberMemberBinding(member, roBindings);
}
/// <summary>
/// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a member that is accessed by using a property accessor method.
/// </summary>
/// <param name="propertyAccessor">The <see cref="MemberInfo"/> that represents a property accessor method.</param>
/// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="MemberMemberBinding.Bindings"/> collection.</param>
/// <returns>
/// A <see cref="MemberMemberBinding"/> that has the <see cref="MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/>,
/// the Member property set to the <see cref="PropertyInfo"/> that represents the property accessed in <paramref name="propertyAccessor"/>,
/// and <see cref="MemberMemberBinding.Bindings"/> properties set to the specified values.
/// </returns>
public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, params MemberBinding[] bindings)
{
return MemberBind(propertyAccessor, (IEnumerable<MemberBinding>)bindings);
}
/// <summary>
/// Creates a <see cref="MemberMemberBinding"/> that represents the recursive initialization of members of a member that is accessed by using a property accessor method.
/// </summary>
/// <param name="propertyAccessor">The <see cref="MemberInfo"/> that represents a property accessor method.</param>
/// <param name="bindings">An <see cref="IEnumerable{T}"/> that contains <see cref="MemberBinding"/> objects to use to populate the <see cref="MemberMemberBinding.Bindings"/> collection.</param>
/// <returns>
/// A <see cref="MemberMemberBinding"/> that has the <see cref="MemberBinding.BindingType"/> property equal to <see cref="MemberBinding"/>,
/// the Member property set to the <see cref="PropertyInfo"/> that represents the property accessed in <paramref name="propertyAccessor"/>,
/// and <see cref="MemberMemberBinding.Bindings"/> properties set to the specified values.
/// </returns>
public static MemberMemberBinding MemberBind(MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings)
{
ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor));
return MemberBind(GetProperty(propertyAccessor, nameof(propertyAccessor)), bindings);
}
private static void ValidateGettableFieldOrPropertyMember(MemberInfo member, out Type memberType)
{
Type? decType = member.DeclaringType;
if (decType == null)
{
throw Error.NotAMemberOfAnyType(member, nameof(member));
}
// Null paramName as there are several paths here with different parameter names at the API
TypeUtils.ValidateType(decType, null, allowByRef: true, allowPointer: true);
switch (member)
{
case PropertyInfo pi:
if (!pi.CanRead)
{
throw Error.PropertyDoesNotHaveGetter(pi, nameof(member));
}
memberType = pi.PropertyType;
break;
case FieldInfo fi:
memberType = fi.FieldType;
break;
default:
throw Error.ArgumentMustBeFieldInfoOrPropertyInfo(nameof(member));
}
}
private static void ValidateMemberInitArgs(Type type, ReadOnlyCollection<MemberBinding> bindings)
{
for (int i = 0, n = bindings.Count; i < n; i++)
{
MemberBinding b = bindings[i];
ContractUtils.RequiresNotNull(b, nameof(bindings));
b.ValidateAsDefinedHere(i);
if (!b.Member.DeclaringType!.IsAssignableFrom(type))
{
throw Error.NotAMemberOfType(b.Member.Name, type, nameof(bindings), i);
}
}
}
}
}
| 53.327273 | 295 | 0.645301 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/MemberMemberBinding.cs | 8,799 | C# |
namespace Acklann.Plaid.Transactions
{
/// <summary>
/// Represents a request for plaid's '/transactions/refresh' endpoint.
/// </summary>
/// <remarks>/transactions/refresh is an optional endpoint for users of the Transactions product. It initiates an on-demand extraction to fetch the newest transactions for an Item. This on-demand extraction takes place in addition to the periodic extractions that automatically occur multiple times a day for any Transactions-enabled Item. If changes to transactions are discovered after calling /transactions/refresh, Plaid will fire a webhook: TRANSACTIONS_REMOVED will be fired if any removed transactions are detected, and DEFAULT_UPDATE will be fired if any new transactions are detected. New transactions can be fetched by calling /transactions/get.</remarks>
/// <seealso cref="Acklann.Plaid.AuthorizedRequestBase" />
public class RefreshTransactionRequest : AuthorizedRequestBase
{
}
}
| 78.416667 | 666 | 0.800213 | [
"MIT"
] | Ackara/Plaid.NET | src/Plaid/Transactions/RefreshTransactionRequest.cs | 941 | C# |
using System;
using System.Linq;
using System.IO;
using System.IO.Compression;
using System.Threading;
namespace MysticMind.PostgresEmbed
{
using System.Collections.Generic;
internal class PgExtension
{
private const string PSQL_EXE = "psql.exe";
private string _pgVersion;
private string _pgHost;
private int _pgPort;
private string _pgUser;
private string _pgDbName;
private string _binariesDir;
private string _pgDir;
private PgExtensionConfig _config;
private string _filename;
public PgExtension(
string pgVersion,
string pghost,
int pgPort,
string pgUser,
string pgDbName,
string binariesDir,
string pgDir,
PgExtensionConfig config)
{
_pgVersion = pgVersion;
_pgHost = pghost;
_pgPort = pgPort;
_pgUser = pgUser;
_pgDbName = pgDbName;
_binariesDir = binariesDir;
_pgDir = pgDir;
_config = config;
_filename = Path.GetFileName(_config.DownloadUrl);
}
public string Download()
{
var zipFile = Path.Combine(_binariesDir, _filename);
// check if zip file exists in the destination folder
// return the file path and don't require to download again
if (File.Exists(zipFile))
{
return zipFile;
}
var progress = new System.Progress<double>();
progress.ProgressChanged += (sender, value) => Console.WriteLine("\r %{0:N0}", value);
try
{
// download the file
var cs = new CancellationTokenSource();
Utils.DownloadAsync(_config.DownloadUrl, zipFile, progress, cs.Token).Wait();
}
catch (Exception ex)
{
throw new Exception($"Failed to download {_config.DownloadUrl}", ex);
}
return zipFile;
}
public void Extract()
{
var zipFile = Path.Combine(_binariesDir, _filename);
// some extensions such as plv8 hs a container folder
// when we extract the binary archive, it get extracted with the container folder
// we want the contents without the container folder for the extensions to install properly
var containerFolderInBinary = GetContainerFolderInBinary(zipFile);
var ignoreRootFolder = !string.IsNullOrEmpty(containerFolderInBinary);
Utils.ExtractZipFolder(zipFile, _pgDir, containerFolderInBinary, ignoreRootFolder);
}
public void CreateExtension()
{
// create a single sql command with semicolon seperators
var sql = string.Join(";", _config.CreateExtensionSqlList);
var args = new List<string>();
// add host
args.Add($"-h {_pgHost}");
// add port
args.Add($"-p {_pgPort}");
// add user
args.Add($"-U {_pgUser}");
// add database name
args.Add($"-d {this._pgDbName}");
// add command
args.Add($"-c \"{sql}\"");
var filename = Path.Combine(_pgDir, "bin", PSQL_EXE);
try
{
var result = Utils.RunProcess(filename, args);
if (result.ExitCode != 0)
{
throw new Exception($"'{sql}' execution returned an error code {result.ExitCode} {result.Output} {result.Error}");
}
}
catch (Exception ex)
{
throw new Exception($"Exception occurred while executing '{sql}'", ex);
}
}
private string GetContainerFolderInBinary(string zipFile)
{
//some of the extension binaries may have a root folder which need to be ignored while extracting content
string containerFolder = "";
using (var archive = ZipFile.OpenRead(zipFile))
{
var result = from entry in archive.Entries
where entry.FullName.EndsWith("/bin/") ||
entry.FullName.EndsWith("/lib/") ||
entry.FullName.EndsWith("/share/")
select entry;
var item = result.FirstOrDefault();
if (item != null)
{
var parts = item.FullName.Split('/');
if (parts.Length > 1)
{
containerFolder = parts[0];
}
}
}
return containerFolder;
}
}
}
| 29.391566 | 134 | 0.521008 | [
"MIT"
] | colinbreame/mysticmind-postgresembed | src/MysticMind.PostgresEmbed/PgExtension.cs | 4,881 | C# |
using System;
namespace BinaryMultiplicator
{
public class MultiplicationMethod2xII : MultiplicationMethodII
{
private MultiplicationMethod2xII() : base(2) {}
public static MultiplicationMethod2xII Singleton { get; } = new MultiplicationMethod2xII();
}
} | 28.4 | 99 | 0.728873 | [
"MIT"
] | Misha135n2/BinaryMultiplicator | BinaryMultiplicator/MultiplicationMethod2xII.cs | 286 | C# |
namespace MetroService.SaasService.Application.Contracts
{
public static class SaasServiceRemoteServiceConsts
{
public const string RemoteServiceName = "SaasService";
}
} | 27.285714 | 62 | 0.753927 | [
"MIT"
] | MetroOffice/MetroOffice.SaasService | src/MetroService.SaasService.Application.Contracts/SaasServiceRemoteServiceConsts.cs | 193 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.