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 Abp.Domain.Entities; namespace Abp.Zero.SampleApp.TPH { public abstract class Person : Entity { public string Name { get; set; } } public abstract class PersonWithIdCard : Person { public string IdCard { get; set; } } public abstract class PersonWithIdCardAndAddress : PersonWithIdCard { public string Address { get; set; } } }
20.894737
71
0.639798
[ "MIT" ]
861191244/aspnetboilerplate
test/Abp.Zero.SampleApp/TPH/Person.cs
399
C#
using Godot; public class SoldierState : NPCState { public SoldierState(Soldier node) : base(node) { speed = Stat.Speed(115); health = Stat.Health(1000); damage = Stat.Damage(100); range = Stat.Range(50); } }
16.0625
50
0.583658
[ "MIT" ]
MickSheridan24/Godot_Project
src/StateManagement/NPCs/SoldierState.cs
257
C#
namespace ARVR { /// <summary> /// Used in a ScriptableObject to indicate the type of the item about which the SO is storing information /// </summary> /// <see cref="Objects.BaseObjectData"/> public enum ItemType : sbyte { Building, Equipment, Food, Medicine, NPC, Player, Story, Weapon } }
29.818182
109
0.643293
[ "MIT" ]
nmcguinness/arvr_1_getting_started_unity
getting_started/Assets/ARVR/Common/Scripts/Enums/ItemType.cs
330
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; namespace IdentityServer4.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<Guid>(nullable: false), CreatedDate = table.Column<DateTimeOffset>(nullable: false), CreatedBy = table.Column<string>(maxLength: 64, nullable: false), ModifiedDate = table.Column<DateTimeOffset>(nullable: true), ModifiedBy = table.Column<string>(maxLength: 64, nullable: true), IsActive = table.Column<bool>(type: "bit", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false), DeletedDate = table.Column<DateTimeOffset>(nullable: true), DeleteBy = table.Column<string>(maxLength: 64, nullable: true), Username = table.Column<string>(nullable: false), Password = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: true), GivenName = table.Column<string>(nullable: true), FamilyName = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: false), EmailVerified = table.Column<bool>(type: "bit", nullable: false), WebSite = table.Column<string>(nullable: true), Address = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { } } }
44.155556
85
0.543533
[ "Apache-2.0" ]
felixsiburian/muju-identity-server
src/Migrations/20200325132858_initial.cs
1,987
C#
using System; using System.Text; using System.Web; using System.Web.Http.Description; namespace MyLOB.Mvc.Areas.HelpPage { public static class ApiDescriptionExtensions { /// <summary> /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" /// </summary> /// <param name="description">The <see cref="ApiDescription"/>.</param> /// <returns>The ID as a string.</returns> public static string GetFriendlyId(this ApiDescription description) { string path = description.RelativePath; string[] urlParts = path.Split('?'); string localPath = urlParts[0]; string queryKeyString = null; if (urlParts.Length > 1) { string query = urlParts[1]; string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; queryKeyString = String.Join("_", queryKeys); } StringBuilder friendlyPath = new StringBuilder(); friendlyPath.AppendFormat("{0}-{1}", description.HttpMethod.Method, localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); if (queryKeyString != null) { friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); } return friendlyPath.ToString(); } } }
39.410256
145
0.556929
[ "MIT" ]
EasyLOB/EasyLOB-MyLOB-NuGet-3
MyLOB.Mvc/Areas/HelpPage/ApiDescriptionExtensions.cs
1,537
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Text; namespace ClearCanvas.Enterprise.Core { /// <summary> /// Indicates that an entity's version has changed, and does not match the requested version /// </summary> public class EntityVersionException : PersistenceException { public EntityVersionException(object oid, Exception inner) : base(string.Format(SR.ExceptionEntityVersion, oid), inner) { } } }
44.081633
97
0.720833
[ "Apache-2.0" ]
econmed/ImageServer20
Enterprise/Core/EntityVersionException.cs
2,162
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Alidns20150109.Models { public class DescribeDomainsRequest : TeaModel { [NameInMap("Lang")] [Validation(Required=false)] public string Lang { get; set; } [NameInMap("KeyWord")] [Validation(Required=false)] public string KeyWord { get; set; } [NameInMap("GroupId")] [Validation(Required=false)] public string GroupId { get; set; } [NameInMap("PageNumber")] [Validation(Required=false)] public long PageNumber { get; set; } [NameInMap("PageSize")] [Validation(Required=false)] public long PageSize { get; set; } [NameInMap("SearchMode")] [Validation(Required=false)] public string SearchMode { get; set; } [NameInMap("ResourceGroupId")] [Validation(Required=false)] public string ResourceGroupId { get; set; } [NameInMap("Starmark")] [Validation(Required=false)] public bool? Starmark { get; set; } } }
24.93617
54
0.611775
[ "Apache-2.0" ]
alibabacloud-sdk-swift/alibabacloud-sdk
alidns-20150109/csharp/core/Models/DescribeDomainsRequest.cs
1,172
C#
using System.Collections; using System.Collections.Generic; using NaughtyAttributes; using UnityEngine; public class Cost : MonoBehaviour { private static Cost _instance; public static Cost Instance => _instance; [BoxGroup("Settlement Required Resources - Gold")] public int goldHamlet, goldVillage, goldTown, goldCity; [BoxGroup("Settlement Required Resources - Wood")] public int woodHamlet, woodVillage, woodTown, woodCity; [BoxGroup("Settlement Required Resources - Grain")] public int grainHamlet, grainVillage, grainTown, grainCity; [BoxGroup("Settlement Required Resources - Sheep")] public int sheepHamlet, sheepVillage, sheepTown, sheepCity; [BoxGroup("Settlement Required Resources - Stone")] public int stoneHamlet, stoneVillage, stoneTown, stoneCity; [BoxGroup("Stronghold Required Resources - Gold")] public int goldOutpost, goldCastle; [BoxGroup("Stronghold Required Resources - Wood")] public int woodOutpost, woodCastle; [BoxGroup("Stronghold Required Resources - Grain")] public int grainOutpost, grainCastle; [BoxGroup("Stronghold Required Resources - Sheep")] public int sheepOutpost, sheepCastle; [BoxGroup("Stronghold Required Resources - Stone")] public int stoneOutpost, stoneCastle; [BoxGroup("Stronghold Gold Upkeep")] public int outpostGoldUpkeep, castleGoldUpkeep; [BoxGroup("Divider")] [HorizontalLine(color: EColor.Green)] [SerializeField] private string divide = "Divider"; [BoxGroup("Settler")] public int goldSettler, goldSettlerMultiplier, woodSettler, grainSettler, sheepSettler, stoneSettler, horseSettler; [BoxGroup("Villager")] public int goldVillager, woodVillager, grainVillager, sheepVillager, stoneVillager, horseVillager; [BoxGroup("Pikeman")] public int goldPikeman, woodPikeman, grainPikeman, sheepPikeman, stonePikeman, horsePikeman; [BoxGroup("Archer")] public int goldArcher, woodArcher, grainArcher, sheepArcher, stoneArcher, horseArcher; [BoxGroup("Footman")] public int goldFootman, woodFootman, grainFootman, sheepFootman, stoneFootman, horseFootman; [BoxGroup("Hussar")] public int goldHussar, woodHussar, grainHussar, sheepHussar, stoneHussar, horseHussar; [BoxGroup("Knight")] public int goldKnight, woodKnight, grainKnight, sheepKnight, stoneKnight, horseKnight; [BoxGroup("Armoured Archer")] public int goldArmouredArcher, woodArmouredArcher, grainArmouredArcher, sheepArmouredArcher, stoneArmouredArcher, horseArmouredArcher; [BoxGroup("Mounted Knight")] public int goldMountedKnight, woodMountedKnight, grainMountedKnight, sheepMountedKnight, stoneMountedKnight, horseMountedKnight; [BoxGroup("Paladin")] public int goldPaladin, woodPaladin, grainPaladin, sheepPaladin, stonePaladin, horsePaladin; [BoxGroup("Mounted Paladin")] public int goldMountedPaladin, woodMountedPaladin, grainMountedPaladin, sheepMountedPaladin, stoneMountedPaladin, horseMountedPaladin; [BoxGroup("King")] public int goldKing, woodKing, grainKing, sheepKing, stoneKing, horseKing; [BoxGroup("Worker")] public int goldWorker, woodWorker, grainWorker, sheepWorker, stoneWorker, horseWorker; [BoxGroup("Divider Upgrades")] [HorizontalLine(color: EColor.Green)] [SerializeField] private string divideUpgrade = "Divide Upgrades"; [BoxGroup("Upgrade Pikeman")] public int goldUpgradePikeman, woodUpgradePikeman, grainUpgradePikeman, sheepUpgradePikeman; [BoxGroup("Upgrade Archer")] public int goldUpgradeArcher, woodUpgradeArcher, grainUpgradeArcher, sheepUpgradeArcher; [BoxGroup("Upgrade Footman")] public int goldUpgradeFootman, woodUpgradeFootman, grainUpgradeFootman, sheepUpgradeFootman; [BoxGroup("Upgrade Hussar")] public int goldUpgradeHussar, woodUpgradeHussar, grainUpgradeHussar, sheepUpgradeHussar; [BoxGroup("Upgrade Knight")] public int goldUpgradeKnight, woodUpgradeKnight, grainUpgradeKnight, sheepUpgradeKnight; [BoxGroup("Upgrade Armoured Archer")] public int goldUpgradeArmouredArcher, woodUpgradeArmouredArcher, grainUpgradeArmouredArcher, sheepUpgradeArmouredArcher; [BoxGroup("Upgrade Mounted Knight")] public int goldUpgradeMountedKnight, woodUpgradeMountedKnight, grainUpgradeMountedKnight, sheepUpgradeMountedKnight; [BoxGroup("Divider Workshop Costs")] [HorizontalLine(color: EColor.Red)] [SerializeField] private string divideWorkshop = "Divide Workshops"; [BoxGroup("Farm")] public int goldFarm, woodFarm; [BoxGroup("Wood Camp")] public int goldLumberCamp, woodLumberCamp; [BoxGroup("Sheep Barn")] public int goldSheepBarn, woodSheepBarn; [BoxGroup("Quarry")] public int goldQuarry, woodQuarry; [BoxGroup("Stables")] public int goldStables, woodStables; [BoxGroup("Divider Market")] [HorizontalLine(color: EColor.Yellow)] [SerializeField] private string divideMarket = "Divide Market"; [BoxGroup("Market Buy")] public int buyWood, buyGrain, buySheep, buyStone; [BoxGroup("Market Sell")] public int sellWood, sellGrain, sellSheep, sellStone; [BoxGroup("Market Multiplier")] public int marketPricesMultiplier = 1; [BoxGroup("Market Fee Reduce Factor")] public int marketFeeReduceFactor = 0; //[HideInInspector] public int unitToSpawnGold, unitToSpawnWood, unitToSpawnGrain, unitToSpawnSheep, unitToSpawnStone, unitToSpawnHorse; private void Awake() { if (_instance == null) _instance = this; } public void UpdateMarketPriceFee() { marketFeeReduceFactor = 0; foreach (Dockyard dockyard in ObjectHolder.Instance.dockyards) { marketFeeReduceFactor++; } } }
34.376404
120
0.707305
[ "MIT" ]
Hir-o/Settlers-of-Albion-Project-Files
Assets/Scripts/Cost.cs
6,121
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI : MonoBehaviour { Text numMovimientosTxt; int numMovimientos; void Awake(){ numMovimientosTxt=GameObject.Find ("Movimientos").GetComponent (typeof(Text)) as Text ; } public void SumarMovimiento(){ numMovimientos += 1; numMovimientosTxt.text = "Movimientos: " + numMovimientos.ToString (); } }
21.45
89
0.750583
[ "MIT" ]
Danruc/Scape_to_Space
ScapeToSpace/Assets/Scripts/Level2/Quest2/Original/UI.cs
431
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.Staffing { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Related_Person_RelationshipObjectIDType : INotifyPropertyChanged { private string typeField; private string valueField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string type { get { return this.typeField; } set { this.typeField = value; this.RaisePropertyChanged("type"); } } [XmlText] public string Value { get { return this.valueField; } set { this.valueField = value; this.RaisePropertyChanged("Value"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
20.819672
136
0.729134
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Staffing/Related_Person_RelationshipObjectIDType.cs
1,270
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using TabSample.Toolbox; namespace TabSample.ViewModels { public class CarsViewModel : BaseViewModel { private List<CarViewModel> _items; public CarsViewModel() { var imageUrls = new[] { "http://media.caranddriver.com/images/media/51/2016-10best-cars-lead-photo-664005-s-original.jpg", "http://i2.cdn.turner.com/cnnnext/dam/assets/150918170501-frankfurt-motor-show-concept-cars-4-super-169.jpg", "https://www.enterprise.com/content/dam/global-vehicle-images/cars/FORD_FOCU_2012-1.png", "https://media.ed.edmunds-media.com/honda/civic/2016/oem/2016_honda_civic_sedan_touring_fq_oem_4_717.jpg", "https://www.enterprise.ca/content/dam/global-vehicle-images/cars/CHRY_200_2015.png", "http://pop.h-cdn.co/assets/cm/15/05/54cb1d27a519c_-_analog-sports-cars-01-1013-de.jpg" }; int i = 0; _items = imageUrls.Select(url => new CarViewModel("Car " + ++i, url)).ToList(); //SelectedItem = Cars.FirstOrDefault(); Test(); } public static string CarsProperty = "Cars"; private ObservableCollection<CarViewModel> _cars; public ObservableCollection<CarViewModel> Cars { get { return _cars; } set { _cars = value; RaisePropertyChanged(() => Cars); } } public static string SelectedItemProperty = "SelectedItem"; private CarViewModel _selectedItem; public CarViewModel SelectedItem { get { return _selectedItem; } set { _selectedItem = value; RaisePropertyChanged(() => SelectedItem); } } public static string TestActionProperty = "TestAction"; private string _testAction; public string TestAction { get { return _testAction; } set { _testAction = value; RaisePropertyChanged(() => TestAction); } } private async void Test() { TestAction = "Testing collection loading."; await Task.Delay(2000); var cars = new ObservableCollection<CarViewModel>(); cars.AddRange(_items); Cars = cars; SelectedItem = Cars.FirstOrDefault(); TestAction = "Testing item removing at index 2."; await Task.Delay(2000); Cars.RemoveAt(2); TestAction = "Testing item inserting at index 2."; await Task.Delay(2000); Cars.Insert(2, _items[2]); TestAction = "Testing item appending at end"; await Task.Delay(5000); Cars.Add(new CarViewModel("Car 6 added", _items[2].ImageUrl)); TestAction = "Testing item replacing at index 0"; await Task.Delay(5000); Cars[0] = new CarViewModel("Car 0 replaced", _items.Last().ImageUrl); TestAction = "Testing completed"; } } }
32.102804
125
0.543523
[ "MIT" ]
gagikkyurkchyan/xamarin-samples
TabSample/TabSample/TabSample/ViewModels/CarsViewModel.cs
3,437
C#
namespace SaaSFulfillmentClient { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using SaaSFulfillmentClient.AzureTable; using SaaSFulfillmentClient.Models; public interface IOperationsStore { Task<IEnumerable<OperationRecord>> GetAllSubscriptionRecordsAsync(Guid subscriptionId, CancellationToken cancellationToken = default); Task RecordAsync( Guid subscriptionId, UpdateOrDeleteSubscriptionRequestResult result, CancellationToken cancellationToken = default); } }
30
142
0.71746
[ "MIT" ]
dstarr/AzureMarketplaceSaaSApiClient
src/IOperationsStore.cs
632
C#
using XeonCommon.Network; namespace XeonCore.Network { public class NetManager : INetManaged<INetClient> { public event NetEventIncoming NetEventIn; public NetQueue Queue = new NetQueue(); public NetManager() { } public void Dispose() { Queue.Dispose(); } public void EmitNetEvent(NetEvent<INetClient> e) { NetEventIn.Invoke(e); } } }
20.954545
56
0.559653
[ "MIT" ]
envis10n/XeonProject
XeonCore/Network/NetManager.cs
463
C#
#region Licence /** * Copyright (C) 2015 Open Tibia Tools <https://github.com/ottools/open-tibia> * * 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 #region Using Statements using System; using System.Drawing; using System.IO; using System.Collections.Generic; using OpenTibia.Client.Things; using OpenTibia.Core; using System.ComponentModel; using System.Threading; #endregion namespace OpenTibia.Client.Sprites { public class SpriteStorage : IStorage, IDisposable { private struct CompilationData { public string Path; public string TmpPath; public Core.Version Version; public ClientFeatures Features; } #region | Constants | private const byte HeaderU16 = 6; private const byte HeaderU32 = 8; #endregion #region | Private Properties | private FileStream stream; private BinaryReader reader; private Dictionary<uint, Sprite> sprites; private uint rawSpriteCount; private byte headSize; private Sprite blankSprite; private bool transparency; private BackgroundWorker worker; private CompilationData compilationData; #endregion #region | Constructor | private SpriteStorage() { this.sprites = new Dictionary<uint, Sprite>(); this.worker = new BackgroundWorker(); this.worker.WorkerSupportsCancellation = true; this.worker.WorkerReportsProgress = true; this.worker.DoWork += new DoWorkEventHandler(this.DoWork_Handler); this.worker.ProgressChanged += new ProgressChangedEventHandler(this.WorkerProgressChanged_Handler); this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.RunWorkerCompleted_Handler); } #endregion #region | Events | public event SpriteListChangedHandler StorageChanged; public event EventHandler StorageCompiled; public event EventHandler StorageCompilationCanceled; public event EventHandler StorageDisposed; public event ProgressHandler ProgressChanged; #endregion #region | Public Properties | public string FilePath { get; private set; } public Core.Version Version { get; private set; } public uint Count { get; private set; } public ClientFeatures ClientFeatures { get; private set; } public bool IsTemporary { get { return this.Loaded && this.FilePath == null; } } public bool IsFull { get { if ((this.ClientFeatures & ClientFeatures.Extended) == ClientFeatures.Extended) { return false; } return this.Count >= 0xFFFF; } } public bool Changed { get; private set; } public bool Loaded { get; private set; } public bool Compiling { get; private set; } public bool Disposed { get; private set; } #endregion #region | Public Methods | public bool AddSprite(Sprite sprite) { if (sprite == null) { throw new ArgumentNullException("sprite"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling) { return false; } uint id = ++this.Count; sprite.ID = id; sprite.Transparent = this.transparency; this.sprites.Add(id, sprite); this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(new Sprite[] { sprite }, StorageChangeType.Add)); } return true; } public bool AddSprite(Bitmap bitmap) { if (bitmap == null) { throw new ArgumentNullException("bitmap"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || bitmap.Width != Sprite.DefaultSize || bitmap.Height != Sprite.DefaultSize) { return false; } if (this.IsFull) { throw new Exception("The limit of sprites was reached."); } uint id = ++this.Count; Sprite sprite = new Sprite(id, this.transparency); sprite.SetBitmap(bitmap); this.sprites.Add(id, sprite); this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(new Sprite[] { sprite }, StorageChangeType.Add)); } return true; } public bool AddSprites(Sprite[] sprites) { if (sprites == null) { throw new ArgumentNullException("sprites"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || sprites.Length == 0) { return false; } List<Sprite> changedSprites = new List<Sprite>(); foreach (Sprite sprite in sprites) { if (sprite == null) { continue; } if (this.IsFull) { throw new Exception("The limit of sprites was reached."); } uint id = ++this.Count; sprite.ID = id; sprite.Transparent = this.transparency; this.sprites.Add(id, sprite); changedSprites.Add(sprite); } if (changedSprites.Count != 0) { this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(changedSprites.ToArray(), StorageChangeType.Add)); } return true; } return false; } public bool AddSprites(Bitmap[] sprites) { if (sprites == null) { throw new ArgumentNullException("sprites"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || sprites.Length == 0) { return false; } List<Sprite> changedSprites = new List<Sprite>(); foreach (Bitmap bitmap in sprites) { if (bitmap == null || bitmap.Width != Sprite.DefaultSize || bitmap.Height != Sprite.DefaultSize) { continue; } if (this.IsFull) { throw new Exception("The limit of sprites was reached."); } uint id = ++this.Count; Sprite sprite = new Sprite(id, this.transparency); this.sprites.Add(id, sprite); changedSprites.Add(sprite); } if (changedSprites.Count != 0) { this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(changedSprites.ToArray(), StorageChangeType.Add)); } return true; } return false; } public bool ReplaceSprite(Sprite newSprite, uint replaceId) { if (newSprite == null) { throw new ArgumentNullException("newSprite"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || replaceId == 0 || replaceId > this.Count) { return false; } newSprite.ID = replaceId; newSprite.Transparent = this.transparency; Sprite replacedSprite = null; if (this.sprites.ContainsKey(replaceId)) { replacedSprite = this.sprites[replaceId]; this.sprites[replaceId] = newSprite; } else { replacedSprite = this.ReadSprite(replaceId); this.sprites.Add(replaceId, newSprite); } this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(new Sprite[] { replacedSprite }, StorageChangeType.Replace)); } return true; } public bool ReplaceSprite(Sprite newSprite) { if (newSprite == null) { throw new ArgumentNullException("newSprite"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling) { return this.ReplaceSprite(newSprite, newSprite.ID); } return false; } public bool ReplaceSprite(Bitmap newBitmap, uint replaceId) { if (newBitmap == null) { throw new ArgumentNullException("newBitmap"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || newBitmap.Width != Sprite.DefaultSize || newBitmap.Height != Sprite.DefaultSize || replaceId == 0 || replaceId > this.Count) { return false; } Sprite newSprite = new Sprite(replaceId, this.transparency); Sprite replacedSprite = null; if (this.sprites.ContainsKey(replaceId)) { replacedSprite = this.sprites[replaceId]; this.sprites[replaceId] = newSprite; } else { replacedSprite = this.ReadSprite(replaceId); this.sprites.Add(replaceId, newSprite); } this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(new Sprite[] { replacedSprite }, StorageChangeType.Replace)); } return true; } public bool ReplaceSprites(Sprite[] newSprites) { if (newSprites == null) { throw new ArgumentNullException("newSprites"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || newSprites.Length == 0) { return false; } List<Sprite> changedSprites = new List<Sprite>(); foreach (Sprite sprite in newSprites) { if (sprite == null || sprite.ID == 0 || sprite.ID > this.Count) { continue; } uint id = sprite.ID; Sprite replacedSprite = null; sprite.Transparent = this.transparency; if (this.sprites.ContainsKey(id)) { replacedSprite = this.sprites[id]; this.sprites[id] = sprite; } else { replacedSprite = this.ReadSprite(id); this.sprites.Add(id, sprite); } changedSprites.Add(replacedSprite); } if (changedSprites.Count != 0) { this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(changedSprites.ToArray(), StorageChangeType.Replace)); } return true; } return false; } public bool RemoveSprite(uint id) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || id == 0 || id > this.Count) { return false; } Sprite removedSprite = this.GetSprite(id); if (id == this.Count && id != 1) { if (this.sprites.ContainsKey(id)) { this.sprites.Remove(id); } this.Count--; } else { if (this.sprites.ContainsKey(id)) { this.sprites[id] = new Sprite(id, this.transparency); } else { this.sprites.Add(id, new Sprite(id, this.transparency)); } } this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(new Sprite[] { removedSprite }, StorageChangeType.Remove)); } return true; } public bool RemoveSprites(uint[] ids) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling || ids == null || ids.Length == 0) { return false; } List<Sprite> changedSprites = new List<Sprite>(); for (int i = 0; i < ids.Length; i++) { uint id = ids[i]; if (id == 0 || id > this.Count) { continue; } changedSprites.Add(this.GetSprite(id)); if (id == this.Count && id != 1) { if (this.sprites.ContainsKey(id)) { this.sprites.Remove(id); } this.Count--; } else { if (this.sprites.ContainsKey(id)) { this.sprites[id] = new Sprite(id, this.transparency); } else { this.sprites.Add(id, new Sprite(id, this.transparency)); } } } if (changedSprites.Count != 0) { this.Changed = true; if (this.StorageChanged != null) { this.StorageChanged(this, new SpriteListChangedArgs(changedSprites.ToArray(), StorageChangeType.Remove)); } } return false; } public bool HasSpriteID(uint id) { return id <= this.Count; } public Sprite GetSprite(uint id) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (id <= this.Count) { if (id == 0) { return this.blankSprite; } if (this.sprites.ContainsKey(id)) { return this.sprites[id]; } return this.ReadSprite(id); } return null; } public Sprite GetSprite(int id) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (id >= 0) { return this.GetSprite((uint)id); } return null; } public Bitmap GetSpriteBitmap(uint id) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (id <= this.Count) { return this.ReadSprite(id).GetBitmap(); } return null; } public Bitmap GetSpriteBitmap(int id) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (id >= 0 && id <= this.Count) { return this.ReadSprite((uint)id).GetBitmap(); } return null; } public bool Save(string path, Core.Version version, ClientFeatures features) { if (path == null) { throw new ArgumentNullException("path"); } if (version == null) { throw new ArgumentNullException("version"); } if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (!this.Loaded || this.Compiling) { return false; } if (features == ClientFeatures.None || features == ClientFeatures.Transparency) { features |= version.Value >= (ushort)DatFormat.Format_755 ? ClientFeatures.PatternZ : features; features |= version.Value >= (ushort)DatFormat.Format_960 ? ClientFeatures.Extended : features; features |= version.Value >= (ushort)DatFormat.Format_1050 ? ClientFeatures.FrameDurations : features; features |= version.Value >= (ushort)DatFormat.Format_1057 ? ClientFeatures.FrameGroups : features; } string directory = Path.GetDirectoryName(path); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!this.Changed && this.Version.Equals(version) && this.ClientFeatures == features) { // just copy the content and reload if nothing has changed. if (this.FilePath != null && !this.FilePath.Equals(path)) { File.Copy(this.FilePath, path, true); if (!this.InternalLoad(path, version, features, true)) { return false; } if (this.ProgressChanged != null) { this.ProgressChanged(this, 100); } if (this.StorageCompiled != null) { this.StorageCompiled(this, new EventArgs()); } } return true; } this.compilationData = new CompilationData(); this.compilationData.Path = path; this.compilationData.TmpPath = Path.Combine(directory, Path.GetFileNameWithoutExtension(path) + ".tmp"); this.compilationData.Version = version; this.compilationData.Features = features; this.Compiling = true; this.worker.RunWorkerAsync(); return true; } public bool Save(string path, Core.Version version) { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } return this.Save(path, version, ClientFeatures.None); } public bool Save() { if (this.Disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (this.Changed && !this.IsTemporary) { return this.Save(this.FilePath, this.Version, this.ClientFeatures); } return true; } public bool Cancel() { if (this.Compiling) { this.Compiling = false; this.worker.CancelAsync(); return true; } return false; } public void Dispose() { this.Disposed = true; if (!this.Loaded) { return; } if (this.stream != null) { this.stream.Dispose(); this.stream = null; this.reader.Dispose(); this.reader = null; } this.FilePath = null; this.sprites.Clear(); this.sprites = null; this.rawSpriteCount = 0; this.Count = 0; this.transparency = false; this.Changed = false; this.Loaded = false; this.Compiling = false; if (this.StorageDisposed != null) { this.StorageDisposed(this, new EventArgs()); } } #endregion #region | Private Methods | private bool InternalCreate(Core.Version version, ClientFeatures features) { if (this.Compiling) { return false; } if (this.Loaded) { return true; } if (features == ClientFeatures.None || features == ClientFeatures.Transparency) { features |= version.Value >= (ushort)DatFormat.Format_755 ? ClientFeatures.PatternZ : features; features |= version.Value >= (ushort)DatFormat.Format_960 ? ClientFeatures.Extended : features; features |= version.Value >= (ushort)DatFormat.Format_1050 ? ClientFeatures.FrameDurations : features; features |= version.Value >= (ushort)DatFormat.Format_1057 ? ClientFeatures.FrameGroups : features; } this.Version = version; this.ClientFeatures = features; this.transparency = (features & ClientFeatures.Transparency) == ClientFeatures.Transparency ? true : false; this.headSize = (features & ClientFeatures.Extended) == ClientFeatures.Extended ? HeaderU32 : HeaderU16; this.blankSprite = new Sprite(0, this.transparency); this.sprites.Add(1, new Sprite(1, this.transparency)); this.rawSpriteCount = 0; this.Count = 1; this.Changed = true; this.Loaded = true; this.Compiling = false; this.Disposed = false; return true; } private bool InternalLoad(string path, Core.Version version, ClientFeatures features, bool reloading) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } if (version == null) { throw new ArgumentNullException("version"); } if (!File.Exists(path)) { string message = "File not found: {0}"; // TODO: ResourceManager.GetString("Exception.FileNotFound"); throw new FileNotFoundException(string.Format(message, path), "path"); } if (this.Compiling) { return false; } if (this.Loaded) { if (reloading) { this.stream.Close(); this.stream = null; } else { return true; } } if (features == ClientFeatures.None || features == ClientFeatures.Transparency) { features |= version.Value >= (ushort)DatFormat.Format_755 ? ClientFeatures.PatternZ : features; features |= version.Value >= (ushort)DatFormat.Format_960 ? ClientFeatures.Extended : features; features |= version.Value >= (ushort)DatFormat.Format_1050 ? ClientFeatures.FrameDurations : features; features |= version.Value >= (ushort)DatFormat.Format_1057 ? ClientFeatures.FrameGroups : features; } this.stream = new FileStream(path, FileMode.Open); this.reader = new BinaryReader(this.stream); uint signature = this.reader.ReadUInt32(); if (signature != version.SprSignature) { string message = "Invalid SPR signature. Expected signature is {0:X} and loaded signature is {1:X}."; throw new Exception(string.Format(message, version.SprSignature, signature)); } if ((features & ClientFeatures.Extended) == ClientFeatures.Extended) { this.headSize = HeaderU32; this.rawSpriteCount = this.reader.ReadUInt32(); } else { this.headSize = HeaderU16; this.rawSpriteCount = this.reader.ReadUInt16(); } this.FilePath = path; this.Version = version; this.ClientFeatures = features; this.transparency = (features & ClientFeatures.Transparency) == ClientFeatures.Transparency ? true : false; this.Count = this.rawSpriteCount; this.blankSprite = new Sprite(0, this.transparency); this.Changed = false; this.Loaded = true; this.Disposed = false; return true; } private Sprite ReadSprite(uint id) { try { if (id > this.rawSpriteCount) { return null; } // O id 1 no arquivo spr é o endereço 0, então subtraímos // o id fornecido e mutiplicamos pela quantidade de bytes // de cada endereço. this.stream.Position = ((id - 1) * 4) + this.headSize; // Lê o endereço do sprite. uint spriteAddress = this.reader.ReadUInt32(); // O endereço 0 representa um sprite em branco, // então retornamos um sprite sem a leitura dos dados. if (spriteAddress == 0) { return new Sprite(id, this.transparency); } // Posiciona o stream para o endereço do sprite. this.stream.Position = spriteAddress; // Leitura da cor magenta usada como referência // para remover o fundo do sprite. this.reader.ReadByte(); // red key color this.reader.ReadByte(); // green key color this.reader.ReadByte(); // blue key color Sprite sprite = new Sprite(id, this.transparency); // O tamanho dos pixels compressados. ushort pixelDataSize = this.reader.ReadUInt16(); if (pixelDataSize != 0) { sprite.CompressedPixels = this.reader.ReadBytes(pixelDataSize); } return sprite; } catch /*(Exception ex)*/ { // TODO ErrorManager.ShowError(ex); } return null; } #endregion #region | Event Handlers | private void DoWork_Handler(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; using (BinaryWriter writer = new BinaryWriter(new FileStream(this.compilationData.TmpPath, FileMode.Create))) { uint count = 0; bool extended = (this.compilationData.Features & ClientFeatures.Extended) == ClientFeatures.Extended; bool transparent = (this.compilationData.Features & ClientFeatures.Transparency) == ClientFeatures.Transparency; bool changeTransparency = this.transparency != transparent; // write the signature writer.Write(this.compilationData.Version.SprSignature); // write the sprite count if (extended) { count = this.Count; writer.Write(count); } else { count = this.Count >= 0xFFFF ? 0xFFFF : this.Count; writer.Write((ushort)count); } int addressPosition = headSize; int address = (int)((count * 4) + headSize); byte[] bytes = null; for (uint id = 1; id <= count; id++) { if (worker.CancellationPending) { e.Cancel = true; break; } writer.Seek(addressPosition, SeekOrigin.Begin); if (this.sprites.ContainsKey(id) || changeTransparency) { Sprite sprite = null; this.sprites.TryGetValue(id, out sprite); if (sprite == null) { sprite = this.ReadSprite(id); } sprite.Transparent = transparent; if (sprite.Length == 0) { // write address 0 writer.Write((uint)0); writer.Seek(address, SeekOrigin.Begin); } else { bytes = sprite.CompressedPixels; // write address writer.Write((uint)address); writer.Seek(address, SeekOrigin.Begin); // write colorkey writer.Write((byte)0xFF); // red writer.Write((byte)0x00); // blue writer.Write((byte)0xFF); // green // write sprite data size writer.Write((short)bytes.Length); if (bytes.Length > 0) { writer.Write(bytes); } } } else if (id <= this.rawSpriteCount) { this.stream.Seek(((id - 1) * 4) + this.headSize, SeekOrigin.Begin); uint spriteAddress = this.reader.ReadUInt32(); if (spriteAddress == 0) { // write address 0 writer.Write((uint)0); writer.Seek(address, SeekOrigin.Begin); } else { // write address writer.Write((uint)address); writer.Seek(address, SeekOrigin.Begin); // write colorkey writer.Write((byte)0xFF); // red writer.Write((byte)0x00); // blue writer.Write((byte)0xFF); // green // sets the position to the pixel data size. this.stream.Seek(spriteAddress + 3, SeekOrigin.Begin); // read the data size from the current stream ushort pixelDataSize = this.reader.ReadUInt16(); // write sprite data size writer.Write(pixelDataSize); // write sprite compressed pixels if (pixelDataSize != 0) { bytes = this.reader.ReadBytes(pixelDataSize); writer.Write(bytes); } } } address = (int)writer.BaseStream.Position; addressPosition += 4; if ((id % 500) == 0) { Thread.Sleep(10); worker.ReportProgress((int)((id * 100) / count)); } } writer.Close(); } if (File.Exists(this.compilationData.Path)) { File.Delete(this.compilationData.Path); } File.Move(this.compilationData.TmpPath, this.compilationData.Path); } private void WorkerProgressChanged_Handler(object sender, ProgressChangedEventArgs e) { if (this.ProgressChanged != null) { this.ProgressChanged(this, e.ProgressPercentage); } } private void RunWorkerCompleted_Handler(object sender, RunWorkerCompletedEventArgs e) { if (!e.Cancelled && this.InternalLoad(this.compilationData.Path, this.compilationData.Version, this.compilationData.Features, true)) { if (this.StorageCompiled != null) { this.StorageCompiled(this, new EventArgs()); } if (this.ProgressChanged != null) { this.ProgressChanged(this, 100); } } else if (File.Exists(this.compilationData.TmpPath)) { File.Delete(this.compilationData.TmpPath); if (this.ProgressChanged != null) { this.ProgressChanged(this, 0); } } if (e.Cancelled && this.StorageCompilationCanceled != null) { this.StorageCompilationCanceled(this, new EventArgs()); } } #endregion #region | Public Static Methods | public static SpriteStorage Create(Core.Version version, ClientFeatures features) { SpriteStorage storage = new SpriteStorage(); if (storage.InternalCreate(version, features)) { return storage; } return null; } public static SpriteStorage Create(Core.Version version) { SpriteStorage storage = new SpriteStorage(); if (storage.InternalCreate(version, ClientFeatures.None)) { return storage; } return null; } public static SpriteStorage Load(string path, Core.Version version, ClientFeatures features) { SpriteStorage storage = new SpriteStorage(); if (storage.InternalLoad(path, version, features, false)) { return storage; } return null; } public static SpriteStorage Load(string path, Core.Version version) { SpriteStorage storage = new SpriteStorage(); if (storage.InternalLoad(path, version, ClientFeatures.None, false)) { return storage; } return null; } #endregion } }
30.968439
174
0.479322
[ "MIT" ]
totolol123/open-tibia
OpenTibia/OpenTibia.Client/Sprites/SpriteStorage.cs
37,299
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.FriendlyUrls.Resolvers; namespace SampleWebFormsApp { public partial class ViewSwitcher : System.Web.UI.UserControl { protected string CurrentView { get; private set; } protected string AlternateView { get; private set; } protected string SwitchUrl { get; private set; } protected void Page_Load(object sender, EventArgs e) { // Determine current view var isMobile = WebFormsFriendlyUrlResolver.IsMobileView(new HttpContextWrapper(Context)); CurrentView = isMobile ? "Mobile" : "Desktop"; // Determine alternate view AlternateView = isMobile ? "Desktop" : "Mobile"; // Create switch URL from the route, e.g. ~/__FriendlyUrls_SwitchView/Mobile?ReturnUrl=/Page var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView"; var switchViewRoute = RouteTable.Routes[switchViewRouteName]; if (switchViewRoute == null) { // Friendly URLs is not enabled or the name of the switch view route is out of sync this.Visible = false; return; } var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView, __FriendlyUrls_SwitchViews = true }); url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl); SwitchUrl = url; } } }
37
120
0.644249
[ "MIT" ]
dzhenko/TelerikAcademy
ASP WebForms/WF-01-ASPIntroduction-Homework/SampleWebFormsApp/ViewSwitcher.ascx.cs
1,591
C#
using System; using Pixelator.Api.Configuration; using Pixelator.Api.Exceptions; namespace Pixelator.Api.Codec { internal class ImageEncoderFactory { public ImageEncoderBase BuildEncoder(Version version, EncodingConfiguration encodingConfiguration) { switch (version) { case Version.V1: return new V1.ImageEncoder(encodingConfiguration); default: throw new UnsupportedVersionException(String.Format("Version {0} is not supported", (short)Version.V1)); } } } }
30.25
124
0.621488
[ "Apache-2.0" ]
TimeToogo/Pixelator.Api
Pixelator.Api/Codec/ImageEncoderFactory.cs
607
C#
// 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 // // Authors: // Miguel de Icaza (miguel@novell.com) // Jb Evain (jbevain@novell.com) // using System; using System.Reflection; using System.Linq; using System.Linq.Expressions; using NUnit.Framework; namespace MonoTests.System.Linq.Expressions { [TestFixture] public class ExpressionTest_Equal { [Test] [ExpectedException (typeof (ArgumentNullException))] public void Arg1Null () { Expression.Equal (null, Expression.Constant (1)); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Arg2Null () { Expression.Equal (Expression.Constant (1), null); } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ArgTypesDifferent () { Expression.Equal (Expression.Constant (1), Expression.Constant (2.0)); } [Test] public void ReferenceCompare () { Expression.Equal (Expression.Constant (new NoOpClass ()), Expression.Constant (new NoOpClass ())); } public struct D { } [Test] [ExpectedException (typeof (InvalidOperationException))] public void NoOperatorClass () { Expression.Equal (Expression.Constant (new D ()), Expression.Constant (new D ())); } [Test] public void Numeric () { BinaryExpression expr = Expression.Equal (Expression.Constant (1), Expression.Constant (2)); Assert.AreEqual (ExpressionType.Equal, expr.NodeType); Assert.AreEqual (typeof (bool), expr.Type); Assert.IsNull (expr.Method); #if !NET_4_0 Assert.AreEqual ("(1 = 2)", expr.ToString ()); #endif } [Test] public void PrimitiveNonNumeric () { BinaryExpression expr = Expression.Equal (Expression.Constant ('a'), Expression.Constant ('b')); Assert.AreEqual (ExpressionType.Equal, expr.NodeType); Assert.AreEqual (typeof (bool), expr.Type); Assert.IsNull (expr.Method); var eq = Expression.Lambda<Func<bool>> (expr).Compile (); Assert.IsFalse (eq ()); } [Test] public void Nullable_LiftToNull_SetToFalse () { int? a = 1; int? b = 2; BinaryExpression expr = Expression.Equal (Expression.Constant (a, typeof(int?)), Expression.Constant (b, typeof(int?)), false, null); Assert.AreEqual (ExpressionType.Equal, expr.NodeType); Assert.AreEqual (typeof (bool), expr.Type); Assert.AreEqual (true, expr.IsLifted); Assert.AreEqual (false, expr.IsLiftedToNull); Assert.IsNull (expr.Method); #if !NET_4_0 Assert.AreEqual ("(1 = 2)", expr.ToString ()); #endif } [Test] public void Nullable_LiftToNull_SetToTrue () { int? a = 1; int? b = 2; BinaryExpression expr = Expression.Equal (Expression.Constant (a, typeof(int?)), Expression.Constant (b, typeof(int?)), true, null); Assert.AreEqual (ExpressionType.Equal, expr.NodeType); Assert.AreEqual (typeof (bool?), expr.Type); Assert.AreEqual (true, expr.IsLifted); Assert.AreEqual (true, expr.IsLiftedToNull); Assert.IsNull (expr.Method); #if !NET_4_0 Assert.AreEqual ("(1 = 2)", expr.ToString ()); #endif } [Test] [ExpectedException(typeof (InvalidOperationException))] public void Nullable_Mixed () { int? a = 1; int b = 2; Expression.Equal (Expression.Constant (a, typeof (int?)), Expression.Constant (b, typeof (int))); } [Test] public void UserDefinedClass () { // We can use the simplest version of GetMethod because we already know only one // exists in the very simple class we're using for the tests. MethodInfo mi = typeof (OpClass).GetMethod ("op_Equality"); BinaryExpression expr = Expression.Equal (Expression.Constant (new OpClass ()), Expression.Constant (new OpClass ())); Assert.AreEqual (ExpressionType.Equal, expr.NodeType); Assert.AreEqual (typeof (bool), expr.Type); Assert.AreEqual (mi, expr.Method); Assert.AreEqual ("op_Equality", expr.Method.Name); #if !NET_4_0 Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) = value(MonoTests.System.Linq.Expressions.OpClass))", expr.ToString ()); #endif } [Test] public void NullableInt32Equal () { var l = Expression.Parameter (typeof (int?), "l"); var r = Expression.Parameter (typeof (int?), "r"); var eq = Expression.Lambda<Func<int?, int?, bool>> ( Expression.Equal (l, r), l, r).Compile (); Assert.IsTrue (eq (null, null)); Assert.IsFalse (eq (null, 1)); Assert.IsFalse (eq (1, null)); Assert.IsFalse (eq (1, 2)); Assert.IsTrue (eq (1, 1)); Assert.IsFalse (eq (null, 0)); Assert.IsFalse (eq (0, null)); } [Test] public void NullableInt32EqualLiftedToNull () { var l = Expression.Parameter (typeof (int?), "l"); var r = Expression.Parameter (typeof (int?), "r"); var eq = Expression.Lambda<Func<int?, int?, bool?>> ( Expression.Equal (l, r, true, null), l, r).Compile (); Assert.AreEqual ((bool?) null, eq (null, null)); Assert.AreEqual ((bool?) null, eq (null, 1)); Assert.AreEqual ((bool?) null, eq (1, null)); Assert.AreEqual ((bool?) false, eq (1, 2)); Assert.AreEqual ((bool?) true, eq (1, 1)); Assert.AreEqual ((bool?) null, eq (null, 0)); Assert.AreEqual ((bool?) null, eq (0, null)); } struct Slot { public int Value; public Slot (int value) { this.Value = value; } public override bool Equals (object obj) { if (!(obj is Slot)) return false; var other = (Slot) obj; return other.Value == this.Value; } public override int GetHashCode () { return Value; } public static bool operator == (Slot a, Slot b) { return a.Value == b.Value; } public static bool operator != (Slot a, Slot b) { return a.Value != b.Value; } } [Test] public void UserDefinedEqual () { var l = Expression.Parameter (typeof (Slot), "l"); var r = Expression.Parameter (typeof (Slot), "r"); var node = Expression.Equal (l, r); Assert.IsFalse (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNotNull (node.Method); var eq = Expression.Lambda<Func<Slot, Slot, bool>> (node, l, r).Compile (); Assert.AreEqual (true, eq (new Slot (21), new Slot (21))); Assert.AreEqual (false, eq (new Slot (1), new Slot (-1))); } [Test] [Category ("NotWorkingInterpreter")] public void UserDefinedEqualLifted () { var l = Expression.Parameter (typeof (Slot?), "l"); var r = Expression.Parameter (typeof (Slot?), "r"); var node = Expression.Equal (l, r); Assert.IsTrue (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNotNull (node.Method); var eq = Expression.Lambda<Func<Slot?, Slot?, bool>> (node, l, r).Compile (); Assert.AreEqual (true, eq (null, null)); Assert.AreEqual (false, eq ((Slot?) new Slot (2), null)); Assert.AreEqual (false, eq (null, (Slot?) new Slot (2))); Assert.AreEqual (true, eq ((Slot?) new Slot (21), (Slot?) new Slot (21))); } [Test] [Category ("NotWorkingInterpreter")] public void UserDefinedEqualLiftedToNull () { var l = Expression.Parameter (typeof (Slot?), "l"); var r = Expression.Parameter (typeof (Slot?), "r"); var node = Expression.Equal (l, r, true, null); Assert.IsTrue (node.IsLifted); Assert.IsTrue (node.IsLiftedToNull); Assert.AreEqual (typeof (bool?), node.Type); Assert.IsNotNull (node.Method); var eq = Expression.Lambda<Func<Slot?, Slot?, bool?>> (node, l, r).Compile (); Assert.AreEqual ((bool?) null, eq (null, null)); Assert.AreEqual ((bool?) null, eq ((Slot?) new Slot (2), null)); Assert.AreEqual ((bool?) null, eq (null, (Slot?) new Slot (2))); Assert.AreEqual ((bool?) true, eq ((Slot?) new Slot (21), (Slot?) new Slot (21))); Assert.AreEqual ((bool?) false, eq ((Slot?) new Slot (21), (Slot?) new Slot (-21))); } struct SlotToNullable { public int Value; public SlotToNullable (int value) { this.Value = value; } public override int GetHashCode () { return Value; } public override bool Equals (object obj) { if (!(obj is SlotToNullable)) return false; var other = (SlotToNullable) obj; return other.Value == this.Value; } public static bool? operator == (SlotToNullable a, SlotToNullable b) { return (bool?) (a.Value == b.Value); } public static bool? operator != (SlotToNullable a, SlotToNullable b) { return (bool?) (a.Value != b.Value); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void UserDefinedToNullableEqualFromNullable () { Expression.Equal ( Expression.Parameter (typeof (SlotToNullable?), "l"), Expression.Parameter (typeof (SlotToNullable?), "r")); } [Test] public void UserDefinedToNullableEqual () { var l = Expression.Parameter (typeof (SlotToNullable), "l"); var r = Expression.Parameter (typeof (SlotToNullable), "r"); var node = Expression.Equal (l, r, false, null); Assert.IsFalse (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool?), node.Type); Assert.IsNotNull (node.Method); var eq = Expression.Lambda<Func<SlotToNullable, SlotToNullable, bool?>> (node, l, r).Compile (); Assert.AreEqual ((bool?) true, eq (new SlotToNullable (2), new SlotToNullable (2))); Assert.AreEqual ((bool?) false, eq (new SlotToNullable (2), new SlotToNullable (-2))); } /*struct SlotFromNullableToNullable { public int Value; public SlotFromNullableToNullable (int value) { this.Value = value; } public override bool Equals (object obj) { if (!(obj is SlotFromNullableToNullable)) return false; var other = (SlotFromNullableToNullable) obj; return other.Value == this.Value; } public override int GetHashCode () { return Value; } public static bool? operator == (SlotFromNullableToNullable? a, SlotFromNullableToNullable? b) { if (a.HasValue && b.HasValue) return (bool?) (a.Value.Value == b.Value.Value); else return null; } public static bool? operator != (SlotFromNullableToNullable? a, SlotFromNullableToNullable? b) { return !(a == b); } } [Test] public void UserDefinedFromNullableToNullableEqual () { var l = Expression.Parameter (typeof (SlotFromNullableToNullable?), "l"); var r = Expression.Parameter (typeof (SlotFromNullableToNullable?), "r"); var node = Expression.Equal (l, r); Assert.IsFalse (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool?), node.Type); Assert.IsNotNull (node.Method); var eq = Expression.Lambda<Func<SlotFromNullableToNullable?, SlotFromNullableToNullable?, bool?>> (node, l, r).Compile (); Assert.AreEqual ((bool?) null, eq (null, null)); Assert.AreEqual ((bool?) null, eq (new SlotFromNullableToNullable (2), null)); Assert.AreEqual ((bool?) null, eq (null, new SlotFromNullableToNullable (2))); Assert.AreEqual ((bool?) true, eq (new SlotFromNullableToNullable (2), new SlotFromNullableToNullable (2))); Assert.AreEqual ((bool?) false, eq (new SlotFromNullableToNullable (2), new SlotFromNullableToNullable (-2))); }*/ [Test] public void NullableBoolEqualToBool () { var l = Expression.Parameter (typeof (bool?), "l"); var r = Expression.Parameter (typeof (bool?), "r"); var node = Expression.Equal (l, r); Assert.IsTrue (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNull (node.Method); var eq = Expression.Lambda<Func<bool?, bool?, bool>> (node, l, r).Compile (); Assert.AreEqual (false, eq (true, null)); Assert.AreEqual (true, eq (null, null)); Assert.AreEqual (true, eq (false, false)); } public enum Foo { Bar, Baz, } [Test] public void EnumEqual () { var l = Expression.Parameter (typeof (Foo), "l"); var r = Expression.Parameter (typeof (Foo), "r"); var node = Expression.Equal (l, r); Assert.IsFalse (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNull (node.Method); var eq = Expression.Lambda<Func<Foo, Foo, bool>> (node, l, r).Compile (); Assert.AreEqual (true, eq (Foo.Bar, Foo.Bar)); Assert.AreEqual (false, eq (Foo.Bar, Foo.Baz)); } [Test] public void LiftedEnumEqual () { var l = Expression.Parameter (typeof (Foo?), "l"); var r = Expression.Parameter (typeof (Foo?), "r"); var node = Expression.Equal (l, r); Assert.IsTrue (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNull (node.Method); var eq = Expression.Lambda<Func<Foo?, Foo?, bool>> (node, l, r).Compile (); Assert.AreEqual (true, eq (Foo.Bar, Foo.Bar)); Assert.AreEqual (false, eq (Foo.Bar, Foo.Baz)); Assert.AreEqual (false, eq (Foo.Bar, null)); Assert.AreEqual (true, eq (null, null)); } [Test] [Category ("NotWorkingInterpreter")] public void NullableNullEqual () { var param = Expression.Parameter (typeof (DateTime?), "x"); var node = Expression.Equal (param, Expression.Constant (null)); Assert.IsTrue (node.IsLifted); Assert.IsFalse (node.IsLiftedToNull); Assert.AreEqual (typeof (bool), node.Type); Assert.IsNull (node.Method); var eq = Expression.Lambda<Func<DateTime?, bool>> (node, new [] { param }).Compile (); Assert.AreEqual (true, eq (null)); Assert.AreEqual (false, eq (DateTime.Now)); } } }
29.274194
143
0.662534
[ "Apache-2.0" ]
3-1415926/mono
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Equal.cs
14,520
C#
namespace AillieoUtils.CSFixedPoint { internal static class FPTanLut_48128 { internal static fp[] table = new fp[] { fp.CreateWithRaw(9689290964), // 2.25596385192916 fp.CreateWithRaw(9689917861), // 2.25610981265033 fp.CreateWithRaw(9690544825), // 2.25625578915814 fp.CreateWithRaw(9691171857), // 2.25640178145532 fp.CreateWithRaw(9691798957), // 2.25654778954459 fp.CreateWithRaw(9692426125), // 2.25669381342869 fp.CreateWithRaw(9693053361), // 2.25683985311035 fp.CreateWithRaw(9693680664), // 2.2569859085923 fp.CreateWithRaw(9694308036), // 2.25713197987727 fp.CreateWithRaw(9694935475), // 2.257278066968 fp.CreateWithRaw(9695562982), // 2.25742416986721 fp.CreateWithRaw(9696190557), // 2.25757028857765 fp.CreateWithRaw(9696818200), // 2.25771642310205 fp.CreateWithRaw(9697445911), // 2.25786257344313 fp.CreateWithRaw(9698073690), // 2.25800873960365 fp.CreateWithRaw(9698701537), // 2.25815492158633 fp.CreateWithRaw(9699329452), // 2.25830111939391 fp.CreateWithRaw(9699957435), // 2.25844733302913 fp.CreateWithRaw(9700585485), // 2.25859356249473 fp.CreateWithRaw(9701213604), // 2.25873980779345 fp.CreateWithRaw(9701841791), // 2.25888606892802 fp.CreateWithRaw(9702470046), // 2.2590323459012 fp.CreateWithRaw(9703098369), // 2.25917863871571 fp.CreateWithRaw(9703726760), // 2.2593249473743 fp.CreateWithRaw(9704355218), // 2.25947127187971 fp.CreateWithRaw(9704983746), // 2.25961761223469 fp.CreateWithRaw(9705612341), // 2.25976396844197 fp.CreateWithRaw(9706241004), // 2.25991034050431 fp.CreateWithRaw(9706869735), // 2.26005672842445 fp.CreateWithRaw(9707498535), // 2.26020313220513 fp.CreateWithRaw(9708127402), // 2.2603495518491 fp.CreateWithRaw(9708756338), // 2.2604959873591 fp.CreateWithRaw(9709385342), // 2.26064243873789 fp.CreateWithRaw(9710014414), // 2.26078890598821 fp.CreateWithRaw(9710643554), // 2.26093538911281 fp.CreateWithRaw(9711272763), // 2.26108188811443 fp.CreateWithRaw(9711902039), // 2.26122840299583 fp.CreateWithRaw(9712531384), // 2.26137493375977 fp.CreateWithRaw(9713160797), // 2.26152148040898 fp.CreateWithRaw(9713790278), // 2.26166804294622 fp.CreateWithRaw(9714419828), // 2.26181462137425 fp.CreateWithRaw(9715049446), // 2.26196121569582 fp.CreateWithRaw(9715679132), // 2.26210782591367 fp.CreateWithRaw(9716308886), // 2.26225445203057 fp.CreateWithRaw(9716938709), // 2.26240109404927 fp.CreateWithRaw(9717568600), // 2.26254775197253 fp.CreateWithRaw(9718198559), // 2.26269442580309 fp.CreateWithRaw(9718828587), // 2.26284111554373 fp.CreateWithRaw(9719458683), // 2.26298782119719 fp.CreateWithRaw(9720088847), // 2.26313454276623 fp.CreateWithRaw(9720719080), // 2.26328128025362 fp.CreateWithRaw(9721349381), // 2.2634280336621 fp.CreateWithRaw(9721979750), // 2.26357480299445 fp.CreateWithRaw(9722610188), // 2.26372158825342 fp.CreateWithRaw(9723240695), // 2.26386838944178 fp.CreateWithRaw(9723871269), // 2.26401520656227 fp.CreateWithRaw(9724501913), // 2.26416203961768 fp.CreateWithRaw(9725132624), // 2.26430888861076 fp.CreateWithRaw(9725763404), // 2.26445575354427 fp.CreateWithRaw(9726394253), // 2.26460263442098 fp.CreateWithRaw(9727025170), // 2.26474953124366 fp.CreateWithRaw(9727656155), // 2.26489644401506 fp.CreateWithRaw(9728287209), // 2.26504337273796 fp.CreateWithRaw(9728918332), // 2.26519031741513 fp.CreateWithRaw(9729549523), // 2.26533727804932 fp.CreateWithRaw(9730180783), // 2.26548425464331 fp.CreateWithRaw(9730812111), // 2.26563124719988 fp.CreateWithRaw(9731443508), // 2.26577825572177 fp.CreateWithRaw(9732074973), // 2.26592528021178 fp.CreateWithRaw(9732706507), // 2.26607232067266 fp.CreateWithRaw(9733338110), // 2.2662193771072 fp.CreateWithRaw(9733969781), // 2.26636644951815 fp.CreateWithRaw(9734601521), // 2.2665135379083 fp.CreateWithRaw(9735233329), // 2.26666064228042 fp.CreateWithRaw(9735865206), // 2.26680776263728 fp.CreateWithRaw(9736497152), // 2.26695489898165 fp.CreateWithRaw(9737129167), // 2.26710205131632 fp.CreateWithRaw(9737761250), // 2.26724921964405 fp.CreateWithRaw(9738393402), // 2.26739640396763 fp.CreateWithRaw(9739025622), // 2.26754360428983 fp.CreateWithRaw(9739657911), // 2.26769082061343 fp.CreateWithRaw(9740290270), // 2.2678380529412 fp.CreateWithRaw(9740922696), // 2.26798530127593 fp.CreateWithRaw(9741555192), // 2.2681325656204 fp.CreateWithRaw(9742187756), // 2.26827984597738 fp.CreateWithRaw(9742820389), // 2.26842714234967 fp.CreateWithRaw(9743453091), // 2.26857445474003 fp.CreateWithRaw(9744085862), // 2.26872178315125 fp.CreateWithRaw(9744718701), // 2.26886912758612 fp.CreateWithRaw(9745351610), // 2.26901648804742 fp.CreateWithRaw(9745984587), // 2.26916386453793 fp.CreateWithRaw(9746617633), // 2.26931125706043 fp.CreateWithRaw(9747250748), // 2.26945866561772 fp.CreateWithRaw(9747883932), // 2.26960609021258 fp.CreateWithRaw(9748517184), // 2.2697535308478 fp.CreateWithRaw(9749150506), // 2.26990098752615 fp.CreateWithRaw(9749783897), // 2.27004846025044 fp.CreateWithRaw(9750417356), // 2.27019594902345 fp.CreateWithRaw(9751050884), // 2.27034345384797 fp.CreateWithRaw(9751684482), // 2.27049097472679 fp.CreateWithRaw(9752318148), // 2.2706385116627 fp.CreateWithRaw(9752951883), // 2.27078606465849 fp.CreateWithRaw(9753585688), // 2.27093363371695 fp.CreateWithRaw(9754219561), // 2.27108121884088 fp.CreateWithRaw(9754853503), // 2.27122882003307 fp.CreateWithRaw(9755487515), // 2.27137643729631 fp.CreateWithRaw(9756121595), // 2.2715240706334 fp.CreateWithRaw(9756755744), // 2.27167172004713 fp.CreateWithRaw(9757389963), // 2.27181938554031 fp.CreateWithRaw(9758024250), // 2.27196706711571 fp.CreateWithRaw(9758658607), // 2.27211476477615 fp.CreateWithRaw(9759293033), // 2.27226247852442 fp.CreateWithRaw(9759927528), // 2.27241020836332 fp.CreateWithRaw(9760562091), // 2.27255795429565 fp.CreateWithRaw(9761196725), // 2.2727057163242 fp.CreateWithRaw(9761831427), // 2.27285349445178 fp.CreateWithRaw(9762466198), // 2.27300128868119 fp.CreateWithRaw(9763101039), // 2.27314909901523 fp.CreateWithRaw(9763735948), // 2.27329692545671 fp.CreateWithRaw(9764370927), // 2.27344476800842 fp.CreateWithRaw(9765005975), // 2.27359262667316 fp.CreateWithRaw(9765641093), // 2.27374050145375 fp.CreateWithRaw(9766276279), // 2.27388839235299 fp.CreateWithRaw(9766911535), // 2.27403629937369 fp.CreateWithRaw(9767546860), // 2.27418422251864 fp.CreateWithRaw(9768182255), // 2.27433216179066 fp.CreateWithRaw(9768817718), // 2.27448011719256 fp.CreateWithRaw(9769453251), // 2.27462808872714 fp.CreateWithRaw(9770088853), // 2.27477607639721 fp.CreateWithRaw(9770724525), // 2.27492408020558 fp.CreateWithRaw(9771360266), // 2.27507210015506 fp.CreateWithRaw(9771996076), // 2.27522013624846 fp.CreateWithRaw(9772631955), // 2.2753681884886 fp.CreateWithRaw(9773267904), // 2.27551625687828 fp.CreateWithRaw(9773903923), // 2.27566434142032 fp.CreateWithRaw(9774540010), // 2.27581244211753 fp.CreateWithRaw(9775176167), // 2.27596055897272 fp.CreateWithRaw(9775812394), // 2.27610869198872 fp.CreateWithRaw(9776448690), // 2.27625684116833 fp.CreateWithRaw(9777085055), // 2.27640500651437 fp.CreateWithRaw(9777721490), // 2.27655318802966 fp.CreateWithRaw(9778357994), // 2.27670138571701 fp.CreateWithRaw(9778994568), // 2.27684959957924 fp.CreateWithRaw(9779631211), // 2.27699782961918 fp.CreateWithRaw(9780267923), // 2.27714607583964 fp.CreateWithRaw(9780904706), // 2.27729433824344 fp.CreateWithRaw(9781541557), // 2.2774426168334 fp.CreateWithRaw(9782178479), // 2.27759091161234 fp.CreateWithRaw(9782815469), // 2.27773922258308 fp.CreateWithRaw(9783452530), // 2.27788754974845 fp.CreateWithRaw(9784089660), // 2.27803589311127 fp.CreateWithRaw(9784726859), // 2.27818425267436 fp.CreateWithRaw(9785364128), // 2.27833262844056 fp.CreateWithRaw(9786001467), // 2.27848102041267 fp.CreateWithRaw(9786638875), // 2.27862942859353 fp.CreateWithRaw(9787276353), // 2.27877785298597 fp.CreateWithRaw(9787913900), // 2.27892629359281 fp.CreateWithRaw(9788551518), // 2.27907475041688 fp.CreateWithRaw(9789189205), // 2.279223223461 fp.CreateWithRaw(9789826961), // 2.27937171272802 fp.CreateWithRaw(9790464787), // 2.27952021822075 fp.CreateWithRaw(9791102683), // 2.27966873994202 fp.CreateWithRaw(9791740649), // 2.27981727789468 fp.CreateWithRaw(9792378684), // 2.27996583208154 fp.CreateWithRaw(9793016789), // 2.28011440250545 fp.CreateWithRaw(9793654964), // 2.28026298916923 fp.CreateWithRaw(9794293209), // 2.28041159207572 fp.CreateWithRaw(9794931523), // 2.28056021122775 fp.CreateWithRaw(9795569907), // 2.28070884662816 fp.CreateWithRaw(9796208361), // 2.28085749827979 fp.CreateWithRaw(9796846885), // 2.28100616618546 fp.CreateWithRaw(9797485479), // 2.28115485034802 fp.CreateWithRaw(9798124142), // 2.2813035507703 fp.CreateWithRaw(9798762876), // 2.28145226745515 fp.CreateWithRaw(9799401679), // 2.28160100040539 fp.CreateWithRaw(9800040552), // 2.28174974962388 fp.CreateWithRaw(9800679495), // 2.28189851511345 fp.CreateWithRaw(9801318508), // 2.28204729687693 fp.CreateWithRaw(9801957590), // 2.28219609491719 fp.CreateWithRaw(9802596743), // 2.28234490923704 fp.CreateWithRaw(9803235965), // 2.28249373983935 fp.CreateWithRaw(9803875258), // 2.28264258672695 fp.CreateWithRaw(9804514620), // 2.28279144990268 fp.CreateWithRaw(9805154053), // 2.28294032936939 fp.CreateWithRaw(9805793555), // 2.28308922512993 fp.CreateWithRaw(9806433128), // 2.28323813718714 fp.CreateWithRaw(9807072770), // 2.28338706554387 fp.CreateWithRaw(9807712483), // 2.28353601020296 fp.CreateWithRaw(9808352265), // 2.28368497116727 fp.CreateWithRaw(9808992118), // 2.28383394843965 fp.CreateWithRaw(9809632040), // 2.28398294202293 fp.CreateWithRaw(9810272033), // 2.28413195191998 fp.CreateWithRaw(9810912095), // 2.28428097813364 fp.CreateWithRaw(9811552228), // 2.28443002066677 fp.CreateWithRaw(9812192431), // 2.28457907952221 fp.CreateWithRaw(9812832704), // 2.28472815470282 fp.CreateWithRaw(9813473047), // 2.28487724621146 fp.CreateWithRaw(9814113461), // 2.28502635405097 fp.CreateWithRaw(9814753944), // 2.28517547822422 fp.CreateWithRaw(9815394498), // 2.28532461873405 fp.CreateWithRaw(9816035121), // 2.28547377558332 fp.CreateWithRaw(9816675815), // 2.2856229487749 fp.CreateWithRaw(9817316580), // 2.28577213831163 fp.CreateWithRaw(9817957414), // 2.28592134419638 fp.CreateWithRaw(9818598319), // 2.286070566432 fp.CreateWithRaw(9819239294), // 2.28621980502135 fp.CreateWithRaw(9819880339), // 2.2863690599673 fp.CreateWithRaw(9820521454), // 2.2865183312727 fp.CreateWithRaw(9821162640), // 2.28666761894042 fp.CreateWithRaw(9821803896), // 2.28681692297332 fp.CreateWithRaw(9822445222), // 2.28696624337425 fp.CreateWithRaw(9823086618), // 2.28711558014609 fp.CreateWithRaw(9823728085), // 2.2872649332917 fp.CreateWithRaw(9824369622), // 2.28741430281394 fp.CreateWithRaw(9825011230), // 2.28756368871567 fp.CreateWithRaw(9825652908), // 2.28771309099977 fp.CreateWithRaw(9826294656), // 2.28786250966911 fp.CreateWithRaw(9826936475), // 2.28801194472653 fp.CreateWithRaw(9827578364), // 2.28816139617493 fp.CreateWithRaw(9828220324), // 2.28831086401716 fp.CreateWithRaw(9828862353), // 2.28846034825609 fp.CreateWithRaw(9829504454), // 2.28860984889459 fp.CreateWithRaw(9830146625), // 2.28875936593555 fp.CreateWithRaw(9830788866), // 2.28890889938181 fp.CreateWithRaw(9831431178), // 2.28905844923626 fp.CreateWithRaw(9832073560), // 2.28920801550178 fp.CreateWithRaw(9832716013), // 2.28935759818123 fp.CreateWithRaw(9833358536), // 2.28950719727749 fp.CreateWithRaw(9834001130), // 2.28965681279342 fp.CreateWithRaw(9834643794), // 2.28980644473192 fp.CreateWithRaw(9835286529), // 2.28995609309585 fp.CreateWithRaw(9835929334), // 2.29010575788809 fp.CreateWithRaw(9836572210), // 2.29025543911152 fp.CreateWithRaw(9837215157), // 2.29040513676902 fp.CreateWithRaw(9837858174), // 2.29055485086346 fp.CreateWithRaw(9838501261), // 2.29070458139773 fp.CreateWithRaw(9839144420), // 2.29085432837469 fp.CreateWithRaw(9839787649), // 2.29100409179725 fp.CreateWithRaw(9840430948), // 2.29115387166827 fp.CreateWithRaw(9841074319), // 2.29130366799064 fp.CreateWithRaw(9841717760), // 2.29145348076724 fp.CreateWithRaw(9842361271), // 2.29160331000095 fp.CreateWithRaw(9843004854), // 2.29175315569467 fp.CreateWithRaw(9843648507), // 2.29190301785127 fp.CreateWithRaw(9844292231), // 2.29205289647363 fp.CreateWithRaw(9844936025), // 2.29220279156465 fp.CreateWithRaw(9845579890), // 2.29235270312722 fp.CreateWithRaw(9846223826), // 2.29250263116421 fp.CreateWithRaw(9846867833), // 2.29265257567852 fp.CreateWithRaw(9847511911), // 2.29280253667303 fp.CreateWithRaw(9848156059), // 2.29295251415064 fp.CreateWithRaw(9848800278), // 2.29310250811424 fp.CreateWithRaw(9849444568), // 2.29325251856671 fp.CreateWithRaw(9850088929), // 2.29340254551095 fp.CreateWithRaw(9850733361), // 2.29355258894985 fp.CreateWithRaw(9851377863), // 2.29370264888631 fp.CreateWithRaw(9852022437), // 2.29385272532321 fp.CreateWithRaw(9852667081), // 2.29400281826345 fp.CreateWithRaw(9853311796), // 2.29415292770992 fp.CreateWithRaw(9853956582), // 2.29430305366553 fp.CreateWithRaw(9854601439), // 2.29445319613316 fp.CreateWithRaw(9855246367), // 2.29460335511572 fp.CreateWithRaw(9855891366), // 2.2947535306161 fp.CreateWithRaw(9856536436), // 2.2949037226372 fp.CreateWithRaw(9857181576), // 2.29505393118192 fp.CreateWithRaw(9857826788), // 2.29520415625315 fp.CreateWithRaw(9858472071), // 2.29535439785381 fp.CreateWithRaw(9859117425), // 2.29550465598678 fp.CreateWithRaw(9859762850), // 2.29565493065498 fp.CreateWithRaw(9860408345), // 2.2958052218613 fp.CreateWithRaw(9861053912), // 2.29595552960864 fp.CreateWithRaw(9861699550), // 2.29610585389991 fp.CreateWithRaw(9862345259), // 2.29625619473802 fp.CreateWithRaw(9862991039), // 2.29640655212587 fp.CreateWithRaw(9863636890), // 2.29655692606636 fp.CreateWithRaw(9864282813), // 2.29670731656241 fp.CreateWithRaw(9864928806), // 2.29685772361691 fp.CreateWithRaw(9865574871), // 2.29700814723278 fp.CreateWithRaw(9866221006), // 2.29715858741292 fp.CreateWithRaw(9866867213), // 2.29730904416024 fp.CreateWithRaw(9867513491), // 2.29745951747766 fp.CreateWithRaw(9868159840), // 2.29761000736808 fp.CreateWithRaw(9868806260), // 2.29776051383442 fp.CreateWithRaw(9869452752), // 2.29791103687958 fp.CreateWithRaw(9870099315), // 2.29806157650648 fp.CreateWithRaw(9870745949), // 2.29821213271804 fp.CreateWithRaw(9871392654), // 2.29836270551716 fp.CreateWithRaw(9872039431), // 2.29851329490676 fp.CreateWithRaw(9872686278), // 2.29866390088975 fp.CreateWithRaw(9873333197), // 2.29881452346906 fp.CreateWithRaw(9873980188), // 2.29896516264759 fp.CreateWithRaw(9874627249), // 2.29911581842827 fp.CreateWithRaw(9875274382), // 2.29926649081401 fp.CreateWithRaw(9875921587), // 2.29941717980773 fp.CreateWithRaw(9876568862), // 2.29956788541236 fp.CreateWithRaw(9877216209), // 2.2997186076308 fp.CreateWithRaw(9877863628), // 2.29986934646599 fp.CreateWithRaw(9878511117), // 2.30002010192084 fp.CreateWithRaw(9879158679), // 2.30017087399827 fp.CreateWithRaw(9879806311), // 2.30032166270121 fp.CreateWithRaw(9880454015), // 2.30047246803258 fp.CreateWithRaw(9881101790), // 2.30062328999531 fp.CreateWithRaw(9881749637), // 2.30077412859231 fp.CreateWithRaw(9882397556), // 2.30092498382652 fp.CreateWithRaw(9883045545), // 2.30107585570086 fp.CreateWithRaw(9883693607), // 2.30122674421826 fp.CreateWithRaw(9884341739), // 2.30137764938164 fp.CreateWithRaw(9884989944), // 2.30152857119394 fp.CreateWithRaw(9885638219), // 2.30167950965808 fp.CreateWithRaw(9886286567), // 2.30183046477699 fp.CreateWithRaw(9886934985), // 2.3019814365536 fp.CreateWithRaw(9887583476), // 2.30213242499084 fp.CreateWithRaw(9888232038), // 2.30228343009165 fp.CreateWithRaw(9888880671), // 2.30243445185896 fp.CreateWithRaw(9889529377), // 2.30258549029569 fp.CreateWithRaw(9890178153), // 2.30273654540479 fp.CreateWithRaw(9890827002), // 2.30288761718919 fp.CreateWithRaw(9891475922), // 2.30303870565181 fp.CreateWithRaw(9892124913), // 2.30318981079561 fp.CreateWithRaw(9892773977), // 2.30334093262351 fp.CreateWithRaw(9893423112), // 2.30349207113845 fp.CreateWithRaw(9894072318), // 2.30364322634337 fp.CreateWithRaw(9894721597), // 2.3037943982412 fp.CreateWithRaw(9895370947), // 2.3039455868349 fp.CreateWithRaw(9896020369), // 2.30409679212739 fp.CreateWithRaw(9896669862), // 2.30424801412162 fp.CreateWithRaw(9897319427), // 2.30439925282052 fp.CreateWithRaw(9897969064), // 2.30455050822705 fp.CreateWithRaw(9898618773), // 2.30470178034413 fp.CreateWithRaw(9899268554), // 2.30485306917473 fp.CreateWithRaw(9899918406), // 2.30500437472177 fp.CreateWithRaw(9900568330), // 2.30515569698821 fp.CreateWithRaw(9901218326), // 2.30530703597699 fp.CreateWithRaw(9901868394), // 2.30545839169105 fp.CreateWithRaw(9902518534), // 2.30560976413334 fp.CreateWithRaw(9903168745), // 2.30576115330682 fp.CreateWithRaw(9903819029), // 2.30591255921442 fp.CreateWithRaw(9904469384), // 2.3060639818591 fp.CreateWithRaw(9905119811), // 2.30621542124381 fp.CreateWithRaw(9905770310), // 2.30636687737149 fp.CreateWithRaw(9906420881), // 2.3065183502451 fp.CreateWithRaw(9907071524), // 2.30666983986758 fp.CreateWithRaw(9907722239), // 2.3068213462419 fp.CreateWithRaw(9908373026), // 2.306972869371 fp.CreateWithRaw(9909023885), // 2.30712440925784 fp.CreateWithRaw(9909674816), // 2.30727596590537 fp.CreateWithRaw(9910325819), // 2.30742753931654 fp.CreateWithRaw(9910976894), // 2.30757912949432 fp.CreateWithRaw(9911628040), // 2.30773073644166 fp.CreateWithRaw(9912279259), // 2.30788236016151 fp.CreateWithRaw(9912930550), // 2.30803400065683 fp.CreateWithRaw(9913581913), // 2.30818565793059 fp.CreateWithRaw(9914233349), // 2.30833733198574 fp.CreateWithRaw(9914884856), // 2.30848902282524 fp.CreateWithRaw(9915536435), // 2.30864073045205 fp.CreateWithRaw(9916188086), // 2.30879245486913 fp.CreateWithRaw(9916839810), // 2.30894419607945 fp.CreateWithRaw(9917491606), // 2.30909595408596 fp.CreateWithRaw(9918143473), // 2.30924772889163 fp.CreateWithRaw(9918795413), // 2.30939952049943 fp.CreateWithRaw(9919447426), // 2.30955132891232 fp.CreateWithRaw(9920099510), // 2.30970315413326 fp.CreateWithRaw(9920751667), // 2.30985499616522 fp.CreateWithRaw(9921403895), // 2.31000685501117 fp.CreateWithRaw(9922056196), // 2.31015873067407 fp.CreateWithRaw(9922708570), // 2.3103106231569 fp.CreateWithRaw(9923361015), // 2.31046253246262 fp.CreateWithRaw(9924013533), // 2.31061445859419 fp.CreateWithRaw(9924666123), // 2.3107664015546 fp.CreateWithRaw(9925318785), // 2.31091836134682 fp.CreateWithRaw(9925971520), // 2.3110703379738 fp.CreateWithRaw(9926624327), // 2.31122233143854 fp.CreateWithRaw(9927277206), // 2.31137434174399 fp.CreateWithRaw(9927930158), // 2.31152636889314 fp.CreateWithRaw(9928583182), // 2.31167841288895 fp.CreateWithRaw(9929236278), // 2.31183047373441 fp.CreateWithRaw(9929889447), // 2.31198255143248 fp.CreateWithRaw(9930542688), // 2.31213464598615 fp.CreateWithRaw(9931196001), // 2.31228675739839 fp.CreateWithRaw(9931849387), // 2.31243888567219 fp.CreateWithRaw(9932502846), // 2.31259103081051 fp.CreateWithRaw(9933156377), // 2.31274319281634 fp.CreateWithRaw(9933809980), // 2.31289537169266 fp.CreateWithRaw(9934463656), // 2.31304756744244 fp.CreateWithRaw(9935117404), // 2.31319978006868 fp.CreateWithRaw(9935771225), // 2.31335200957435 fp.CreateWithRaw(9936425118), // 2.31350425596244 fp.CreateWithRaw(9937079084), // 2.31365651923592 fp.CreateWithRaw(9937733122), // 2.31380879939779 fp.CreateWithRaw(9938387233), // 2.31396109645102 fp.CreateWithRaw(9939041416), // 2.31411341039861 fp.CreateWithRaw(9939695672), // 2.31426574124354 fp.CreateWithRaw(9940350001), // 2.3144180889888 fp.CreateWithRaw(9941004402), // 2.31457045363737 fp.CreateWithRaw(9941658876), // 2.31472283519225 fp.CreateWithRaw(9942313422), // 2.31487523365641 fp.CreateWithRaw(9942968041), // 2.31502764903286 fp.CreateWithRaw(9943622733), // 2.31518008132459 fp.CreateWithRaw(9944277498), // 2.31533253053457 fp.CreateWithRaw(9944932335), // 2.31548499666582 fp.CreateWithRaw(9945587244), // 2.31563747972131 fp.CreateWithRaw(9946242227), // 2.31578997970404 fp.CreateWithRaw(9946897282), // 2.31594249661701 fp.CreateWithRaw(9947552410), // 2.31609503046321 fp.CreateWithRaw(9948207610), // 2.31624758124564 fp.CreateWithRaw(9948862884), // 2.31640014896728 fp.CreateWithRaw(9949518230), // 2.31655273363115 fp.CreateWithRaw(9950173649), // 2.31670533524024 fp.CreateWithRaw(9950829141), // 2.31685795379754 fp.CreateWithRaw(9951484705), // 2.31701058930605 fp.CreateWithRaw(9952140342), // 2.31716324176878 fp.CreateWithRaw(9952796053), // 2.31731591118872 fp.CreateWithRaw(9953451836), // 2.31746859756888 fp.CreateWithRaw(9954107691), // 2.31762130091226 fp.CreateWithRaw(9954763620), // 2.31777402122185 fp.CreateWithRaw(9955419622), // 2.31792675850067 fp.CreateWithRaw(9956075696), // 2.31807951275171 fp.CreateWithRaw(9956731844), // 2.31823228397799 fp.CreateWithRaw(9957388064), // 2.3183850721825 fp.CreateWithRaw(9958044357), // 2.31853787736826 fp.CreateWithRaw(9958700724), // 2.31869069953827 fp.CreateWithRaw(9959357163), // 2.31884353869553 fp.CreateWithRaw(9960013675), // 2.31899639484306 fp.CreateWithRaw(9960670260), // 2.31914926798386 fp.CreateWithRaw(9961326918), // 2.31930215812094 fp.CreateWithRaw(9961983649), // 2.31945506525732 fp.CreateWithRaw(9962640453), // 2.31960798939601 fp.CreateWithRaw(9963297331), // 2.31976093054001 fp.CreateWithRaw(9963954281), // 2.31991388869234 fp.CreateWithRaw(9964611304), // 2.32006686385602 fp.CreateWithRaw(9965268401), // 2.32021985603405 fp.CreateWithRaw(9965925570), // 2.32037286522945 fp.CreateWithRaw(9966582813), // 2.32052589144524 fp.CreateWithRaw(9967240128), // 2.32067893468443 fp.CreateWithRaw(9967897517), // 2.32083199495003 fp.CreateWithRaw(9968554979), // 2.32098507224508 fp.CreateWithRaw(9969212514), // 2.32113816657257 fp.CreateWithRaw(9969870123), // 2.32129127793555 fp.CreateWithRaw(9970527804), // 2.32144440633701 fp.CreateWithRaw(9971185559), // 2.32159755177999 fp.CreateWithRaw(9971843387), // 2.3217507142675 fp.CreateWithRaw(9972501288), // 2.32190389380256 fp.CreateWithRaw(9973159262), // 2.3220570903882 fp.CreateWithRaw(9973817310), // 2.32221030402745 fp.CreateWithRaw(9974475431), // 2.32236353472332 fp.CreateWithRaw(9975133625), // 2.32251678247883 fp.CreateWithRaw(9975791892), // 2.32267004729703 fp.CreateWithRaw(9976450233), // 2.32282332918092 fp.CreateWithRaw(9977108647), // 2.32297662813354 fp.CreateWithRaw(9977767134), // 2.32312994415791 fp.CreateWithRaw(9978425695), // 2.32328327725707 fp.CreateWithRaw(9979084329), // 2.32343662743403 fp.CreateWithRaw(9979743036), // 2.32358999469184 fp.CreateWithRaw(9980401817), // 2.32374337903352 fp.CreateWithRaw(9981060671), // 2.3238967804621 fp.CreateWithRaw(9981719598), // 2.32405019898061 fp.CreateWithRaw(9982378599), // 2.32420363459209 fp.CreateWithRaw(9983037674), // 2.32435708729957 fp.CreateWithRaw(9983696821), // 2.32451055710608 fp.CreateWithRaw(9984356043), // 2.32466404401466 fp.CreateWithRaw(9985015337), // 2.32481754802834 fp.CreateWithRaw(9985674706), // 2.32497106915016 fp.CreateWithRaw(9986334147), // 2.32512460738315 fp.CreateWithRaw(9986993663), // 2.32527816273036 fp.CreateWithRaw(9987653251), // 2.32543173519482 fp.CreateWithRaw(9988312913), // 2.32558532477956 fp.CreateWithRaw(9988972649), // 2.32573893148764 fp.CreateWithRaw(9989632459), // 2.32589255532208 fp.CreateWithRaw(9990292342), // 2.32604619628594 fp.CreateWithRaw(9990952298), // 2.32619985438224 fp.CreateWithRaw(9991612328), // 2.32635352961404 fp.CreateWithRaw(9992272432), // 2.32650722198438 fp.CreateWithRaw(9992932609), // 2.3266609314963 fp.CreateWithRaw(9993592860), // 2.32681465815284 fp.CreateWithRaw(9994253185), // 2.32696840195705 fp.CreateWithRaw(9994913583), // 2.32712216291198 fp.CreateWithRaw(9995574055), // 2.32727594102068 fp.CreateWithRaw(9996234601), // 2.32742973628618 fp.CreateWithRaw(9996895220), // 2.32758354871155 fp.CreateWithRaw(9997555913), // 2.32773737829982 fp.CreateWithRaw(9998216680), // 2.32789122505405 fp.CreateWithRaw(9998877520), // 2.32804508897728 fp.CreateWithRaw(9999538435), // 2.32819897007258 fp.CreateWithRaw(10000199423), // 2.32835286834298 fp.CreateWithRaw(10000860484), // 2.32850678379155 fp.CreateWithRaw(10001521620), // 2.32866071642134 fp.CreateWithRaw(10002182829), // 2.32881466623539 fp.CreateWithRaw(10002844113), // 2.32896863323677 fp.CreateWithRaw(10003505470), // 2.32912261742853 fp.CreateWithRaw(10004166901), // 2.32927661881373 fp.CreateWithRaw(10004828405), // 2.32943063739542 fp.CreateWithRaw(10005489984), // 2.32958467317666 fp.CreateWithRaw(10006151637), // 2.3297387261605 fp.CreateWithRaw(10006813363), // 2.32989279635002 fp.CreateWithRaw(10007475163), // 2.33004688374826 fp.CreateWithRaw(10008137038), // 2.33020098835829 fp.CreateWithRaw(10008798986), // 2.33035511018317 fp.CreateWithRaw(10009461008), // 2.33050924922596 fp.CreateWithRaw(10010123104), // 2.33066340548972 fp.CreateWithRaw(10010785274), // 2.33081757897752 fp.CreateWithRaw(10011447518), // 2.33097176969242 fp.CreateWithRaw(10012109836), // 2.33112597763749 fp.CreateWithRaw(10012772228), // 2.33128020281578 fp.CreateWithRaw(10013434695), // 2.33143444523037 fp.CreateWithRaw(10014097235), // 2.33158870488433 fp.CreateWithRaw(10014759849), // 2.33174298178072 fp.CreateWithRaw(10015422537), // 2.33189727592261 fp.CreateWithRaw(10016085300), // 2.33205158731306 fp.CreateWithRaw(10016748136), // 2.33220591595516 fp.CreateWithRaw(10017411047), // 2.33236026185196 fp.CreateWithRaw(10018074031), // 2.33251462500655 fp.CreateWithRaw(10018737090), // 2.33266900542199 fp.CreateWithRaw(10019400223), // 2.33282340310135 fp.CreateWithRaw(10020063430), // 2.33297781804771 fp.CreateWithRaw(10020726712), // 2.33313225026415 fp.CreateWithRaw(10021390067), // 2.33328669975373 fp.CreateWithRaw(10022053497), // 2.33344116651954 fp.CreateWithRaw(10022717001), // 2.33359565056464 fp.CreateWithRaw(10023380579), // 2.33375015189213 fp.CreateWithRaw(10024044231), // 2.33390467050506 fp.CreateWithRaw(10024707958), // 2.33405920640653 fp.CreateWithRaw(10025371759), // 2.33421375959962 fp.CreateWithRaw(10026035634), // 2.33436833008739 fp.CreateWithRaw(10026699584), // 2.33452291787294 fp.CreateWithRaw(10027363607), // 2.33467752295935 fp.CreateWithRaw(10028027705), // 2.33483214534969 fp.CreateWithRaw(10028691878), // 2.33498678504705 fp.CreateWithRaw(10029356125), // 2.33514144205452 fp.CreateWithRaw(10030020446), // 2.33529611637517 fp.CreateWithRaw(10030684841), // 2.3354508080121 fp.CreateWithRaw(10031349311), // 2.33560551696838 fp.CreateWithRaw(10032013856), // 2.33576024324711 fp.CreateWithRaw(10032678474), // 2.33591498685137 fp.CreateWithRaw(10033343167), // 2.33606974778426 fp.CreateWithRaw(10034007935), // 2.33622452604885 fp.CreateWithRaw(10034672777), // 2.33637932164825 fp.CreateWithRaw(10035337694), // 2.33653413458553 fp.CreateWithRaw(10036002685), // 2.33668896486379 fp.CreateWithRaw(10036667750), // 2.33684381248612 fp.CreateWithRaw(10037332890), // 2.33699867745562 fp.CreateWithRaw(10037998104), // 2.33715355977538 fp.CreateWithRaw(10038663393), // 2.33730845944849 fp.CreateWithRaw(10039328757), // 2.33746337647804 fp.CreateWithRaw(10039994195), // 2.33761831086714 fp.CreateWithRaw(10040659708), // 2.33777326261887 fp.CreateWithRaw(10041325295), // 2.33792823173634 fp.CreateWithRaw(10041990957), // 2.33808321822264 fp.CreateWithRaw(10042656694), // 2.33823822208087 fp.CreateWithRaw(10043322505), // 2.33839324331413 fp.CreateWithRaw(10043988390), // 2.33854828192552 fp.CreateWithRaw(10044654351), // 2.33870333791814 fp.CreateWithRaw(10045320386), // 2.33885841129509 fp.CreateWithRaw(10045986496), // 2.33901350205947 fp.CreateWithRaw(10046652680), // 2.33916861021439 fp.CreateWithRaw(10047318939), // 2.33932373576294 fp.CreateWithRaw(10047985273), // 2.33947887870824 fp.CreateWithRaw(10048651682), // 2.33963403905339 fp.CreateWithRaw(10049318165), // 2.33978921680149 fp.CreateWithRaw(10049984723), // 2.33994441195565 fp.CreateWithRaw(10050651356), // 2.34009962451898 fp.CreateWithRaw(10051318064), // 2.34025485449458 fp.CreateWithRaw(10051984846), // 2.34041010188557 fp.CreateWithRaw(10052651704), // 2.34056536669505 fp.CreateWithRaw(10053318636), // 2.34072064892613 fp.CreateWithRaw(10053985643), // 2.34087594858193 fp.CreateWithRaw(10054652724), // 2.34103126566555 fp.CreateWithRaw(10055319881), // 2.34118660018011 fp.CreateWithRaw(10055987113), // 2.34134195212873 fp.CreateWithRaw(10056654419), // 2.3414973215145 fp.CreateWithRaw(10057321800), // 2.34165270834056 fp.CreateWithRaw(10057989257), // 2.34180811261001 fp.CreateWithRaw(10058656788), // 2.34196353432597 fp.CreateWithRaw(10059324394), // 2.34211897349155 fp.CreateWithRaw(10059992075), // 2.34227443010989 fp.CreateWithRaw(10060659831), // 2.34242990418408 fp.CreateWithRaw(10061327662), // 2.34258539571726 fp.CreateWithRaw(10061995568), // 2.34274090471253 fp.CreateWithRaw(10062663549), // 2.34289643117303 fp.CreateWithRaw(10063331605), // 2.34305197510187 fp.CreateWithRaw(10063999737), // 2.34320753650218 fp.CreateWithRaw(10064667943), // 2.34336311537708 fp.CreateWithRaw(10065336224), // 2.34351871172968 fp.CreateWithRaw(10066004580), // 2.34367432556312 fp.CreateWithRaw(10066673012), // 2.34382995688052 fp.CreateWithRaw(10067341518), // 2.34398560568501 fp.CreateWithRaw(10068010100), // 2.34414127197971 fp.CreateWithRaw(10068678757), // 2.34429695576774 fp.CreateWithRaw(10069347489), // 2.34445265705225 fp.CreateWithRaw(10070016296), // 2.34460837583634 fp.CreateWithRaw(10070685178), // 2.34476411212317 fp.CreateWithRaw(10071354135), // 2.34491986591585 fp.CreateWithRaw(10072023168), // 2.34507563721751 fp.CreateWithRaw(10072692276), // 2.34523142603129 fp.CreateWithRaw(10073361459), // 2.34538723236033 fp.CreateWithRaw(10074030717), // 2.34554305620774 fp.CreateWithRaw(10074700051), // 2.34569889757667 fp.CreateWithRaw(10075369460), // 2.34585475647025 fp.CreateWithRaw(10076038944), // 2.34601063289162 fp.CreateWithRaw(10076708503), // 2.34616652684391 fp.CreateWithRaw(10077378138), // 2.34632243833026 fp.CreateWithRaw(10078047848), // 2.34647836735381 fp.CreateWithRaw(10078717633), // 2.34663431391769 fp.CreateWithRaw(10079387494), // 2.34679027802504 fp.CreateWithRaw(10080057430), // 2.34694625967901 fp.CreateWithRaw(10080727442), // 2.34710225888274 fp.CreateWithRaw(10081397529), // 2.34725827563935 fp.CreateWithRaw(10082067691), // 2.34741430995201 fp.CreateWithRaw(10082737929), // 2.34757036182385 fp.CreateWithRaw(10083408242), // 2.34772643125801 fp.CreateWithRaw(10084078630), // 2.34788251825763 fp.CreateWithRaw(10084749094), // 2.34803862282588 fp.CreateWithRaw(10085419634), // 2.34819474496588 fp.CreateWithRaw(10086090249), // 2.34835088468078 fp.CreateWithRaw(10086760939), // 2.34850704197374 fp.CreateWithRaw(10087431705), // 2.3486632168479 fp.CreateWithRaw(10088102547), // 2.34881940930641 fp.CreateWithRaw(10088773464), // 2.34897561935241 fp.CreateWithRaw(10089444456), // 2.34913184698907 fp.CreateWithRaw(10090115524), // 2.34928809221952 fp.CreateWithRaw(10090786668), // 2.34944435504693 fp.CreateWithRaw(10091457888), // 2.34960063547444 fp.CreateWithRaw(10092129182), // 2.34975693350521 fp.CreateWithRaw(10092800553), // 2.34991324914239 fp.CreateWithRaw(10093471999), // 2.35006958238914 fp.CreateWithRaw(10094143521), // 2.35022593324861 fp.CreateWithRaw(10094815119), // 2.35038230172395 fp.CreateWithRaw(10095486792), // 2.35053868781834 fp.CreateWithRaw(10096158541), // 2.35069509153491 fp.CreateWithRaw(10096830365), // 2.35085151287684 fp.CreateWithRaw(10097502265), // 2.35100795184727 fp.CreateWithRaw(10098174241), // 2.35116440844938 fp.CreateWithRaw(10098846293), // 2.35132088268632 fp.CreateWithRaw(10099518421), // 2.35147737456125 fp.CreateWithRaw(10100190624), // 2.35163388407733 fp.CreateWithRaw(10100862903), // 2.35179041123774 fp.CreateWithRaw(10101535258), // 2.35194695604562 fp.CreateWithRaw(10102207688), // 2.35210351850416 fp.CreateWithRaw(10102880195), // 2.3522600986165 fp.CreateWithRaw(10103552777), // 2.35241669638582 fp.CreateWithRaw(10104225435), // 2.35257331181529 fp.CreateWithRaw(10104898169), // 2.35272994490807 fp.CreateWithRaw(10105570979), // 2.35288659566733 fp.CreateWithRaw(10106243865), // 2.35304326409624 fp.CreateWithRaw(10106916827), // 2.35319995019797 fp.CreateWithRaw(10107589864), // 2.35335665397568 fp.CreateWithRaw(10108262978), // 2.35351337543256 fp.CreateWithRaw(10108936167), // 2.35367011457178 fp.CreateWithRaw(10109609433), // 2.3538268713965 fp.CreateWithRaw(10110282774), // 2.35398364590989 fp.CreateWithRaw(10110956191), // 2.35414043811515 fp.CreateWithRaw(10111629685), // 2.35429724801543 fp.CreateWithRaw(10112303254), // 2.35445407561391 fp.CreateWithRaw(10112976900), // 2.35461092091378 fp.CreateWithRaw(10113650621), // 2.35476778391821 fp.CreateWithRaw(10114324419), // 2.35492466463037 fp.CreateWithRaw(10114998292), // 2.35508156305346 fp.CreateWithRaw(10115672242), // 2.35523847919063 fp.CreateWithRaw(10116346268), // 2.35539541304508 fp.CreateWithRaw(10117020370), // 2.35555236462 fp.CreateWithRaw(10117694548), // 2.35570933391855 fp.CreateWithRaw(10118368802), // 2.35586632094392 fp.CreateWithRaw(10119043132), // 2.35602332569929 fp.CreateWithRaw(10119717538), // 2.35618034818786 fp.CreateWithRaw(10120392021), // 2.3563373884128 fp.CreateWithRaw(10121066580), // 2.3564944463773 fp.CreateWithRaw(10121741215), // 2.35665152208455 fp.CreateWithRaw(10122415926), // 2.35680861553774 fp.CreateWithRaw(10123090714), // 2.35696572674004 fp.CreateWithRaw(10123765577), // 2.35712285569466 fp.CreateWithRaw(10124440517), // 2.35728000240477 fp.CreateWithRaw(10125115534), // 2.35743716687358 fp.CreateWithRaw(10125790626), // 2.35759434910427 fp.CreateWithRaw(10126465795), // 2.35775154910003 fp.CreateWithRaw(10127141040), // 2.35790876686406 fp.CreateWithRaw(10127816362), // 2.35806600239955 fp.CreateWithRaw(10128491759), // 2.3582232557097 fp.CreateWithRaw(10129167234), // 2.35838052679769 fp.CreateWithRaw(10129842784), // 2.35853781566672 fp.CreateWithRaw(10130518411), // 2.35869512232 fp.CreateWithRaw(10131194114), // 2.35885244676071 fp.CreateWithRaw(10131869894), // 2.35900978899206 fp.CreateWithRaw(10132545750), // 2.35916714901725 fp.CreateWithRaw(10133221683), // 2.35932452683947 fp.CreateWithRaw(10133897692), // 2.35948192246192 fp.CreateWithRaw(10134573777), // 2.35963933588781 fp.CreateWithRaw(10135249939), // 2.35979676712033 fp.CreateWithRaw(10135926178), // 2.3599542161627 fp.CreateWithRaw(10136602493), // 2.3601116830181 fp.CreateWithRaw(10137278884), // 2.36026916768976 fp.CreateWithRaw(10137955353), // 2.36042667018086 fp.CreateWithRaw(10138631897), // 2.36058419049462 fp.CreateWithRaw(10139308518), // 2.36074172863425 fp.CreateWithRaw(10139985216), // 2.36089928460295 fp.CreateWithRaw(10140661990), // 2.36105685840392 fp.CreateWithRaw(10141338841), // 2.36121445004038 fp.CreateWithRaw(10142015769), // 2.36137205951554 fp.CreateWithRaw(10142692773), // 2.36152968683261 fp.CreateWithRaw(10143369854), // 2.36168733199479 fp.CreateWithRaw(10144047011), // 2.36184499500531 fp.CreateWithRaw(10144724245), // 2.36200267586736 fp.CreateWithRaw(10145401556), // 2.36216037458417 fp.CreateWithRaw(10146078944), // 2.36231809115895 fp.CreateWithRaw(10146756408), // 2.36247582559491 fp.CreateWithRaw(10147433949), // 2.36263357789528 fp.CreateWithRaw(10148111567), // 2.36279134806326 fp.CreateWithRaw(10148789261), // 2.36294913610207 fp.CreateWithRaw(10149467032), // 2.36310694201493 fp.CreateWithRaw(10150144880), // 2.36326476580506 fp.CreateWithRaw(10150822805), // 2.36342260747568 fp.CreateWithRaw(10151500807), // 2.36358046703002 fp.CreateWithRaw(10152178885), // 2.36373834447128 fp.CreateWithRaw(10152857041), // 2.36389623980269 fp.CreateWithRaw(10153535273), // 2.36405415302748 fp.CreateWithRaw(10154213582), // 2.36421208414886 fp.CreateWithRaw(10154891968), // 2.36437003317007 fp.CreateWithRaw(10155570430), // 2.36452800009432 fp.CreateWithRaw(10156248970), // 2.36468598492485 fp.CreateWithRaw(10156927587), // 2.36484398766487 fp.CreateWithRaw(10157606280), // 2.36500200831762 fp.CreateWithRaw(10158285051), // 2.36516004688632 fp.CreateWithRaw(10158963898), // 2.36531810337421 fp.CreateWithRaw(10159642823), // 2.3654761777845 fp.CreateWithRaw(10160321824), // 2.36563427012044 fp.CreateWithRaw(10161000902), // 2.36579238038525 fp.CreateWithRaw(10161680058), // 2.36595050858217 fp.CreateWithRaw(10162359290), // 2.36610865471442 fp.CreateWithRaw(10163038600), // 2.36626681878525 fp.CreateWithRaw(10163717986), // 2.36642500079787 fp.CreateWithRaw(10164397450), // 2.36658320075554 fp.CreateWithRaw(10165076991), // 2.36674141866148 fp.CreateWithRaw(10165756609), // 2.36689965451894 fp.CreateWithRaw(10166436304), // 2.36705790833114 fp.CreateWithRaw(10167116076), // 2.36721618010133 fp.CreateWithRaw(10167795925), // 2.36737446983274 fp.CreateWithRaw(10168475851), // 2.36753277752862 fp.CreateWithRaw(10169155855), // 2.36769110319221 fp.CreateWithRaw(10169835935), // 2.36784944682674 fp.CreateWithRaw(10170516093), // 2.36800780843546 fp.CreateWithRaw(10171196329), // 2.36816618802161 fp.CreateWithRaw(10171876641), // 2.36832458558844 fp.CreateWithRaw(10172557031), // 2.36848300113918 fp.CreateWithRaw(10173237497), // 2.36864143467709 fp.CreateWithRaw(10173918042), // 2.3687998862054 fp.CreateWithRaw(10174598663), // 2.36895835572738 fp.CreateWithRaw(10175279362), // 2.36911684324625 fp.CreateWithRaw(10175960138), // 2.36927534876528 fp.CreateWithRaw(10176640991), // 2.3694338722877 fp.CreateWithRaw(10177321922), // 2.36959241381678 fp.CreateWithRaw(10178002930), // 2.36975097335575 fp.CreateWithRaw(10178684015), // 2.36990955090788 fp.CreateWithRaw(10179365178), // 2.37006814647641 fp.CreateWithRaw(10180046418), // 2.3702267600646 fp.CreateWithRaw(10180727736), // 2.37038539167569 fp.CreateWithRaw(10181409131), // 2.37054404131295 fp.CreateWithRaw(10182090603), // 2.37070270897963 fp.CreateWithRaw(10182772153), // 2.37086139467898 fp.CreateWithRaw(10183453780), // 2.37102009841427 fp.CreateWithRaw(10184135485), // 2.37117882018874 fp.CreateWithRaw(10184817268), // 2.37133756000566 fp.CreateWithRaw(10185499127), // 2.37149631786829 fp.CreateWithRaw(10186181065), // 2.37165509377988 fp.CreateWithRaw(10186863080), // 2.3718138877437 fp.CreateWithRaw(10187545172), // 2.37197269976301 fp.CreateWithRaw(10188227342), // 2.37213152984107 fp.CreateWithRaw(10188909590), // 2.37229037798114 fp.CreateWithRaw(10189591915), // 2.37244924418648 fp.CreateWithRaw(10190274317), // 2.37260812846037 fp.CreateWithRaw(10190956798), // 2.37276703080607 fp.CreateWithRaw(10191639356), // 2.37292595122683 fp.CreateWithRaw(10192321992), // 2.37308488972594 fp.CreateWithRaw(10193004705), // 2.37324384630665 fp.CreateWithRaw(10193687496), // 2.37340282097224 fp.CreateWithRaw(10194370364), // 2.37356181372598 fp.CreateWithRaw(10195053311), // 2.37372082457113 fp.CreateWithRaw(10195736335), // 2.37387985351096 fp.CreateWithRaw(10196419437), // 2.37403890054875 fp.CreateWithRaw(10197102616), // 2.37419796568777 fp.CreateWithRaw(10197785874), // 2.3743570489313 fp.CreateWithRaw(10198469209), // 2.3745161502826 fp.CreateWithRaw(10199152622), // 2.37467526974495 fp.CreateWithRaw(10199836112), // 2.37483440732162 fp.CreateWithRaw(10200519681), // 2.3749935630159 fp.CreateWithRaw(10201203327), // 2.37515273683106 fp.CreateWithRaw(10201887051), // 2.37531192877038 fp.CreateWithRaw(10202570853), // 2.37547113883714 fp.CreateWithRaw(10203254733), // 2.37563036703461 fp.CreateWithRaw(10203938691), // 2.37578961336607 fp.CreateWithRaw(10204622727), // 2.37594887783482 fp.CreateWithRaw(10205306840), // 2.37610816044412 fp.CreateWithRaw(10205991032), // 2.37626746119726 fp.CreateWithRaw(10206675301), // 2.37642678009753 fp.CreateWithRaw(10207359649), // 2.37658611714821 fp.CreateWithRaw(10208044074), // 2.37674547235258 fp.CreateWithRaw(10208728578), // 2.37690484571393 fp.CreateWithRaw(10209413159), // 2.37706423723555 fp.CreateWithRaw(10210097818), // 2.37722364692072 fp.CreateWithRaw(10210782556), // 2.37738307477274 fp.CreateWithRaw(10211467371), // 2.37754252079488 fp.CreateWithRaw(10212152265), // 2.37770198499044 fp.CreateWithRaw(10212837236), // 2.37786146736272 fp.CreateWithRaw(10213522286), // 2.378020967915 fp.CreateWithRaw(10214207414), // 2.37818048665057 fp.CreateWithRaw(10214892620), // 2.37834002357273 fp.CreateWithRaw(10215577904), // 2.37849957868477 fp.CreateWithRaw(10216263266), // 2.37865915198998 fp.CreateWithRaw(10216948706), // 2.37881874349167 fp.CreateWithRaw(10217634224), // 2.37897835319312 fp.CreateWithRaw(10218319821), // 2.37913798109764 fp.CreateWithRaw(10219005496), // 2.37929762720851 fp.CreateWithRaw(10219691249), // 2.37945729152905 fp.CreateWithRaw(10220377080), // 2.37961697406254 fp.CreateWithRaw(10221062990), // 2.3797766748123 fp.CreateWithRaw(10221748977), // 2.37993639378161 fp.CreateWithRaw(10222435043), // 2.38009613097379 fp.CreateWithRaw(10223121188), // 2.38025588639212 fp.CreateWithRaw(10223807410), // 2.38041566003993 fp.CreateWithRaw(10224493711), // 2.3805754519205 fp.CreateWithRaw(10225180090), // 2.38073526203715 fp.CreateWithRaw(10225866548), // 2.38089509039319 fp.CreateWithRaw(10226553084), // 2.38105493699191 fp.CreateWithRaw(10227239698), // 2.38121480183662 fp.CreateWithRaw(10227926391), // 2.38137468493064 fp.CreateWithRaw(10228613162), // 2.38153458627726 fp.CreateWithRaw(10229300011), // 2.38169450587981 fp.CreateWithRaw(10229986939), // 2.38185444374159 fp.CreateWithRaw(10230673946), // 2.38201439986592 fp.CreateWithRaw(10231361030), // 2.38217437425609 fp.CreateWithRaw(10232048194), // 2.38233436691544 fp.CreateWithRaw(10232735435), // 2.38249437784726 fp.CreateWithRaw(10233422755), // 2.38265440705489 fp.CreateWithRaw(10234110154), // 2.38281445454162 fp.CreateWithRaw(10234797631), // 2.38297452031077 fp.CreateWithRaw(10235485187), // 2.38313460436567 fp.CreateWithRaw(10236172822), // 2.38329470670963 fp.CreateWithRaw(10236860534), // 2.38345482734598 fp.CreateWithRaw(10237548326), // 2.38361496627801 fp.CreateWithRaw(10238236196), // 2.38377512350907 fp.CreateWithRaw(10238924145), // 2.38393529904246 fp.CreateWithRaw(10239612172), // 2.38409549288152 fp.CreateWithRaw(10240300278), // 2.38425570502956 fp.CreateWithRaw(10240988462), // 2.3844159354899 fp.CreateWithRaw(10241676726), // 2.38457618426588 fp.CreateWithRaw(10242365068), // 2.3847364513608 fp.CreateWithRaw(10243053488), // 2.38489673677801 fp.CreateWithRaw(10243741988), // 2.38505704052083 fp.CreateWithRaw(10244430566), // 2.38521736259258 fp.CreateWithRaw(10245119222), // 2.38537770299659 fp.CreateWithRaw(10245807958), // 2.38553806173619 fp.CreateWithRaw(10246496772), // 2.38569843881471 fp.CreateWithRaw(10247185665), // 2.38585883423548 fp.CreateWithRaw(10247874637), // 2.38601924800184 fp.CreateWithRaw(10248563688), // 2.38617968011711 fp.CreateWithRaw(10249252817), // 2.38634013058462 fp.CreateWithRaw(10249942026), // 2.38650059940772 fp.CreateWithRaw(10250631313), // 2.38666108658972 fp.CreateWithRaw(10251320679), // 2.38682159213398 fp.CreateWithRaw(10252010124), // 2.38698211604383 fp.CreateWithRaw(10252699648), // 2.38714265832259 fp.CreateWithRaw(10253389251), // 2.38730321897362 fp.CreateWithRaw(10254078932), // 2.38746379800025 fp.CreateWithRaw(10254768693), // 2.38762439540581 fp.CreateWithRaw(10255458532), // 2.38778501119365 fp.CreateWithRaw(10256148451), // 2.38794564536711 fp.CreateWithRaw(10256838448), // 2.38810629792953 fp.CreateWithRaw(10257528525), // 2.38826696888426 fp.CreateWithRaw(10258218680), // 2.38842765823463 fp.CreateWithRaw(10258908915), // 2.38858836598399 fp.CreateWithRaw(10259599229), // 2.38874909213568 fp.CreateWithRaw(10260289621), // 2.38890983669306 fp.CreateWithRaw(10260980093), // 2.38907059965947 fp.CreateWithRaw(10261670644), // 2.38923138103825 fp.CreateWithRaw(10262361273), // 2.38939218083275 fp.CreateWithRaw(10263051982), // 2.38955299904632 fp.CreateWithRaw(10263742771), // 2.38971383568232 fp.CreateWithRaw(10264433638), // 2.38987469074409 fp.CreateWithRaw(10265124584), // 2.39003556423498 fp.CreateWithRaw(10265815610), // 2.39019645615834 fp.CreateWithRaw(10266506714), // 2.39035736651754 fp.CreateWithRaw(10267197898), // 2.39051829531592 fp.CreateWithRaw(10267889162), // 2.39067924255683 fp.CreateWithRaw(10268580504), // 2.39084020824364 fp.CreateWithRaw(10269271925), // 2.3910011923797 fp.CreateWithRaw(10269963426), // 2.39116219496836 fp.CreateWithRaw(10270655006), // 2.39132321601299 fp.CreateWithRaw(10271346666), // 2.39148425551693 fp.CreateWithRaw(10272038405), // 2.39164531348357 fp.CreateWithRaw(10272730223), // 2.39180638991624 fp.CreateWithRaw(10273422120), // 2.39196748481832 fp.CreateWithRaw(10274114097), // 2.39212859819316 fp.CreateWithRaw(10274806153), // 2.39228973004413 fp.CreateWithRaw(10275498288), // 2.39245088037459 fp.CreateWithRaw(10276190503), // 2.3926120491879 fp.CreateWithRaw(10276882797), // 2.39277323648744 fp.CreateWithRaw(10277575171), // 2.39293444227657 fp.CreateWithRaw(10278267624), // 2.39309566655864 fp.CreateWithRaw(10278960156), // 2.39325690933705 fp.CreateWithRaw(10279652768), // 2.39341817061513 fp.CreateWithRaw(10280345459), // 2.39357945039629 fp.CreateWithRaw(10281038230), // 2.39374074868386 fp.CreateWithRaw(10281731081), // 2.39390206548124 fp.CreateWithRaw(10282424010), // 2.39406340079179 fp.CreateWithRaw(10283117020), // 2.39422475461889 fp.CreateWithRaw(10283810109), // 2.3943861269659 fp.CreateWithRaw(10284503277), // 2.39454751783621 fp.CreateWithRaw(10285196525), // 2.39470892723318 fp.CreateWithRaw(10285889853), // 2.39487035516019 fp.CreateWithRaw(10286583260), // 2.39503180162062 fp.CreateWithRaw(10287276747), // 2.39519326661785 fp.CreateWithRaw(10287970314), // 2.39535475015526 fp.CreateWithRaw(10288663960), // 2.39551625223622 fp.CreateWithRaw(10289357686), // 2.39567777286411 fp.CreateWithRaw(10290051491), // 2.39583931204232 fp.CreateWithRaw(10290745376), // 2.39600086977422 fp.CreateWithRaw(10291439341), // 2.3961624460632 fp.CreateWithRaw(10292133386), // 2.39632404091265 fp.CreateWithRaw(10292827510), // 2.39648565432594 fp.CreateWithRaw(10293521714), // 2.39664728630646 fp.CreateWithRaw(10294215998), // 2.39680893685759 fp.CreateWithRaw(10294910362), // 2.39697060598273 fp.CreateWithRaw(10295604805), // 2.39713229368526 fp.CreateWithRaw(10296299328), // 2.39729399996856 fp.CreateWithRaw(10296993931), // 2.39745572483603 fp.CreateWithRaw(10297688614), // 2.39761746829106 fp.CreateWithRaw(10298383377), // 2.39777923033703 fp.CreateWithRaw(10299078219), // 2.39794101097735 fp.CreateWithRaw(10299773142), // 2.39810281021539 fp.CreateWithRaw(10300468144), // 2.39826462805456 fp.CreateWithRaw(10301163226), // 2.39842646449824 fp.CreateWithRaw(10301858389), // 2.39858831954984 fp.CreateWithRaw(10302553631), // 2.39875019321274 fp.CreateWithRaw(10303248953), // 2.39891208549035 fp.CreateWithRaw(10303944355), // 2.39907399638606 fp.CreateWithRaw(10304639837), // 2.39923592590327 fp.CreateWithRaw(10305335399), // 2.39939787404537 fp.CreateWithRaw(10306031041), // 2.39955984081577 fp.CreateWithRaw(10306726763), // 2.39972182621787 fp.CreateWithRaw(10307422565), // 2.39988383025507 fp.CreateWithRaw(10308118447), // 2.40004585293077 fp.CreateWithRaw(10308814409), // 2.40020789424837 fp.CreateWithRaw(10309510451), // 2.40036995421129 fp.CreateWithRaw(10310206573), // 2.40053203282291 fp.CreateWithRaw(10310902776), // 2.40069413008665 fp.CreateWithRaw(10311599058), // 2.40085624600592 fp.CreateWithRaw(10312295421), // 2.40101838058411 fp.CreateWithRaw(10312991864), // 2.40118053382465 fp.CreateWithRaw(10313688387), // 2.40134270573093 fp.CreateWithRaw(10314384990), // 2.40150489630636 fp.CreateWithRaw(10315081674), // 2.40166710555437 fp.CreateWithRaw(10315778437), // 2.40182933347836 fp.CreateWithRaw(10316475281), // 2.40199158008173 fp.CreateWithRaw(10317172205), // 2.40215384536791 fp.CreateWithRaw(10317869210), // 2.4023161293403 fp.CreateWithRaw(10318566294), // 2.40247843200233 fp.CreateWithRaw(10319263459), // 2.4026407533574 fp.CreateWithRaw(10319960704), // 2.40280309340894 fp.CreateWithRaw(10320658030), // 2.40296545216035 fp.CreateWithRaw(10321355436), // 2.40312782961507 fp.CreateWithRaw(10322052922), // 2.4032902257765 fp.CreateWithRaw(10322750489), // 2.40345264064806 fp.CreateWithRaw(10323448136), // 2.40361507423318 fp.CreateWithRaw(10324145863), // 2.40377752653528 fp.CreateWithRaw(10324843671), // 2.40393999755778 fp.CreateWithRaw(10325541559), // 2.4041024873041 fp.CreateWithRaw(10326239527), // 2.40426499577767 fp.CreateWithRaw(10326937576), // 2.4044275229819 fp.CreateWithRaw(10327635706), // 2.40459006892023 fp.CreateWithRaw(10328333916), // 2.40475263359608 fp.CreateWithRaw(10329032206), // 2.40491521701289 fp.CreateWithRaw(10329730577), // 2.40507781917406 fp.CreateWithRaw(10330429029), // 2.40524044008304 fp.CreateWithRaw(10331127561), // 2.40540307974326 fp.CreateWithRaw(10331826173), // 2.40556573815814 fp.CreateWithRaw(10332524866), // 2.40572841533112 fp.CreateWithRaw(10333223640), // 2.40589111126562 fp.CreateWithRaw(10333922494), // 2.40605382596509 fp.CreateWithRaw(10334621429), // 2.40621655943295 fp.CreateWithRaw(10335320445), // 2.40637931167264 fp.CreateWithRaw(10336019541), // 2.40654208268759 fp.CreateWithRaw(10336718718), // 2.40670487248124 fp.CreateWithRaw(10337417975), // 2.40686768105703 fp.CreateWithRaw(10338117314), // 2.40703050841839 fp.CreateWithRaw(10338816733), // 2.40719335456877 fp.CreateWithRaw(10339516232), // 2.4073562195116 fp.CreateWithRaw(10340215812), // 2.40751910325032 fp.CreateWithRaw(10340915474), // 2.40768200578838 fp.CreateWithRaw(10341615215), // 2.40784492712922 fp.CreateWithRaw(10342315038), // 2.40800786727627 fp.CreateWithRaw(10343014941), // 2.40817082623299 fp.CreateWithRaw(10343714926), // 2.40833380400281 fp.CreateWithRaw(10344414991), // 2.40849680058919 fp.CreateWithRaw(10345115136), // 2.40865981599556 fp.CreateWithRaw(10345815363), // 2.40882285022539 fp.CreateWithRaw(10346515671), // 2.4089859032821 fp.CreateWithRaw(10347216059), // 2.40914897516916 fp.CreateWithRaw(10347916528), // 2.40931206589001 fp.CreateWithRaw(10348617079), // 2.40947517544811 fp.CreateWithRaw(10349317710), // 2.40963830384689 fp.CreateWithRaw(10350018422), // 2.40980145108983 fp.CreateWithRaw(10350719215), // 2.40996461718036 fp.CreateWithRaw(10351420089), // 2.41012780212194 fp.CreateWithRaw(10352121044), // 2.41029100591803 fp.CreateWithRaw(10352822080), // 2.41045422857209 fp.CreateWithRaw(10353523197), // 2.41061747008756 fp.CreateWithRaw(10354224395), // 2.41078073046791 fp.CreateWithRaw(10354925674), // 2.41094400971659 fp.CreateWithRaw(10355627034), // 2.41110730783707 fp.CreateWithRaw(10356328475), // 2.4112706248328 fp.CreateWithRaw(10357029997), // 2.41143396070724 fp.CreateWithRaw(10357731601), // 2.41159731546385 fp.CreateWithRaw(10358433285), // 2.4117606891061 fp.CreateWithRaw(10359135051), // 2.41192408163745 fp.CreateWithRaw(10359836897), // 2.41208749306137 fp.CreateWithRaw(10360538825), // 2.41225092338131 fp.CreateWithRaw(10361240834), // 2.41241437260074 fp.CreateWithRaw(10361942924), // 2.41257784072314 fp.CreateWithRaw(10362645096), // 2.41274132775196 fp.CreateWithRaw(10363347349), // 2.41290483369068 fp.CreateWithRaw(10364049682), // 2.41306835854276 fp.CreateWithRaw(10364752098), // 2.41323190231167 fp.CreateWithRaw(10365454594), // 2.41339546500089 fp.CreateWithRaw(10366157172), // 2.41355904661389 fp.CreateWithRaw(10366859831), // 2.41372264715413 fp.CreateWithRaw(10367562571), // 2.4138862666251 fp.CreateWithRaw(10368265393), // 2.41404990503026 }; } }
62.157129
62
0.647588
[ "MIT" ]
aillieo/CSFixedPoint
CSFixedPoint/FPTanLut/FPTanLut_48128.cs
64,084
C#
//-------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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 ExperienceExtractor.Api.Jobs; using ExperienceExtractor.Api.Parsing; using ExperienceExtractor.Data; using ExperienceExtractor.Export; using ExperienceExtractor.Mapping; using ExperienceExtractor.Processing; using ExperienceExtractor.Processing.DataSources; using Newtonsoft.Json.Linq; using Sitecore.Globalization; namespace ExperienceExtractor.Scheduling { public class UpdateJobWrapper : IJobSpecification { private readonly string _lockKey; public IJobSpecification Prototype { get; set; } public bool Rebuild { get; set; } public UpdateJobWrapper(IJobSpecification prototype, bool rebuild = false, string lockKey = null) { _lockKey = lockKey; Prototype = prototype; Rebuild = rebuild; } public virtual string LockKey { get { return _lockKey ?? Prototype.LockKey; } } public Language DefaultLanguage { get { return Prototype.DefaultLanguage; } } public IDataSource CreateDataSource() { return Prototype.CreateDataSource(); } public ITableMapper CreateRootMapper() { return Prototype.CreateRootMapper(); } public IEnumerable<ITableDataPostProcessor> CreatePostProcessors() { foreach (var proc in Prototype.CreatePostProcessors()) { var updateProc = proc as IUpdatingTableDataPostProcessor; if (updateProc != null) { if (Rebuild) { updateProc.AdjustToRebuild(); } else { updateProc.AdjustToUpdate(); } } yield return proc; } } public ITableDataExporter CreateExporter(string tempPath) { return Prototype.CreateExporter(tempPath); } public IList<TableData> Load(string tempPath) { return Prototype.Load(tempPath); } public void Initialize(Job job) { Prototype.Initialize(job); } public override string ToString() { return Prototype.ToString(); } } }
31.23301
105
0.566677
[ "Apache-2.0" ]
STDGA/experience-extractor
src/ExperienceExtractor.Scheduling/UpdateJobWrapper.cs
3,219
C#
using UnityEngine; using Verse; using System.Collections.Generic; using System.Linq; using Verse.AI; using RimWorld; using System; namespace TorannMagic { public static class TM_Data { public static List<ThingDef> SpellList() { IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (def.defName.Contains("SpellOf_")) select def; return enumerable.ToList(); } public static List<ThingDef> MasterSpellList() { List<ThingDef> masterSpellList = new List<ThingDef>(); masterSpellList.Add(TorannMagicDefOf.SpellOf_Firestorm); masterSpellList.Add(TorannMagicDefOf.SpellOf_Blizzard); masterSpellList.Add(TorannMagicDefOf.SpellOf_EyeOfTheStorm); masterSpellList.Add(TorannMagicDefOf.SpellOf_RegrowLimb); masterSpellList.Add(TorannMagicDefOf.SpellOf_FoldReality); masterSpellList.Add(TorannMagicDefOf.SpellOf_Resurrection); masterSpellList.Add(TorannMagicDefOf.SpellOf_HolyWrath); masterSpellList.Add(TorannMagicDefOf.SpellOf_LichForm); masterSpellList.Add(TorannMagicDefOf.SpellOf_SummonPoppi); masterSpellList.Add(TorannMagicDefOf.SpellOf_BattleHymn); masterSpellList.Add(TorannMagicDefOf.SpellOf_PsychicShock); masterSpellList.Add(TorannMagicDefOf.SpellOf_Scorn); masterSpellList.Add(TorannMagicDefOf.SpellOf_Meteor); masterSpellList.Add(TorannMagicDefOf.SpellOf_OrbitalStrike); masterSpellList.Add(TorannMagicDefOf.SpellOf_BloodMoon); masterSpellList.Add(TorannMagicDefOf.SpellOf_Shapeshift); masterSpellList.Add(TorannMagicDefOf.SpellOf_Recall); masterSpellList.Add(TorannMagicDefOf.SpellOf_SpiritOfLight); masterSpellList.Add(TorannMagicDefOf.SpellOf_GuardianSpirit); return masterSpellList; } public static List<ThingDef> RestrictedAbilities { get { List<ThingDef> restricted = new List<ThingDef>(); restricted.Add(TorannMagicDefOf.SpellOf_BattleHymn); restricted.Add(TorannMagicDefOf.SpellOf_BlankMind); restricted.Add(TorannMagicDefOf.SpellOf_Blizzard); restricted.Add(TorannMagicDefOf.SpellOf_BloodMoon); restricted.Add(TorannMagicDefOf.SpellOf_BriarPatch); restricted.Add(TorannMagicDefOf.SpellOf_CauterizeWound); restricted.Add(TorannMagicDefOf.SpellOf_ChargeBattery); restricted.Add(TorannMagicDefOf.SpellOf_DryGround); restricted.Add(TorannMagicDefOf.SpellOf_EyeOfTheStorm); restricted.Add(TorannMagicDefOf.SpellOf_FertileLands); restricted.Add(TorannMagicDefOf.SpellOf_Firestorm); restricted.Add(TorannMagicDefOf.SpellOf_FoldReality); restricted.Add(TorannMagicDefOf.SpellOf_HolyWrath); restricted.Add(TorannMagicDefOf.SpellOf_LichForm); restricted.Add(TorannMagicDefOf.SpellOf_MechaniteReprogramming); restricted.Add(TorannMagicDefOf.SpellOf_Meteor); restricted.Add(TorannMagicDefOf.SpellOf_OrbitalStrike); restricted.Add(TorannMagicDefOf.SpellOf_Overdrive); restricted.Add(TorannMagicDefOf.SpellOf_PsychicShock); restricted.Add(TorannMagicDefOf.SpellOf_Recall); restricted.Add(TorannMagicDefOf.SpellOf_RegrowLimb); restricted.Add(TorannMagicDefOf.SpellOf_Resurrection); restricted.Add(TorannMagicDefOf.SpellOf_Sabotage); restricted.Add(TorannMagicDefOf.SpellOf_Scorn); restricted.Add(TorannMagicDefOf.SpellOf_Shapeshift); restricted.Add(TorannMagicDefOf.SpellOf_SummonPoppi); restricted.Add(TorannMagicDefOf.SpellOf_TechnoShield); restricted.Add(TorannMagicDefOf.SpellOf_WetGround); restricted.Add(TorannMagicDefOf.SpellOf_SpiritOfLight); restricted.Add(TorannMagicDefOf.SpellOf_GuardianSpirit); restricted.Add(TorannMagicDefOf.SpellOf_Discord); restricted.Add(TorannMagicDefOf.SpellOf_ShieldOther); return restricted; } } public static List<ThingDef> StandardSpellList() { return SpellList().Except(MasterSpellList()).ToList(); } public static List<ThingDef> StandardSkillList() { IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (def.defName.Contains("SkillOf_")) select def; return enumerable.ToList(); } public static List<ThingDef> FighterBookList() { List<ThingDef> fighterBookList = new List<ThingDef>(); fighterBookList.Add(TorannMagicDefOf.BookOfGladiator); fighterBookList.Add(TorannMagicDefOf.BookOfBladedancer); fighterBookList.Add(TorannMagicDefOf.BookOfDeathKnight); fighterBookList.Add(TorannMagicDefOf.BookOfFaceless); fighterBookList.Add(TorannMagicDefOf.BookOfPsionic); fighterBookList.Add(TorannMagicDefOf.BookOfRanger); fighterBookList.Add(TorannMagicDefOf.BookOfSniper); fighterBookList.Add(TorannMagicDefOf.BookOfMonk); fighterBookList.Add(TorannMagicDefOf.BookOfCommander); fighterBookList.Add(TorannMagicDefOf.BookOfSuperSoldier); foreach(TMDefs.TM_CustomClass cc in TM_ClassUtility.CustomClasses()) { if (cc.isFighter && cc.fullScript != null) { fighterBookList.Add(cc.fullScript); } } return fighterBookList; } public static List<ThingDef> MageBookList() { IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (def.defName.Contains("BookOf")) select def; enumerable = enumerable.Except(MageTornScriptList()); return enumerable.Except(FighterBookList()).ToList(); } public static List<ThingDef> AllBooksList() { IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (def.defName.Contains("BookOf")) select def; return enumerable.Except(MageTornScriptList()).ToList(); } public static List<ThingDef> MageTornScriptList() { IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (def.defName.Contains("Torn_BookOf")) select def; return enumerable.ToList(); } public static List<TraitDef> MagicTraits { get { List<TraitDef> magicTraits = new List<TraitDef>(); magicTraits.Clear(); magicTraits.Add(TorannMagicDefOf.Arcanist); magicTraits.Add(TorannMagicDefOf.InnerFire); magicTraits.Add(TorannMagicDefOf.HeartOfFrost); magicTraits.Add(TorannMagicDefOf.StormBorn); magicTraits.Add(TorannMagicDefOf.Druid); magicTraits.Add(TorannMagicDefOf.Priest); magicTraits.Add(TorannMagicDefOf.Necromancer); magicTraits.Add(TorannMagicDefOf.Technomancer); magicTraits.Add(TorannMagicDefOf.Geomancer); magicTraits.Add(TorannMagicDefOf.Warlock); magicTraits.Add(TorannMagicDefOf.Succubus); magicTraits.Add(TorannMagicDefOf.ChaosMage); magicTraits.Add(TorannMagicDefOf.Paladin); magicTraits.Add(TorannMagicDefOf.Summoner); magicTraits.Add(TorannMagicDefOf.Lich); magicTraits.Add(TorannMagicDefOf.TM_Bard); magicTraits.Add(TorannMagicDefOf.Chronomancer); magicTraits.Add(TorannMagicDefOf.Enchanter); magicTraits.Add(TorannMagicDefOf.BloodMage); magicTraits.Add(TorannMagicDefOf.TM_Wanderer); magicTraits.Add(TorannMagicDefOf.TM_Brightmage); magicTraits.Add(TorannMagicDefOf.TM_Shaman); return magicTraits; } } public static List<TraitDef> MightTraits { get { List<TraitDef> mightTraits = new List<TraitDef>(); mightTraits.Clear(); mightTraits.Add(TorannMagicDefOf.Bladedancer); mightTraits.Add(TorannMagicDefOf.Gladiator); mightTraits.Add(TorannMagicDefOf.Faceless); mightTraits.Add(TorannMagicDefOf.TM_Sniper); mightTraits.Add(TorannMagicDefOf.Ranger); mightTraits.Add(TorannMagicDefOf.TM_Psionic); mightTraits.Add(TorannMagicDefOf.TM_Monk); mightTraits.Add(TorannMagicDefOf.TM_Commander); mightTraits.Add(TorannMagicDefOf.TM_SuperSoldier); mightTraits.Add(TorannMagicDefOf.TM_Wayfarer); return mightTraits; } } public static List<TraitDef> AllClassTraits { get { List<TraitDef> allClassTraits = new List<TraitDef>(); allClassTraits.Clear(); allClassTraits.AddRange(MightTraits); allClassTraits.AddRange(MagicTraits); allClassTraits.AddRange(TM_ClassUtility.CustomClassTraitDefs); return allClassTraits; } } public static List<TraitDef> AllClassConflictTraits { get { List<TraitDef> allClassConflictTraits = new List<TraitDef>(); allClassConflictTraits.Clear(); allClassConflictTraits.AddRange(AllClassTraits); allClassConflictTraits.Add(TorannMagicDefOf.TM_Gifted); AllClassConflictTraits.Add(TorannMagicDefOf.PhysicalProdigy); return allClassConflictTraits; } } public static List<ThingDef> MagicFociList() { List<ThingDef> magicFocis = new List<ThingDef>(); magicFocis.Clear(); IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (true) select def; List<string> magicFociList = WeaponCategoryList.Named("TM_Category_MagicalFoci").weaponDefNames; foreach (ThingDef current in enumerable) { for (int i = 0; i < magicFociList.Count; i++) { if (current.defName == magicFociList[i].ToString() || magicFociList[i].ToString() == "*") { //Log.Message("adding magicFoci def " + current.defName); magicFocis.AddDistinct(current); } } } return magicFocis; } public static List<ThingDef> BowList() { List<ThingDef> bows = new List<ThingDef>(); bows.Clear(); IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (true) select def; List<string> bowList = WeaponCategoryList.Named("TM_Category_Bows").weaponDefNames; foreach (ThingDef current in enumerable) { for (int i = 0; i < bowList.Count; i++) { if (current.defName == bowList[i].ToString() || bowList[i].ToString() == "*") { //Log.Message("adding bow def " + current.defName); bows.AddDistinct(current); } } } return bows; } public static List<ThingDef> PistolList() { List<ThingDef> pistols = new List<ThingDef>(); pistols.Clear(); IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (true) select def; List<string> pistolList = WeaponCategoryList.Named("TM_Category_Pistols").weaponDefNames; foreach (ThingDef current in enumerable) { for (int i = 0; i < pistolList.Count; i++) { if (current.defName == pistolList[i].ToString() || pistolList[i].ToString() == "*") { //Log.Message("adding pistol def " + current.defName); pistols.AddDistinct(current); } } } return pistols; } public static List<ThingDef> RifleList() { List<ThingDef> rifles = new List<ThingDef>(); rifles.Clear(); IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (true) select def; List<string> rifleList = WeaponCategoryList.Named("TM_Category_Rifles").weaponDefNames; foreach (ThingDef current in enumerable) { for (int i = 0; i < rifleList.Count; i++) { if (current.defName == rifleList[i].ToString() || rifleList[i].ToString() == "*") { //Log.Message("adding rifle def " + current.defName); rifles.AddDistinct(current); } } } return rifles; } public static List<ThingDef> ShotgunList() { List<ThingDef> shotguns = new List<ThingDef>(); shotguns.Clear(); IEnumerable<ThingDef> enumerable = from def in DefDatabase<ThingDef>.AllDefs where (true) select def; List<string> shotgunList = WeaponCategoryList.Named("TM_Category_Shotguns").weaponDefNames; foreach (ThingDef current in enumerable) { for (int i = 0; i < shotgunList.Count; i++) { if (current.defName == shotgunList[i].ToString() || shotgunList[i].ToString() == "*") { //Log.Message("adding shotgun def " + current.defName); shotguns.AddDistinct(current); } } } return shotguns; } public static List<HediffDef> AilmentList() { List<HediffDef> ailments = new List<HediffDef>(); ailments.Clear(); IEnumerable<HediffDef> enumerable = from def in DefDatabase<HediffDef>.AllDefs where (true) select def; List<TMDefs.TM_CategoryHediff> ailmentList = HediffCategoryList.Named("TM_Category_Hediffs").ailments; foreach (HediffDef current in enumerable) { for (int i = 0; i < ailmentList.Count; i++) { if (current.defName == ailmentList[i].hediffDefname || (ailmentList[i].containsDefnameString && current.defName.Contains(ailmentList[i].hediffDefname)) || ailmentList[i].ToString() == "*") { //Log.Message("adding shotgun def " + current.defName); ailments.AddDistinct(current); } } } return ailments; } public static List<HediffDef> AddictionList() { List<HediffDef> addictions = new List<HediffDef>(); addictions.Clear(); IEnumerable<HediffDef> enumerable = from def in DefDatabase<HediffDef>.AllDefs where (true) select def; List<TMDefs.TM_CategoryHediff> addictionList = HediffCategoryList.Named("TM_Category_Hediffs").addictions; foreach (HediffDef current in enumerable) { for (int i = 0; i < addictionList.Count; i++) { if (current.defName == addictionList[i].hediffDefname || (addictionList[i].containsDefnameString && current.defName.Contains(addictionList[i].hediffDefname)) || addictionList[i].ToString() == "*") { //Log.Message("adding shotgun def " + current.defName); addictions.AddDistinct(current); } } } return addictions; } public static List<HediffDef> MechaniteList() { List<HediffDef> mechanites = new List<HediffDef>(); mechanites.Clear(); IEnumerable<HediffDef> enumerable = from def in DefDatabase<HediffDef>.AllDefs where (true) select def; List<TMDefs.TM_CategoryHediff> mechaniteList = HediffCategoryList.Named("TM_Category_Hediffs").mechanites; foreach (HediffDef current in enumerable) { for (int i = 0; i < mechaniteList.Count; i++) { if (current.defName == mechaniteList[i].hediffDefname || (mechaniteList[i].containsDefnameString && current.defName.Contains(mechaniteList[i].hediffDefname)) || mechaniteList[i].ToString() == "*") { //Log.Message("adding shotgun def " + current.defName); mechanites.AddDistinct(current); } } } return mechanites; } public static List<HediffDef> DiseaseList() { List<HediffDef> diseases = new List<HediffDef>(); diseases.Clear(); IEnumerable<HediffDef> enumerable = from def in DefDatabase<HediffDef>.AllDefs where (true) select def; List<TMDefs.TM_CategoryHediff> diseaseList = HediffCategoryList.Named("TM_Category_Hediffs").diseases; foreach (HediffDef current in enumerable) { for (int i = 0; i < diseaseList.Count; i++) { if (current.defName == diseaseList[i].hediffDefname || (diseaseList[i].containsDefnameString && current.defName.Contains(diseaseList[i].hediffDefname)) || diseaseList[i].ToString() == "*") { //Log.Message("adding shotgun def " + current.defName); diseases.AddDistinct(current); } } } return diseases; } public static IEnumerable<TM_CustomPowerDef> CustomFighterPowerDefs() { IEnumerable<TM_CustomPowerDef> enumerable = from def in DefDatabase<TM_CustomPowerDef>.AllDefs where (def.customPower != null && def.customPower.forFighter) select def; return enumerable; } public static IEnumerable<TM_CustomPowerDef> CustomMagePowerDefs() { IEnumerable<TM_CustomPowerDef> enumerable = from def in DefDatabase<TM_CustomPowerDef>.AllDefs where (def.customPower != null && def.customPower.forMage) select def; return enumerable; } } }
46.548315
216
0.547456
[ "BSD-3-Clause" ]
Phenrei/RWoM
RimWorldOfMagic/RimWorldOfMagic/TM_Data.cs
20,716
C#
namespace Cosmos.Optionals; /// <summary> /// None <br /> /// 无 /// </summary> /// <typeparam name="T"></typeparam> public sealed class None<T> : Optional<T, None<T>>, IEquatable<None<T>>, IComparable<None<T>> { internal None() : base(default, false) { } #region Equals /// <inheritdoc /> public override bool Equals(T other) { if (other is null) return true; return Internal.Equals(other); } /// <summary> /// Equals /// </summary> /// <param name="other"></param> /// <returns></returns> public override bool Equals(None<T> other) { if (other is null) return false; return Internal.Equals(other.Internal); } #endregion #region CompareTo /// <inheritdoc /> public override int CompareTo(T other) { if (other is null) return 0; return Internal.CompareTo(other); } /// <summary> /// Compare to /// </summary> /// <param name="other"></param> /// <returns></returns> public override int CompareTo(None<T> other) { if (other is null) return 1; return Internal.CompareTo(other.Internal); } #endregion #region Explicit operator /// <summary> /// Convert maybe to none /// </summary> /// <param name="some"></param> /// <returns></returns> public static explicit operator None<T>(Some<T> some) { return Optional.Wrapped.None<T>(); } /// <summary> /// Convert maybe to none /// </summary> /// <param name="maybe"></param> /// <returns></returns> public static explicit operator None<T>(Maybe<T> maybe) { return maybe.ToWrappedNone(); } #endregion #region Or / Else /// <inheritdoc /> public override None<T> Or(T alternative) => default; /// <inheritdoc /> public override None<T> Or(Func<T> alternativeFactory) => this; /// <inheritdoc /> public override None<T> Else(None<T> alternativeMaybe) => alternativeMaybe; /// <inheritdoc /> public override None<T> Else(Func<None<T>> alternativeMaybeFactory) => this; #endregion #region Filter /// <inheritdoc /> public override None<T> Filter(bool condition) => this; /// <inheritdoc /> public override None<T> Filter(Func<T, bool> predicate) => this; #endregion #region Not null /// <inheritdoc /> public override None<T> NotNull() => default; #endregion }
21.698276
93
0.570918
[ "Apache-2.0" ]
cosmos-loops/Cosmos.Standard
src/Cosmos.Extensions.Optionals/Cosmos/Optionals/None.cs
2,519
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.Runtime.InteropServices; using Microsoft.Xna.Framework.Audio; using MonoGame.Framework.Utilities; using System.IO; namespace MonoGame.OpenAL { internal enum ALFormat { Mono8 = 0x1100, Mono16 = 0x1101, Stereo8 = 0x1102, Stereo16 = 0x1103, MonoIma4 = 0x1300, StereoIma4 = 0x1301, MonoMSAdpcm = 0x1302, StereoMSAdpcm = 0x1303, MonoFloat32 = 0x10010, StereoFloat32 = 0x10011, } internal enum ALError { NoError = 0, InvalidName = 0xA001, InvalidEnum = 0xA002, InvalidValue = 0xA003, InvalidOperation = 0xA004, OutOfMemory = 0xA005, } internal enum ALGetString { Extensions = 0xB004, } internal enum ALBufferi { UnpackBlockAlignmentSoft = 0x200C, LoopSoftPointsExt = 0x2015, } internal enum ALGetBufferi { Bits = 0x2002, Channels = 0x2003, Size = 0x2004, } internal enum ALSourceb { Looping = 0x1007, } internal enum ALSourcei { SourceRelative = 0x202, Buffer = 0x1009, EfxDirectFilter = 0x20005, EfxAuxilarySendFilter = 0x20006, } internal enum ALSourcef { Pitch = 0x1003, Gain = 0x100A, ReferenceDistance = 0x1020 } internal enum ALGetSourcei { SampleOffset = 0x1025, SourceState = 0x1010, BuffersQueued = 0x1015, BuffersProcessed = 0x1016, } internal enum ALSourceState { Initial = 0x1011, Playing = 0x1012, Paused = 0x1013, Stopped = 0x1014, } internal enum ALListener3f { Position = 0x1004, } internal enum ALSource3f { Position = 0x1004, Velocity = 0x1006, } internal enum ALDistanceModel { None = 0, InverseDistanceClamped = 0xD002, } internal enum AlcError { NoError = 0, } internal enum AlcGetString { CaptureDeviceSpecifier = 0x0310, CaptureDefaultDeviceSpecifier = 0x0311, Extensions = 0x1006, } internal enum AlcGetInteger { CaptureSamples = 0x0312, } internal enum EfxFilteri { FilterType = 0x8001, } internal enum EfxFilterf { LowpassGain = 0x0001, LowpassGainHF = 0x0002, HighpassGain = 0x0001, HighpassGainLF = 0x0002, BandpassGain = 0x0001, BandpassGainLF = 0x0002, BandpassGainHF = 0x0003, } internal enum EfxFilterType { None = 0x0000, Lowpass = 0x0001, Highpass = 0x0002, Bandpass = 0x0003, } internal enum EfxEffecti { EffectType = 0x8001, SlotEffect = 0x0001, } internal enum EfxEffectSlotf { EffectSlotGain = 0x0002, } internal enum EfxEffectf { EaxReverbDensity = 0x0001, EaxReverbDiffusion = 0x0002, EaxReverbGain = 0x0003, EaxReverbGainHF = 0x0004, EaxReverbGainLF = 0x0005, DecayTime = 0x0006, DecayHighFrequencyRatio = 0x0007, DecayLowFrequencyRation = 0x0008, EaxReverbReflectionsGain = 0x0009, EaxReverbReflectionsDelay = 0x000A, ReflectionsPain = 0x000B, LateReverbGain = 0x000C, LateReverbDelay = 0x000D, LateRevertPain = 0x000E, EchoTime = 0x000F, EchoDepth = 0x0010, ModulationTime = 0x0011, ModulationDepth = 0x0012, AirAbsorbsionHighFrequency = 0x0013, EaxReverbHFReference = 0x0014, EaxReverbLFReference = 0x0015, RoomRolloffFactor = 0x0016, DecayHighFrequencyLimit = 0x0017, } internal enum EfxEffectType { Reverb = 0x8000, } internal class AL { public static IntPtr NativeLibrary = GetNativeLibrary(); private static IntPtr GetNativeLibrary() { #if DESKTOPGL if (CurrentPlatform.OS == OS.Windows) return FuncLoader.LoadLibraryExt("soft_oal.dll"); else if (CurrentPlatform.OS == OS.Linux) return FuncLoader.LoadLibraryExt("libopenal.so.1"); else if (CurrentPlatform.OS == OS.MacOSX) return FuncLoader.LoadLibraryExt("libopenal.1.dylib"); else return FuncLoader.LoadLibraryExt("openal"); #elif ANDROID var ret = FuncLoader.LoadLibrary("libopenal32.so"); if (ret == IntPtr.Zero) { var appFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var appDir = Path.GetDirectoryName(appFilesDir); var lib = Path.Combine(appDir, "lib", "libopenal32.so"); ret = FuncLoader.LoadLibrary(lib); } return ret; #else return FuncLoader.LoadLibrary("/System/Library/Frameworks/OpenAL.framework/OpenAL"); #endif } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alenable(int cap); internal static d_alenable Enable = FuncLoader.LoadFunction<d_alenable>(NativeLibrary, "alEnable"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_albufferdata(uint bid, int format, IntPtr data, int size, int freq); internal static d_albufferdata alBufferData = FuncLoader.LoadFunction<d_albufferdata>(NativeLibrary, "alBufferData"); internal static void BufferData(int bid, ALFormat format, byte[] data, int size, int freq) { var handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { alBufferData((uint)bid, (int)format, handle.AddrOfPinnedObject(), size, freq); } finally { handle.Free(); } } internal static void BufferData(int bid, ALFormat format, short[] data, int size, int freq) { var handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { alBufferData((uint)bid, (int)format, handle.AddrOfPinnedObject(), size, freq); } finally { handle.Free(); } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void d_aldeletebuffers(int n, int* buffers); internal static d_aldeletebuffers alDeleteBuffers = FuncLoader.LoadFunction<d_aldeletebuffers>(NativeLibrary, "alDeleteBuffers"); internal static void DeleteBuffers(int[] buffers) { DeleteBuffers(buffers.Length, ref buffers[0]); } internal unsafe static void DeleteBuffers(int n, ref int buffers) { fixed (int* pbuffers = &buffers) { alDeleteBuffers(n, pbuffers); } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_albufferi(int buffer, ALBufferi param, int value); internal static d_albufferi Bufferi = FuncLoader.LoadFunction<d_albufferi>(NativeLibrary, "alBufferi"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_algetbufferi(int bid, ALGetBufferi param, out int value); internal static d_algetbufferi GetBufferi = FuncLoader.LoadFunction<d_algetbufferi>(NativeLibrary, "alGetBufferi"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_albufferiv(int bid, ALBufferi param, int[] values); internal static d_albufferiv Bufferiv = FuncLoader.LoadFunction<d_albufferiv>(NativeLibrary, "alBufferiv"); internal static void GetBuffer(int bid, ALGetBufferi param, out int value) { GetBufferi(bid, param, out value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void d_algenbuffers(int count, int* buffers); internal static d_algenbuffers alGenBuffers = FuncLoader.LoadFunction<d_algenbuffers>(NativeLibrary, "alGenBuffers"); internal unsafe static void GenBuffers(int count, out int[] buffers) { buffers = new int[count]; fixed (int* ptr = &buffers[0]) { alGenBuffers(count, ptr); } } internal static void GenBuffers(int count, out int buffer) { int[] ret; GenBuffers(count, out ret); buffer = ret[0]; } internal static int[] GenBuffers(int count) { int[] ret; GenBuffers(count, out ret); return ret; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_algensources(int n, uint[] sources); internal static d_algensources alGenSources = FuncLoader.LoadFunction<d_algensources>(NativeLibrary, "alGenSources"); internal static void GenSources(int[] sources) { uint[] temp = new uint[sources.Length]; alGenSources(temp.Length, temp); for (int i = 0; i < temp.Length; i++) { sources[i] = (int)temp[i]; } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate ALError d_algeterror(); internal static d_algeterror GetError = FuncLoader.LoadFunction<d_algeterror>(NativeLibrary, "alGetError"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool d_alisbuffer(uint buffer); internal static d_alisbuffer alIsBuffer = FuncLoader.LoadFunction<d_alisbuffer>(NativeLibrary, "alIsBuffer"); internal static bool IsBuffer(int buffer) { return alIsBuffer((uint)buffer); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourcepause(uint source); internal static d_alsourcepause alSourcePause = FuncLoader.LoadFunction<d_alsourcepause>(NativeLibrary, "alSourcePause"); internal static void SourcePause(int source) { alSourcePause((uint)source); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourceplay(uint source); internal static d_alsourceplay alSourcePlay = FuncLoader.LoadFunction<d_alsourceplay>(NativeLibrary, "alSourcePlay"); internal static void SourcePlay(int source) { alSourcePlay((uint)source); } internal static string GetErrorString(ALError errorCode) { return errorCode.ToString(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool d_alissource(int source); internal static d_alissource IsSource = FuncLoader.LoadFunction<d_alissource>(NativeLibrary, "alIsSource"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_aldeletesources(int n, ref int sources); internal static d_aldeletesources alDeleteSources = FuncLoader.LoadFunction<d_aldeletesources>(NativeLibrary, "alDeleteSources"); internal static void DeleteSource(int source) { alDeleteSources(1, ref source); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourcestop(int sourceId); internal static d_alsourcestop SourceStop = FuncLoader.LoadFunction<d_alsourcestop>(NativeLibrary, "alSourceStop"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourcei(int sourceId, int i, int a); internal static d_alsourcei alSourcei = FuncLoader.LoadFunction<d_alsourcei>(NativeLibrary, "alSourcei"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsource3i(int sourceId, ALSourcei i, int a, int b, int c); internal static d_alsource3i alSource3i = FuncLoader.LoadFunction<d_alsource3i>(NativeLibrary, "alSource3i"); internal static void Source(int sourceId, ALSourcei i, int a) { alSourcei(sourceId, (int)i, a); } internal static void Source(int sourceId, ALSourceb i, bool a) { alSourcei(sourceId, (int)i, a ? 1 : 0); } internal static void Source(int sourceId, ALSource3f i, float x, float y, float z) { alSource3f(sourceId, i, x, y, z); } internal static void Source(int sourceId, ALSourcef i, float dist) { alSourcef(sourceId, i, dist); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourcef(int sourceId, ALSourcef i, float a); internal static d_alsourcef alSourcef = FuncLoader.LoadFunction<d_alsourcef>(NativeLibrary, "alSourcef"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsource3f(int sourceId, ALSource3f i, float x, float y, float z); internal static d_alsource3f alSource3f = FuncLoader.LoadFunction<d_alsource3f>(NativeLibrary, "alSource3f"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_algetsourcei(int sourceId, ALGetSourcei i, out int state); internal static d_algetsourcei GetSource = FuncLoader.LoadFunction<d_algetsourcei>(NativeLibrary, "alGetSourcei"); internal static ALSourceState GetSourceState(int sourceId) { int state; GetSource(sourceId, ALGetSourcei.SourceState, out state); return (ALSourceState)state; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_algetlistener3f(ALListener3f param, out float value1, out float value2, out float value3); internal static d_algetlistener3f GetListener = FuncLoader.LoadFunction<d_algetlistener3f>(NativeLibrary, "alGetListener3f"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_aldistancemodel(ALDistanceModel model); internal static d_aldistancemodel DistanceModel = FuncLoader.LoadFunction<d_aldistancemodel>(NativeLibrary, "alDistanceModel"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_aldopplerfactor(float value); internal static d_aldopplerfactor DopplerFactor = FuncLoader.LoadFunction<d_aldopplerfactor>(NativeLibrary, "alDopplerFactor"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void d_alsourcequeuebuffers(int sourceId, int numEntries, int* buffers); internal static d_alsourcequeuebuffers alSourceQueueBuffers = FuncLoader.LoadFunction<d_alsourcequeuebuffers>(NativeLibrary, "alSourceQueueBuffers"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate void d_alsourceunqueuebuffers(int sourceId, int numEntries, int* salvaged); internal static d_alsourceunqueuebuffers alSourceUnqueueBuffers = FuncLoader.LoadFunction<d_alsourceunqueuebuffers>(NativeLibrary, "alSourceUnqueueBuffers"); internal static unsafe void SourceQueueBuffers(int sourceId, int numEntries, int[] buffers) { fixed (int* ptr = &buffers[0]) { AL.alSourceQueueBuffers(sourceId, numEntries, ptr); } } internal unsafe static void SourceQueueBuffer(int sourceId, int buffer) { AL.alSourceQueueBuffers(sourceId, 1, &buffer); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alsourceunqueuebuffers2(int sid, int numEntries, out int[] bids); internal static d_alsourceunqueuebuffers2 alSourceUnqueueBuffers2 = FuncLoader.LoadFunction<d_alsourceunqueuebuffers2>(NativeLibrary, "alSourceUnqueueBuffers"); internal static unsafe int[] SourceUnqueueBuffers(int sourceId, int numEntries) { if (numEntries <= 0) { throw new ArgumentOutOfRangeException("numEntries", "Must be greater than zero."); } int[] array = new int[numEntries]; fixed (int* ptr = &array[0]) { alSourceUnqueueBuffers(sourceId, numEntries, ptr); } return array; } internal static void SourceUnqueueBuffers(int sid, int numENtries, out int[] bids) { alSourceUnqueueBuffers2(sid, numENtries, out bids); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int d_algetenumvalue(string enumName); internal static d_algetenumvalue alGetEnumValue = FuncLoader.LoadFunction<d_algetenumvalue>(NativeLibrary, "alGetEnumValue"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool d_alisextensionpresent(string extensionName); internal static d_alisextensionpresent IsExtensionPresent = FuncLoader.LoadFunction<d_alisextensionpresent>(NativeLibrary, "alIsExtensionPresent"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_algetprocaddress(string functionName); internal static d_algetprocaddress alGetProcAddress = FuncLoader.LoadFunction<d_algetprocaddress>(NativeLibrary, "alGetProcAddress"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr d_algetstring(int p); private static d_algetstring alGetString = FuncLoader.LoadFunction<d_algetstring>(NativeLibrary, "alGetString"); internal static string GetString(int p) { return Marshal.PtrToStringAnsi(alGetString(p)); } internal static string Get(ALGetString p) { return GetString((int)p); } } internal partial class Alc { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alccreatecontext(IntPtr device, int[] attributes); internal static d_alccreatecontext CreateContext = FuncLoader.LoadFunction<d_alccreatecontext>(AL.NativeLibrary, "alcCreateContext"); internal static AlcError GetError() { return GetErrorForDevice(IntPtr.Zero); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate AlcError d_alcgeterror(IntPtr device); internal static d_alcgeterror GetErrorForDevice = FuncLoader.LoadFunction<d_alcgeterror>(AL.NativeLibrary, "alcGetError"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcgetintegerv(IntPtr device, int param, int size, int[] values); internal static d_alcgetintegerv alcGetIntegerv = FuncLoader.LoadFunction<d_alcgetintegerv>(AL.NativeLibrary, "alcGetIntegerv"); internal static void GetInteger(IntPtr device, AlcGetInteger param, int size, int[] values) { alcGetIntegerv(device, (int)param, size, values); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alcgetcurrentcontext(); internal static d_alcgetcurrentcontext GetCurrentContext = FuncLoader.LoadFunction<d_alcgetcurrentcontext>(AL.NativeLibrary, "alcGetCurrentContext"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcmakecontextcurrent(IntPtr context); internal static d_alcmakecontextcurrent MakeContextCurrent = FuncLoader.LoadFunction<d_alcmakecontextcurrent>(AL.NativeLibrary, "alcMakeContextCurrent"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcdestroycontext(IntPtr context); internal static d_alcdestroycontext DestroyContext = FuncLoader.LoadFunction<d_alcdestroycontext>(AL.NativeLibrary, "alcDestroyContext"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcclosedevice(IntPtr device); internal static d_alcclosedevice CloseDevice = FuncLoader.LoadFunction<d_alcclosedevice>(AL.NativeLibrary, "alcCloseDevice"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alcopendevice(string device); internal static d_alcopendevice OpenDevice = FuncLoader.LoadFunction<d_alcopendevice>(AL.NativeLibrary, "alcOpenDevice"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alccaptureopendevice(string device, uint sampleRate, int format, int sampleSize); internal static d_alccaptureopendevice alcCaptureOpenDevice = FuncLoader.LoadFunction<d_alccaptureopendevice>(AL.NativeLibrary, "alcCaptureOpenDevice"); internal static IntPtr CaptureOpenDevice(string device, uint sampleRate, ALFormat format, int sampleSize) { return alcCaptureOpenDevice(device, sampleRate, (int)format, sampleSize); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alccapturestart(IntPtr device); internal static d_alccapturestart CaptureStart = FuncLoader.LoadFunction<d_alccapturestart>(AL.NativeLibrary, "alcCaptureStart"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alccapturesamples(IntPtr device, IntPtr buffer, int samples); internal static d_alccapturesamples CaptureSamples = FuncLoader.LoadFunction<d_alccapturesamples>(AL.NativeLibrary, "alcCaptureSamples"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alccapturestop(IntPtr device); internal static d_alccapturestop CaptureStop = FuncLoader.LoadFunction<d_alccapturestop>(AL.NativeLibrary, "alcCaptureStop"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alccaptureclosedevice(IntPtr device); internal static d_alccaptureclosedevice CaptureCloseDevice = FuncLoader.LoadFunction<d_alccaptureclosedevice>(AL.NativeLibrary, "alcCaptureCloseDevice"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool d_alcisextensionpresent(IntPtr device, string extensionName); internal static d_alcisextensionpresent IsExtensionPresent = FuncLoader.LoadFunction<d_alcisextensionpresent>(AL.NativeLibrary, "alcIsExtensionPresent"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr d_alcgetstring(IntPtr device, int p); internal static d_alcgetstring alcGetString = FuncLoader.LoadFunction<d_alcgetstring>(AL.NativeLibrary, "alcGetString"); internal static string GetString(IntPtr device, int p) { return Marshal.PtrToStringAnsi(alcGetString(device, p)); } internal static string GetString(IntPtr device, AlcGetString p) { return GetString(device, (int)p); } #if IOS [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcsuspendcontext(IntPtr context); internal static d_alcsuspendcontext SuspendContext = FuncLoader.LoadFunction<d_alcsuspendcontext>(AL.NativeLibrary, "alcSuspendContext"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcprocesscontext(IntPtr context); internal static d_alcprocesscontext ProcessContext = FuncLoader.LoadFunction<d_alcprocesscontext>(AL.NativeLibrary, "alcProcessContext"); #endif #if ANDROID [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcdevicepausesoft(IntPtr device); internal static d_alcdevicepausesoft DevicePause = FuncLoader.LoadFunction<d_alcdevicepausesoft>(AL.NativeLibrary, "alcDevicePauseSOFT"); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void d_alcdeviceresumesoft(IntPtr device); internal static d_alcdeviceresumesoft DeviceResume = FuncLoader.LoadFunction<d_alcdeviceresumesoft>(AL.NativeLibrary, "alcDeviceResumeSOFT"); #endif } internal class XRamExtension { internal enum XRamStorage { Automatic, Hardware, Accessible } private int RamSize; private int RamFree; private int StorageAuto; private int StorageHardware; private int StorageAccessible; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool SetBufferModeDelegate(int n, ref int buffers, int value); private SetBufferModeDelegate setBufferMode; internal XRamExtension() { IsInitialized = false; if (!AL.IsExtensionPresent("EAX-RAM")) { return; } RamSize = AL.alGetEnumValue("AL_EAX_RAM_SIZE"); RamFree = AL.alGetEnumValue("AL_EAX_RAM_FREE"); StorageAuto = AL.alGetEnumValue("AL_STORAGE_AUTOMATIC"); StorageHardware = AL.alGetEnumValue("AL_STORAGE_HARDWARE"); StorageAccessible = AL.alGetEnumValue("AL_STORAGE_ACCESSIBLE"); if (RamSize == 0 || RamFree == 0 || StorageAuto == 0 || StorageHardware == 0 || StorageAccessible == 0) { return; } try { setBufferMode = (XRamExtension.SetBufferModeDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("EAXSetBufferMode"), typeof(XRamExtension.SetBufferModeDelegate)); } catch (Exception) { return; } IsInitialized = true; } internal bool IsInitialized { get; private set; } internal bool SetBufferMode(int i, ref int id, XRamStorage storage) { if (storage == XRamExtension.XRamStorage.Accessible) { return setBufferMode(i, ref id, StorageAccessible); } if (storage != XRamExtension.XRamStorage.Hardware) { return setBufferMode(i, ref id, StorageAuto); } return setBufferMode(i, ref id, StorageHardware); } } internal class EffectsExtension { /* Effect API */ [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alGenEffectsDelegate(int n, out uint effect); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alDeleteEffectsDelegate(int n, ref int effect); //[UnmanagedFunctionPointer (CallingConvention.Cdecl)] //private delegate bool alIsEffectDelegate (uint effect); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alEffectfDelegate(uint effect, EfxEffectf param, float value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alEffectiDelegate(uint effect, EfxEffecti param, int value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alGenAuxiliaryEffectSlotsDelegate(int n, out uint effectslots); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alDeleteAuxiliaryEffectSlotsDelegate(int n, ref int effectslots); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alAuxiliaryEffectSlotiDelegate(uint slot, EfxEffecti type, uint effect); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alAuxiliaryEffectSlotfDelegate(uint slot, EfxEffectSlotf param, float value); /* Filter API */ [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate void alGenFiltersDelegate(int n, [Out] uint* filters); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alFilteriDelegate(uint fid, EfxFilteri param, int value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void alFilterfDelegate(uint fid, EfxFilterf param, float value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private unsafe delegate void alDeleteFiltersDelegate(int n, [In] uint* filters); private alGenEffectsDelegate alGenEffects; private alDeleteEffectsDelegate alDeleteEffects; //private alIsEffectDelegate alIsEffect; private alEffectfDelegate alEffectf; private alEffectiDelegate alEffecti; private alGenAuxiliaryEffectSlotsDelegate alGenAuxiliaryEffectSlots; private alDeleteAuxiliaryEffectSlotsDelegate alDeleteAuxiliaryEffectSlots; private alAuxiliaryEffectSlotiDelegate alAuxiliaryEffectSloti; private alAuxiliaryEffectSlotfDelegate alAuxiliaryEffectSlotf; private alGenFiltersDelegate alGenFilters; private alFilteriDelegate alFilteri; private alFilterfDelegate alFilterf; private alDeleteFiltersDelegate alDeleteFilters; internal static IntPtr device; static EffectsExtension _instance; internal static EffectsExtension Instance { get { if (_instance == null) _instance = new EffectsExtension(); return _instance; } } internal EffectsExtension() { IsInitialized = false; if (!Alc.IsExtensionPresent(device, "ALC_EXT_EFX")) { return; } alGenEffects = (alGenEffectsDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alGenEffects"), typeof(alGenEffectsDelegate)); alDeleteEffects = (alDeleteEffectsDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alDeleteEffects"), typeof(alDeleteEffectsDelegate)); alEffectf = (alEffectfDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alEffectf"), typeof(alEffectfDelegate)); alEffecti = (alEffectiDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alEffecti"), typeof(alEffectiDelegate)); alGenAuxiliaryEffectSlots = (alGenAuxiliaryEffectSlotsDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alGenAuxiliaryEffectSlots"), typeof(alGenAuxiliaryEffectSlotsDelegate)); alDeleteAuxiliaryEffectSlots = (alDeleteAuxiliaryEffectSlotsDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alDeleteAuxiliaryEffectSlots"), typeof(alDeleteAuxiliaryEffectSlotsDelegate)); alAuxiliaryEffectSloti = (alAuxiliaryEffectSlotiDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alAuxiliaryEffectSloti"), typeof(alAuxiliaryEffectSlotiDelegate)); alAuxiliaryEffectSlotf = (alAuxiliaryEffectSlotfDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alAuxiliaryEffectSlotf"), typeof(alAuxiliaryEffectSlotfDelegate)); alGenFilters = (alGenFiltersDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alGenFilters"), typeof(alGenFiltersDelegate)); alFilteri = (alFilteriDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alFilteri"), typeof(alFilteriDelegate)); alFilterf = (alFilterfDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alFilterf"), typeof(alFilterfDelegate)); alDeleteFilters = (alDeleteFiltersDelegate)Marshal.GetDelegateForFunctionPointer(AL.alGetProcAddress("alDeleteFilters"), typeof(alDeleteFiltersDelegate)); IsInitialized = true; } internal bool IsInitialized { get; private set; } /* alEffecti (effect, EfxEffecti.FilterType, (int)EfxEffectType.Reverb); ALHelper.CheckError ("Failed to set Filter Type."); */ internal void GenAuxiliaryEffectSlots(int count, out uint slot) { this.alGenAuxiliaryEffectSlots(count, out slot); ALHelper.CheckError("Failed to Genereate Aux slot"); } internal void GenEffect(out uint effect) { this.alGenEffects(1, out effect); ALHelper.CheckError("Failed to Generate Effect."); } internal void DeleteAuxiliaryEffectSlot(int slot) { alDeleteAuxiliaryEffectSlots(1, ref slot); } internal void DeleteEffect(int effect) { alDeleteEffects(1, ref effect); } internal void BindEffectToAuxiliarySlot(uint slot, uint effect) { alAuxiliaryEffectSloti(slot, EfxEffecti.SlotEffect, effect); ALHelper.CheckError("Failed to bind Effect"); } internal void AuxiliaryEffectSlot(uint slot, EfxEffectSlotf param, float value) { alAuxiliaryEffectSlotf(slot, param, value); ALHelper.CheckError("Failes to set " + param + " " + value); } internal void BindSourceToAuxiliarySlot(int SourceId, int slot, int slotnumber, int filter) { AL.alSource3i(SourceId, ALSourcei.EfxAuxilarySendFilter, slot, slotnumber, filter); } internal void Effect(uint effect, EfxEffectf param, float value) { alEffectf(effect, param, value); ALHelper.CheckError("Failed to set " + param + " " + value); } internal void Effect(uint effect, EfxEffecti param, int value) { alEffecti(effect, param, value); ALHelper.CheckError("Failed to set " + param + " " + value); } internal unsafe int GenFilter() { uint filter = 0; this.alGenFilters(1, &filter); return (int)filter; } internal void Filter(int sourceId, EfxFilteri filter, int EfxFilterType) { this.alFilteri((uint)sourceId, filter, EfxFilterType); } internal void Filter(int sourceId, EfxFilterf filter, float EfxFilterType) { this.alFilterf((uint)sourceId, filter, EfxFilterType); } internal void BindFilterToSource(int sourceId, int filterId) { AL.Source(sourceId, ALSourcei.EfxDirectFilter, filterId); } internal unsafe void DeleteFilter(int filterId) { alDeleteFilters(1, (uint*)&filterId); } } }
40.455711
218
0.676846
[ "MIT" ]
Alan-love/MonoGame
MonoGame.Framework/Platform/Audio/OpenAL.cs
34,713
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace StreamJsonRpc { /// <summary> /// Interface optionally implemented by <see cref="IJsonRpcMessageFormatter" /> implementations that need a reference to their owner <see cref="JsonRpc" /> class. /// </summary> public interface IJsonRpcInstanceContainer { /// <summary> /// Sets the <see cref="JsonRpc"/> instance. /// </summary> /// <exception cref="System.InvalidOperationException">May be thrown when set more than once.</exception> JsonRpc Rpc { set; } } }
34.52381
166
0.648276
[ "MIT" ]
AbhitejJohn/vs-streamjsonrpc
src/StreamJsonRpc/IJsonRpcInstanceContainer.cs
727
C#
// Copyright 2015 Sascha-Christian Hensel // // 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 ezNReporting.Template.Composition; namespace ezNReporting.Template.Section { /// <summary> /// Defines members of a section, which is a logical grouping within a report. /// </summary> public interface IReportTemplateSection { /// <summary> /// Gets the section type. /// </summary> SectionType Type { get; } /// <summary> /// Gets/sets an element representing the root container of this section. /// </summary> /// <exception cref="System.ArgumentNullException">The root element is being set to a null value.</exception> ICompositionElement RootElement { get; set; } } }
36.571429
117
0.684375
[ "Apache-2.0" ]
AliAlbasrawi/a9
ezNReporting/Template/Section/IReportTemplateSection.cs
1,282
C#
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("OxideTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OxideTest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("89f02c4c-1b90-4484-850b-32d33a2c4b30")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
34.74359
84
0.738745
[ "MIT" ]
bgourlie/BriansMod
Oxide.Ext.BriansMod/Properties/AssemblyInfo.cs
1,358
C#
using Aya.Events; namespace Aya.Sample { [EventEnum] public enum EventType003 { Event01, Event02, } public class UserCSharpClass003 : ObjectListener { [Listen(EventType003.Event01)] public void ListenMethod01() { } [Listen(EventType003.Event01, 9, true)] public void ListenMethod02(object eventType) { } [Listen(EventType003.Event01, 5)] public void ListenMethod03() { } [Listen(EventType003.Event01, EventType003.Event02)] public void ListenMethod04() { } [ListenType(typeof(EventType003))] public void ListenMethod05() { } [ListenGroup(EventType003.Event01, "Group01")] public void ListenMethod06() { } } }
16.538462
60
0.545349
[ "MIT" ]
ls9512/UEvent
Samples/Script/Example_003_ListenEvent.cs
862
C#
using RecensysCoreRepository.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RecensysCoreRepository.Repositories { public interface IDistributionRepository: IDisposable { DistributionDTO Read(int stageId); bool Update(DistributionDTO dto); } }
22.6
57
0.766962
[ "MIT" ]
cholewa1992/ReviewIT-backend
ReviewIT-Backend/RecensysCoreRepository/Repositories/IDistributionRepository.cs
341
C#
using System; using AudioMog.Application.AudioFileRebuilder; using AudioMog.Core.Audio; namespace AudioMog.Application.Codecs { public abstract class ACodec { public abstract string FileFormat { get; } public abstract void ExtractOriginal(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string outputPath); public abstract void ExtractAsWav(IApplicationLogger logger, MaterialSection.MaterialEntry entry, byte[] fullFileBytes, string wavPath); public abstract void FixHeader(TemporaryTrack track); protected void WriteUint(byte[] bytes, int offset, uint value) { var sizeBytes = BitConverter.GetBytes(value); Buffer.BlockCopy(sizeBytes, 0, bytes, offset, sizeBytes.Length); } protected void WriteUshort(byte[] bytes, int offset, ushort value) { var sizeBytes = BitConverter.GetBytes(value); Buffer.BlockCopy(sizeBytes, 0, bytes, offset, sizeBytes.Length); } protected void WriteByte(byte[] bytes, int offset, byte value) { bytes[offset] = value; } } }
31.69697
144
0.760994
[ "MIT" ]
Yoraiz0r/AudioMog
AudioMogApplication/Codecs/ACodec.cs
1,048
C#
using System; using System.IO; using System.Threading; using NUnit.Framework; using Stash.caches; namespace Stash.Test.caches { [TestFixture] internal class RulesCacheTests { private ICache _cache; private string _key; private int _counter; private Func<object> _getter; private TimeSpan _timeout; private Func<Ticket, bool> _evictionRule; //private readonly TimeSpan _timeout; //private readonly Func<DateTime> _now; //_now = () => DateTime.UtcNow; //_builder = (value) => Ticket.GetInstance(value, _now()); [SetUp] public void SetUp() { _key = Path.GetRandomFileName(); _counter = 0; _getter = () => ++_counter; _timeout = TimeSpan.FromMilliseconds(250); _evictionRule = (ticket) => DateTime.UtcNow > ticket.Created + _timeout; _cache = new Cache(_evictionRule); } [Test] public void WhenSuppliedKeyIsNullOrEmpty_PutThrowsError() { var expectedValue = new Random().Next(); Assert.Throws<ArgumentNullException>(() => _cache.Set(null, expectedValue)); Assert.Throws<ArgumentNullException>(() => _cache.Set(string.Empty, expectedValue)); } [Test] public void WhenSuppliedIsNullOrEmpty_ReturnsValueFromGetter() { var counter = 0; Func<int> getter = () => ++counter; Assert.AreEqual(1, _cache.Get(null, getter)); Assert.AreEqual(2, _cache.Get(null, getter)); Assert.AreEqual(3, _cache.Get(string.Empty, getter)); Assert.AreEqual(4, _cache.Get(string.Empty, getter)); } [Test] public void WhenNullValueIsPut_GetReturnsNull() { string expectedValue = null; Func<string> getter = () => "abc123"; var key = Path.GetRandomFileName(); _cache.Set(key, expectedValue); Assert.AreEqual(expectedValue, _cache.Get(key, getter)); } [Test] public void WhenValueIsPut_GetReturnsThatValue() { var expectedValue = new Random().Next(); Func<int> getter = () => ++expectedValue; var key = Path.GetRandomFileName(); _cache.Set(key, expectedValue - 1); _cache.Set(key, expectedValue); Assert.AreEqual(expectedValue, _cache.Get(key, getter)); } [Test] public void IfStoredTypeCanBeConvertedToTValue_ThenConvertIt() { var expectedValue = new Random().Next(); Func<string> getter = () => "abc123"; var key = Path.GetRandomFileName(); // put an int in _cache.Set(key, expectedValue); // get a string out? Should be OK string actual; actual = _cache.Get<string>(key, null); Assert.AreEqual(expectedValue.ToString(), actual); } [Test] public void IfStoredTypeCannotBeConvertedToTValue_ThenThrow() { var expectedValue = new Random().Next(); Func<DateTime> getter = () => DateTime.Now; var key = Path.GetRandomFileName(); // put an int in _cache.Set(key, expectedValue); // Get a date/time out? Nope. DateTime actual; Assert.Throws<ArgumentException>(() => actual = _cache.Get(key, getter)); } [Test] public void WhenKeyIsMissing_GetStoresAndReturnsValueFromGetter() { var key = Path.GetRandomFileName(); var counter = 0; Func<int> getter = () => ++counter; Assert.AreEqual(1, _cache.Get(key, getter)); Assert.AreEqual(1, _cache.Get(key, getter)); Assert.AreEqual(1, _cache.Get(key, getter)); } [Test] public void Clear_EmptiesCache() { Assert.AreEqual(0, _cache.Count); var expected = new Random().Next(50, 100); for (var i = 1; i <= expected; i++) { _cache.Set($"key{i}", Path.GetRandomFileName()); Assert.AreEqual(i, _cache.Count); } Assert.AreEqual(expected, _cache.Count); _cache.Clear(); Assert.AreEqual(0, _cache.Count); } [Test] public void Size_ReportsSize() { Assert.AreEqual(0, _cache.Count); var expected = new Random().Next(50, 100); for (var i = 1; i <= expected; i++) { _cache.Set($"key{i}", Path.GetRandomFileName()); Assert.AreEqual(i, _cache.Count); } Assert.AreEqual(expected, _cache.Count); } [Test] public void Count_checksAndEvicts() { //var cache = new Cache(_ticketBuilder, _evictionRule); Assert.AreEqual(0, _cache.Count); _cache.Set(_key, _getter); Assert.AreEqual(1, _cache.Count); Thread.Sleep(TimeSpan.FromMilliseconds(500)); Assert.AreEqual(0, _cache.Count); } [Test] public void Get_appliesEvictionRule() { _counter = 0; // doesn't exist, get new thing var actual = _cache.Get(_key, _getter); Assert.AreEqual(1, actual); // Exists and not expired, get existing value actual = _cache.Get(_key, _getter); Assert.AreEqual(1, actual); Thread.Sleep(TimeSpan.FromMilliseconds(500)); // Exists but expired, get new value actual = _cache.Get(_key, _getter); Assert.AreEqual(2, actual); // Exists and not expired, get existing value actual = _cache.Get(_key, _getter); Assert.AreEqual(2, actual); } } }
30.917526
96
0.543014
[ "MIT" ]
PanelOfExperts/Stash
Source/Tests.Stash/caches/RulesCacheTests.cs
6,000
C#
namespace _10.Car_Salesman { using System; using System.Text; public class Car { private string model; private Engine engine; private string color; private int weight; public Car(string model, Engine engine) { Model = model; Engine = engine; } public Car(string model, Engine engine, int weight) : this(model, engine) { Weight = weight; } public Car(string model, Engine engine, string color) : this(model, engine) { Color = color; } public Car(string model, Engine engine, int weight, string color) : this(model, engine) { Weight = weight; Color = color; } public string Color { get { return color; } set { color = value; } } public int Weight { get { return weight; } set { weight = value; } } public Engine Engine { get { return engine; } set { engine = value; } } public string Model { get { return model; } set { model = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append($"{this.model}: {Environment.NewLine}"); sb.Append($" {this.engine.Model}: {Environment.NewLine}"); sb.Append($" Power: {this.engine.Power}{Environment.NewLine}"); if (this.engine.PowerDisplacement== -9999999) { sb.Append($" Displacement: n/a {Environment.NewLine}"); } else { sb.Append($" Displacement: {this.engine.PowerDisplacement}{Environment.NewLine}"); } sb.Append($" Efficiency: {this.engine.Efficiency}{Environment.NewLine}"); if (this.weight == -9999999) { sb.Append($" Weight: n/a {Environment.NewLine}"); } else { sb.Append($" Weight: {this.weight}{Environment.NewLine}"); } sb.Append($" Color: {this.color}"); return sb.ToString(); } } }
26.217391
101
0.461028
[ "MIT" ]
MihailDobrev/SoftUni
C# Fundamentals/C# OOP Basics/02. Defining Classes - Exercise/10. Car Salesman/Car.cs
2,414
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HarmornyHelper.forms { public partial class IntervalsControl : UserControl { public IntervalsControl() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } } }
16.846154
55
0.76484
[ "MIT" ]
emorrison1962/HarmonyHelper
HarmonyHelper/HarmornyHelper.forms/Views/IntervalsControl.cs
440
C#
namespace DPSF_Demo { /// <summary> /// The main entry point for the application. /// </summary> static class ApplicationEntryPoint { /// <summary> /// The application entry point when this project is set as the Startup Project. /// </summary> private static void Main() { using (var game = new DPSFDemo()) { BasicVirtualEnvironment.ApplicationEntryPoint.RunGame(game); } } } }
21.526316
82
0.669927
[ "MIT" ]
deadlydog/DPSF-XNA
XNA 4.0/Installer/Installer Files/DPSF Demo/DPSF Demo/DPSF Demo/ApplicationEntryPoint.cs
411
C#
/* * Copyright (c) Contributors, http://vision-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Vision-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; namespace Vision.Framework.Services.ClassHelpers.Other { /// <summary> /// Delegate to fire when a generic event comes in /// </summary> /// <param name="FunctionName">Name of the event being fired</param> /// <param name="parameters">Parameters that the event has, can be null</param> public delegate object OnGenericEventHandler(string FunctionName, object parameters); /// <summary> /// A generic event manager that fires one event for many generic events /// </summary> public class VisionEventManager { private readonly Dictionary<string, List<OnGenericEventHandler>> m_events = new Dictionary<string, List<OnGenericEventHandler>>(); /// <summary> /// Events so far: /// DrawDistanceChanged - Changed Draw Distance /// parameter is a ScenePresence /// BanUser - Added a new banned user to the estate bans /// parameter is a UUID of an agent /// UnBanUser - Removed a banned user from the estate bans /// parameter is a UUID of an agent /// SignficantCameraMovement - The Camera has moved a distance that has triggered this update /// parameter is a ScenePresence /// ObjectChangedOwner - An object's owner was changed /// parameter is a SceneObjectGroup /// ObjectChangedPhysicalStatus - An object's physical status has changed /// parameter is a SceneObjectGroup /// ObjectEnteringNewParcel - An object has entered a new parcel /// parameter is an object[], with o[0] a SceneObjectGroup, o[1] the new parcel UUID, and o[2] the old parcel UUID /// UserStatusChange - User's status (logged in/out) has changed /// parameter is a object[], with o[0] the UUID of the user (as a string), o[1] whether they are logging in, o[2] the region they are entering (if logging in) /// PreRegisterRegion - A region is about to be registered /// parameter is a GridRegion /// NewUserConnection - A new user has been added to the scene (child or root) /// parameter is an object[], with o[0] the AgentCircuitData that will be added to the region /// EstateUpdated - An estate has been updated /// parameter is the EstateSettings of the changed estate /// ObjectAddedFlag - An object in the Scene has added a prim flag /// parameter is an object[], with o[0] a ISceneChildEntity and o[1] the flag that was changed /// ObjectRemovedFlag - An object in the Scene has removed a prim flag /// parameter is an object[], with o[0] a ISceneChildEntity and o[1] the flag that was changed /// SetAppearance - An avatar has updated their appearance /// parameter is an object[], with o[0] the UUID of the avatar and o[1] the AvatarData that is to be updated /// GridRegionSuccessfullyRegistered - Vision.Server, A region has registered with the grid service /// parameter is an object[], with o[0] the OSDMap which will be sent to the new region, o[1] the SessionID, o[2] the GridRegion that registered /// Backup - The 'backup' console command was triggered, everything should backup /// no parameters /// DeleteUserInformation - The user is being deleted, remove all of their information from all databases /// parameter are the user's UUID /// CreateUserInformation - The user account is being created /// parameter are the user's UUID /// UpdateUserInformation - The user account is being updated /// parameter are the user's UUID /// </summary> public void RegisterEventHandler(string functionName, OnGenericEventHandler handler) { lock (m_events) { if (!m_events.ContainsKey(functionName)) m_events.Add(functionName, new List<OnGenericEventHandler>()); m_events[functionName].Add(handler); } } public void UnregisterEventHandler(string functionName, OnGenericEventHandler handler) { lock (m_events) { if (!m_events.ContainsKey(functionName)) return; m_events[functionName].Remove(handler); } } /// <summary> /// Fire a generic event for all modules hooking onto it /// </summary> /// <param name="FunctionName">Name of event to trigger</param> /// <param name="Param">Any parameters to pass along with the event</param> public List<object> FireGenericEventHandler(string FunctionName, object Param) { List<object> retVal = new List<object>(); lock (m_events) { //If not null, fire for all List<OnGenericEventHandler> events; if (m_events.TryGetValue(FunctionName, out events)) { retVal.AddRange( new List<OnGenericEventHandler>(events).Select(handler => handler(FunctionName, Param)) .Where(param => param != null)); } } return retVal; } } }
55.255639
171
0.628521
[ "MIT" ]
VisionSim/Vision-Sim
Vision/Framework/Services/ClassHelpers/Other/VisionEventManager.cs
7,349
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Dolittle.Runtime.Artifacts; using Dolittle.Runtime.Embeddings.Store; using Dolittle.Runtime.Events.Store; using Dolittle.Runtime.Projections.Store; using Dolittle.Runtime.Rudimentary; using Machine.Specifications; using It = Machine.Specifications.It; namespace Dolittle.Runtime.Embeddings.Processing.for_EmbeddingStateUpdater.when_updating; public class from_many_events : given.all_dependencies { static ProjectionKey projection_key; static EmbeddingCurrentState current_state; static CommittedAggregateEvent unprocessed_event; static CommittedAggregateEvents unprocessed_events; static EmbeddingCurrentState projection_result; Establish context = () => { projection_key = "projection-key"; current_state = new EmbeddingCurrentState(3, EmbeddingCurrentStateType.Persisted, "state-current", projection_key); unprocessed_event = new CommittedAggregateEvent(new Artifact(embedding.Value, ArtifactGeneration.First), 3, 10, DateTimeOffset.Now, projection_key.Value, execution_context, event_type, false, "event-one-content"); unprocessed_events = new CommittedAggregateEvents(projection_key.Value, embedding.Value, new[] { unprocessed_event }); projection_result = new EmbeddingCurrentState(current_state.Version.Value + 3, EmbeddingCurrentStateType.Persisted, "state-updated", projection_key); embedding_store .Setup(_ => _.TryGetKeys(embedding, cancellation_token)) .Returns(Task.FromResult<Try<IEnumerable<ProjectionKey>>>(new[] { projection_key })); embedding_store .Setup(_ => _.TryGet(embedding, projection_key, cancellation_token)) .Returns(Task.FromResult<Try<EmbeddingCurrentState>>(current_state)); embedding_store .Setup(_ => _.TryReplace(embedding, projection_key, projection_result.Version, projection_result.State, cancellation_token)) .Returns(Task.FromResult(Try.Succeeded())); committed_events_fetcher .Setup(_ => _.FetchForAggregateAfter(projection_key.Value, embedding.Value, current_state.Version, cancellation_token)) .Returns(Task.FromResult(unprocessed_events)); project_many_events .Setup(_ => _.TryProject(current_state, unprocessed_events, execution_context, Moq.It.IsAny<CancellationToken>())) .Returns(Task.FromResult<Partial<EmbeddingCurrentState>>(projection_result)); }; static Try result; Because of = () => result = state_updater.TryUpdateAll(execution_context, cancellation_token).GetAwaiter().GetResult(); It should_succeed = () => result.Success.ShouldBeTrue(); It should_ask_the_embedding_store_for_keys = () => embedding_store.Verify(_ => _.TryGetKeys(embedding, cancellation_token)); It should_get_the_last_state_from_the_embedding_store = () => embedding_store.Verify(_ => _.TryGet(embedding, projection_key, cancellation_token)); It should_ask_the_event_store_for_new_events = () => committed_events_fetcher.Verify(_ => _.FetchForAggregateAfter(projection_key.Value, embedding.Value, current_state.Version, cancellation_token)); It should_project_the_events = () => project_many_events.Verify(_ => _.TryProject(current_state, unprocessed_events, execution_context, cancellation_token)); It should_store_the_final_state = () => embedding_store.Verify(_ => _.TryReplace(embedding, projection_key, projection_result.Version, projection_result.State, cancellation_token)); It should_not_store_any_intermediate_states = () => embedding_store.VerifyNoOtherCalls(); }
62.803279
221
0.767946
[ "MIT" ]
dolittle-runtime/Runtime
Specifications/Embeddings.Processing/for_EmbeddingStateUpdater/when_updating/from_many_events.cs
3,831
C#
/* Copyright 2020-2021. Huawei Technologies Co., Ltd. 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.IO; using Huawei.Agconnect.Config; using Android.Content; using Android.Util; /* * This class is used to read agconnect-service file. */ namespace HMSSample { public class HmsLazyInputStream : LazyInputStream { public HmsLazyInputStream(Context context) : base(context) { } public override Stream Get(Context context) { try { return context.Assets.Open("agconnect-services.json"); } catch (Exception e) { Log.Info(e.ToString(), "Can't open agconnect file"); return null; } } } }
27.795918
79
0.628488
[ "Apache-2.0" ]
HMS-Core/hms-xamarin-bindings
android/samples/LocationKitDemo/HMSSample/HmsLazyInputStream.cs
1,364
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("Task_OOP")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Task_OOP")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("5da6e241-28c8-492f-b654-f8cb3dbe4759")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.405405
84
0.746387
[ "Apache-2.0" ]
DeadDevelopmentInc/Task_OOP
Task_OOP/Task_OOP/Properties/AssemblyInfo.cs
1,387
C#
using Microsoft.Data.SqlClient; using System; using System.Data; namespace Zinger.Services.Providers { public class SqlServerQueryProvider : QueryProvider { public override ProviderType ProviderType => ProviderType.SqlServer; public SqlServerQueryProvider(string connectionString) : base(connectionString) { } protected override IDbDataAdapter GetAdapter(IDbCommand command) => new SqlDataAdapter(command as SqlCommand); public override IDbCommand GetCommand(string query, IDbConnection connection) => new SqlCommand(query, connection as SqlConnection); public override IDbConnection GetConnection() => new SqlConnection(_connectionString); protected override string AppendErrorMessage(Exception exc) { var lineNum = (exc as SqlException)?.LineNumber ?? 0; return (lineNum > 0) ? $" at line {lineNum}" : null; } } }
34.740741
140
0.703625
[ "MIT" ]
adamfoneil/Postulate.Zinger
Zinger/Services/Providers/SqlServerQueryProvider.cs
940
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace MoreMatchTypes.Match_Setup { public class MatchTypeHook { public static void ResetRules() { MoreMatchTypes_Form.moreMatchTypesForm.ResetModOptions(); } public static void SetLuchaRules() { MoreMatchTypes_Form.moreMatchTypesForm.cb_normalMatch.Checked = false; MoreMatchTypes_Form.moreMatchTypesForm.cb_luchaTag.Checked = true; if (Control.ModifierKeys == Keys.Shift) { MoreMatchTypes_Form.moreMatchTypesForm.cb_luchaFalls.Checked = true; } else { MoreMatchTypes_Form.moreMatchTypesForm.cb_luchaFalls.Checked = false; } } public static void SetEliminationRules() { MoreMatchTypes_Form.moreMatchTypesForm.cb_normalMatch.Checked = false; MoreMatchTypes_Form.moreMatchTypesForm.cb_elimination.Checked = true; if (Control.ModifierKeys == Keys.Shift) { MoreMatchTypes_Form.moreMatchTypesForm.cb_losersLeave.Checked = true; } else { MoreMatchTypes_Form.moreMatchTypesForm.cb_losersLeave.Checked = false; } } public static void SetTTTRules() { MoreMatchTypes_Form.moreMatchTypesForm.cb_normalMatch.Checked = false; MoreMatchTypes_Form.moreMatchTypesForm.cb_ttt.Checked = true; } #region Helper Methods private static void ShowMessage(String message) { MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion } }
30.733333
102
0.620933
[ "MIT" ]
timcanpy/MoreMatchTypes
MoreMatchTypes/Match Setup/MatchTypeHook.cs
1,846
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Globalization; using Newtonsoft.Json.Linq; using Squidex.ClientLibrary; using TestSuite.Model; namespace TestSuite.Fixtures { public class ContentQueryFixture1to10 : ContentFixture { public ContentQueryFixture1to10() : this("my-reads") { } protected ContentQueryFixture1to10(string schemaName = "my-schema") : base(schemaName) { Task.Run(async () => { #pragma warning disable MA0056 // Do not call overridable members in constructor Dispose(); #pragma warning restore MA0056 // Do not call overridable members in constructor for (var i = 10; i > 0; i--) { var text = i.ToString(CultureInfo.InvariantCulture); var data = new TestEntityData { String = text, Json = JObject.FromObject(new { nested1 = new { nested2 = i } }), Number = i, }; if (i % 2 == 0) { data.Geo = new { type = "Point", coordinates = new[] { i, i } }; } else { data.Geo = new { longitude = i, latitude = i }; } await Contents.CreateAsync(data, ContentCreateOptions.AsPublish); } }).Wait(); } public override void Dispose() { Task.Run(async () => { var contents = await Contents.GetAsync(); foreach (var content in contents.Items) { await Contents.DeleteAsync(content); } }).Wait(); GC.SuppressFinalize(this); } } }
31
88
0.396195
[ "MIT" ]
Appleseed/squidex
backend/tools/TestSuite/TestSuite.Shared/Fixtures/ContentQueryFixture1to10.cs
2,420
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using VideoManagement.Models.Tables; using VideoManagement.UI.WPF.Helpers; using VideoManagement.UI.WPF.ViewModels; namespace VideoManagement.UI.WPF.Views { /// <summary> /// Interaction logic for RecentPathsView.xaml /// </summary> public partial class RecentPathsView : UserControl { public RecentPathsView() { InitializeComponent(); DataContext = new RecentPathsViewModel(); recentPaths.MouseDoubleClick += RecentPaths_MouseDoubleClick; } private void RecentPaths_MouseDoubleClick(object sender, MouseButtonEventArgs e) { selectedItem = recentPaths.SelectedItem as RecentPath; } public RecentPath SelectedItem => selectedItem; private RecentPath selectedItem { get; set; } private void CopyCurrentPath_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; var textToCopy = btn.Tag.ToString(); CopyTool.CopyToClipboard(textToCopy); } } }
28.8
88
0.7
[ "MIT" ]
JDSRAO/VideoManagement
src/VideoManagement/VideoManagement.UI.WPF/Views/RecentPathsView.xaml.cs
1,442
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticfilesystem-2015-02-01.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.ElasticFileSystem.Model { /// <summary> /// Returned if an error occurred on the server side. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class InternalServerErrorException : AmazonElasticFileSystemException { private string _errorCode; /// <summary> /// Constructs a new InternalServerErrorException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InternalServerErrorException(string message) : base(message) {} /// <summary> /// Construct instance of InternalServerErrorException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InternalServerErrorException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InternalServerErrorException /// </summary> /// <param name="innerException"></param> public InternalServerErrorException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InternalServerErrorException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InternalServerErrorException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InternalServerErrorException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InternalServerErrorException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the InternalServerErrorException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InternalServerErrorException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.ErrorCode = (string)info.GetValue("ErrorCode", typeof(string)); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ErrorCode", this.ErrorCode); } #endif /// <summary> /// Gets and sets the property ErrorCode. /// </summary> [AWSProperty(Required=true, Min=1)] public string ErrorCode { get { return this._errorCode; } set { this._errorCode = value; } } // Check to see if ErrorCode property is set internal bool IsSetErrorCode() { return this._errorCode != null; } } }
46.552448
179
0.656302
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ElasticFileSystem/Generated/Model/InternalServerErrorException.cs
6,657
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 ILCompiler.Reflection.ReadyToRun; using System; using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; using System.IO; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Text; using System.Threading.Tasks; using System.Xml; namespace R2RDump { public class DumpOptions : IAssemblyResolver { public FileInfo[] In { get; set; } public FileInfo Out { get; set; } public bool Xml { get; set; } public bool Raw { get; set; } public bool Header { get; set; } public bool Disasm { get; set; } public bool Naked { get; set; } public string[] Query { get; set; } public string[] Keyword { get; set; } public string[] RuntimeFunction { get; set; } public string[] Section { get; set; } public bool Unwind { get; set; } public bool GC { get; set; } public bool SectionContents { get; set; } public bool EntryPoints { get; set; } public bool Normalize { get; set; } public bool Verbose { get; set; } public bool Diff { get; set; } public bool IgnoreSensitive { get; set; } public FileInfo[] Reference { get; set; } public DirectoryInfo[] ReferencePath { get; set; } public bool SignatureBinary { get; set; } public bool InlineSignatureBinary { get; set; } public Dictionary<string, EcmaMetadataReader> AssemblyCache = new Dictionary<string, EcmaMetadataReader>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Probing extensions to use when looking up assemblies under reference paths. /// </summary> private readonly static string[] ProbeExtensions = new string[] { ".ni.exe", ".ni.dll", ".exe", ".dll" }; /// <summary> /// Try to locate a (reference) assembly using the list of explicit reference assemblies /// and the list of reference paths passed to R2RDump. /// </summary> /// <param name="simpleName">Simple name of the assembly to look up</param> /// <param name="parentFile">Name of assembly from which we're performing the lookup</param> /// <returns></returns> public string FindAssembly(string simpleName, string parentFile) { foreach (FileInfo refAsm in Reference ?? Enumerable.Empty<FileInfo>()) { if (Path.GetFileNameWithoutExtension(refAsm.FullName).Equals(simpleName, StringComparison.OrdinalIgnoreCase)) { return refAsm.FullName; } } IEnumerable<string> allRefPaths = new string[] { Path.GetDirectoryName(parentFile) } .Concat((ReferencePath ?? Enumerable.Empty<DirectoryInfo>()).Select(path => path.FullName)); foreach (string refPath in allRefPaths) { foreach (string extension in ProbeExtensions) { string probeFile = Path.Combine(refPath, simpleName + extension); if (File.Exists(probeFile)) { return probeFile; } } } return null; } } public abstract class Dumper { protected readonly R2RReader _r2r; protected TextWriter _writer; protected readonly Disassembler _disassembler; protected readonly DumpOptions _options; public Dumper(R2RReader r2r, TextWriter writer, Disassembler disassembler, DumpOptions options) { _r2r = r2r; _writer = writer; _disassembler = disassembler; _options = options; } public IEnumerable<R2RSection> NormalizedSections() { IEnumerable<R2RSection> sections = _r2r.R2RHeader.Sections.Values; if (_options.Normalize) { sections = sections.OrderBy((s) => s.Type); } return sections; } public IEnumerable<R2RMethod> NormalizedMethods() { IEnumerable<R2RMethod> methods = _r2r.R2RMethods; if (_options.Normalize) { methods = methods.OrderBy((m) => m.SignatureString); } return methods; } /// <summary> /// Run right before printing output /// </summary> abstract internal void Begin(); /// <summary> /// Run right after printing output /// </summary> abstract internal void End(); abstract internal void WriteDivider(string title); abstract internal void WriteSubDivider(); abstract internal void SkipLine(); abstract internal void DumpHeader(bool dumpSections); abstract internal void DumpSection(R2RSection section, XmlNode parentNode = null); abstract internal void DumpEntryPoints(); abstract internal void DumpAllMethods(); abstract internal void DumpMethod(R2RMethod method, XmlNode parentNode = null); abstract internal void DumpRuntimeFunction(RuntimeFunction rtf, XmlNode parentNode = null); abstract internal void DumpDisasm(RuntimeFunction rtf, int imageOffset, XmlNode parentNode = null); abstract internal void DumpBytes(int rva, uint size, XmlNode parentNode = null, string name = "Raw", bool convertToOffset = true); abstract internal void DumpSectionContents(R2RSection section, XmlNode parentNode = null); abstract internal XmlNode DumpQueryCount(string q, string title, int count); } class R2RDump { private readonly DumpOptions _options; private readonly TextWriter _writer; private readonly Dictionary<R2RSection.SectionType, bool> _selectedSections = new Dictionary<R2RSection.SectionType, bool>(); private Dumper _dumper; private R2RDump(DumpOptions options) { _options = options; if (_options.Verbose) { _options.Disasm = true; _options.Unwind = true; _options.GC = true; _options.SectionContents = true; } // open output stream if (_options.Out != null) { _writer = new StreamWriter(_options.Out.FullName, append: false, encoding: Encoding.ASCII); } else { _writer = Console.Out; } } private static int ArgStringToInt(string arg) { int n; if (!ArgStringToInt(arg, out n)) { throw new ArgumentException("Can't parse argument to int"); } return n; } /// <summary> /// Converts string passed as cmd line args into int, works for hexadecimal with 0x as prefix /// </summary> /// <param name="arg">The argument string to convert</param> /// <param name="n">The integer representation</param> private static bool ArgStringToInt(string arg, out int n) { arg = arg.Trim(); if (arg.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { return int.TryParse(arg.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out n); } return int.TryParse(arg, out n); } /// <summary> /// Outputs a warning message /// </summary> /// <param name="warning">The warning message to output</param> public static void WriteWarning(string warning) { Console.WriteLine($"Warning: {warning}"); } // <summary> /// For each query in the list of queries, dump all methods matching the query by name, signature or id /// </summary> /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param> /// <param name="title">The title to print, "R2R Methods by Query" or "R2R Methods by Keyword"</param> /// <param name="queries">The keywords/ids to search for</param> /// <param name="exact">Specifies whether to look for methods with names/signatures/ids matching the method exactly or partially</param> private void QueryMethod(R2RReader r2r, string title, IReadOnlyList<string> queries, bool exact) { if (queries.Count > 0) { _dumper.WriteDivider(title); } foreach (string q in queries) { IList<R2RMethod> res = FindMethod(r2r, q, exact); XmlNode queryNode = _dumper.DumpQueryCount(q, "Methods", res.Count); foreach (R2RMethod method in res) { _dumper.DumpMethod(method, queryNode); } } } // <summary> /// For each query in the list of queries, dump all sections by the name or value of the ReadyToRunSectionType enum /// </summary> /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param> /// <param name="queries">The names/values to search for</param> private void QuerySection(R2RReader r2r, IReadOnlyList<string> queries) { if (queries.Count > 0) { _dumper.WriteDivider("R2R Section"); } foreach (string q in queries) { IList<R2RSection> res = FindSection(r2r, q); XmlNode queryNode = _dumper.DumpQueryCount(q, "Sections", res.Count); foreach (R2RSection section in res) { _dumper.DumpSection(section, queryNode); } } } // <summary> /// For each query in the list of queries, dump a runtime function by id. /// The method containing the runtime function gets outputted, along with the single runtime function that was searched /// </summary> /// <param name="r2r">Contains all the extracted info about the ReadyToRun image</param> /// <param name="queries">The ids to search for</param> private void QueryRuntimeFunction(R2RReader r2r, IEnumerable<string> queries) { if (queries.Any()) { _dumper.WriteDivider("Runtime Functions"); } foreach (string q in queries) { RuntimeFunction rtf = FindRuntimeFunction(r2r, ArgStringToInt(q)); if (rtf == null) { WriteWarning("Unable to find by id " + q); continue; } XmlNode queryNode = _dumper.DumpQueryCount(q.ToString(), "Runtime Function", 1); _dumper.DumpRuntimeFunction(rtf, queryNode); } } /// <summary> /// Outputs specified headers, sections, methods or runtime functions for one ReadyToRun image /// </summary> /// <param name="r2r">The structure containing the info of the ReadyToRun image</param> public void Dump(R2RReader r2r) { _dumper.Begin(); if (_options.Header || !_options.EntryPoints) { _dumper.WriteDivider("R2R Header"); _dumper.DumpHeader(true); } bool haveQuery = false; if (_options.Section != null) { haveQuery = true; QuerySection(r2r, _options.Section); } if (_options.RuntimeFunction != null) { haveQuery = true; QueryRuntimeFunction(r2r, _options.RuntimeFunction); } if (_options.Query != null) { haveQuery = true; QueryMethod(r2r, "R2R Methods by Query", _options.Query, true); } if (_options.Keyword != null) { haveQuery = true; QueryMethod(r2r, "R2R Methods by Keyword", _options.Keyword, false); } if (!haveQuery) { // Dump all sections and methods if no queries specified if (_options.EntryPoints) { _dumper.DumpEntryPoints(); } if (!_options.Header && !_options.EntryPoints) { _dumper.DumpAllMethods(); } } _dumper.End(); } /// <summary> /// Returns true if the name, signature or id of <param>method</param> matches <param>query</param> /// </summary> /// <param name="exact">Specifies exact or partial match</param> /// <remarks>Case-insensitive and ignores whitespace</remarks> private bool Match(R2RMethod method, string query, bool exact) { int id; bool isNum = ArgStringToInt(query, out id); bool idMatch = isNum && (method.Rid == id || MetadataTokens.GetRowNumber(method.MetadataReader, method.MethodHandle) == id); bool sigMatch = false; if (exact) { sigMatch = method.Name.Equals(query, StringComparison.OrdinalIgnoreCase); if (!sigMatch) { string sig = method.SignatureString.Replace(" ", ""); string q = query.Replace(" ", ""); int iMatch = sig.IndexOf(q, StringComparison.OrdinalIgnoreCase); sigMatch = (iMatch == 0 || (iMatch > 0 && iMatch == (sig.Length - q.Length) && sig[iMatch - 1] == '.')); } } else { string sig = method.Signature.ReturnType + method.SignatureString.Replace(" ", ""); sigMatch = (sig.IndexOf(query.Replace(" ", ""), StringComparison.OrdinalIgnoreCase) >= 0); } return idMatch || sigMatch; } /// <summary> /// Returns true if the name or value of the ReadyToRunSectionType of <param>section</param> matches <param>query</param> /// </summary> /// <remarks>Case-insensitive</remarks> private bool Match(R2RSection section, string query) { int queryInt; bool isNum = ArgStringToInt(query, out queryInt); string typeName = Enum.GetName(typeof(R2RSection.SectionType), section.Type); return (isNum && (int)section.Type == queryInt) || typeName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; } /// <summary> /// Finds all R2RMethods by name/signature/id matching <param>query</param> /// </summary> /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param> /// <param name="query">The name/signature/id to search for</param> /// <param name="exact">Specifies exact or partial match</param> /// <out name="res">List of all matching methods</out> /// <remarks>Case-insensitive and ignores whitespace</remarks> public IList<R2RMethod> FindMethod(R2RReader r2r, string query, bool exact) { List<R2RMethod> res = new List<R2RMethod>(); foreach (R2RMethod method in r2r.R2RMethods) { if (Match(method, query, exact)) { res.Add(method); } } return res; } /// <summary> /// Finds all R2RSections by name or value of the ReadyToRunSectionType matching <param>query</param> /// </summary> /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param> /// <param name="query">The name or value to search for</param> /// <out name="res">List of all matching sections</out> /// <remarks>Case-insensitive</remarks> public IList<R2RSection> FindSection(R2RReader r2r, string query) { List<R2RSection> res = new List<R2RSection>(); foreach (R2RSection section in r2r.R2RHeader.Sections.Values) { if (Match(section, query)) { res.Add(section); } } return res; } /// <summary> /// Returns the runtime function with id matching <param>rtfQuery</param> /// </summary> /// <param name="r2r">Contains all extracted info about the ReadyToRun image</param> /// <param name="rtfQuery">The name or value to search for</param> public RuntimeFunction FindRuntimeFunction(R2RReader r2r, int rtfQuery) { foreach (R2RMethod m in r2r.R2RMethods) { foreach (RuntimeFunction rtf in m.RuntimeFunctions) { if (rtf.Id == rtfQuery || (rtf.StartAddress >= rtfQuery && rtf.StartAddress + rtf.Size < rtfQuery)) { return rtf; } } } return null; } private int Run() { Disassembler disassembler = null; try { if (_options.In == null || _options.In.Length == 0) throw new ArgumentException("Input filename must be specified (--in <file>)"); if (_options.Diff && _options.In.Length < 2) throw new ArgumentException("Need at least 2 input files in diff mode"); if (_options.Naked && _options.Raw) { throw new ArgumentException("The option '--naked' is incompatible with '--raw'"); } R2RReader previousReader = null; foreach (FileInfo filename in _options.In) { // parse the ReadyToRun image R2RReader r2r = new R2RReader(_options, filename.FullName); if (_options.Disasm) { if (r2r.InputArchitectureSupported() && r2r.DisassemblerArchitectureSupported()) { disassembler = new Disassembler(r2r, _options); } else { throw new ArgumentException($"The architecture of input file {filename} ({r2r.Machine.ToString()}) or the architecture of the disassembler tools ({System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString()}) is not supported."); } } if (_options.Xml) { _dumper = new XmlDumper(_options.IgnoreSensitive, r2r, _writer, disassembler, _options); } else { _dumper = new TextDumper(r2r, _writer, disassembler, _options); } if (!_options.Diff) { // output the ReadyToRun info Dump(r2r); } else if (previousReader != null) { new R2RDiff(previousReader, r2r, _writer).Run(); } previousReader = r2r; } } catch (Exception e) { Console.WriteLine("Error: " + e.ToString()); if (e is ArgumentException) { Console.WriteLine(); } if (_options.Xml) { XmlDocument document = new XmlDocument(); XmlNode node = document.CreateNode("element", "Error", ""); node.InnerText = e.Message; document.AppendChild(node); if (_writer != null) { document.Save(_writer); } } return 1; } finally { if (disassembler != null) { disassembler.Dispose(); } // close output stream _writer.Close(); } return 0; } public static async Task<int> Main(string[] args) { var command = CommandLineOptions.RootCommand(); command.Handler = CommandHandler.Create<DumpOptions>((DumpOptions options) => new R2RDump(options).Run()); return await command.InvokeAsync(args); } } }
38.520947
278
0.537308
[ "MIT" ]
DrewScoggins/runtime
src/coreclr/src/tools/r2rdump/R2RDump.cs
21,150
C#
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( "org.secc.Mapping" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Southeast Christian Church" )] [assembly: AssemblyProduct( "org.secc.Mapping" )] [assembly: AssemblyCopyright( "Copyright © Southeast Christian Church 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( "749eb2a1-5240-4a1f-a0a1-110ea282ff7e" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
39.916667
84
0.736952
[ "ECL-2.0" ]
secc/RockPlugins
Plugins/org.secc.Mapping/Properties/AssemblyInfo.cs
1,440
C#
using System; using AppKit; using LogJoint.UI; using LogJoint.Drawing; using LJD = LogJoint.Drawing; using Foundation; using CoreGraphics; using System.Collections.Generic; using LogJoint.UI.Presenters.Postprocessing.StateInspectorVisualizer; namespace LogJoint.UI.Postprocessing.StateInspector { public class StateHistoryTableRowView: NSTableRowView { public StateInspectorWindowController owner; public int row; public IReadOnlyList<IStateHistoryItem> items; static LJD.Image bookmarkImage = new LJD.Image(NSImage.ImageNamed("Bookmark.png")); public override void DrawBackground(CGRect dirtyRect) { base.DrawBackground(dirtyRect); DrawFocusedMessage(); DrawBookmark(); } public override void DrawSelection(CGRect dirtyRect) { base.DrawSelection(dirtyRect); DrawFocusedMessage(); DrawBookmark(); } void DrawFocusedMessage() { Tuple<int, int> focused = owner.ViewModel.FocusedMessagePositionInChangeHistory; if (focused != null) { var frame = this.Frame.ToRectangleF (); float y; float itemH = frame.Height; SizeF markSize = UIUtils.FocusedItemMarkFrame.Size; if (focused.Item1 != focused.Item2) y = itemH * focused.Item1 + itemH / 2; else y = itemH * focused.Item1; if (Math.Abs(y) < .01f) y = markSize.Height / 2; y -= frame.Y; using (var g = new LogJoint.Drawing.Graphics()) { UIUtils.DrawFocusedItemMark(g, (float)owner.HistoryTableView.GetCellFrame(1, row).Left - 2, y, drawOuterFrame: true); } } } void DrawBookmark() { bool bookmarked = owner.ViewModel.IsChangeHistoryItemBookmarked(items [row]); if (bookmarked) { var frame = this.Frame.ToRectangleF (); float itemH = frame.Height; using (var g = new LogJoint.Drawing.Graphics()) { var sz = bookmarkImage.GetSize(width: 9); g.DrawImage(bookmarkImage, new RectangleF(new PointF( (float)owner.HistoryTableView.GetCellFrame(0, row).Left + 1, itemH * row + itemH / 2 - frame.Y - sz.Height / 2), sz)); } } } [Export ("insertText:")] void OnInsertText (NSObject theEvent) { var s = theEvent.ToString(); if (s == "b" || s == "B") { s.ToLower(); //owner.OnKeyEvent(Key.Bookmark); } } public override bool AcceptsFirstResponder () { return true; } } }
25.172043
92
0.681333
[ "MIT" ]
rkapl123/logjoint
trunk/platforms/osx/logjoint.mac/ui/Postprocessors/StateInspectorWindow/StateHistoryTableRowView.cs
2,343
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using AccountSetting = System.Collections.Generic.KeyValuePair<string, System.Func<string, bool>>; using ConnectionStringFilter = System.Func<System.Collections.Generic.IDictionary<string, string>, System.Collections.Generic.IDictionary<string, string>>; #pragma warning disable SA1402 // File may only contain a single type namespace Azure.Storage { internal class StorageConnectionString { /// <summary> /// Gets or sets a value indicating whether the FISMA MD5 setting will be used. /// </summary> /// <value><c>false</c> to use the FISMA MD5 setting; <c>true</c> to use the .NET default implementation.</value> internal static bool UseV1MD5 => true; /// <summary> /// Validator for the UseDevelopmentStorage setting. Must be "true". /// </summary> private static readonly AccountSetting s_useDevelopmentStorageSetting = Setting(Constants.ConnectionStrings.UseDevelopmentSetting, "true"); /// <summary> /// Validator for the DevelopmentStorageProxyUri setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_developmentStorageProxyUriSetting = Setting(Constants.ConnectionStrings.DevelopmentProxyUriSetting, IsValidUri); /// <summary> /// Validator for the DefaultEndpointsProtocol setting. Must be either "http" or "https". /// </summary> private static readonly AccountSetting s_defaultEndpointsProtocolSetting = Setting(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting, "http", "https"); /// <summary> /// Validator for the AccountName setting. No restrictions. /// </summary> private static readonly AccountSetting s_accountNameSetting = Setting(Constants.ConnectionStrings.AccountNameSetting); /// <summary> /// Validator for the AccountKey setting. No restrictions. /// </summary> private static readonly AccountSetting s_accountKeyNameSetting = Setting(Constants.ConnectionStrings.AccountKeyNameSetting); /// <summary> /// Validator for the AccountKey setting. Must be a valid base64 string. /// </summary> private static readonly AccountSetting s_accountKeySetting = Setting(Constants.ConnectionStrings.AccountKeySetting, IsValidBase64String); /// <summary> /// Validator for the BlobEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_blobEndpointSetting = Setting(Constants.ConnectionStrings.BlobEndpointSetting, IsValidUri); /// <summary> /// Validator for the QueueEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_queueEndpointSetting = Setting(Constants.ConnectionStrings.QueueEndpointSetting, IsValidUri); /// <summary> /// Validator for the FileEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_fileEndpointSetting = Setting(Constants.ConnectionStrings.FileEndpointSetting, IsValidUri); /// <summary> /// Validator for the TableEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_tableEndpointSetting = Setting(Constants.ConnectionStrings.TableEndpointSetting, IsValidUri); /// <summary> /// Validator for the BlobSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_blobSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.BlobSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the QueueSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_queueSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.QueueSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the FileSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_fileSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.FileSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the TableSecondaryEndpoint setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_tableSecondaryEndpointSetting = Setting(Constants.ConnectionStrings.TableSecondaryEndpointSetting, IsValidUri); /// <summary> /// Validator for the EndpointSuffix setting. Must be a valid Uri. /// </summary> private static readonly AccountSetting s_endpointSuffixSetting = Setting(Constants.ConnectionStrings.EndpointSuffixSetting, IsValidDomain); /// <summary> /// Validator for the SharedAccessSignature setting. No restrictions. /// </summary> private static readonly AccountSetting s_sharedAccessSignatureSetting = Setting(Constants.ConnectionStrings.SharedAccessSignatureSetting); /// <summary> /// Singleton instance for the development storage account. /// </summary> private static StorageConnectionString s_devStoreAccount; /// <summary> /// Initializes a new instance of the <see cref="StorageConnectionString"/> class using the specified /// account credentials and service endpoints. /// </summary> /// <param name="storageCredentials">A StorageCredentials object.</param> /// <param name="blobStorageUri">A <see cref="System.Uri"/> specifying the Blob service endpoint or endpoints.</param> /// <param name="queueStorageUri">A <see cref="System.Uri"/> specifying the Queue service endpoint or endpoints.</param> /// <param name="tableStorageUri">A <see cref="System.Uri"/> specifying the Table service endpoint or endpoints.</param> /// <param name="fileStorageUri">A <see cref="System.Uri"/> specifying the File service endpoint or endpoints.</param> public StorageConnectionString( object storageCredentials, (Uri Primary, Uri Secondary) blobStorageUri = default, (Uri Primary, Uri Secondary) queueStorageUri = default, (Uri Primary, Uri Secondary) tableStorageUri = default, (Uri Primary, Uri Secondary) fileStorageUri = default) { Credentials = storageCredentials; BlobStorageUri = blobStorageUri; QueueStorageUri = queueStorageUri; TableStorageUri = tableStorageUri; FileStorageUri = fileStorageUri; DefaultEndpoints = false; } /// <summary> /// Gets a <see cref="StorageConnectionString"/> object that references the well-known development storage account. /// </summary> /// <value>A <see cref="StorageConnectionString"/> object representing the development storage account.</value> public static StorageConnectionString DevelopmentStorageAccount { get { if (s_devStoreAccount == null) { s_devStoreAccount = GetDevelopmentStorageAccount(null); } return s_devStoreAccount; } } /// <summary> /// Indicates whether this account is a development storage account. /// </summary> internal bool IsDevStoreAccount { get; set; } /// <summary> /// The storage service hostname suffix set by the user, if any. /// </summary> internal string EndpointSuffix { get; set; } /// <summary> /// The connection string parsed into settings. /// </summary> internal IDictionary<string, string> Settings { get; set; } /// <summary> /// True if the user used a constructor that auto-generates endpoints. /// </summary> internal bool DefaultEndpoints { get; set; } /// <summary> /// Gets the primary endpoint for the Blob service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Blob service endpoint.</value> public Uri BlobEndpoint => BlobStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the Queue service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Queue service endpoint.</value> public Uri QueueEndpoint => QueueStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the Table service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary Table service endpoint.</value> public Uri TableEndpoint => TableStorageUri.PrimaryUri; /// <summary> /// Gets the primary endpoint for the File service, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the primary File service endpoint.</value> public Uri FileEndpoint => FileStorageUri.PrimaryUri; /// <summary> /// Gets the endpoints for the Blob service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Blob service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) BlobStorageUri { get; set; } /// <summary> /// Gets the endpoints for the Queue service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Queue service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) QueueStorageUri { get; set; } /// <summary> /// Gets the endpoints for the Table service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the Table service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) TableStorageUri { get; set; } /// <summary> /// Gets the endpoints for the File service at the primary and secondary location, as configured for the storage account. /// </summary> /// <value>A <see cref="System.Uri"/> containing the File service endpoints.</value> public (Uri PrimaryUri, Uri SecondaryUri) FileStorageUri { get; set; } /// <summary> /// Gets the credentials used to create this <see cref="StorageConnectionString"/> object. /// </summary> /// <value>A StorageCredentials object.</value> public object Credentials { get; set; } /// <summary> /// Private record of the account name for use in ToString(bool). /// </summary> internal string _accountName; /// <summary> /// Parses a connection string and returns a <see cref="StorageConnectionString"/> created /// from the connection string. /// </summary> /// <param name="connectionString">A valid connection string.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="connectionString"/> is null or empty.</exception> /// <exception cref="FormatException">Thrown if <paramref name="connectionString"/> is not a valid connection string.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="connectionString"/> cannot be parsed.</exception> /// <returns>A <see cref="StorageConnectionString"/> object constructed from the values provided in the connection string.</returns> public static StorageConnectionString Parse(string connectionString) { if (string.IsNullOrEmpty(connectionString)) { throw Errors.ArgumentNull(nameof(connectionString)); } if (ParseCore(connectionString, out StorageConnectionString ret, err => { throw Errors.InvalidFormat(err); })) { return ret; } throw Errors.ParsingConnectionStringFailed(); } /// <summary> /// Indicates whether a connection string can be parsed to return a <see cref="StorageConnectionString"/> object. /// </summary> /// <param name="connectionString">The connection string to parse.</param> /// <param name="account">A <see cref="StorageConnectionString"/> object to hold the instance returned if /// the connection string can be parsed.</param> /// <returns><b>true</b> if the connection string was successfully parsed; otherwise, <b>false</b>.</returns> public static bool TryParse(string connectionString, out StorageConnectionString account) { if (string.IsNullOrEmpty(connectionString)) { account = null; return false; } try { return ParseCore(connectionString, out account, err => { }); } catch (Exception) { account = null; return false; } } ///// <summary> ///// Returns a shared access signature for the account. ///// </summary> ///// <param name="policy">A <see cref="SharedAccessAccountPolicy"/> object specifying the access policy for the shared access signature.</param> ///// <returns>A shared access signature, as a URI query string.</returns> ///// <remarks>The query string returned includes the leading question mark.</remarks> //public string GetSharedAccessSignature(SharedAccessAccountPolicy policy) //{ // if (!this.Credentials.IsSharedKey) // { // var errorMessage = String.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey); // throw new InvalidOperationException(errorMessage); // } // StorageAccountKey accountKey = this.Credentials.Key; // string signature = SharedAccessSignatureHelper.GetHash(policy, this.Credentials.AccountName, Constants.HeaderConstants.TargetStorageVersion, accountKey.KeyValue); // UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion); // return builder.ToString(); //} /// <summary> /// Returns a <see cref="StorageConnectionString"/> with development storage credentials using the specified proxy Uri. /// </summary> /// <param name="proxyUri">The proxy endpoint to use.</param> /// <returns>The new <see cref="StorageConnectionString"/>.</returns> private static StorageConnectionString GetDevelopmentStorageAccount(Uri proxyUri) { UriBuilder builder = proxyUri != null ? new UriBuilder(proxyUri.Scheme, proxyUri.Host) : new UriBuilder("http", "127.0.0.1"); builder.Path = Constants.ConnectionStrings.DevStoreAccountName; builder.Port = Constants.ConnectionStrings.BlobEndpointPortNumber; Uri blobEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.TableEndpointPortNumber; Uri tableEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.QueueEndpointPortNumber; Uri queueEndpoint = builder.Uri; builder.Path = Constants.ConnectionStrings.DevStoreAccountName + Constants.ConnectionStrings.SecondaryLocationAccountSuffix; builder.Port = Constants.ConnectionStrings.BlobEndpointPortNumber; Uri blobSecondaryEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.QueueEndpointPortNumber; Uri queueSecondaryEndpoint = builder.Uri; builder.Port = Constants.ConnectionStrings.TableEndpointPortNumber; Uri tableSecondaryEndpoint = builder.Uri; var credentials = new StorageSharedKeyCredential(Constants.ConnectionStrings.DevStoreAccountName, Constants.ConnectionStrings.DevStoreAccountKey); #pragma warning disable IDE0017 // Simplify object initialization var account = new StorageConnectionString( credentials, blobStorageUri: (blobEndpoint, blobSecondaryEndpoint), queueStorageUri: (queueEndpoint, queueSecondaryEndpoint), tableStorageUri: (tableEndpoint, tableSecondaryEndpoint), fileStorageUri: (default, default) /* fileStorageUri */); #pragma warning restore IDE0017 // Simplify object initialization #pragma warning disable IDE0028 // Simplify collection initialization account.Settings = new Dictionary<string, string>(); #pragma warning restore IDE0028 // Simplify collection initialization account.Settings.Add(Constants.ConnectionStrings.UseDevelopmentSetting, "true"); if (proxyUri != null) { account.Settings.Add(Constants.ConnectionStrings.DevelopmentProxyUriSetting, proxyUri.ToString()); } account.IsDevStoreAccount = true; return account; } /// <summary> /// Internal implementation of Parse/TryParse. /// </summary> /// <param name="connectionString">The string to parse.</param> /// <param name="accountInformation">The <see cref="StorageConnectionString"/> to return.</param> /// <param name="error">A callback for reporting errors.</param> /// <returns>If true, the parse was successful. Otherwise, false.</returns> internal static bool ParseCore(string connectionString, out StorageConnectionString accountInformation, Action<string> error) { IDictionary<string, string> settings = ParseStringIntoSettings(connectionString, error); // malformed settings string if (settings == null) { accountInformation = null; return false; } // helper method string settingOrDefault(string key) { settings.TryGetValue(key, out var result); return result; } // devstore case if (MatchesSpecification( settings, AllRequired(s_useDevelopmentStorageSetting), Optional(s_developmentStorageProxyUriSetting))) { accountInformation = settings.TryGetValue(Constants.ConnectionStrings.DevelopmentProxyUriSetting, out var proxyUri) ? GetDevelopmentStorageAccount(new Uri(proxyUri)) : DevelopmentStorageAccount; accountInformation.Settings = s_validCredentials(settings); return true; } // non-devstore case ConnectionStringFilter endpointsOptional = Optional( s_blobEndpointSetting, s_blobSecondaryEndpointSetting, s_queueEndpointSetting, s_queueSecondaryEndpointSetting, s_fileEndpointSetting, s_fileSecondaryEndpointSetting, s_tableEndpointSetting, s_tableSecondaryEndpointSetting // not supported but we don't want default connection string from portal to fail ); ConnectionStringFilter primaryEndpointRequired = AtLeastOne( s_blobEndpointSetting, s_queueEndpointSetting, s_fileEndpointSetting, s_tableEndpointSetting ); ConnectionStringFilter secondaryEndpointsOptional = Optional( s_blobSecondaryEndpointSetting, s_queueSecondaryEndpointSetting, s_fileSecondaryEndpointSetting, s_tableSecondaryEndpointSetting ); ConnectionStringFilter automaticEndpointsMatchSpec = MatchesExactly(MatchesAll( MatchesOne( MatchesAll(AllRequired(s_accountKeySetting), Optional(s_accountKeyNameSetting)), // Key + Name, Endpoints optional AllRequired(s_sharedAccessSignatureSetting) // SAS + Name, Endpoints optional ), AllRequired(s_accountNameSetting), // Name required to automatically create URIs endpointsOptional, Optional(s_defaultEndpointsProtocolSetting, s_endpointSuffixSetting) )); ConnectionStringFilter explicitEndpointsMatchSpec = MatchesExactly(MatchesAll( // Any Credentials, Endpoints must be explicitly declared s_validCredentials, primaryEndpointRequired, secondaryEndpointsOptional )); var matchesAutomaticEndpointsSpec = MatchesSpecification(settings, automaticEndpointsMatchSpec); var matchesExplicitEndpointsSpec = MatchesSpecification(settings, explicitEndpointsMatchSpec); if (matchesAutomaticEndpointsSpec || matchesExplicitEndpointsSpec) { if (matchesAutomaticEndpointsSpec && !settings.ContainsKey(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting)) { settings.Add(Constants.ConnectionStrings.DefaultEndpointsProtocolSetting, "https"); } var blobEndpoint = settingOrDefault(Constants.ConnectionStrings.BlobEndpointSetting); var queueEndpoint = settingOrDefault(Constants.ConnectionStrings.QueueEndpointSetting); var tableEndpoint = settingOrDefault(Constants.ConnectionStrings.TableEndpointSetting); var fileEndpoint = settingOrDefault(Constants.ConnectionStrings.FileEndpointSetting); var blobSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.BlobSecondaryEndpointSetting); var queueSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.QueueSecondaryEndpointSetting); var tableSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.TableSecondaryEndpointSetting); var fileSecondaryEndpoint = settingOrDefault(Constants.ConnectionStrings.FileSecondaryEndpointSetting); var sasToken = settingOrDefault(Constants.ConnectionStrings.SharedAccessSignatureSetting); // if secondary is specified, primary must also be specified static bool s_isValidEndpointPair(string primary, string secondary) => !string.IsNullOrWhiteSpace(primary) || /* primary is null, and... */ string.IsNullOrWhiteSpace(secondary); (Uri Primary, Uri Secondary) createStorageUri(string primary, string secondary, string sasToken, Func<IDictionary<string, string>, (Uri Primary, Uri Secondary)> factory) { return !string.IsNullOrWhiteSpace(secondary) && !string.IsNullOrWhiteSpace(primary) ? (CreateUri(primary, sasToken), CreateUri(secondary, sasToken)) : !string.IsNullOrWhiteSpace(primary) ? (CreateUri(primary, sasToken), default) : matchesAutomaticEndpointsSpec && factory != null ? factory(settings) : (default, default); static Uri CreateUri(string endpoint, string sasToken) { var builder = new UriBuilder(endpoint); if (!string.IsNullOrEmpty(builder.Query)) { builder.Query += "&" + sasToken; } else { builder.Query = sasToken; } return builder.Uri; } } if ( s_isValidEndpointPair(blobEndpoint, blobSecondaryEndpoint) && s_isValidEndpointPair(queueEndpoint, queueSecondaryEndpoint) && s_isValidEndpointPair(tableEndpoint, tableSecondaryEndpoint) && s_isValidEndpointPair(fileEndpoint, fileSecondaryEndpoint) ) { accountInformation = new StorageConnectionString( GetCredentials(settings), blobStorageUri: createStorageUri(blobEndpoint, blobSecondaryEndpoint, sasToken, ConstructBlobEndpoint), queueStorageUri: createStorageUri(queueEndpoint, queueSecondaryEndpoint, sasToken, ConstructQueueEndpoint), tableStorageUri: createStorageUri(tableEndpoint, tableSecondaryEndpoint, sasToken, ConstructTableEndpoint), fileStorageUri: createStorageUri(fileEndpoint, fileSecondaryEndpoint, sasToken, ConstructFileEndpoint) ) { EndpointSuffix = settingOrDefault(Constants.ConnectionStrings.EndpointSuffixSetting), Settings = s_validCredentials(settings) }; accountInformation._accountName = settingOrDefault(Constants.ConnectionStrings.AccountNameSetting); return true; } } // not valid accountInformation = null; error("No valid combination of account information found."); return false; } /// <summary> /// Tokenizes input and stores name value pairs. /// </summary> /// <param name="connectionString">The string to parse.</param> /// <param name="error">Error reporting delegate.</param> /// <returns>Tokenized collection.</returns> private static IDictionary<string, string> ParseStringIntoSettings(string connectionString, Action<string> error) { IDictionary<string, string> settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var splitted = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var nameValue in splitted) { var splittedNameValue = nameValue.Split(new char[] { '=' }, 2); if (splittedNameValue.Length != 2) { error("Settings must be of the form \"name=value\"."); return null; } if (settings.ContainsKey(splittedNameValue[0])) { error(string.Format(CultureInfo.InvariantCulture, "Duplicate setting '{0}' found.", splittedNameValue[0])); return null; } settings.Add(splittedNameValue[0], splittedNameValue[1]); } return settings; } /// <summary> /// Encapsulates a validation rule for an enumeration based account setting. /// </summary> /// <param name="name">The name of the setting.</param> /// <param name="validValues">A list of valid values for the setting.</param> /// <returns>An <see cref="AccountSetting"/> representing the enumeration constraint.</returns> private static AccountSetting Setting(string name, params string[] validValues) => new AccountSetting( name, (settingValue) => validValues.Length == 0 ? true : validValues.Contains(settingValue, StringComparer.OrdinalIgnoreCase) ); /// <summary> /// Encapsulates a validation rule using a func. /// </summary> /// <param name="name">The name of the setting.</param> /// <param name="isValid">A func that determines if the value is valid.</param> /// <returns>An <see cref="AccountSetting"/> representing the constraint.</returns> private static AccountSetting Setting(string name, Func<string, bool> isValid) => new AccountSetting(name, isValid); /// <summary> /// Determines whether the specified setting value is a valid base64 string. /// </summary> /// <param name="settingValue">The setting value.</param> /// <returns><c>true</c> if the specified setting value is a valid base64 string; otherwise, <c>false</c>.</returns> private static bool IsValidBase64String(string settingValue) { try { Convert.FromBase64String(settingValue); return true; } catch (FormatException) { return false; } } /// <summary> /// Validation function that validates Uris. /// </summary> /// <param name="settingValue">Value to validate.</param> /// <returns><c>true</c> if the specified setting value is a valid Uri; otherwise, <c>false</c>.</returns> private static bool IsValidUri(string settingValue) => Uri.IsWellFormedUriString(settingValue, UriKind.Absolute); /// <summary> /// Validation function that validates a domain name. /// </summary> /// <param name="settingValue">Value to validate.</param> /// <returns><c>true</c> if the specified setting value is a valid domain; otherwise, <c>false</c>.</returns> private static bool IsValidDomain(string settingValue) => Uri.CheckHostName(settingValue).Equals(UriHostNameType.Dns); /// <summary> /// Settings filter that requires all specified settings be present and valid. /// </summary> /// <param name="requiredSettings">A list of settings that must be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter AllRequired(params AccountSetting[] requiredSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (AccountSetting requirement in requiredSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); } else { return null; } } return result; }; /// <summary> /// Settings filter that removes optional values. /// </summary> /// <param name="optionalSettings">A list of settings that are optional.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter Optional(params AccountSetting[] optionalSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (AccountSetting requirement in optionalSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); } } return result; }; /// <summary> /// Settings filter that ensures that at least one setting is present. /// </summary> /// <param name="atLeastOneSettings">A list of settings of which one must be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")] private static ConnectionStringFilter AtLeastOne(params AccountSetting[] atLeastOneSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); var foundOne = false; foreach (AccountSetting requirement in atLeastOneSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { result.Remove(requirement.Key); foundOne = true; } } return foundOne ? result : null; }; /// <summary> /// Settings filter that ensures that none of the specified settings are present. /// </summary> /// <param name="atLeastOneSettings">A list of settings of which one must not be present.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")] private static ConnectionStringFilter None(params AccountSetting[] atLeastOneSettings) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); var foundOne = false; foreach (AccountSetting requirement in atLeastOneSettings) { if (result.TryGetValue(requirement.Key, out var value) && requirement.Value(value)) { foundOne = true; } } return foundOne ? null : result; }; /// <summary> /// Settings filter that ensures that all of the specified filters match. /// </summary> /// <param name="filters">A list of filters of which all must match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesAll(params ConnectionStringFilter[] filters) => (settings) => { IDictionary<string, string> result = new Dictionary<string, string>(settings, StringComparer.OrdinalIgnoreCase); foreach (ConnectionStringFilter filter in filters) { if (result == null) { break; } result = filter(result); } return result; }; /// <summary> /// Settings filter that ensures that exactly one filter matches. /// </summary> /// <param name="filters">A list of filters of which exactly one must match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesOne(params ConnectionStringFilter[] filters) => (settings) => { IDictionary<string, string>[] results = filters .Select(filter => filter(new Dictionary<string, string>(settings))) .Where(result => result != null) .Take(2) .ToArray(); return results.Length != 1 ? null : results.First(); }; /// <summary> /// Settings filter that ensures that the specified filter is an exact match. /// </summary> /// <param name="filter">A list of filters of which ensures that the specified filter is an exact match.</param> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static ConnectionStringFilter MatchesExactly(ConnectionStringFilter filter) => (settings) => { IDictionary<string, string> results = filter(settings); return results == null || results.Any() ? null : results; }; /// <summary> /// Settings filter that ensures that a valid combination of credentials is present. /// </summary> /// <returns>The remaining settings or <c>null</c> if the filter's requirement is not satisfied.</returns> private static readonly ConnectionStringFilter s_validCredentials = MatchesOne( MatchesAll(AllRequired(s_accountNameSetting, s_accountKeySetting), Optional(s_accountKeyNameSetting), None(s_sharedAccessSignatureSetting)), // AccountAndKey MatchesAll(AllRequired(s_sharedAccessSignatureSetting), Optional(s_accountNameSetting), None(s_accountKeySetting, s_accountKeyNameSetting)), // SharedAccessSignature (AccountName optional) None(s_accountNameSetting, s_accountKeySetting, s_accountKeyNameSetting, s_sharedAccessSignatureSetting) // Anonymous ); /// <summary> /// Tests to see if a given list of settings matches a set of filters exactly. /// </summary> /// <param name="settings">The settings to check.</param> /// <param name="constraints">A list of filters to check.</param> /// <returns> /// If any filter returns null, false. /// If there are any settings left over after all filters are processed, false. /// Otherwise true. /// </returns> private static bool MatchesSpecification( IDictionary<string, string> settings, params ConnectionStringFilter[] constraints) { foreach (ConnectionStringFilter constraint in constraints) { IDictionary<string, string> remainingSettings = constraint(settings); if (remainingSettings == null) { return false; } else { settings = remainingSettings; } } return !settings.Any(); } /// <summary> /// Gets a StorageCredentials object corresponding to whatever credentials are supplied in the given settings. /// </summary> /// <param name="settings">The settings to check.</param> /// <returns>The StorageCredentials object specified in the settings.</returns> private static object GetCredentials(IDictionary<string, string> settings) { settings.TryGetValue(Constants.ConnectionStrings.AccountNameSetting, out var accountName); settings.TryGetValue(Constants.ConnectionStrings.AccountKeySetting, out var accountKey); settings.TryGetValue(Constants.ConnectionStrings.SharedAccessSignatureSetting, out var sharedAccessSignature); // The accountKeyName isn't used //settings.TryGetValue(Constants.ConnectionStrings.AccountKeyNameSetting, out var accountKeyName); return accountName != null && accountKey != null && sharedAccessSignature == null ? new StorageSharedKeyCredential(accountName, accountKey/*, accountKeyName */) : (object)(accountKey == null /* && accountKeyName == null */ && sharedAccessSignature != null ? new SharedAccessSignatureCredentials(sharedAccessSignature) : null); } /// <summary> /// Gets the default blob endpoint using specified settings. /// </summary> /// <param name="settings">The settings to use.</param> /// <returns>The default blob endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructBlobEndpoint(IDictionary<string, string> settings) => ConstructBlobEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default blob endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default blob endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructBlobEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultBlobHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default file endpoint using specified settings. /// </summary> /// <param name="settings">The settings to use.</param> /// <returns>The default file endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructFileEndpoint(IDictionary<string, string> settings) => ConstructFileEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default file endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default file endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructFileEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultFileHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default queue endpoint using the specified settings. /// </summary> /// <param name="settings">The settings.</param> /// <returns>The default queue endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructQueueEndpoint(IDictionary<string, string> settings) => ConstructQueueEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default queue endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default queue endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructQueueEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultQueueHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Gets the default table endpoint using the specified settings. /// </summary> /// <param name="settings">The settings.</param> /// <returns>The default table endpoint.</returns> private static (Uri Primary, Uri Secondary) ConstructTableEndpoint(IDictionary<string, string> settings) => ConstructTableEndpoint( settings[Constants.ConnectionStrings.DefaultEndpointsProtocolSetting], settings[Constants.ConnectionStrings.AccountNameSetting], settings.ContainsKey(Constants.ConnectionStrings.EndpointSuffixSetting) ? settings[Constants.ConnectionStrings.EndpointSuffixSetting] : null, settings.ContainsKey(Constants.ConnectionStrings.SharedAccessSignatureSetting) ? settings[Constants.ConnectionStrings.SharedAccessSignatureSetting] : null); /// <summary> /// Gets the default queue endpoint using the specified protocol and account name. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns>The default table endpoint.</returns> internal static (Uri Primary, Uri Secondary) ConstructTableEndpoint(string scheme, string accountName, string endpointSuffix, string sasToken) { if (string.IsNullOrEmpty(scheme)) { throw Errors.ArgumentNull(nameof(scheme)); } if (string.IsNullOrEmpty(accountName)) { throw Errors.ArgumentNull(nameof(accountName)); } if (string.IsNullOrEmpty(endpointSuffix)) { endpointSuffix = Constants.ConnectionStrings.DefaultEndpointSuffix; } return ConstructUris(scheme, accountName, Constants.ConnectionStrings.DefaultTableHostnamePrefix, endpointSuffix, sasToken); } /// <summary> /// Construct the Primary/Secondary Uri tuple. /// </summary> /// <param name="scheme">The protocol to use.</param> /// <param name="accountName">The name of the storage account.</param> /// <param name="hostNamePrefix">Prefix that appears before the host name, e.g. "blob".</param> /// <param name="endpointSuffix">The Endpoint DNS suffix; use <c>null</c> for default.</param> /// <param name="sasToken">The sas token; use <c>null</c> for default.</param> /// <returns></returns> private static (Uri Primary, Uri Secondary) ConstructUris( string scheme, string accountName, string hostNamePrefix, string endpointSuffix, string sasToken) { var primaryUriBuilder = new UriBuilder { Scheme = scheme, Host = string.Format( CultureInfo.InvariantCulture, "{0}.{1}.{2}", accountName, hostNamePrefix, endpointSuffix), Query = sasToken }; var secondaryUriBuilder = new UriBuilder { Scheme = scheme, Host = string.Format( CultureInfo.InvariantCulture, "{0}{1}.{2}.{3}", accountName, Constants.ConnectionStrings.SecondaryLocationAccountSuffix, hostNamePrefix, endpointSuffix), Query = sasToken }; return (primaryUriBuilder.Uri, secondaryUriBuilder.Uri); } } }
49.411251
207
0.61985
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/storage/Azure.Storage.Common/src/Shared/StorageConnectionString.cs
50,943
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32; namespace RaccineSettings { class RulesSync { public static bool fCompileRules = false; static public void Main(String[] args) { var contentsUrl = $"https://api.github.com/repos/Neo23x0/Raccine/contents/yara?ref=main"; //var contentsUrl = $"https://api.github.com/repos/Neo23x0/Raccine/contents/yara?ref=yara-mem-matching"; SyncContentFromUrl(contentsUrl, ""); } public static string GetYaraDefines() { return " -d Name=\"\" -d ExecutablePath=\"\" -d CommandLine=\"\" -d TimeSinceExeCreation=0 -d ParentName=\"\" -d ParentExecutablePath=\"\" -d ParentCommandLine= -d ParentTimeSinceExeCreation=0 -d GrandParentName=\"\" -d GrandParentExecutablePath=\"\" -d GrandParentCommandLine=\"\" -d GrandParentTimeSinceExeCreation=0 "; } public static bool SyncContentFromUrl(string contentsUrl, string subdir) { String newLinePattern = "([\r]?\n)"; var httpClient = new HttpClient(); Console.WriteLine("Downloading rules from " + contentsUrl); var jsonData = string.Empty; try { using (var webClient = new System.Net.WebClient()) { webClient.Headers.Add("user-agent", "Mozilla/4.0"); jsonData = webClient.DownloadString(contentsUrl); } string szRulesDir = RulesDir; JavaScriptSerializer js = new JavaScriptSerializer(); Rule[] rules = js.Deserialize<Rule[]>(jsonData); uint iRuleCount = 0; foreach (Rule rule in rules) { string type = rule.type; if (rule.name.EndsWith(".yar")) { using (var webClient = new System.Net.WebClient()) { webClient.Headers.Add("user-agent", "Mozilla/4.0"); string yararule = webClient.DownloadString(rule.download_url); string szDir = szRulesDir + "\\" + subdir; System.IO.Directory.CreateDirectory(szDir); string szRulePath = szDir + rule.name; Console.WriteLine("Updating rule " + szRulePath); using (System.IO.StreamWriter file = new System.IO.StreamWriter(szRulePath, false)) { file.WriteLine(Regex.Replace(yararule, newLinePattern, "\r\n")); file.Flush(); file.Close(); iRuleCount++; if (fCompileRules) { string szCompiledRulePath = szRulePath + "c"; // e.g. rule_file.yarc string compilation_program = ""; if (Environment.Is64BitOperatingSystem) { compilation_program = "%ProgramFiles%\\Raccine\\yarac64.exe"; } else { compilation_program = "%ProgramFiles%\\Raccine\\yarac32.exe"; } compilation_program = Environment.ExpandEnvironmentVariables(compilation_program); if (File.Exists(compilation_program)) { string command_line = GetYaraDefines() + "\"" + szRulePath + "\" \"" + szCompiledRulePath + "\""; compilation_program = "\"" + compilation_program + "\""; ProcessStartInfo psi = new ProcessStartInfo(compilation_program); psi.Arguments = command_line; psi.UseShellExecute = false; Process.Start(psi); if (File.Exists(szCompiledRulePath)) { Console.WriteLine("Compiled rule to {0}", szCompiledRulePath); } } else { Console.WriteLine("Can't find yara rule compiler: " + compilation_program); } } } } } else if (rule.type == "dir") { SyncContentFromUrl(rule.url, rule.name + "\\"); } } Console.WriteLine("Updated {0} rules.", iRuleCount); Thread.Sleep(2000); } catch (Exception e) { Console.WriteLine(e.Message); Thread.Sleep(4000); } return true; } public static string RulesDir { get { RegistryKey RaccineKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Raccine", false); String setting = (String)RaccineKey.GetValue("RulesDir"); if (String.IsNullOrEmpty(setting)) { setting = Environment.ExpandEnvironmentVariables(@"%PROGRAMFILES%\Raccine\yara"); } Console.WriteLine("YARA Rules directory is: {0}", setting); return setting; } } } class Rule { public string name { get; set; } public string path { get; set; } public string sha { get; set; } public uint size { get; set; } public string url { get; set; } public string html_url { get; set; } public string git_url { get; set; } public string download_url { get; set; } public string type { get; set; } } }
41.509202
333
0.455365
[ "Unlicense" ]
Apro123/Raccine
RaccineGUI/RaccineCfg/RaccineRulesSync/Program.cs
6,766
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Reflection; using GeometryGym.Ifc; namespace TestModelViewDefinition { class Program { static void Main(string[] args) { DirectoryInfo di = Directory.GetParent(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); di = Directory.GetParent(di.FullName); string path = Path.Combine(di.FullName, "examples"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); Generate(ModelView.Ifc4DesignTransfer, path); Generate(ModelView.Ifc4Reference, path); } internal static IfcBeam createBeam(IfcProduct host, IfcProfileDef profile, IfcCartesianPoint cartesianPoint, string globalId) { DatabaseIfc db = host.Database; IfcAxis2Placement3D position = new IfcAxis2Placement3D(db.Factory.Origin, db.Factory.XAxis, db.Factory.YAxisNegative); IfcExtrudedAreaSolid extrudedAreaSolid = new IfcExtrudedAreaSolid(profile, position, 5000); IfcShapeRepresentation shapeRepresentation = new IfcShapeRepresentation(extrudedAreaSolid); IfcProductDefinitionShape productDefinitionShape = new IfcProductDefinitionShape(shapeRepresentation); IfcLocalPlacement localPlacement = createLocalPlacement(host,cartesianPoint, db.Factory.YAxis); IfcBeam beam = new IfcBeam(host, localPlacement, productDefinitionShape); setGlobalId(beam, globalId); return beam; } internal static IfcColumn createColumn(IfcProduct host, IfcProfileDef profile, IfcCartesianPoint cartesianPoint, string globalId) { DatabaseIfc db = host.Database; IfcExtrudedAreaSolid extrudedAreaSolid = new IfcExtrudedAreaSolid(profile, 5000); IfcShapeRepresentation shapeRepresentation = new IfcShapeRepresentation(extrudedAreaSolid); IfcProductDefinitionShape productDefinitionShape = new IfcProductDefinitionShape(shapeRepresentation); IfcLocalPlacement localPlacement = createLocalPlacement(host, cartesianPoint, db.Factory.YAxis); IfcColumn column = new IfcColumn(host, localPlacement, productDefinitionShape); setGlobalId(column, globalId); return column; } internal static IfcLocalPlacement createLocalPlacement(IfcProduct host, IfcCartesianPoint cartesianPoint, IfcDirection direction) { IfcAxis2Placement3D axis2Placement3D = new IfcAxis2Placement3D(cartesianPoint); if(direction != null) axis2Placement3D.RefDirection = direction; return new IfcLocalPlacement(host.ObjectPlacement, axis2Placement3D); } internal static void setGlobalId(IfcRoot root, string globalId) { if (!string.IsNullOrEmpty(globalId)) root.GlobalId = globalId; } internal static DatabaseIfc Generate(ModelView mvd, string path) { DatabaseIfc db = new DatabaseIfc(true, mvd); //IfcGeometricRepresentationContext //IfcCartesianPoint //IfcAxis2Placement3D //IfcDirection //IfcAxis2Placement2D //IfcSIUnit //IfcLocalPlacement IfcSite site = new IfcSite(db, "TestSite"); //IfcPerson NOT RV //IfcOrganization NOT RV //IfcPersonAndOrganization NOT RV //IfcOwnerHistory NOT RV //fcApplication NOT RV // IfcProjectLibrary NOT RV Can't have multiple context IfcProject project = new IfcProject(site, "TestProject", IfcUnitAssignment.Length.Millimetre) { }; //IfcUnitAssignment //IfcRelAggregates IfcBuilding building = new IfcBuilding(site, "TestBuilding") { }; IfcBuildingStorey buildingStorey = new IfcBuildingStorey(building, "TestBuildingStorey", 200); IfcSpace space = new IfcSpace(buildingStorey, null, null) { Name = "TestSpace" }; space.setRelatingType(new IfcSpaceType(db, "TestSpaceType", IfcSpaceTypeEnum.INTERNAL)); IfcZone zone = new IfcZone(buildingStorey, "TestZone", new List<IfcSpace>() { space }) { LongName = "TestZoneLongName" }; IfcLocalPlacement storeyLocalPlacement = buildingStorey.ObjectPlacement as IfcLocalPlacement; IfcMaterial material = new IfcMaterial(db, "TestMaterial") { Description = "TestDescription", Category = "TestCategory" }; IfcMaterialProperties materialProperties = new IfcMaterialProperties("TestMaterialProperties", material); materialProperties.AddProperty(new IfcPropertySingleValue(db, "MassDensity", new IfcMassDensityMeasure(1))); IfcSurfaceStyleShading surfaceStyleShading = new IfcSurfaceStyleShading(new IfcColourRgb(db, 1, 0, 0) { Name = "Red" }); IfcSurfaceStyle surfaceStyle = new IfcSurfaceStyle(surfaceStyleShading,null,null,null,null); IfcMaterialDefinitionRepresentation materialDefinitionRepresentation = new IfcMaterialDefinitionRepresentation(new IfcStyledRepresentation(new IfcStyledItem(surfaceStyle) { Name = "TestStyledItem" }), material); IfcIndexedPolyCurve indexedPolyCurve = IPE200Curve(db); IfcArbitraryClosedProfileDef arbitraryClosedProfileDef = new IfcArbitraryClosedProfileDef("IPE200", indexedPolyCurve); IfcMaterialProfile materialProfile = new IfcMaterialProfile("TestMaterialProfile", material, arbitraryClosedProfileDef); IfcMaterialProfileSet materialProfileSet = new IfcMaterialProfileSet("TestMaterialProfileSet", materialProfile); IfcBeamType beamType = new IfcBeamType(db, "TestBeamType", IfcBeamTypeEnum.BEAM); beamType.MaterialSelect = materialProfileSet; int beamXPosition = 1000, beamYposition = 0, beamXSpacing = 1000; int columnXPosition = -1000, columnYposition = 0, columnYSpacing = 1000; IfcCartesianPoint cartesianPoint = new IfcCartesianPoint(db, beamXPosition += beamXSpacing, beamYposition, 0); IfcBeam beam = createBeam(buildingStorey, arbitraryClosedProfileDef, cartesianPoint, "16KYUrH45BNwdHw8Y$ia8f"); beam.setRelatingType(beamType); //IfcRelDefinesByType IfcProfileDef columnProfile = arbitraryClosedProfileDef; if(mvd != ModelView.Ifc4Reference) columnProfile = new IfcIShapeProfileDef(db, "IShapeProfileDef", 500, 300, 15, 20) { FilletRadius = 10 }; IfcColumnType columnType = new IfcColumnType(db, "TestColumnType", IfcColumnTypeEnum.COLUMN); cartesianPoint = new IfcCartesianPoint(db, columnXPosition, columnYposition+= columnYSpacing, 0); //IfcGeometricRepresentationSubContext IfcColumn column = createColumn(buildingStorey, columnProfile, cartesianPoint, "2jS8dBukzApveBm5m9QrBf"); column.setRelatingType(columnType); if (mvd != ModelView.Ifc4Reference) { IfcCircleProfileDef circleProfileDef = circleProfileDef = new IfcCircleProfileDef(db, "TestCircleProfile", 350); cartesianPoint = new IfcCartesianPoint(db, columnXPosition, columnYposition += columnYSpacing, 0); createColumn(buildingStorey, circleProfileDef, cartesianPoint, ""); IfcRectangleProfileDef rectangleProfileDef = new IfcRectangleProfileDef(db, "TestRectangle", 400, 600); cartesianPoint = new IfcCartesianPoint(db, beamXPosition += beamXSpacing, beamYposition, 0); createBeam(buildingStorey, rectangleProfileDef, cartesianPoint, ""); IfcRectangleHollowProfileDef rectangleHollowProfileDef = new IfcRectangleHollowProfileDef(db, "TestRectangleHollow", 400, 600, 12); cartesianPoint = new IfcCartesianPoint(db, beamXPosition += beamXSpacing, beamYposition, 0); createBeam(buildingStorey, rectangleHollowProfileDef, cartesianPoint, ""); } IfcProfileDef memberProfile = arbitraryClosedProfileDef; if (mvd != ModelView.Ifc4Reference) memberProfile = new IfcCircleHollowProfileDef(db, "TestCircleHollowProfile", 75, 9); cartesianPoint = new IfcCartesianPoint(db, -1000, -1000, 0); IfcProductDefinitionShape productDefinitionShape = new IfcProductDefinitionShape(new IfcShapeRepresentation(new IfcExtrudedAreaSolid(memberProfile, 2000))); IfcMember member = new IfcMember(buildingStorey, createLocalPlacement(buildingStorey, cartesianPoint, db.Factory.YAxisNegative), productDefinitionShape); // if(mdv != ModelView.Ifc4Reference) // IfcActorRole NOT RV //IfcActuator //IfcActuatorType //IfcAdvancedBrep NOT RV //IfcAdvancedFace NOT RV //IfcAirTerminal //IfcAirTerminalBox //IfcAirTerminalBoxType //IfcAirTerminalType //IfcAirToAirHeatRecovery //IfcAirToAirHeatRecoveryType //IfcAlarm //IfcAlarmType //IfcArbitraryOpenProfileDef //IfcArbitraryProfileDefWithVoids //IfcAsymmetricIShapeProfileDef NOT RV //IfcAudioVisualAppliance //IfcAudioVisualApplianceType //IfcAxis1Placement //IfcBeamStandardCase NOT RV //IfcBlock NOT RV //IfcBoiler //IfcBoilerType //IfcBooleanClippingResult NOT RV //IfcBooleanResult NOT RV //IfcBSplineCurveWithKnots NOT RV //IfcBSplineSurface NOT RV //IfcBSplineSurfaceWithKnots NOT RV //IfcBuildingElementPart //IfcBuildingElementPartType //IfcBuildingElementProxy //IfcBuildingElementProxyType //IfcBuildingSystem //IfcBurner //IfcBurnerType //IfcCableCarrierFitting //IfcCableCarrierFittingType //IfcCableCarrierSegment //IfcCableCarrierSegmentType //IfcCableFitting //IfcCableFittingType //IfcCableSegment //IfcCableSegmentType //IfcCartesianPointList2D //IfcCartesianPointList3D //IfcCartesianTransformationOperator2D //IfcCartesianTransformationOperator2DnonUniform //IfcCartesianTransformationOperator3D //IfcCartesianTransformationOperator3DnonUniform //IfcCenterLineProfileDef //IfcChiller //IfcChillerType //IfcChimney //IfcChimneyType //IfcCircle //IfcCircleHollowProfileDef NOT RV //IfcCivilElement //IfcCivilElementType //IfcClassification //IfcClassificationReference //IfcClosedShell //IfcCoil //IfcCoilType //IfcColourRgbList //IfcColourSpecification //IfcColumnStandardCase NOT RV //IfcCommunicationsAppliance //IfcCommunicationsApplianceType //IfcComplexProperty //IfcCompositeProfileDef NOT RV //IfcCompressor //IfcCompressorType //IfcCondenser //IfcCondenserType //IfcConnectedFaceSet NOT RV //IfcConnectionCurveGeometry NOT RV //IfcConnectionVolumeGeometry NOT RV //IfcController //IfcControllerType //IfcConversionBasedUnit //IfcConversionBasedUnitWithOffset //IfcCooledBeam //IfcCooledBeamType //IfcCoolingTower //IfcCoolingTowerType //IfcCovering //IfcCoveringType //IfcCsgSolid NOT RV //IfcCShapeProfileDef NOT RV //IfcCurtainWall //IfcCurtainWallType //IfcCurveStyle //IfcCurveStyleFont //IfcCurveStyleFontPattern //IfcDamper //IfcDamperType //IfcDerivedProfileDef NOT RV //IfcDerivedUnit //IfcDerivedUnitElement //IfcDimensionalExponents //IfcDiscreteAccessory //IfcDiscreteAccessoryType //IfcDistributionChamberElement //IfcDistributionChamberElementType //IfcDistributionCircuit //IfcDistributionControlElement //IfcDistributionControlElementType //IfcDistributionElement //IfcDistributionElementType //IfcDistributionFlowElement //IfcDistributionFlowElementType //IfcDistributionPort //IfcDistributionSystem //IfcDocumentReference //IfcDoor //IfcDoorLiningProperties //IfcDoorPanelProperties //IfcDoorStandardCase NOT RV //IfcDoorType //IfcDuctFitting //IfcDuctFittingType //IfcDuctSegment //IfcDuctSegmentType //IfcDuctSilencer //IfcDuctSilencerType //IfcEdge NOT RV //IfcEdgeCurve NOT RV //IfcEdgeLoop NOT RV //IfcElectricAppliance //IfcElectricApplianceType //IfcElectricDistributionBoard //IfcElectricDistributionBoardType //IfcElectricFlowStorageDevice //IfcElectricFlowStorageDeviceType //IfcElectricGenerator //IfcElectricGeneratorType //IfcElectricMotor //IfcElectricMotorType //IfcElectricTimeControl //IfcElectricTimeControlType //IfcElementAssembly //IfcElementAssemblyType //IfcElementComponent //IfcElementComponentType //IfcElementQuantity //IfcEllipseProfileDef NOT RV //IfcEnergyConversionDevice //IfcEnergyConversionDeviceType //IfcEngine //IfcEngineType //IfcEvaporativeCooler //IfcEvaporativeCoolerType //IfcEvaporator //IfcEvaporatorType //IfcExtendedProperties //IfcExternalInformation //IfcExternalReference //IfcExtrudedAreaSolidTapered NOT RV //IfcFace NOT RV //IfcFaceBasedSurfaceModel NOT RV //IfcFaceBound NOT RV //IfcFaceOuterBound NOT RV //IfcFaceSurface NOT RV //IfcFacetedBrep NOT RV //IfcFan //IfcFanType //IfcFastener //IfcFastenerType //IfcFeatureElement //IfcFeatureElementAddition NOT RV //IfcFeatureElementSubtraction //IfcFillAreaStyle //IfcFillAreaStyleHatching //IfcFilter //IfcFilterType //IfcFireSuppressionTerminal //IfcFireSuppressionTerminalType //IfcFixedReferenceSweptAreaSolid NOT RV //IfcFlowController //IfcFlowControllerType //IfcFlowFitting //IfcFlowFittingType //IfcFlowInstrument //IfcFlowInstrumentType //IfcFlowMeter //IfcFlowMeterType //IfcFlowMovingDevice //IfcFlowMovingDeviceType //IfcFlowSegment //IfcFlowSegmentType //IfcFlowStorageDevice //IfcFlowStorageDeviceType //IfcFlowTerminal //IfcFlowTerminalType //IfcFlowTreatmentDevice //IfcFlowTreatmentDeviceType //IfcFooting //IfcFootingType //IfcFurnishingElement //IfcFurnishingElementType //IfcFurniture //IfcFurnitureType //IfcGeographicElement //IfcGeographicElementType //IfcGeometricCurveSet //IfcGeometricSet //IfcGrid //IfcGridAxis //IfcGridPlacement NOT RV //IfcGroup //IfcHalfSpaceSolid NOT RV //IfcHeatExchanger //IfcHeatExchangerType //IfcHumidifier //IfcHumidifierType //IfcIndexedColourMap //IfcIndexedTextureMap //IfcIndexedTriangleTextureMap //IfcInterceptor //IfcInterceptorType //IfcJunctionBox //IfcJunctionBoxType //IfcLamp //IfcLampType //IfcLibraryInformation NOT RV //IfcLibraryReference NOT RV //IfcLightFixture //IfcLightFixtureType //IfcLine //IfcLoop NOT RV //IfcLShapeProfileDef NOT RV //IfcMapConversion //IfcMappedItem //IfcMaterialConstituent //IfcMaterialConstituentSet //IfcMaterialLayer //IfcMaterialLayerSet //IfcMaterialLayerSetUsage NOT RV //IfcMaterialLayerWithOffsets NOT RV //IfcMaterialProfileSetUsage NOT RV //IfcMaterialProfileSetUsageTapering NOT RV //IfcMaterialProfileWithOffsets NOT RV //IfcMaterialUsageDefinition NOT RV //IfcMeasureWithUnit //IfcMechanicalFastener //IfcMechanicalFastenerType //IfcMedicalDevice //IfcMedicalDeviceType //IfcMemberStandardCase NOT RV //IfcMonetaryUnit //IfcMotorConnection //IfcMotorConnectionType //IfcNamedUnit //IfcOpeningElement //IfcOpeningStandardCase NOT RV //IfcOpenShell NOT RV //IfcOrientedEdge NOT RV //IfcOutlet //IfcOutletType //IfcPcurve NOT RV //IfcPhysicalComplexQuantity //IfcPhysicalQuantity //IfcPhysicalSimpleQuantity //IfcPile //IfcPileType //IfcPipeFitting //IfcPipeFittingType //IfcPipeSegment //IfcPipeSegmentType //IfcPlane NOT RV //IfcPlate //IfcPlateStandardCase NOT RV //IfcPlateType //IfcPoint //IfcPolygonalBoundedHalfSpace NOT RV //IfcPolyline NOT RV //IfcPolyLoop NOT RV //IfcPort //IfcPostalAddress //IfcPreDefinedPropertySet //IfcPresentationItem //IfcPresentationLayerAssignment //IfcPresentationStyle //IfcPresentationStyleAssignment //IfcProductDefinitionShape //IfcProductRepresentation //IfcProfileDef //IfcProfileProperties //IfcProjectedCRS //IfcProjectionElement NOT RV //IfcProperty //IfcPropertyAbstraction //IfcPropertyBoundedValue //IfcPropertyDefinition //IfcPropertyEnumeratedValue //IfcPropertyEnumeration //IfcPropertyListValue //IfcPropertySet //IfcPropertySetTemplate NOT RV //IfcPropertyTableValue //IfcPropertyTemplate NOT RV //IfcPropertyTemplateDefinition NOT RV //IfcProtectiveDevice //IfcProtectiveDeviceTrippingUnit //IfcProtectiveDeviceTrippingUnitType //IfcProtectiveDeviceType //IfcPump //IfcPumpType //IfcQuantityArea //IfcQuantityCount //IfcQuantityLength //IfcQuantitySet //IfcQuantityTime //IfcQuantityVolume //IfcQuantityWeight //IfcRailing //IfcRailingType //IfcRamp //IfcRampFlight //IfcRampFlightType //IfcRampType //IfcRectangularPyramid NOT RV //IfcReinforcingBar //IfcReinforcingBarType //IfcReinforcingElement //IfcReinforcingElementType //IfcReinforcingMesh //IfcReinforcingMeshType //IfcRelAssignsToGroup //IfcRelAssociatesClassification //IfcRelAssociatesDocument //IfcRelAssociatesLibrary NOT RV //IfcRelAssociatesMaterial //IfcRelConnectsElements NOT RV //IfcRelConnectsPathElements NOT RV //IfcRelConnectsPorts //IfcRelConnectsWithRealizingElements NOT RV //IfcRelContainedInSpatialStructure //IfcRelCoversBldgElements //IfcRelDeclares //IfcRelDefinesByProperties //IfcRelFillsElement //IfcRelFlowControlElements NOT RV //IfcRelInterferesElements NOT RV //IfcRelNests //IfcRelProjectsElement NOT RV //IfcRelServicesBuildings //IfcRelVoidsElement //IfcRepresentation //IfcRepresentationContext //IfcRepresentationItem //IfcRepresentationMap //IfcRevolvedAreaSolid //IfcRevolvedAreaSolidTapered NOT RV //IfcRightCircularCone NOT RV //IfcRightCircularCylinder NOT RV //IfcRoof //IfcRoofType //IfcRoundedRectangleProfileDef NOT RV //IfcSanitaryTerminal //IfcSanitaryTerminalType //IfcSensor //IfcSensorType //IfcShadingDevice //IfcShadingDeviceType //IfcShapeRepresentation //IfcShellBasedSurfaceModel NOT RV //IfcSimplePropertyTemplate NOT RV //IfcSlab //IfcSlabElementedCase NOT RV //IfcSlabStandardCase NOT RV //IfcSlabType //IfcSolarDevice //IfcSolarDeviceType //IfcSpaceHeater //IfcSpaceHeaterType //IfcSpatialZone //IfcSpatialZoneType //IfcSphere NOT RV //IfcStackTerminal //IfcStackTerminalType //IfcStair //IfcStairFlight //IfcStairFlightType //IfcStairType //IfcStyleModel //IfcSurface NOT RV //IfcSurfaceCurveSweptAreaSolid NOT RV //IfcSurfaceOfLinearExtrusion NOT RV //IfcSurfaceOfRevolution NOT RV //IfcSurfaceStyleRendering //IfcSurfaceStyleWithTextures surfaceStyleWithTextures = new IfcSurfaceStyleWithTextures(new IfcImageTexture(db,true,true,"")); //IfcSweptDiskSolid //IfcSwitchingDevice //IfcSwitchingDeviceType //IfcSystemFurnitureElement //IfcSystemFurnitureElementType //IfcTank //IfcTankType //IfcTelecomAddress NOT RV //IfcTendon //IfcTendonAnchor //IfcTendonAnchorType //IfcTendonType //IfcTessellatedFaceSet //IfcTessellatedItem //IfcTextureCoordinate //IfcTextureVertexList //IfcTransformer //IfcTransformerType //IfcTransportElement //IfcTransportElementType //IfcTriangulatedFaceSet //IfcTrimmedCurve //IfcTShapeProfileDef NOT RV //IfcTubeBundle //IfcTubeBundleType //IfcUnitaryControlElement //IfcUnitaryControlElementType //IfcUnitaryEquipment //IfcUnitaryEquipmentType //IfcUShapeProfileDef NOT RV //IfcValve //IfcValveType //IfcVector //IfcVertex NOT RV //IfcVertexPoint NOT RV //IfcVibrationIsolator //IfcVibrationIsolatorType //IfcVirtualGridIntersection NOT RV //IfcWall //IfcWallElementedCase NOT RV //IfcWallStandardCase NOT RV //IfcWallType //IfcWasteTerminal //IfcWasteTerminalType //IfcWindow //IfcWindowLiningProperties //IfcWindowPanelProperties //IfcWindowStandardCase NOT RV //IfcWindowType //IfcZShapeProfileDef NOT RV db.WriteFile(Path.Combine(path, mvd.ToString() + ".ifc")); return db; } internal static IfcIndexedPolyCurve IPE200Curve(DatabaseIfc db) { List<Tuple<double, double>> tuples = new List<Tuple<double, double>>() { new Tuple<double, double>(2.8, -79.5), new Tuple<double, double>(2.8, 79.5), new Tuple<double, double>(6.314719, 87.985281), new Tuple<double, double>(14.8, 91.5), new Tuple<double, double>(50.0, 91.5), new Tuple<double, double>(50.0, 100.0), new Tuple<double, double>(-50.0, 100.0), new Tuple<double, double>(-50.0, 91.5), new Tuple<double, double>(-14.8, 91.5), new Tuple<double, double>(-6.314719, 87.985281), new Tuple<double, double>(-2.8, 79.5), new Tuple<double, double>(-2.8, -79.5), new Tuple<double, double>(-6.314719, -87.985281), new Tuple<double, double>(-14.8, -91.5), new Tuple<double, double>(-50.0, -91.5), new Tuple<double, double>(-50.0, -100.0), new Tuple<double, double>(50.0, -100.0), new Tuple<double, double>(50.0, -91.5), new Tuple<double, double>(14.8, -91.5), new Tuple<double, double>(6.314719, -87.985281) }; IfcCartesianPointList2D points = new IfcCartesianPointList2D(db, tuples); List<IfcSegmentIndexSelect> segments = new List<IfcSegmentIndexSelect>(); segments.Add(new IfcLineIndex(1, 2)); segments.Add(new IfcArcIndex(2, 3, 4)); segments.Add(new IfcLineIndex(4,5)); segments.Add(new IfcLineIndex(5,6)); segments.Add(new IfcLineIndex(6,7)); segments.Add(new IfcLineIndex(7,8)); segments.Add(new IfcLineIndex(8,9)); segments.Add(new IfcArcIndex(9,10,11)); segments.Add(new IfcLineIndex(11,12)); segments.Add(new IfcArcIndex(12,13,14)); segments.Add(new IfcLineIndex(14,15)); segments.Add(new IfcLineIndex(15,16)); segments.Add(new IfcLineIndex(16,17)); segments.Add(new IfcLineIndex(17,18)); segments.Add(new IfcLineIndex(18,19)); segments.Add(new IfcArcIndex(19,20,1)); return new IfcIndexedPolyCurve(points, segments); } } }
34.883683
913
0.758764
[ "MIT" ]
GeometryGym/GeometryGymIFCExamples
TestModelViewDefinition/Program.cs
21,595
C#
using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; using WebVella.Erp.Api; using WebVella.Erp.Web.Services; namespace WebVella.Erp.Web.Components { public class UserNavViewComponent : ViewComponent { protected ErpRequestContext ErpRequestContext { get; set; } public UserNavViewComponent([FromServices]ErpRequestContext coreReqCtx) { ErpRequestContext = coreReqCtx; } public async Task<IViewComponentResult> InvokeAsync( ) { var pageContext = ErpRequestContext.PageContext; ViewBag.CurrentUser = AuthService.GetUser(UserClaimsPrincipal); ViewBag.PageId = null; if (ErpRequestContext.Page != null) { ViewBag.PageId = ErpRequestContext.Page.Id; } return await Task.FromResult<IViewComponentResult>(View("UserNav.Default")); } } }
25.1875
79
0.765509
[ "Apache-2.0" ]
628426/WebVella-ERP
WebVella.Erp.Web/Components/UserNav/UserNavViewComponent.cs
808
C#
using System; namespace NAudio.Wave.SampleProviders { /// <summary> /// No nonsense mono to stereo provider, no volume adjustment, /// just copies input to left and right. /// </summary> public class MonoToStereoSampleProvider : ISampleProvider { private readonly ISampleProvider source; private float[] sourceBuffer; /// <summary> /// Initializes a new instance of MonoToStereoSampleProvider /// </summary> /// <param name="source">Source sample provider</param> public MonoToStereoSampleProvider(ISampleProvider source) { LeftVolume = 1.0f; RightVolume = 1.0f; if (source.WaveFormat.Channels != 1) { throw new ArgumentException("Source must be mono"); } this.source = source; WaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(source.WaveFormat.SampleRate, 2); } /// <summary> /// WaveFormat of this provider /// </summary> public WaveFormat WaveFormat { get; private set; } /// <summary> /// Reads samples from this provider /// </summary> /// <param name="buffer">Sample buffer</param> /// <param name="offset">Offset into sample buffer</param> /// <param name="count">Number of samples required</param> /// <returns>Number of samples read</returns> public int Read(float[] buffer, int offset, int count) { var sourceSamplesRequired = count / 2; var outIndex = offset; EnsureSourceBuffer(sourceSamplesRequired); var sourceSamplesRead = source.Read(sourceBuffer, 0, sourceSamplesRequired); for (var n = 0; n < sourceSamplesRead; n++) { buffer[outIndex++] = sourceBuffer[n] * LeftVolume; buffer[outIndex++] = sourceBuffer[n] * RightVolume; } return sourceSamplesRead * 2; } /// <summary> /// Multiplier for left channel (default is 1.0) /// </summary> public float LeftVolume { get; set; } /// <summary> /// Multiplier for right channel (default is 1.0) /// </summary> public float RightVolume { get; set; } private void EnsureSourceBuffer(int count) { if (sourceBuffer == null || sourceBuffer.Length < count) { sourceBuffer = new float[count]; } } } }
34.893333
96
0.546809
[ "MIT" ]
jaebird/SoundIO-cil
Support/NAudioLite/Wave/SampleProviders/MonoToStereoSampleProvider.cs
2,619
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NuGetPe.AssemblyMetadata { public class AssemblyDebugData { public PdbType PdbType { get; internal set; } public IReadOnlyList<SourceLinkMap> SourceLink { get; internal set; } public IReadOnlyList<AssemblyDebugSourceDocument> Sources { get; internal set; } } public enum PdbType { Portable, Embedded, Full } }
20.52
88
0.680312
[ "MIT" ]
nicoleputois/NuGetPackageExplorer-master
Core/AssemblyMetadata/AssemblyDebugData.cs
515
C#
 // // Copyright (c) Michael Eddington // // 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. // // Authors: // Michael Eddington (mike@dejavusecurity.com) // Mikhail Davidov (sirus@haxsys.net) // $Id$ using System; using System.Collections.Generic; using System.Text; using Peach.Core.Dom; using Peach.Core.Fixups.Libraries; namespace Peach.Core.Fixups { [Description("Fixup used in testing. Will copy another elements value into us.")] [Fixup("CopyValue", true)] [Fixup("CopyValueFixup")] [Parameter("ref", typeof(DataElement), "Reference to data element")] [Serializable] public class CopyValueFixup : Fixup { public CopyValueFixup(DataElement parent, Dictionary<string, Variant> args) : base(parent, args, "ref") { } protected override Variant fixupImpl() { var elem = elements["ref"]; return new Variant(elem.Value); } } } // end
33.271186
84
0.715232
[ "MIT" ]
FXTi/peachfuzz-code
Peach.Core/Fixups/CopyValueFixup.cs
1,965
C#
using System; using System.Collections.Generic; namespace NMaier.SimpleDlna.Utilities { using PartsCache = LeastRecentlyUsedDictionary<string, BaseSortPart[]>; public sealed class NaturalStringComparer : StringComparer { private static readonly StringComparer comparer = StringComparer.CurrentCultureIgnoreCase; private static readonly bool platformSupport = HasPlatformSupport(); private readonly PartsCache partsCache = new PartsCache(5000); private readonly bool stemBase; public NaturalStringComparer() : this(false) { } public NaturalStringComparer(bool stemBase) { this.stemBase = stemBase; } private static bool HasPlatformSupport() { try { return SafeNativeMethods.StrCmpLogicalW("a", "b") != 0; } catch (Exception) { return false; } } private BaseSortPart[] Split(string str) { BaseSortPart[] rv; if (partsCache.TryGetValue(str, out rv)) { return rv; } var parts = new List<BaseSortPart>(); var num = false; var start = 0; for (var i = 0; i < str.Length; ++i) { var c = str[i]; var cnum = c >= '0' && c <= '9'; if (cnum == num) { continue; } if (i != 0) { var p = str.Substring(start, i - start).Trim(); if (num) { parts.Add(new NumericSortPart(p)); } else { if (!string.IsNullOrWhiteSpace(p)) { parts.Add(new StringSortPart(p, comparer)); } } } num = cnum; start = i; } var pe = str.Substring(start).Trim(); if (!string.IsNullOrWhiteSpace(pe)) { if (num) { parts.Add(new NumericSortPart(pe)); } else { parts.Add(new StringSortPart(pe, comparer)); } } rv = parts.ToArray(); lock (partsCache) { partsCache[str] = rv; } return rv; } public override int Compare(string x, string y) { if (stemBase) { x = x.StemCompareBase(); y = y.StemCompareBase(); } if (platformSupport) { return SafeNativeMethods.StrCmpLogicalW(x, y); } if (x == y || StringComparer.InvariantCulture.Compare(x, y) == 0) { return 0; } var p1 = Split(x); var p2 = Split(y); int rv; var e = Math.Min(p1.Length, p2.Length); for (var i = 0; i < e; ++i) { rv = p1[i].CompareTo(p2[i]); if (rv != 0) { return rv; } } rv = p1.Length.CompareTo(p2.Length); if (rv == 0) { return comparer.Compare(x, y); } return rv; } public override bool Equals(string x, string y) { return Compare(x, y) == 0; } public override int GetHashCode(string obj) { return comparer.GetHashCode(obj); } } }
23.181102
73
0.536005
[ "BSD-2-Clause" ]
AlexAkulov/simpleDLNA
util/NaturalStringComparer.cs
2,946
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.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.AspNetCore.SignalR.Client.SourceGenerator; [Generator] internal partial class HubClientProxyGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var methodDeclaration = context.SyntaxProvider .CreateSyntaxProvider(static (s, _) => Parser.IsSyntaxTargetForAttribute(s), static (ctx, _) => Parser.GetSemanticTargetForAttribute(ctx)) .Where(static m => m is not null) .Collect(); var memberAccessExpressions = context.SyntaxProvider .CreateSyntaxProvider(static (s, _) => Parser.IsSyntaxTargetForGeneration(s), static (ctx, _) => Parser.GetSemanticTargetForGeneration(ctx)) .Where(static m => m is not null); var compilationAndMethodDeclaration = context.CompilationProvider.Combine(methodDeclaration); var payload = compilationAndMethodDeclaration .Combine(memberAccessExpressions.Collect()); context.RegisterSourceOutput(payload, static (spc, source) => Execute(source.Left.Left, source.Left.Right, source.Right, spc)); } private static void Execute(Compilation compilation, ImmutableArray<MethodDeclarationSyntax> methodDeclarationSyntaxes, ImmutableArray<MemberAccessExpressionSyntax> memberAccessExpressionSyntaxes, SourceProductionContext context) { var parser = new Parser(context, compilation); var spec = parser.Parse(methodDeclarationSyntaxes, memberAccessExpressionSyntaxes); var emitter = new Emitter(context, spec); emitter.Emit(); } }
44
233
0.72833
[ "MIT" ]
3ejki/aspnetcore
src/SignalR/clients/csharp/Client.SourceGenerator/src/HubClientProxyGenerator.cs
1,892
C#
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // https://github.com/dotnet/roslyn-analyzers/issues/955 [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "RS0006:Do not mix attributes from different versions of MEF", Justification = "<Pending>", Scope = "type", Target = "~T:Microsoft.VisualStudio.ProjectSystem.VS.Input.Commands.OpenProjectDesignerCommand")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "RS0006:Do not mix attributes from different versions of MEF", Justification = "<Pending>", Scope = "type", Target = "~T:Microsoft.VisualStudio.ProjectSystem.VS.Input.Commands.OpenProjectDesignerOnDefaultActionCommand")]
98
294
0.791383
[ "Apache-2.0" ]
HydAu/RoslynProjectSystem
src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/GlobalSuppressions.cs
884
C#
using System.IO; namespace Chroma.Audio.Sources { public class Sound : FileBasedAudioSource { public Sound(string filePath) : base(filePath, true) { } public Sound(Stream stream) : base(stream, true) { } } }
17.294118
45
0.52381
[ "MIT" ]
Chroma-2D/Chroma
Chroma/Audio/Sources/Sound.cs
296
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codedeploy-2014-10-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CodeDeploy.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for StopDeployment operation /// </summary> public class StopDeploymentResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { StopDeploymentResponse response = new StopDeploymentResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("statusMessage", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.StatusMessage = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentAlreadyCompletedException")) { return DeploymentAlreadyCompletedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentDoesNotExistException")) { return DeploymentDoesNotExistExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentGroupDoesNotExistException")) { return DeploymentGroupDoesNotExistExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("DeploymentIdRequiredException")) { return DeploymentIdRequiredExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidDeploymentIdException")) { return InvalidDeploymentIdExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnsupportedActionForDeploymentTypeException")) { return UnsupportedActionForDeploymentTypeExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonCodeDeployException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static StopDeploymentResponseUnmarshaller _instance = new StopDeploymentResponseUnmarshaller(); internal static StopDeploymentResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StopDeploymentResponseUnmarshaller Instance { get { return _instance; } } } }
41.838235
193
0.640246
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodeDeploy/Generated/Model/Internal/MarshallTransformations/StopDeploymentResponseUnmarshaller.cs
5,690
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using BlockM3.AEternity.SDK.Sophia.Attributes; namespace BlockM3.AEternity.SDK.Sophia.Types { public class EventType : SophiaType { public EventType(string mapname, string name, List<SophiaType> types) : base(mapname) { Name = name; FieldTypes = types; } public override string SophiaBaseName => "event"; public override string SophiaName => Name + " (" + string.Join(", ", FieldTypes.Select(a => a.SophiaName)) + ")"; public List<SophiaType> FieldTypes { get; } public string Name { get; } public override string Serialize(object o, Type t) { SophiaEventAttribute rec = t.GetCustomAttribute<SophiaEventAttribute>(); if (!t.IsClass) throw new ArgumentException("Events can be only classes"); if (rec == null) throw new ArgumentException("Events classes should have the SophiaEvent Attribute"); StringBuilder bld = new StringBuilder(); bld.Append(Name); bld.Append("("); List<(string, PropertyInfo)> props = OrderProps(t.GetTypeInfo()); bool add = false; if (props.Count < FieldTypes.Count) { throw new ArgumentException($"Unable to serialize event, the class has less properties than the definition"); } for (int x = 0; x < FieldTypes.Count; x++) { add = true; PropertyInfo p = props[x].Item2; bld.Append(FieldTypes[x].Serialize(p.GetValue(o), p.PropertyType)); bld.Append(", "); } if (add) bld.Remove(bld.Length - 2, 2); bld.Append(")"); return bld.ToString(); } public override object Deserialize(string value, Type t) { if (value.StartsWith("\"") && value.EndsWith("\"")) value = value.Substring(1, value.Length - 2); SophiaEventAttribute rec = t.GetCustomAttribute<SophiaEventAttribute>(); if (!t.IsClass) throw new ArgumentException("Events can be only classes"); if (rec == null) throw new ArgumentException("Events classes should have the SophiaEvent Attribute"); value = value.Trim(); int idx = value.IndexOf('('); if (idx > -1) value = value.Substring(idx); if (value.StartsWith("(") && value.EndsWith(")")) value = value.Substring(1, value.Length - 2).Trim(); string[] dicsplits = SophiaMapper.SplitByComma(value); List<(string, PropertyInfo)> props = OrderProps(t.GetTypeInfo()); object o = Activator.CreateInstance(t); if (props.Count < FieldTypes.Count || dicsplits.Length != FieldTypes.Count) { throw new ArgumentException($"Unable to deserialize event, the class has less properties than the definition"); } for (int x = 0; x < FieldTypes.Count; x++) { PropertyInfo p = props[x].Item2; p.SetValue(o, FieldTypes[x].Deserialize(dicsplits[x], p.PropertyType)); } return o; } } }
39.390805
127
0.557339
[ "ISC" ]
block-m3/aepp-sdk-net
BlockM3.AEternity.SDK/Sophia/Types/EventType.cs
3,429
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the medialive-2017-10-14.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.MediaLive.Model { /// <summary> /// Container for the parameters to the DeleteChannel operation. /// Starts deletion of channel. The associated outputs are also deleted. /// </summary> public partial class DeleteChannelRequest : AmazonMediaLiveRequest { private string _channelId; /// <summary> /// Gets and sets the property ChannelId. Unique ID of the channel. /// </summary> [AWSProperty(Required=true)] public string ChannelId { get { return this._channelId; } set { this._channelId = value; } } // Check to see if ChannelId property is set internal bool IsSetChannelId() { return this._channelId != null; } } }
29.964286
107
0.674017
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/MediaLive/Generated/Model/DeleteChannelRequest.cs
1,678
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WeText.Common.Messaging { /// <summary> /// Represents that the implemented classes are the command senders /// that will send a command to the message bus. /// </summary> public interface ICommandSender : IMessagePublisher { } }
23.647059
72
0.68408
[ "MIT" ]
daxnet/we-text
src/WeText.Common/Messaging/ICommandSender.cs
404
C#
using System.Threading; using System.Threading.Tasks; using Elsa.Models; using Elsa.Webhooks.Persistence.YesSql.Data; using Elsa.Webhooks.Persistence.YesSql.Documents; using Elsa.Webhooks.Persistence.YesSql.Indexes; using Elsa.Persistence.Specifications; using Elsa.Persistence.YesSql; using Elsa.Persistence.YesSql.Services; using Elsa.Persistence.YesSql.Stores; using AutoMapper; using Elsa.Webhooks.Models; using Microsoft.Extensions.Logging; using YesSql; using IIdGenerator = Elsa.Services.IIdGenerator; namespace Elsa.Webhooks.Persistence.YesSql.Stores { public class YesSqlWebhookDefinitionStore : YesSqlStore<WebhookDefinition, WebhookDefinitionDocument>, IWebhookDefinitionStore { public YesSqlWebhookDefinitionStore(ISessionProvider sessionProvider, IIdGenerator idGenerator, IMapper mapper, ILogger<YesSqlWebhookDefinitionStore> logger) : base(sessionProvider, idGenerator, mapper, logger, CollectionNames.WebhookDefinitions) { } protected override async Task<WebhookDefinitionDocument?> FindDocumentAsync(ISession session, WebhookDefinition entity, CancellationToken cancellationToken) => await Query<WebhookDefinitionIndex>(session, x => x.WebhookDefinitionId == entity.Id).FirstOrDefaultAsync(); protected override IQuery<WebhookDefinitionDocument> MapSpecification(ISession session, ISpecification<WebhookDefinition> specification) { return specification switch { EntityIdSpecification<WebhookDefinition> s => Query<WebhookDefinitionIndex>(session, x => x.WebhookDefinitionId == s.Id), _ => AutoMapSpecification<WebhookDefinitionIndex>(session, specification) }; } protected override IQuery<WebhookDefinitionDocument> OrderBy(IQuery<WebhookDefinitionDocument> query, IOrderBy<WebhookDefinition> orderBy, ISpecification<WebhookDefinition> specification) { var expression = orderBy.OrderByExpression.ConvertType<WebhookDefinition, WebhookDefinitionDocument>().ConvertType<WebhookDefinitionDocument, WebhookDefinitionIndex>(); var indexedQuery = query.With<WebhookDefinitionIndex>(); return orderBy.SortDirection == SortDirection.Ascending ? indexedQuery.OrderBy(expression) : indexedQuery.OrderByDescending(expression); } } }
54.372093
276
0.77716
[ "MIT" ]
feijie999/elsa-core
src/activities/webhooks/Elsa.Webhooks.Persistence.YesSql/Stores/YesSqlWebhookDefinitionStore.cs
2,338
C#
using Sharpen; namespace org.bouncycastle.x509 { [Sharpen.NakedStub] public class ExtendedPKIXBuilderParameters { } }
12.3
43
0.780488
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/naked-stubs/org/bouncycastle/x509/ExtendedPKIXBuilderParameters.cs
123
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using CSPlang.Any2; using CSPlang.Shared; namespace CSPlang.One2 { public class One2AnyImpl : One2AnyChannel, ChannelInternals { private ChannelInternals channel; /** The mutex on which readers must synchronize */ private readonly CSPMutex _readCspMutex = new CSPMutex(); internal One2AnyImpl(ChannelInternals _channel) { channel = _channel; } public SharedChannelInput In() { return new SharedChannelInputImpl(this, 0); } public ChannelOutput Out() { return new ChannelOutputImpl(channel, 0); } public void endRead() { channel.endRead(); _readCspMutex.Release(); } public Object read() { _readCspMutex.Claim(); //A poison exception might be thrown, hence the try/finally: try { return channel.read(); } finally { _readCspMutex.Release(); } } //begin never used: public Boolean readerDisable() { return false; } public Boolean readerEnable(Alternative alt) { return false; } public Boolean readerPending() { return false; } //end never used public void readerPoison(int strength) { _readCspMutex.Claim(); channel.readerPoison(strength); _readCspMutex.Release(); } public Object startRead() { _readCspMutex.Claim(); try { return channel.startRead(); } catch (RuntimeException e) { channel.endRead(); _readCspMutex.Release(); throw e; } } //begin never used public void write(Object obj) { channel.write(obj); } public void writerPoison(int strength) { channel.writerPoison(strength); } //end never used public bool writerEnable(Alternative alt) { throw new NotImplementedException(); } public bool writerDisable() { throw new NotImplementedException(); } public bool writerPending() { throw new NotImplementedException(); } } }
21.447154
74
0.501895
[ "MIT" ]
PasierbKarol/CSPsharp
CSPlang/One2/One2AnyImpl.cs
2,640
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using GalaSoft.MvvmLight.Threading; using ResultStudioWPF.Mappers; using ResultStudioWPF.Views.Windows; namespace ResultStudioWPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : System.Windows.Application { private void Application_Startup(object sender, StartupEventArgs e) { DispatcherHelper.Initialize(); PresentationTraceSources.Refresh(); PresentationTraceSources.DataBindingSource.Listeners.Add(new ConsoleTraceListener()); PresentationTraceSources.DataBindingSource.Listeners.Add(new DebugTraceListener()); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; var mainWindow = new MainWindow(); mainWindow.Show(); } private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { //throw new NotImplementedException(); } private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { //throw new NotImplementedException(); } private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //throw new NotImplementedException(); } } public class DebugTraceListener : TraceListener { public override void Write(string message) { Debugger.Break(); } public override void WriteLine(string message) { Debugger.Break(); } } }
29.123077
109
0.742208
[ "MIT" ]
Ariksman/ResultStudioWPF
ResultStudioWPF/App.xaml.cs
1,895
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Migrations.Operations.Builders { /// <summary> /// A builder for <see cref="IAlterMigrationOperation" /> operations. /// </summary> /// <typeparam name="TOperation"> The operation type to build. </typeparam> public class AlterOperationBuilder<TOperation> : OperationBuilder<TOperation> where TOperation : MigrationOperation, IAlterMigrationOperation { /// <summary> /// Constructs a builder for the given <see cref="MigrationOperation" />. /// </summary> /// <param name="operation"> The operation. </param> public AlterOperationBuilder([NotNull] TOperation operation) : base(operation) { } /// <summary> /// Annotates the <see cref="MigrationOperation" /> with the given name/value pair. /// </summary> /// <param name="name"> The annotation name. </param> /// <param name="value"> The annotation value. </param> /// <returns> The same builder so that multiple calls can be chained. </returns> public new virtual AlterOperationBuilder<TOperation> Annotation( [NotNull] string name, [NotNull] object value) => (AlterOperationBuilder<TOperation>)base.Annotation(name, value); /// <summary> /// Annotates the <see cref="MigrationOperation" /> with the given name/value pair as /// an annotation that was present before the alteration. /// </summary> /// <param name="name"> The annotation name. </param> /// <param name="value"> The annotation value. </param> /// <returns> The same builder so that multiple calls can be chained. </returns> public virtual AlterOperationBuilder<TOperation> OldAnnotation( [NotNull] string name, [NotNull] object value) { Check.NotEmpty(name, nameof(name)); Check.NotNull(value, nameof(value)); Operation.OldAnnotations.AddAnnotation(name, value); return this; } } }
42.035714
111
0.630416
[ "Apache-2.0" ]
0b01/efcore
src/EFCore.Relational/Migrations/Operations/Builders/AlterOperationBuilder.cs
2,354
C#
// $Id: NetworkArchiver.cs 774 2005-09-21 20:22:33Z pediddle $ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace UW.ClassroomPresenter.Test.Network.Common { /// <summary> /// NetworkArchiver stores a stream of events in a file for later review /// </summary> public class NetworkArchiver { // The file containing the ink archive private FileStream archive = null; private long PrevEventOffset = -1; // Access Mode public enum ArchiveMode { ReadingMode, WritingMode, None }; private ArchiveMode mode = ArchiveMode.None; public ArchiveMode Mode { get { return mode; } set { mode = value; } } // Constructor public NetworkArchiver() { } ~NetworkArchiver() { CloseArchive(); } // ------------------ Reading/Writing ---------------------- // Closes the currently opened archive files public void CloseArchive() { if( archive != null ) archive.Close(); archive = null; mode = ArchiveMode.None; } // ------------------ Reading ---------------------- // Open an existing archive for reading public bool OpenArchive( string fullpath ) { archive = new FileStream( fullpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ); mode = ArchiveMode.ReadingMode; return true; } // Get the Next event from the archive and advance the File pointer public NetworkEvent GetNextEvent() { NetworkEvent e = null; if( mode == ArchiveMode.ReadingMode ) { // Read the previous offset and current length long tempPrevOffset = (long)ReadLong( archive ); long tempLength = (long)ReadLong( archive ); // Read the object from the file byte[] byteArray = new byte[tempLength]; archive.Read( byteArray, 0, (int)tempLength ); // Deserialize the ArchiveEvent try { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream( byteArray, 0, (int)tempLength ); e = (NetworkEvent)binaryFormatter.Deserialize(memoryStream); } catch (System.Runtime.Serialization.SerializationException) { return null; } } return e; } // Get the Prev event from the archive and place the the File pointer at the beginning of that event public NetworkEvent GetPrevEvent() { PrevEvent(); return PeekNextEvent(); } // Advances the File pointer to the beginning of the previous event public void PrevEvent() { if( mode == ArchiveMode.ReadingMode ) { // Read the previous event from the file long tempPrevOffset = (long)ReadLong( archive ); if( tempPrevOffset == -1 ) { archive.Seek( -8, SeekOrigin.Current ); return; } // Go to the previous event archive.Seek( tempPrevOffset, SeekOrigin.Begin ); } } // Advances the File pointer to the beginning of the next event public void NextEvent() { if( mode == ArchiveMode.ReadingMode ) { // Read the previous event from the file long tempPrevOffset = (long)ReadLong( archive ); long tempLength = (long)ReadLong( archive ); // Go to the next event archive.Seek( tempLength, SeekOrigin.Current ); } } // Gets the next event but does not advance the File pointer public NetworkEvent PeekNextEvent() { NetworkEvent e = GetNextEvent(); PrevEvent(); return e; } // Returns whether the archive has more events in it public bool HasMoreEvents() { return ( archive.Position < archive.Length ); } // ------------------ Writing ---------------------- // Create a new archive for writing public void NewArchive( string fullpath ) { archive = new FileStream( fullpath, FileMode.Create, FileAccess.Write, FileShare.None ); mode = ArchiveMode.WritingMode; } // Add an event to the currently opened archive public void AppendEvent( NetworkEvent e ) { if( mode == ArchiveMode.WritingMode ) { // Save the current file offset long tempPrevOffset = this.PrevEventOffset; this.PrevEventOffset = archive.Position; // Serialize the Object MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, e); // Write to a byte array byte[] byteArray = new byte[memoryStream.Length]; memoryStream.Position = 0; memoryStream.Read(byteArray, 0, (int) memoryStream.Length); // Write to the file WriteLong( archive, (ulong)tempPrevOffset ); // Previous Event File Offset WriteLong( archive, (ulong)memoryStream.Length ); // Current Event Length archive.Write( byteArray, 0, (int)memoryStream.Length ); // Current Event Data } } // Writes a Long to the file private void WriteLong( FileStream s, ulong i ) { s.WriteByte( (byte)(i >> 0) ); s.WriteByte( (byte)(i >> 8) ); s.WriteByte( (byte)(i >> 16) ); s.WriteByte( (byte)(i >> 24) ); s.WriteByte( (byte)(i >> 32) ); s.WriteByte( (byte)(i >> 40) ); s.WriteByte( (byte)(i >> 48) ); s.WriteByte( (byte)(i >> 56) ); } // Reads a long from the file private ulong ReadLong( FileStream s ) { ulong result = 0; result += (ulong)s.ReadByte(); result += (ulong)s.ReadByte() << 8; result += (ulong)s.ReadByte() << 16; result += (ulong)s.ReadByte() << 24; result += (ulong)s.ReadByte() << 32; result += (ulong)s.ReadByte() << 40; result += (ulong)s.ReadByte() << 48; result += (ulong)s.ReadByte() << 56; return result; } } } // -- END ADDED
37.688172
109
0.510699
[ "Apache-2.0" ]
ClassroomPresenter/CP3
Test Code/Network Testing/Common/NetworkArchiver.cs
7,010
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Kudu.Console { 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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <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("Kudu.Console.Resources", typeof(Resources).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 string similar to Error - Changes committed to remote repository but deployment to website failed.. /// </summary> internal static string Log_DeploymentError { get { return ResourceManager.GetString("Log_DeploymentError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Skipping deployment. Remove SCM_DISABLE_DEPLOY_ON_PUSH=1 in app setting to reenable.. /// </summary> internal static string Log_NoDeploymentOnPush { get { return ResourceManager.GetString("Log_NoDeploymentOnPush", resourceCulture); } } } }
42.963415
167
0.606869
[ "Apache-2.0" ]
dotJEM/kudu
Kudu.Console/Resources.Designer.cs
3,525
C#
using System; using System.Linq; using System.Collections.Generic; namespace _06._List_Manipulation_Basics { class Program { static void Main() { List<int> numbers = Console.ReadLine() .Split() .Select(int.Parse) .ToList(); string[] command = Console.ReadLine().Split(); bool isChanged = false; while (command[0] != "end") { if (command[0] == "Add") { numbers.Add(int.Parse(command[1])); isChanged = true; } else if (command[0] == "Remove") { numbers.Remove(int.Parse(command[1])); isChanged = true; } else if (command[0] == "RemoveAt") { numbers.RemoveAt(int.Parse(command[1])); isChanged = true; } else if (command[0] == "Insert") { numbers.Insert(int.Parse(command[2]), int.Parse(command[1])); isChanged = true; } else if (command[0] == "Contains") { PrintIfContain(numbers, int.Parse(command[1])); } else if (command[0] == "PrintEven") { PrintEven(numbers); } else if (command[0] == "PrintOdd") { PrintOdd(numbers); } else if (command[0] == "GetSum") { PrintSum(numbers); } else if (command[0] == "Filter") { FilterList(numbers, command[1], int.Parse(command[2])); } command = Console.ReadLine().Split(); } if (isChanged == true) Console.WriteLine(string.Join(" ", numbers)); } static void PrintIfContain(List<int> numbers, int num) { foreach (int item in numbers) { if (item == num) { Console.WriteLine("Yes"); return; } } Console.WriteLine("No such number"); } static void PrintEven(List<int> numbers) { foreach (int item in numbers) { if (item % 2 == 0) { Console.Write(item + " "); } } } static void PrintOdd(List<int> numbers) { foreach (int item in numbers) { if (item % 2 == 1) { Console.Write(item + " "); } } } static void PrintSum(List<int> numbers) { int sum = 0; foreach (int item in numbers) { sum += item; } Console.WriteLine(sum); } static void FilterList(List<int> numbers, string @operator, int num) { switch (@operator) { case ">": Console.WriteLine(string.Join(" ", numbers.FindAll(x => x > num))); break; case "<": Console.WriteLine(string.Join(" ", numbers.FindAll(x => x < num))); break; case ">=": Console.WriteLine(string.Join(" ", numbers.FindAll(x => x >= num))); break; case "<=": Console.WriteLine(string.Join(" ", numbers.FindAll(x => x <= num))); break; default: break; } } } }
28.446043
88
0.37304
[ "MIT" ]
1TaNaTa1/Programming-Fundamentals
05. Lists/Lab/07. List Manipulation Advanced/Program.cs
3,956
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ECommerce { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
25.16
77
0.666137
[ "MIT" ]
ItsJuniorDias/CRUD-ASP.NET
Program.cs
631
C#
using Gandalan.IDAS.Client.Contracts.Contracts; using Gandalan.IDAS.WebApi.Data.DTOs.Produktion; using System; namespace Gandalan.IDAS.WebApi.Client.BusinessRoutinen { public class AVBerechnungCloudRoutinen : WebRoutinenBase { public AVBerechnungCloudRoutinen(IWebApiConfig settings) : base(settings) { } public BerechnungParameterDTO Process(BerechnungParameterDTO parameter) { return Post<BerechnungParameterDTO>($"ProcessIbos/Process", parameter); } } }
28
83
0.718045
[ "MIT" ]
Saibamen/idas-client-libs
Gandalan.IDAS.WebApi.Client/BusinessRoutinen/AVBerechnungCloudRoutinen.cs
534
C#
using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using Microsoft.Xna.Framework; using MonoGame.Extended.TextureAtlases; using Newtonsoft.Json; namespace MonoGame.Extended.Gui { public class Binding { public Binding(object viewModel, string viewModelProperty, string viewProperty) { ViewModel = viewModel; ViewModelProperty = viewModelProperty; ViewProperty = viewProperty; } public object ViewModel { get; } public string ViewModelProperty { get; } public string ViewProperty { get; } } public abstract class Element { public string Name { get; set; } public Point Position { get; set; } public Point Origin { get; set; } public Color BackgroundColor { get; set; } public Color BorderColor { get; set; } = Color.White; public int BorderThickness { get; set; } = 0; private TextureRegion2D _backgroundRegion; public TextureRegion2D BackgroundRegion { get => _backgroundRegion; set { _backgroundRegion = value; if (_backgroundRegion != null && BackgroundColor == Color.Transparent) BackgroundColor = Color.White; } } public List<Binding> Bindings { get; } = new List<Binding>(); protected void OnPropertyChanged(string propertyName) { foreach (var binding in Bindings) { if (binding.ViewProperty == propertyName) { var value = GetType() .GetTypeInfo() .GetDeclaredProperty(binding.ViewProperty) .GetValue(this); binding.ViewModel .GetType() .GetTypeInfo() .GetDeclaredProperty(binding.ViewModelProperty) .SetValue(binding.ViewModel, value); } } } private Size _size; public Size Size { get => _size; set { _size = value; OnSizeChanged(); } } protected virtual void OnSizeChanged() { } public int MinWidth { get; set; } public int MinHeight { get; set; } public int MaxWidth { get; set; } = int.MaxValue; public int MaxHeight { get; set; } = int.MaxValue; public int Width { get => Size.Width; set => Size = new Size(value, Size.Height); } public int Height { get => Size.Height; set => Size = new Size(Size.Width, value); } public Size ActualSize { get; internal set; } public abstract void Draw(IGuiContext context, IGuiRenderer renderer, float deltaSeconds); } public abstract class Element<TParent> : Element, IRectangular where TParent : IRectangular { [EditorBrowsable(EditorBrowsableState.Never)] [JsonIgnore] public TParent Parent { get; internal set; } [EditorBrowsable(EditorBrowsableState.Never)] [JsonIgnore] public Rectangle BoundingRectangle { get { var offset = Point.Zero; if (Parent != null) offset = Parent.BoundingRectangle.Location; return new Rectangle(offset + Position - ActualSize * Origin, ActualSize); } } } }
29.007937
98
0.536799
[ "MIT" ]
Acidburn0zzz/MonoGame.Extended
Source/MonoGame.Extended.Gui/Element.cs
3,655
C#
using System; using Amazon.Util; namespace IdentityServer4.Contrib.DynamoDB.Models { public static class Mapper { public static PersistedGrant ToPersistedGrantModel(IdentityServer4.Models.PersistedGrant grant) { return new PersistedGrant { Key = grant.Key, ClientId = grant.ClientId, SessionId = grant.SessionId, SubjectId = grant.SubjectId, Data = grant.Data, Type = grant.Type, Description = grant.Description, Expiration = grant.Expiration.HasValue ? new Nullable<int>(AWSSDKUtils.ConvertToUnixEpochSeconds(grant.Expiration.Value)) : null, CreationTime = grant.CreationTime, ConsumedTime = grant.ConsumedTime }; } public static IdentityServer4.Models.PersistedGrant ToPersistedGrant(PersistedGrant grant) { return new IdentityServer4.Models.PersistedGrant { Key = grant.Key, ClientId = grant.ClientId, SessionId = grant.SessionId, SubjectId = grant.SubjectId, Data = grant.Data, Type = grant.Type, Description = grant.Description, Expiration = grant.Expiration.HasValue ? new DateTime?(AWSSDKUtils.ConvertFromUnixEpochSeconds(grant.Expiration.Value)) : null, CreationTime = grant.CreationTime, ConsumedTime = grant.ConsumedTime }; } } }
37.928571
145
0.578154
[ "MIT" ]
seek-oss/IdentityServer4.Contrib.DynamoDB
IdentityServer4.Contrib.DynamoDB/Models/Mapper.cs
1,593
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.Threading; namespace System.Xaml { // XamlNode Double Buffering object that multi-threaded access // ONE reader and ONE writer. // This is the bridge used to Parse on one thread and Build on a second. public class XamlBackgroundReader : XamlReader, IXamlLineInfo { EventWaitHandle _providerFullEvent; EventWaitHandle _dataReceivedEvent; XamlNode[] _incoming; int _inIdx; XamlNode[] _outgoing; int _outIdx; int _outValid; XamlNode _currentNode; XamlReader _wrappedReader; XamlReader _internalReader; XamlWriter _writer; bool _wrappedReaderHasLineInfo; int _lineNumber=0; int _linePosition=0; Thread _thread; Exception _caughtException; public XamlBackgroundReader(XamlReader wrappedReader) { if (wrappedReader == null) { throw new ArgumentNullException(nameof(wrappedReader)); } Initialize(wrappedReader, 64); } private void Initialize(XamlReader wrappedReader, int bufferSize) { _providerFullEvent = new EventWaitHandle(false, EventResetMode.AutoReset); _dataReceivedEvent = new EventWaitHandle(false, EventResetMode.AutoReset); _incoming = new XamlNode[bufferSize]; _outgoing = new XamlNode[bufferSize]; _wrappedReader = wrappedReader; _wrappedReaderHasLineInfo = ((IXamlLineInfo)_wrappedReader).HasLineInfo; var xamlNodeAddDelegate = new XamlNodeAddDelegate(Add); XamlLineInfoAddDelegate lineInfoAddDelegate = null; if (_wrappedReaderHasLineInfo) { lineInfoAddDelegate = new XamlLineInfoAddDelegate(AddLineInfo); } _writer = new WriterDelegate(xamlNodeAddDelegate, lineInfoAddDelegate, _wrappedReader.SchemaContext); XamlNodeNextDelegate xamlNodeNextDelegate; if(_wrappedReaderHasLineInfo) { xamlNodeNextDelegate = new XamlNodeNextDelegate(Next_ProcessLineInfo); } else { xamlNodeNextDelegate = new XamlNodeNextDelegate(Next); } _internalReader = new ReaderDelegate(_wrappedReader.SchemaContext, xamlNodeNextDelegate, _wrappedReaderHasLineInfo); //Standin so it won't start null _currentNode = new XamlNode(XamlNode.InternalNodeType.StartOfStream); } public void StartThread() { StartThread("XAML reader thread"); } public void StartThread(string threadName) { if (_thread != null) { throw new InvalidOperationException(SR.Get(SRID.ThreadAlreadyStarted)); } ParameterizedThreadStart start = new ParameterizedThreadStart(XamlReaderThreadStart); _thread = new Thread(start); _thread.Name = threadName; _thread.Start(); } // The "ThreadStart" function private void XamlReaderThreadStart(object none) { try { InterruptableTransform(_wrappedReader, _writer, true); } catch (Exception ex) { _writer.Close(); _caughtException = ex; } } internal bool IncomingFull { get { return _inIdx >= _incoming.Length; } } internal bool OutgoingEmpty { get { return _outIdx >= _outValid; } } private void SwapBuffers() { XamlNode[] tmp = _incoming; _incoming = _outgoing; _outgoing = tmp; _outIdx = 0; _outValid = _inIdx; // in the EOF case the buffer can be short. _inIdx = 0; } private void AddToBuffer(XamlNode node) { _incoming[_inIdx] = node; _inIdx += 1; if (IncomingFull) { _providerFullEvent.Set(); // Reader is Full _dataReceivedEvent.WaitOne(); // Wait for data to be picked up. } } private void Add(XamlNodeType nodeType, object data) { if (IsDisposed) { return; } if (nodeType != XamlNodeType.None) { AddToBuffer(new XamlNode(nodeType, data)); return; } Debug.Assert(XamlNode.IsEof_Helper(nodeType, data)); AddToBuffer(new XamlNode(XamlNode.InternalNodeType.EndOfStream)); _providerFullEvent.Set(); } private void AddLineInfo(int lineNumber, int linePosition) { if (IsDisposed) { return; } LineInfo lineInfo = new LineInfo(lineNumber, linePosition); XamlNode node = new XamlNode(lineInfo); AddToBuffer(node); } private XamlNode Next() { if (IsDisposed) { throw new ObjectDisposedException("XamlBackgroundReader"); } if (OutgoingEmpty) { // This is for users that read PAST the EOF record. // Don't let them hang on WaitOne() return EOF Again! if (_currentNode.IsEof) { return _currentNode; } _providerFullEvent.WaitOne(); // Wait for provider to fill up. SwapBuffers(); _dataReceivedEvent.Set(); // Let the Reader run. } _currentNode = _outgoing[_outIdx++]; if (_currentNode.IsEof) { if (_thread != null) { // If the input ended due to an (caught) exception on the background thread, // then at the end of reading the input re-throw the exception on the // foreground thread. _thread.Join(); if (_caughtException != null) { Exception ex = _caughtException; _caughtException = null; throw ex; } } } return _currentNode; } private XamlNode Next_ProcessLineInfo() { bool done = false; while (!done) { Next(); if (_currentNode.IsLineInfo) { _lineNumber = _currentNode.LineInfo.LineNumber; _linePosition = _currentNode.LineInfo.LinePosition; } else { done = true; } } return _currentNode; } private void InterruptableTransform(XamlReader reader, XamlWriter writer, bool closeWriter) { IXamlLineInfo xamlLineInfo = reader as IXamlLineInfo; IXamlLineInfoConsumer xamlLineInfoConsumer = writer as IXamlLineInfoConsumer; bool shouldPassLineNumberInfo = false; if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) && (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)) { shouldPassLineNumberInfo = true; } while (reader.Read()) { if (IsDisposed) { break; } if (shouldPassLineNumberInfo) { if (xamlLineInfo.LineNumber != 0) { xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition); } } writer.WriteNode(reader); } if (closeWriter) { writer.Close(); } } #region XamlReader public override bool Read() { return _internalReader.Read(); } public override XamlNodeType NodeType { get { return _internalReader.NodeType; } } public override bool IsEof { get { return _internalReader.IsEof; } } public override NamespaceDeclaration Namespace { get { return _internalReader.Namespace; } } public override XamlType Type { get { return _internalReader.Type; } } public override object Value { get { return _internalReader.Value; } } public override XamlMember Member { get { return _internalReader.Member; } } public override XamlSchemaContext SchemaContext { get { return _internalReader.SchemaContext; } } #endregion #region IXamlLineInfo Members public bool HasLineInfo { get { return _wrappedReaderHasLineInfo; } } public int LineNumber { get { return _lineNumber; } } public int LinePosition { get { return _linePosition; } } #endregion protected override void Dispose(bool disposing) { base.Dispose(disposing); _dataReceivedEvent.Set(); // Release any blocked writers. ((IDisposable)_dataReceivedEvent).Dispose(); ((IDisposable)_internalReader).Dispose(); ((IDisposable)_providerFullEvent).Dispose(); ((IDisposable)_writer).Dispose(); } } }
30.109792
128
0.529023
[ "MIT" ]
56hide/wpf
src/Microsoft.DotNet.Wpf/src/System.Xaml/System/Xaml/Primitives/XamlBackgroundReader.cs
10,147
C#
/*Implement an extension method Substring(int index, int length) for the class StringBuilder that returns new StringBuilder and has the same functionality as Substring in the class String.*/ namespace SubstringStringBuilder { using System; using System.Text; public static class StringBuilderExtensions { //both startIndex and lenghth public static StringBuilder Substring(this StringBuilder input, int index, int length) { return new StringBuilder(input.ToString().Substring(index, length)); } //only startIndex public static StringBuilder Substring(this StringBuilder input, int index) { return new StringBuilder(input.ToString().Substring(index)); } } public class StringBuilderExtensionsTester { static void Main() { var s = new StringBuilder( "Ivailo Kenov" ); //s.Substring(08, 9); Console.WriteLine(s); var s1 = new StringBuilder(); s1 = s.Substring(0, 6); Console.WriteLine(s1); Console.WriteLine(s.Substring(7)); var strBuild = new StringBuilder(); strBuild.Append("Ivo Kenov"); Console.WriteLine(strBuild.Substring(0, 3)); } } }
31.046512
191
0.607491
[ "MIT" ]
kaizer04/Telerik-Academy-2013-2014
OOP/Extension-Lambda-Expressions-and-LINQ-Homework/01. SubstringStringBuilder/StringBuilderExtensions.cs
1,337
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary>The result returned from a database check name availability request.</summary> [System.ComponentModel.TypeConverter(typeof(CheckNameRequestTypeConverter))] public partial class CheckNameRequest { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.CheckNameRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal CheckNameRequest(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Name")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Name, global::System.Convert.ToString); } if (content.Contains("Type")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Type = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Type) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Type, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Type.CreateFrom); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.CheckNameRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal CheckNameRequest(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Name")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Name, global::System.Convert.ToString); } if (content.Contains("Type")) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Type = (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Type) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequestInternal)this).Type, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Type.CreateFrom); } AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.CheckNameRequest" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequest" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequest DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new CheckNameRequest(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.CheckNameRequest" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequest" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequest DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new CheckNameRequest(content); } /// <summary> /// Creates a new instance of <see cref="CheckNameRequest" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.ICheckNameRequest FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// The result returned from a database check name availability request. [System.ComponentModel.TypeConverter(typeof(CheckNameRequestTypeConverter))] public partial interface ICheckNameRequest { } }
62.28
375
0.680903
[ "MIT" ]
AlanFlorance/azure-powershell
src/Kusto/generated/api/Models/Api20220201/CheckNameRequest.PowerShell.cs
9,193
C#
using System; using Crestron.SimplSharpPro.DeviceSupport; namespace PepperDash.Essentials.Bridges { /// <summary> /// Defines a device that uses the legacy JoinMapBase for its join map /// </summary> [Obsolete("IBridgeAdvanced should be used going forward with JoinMapBaseAdvanced")] public interface IBridge { void LinkToApi(BasicTriList trilist, uint joinStart, string joinMapKey); } }
30.357143
87
0.724706
[ "MIT" ]
PepperDash/Essentials
PepperDashEssentials/Bridges/IBridge.cs
427
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayOpenMiniReleaststBatchqueryModel Data Structure. /// </summary> [Serializable] public class AlipayOpenMiniReleaststBatchqueryModel : AopObject { /// <summary> /// 20 /// </summary> [XmlElement("canshu")] public string Canshu { get; set; } /// <summary> /// 测试数据 /// </summary> [XmlElement("fuza")] public GavintestNewLeveaOne Fuza { get; set; } } }
22.24
67
0.571942
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Domain/AlipayOpenMiniReleaststBatchqueryModel.cs
564
C#
using GunplaOnlineShop.Data; using GunplaOnlineShop.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GunplaOnlineShop.Controllers { public class AdminController:BaseController { public AdminController(AppDbContext context, UserManager<ApplicationUser> userManager) : base(context, userManager) { } public IActionResult Index() { return View(); } } }
24
123
0.724638
[ "MIT" ]
GunplaOnlineShop/GunplaOnlineShop
GunplaOnlineShop/GunplaOnlineShop/Controllers/AdminController.cs
554
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.OpsWorks.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// Set Permission Request Marshaller /// </summary> internal class SetPermissionRequestMarshaller : IMarshaller<IRequest, SetPermissionRequest> { public IRequest Marshall(SetPermissionRequest setPermissionRequest) { IRequest request = new DefaultRequest(setPermissionRequest, "AmazonOpsWorks"); string target = "OpsWorks_20130218.SetPermission"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; string uriResourcePath = ""; if (uriResourcePath.Contains("?")) { string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1); uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?")); foreach (string s in queryString.Split('&', ';')) { string[] nameValuePair = s.Split('='); if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0) { request.Parameters.Add(nameValuePair[0], nameValuePair[1]); } else { request.Parameters.Add(nameValuePair[0], null); } } } request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter()) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); if (setPermissionRequest != null && setPermissionRequest.IsSetStackId()) { writer.WritePropertyName("StackId"); writer.Write(setPermissionRequest.StackId); } if (setPermissionRequest != null && setPermissionRequest.IsSetIamUserArn()) { writer.WritePropertyName("IamUserArn"); writer.Write(setPermissionRequest.IamUserArn); } if (setPermissionRequest != null && setPermissionRequest.IsSetAllowSsh()) { writer.WritePropertyName("AllowSsh"); writer.Write(setPermissionRequest.AllowSsh); } if (setPermissionRequest != null && setPermissionRequest.IsSetAllowSudo()) { writer.WritePropertyName("AllowSudo"); writer.Write(setPermissionRequest.AllowSudo); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
36.87963
97
0.566407
[ "Apache-2.0" ]
mahanthbeeraka/dataservices-sdk-dotnet
AWSSDK/Amazon.OpsWorks/Model/Internal/MarshallTransformations/SetPermissionRequestMarshaller.cs
3,983
C#
namespace SKIT.FlurlHttpClient.Wechat.Work.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/kf/get_servicer_statistic 接口的响应。</para> /// </summary> public class CgibinKfGetServicerStatisticResponse : WechatWorkResponse { public static class Types { public class Statistic { public static class Types { public class Data { /// <summary> /// 获取或设置咨询会话数。 /// </summary> [Newtonsoft.Json.JsonProperty("session_cnt")] [System.Text.Json.Serialization.JsonPropertyName("session_cnt")] public int SessionCount { get; set; } /// <summary> /// 获取或设置咨询客户数。 /// </summary> [Newtonsoft.Json.JsonProperty("customer_cnt")] [System.Text.Json.Serialization.JsonPropertyName("customer_cnt")] public int CustomerCount { get; set; } /// <summary> /// 获取或设置咨询消息数。 /// </summary> [Newtonsoft.Json.JsonProperty("customer_msg_cnt")] [System.Text.Json.Serialization.JsonPropertyName("customer_msg_cnt")] public int CustomerMessageCount { get; set; } /// <summary> /// 获取或设置人工回复率。 /// </summary> [Newtonsoft.Json.JsonProperty("reply_rate")] [System.Text.Json.Serialization.JsonPropertyName("reply_rate")] public double ReplyRate { get; set; } /// <summary> /// 获取或设置平均首次响应时长(单位:秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("first_reply_average_sec")] [System.Text.Json.Serialization.JsonPropertyName("first_reply_average_sec")] public int FirstReplyAverageSeconds { get; set; } /// <summary> /// 获取或设置满意度评价发送数。 /// </summary> [Newtonsoft.Json.JsonProperty("satisfaction_investgate_cnt")] [System.Text.Json.Serialization.JsonPropertyName("satisfaction_investgate_cnt")] public int SatisfactionInvestgateCount { get; set; } /// <summary> /// 获取或设置满意度参评率。 /// </summary> [Newtonsoft.Json.JsonProperty("satisfaction_participation_rate")] [System.Text.Json.Serialization.JsonPropertyName("satisfaction_participation_rate")] public double SatisfactionParticipationRate { get; set; } /// <summary> /// 获取或设置“满意”评价占比。 /// </summary> [Newtonsoft.Json.JsonProperty("satisfied_rate")] [System.Text.Json.Serialization.JsonPropertyName("satisfied_rate")] public double SatisfiedRate { get; set; } /// <summary> /// 获取或设置“一般”评价占比。 /// </summary> [Newtonsoft.Json.JsonProperty("middling_rate")] [System.Text.Json.Serialization.JsonPropertyName("middling_rate")] public double MiddlingRate { get; set; } /// <summary> /// 获取或设置“不满意”评价占比。 /// </summary> [Newtonsoft.Json.JsonProperty("dissatisfied_rate")] [System.Text.Json.Serialization.JsonPropertyName("dissatisfied_rate")] public double DissatisfiedRate { get; set; } /// <summary> /// 获取或设置升级服务客户数。 /// </summary> [Newtonsoft.Json.JsonProperty("upgrade_service_customer_cnt")] [System.Text.Json.Serialization.JsonPropertyName("upgrade_service_customer_cnt")] public int UpgradeServiceCustomerCount { get; set; } /// <summary> /// 获取或设置专员服务邀请数。 /// </summary> [Newtonsoft.Json.JsonProperty("upgrade_service_member_invite_cnt")] [System.Text.Json.Serialization.JsonPropertyName("upgrade_service_member_invite_cnt")] public int UpgradeServiceMemberInviteCount { get; set; } /// <summary> /// 获取或设置添加专员的客户数。 /// </summary> [Newtonsoft.Json.JsonProperty("upgrade_service_member_customer_cnt")] [System.Text.Json.Serialization.JsonPropertyName("upgrade_service_member_customer_cnt")] public int UpgradeServiceMemberCustomerCount { get; set; } /// <summary> /// 获取或设置客户群服务邀请数。 /// </summary> [Newtonsoft.Json.JsonProperty("upgrade_service_groupchat_invite_cnt")] [System.Text.Json.Serialization.JsonPropertyName("upgrade_service_groupchat_invite_cnt")] public int UpgradeServiceGroupChatInviteCount { get; set; } /// <summary> /// 获取或设置加入客户群的客户数。 /// </summary> [Newtonsoft.Json.JsonProperty("upgrade_service_groupchat_customer_cnt")] [System.Text.Json.Serialization.JsonPropertyName("upgrade_service_groupchat_customer_cnt")] public int UpgradeServiceGroupChatCustomerCount { get; set; } } } /// <summary> /// 获取或设置统计日期时间戳。 /// </summary> [Newtonsoft.Json.JsonProperty("stat_date")] [System.Text.Json.Serialization.JsonPropertyName("stat_date")] public long StatisticsTimestamp { get; set; } /// <summary> /// 获取或设置统计数据信息。 /// </summary> [Newtonsoft.Json.JsonProperty("statistic")] [System.Text.Json.Serialization.JsonPropertyName("statistic")] public Types.Data Data { get; set; } = default!; } } /// <summary> /// 获取或设置统计数据列表。 /// </summary> [Newtonsoft.Json.JsonProperty("statistic_list")] [System.Text.Json.Serialization.JsonPropertyName("statistic_list")] public Types.Statistic[]? StatisticList { get; set; } = default!; } }
47.979592
115
0.481781
[ "MIT" ]
OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Work/Models/CgibinKf/CgibinKfGetServicerStatisticResponse.cs
7,549
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Agenda_em_SQL { public partial class frmAgendaSQL : Form { public frmAgendaSQL() { InitializeComponent(); } } }
18.380952
44
0.696891
[ "Apache-2.0" ]
Eduardo-Quirino/.net
projetos/Agenda em SQL/Agenda em SQL/Form1.cs
388
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using AdventureWorks.BaseDomain.Enums; using AdventureWorks.BaseDomain.Interfaces; using AdventureWorks.BaseDomain.CustomTypes; using AdventureWorks.BaseDomain.Entities.Sales; namespace AdventureWorks.Domain.Entities.Sales { public partial class CurrencyRate : BaseCurrencyRate, ILogging { [Required] [StringLength(200)] public string ModifiedBy { get; set; } [Column(TypeName = "datetime")] public DateTime ModifiedAt { get; set; } #region Navigation Properties public Currency CurrencyFrom { get; set; } public Currency CurrencyTo { get; set; } public ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; } = new List<SalesOrderHeader>(); #endregion } }
29.225806
108
0.724062
[ "Unlicense" ]
CodeSwifterGit/adventure-works
src/AdventureWorks.Domain/Entities/Sales/CurrencyRate.cs
906
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.Serialization.Json; namespace VLCore.Utils { /// <summary> /// json serializer /// </summary> public static class JsonSerializer { /// <summary> /// serialize json /// </summary> public static string Serialize(object obj) { using (MemoryStream ms = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(ms, obj); ms.Position = 0; using (StreamReader reader = new StreamReader(ms)) { return reader.ReadToEnd(); } } } /// <summary> /// deserialize json /// </summary> public static T Deserialize<T>(string jsonStr) { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } } }
28.133333
102
0.549763
[ "MIT" ]
vitolu1993/VLCore
VLCore/Utils/JsonSerializer.cs
1,268
C#
// <auto-generated /> namespace CodeFirstVidzyExcercise.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 AddGenresToGenreTable : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AddGenresToGenreTable)); string IMigrationMetadata.Id { get { return "201907311238470_AddGenresToGenreTable"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.6
104
0.638695
[ "MIT" ]
AndriesDeKock/c-sharp-code-first-entity-framework-vidzy-excercise
Migrations/201907311238470_AddGenresToGenreTable.Designer.cs
858
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201 { using Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell; /// <summary>Parameters allowed to update for a server.</summary> [System.ComponentModel.TypeConverter(typeof(ServerUpdateParametersTypeConverter))] public partial class ServerUpdateParameters { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParameters" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ServerUpdateParameters(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParameters" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ServerUpdateParameters(content); } /// <summary> /// Creates a new instance of <see cref="ServerUpdateParameters" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParameters FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParameters" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ServerUpdateParameters(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Identity")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ResourceIdentityTypeConverter.ConvertFrom); } if (content.Contains("Sku")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.SkuTypeConverter.ConvertFrom); } if (content.Contains("Property")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersPropertiesTypeConverter.ConvertFrom); } if (content.Contains("Tag")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersTagsTypeConverter.ConvertFrom); } if (content.Contains("IdentityType")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType?) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType.CreateFrom); } if (content.Contains("SkuName")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuName, global::System.Convert.ToString); } if (content.Contains("SkuTier")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuTier = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier?) content.GetValueForProperty("SkuTier",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuTier, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier.CreateFrom); } if (content.Contains("SkuCapacity")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuCapacity = (int?) content.GetValueForProperty("SkuCapacity",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuCapacity, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("SkuSize")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuSize = (string) content.GetValueForProperty("SkuSize",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuSize, global::System.Convert.ToString); } if (content.Contains("SkuFamily")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuFamily, global::System.Convert.ToString); } if (content.Contains("StorageProfile")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfile = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile) content.GetValueForProperty("StorageProfile",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfile, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.StorageProfileTypeConverter.ConvertFrom); } if (content.Contains("IdentityPrincipalId")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityPrincipalId, global::System.Convert.ToString); } if (content.Contains("IdentityTenantId")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityTenantId, global::System.Convert.ToString); } if (content.Contains("AdministratorLoginPassword")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).AdministratorLoginPassword = (System.Security.SecureString) content.GetValueForProperty("AdministratorLoginPassword",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).AdministratorLoginPassword, (object ss) => (System.Security.SecureString)ss); } if (content.Contains("Version")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Version = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion?) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Version, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion.CreateFrom); } if (content.Contains("SslEnforcement")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SslEnforcement = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum?) content.GetValueForProperty("SslEnforcement",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SslEnforcement, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum.CreateFrom); } if (content.Contains("MinimalTlsVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).MinimalTlsVersion = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum?) content.GetValueForProperty("MinimalTlsVersion",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).MinimalTlsVersion, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum.CreateFrom); } if (content.Contains("PublicNetworkAccess")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).PublicNetworkAccess = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum?) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).PublicNetworkAccess, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum.CreateFrom); } if (content.Contains("ReplicationRole")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).ReplicationRole = (string) content.GetValueForProperty("ReplicationRole",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).ReplicationRole, global::System.Convert.ToString); } if (content.Contains("StorageProfileStorageMb")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageMb = (int?) content.GetValueForProperty("StorageProfileStorageMb",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageMb, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("StorageProfileStorageAutogrow")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageAutogrow = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow?) content.GetValueForProperty("StorageProfileStorageAutogrow",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageAutogrow, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow.CreateFrom); } if (content.Contains("StorageProfileBackupRetentionDay")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileBackupRetentionDay = (int?) content.GetValueForProperty("StorageProfileBackupRetentionDay",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileBackupRetentionDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("StorageProfileGeoRedundantBackup")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileGeoRedundantBackup = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup?) content.GetValueForProperty("StorageProfileGeoRedundantBackup",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileGeoRedundantBackup, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup.CreateFrom); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParameters" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ServerUpdateParameters(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Identity")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IResourceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ResourceIdentityTypeConverter.ConvertFrom); } if (content.Contains("Sku")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ISku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.SkuTypeConverter.ConvertFrom); } if (content.Contains("Property")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersPropertiesTypeConverter.ConvertFrom); } if (content.Contains("Tag")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersTags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerUpdateParametersTagsTypeConverter.ConvertFrom); } if (content.Contains("IdentityType")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityType = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType?) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityType, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.IdentityType.CreateFrom); } if (content.Contains("SkuName")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuName, global::System.Convert.ToString); } if (content.Contains("SkuTier")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuTier = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier?) content.GetValueForProperty("SkuTier",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuTier, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SkuTier.CreateFrom); } if (content.Contains("SkuCapacity")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuCapacity = (int?) content.GetValueForProperty("SkuCapacity",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuCapacity, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("SkuSize")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuSize = (string) content.GetValueForProperty("SkuSize",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuSize, global::System.Convert.ToString); } if (content.Contains("SkuFamily")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuFamily = (string) content.GetValueForProperty("SkuFamily",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SkuFamily, global::System.Convert.ToString); } if (content.Contains("StorageProfile")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfile = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile) content.GetValueForProperty("StorageProfile",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfile, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.StorageProfileTypeConverter.ConvertFrom); } if (content.Contains("IdentityPrincipalId")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityPrincipalId, global::System.Convert.ToString); } if (content.Contains("IdentityTenantId")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).IdentityTenantId, global::System.Convert.ToString); } if (content.Contains("AdministratorLoginPassword")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).AdministratorLoginPassword = (System.Security.SecureString) content.GetValueForProperty("AdministratorLoginPassword",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).AdministratorLoginPassword, (object ss) => (System.Security.SecureString)ss); } if (content.Contains("Version")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Version = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion?) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).Version, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion.CreateFrom); } if (content.Contains("SslEnforcement")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SslEnforcement = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum?) content.GetValueForProperty("SslEnforcement",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).SslEnforcement, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum.CreateFrom); } if (content.Contains("MinimalTlsVersion")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).MinimalTlsVersion = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum?) content.GetValueForProperty("MinimalTlsVersion",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).MinimalTlsVersion, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum.CreateFrom); } if (content.Contains("PublicNetworkAccess")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).PublicNetworkAccess = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum?) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).PublicNetworkAccess, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum.CreateFrom); } if (content.Contains("ReplicationRole")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).ReplicationRole = (string) content.GetValueForProperty("ReplicationRole",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).ReplicationRole, global::System.Convert.ToString); } if (content.Contains("StorageProfileStorageMb")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageMb = (int?) content.GetValueForProperty("StorageProfileStorageMb",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageMb, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("StorageProfileStorageAutogrow")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageAutogrow = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow?) content.GetValueForProperty("StorageProfileStorageAutogrow",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileStorageAutogrow, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow.CreateFrom); } if (content.Contains("StorageProfileBackupRetentionDay")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileBackupRetentionDay = (int?) content.GetValueForProperty("StorageProfileBackupRetentionDay",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileBackupRetentionDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); } if (content.Contains("StorageProfileGeoRedundantBackup")) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileGeoRedundantBackup = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup?) content.GetValueForProperty("StorageProfileGeoRedundantBackup",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerUpdateParametersInternal)this).StorageProfileGeoRedundantBackup, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup.CreateFrom); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Parameters allowed to update for a server. [System.ComponentModel.TypeConverter(typeof(ServerUpdateParametersTypeConverter))] public partial interface IServerUpdateParameters { } }
96.396226
500
0.73638
[ "MIT" ]
Agazoth/azure-powershell
src/MySql/generated/api/Models/Api20171201/ServerUpdateParameters.PowerShell.cs
30,337
C#
using Newtonsoft.Json; using SFA.DAS.Charities.Domain.Entities; using System; namespace SFA.DAS.Charities.Import.Functions.LoadCharityCommissionsDataInToStaging.CharityCommissionModels { public class CharityTrusteeModel { [JsonProperty("date_of_extract")] public DateTime ExtractedDate { get; set; } [JsonProperty("organisation_number")] public int CharityId { get; set; } [JsonProperty("registered_charity_number")] public int RegisteredCharityNumber { get; set; } [JsonProperty("linked_charity_number")] public int LinkedCharityNumber { get; set; } [JsonProperty("trustee_id")] public int TrusteeId { get; set; } [JsonProperty("trustee_name")] public string TrusteeName { get; set; } [JsonProperty("trustee_is_chair")] public bool IsChair { get; set; } [JsonProperty("individual_or_organisation")] public char IndividualOrOrganisation { get; set; } [JsonProperty("trustee_date_of_appointment")] public DateTime? AppointmentDate { get; set; } public static implicit operator CharityTrusteeStaging(CharityTrusteeModel model) => new CharityTrusteeStaging { CharityId = model.CharityId, RegistrationNumber = model.RegisteredCharityNumber, TrusteeId = model.TrusteeId, Name = model.TrusteeName, IsChair = model.IsChair, AppointmentDate = model.AppointmentDate, TrusteeType = model.IndividualOrOrganisation == 'O' ? TrusteeType.Organisation : TrusteeType.Individual }; } }
41.073171
119
0.653207
[ "MIT" ]
SkillsFundingAgency/das-charities-api
src/SFA.DAS.Charities.Import/Functions/LoadCharityCommissionsDataInToStaging/CharityCommissionModels/CharityTrusteeModel.cs
1,686
C#
using System.Reflection; namespace BlazorDoc.Models { public class PropertyComment { public string Summary { get; set; } public PropertyInfo PropertyInfo { get; set; } public PropertyComment(string summary, PropertyInfo propertyInfo) { Summary = summary; PropertyInfo = propertyInfo; } } }
23
73
0.619565
[ "MIT" ]
BlazoredDocumentation/BlazorDoc
BlazorDoc.Core/Models/PropertyComment.cs
370
C#
namespace CinemaWorld.Models.ViewModels.Countries { using System.ComponentModel.DataAnnotations; using CinemaWorld.Services.Mapping; using static CinemaWorld.Models.Common.ModelValidation; using static CinemaWorld.Models.Common.ModelValidation.Country; using Country = CinemaWorld.Data.Models.Country; public class CountryEditViewModel : IMapFrom<Country> { public int Id { get; set; } [Required(ErrorMessage = EmptyFieldLengthError)] [StringLength(NameMaxLength, MinimumLength = NameMinLength, ErrorMessage = NameLengthError)] public string Name { get; set; } } }
30.238095
100
0.732283
[ "MIT" ]
stanislavstoyanov99/CinemaWorld
src/CinemaWorld.Models.ViewModels/Countries/CountryEditViewModel.cs
637
C#
using System; using System.Linq; using System.Threading.Tasks; using ExchangeSharp; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ExchangeSharpTests { [TestClass] public sealed class ExchangeBitBankTests { private ExchangeBitBankAPI MakeMockRequestMaker(string response = null) { var requestMaker = new MockAPIRequestMaker(); if (response != null) { requestMaker.GlobalResponse = response; } var api = (ExchangeAPI.GetExchangeAPI(ExchangeName.BitBank) as ExchangeBitBankAPI)!; api.RequestMaker = requestMaker; return api; } # region Public API [TestMethod] public async Task ShouldParseGetTickerResult() { var data = @" { success: 1, data: { sell: '395733', buy: '395648', high: '397562', low: '393668', last: '395556', vol: '719.0633', timestamp: 1550087192693 } } "; var api = MakeMockRequestMaker(data); var ticker = await api.GetTickerAsync("BTC-JPY"); ticker.MarketSymbol.Should().Be("btc_jpy"); ticker.Ask.Should().Be(395733m); ticker.Bid.Should().Be(395648m); ticker.Last.Should().Be(395556m); ticker.Volume.BaseCurrencyVolume.Should().Be(719.0633m); } [TestMethod] public async Task ShouldGetTransactions() { var data = @" { success: 1, data: { transactions:[ { transaction_id: 29039731, side: 'sell', price: '395939', amount: '0.0382', executed_at: 1550112110441 }, { transaction_id: 29039683, side: 'buy', price: '396801', amount: '0.0080', executed_at: 1550111567665 } ] } } "; var api = MakeMockRequestMaker(data); ExchangeOrderBook resp = await api.GetOrderBookAsync("BTC-JPY"); resp.MarketSymbol.Should().Be("btc_jpy"); resp.Asks.Should().HaveCount(1); resp.Bids.Should().HaveCount(1); } [TestMethod] public async Task ShouldGetCandleStick() { var data = @" { success: 1, data: { candlestick: [ { type: '1hour', ohlcv: [ [ '1662145', '1665719', '1612861', '1629941', '5.8362', 1514160000000 ], [ '0.01173498', '0.01173498', '0.01160568', '0.01160571', '95.0761', 1549674000000 ] ] } ], timestamp: 1514246399496 } } "; var api = MakeMockRequestMaker(data); // starttime is required. // await Assert.ThrowsExceptionAsync<APIException>(async () => await api.GetCandlesAsync("BTC-JPY", 3600)); var resp = await api.GetCandlesAsync("BTC-JPY", 3600, CryptoUtility.UtcNow); MarketCandle candle = resp.First(); candle.ExchangeName.Should().Be("BitBank"); candle.OpenPrice.Should().Be(1662145m); candle.HighPrice.Should().Be(1665719m); candle.LowPrice.Should().Be(1612861m); candle.ClosePrice.Should().Be(1629941); candle.BaseCurrencyVolume.Should().Be(5.8362); candle.Timestamp.Should().Be(DateTimeOffset.FromUnixTimeMilliseconds(1514160000000).DateTime); } # endregion # region Private API [TestMethod] public async Task ShouldGetAssets() { var data = @" { success: 1, data: { assets: [ { asset: 'jpy', amount_precision: 4, onhand_amount: '3551.9501', locked_amount: '0.0000', free_amount: '3551.9501', stop_deposit: false, stop_withdrawal: false, withdrawal_fee: { threshold: '30000.0000', under: '540.0000', over: '756.0000' } } ] } } "; var api = MakeMockRequestMaker(data); var resp = await api.GetAmountsAsync(); resp.First().Key.Should().Equals("JPY"); resp.First().Value.Should().Equals(3551.9501m); } [TestMethod] public async Task ShouldGetOrderDetail() { var data = @" { success: 1, data: { order_id: 558167000, pair: 'btc_jpy', side: 'sell', type: 'limit', start_amount: '0.00400000', remaining_amount: '0.00000000', executed_amount: '0.00400000', price: '395254.0000', average_price: '395254.0000', ordered_at: 1550096080188, executed_at: 1550096081545, status: 'FULLY_FILLED' } } "; var api = MakeMockRequestMaker(data); // Throws error when no Market Symbol var resp = await api.GetOrderDetailsAsync("558167000", "BTC-JPY"); ExchangeOrderResult resp2 = await api.GetOrderDetailsAsync("58037954"); resp.Should().BeEquivalentTo(resp2); } [TestMethod] public async Task ShouldGetOrders() { var data = @" { success: 1, data: { orders:[ { order_id: 558167037, pair: 'btc_jpy', side: 'sell', type: 'limit', start_amount: '0.00400000', remaining_amount: '0.00000000', executed_amount: '0.00400000', price: '395254.0000', average_price: '395254.0000', ordered_at: 1550096080188, executed_at: 1550096081545, status: 'FULLY_FILLED' } ] } } "; var api = MakeMockRequestMaker(data); var orderBooks = await api.GetOpenOrderDetailsAsync(); ExchangeOrderResult order = orderBooks.First(); order.IsBuy.Should().BeFalse(); } # endregion } }
34.957082
119
0.397176
[ "MIT" ]
EmergentCybernetics/ExchangeSharp
tests/ExchangeSharpTests/ExchangeBitBankTests.cs
8,145
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; #nullable enable namespace Microsoft.EntityFrameworkCore.Infrastructure { /// <summary> /// <para> /// Initializes a <see cref="IModel" /> with the runtime dependencies. /// This is typically implemented by database providers to ensure that any /// runtime dependencies specific to their database are used. /// </para> /// <para> /// This interface is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Singleton" />. This means a single instance /// is used by many <see cref="DbContext" /> instances. The implementation must be thread-safe. /// This service cannot depend on services registered as <see cref="ServiceLifetime.Scoped" />. /// </para> /// </summary> public interface IModelRuntimeInitializer { /// <summary> /// Validates and initializes the given model with runtime dependencies. /// </summary> /// <param name="model"> The model to initialize. </param> /// <param name="validationLogger"> The validation logger. </param> /// <returns> The initialized model. </returns> IModel Initialize([NotNull] IModel model, [NotNull] IDiagnosticsLogger<DbLoggerCategory.Model.Validation>? validationLogger); } }
45.525
133
0.660626
[ "Apache-2.0" ]
Ali-YousefiTelori/EntityFrameworkCore
src/EFCore/Infrastructure/IModelRuntimeInitializer.cs
1,821
C#
using System; using EventStore.ClientAPI.Resilience; namespace EventStore.ClientAPI.Subscriptions { /// <summary> /// Represents a subscription to EventStore that has been dropped that is used by the /// DroppedSubscriptionPolicy to handle it. /// </summary> public class DroppedSubscription { public DroppedSubscription(ISubscription subscription, Exception exception, SubscriptionDropReason dropReason) { StreamId = subscription.StreamId; Error = exception; DropReason = dropReason; RetryPolicy = subscription.RetryPolicy; } public string StreamId { get; } public Exception Error { get; } public SubscriptionDropReason DropReason { get; } public RetryPolicy RetryPolicy { get; } } }
32.76
118
0.667888
[ "Apache-2.0", "CC0-1.0" ]
cuteant/EventStore-DotNetty-Fork
src/EventStore.ClientAPI.Consumer/Subscriptions/DroppedSubscription.cs
821
C#
// Url:https://leetcode.com/problems/lemonade-change /* 860. Lemonade Change Easy At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5. Note that you don't have any change in hand at first. Return true if and only if you can provide every customer with correct change. Example 1: Input: [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true. Example 2: Input: [5,5,10] Output: true Example 3: Input: [10,10] Output: false Example 4: Input: [5,5,10,10,20] Output: false Explanation: From the first two customers in order, we collect two $5 bills. For the next two customers in order, we collect a $10 bill and give back a $5 bill. For the last customer, we can't give change of $15 back because we only have two $10 bills. Since not every customer received correct change, the answer is false. Note: 0 <= bills.length <= 10000 bills[i] will be either 5, 10, or 20. */ using System; namespace InterviewPreperationGuide.Core.LeetCode.problem860 { public class Solution { public void Init () { Console.WriteLine (); } // Time: O () // Space: O () public bool LemonadeChange (int[] bills) { return false; } } }
21.9375
197
0.692308
[ "MIT" ]
tarunbatta/ipg
core/leetcode/860.cs
1,755
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ComponentModel { /// <summary> /// Provides data for the <see langword='PropertyChanged'/> event. /// </summary> public class PropertyChangedEventArgs : EventArgs { /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.PropertyChangedEventArgs'/> /// class. /// </summary> public PropertyChangedEventArgs(string? propertyName) { PropertyName = propertyName; } /// <summary> /// Indicates the name of the property that changed. /// </summary> public virtual string? PropertyName { get; } } }
32.148148
106
0.633641
[ "MIT" ]
06needhamt/runtime
src/libraries/System.ObjectModel/src/System/ComponentModel/PropertyChangedEventArgs.cs
868
C#
using System; using System.Collections.Generic; using System.Net.Sockets; using MineLib.Network.IO; namespace MineLib.Network { public sealed partial class NetworkHandler : INetworkHandler { // -- Debugging public List<IPacket> PacketsReceived { get; set; } public List<IPacket> PacketsSended { get; set; } // -- Debugging. #region Properties public NetworkMode NetworkMode { get { return _minecraft.Mode; } } public bool DebugPackets { get; set; } public bool Connected { get { return _baseSock.Connected; } } public bool Crashed { get; private set; } #endregion private readonly IMinecraftClient _minecraft; private Socket _baseSock; private IMinecraftStream _stream; public NetworkHandler(IMinecraftClient client) { _minecraft = client; PacketsReceived = new List<IPacket>(); PacketsSended = new List<IPacket>(); } /// <summary> /// Start NetworkHandler. /// </summary> public void Start(bool debugPackets = true) { DebugPackets = debugPackets; // -- Connect to server. switch (NetworkMode) { case NetworkMode.Modern: _baseSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _baseSock.BeginConnect(_minecraft.ServerHost, _minecraft.ServerPort, ConnectedModern, null); break; case NetworkMode.Classic: _baseSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _baseSock.BeginConnect(_minecraft.ServerHost, _minecraft.ServerPort, ConnectedClassic, null); break; case NetworkMode.PocketEdition: _baseSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp); _baseSock.BeginConnect(_minecraft.ServerHost, _minecraft.ServerPort, ConnectedPocketEdition, null); break; } } public IAsyncResult BeginSendPacket(IPacket packet, AsyncCallback asyncCallback, object state) { if (!Connected) throw new Exception("Connection error"); if (DebugPackets) PacketsSended.Add(packet); IAsyncResult result = BeginSend(packet, asyncCallback, state); EndSend(result); return result; } public IAsyncResult BeginSend(IPacket packet, AsyncCallback asyncCallback, object state) { return _stream.BeginWrite(packet, asyncCallback, state); } public void EndSend(IAsyncResult asyncResult) { _stream.EndWrite(asyncResult); } /// <summary> /// Dispose NetworkHandler. /// </summary> public void Dispose() { if (_baseSock != null) _baseSock.Close(); if (_stream != null) _stream.Dispose(); if (PacketsReceived != null) PacketsReceived.Clear(); if (PacketsSended != null) PacketsSended.Clear(); } } }
31.194444
119
0.573167
[ "MIT" ]
MineLib/MineLib.Network
NetworkHandler.cs
3,371
C#
namespace BuildingBlocks.Swagger; public interface ISwaggerOptionsBuilder { ISwaggerOptionsBuilder Enable(bool enabled); ISwaggerOptionsBuilder ReDocEnable(bool reDocEnabled); ISwaggerOptionsBuilder WithName(string name); ISwaggerOptionsBuilder WithTitle(string title); ISwaggerOptionsBuilder WithVersion(string version); ISwaggerOptionsBuilder WithRoutePrefix(string routePrefix); ISwaggerOptionsBuilder IncludeSecurity(bool includeSecurity); SwaggerOptions Build(); }
38.615385
65
0.820717
[ "MIT" ]
MedAmineBenbaha/University-Microservices
src/BuldingBlocks/Swagger/ISwaggerOptionsBuilder.cs
502
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class FieldGenerator { private static MemberDeclarationSyntax LastField( SyntaxList<MemberDeclarationSyntax> members, FieldDeclarationSyntax fieldDeclaration) { var lastConst = members.OfType<FieldDeclarationSyntax>() .Where(f => f.Modifiers.Any(SyntaxKind.ConstKeyword)) .LastOrDefault(); // Place a const after the last existing const. If we don't have a last const // we'll just place the const before the first member in the type. if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return lastConst; } var lastReadOnly = members.OfType<FieldDeclarationSyntax>() .Where(f => f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword)) .LastOrDefault(); var lastNormal = members.OfType<FieldDeclarationSyntax>() .Where(f => !f.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) && !f.Modifiers.Any(SyntaxKind.ConstKeyword)) .LastOrDefault(); // Place a readonly field after the last readonly field if we have one. Otherwise // after the last field/const. return fieldDeclaration.Modifiers.Any(SyntaxKind.ReadOnlyKeyword) ? lastReadOnly ?? lastConst ?? lastNormal : lastNormal ?? lastReadOnly ?? lastConst; } internal static CompilationUnitSyntax AddFieldTo( CompilationUnitSyntax destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateFieldDeclaration(field, options); // Place the field after the last field or const, or at the start of the type // declaration. var members = Insert(destination.Members, declaration, options, availableIndices, after: m => LastField(m, declaration), before: FirstMember); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddFieldTo( TypeDeclarationSyntax destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateFieldDeclaration(field, options); // Place the field after the last field or const, or at the start of the type // declaration. var members = Insert(destination.Members, declaration, options, availableIndices, after: m => LastField(m, declaration), before: FirstMember); return AddMembersTo(destination, members); } public static FieldDeclarationSyntax GenerateFieldDeclaration( IFieldSymbol field, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<VariableDeclaratorSyntax>(field, options); if (reusableSyntax != null) { if (reusableSyntax.Parent is VariableDeclarationSyntax variableDeclaration) { var newVariableDeclaratorsList = new SeparatedSyntaxList<VariableDeclaratorSyntax>().Add(reusableSyntax); var newVariableDeclaration = variableDeclaration.WithVariables(newVariableDeclaratorsList); if (variableDeclaration.Parent is FieldDeclarationSyntax fieldDecl) { return fieldDecl.WithDeclaration(newVariableDeclaration); } } } var initializer = CodeGenerationFieldInfo.GetInitializer(field) is ExpressionSyntax initializerNode ? SyntaxFactory.EqualsValueClause(initializerNode) : GenerateEqualsValue(field); var fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), options), GenerateModifiers(field, options), SyntaxFactory.VariableDeclaration( field.Type.GenerateTypeSyntax(), SyntaxFactory.SingletonSeparatedList( AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer))))); return AddFormatterAndCodeGeneratorAnnotationsTo( ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, options)); } private static EqualsValueClauseSyntax GenerateEqualsValue(IFieldSymbol field) { if (field.HasConstantValue) { var canUseFieldReference = field.Type != null && !field.Type.Equals(field.ContainingType); return SyntaxFactory.EqualsValueClause(ExpressionGenerator.GenerateExpression(field.Type, field.ConstantValue, canUseFieldReference)); } return null; } private static SyntaxTokenList GenerateModifiers(IFieldSymbol field, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); AddAccessibilityModifiers(field.DeclaredAccessibility, tokens, options, Accessibility.Private); if (field.IsConst) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); } else { if (field.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (field.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } } if (CodeGenerationFieldInfo.GetIsUnsafe(field)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
44.173077
150
0.627485
[ "MIT" ]
Dean-ZhenYao-Wang/roslyn
src/Workspaces/CSharp/Portable/CodeGeneration/FieldGenerator.cs
6,893
C#
using System; namespace Jojatekok.PoloniexAPI.MarketTools { public interface ITrade { DateTime Time { get; } OrderType Type { get; } double PricePerCoin { get; } double AmountQuote { get; } double AmountBase { get; } } }
16.352941
43
0.586331
[ "MIT" ]
asyrafc/PoloniceMonitor
PoloniexApi.Net/MarketTools/Trade.Interface.cs
280
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using BinanceExchange.API.Caching; using BinanceExchange.API.Client.Interfaces; using BinanceExchange.API.Enums; using BinanceExchange.API.Models.Request; using BinanceExchange.API.Models.Response; using BinanceExchange.API.Models.Response.Abstract; using BinanceExchange.API.Utility; using log4net; namespace BinanceExchange.API.Client { /// <summary> /// The Binance Client used to communicate with the official Binance API. For more information on underlying API calls see: /// https://www.binance.com/restapipub.html /// </summary> public class BinanceClient : IBinanceClient { public TimeSpan TimestampOffset { get => _timestampOffset; set { _timestampOffset = value; RequestClient.SetTimestampOffset(_timestampOffset); } } private TimeSpan _timestampOffset; private readonly string _apiKey; private readonly string _secretKey; private readonly IAPIProcessor _apiProcessor; private readonly int _defaultReceiveWindow; private readonly ILog _logger; /// <summary> /// Create a new Binance Client based on the configuration provided /// </summary> /// <param name="configuration"></param> /// <param name="apiCache"></param> public BinanceClient(ClientConfiguration configuration, IAPIProcessor apiProcessor = null) { _logger = configuration.Logger ?? LogManager.GetLogger(typeof(BinanceClient)); Guard.AgainstNull(configuration); Guard.AgainstNullOrEmpty(configuration.ApiKey); Guard.AgainstNull(configuration.SecretKey); _defaultReceiveWindow = configuration.DefaultReceiveWindow; _apiKey = configuration.ApiKey; _secretKey = configuration.SecretKey; RequestClient.SetTimestampOffset(configuration.TimestampOffset); RequestClient.SetRateLimiting(configuration.EnableRateLimiting); RequestClient.SetAPIKey(_apiKey); if (apiProcessor == null) { _apiProcessor = new APIProcessor(_apiKey, _secretKey, new APICacheManager()); _apiProcessor.SetCacheTime(configuration.CacheTime); } else { _apiProcessor = apiProcessor; } } #region User Stream /// <summary> /// Starts a user data stream /// </summary> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> StartUserDataStream() { return await _apiProcessor.ProcessPostRequest<UserDataStreamResponse>(Endpoints.UserStream.StartUserDataStream); } /// <summary> /// Pings a user data stream to prevent timeouts /// </summary> /// <param name="userDataListenKey"></param> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> KeepAliveUserDataStream(string userDataListenKey) { Guard.AgainstNullOrEmpty(userDataListenKey); return await _apiProcessor.ProcessPutRequest<UserDataStreamResponse>(Endpoints.UserStream.KeepAliveUserDataStream(userDataListenKey)); } /// <summary> /// Closes a user data stream /// </summary> /// <param name="userDataListenKey"></param> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> CloseUserDataStream(string userDataListenKey) { Guard.AgainstNullOrEmpty(userDataListenKey); return await _apiProcessor.ProcessDeleteRequest<UserDataStreamResponse>(Endpoints.UserStream.CloseUserDataStream(userDataListenKey)); } #endregion #region General /// <summary> /// Test the connectivity to the API /// </summary> public async Task<EmptyResponse> TestConnectivity() { return await _apiProcessor.ProcessGetRequest<EmptyResponse>(Endpoints.General.TestConnectivity); } /// <summary> /// Get the current server time (UTC) /// </summary> /// <returns><see cref="ServerTimeResponse"/></returns> public async Task<ServerTimeResponse> GetServerTime() { return await _apiProcessor.ProcessGetRequest<ServerTimeResponse>(Endpoints.General.ServerTime); } /// <summary> /// Current exchange trading rules and symbol information /// </summary> /// <returns><see cref="ExchangeInfoResponse"/></returns> public async Task<ExchangeInfoResponse> GetExchangeInfo() { return await _apiProcessor.ProcessGetRequest<ExchangeInfoResponse>(Endpoints.General.ExchangeInfo); } #endregion #region Market Data /// <summary> /// Gets the current depth order book for the specified symbol /// </summary> /// <param name="symbol">The symbole to retrieve the order book for</param> /// <param name="useCache"></param> /// <param name="limit">Amount to request - defaults to 100</param> /// <returns></returns> public async Task<OrderBookResponse> GetOrderBook(string symbol, bool useCache = false, int limit = 100) { Guard.AgainstNull(symbol); if (limit > 100) { throw new ArgumentException("When requesting the order book, you can't request more than 100 at a time.", nameof(limit)); } return await _apiProcessor.ProcessGetRequest<OrderBookResponse>(Endpoints.MarketData.OrderBook(symbol, limit, useCache)); } /// <summary> /// Gets the Compressed aggregated trades in the specified window /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<List<CompressedAggregateTradeResponse>> GetCompressedAggregateTrades(GetCompressedAggregateTradesRequest request) { Guard.AgainstNull(request); Guard.AgainstNull(request.Symbol); if (request.Limit == null || (request.Limit <= 0 || request.Limit > 500)) { request.Limit = 500; } return await _apiProcessor.ProcessGetRequest<List<CompressedAggregateTradeResponse>>(Endpoints.MarketData.CompressedAggregateTrades(request)); } /// <summary> /// Gets the Klines/Candlesticks for the provided request /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<List<KlineCandleStickResponse>> GetKlinesCandlesticks(GetKlinesCandlesticksRequest request) { Guard.AgainstNull(request.Symbol); Guard.AgainstNull(request.Interval); if (request.Limit == 0 || request.Limit > 500) { request.Limit = 500; } return await _apiProcessor.ProcessGetRequest<List<KlineCandleStickResponse>>(Endpoints.MarketData.KlineCandlesticks(request)); } /// <summary> /// Gets the Daily price ticker for the provided symbol /// </summary> /// <param name="symbol"></param> /// <returns></returns> public async Task<SymbolPriceChangeTickerResponse> GetDailyTicker(string symbol) { Guard.AgainstNull(symbol); return await _apiProcessor.ProcessGetRequest<SymbolPriceChangeTickerResponse>(Endpoints.MarketData.DayPriceTicker(symbol)); } /// <summary> /// Gets all prices for all symbols /// </summary> /// <returns></returns> public async Task<List<SymbolPriceResponse>> GetSymbolsPriceTicker() { return await _apiProcessor.ProcessGetRequest<List<SymbolPriceResponse>>(Endpoints.MarketData.AllSymbolsPriceTicker); } /// <summary> /// Gets the best and quantity on the order book for all symbols /// </summary> /// <returns></returns> public async Task<List<SymbolOrderBookResponse>> GetSymbolOrderBookTicker() { return await _apiProcessor.ProcessGetRequest<List<SymbolOrderBookResponse>>(Endpoints.MarketData.SymbolsOrderBookTicker); } #endregion #region Account and Market /// <summary> /// Creates an order based on the provided request /// </summary> /// <param name="request">The <see cref="CreateOrderRequest"/> that is used to define the order</param> /// <returns>This method can return <see cref="AcknowledgeCreateOrderResponse"/>, <see cref="FullCreateOrderResponse"/> /// or <see cref="ResultCreateOrderResponse"/> based on the provided NewOrderResponseType enum in the request. /// </returns> public async Task<BaseCreateOrderResponse> CreateOrder(CreateOrderRequest request) { Guard.AgainstNull(request.Symbol); Guard.AgainstNull(request.Side); Guard.AgainstNull(request.Type); Guard.AgainstNull(request.Quantity); switch (request.NewOrderResponseType) { case NewOrderResponseType.Acknowledge: return await _apiProcessor.ProcessPostRequest<AcknowledgeCreateOrderResponse>(Endpoints.Account.NewOrder(request)); case NewOrderResponseType.Full: return await _apiProcessor.ProcessPostRequest<FullCreateOrderResponse>(Endpoints.Account.NewOrder(request)); default: return await _apiProcessor.ProcessPostRequest<ResultCreateOrderResponse>(Endpoints.Account.NewOrder(request)); } } /// <summary> /// Creates a test order based on the provided request /// </summary> /// <param name="request">The <see cref="CreateOrderRequest"/> that is used to define the order</param> /// <returns></returns> public async Task<EmptyResponse> CreateTestOrder(CreateOrderRequest request) { Guard.AgainstNull(request.Symbol); Guard.AgainstNull(request.Side); Guard.AgainstNull(request.Type); Guard.AgainstNull(request.Quantity); return await _apiProcessor.ProcessPostRequest<EmptyResponse>(Endpoints.Account.NewOrderTest(request)); } /// <summary> /// Queries an order based on the provided request /// </summary> /// <param name="request">The <see cref="QueryOrderRequest"/> that is used to define the order</param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<OrderResponse> QueryOrder(QueryOrderRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request.Symbol); return await _apiProcessor.ProcessGetRequest<OrderResponse>(Endpoints.Account.QueryOrder(request), receiveWindow); } /// <summary> /// Cancels an order based on the provided request /// </summary> /// <param name="request">The <see cref="CancelOrderRequest"/> that is used to define the order</param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<CancelOrderResponse> CancelOrder(CancelOrderRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request.Symbol); return await _apiProcessor.ProcessDeleteRequest<CancelOrderResponse>(Endpoints.Account.CancelOrder(request), receiveWindow); } /// <summary> /// Queries all orders based on the provided request /// </summary> /// <param name="request">The <see cref="CurrentOpenOrdersRequest"/> that is used to define the orders</param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<List<OrderResponse>> GetCurrentOpenOrders(CurrentOpenOrdersRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<List<OrderResponse>>(Endpoints.Account.CurrentOpenOrders(request), receiveWindow); } /// <summary> /// Queries all orders based on the provided request /// </summary> /// <param name="request">The <see cref="AllOrdersRequest"/> that is used to define the orders</param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<List<OrderResponse>> GetAllOrders(AllOrdersRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request.Symbol); return await _apiProcessor.ProcessGetRequest<List<OrderResponse>>(Endpoints.Account.AllOrders(request), receiveWindow); } /// <summary> /// Queries the current account information /// </summary> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<AccountInformationResponse> GetAccountInformation(int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<AccountInformationResponse>(Endpoints.Account.AccountInformation, receiveWindow); } /// <summary> /// Queries the current margin account information /// </summary> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<MarginAccountInformationResponse> GetMarginAccountInformation(int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<MarginAccountInformationResponse>(Endpoints.Margin.Account.AccountInformation, receiveWindow); } /// <summary> /// Queries the futures margin account information /// </summary> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<FuturesAccountInformationResponse> GetFuturesAccountInformation(int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<FuturesAccountInformationResponse>(Endpoints.Futures.Account.AccountInformation, receiveWindow); } /// <summary> /// Queries the all trades against this account /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<List<AccountTradeReponse>> GetAccountTrades(AllTradesRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<List<AccountTradeReponse>>(Endpoints.Account.AccountTradeList(request), receiveWindow); } /// <summary> /// Sends a request to withdraw to an address /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<WithdrawResponse> CreateWithdrawRequest(WithdrawRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNullOrEmpty(request.Asset); Guard.AgainstNullOrEmpty(request.Address); Guard.AgainstNull(request.Amount); return await _apiProcessor.ProcessPostRequest<WithdrawResponse>(Endpoints.Account.Withdraw(request), receiveWindow); } /// <summary> /// Gets the Deposit history /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<DepositListResponse> GetDepositHistory(FundHistoryRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<DepositListResponse>(Endpoints.Account.DepositHistory(request), receiveWindow); } /// <summary> /// Gets the Withdraw history /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<WithdrawListResponse> GetWithdrawHistory(FundHistoryRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request); return await _apiProcessor.ProcessGetRequest<WithdrawListResponse>(Endpoints.Account.WithdrawHistory(request), receiveWindow); } /// <summary> /// Gets the the Deposit address /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<DepositAddressResponse> DepositAddress(DepositAddressRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request); Guard.AgainstNullOrEmpty(request.Asset); return await _apiProcessor.ProcessGetRequest<DepositAddressResponse>(Endpoints.Account.DepositAddress(request), receiveWindow); } /// <summary> /// Returns the current Binance API System Status /// </summary> /// <param name="request"></param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<DepositAddressResponse> GetSystemStatus(int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); return await _apiProcessor.ProcessGetRequest<DepositAddressResponse>(Endpoints.Account.SystemStatus(), receiveWindow); } #endregion #region Margin /// <summary> /// Starts a user data stream /// </summary> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> StartMarginUserDataStream() { return await _apiProcessor.ProcessPostRequest<UserDataStreamResponse>(Endpoints.Margin.StartUserDataStream); } /// <summary> /// Pings a user data stream to prevent timeouts /// </summary> /// <param name="userDataListenKey"></param> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> KeepAliveMarginUserDataStream(string userDataListenKey) { Guard.AgainstNullOrEmpty(userDataListenKey); return await _apiProcessor.ProcessPutRequest<UserDataStreamResponse>(Endpoints.Margin.KeepAliveUserDataStream(userDataListenKey)); } /// <summary> /// Closes a user data stream /// </summary> /// <param name="userDataListenKey"></param> /// /// <returns><see cref="UserDataStreamResponse"/></returns> public async Task<UserDataStreamResponse> CloseMarginUserDataStream(string userDataListenKey) { Guard.AgainstNullOrEmpty(userDataListenKey); return await _apiProcessor.ProcessDeleteRequest<UserDataStreamResponse>(Endpoints.Margin.CloseUserDataStream(userDataListenKey)); } public async Task<List<MarginOrderResponse>> GetMarginAllOrders(MarginAllOrdersRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request.Symbol); return await _apiProcessor.ProcessGetRequest<List<MarginOrderResponse>>(Endpoints.Margin.AllOrders(request), receiveWindow); } /// <summary> /// Creates an order based on the provided request /// </summary> /// <param name="request">The <see cref="CreateOrderRequest"/> that is used to define the order</param> /// <returns>This method can return <see cref="AcknowledgeCreateOrderResponse"/>, <see cref="FullCreateOrderResponse"/> /// or <see cref="ResultCreateOrderResponse"/> based on the provided NewOrderResponseType enum in the request. /// </returns> public async Task<MarginBaseCreateOrderResponse> CreateMarginOrder(MarginCreateOrderRequest request) { Guard.AgainstNull(request.Symbol); Guard.AgainstNull(request.Side); Guard.AgainstNull(request.Type); Guard.AgainstNull(request.Quantity); switch (request.NewOrderResponseType) { case NewOrderResponseType.Acknowledge: return await _apiProcessor.ProcessPostRequest<MarginAcknowledgeCreateOrderResponse>(Endpoints.Margin.NewOrder(request)); case NewOrderResponseType.Full: return await _apiProcessor.ProcessPostRequest<MarginFullCreateOrderResponse>(Endpoints.Margin.NewOrder(request)); default: return await _apiProcessor.ProcessPostRequest<MarginResultCreateOrderResponse>(Endpoints.Margin.NewOrder(request)); } } ///// <summary> ///// Queries an order based on the provided request ///// </summary> ///// <param name="request">The <see cref="QueryOrderRequest"/> that is used to define the order</param> ///// <param name="receiveWindow"></param> ///// <returns></returns> //public async Task<OrderResponse> QueryMarginOrder(MarginQueryOrderRequest request, int receiveWindow = -1) //{ // receiveWindow = SetReceiveWindow(receiveWindow); // Guard.AgainstNull(request.Symbol); // return await _apiProcessor.ProcessGetRequest<OrderResponse>(Endpoints.Account.QueryOrder(request), receiveWindow); //} /// <summary> /// Cancels an order based on the provided request /// </summary> /// <param name="request">The <see cref="CancelOrderRequest"/> that is used to define the order</param> /// <param name="receiveWindow"></param> /// <returns></returns> public async Task<MarginCancelOrderResponse> CancelMarginOrder(MarginCancelOrderRequest request, int receiveWindow = -1) { receiveWindow = SetReceiveWindow(receiveWindow); Guard.AgainstNull(request.Symbol); return await _apiProcessor.ProcessDeleteRequest<MarginCancelOrderResponse>(Endpoints.Margin.CancelOrder(request), receiveWindow); } #endregion private int SetReceiveWindow(int receiveWindow) { if (receiveWindow == -1) { receiveWindow = _defaultReceiveWindow; } return receiveWindow; } } }
43.679702
154
0.640007
[ "MIT" ]
krisztianleicht/BinanceDotNet
BinanceExchange.API/Client/BinanceClient.cs
23,458
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Template.Core.FastReflection { public static class FastReflectionCaches { static FastReflectionCaches() { MethodInvokerCache = new MethodInvokerCache(); PropertyAccessorCache = new PropertyAccessorCache(); FieldAccessorCache = new FieldAccessorCache(); ConstructorInvokerCache = new ConstructorInvokerCache(); } public static IFastReflectionCache<MethodInfo, MethodInvoker> MethodInvokerCache { get; set; } public static IFastReflectionCache<PropertyInfo, PropertyAccessor> PropertyAccessorCache { get; set; } public static IFastReflectionCache<FieldInfo, FieldAccessor> FieldAccessorCache { get; set; } public static IFastReflectionCache<ConstructorInfo, ConstructorInvoker> ConstructorInvokerCache { get; set; } } }
34.172414
117
0.730575
[ "MIT" ]
xin2015/Template
Template/Template.Core/FastReflection/FastReflectionCaches.cs
993
C#
//------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Runtime Version:2.0.40607.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ namespace WindowsApplication1.Properties { using System; using System.IO; using System.Resources; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the Strongly Typed Resource Builder // class via a tool like ResGen or Visual Studio.NET. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. class Resources { private static System.Resources.ResourceManager _resMgr; private static System.Globalization.CultureInfo _resCulture; /*FamANDAssem*/ internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Resources.ResourceManager ResourceManager { get { if ((_resMgr == null)) { System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly); _resMgr = temp; } return _resMgr; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Globalization.CultureInfo Culture { get { return _resCulture; } set { _resCulture = value; } } } }
33.915493
139
0.538206
[ "MIT" ]
davidgn/Prager-Software
Backup/Create Registration Codes/Properties/Resources.cs
2,410
C#
using Microsoft.VisualStudio.Text.Classification; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; namespace TaskRunnerExtension.OutputFormatting { public class CustomClassifier : IClassifier { private IClassificationTypeRegistryService _classificationTypeRegistry; private IClassificationFormatMapService _format; internal CustomClassifier(IClassificationTypeRegistryService registry, IClassificationFormatMapService format) { _classificationTypeRegistry = registry; _format = format; } public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged; public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span) { ITextSnapshot snapshot = span.Snapshot; List<ClassificationSpan> spans = new List<ClassificationSpan>(); if (snapshot.Length == 0) { return spans; } var allText = span.GetText(); int startno = span.Start.GetContainingLine().LineNumber; int endno = (span.End - 1).GetContainingLine().LineNumber; for (int i = startno; i <= endno; i++) { ITextSnapshotLine line = snapshot.GetLineFromLineNumber(i); if (line.Length == 0) { continue; } string text = line.Snapshot.GetText(new SnapshotSpan(line.Start, line.Length)); int c1 = 0, c2, c3; IClassificationType fgType = _classificationTypeRegistry.GetClassificationType("output.term.color15"); IClassificationType bgType = null; // _classificationTypeRegistry.GetClassificationType("output.term.bgcolor00"); c1 = text.IndexOf("\u001b["); // '\x001b' if (c1 >= 0) { handleMarker: c3 = text.IndexOf("m", c1); if (c3 < 0) { // invalid or unexpected escape sequence continue; } string[] escapeCodes = text.Substring(c1 + 2, c3 - c1 - 2).Split(';'); int l = escapeCodes.Length; if (string.IsNullOrEmpty(escapeCodes[l - 1])) { l--; } for (int ii = 0; ii < l; ii++) { int v; if (int.TryParse(escapeCodes[ii], out v)) { // ansi colors if ((v >= 30 && v <= 37) || (v >= 40 && v <= 47)) { bool bright = false; if (ii + 1 < l) { int v2; if (int.TryParse(escapeCodes[ii + 1], out v2)) { if (v2 == 1) { bright = true; ii++; } else if (v2 != 0) { break; } } else { break; } } if (v >= 30 && v <= 37) { if (!bright) { fgType = _classificationTypeRegistry.GetClassificationType("output.term.color" + (v - 30).ToString("00")); } else { fgType = _classificationTypeRegistry.GetClassificationType("output.term.color" + (0x08 + (v - 30)).ToString("00")); } } if (v >= 40 && v <= 47) { if (!bright) { bgType = _classificationTypeRegistry.GetClassificationType("output.term.bgcolor" + (v - 40).ToString("00")); } else { bgType = _classificationTypeRegistry.GetClassificationType("output.term.bgcolor" + (0x08 + (v - 40)).ToString("00")); } } } else if (v >= 90 && v <= 97) { fgType = _classificationTypeRegistry.GetClassificationType("output.term.color" + (0x08 + (v - 90)).ToString("00")); } else if (v >= 100 && v <= 107) { bgType = _classificationTypeRegistry.GetClassificationType("output.term.bgcolor" + (0x08 + (v - 100)).ToString("00")); } else if (v == 38 || v == 48) { if (ii + 1 < l) { int v2; if (int.TryParse(escapeCodes[ii + 1], out v2)) { if (v2 == 2) { // rgb if (ii + 4 < l) { int r, g, b; if (!int.TryParse(escapeCodes[ii + 2], out r) || !int.TryParse(escapeCodes[ii + 3], out g) || !int.TryParse(escapeCodes[ii + 4], out b)) { break; } // TODO: handle rgb code ii += 4; } else { break; } } else if (v2 == 5) { // 256 color mode if (ii + 2 < l) { int code; if (!int.TryParse(escapeCodes[ii + 2], out code)) { break; } if (v == 38) { fgType = _classificationTypeRegistry.GetClassificationType("output.term.color" + code.ToString("00")); } if (v == 48) { bgType = _classificationTypeRegistry.GetClassificationType("output.term.bgcolor" + code.ToString("00")); } ii += 2; } else { break; } } else { break; } } else { break; } } else { break; } } else { break; } } else { break; } } c3++; // include 'm' character var tCode = _classificationTypeRegistry.GetClassificationType("output.term.colorcode"); spans.Add(new ClassificationSpan(new SnapshotSpan(line.Extent.Start + c1, c3 - c1), tCode)); c2 = text.IndexOf("\u001b[", c3); if (c2 >= 0) { if (c2 - c3 >= 0) { spans.Add(new ClassificationSpan(new SnapshotSpan(line.Extent.Start + c3, c2 - c3), fgType)); if (bgType != null) { spans.Add(new ClassificationSpan(new SnapshotSpan(line.Extent.Start + c3, c2 - c3), bgType)); } } c1 = c2; goto handleMarker; } else if (text.Length - c3 > 0) { spans.Add(new ClassificationSpan(new SnapshotSpan(line.Extent.Start + c3, text.Length - c3), fgType)); if (bgType != null) { spans.Add(new ClassificationSpan(new SnapshotSpan(line.Extent.Start + c3, text.Length - c3), bgType)); } } //spans.Add(new ClassificationSpan(line.Extent, t)); } } return spans; } } }
32.86631
151
0.542467
[ "Apache-2.0" ]
IonKiwi/TaskRunnerExtension
TaskRunnerExtension/OutputFormatting/CustomClassifier.cs
6,148
C#