content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
namespace xbuffer
{
public static class t_Global3Buffer
{
public static t_Global3 deserialize(byte[] buffer, ref uint offset)
{
// null
bool _null = boolBuffer.deserialize(buffer, ref offset);
if (_null) return null;
// id
int _id = intBuffer.deserialize(buffer, ref offset);
// stringvalue
string _stringvalue = stringBuffer.deserialize(buffer, ref offset);
// intvalue
int _intvalue = intBuffer.deserialize(buffer, ref offset);
// floatvalue
float _floatvalue = floatBuffer.deserialize(buffer, ref offset);
// intarrayvalue
int _intarrayvalue_length = intBuffer.deserialize(buffer, ref offset);
int[] _intarrayvalue = new int[_intarrayvalue_length];
for (int i = 0; i < _intarrayvalue_length; i++)
{
_intarrayvalue[i] = intBuffer.deserialize(buffer, ref offset);
}
// stringarrayvalue
int _stringarrayvalue_length = intBuffer.deserialize(buffer, ref offset);
string[] _stringarrayvalue = new string[_stringarrayvalue_length];
for (int i = 0; i < _stringarrayvalue_length; i++)
{
_stringarrayvalue[i] = stringBuffer.deserialize(buffer, ref offset);
}
// value
return new t_Global3() {
id = _id,
stringvalue = _stringvalue,
intvalue = _intvalue,
floatvalue = _floatvalue,
intarrayvalue = _intarrayvalue,
stringarrayvalue = _stringarrayvalue,
};
}
public static void serialize(t_Global3 value, XSteam steam)
{
// null
boolBuffer.serialize(value == null, steam);
if (value == null) return;
// id
intBuffer.serialize(value.id, steam);
// stringvalue
stringBuffer.serialize(value.stringvalue, steam);
// intvalue
intBuffer.serialize(value.intvalue, steam);
// floatvalue
floatBuffer.serialize(value.floatvalue, steam);
// intarrayvalue
intBuffer.serialize(value.intarrayvalue.Length, steam);
for (int i = 0; i < value.intarrayvalue.Length; i++)
{
intBuffer.serialize(value.intarrayvalue[i], steam);
}
// stringarrayvalue
intBuffer.serialize(value.stringarrayvalue.Length, steam);
for (int i = 0; i < value.stringarrayvalue.Length; i++)
{
stringBuffer.serialize(value.stringarrayvalue[i], steam);
}
}
}
}
| 27.369565 | 84 | 0.610405 | [
"Apache-2.0"
] | fqkw6/ILRuntimeMyFrame | ILRunTimeTool/XbufferExcelToData/XbufferExcelToData/bin/Debug/CSOutput/BufferCode/t_Global3Buffer.cs | 2,518 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using FluentAssertions;
using NBitcoin;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Utilities;
namespace Stratis.Bitcoin.Tests.Common
{
public class TestBase
{
public Network Network { get; protected set; }
/// <summary>
/// Initializes logger factory for inherited tests.
/// </summary>
public TestBase(Network network)
{
this.Network = network;
var serializer = new DBreezeSerializer();
serializer.Initialize(this.Network);
}
public static string AssureEmptyDir(string dir)
{
string uniqueDirName = $"{dir}-{DateTime.UtcNow:ddMMyyyyTHH.mm.ss.fff}";
Directory.CreateDirectory(uniqueDirName);
return uniqueDirName;
}
/// <summary>
/// Creates a directory and initializes a <see cref="DataFolder"/> for a test, based on the name of the class containing the test and the name of the test.
/// </summary>
/// <param name="caller">The calling object, from which we derive the namespace in which the test is contained.</param>
/// <param name="callingMethod">The name of the test being executed. A directory with the same name will be created.</param>
/// <returns>The <see cref="DataFolder"/> that was initialized.</returns>
public static DataFolder CreateDataFolder(object caller, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = "")
{
string directoryPath = GetTestDirectoryPath(caller, callingMethod);
var dataFolder = new DataFolder(new NodeSettings(networksSelector: Networks.Networks.Bitcoin, args: new string[] { $"-datadir={AssureEmptyDir(directoryPath)}" }).DataDir);
return dataFolder;
}
/// <summary>
/// Creates a directory for a test, based on the name of the class containing the test and the name of the test.
/// </summary>
/// <param name="caller">The calling object, from which we derive the namespace in which the test is contained.</param>
/// <param name="callingMethod">The name of the test being executed. A directory with the same name will be created.</param>
/// <returns>The path of the directory that was created.</returns>
public static string CreateTestDir(object caller, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = "")
{
string directoryPath = GetTestDirectoryPath(caller, callingMethod);
return AssureEmptyDir(directoryPath);
}
/// <summary>
/// Creates a directory for a test.
/// </summary>
/// <param name="testDirectory">The directory in which the test files are contained.</param>
/// <returns>The path of the directory that was created.</returns>
public static string CreateTestDir(string testDirectory)
{
string directoryPath = GetTestDirectoryPath(testDirectory);
return AssureEmptyDir(directoryPath);
}
/// <summary>
/// Gets the path of the directory that <see cref="CreateTestDir(object, string)"/> or <see cref="CreateDataFolder(object, string)"/> would create.
/// </summary>
/// <remarks>The path of the directory is of the form TestCase/{testClass}/{testName}.</remarks>
/// <param name="caller">The calling object, from which we derive the namespace in which the test is contained.</param>
/// <param name="callingMethod">The name of the test being executed. A directory with the same name will be created.</param>
/// <returns>The path of the directory.</returns>
public static string GetTestDirectoryPath(object caller, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = "")
{
return GetTestDirectoryPath(Path.Combine(caller.GetType().Name, callingMethod));
}
/// <summary>
/// Gets the path of the directory that <see cref="CreateTestDir(object, string)"/> or <see cref="CreateDataFolder(object, string)"/> would create.
/// </summary>
/// <remarks>The path of the directory is of the form TestCase/{testClass}/{testName}.</remarks>
/// <param name="testDirectory">The directory in which the test files are contained.</param>
/// <returns>The path of the directory.</returns>
public static string GetTestDirectoryPath(string testDirectory)
{
return Path.Combine("..", "..", "..", "..", "TestCase", testDirectory);
}
public void AppendBlocksToChain(ConcurrentChain chain, IEnumerable<Block> blocks)
{
foreach (Block block in blocks)
{
if (chain.Tip != null)
block.Header.HashPrevBlock = chain.Tip.HashBlock;
chain.SetTip(block.Header);
}
}
public List<Block> CreateBlocks(int amount, bool bigBlocks = false)
{
var blocks = new List<Block>();
for (int i = 0; i < amount; i++)
{
Block block = this.CreateBlock(i);
block.Header.HashPrevBlock = blocks.LastOrDefault()?.GetHash() ?? this.Network.GenesisHash;
blocks.Add(block);
}
return blocks;
}
private Block CreateBlock(int blockNumber, bool bigBlocks = false)
{
Block block = this.Network.CreateBlock();
int transactionCount = bigBlocks ? 1000 : 10;
for (int j = 0; j < transactionCount; j++)
{
Transaction trx = this.Network.CreateTransaction();
block.AddTransaction(this.Network.CreateTransaction());
trx.AddInput(new TxIn(Script.Empty));
trx.AddOutput(Money.COIN + j + blockNumber, new Script(Enumerable.Range(1, 5).SelectMany(index => Guid.NewGuid().ToByteArray())));
trx.AddInput(new TxIn(Script.Empty));
trx.AddOutput(Money.COIN + j + blockNumber + 1, new Script(Enumerable.Range(1, 5).SelectMany(index => Guid.NewGuid().ToByteArray())));
block.AddTransaction(trx);
}
block.UpdateMerkleRoot();
return block;
}
public ProvenBlockHeader CreateNewProvenBlockHeaderMock(PosBlock posBlock = null)
{
PosBlock block = posBlock == null ? CreatePosBlockMock() : posBlock;
ProvenBlockHeader provenBlockHeader = ((PosConsensusFactory)this.Network.Consensus.ConsensusFactory).CreateProvenBlockHeader(block);
return provenBlockHeader;
}
public PosBlock CreatePosBlockMock()
{
// Create coinstake Tx.
Transaction previousTx = this.Network.CreateTransaction();
previousTx.AddOutput(new TxOut());
Transaction coinstakeTx = this.Network.CreateTransaction();
coinstakeTx.AddOutput(new TxOut(0, Script.Empty));
coinstakeTx.AddOutput(new TxOut(50, new Script()));
coinstakeTx.AddInput(previousTx, 0);
coinstakeTx.IsCoinStake.Should().BeTrue();
coinstakeTx.IsCoinBase.Should().BeFalse();
// Create coinbase Tx.
Transaction coinBaseTx = this.Network.CreateTransaction();
coinBaseTx.AddOutput(100, new Script());
coinBaseTx.AddInput(new TxIn());
coinBaseTx.IsCoinBase.Should().BeTrue();
coinBaseTx.IsCoinStake.Should().BeFalse();
var block = (PosBlock)this.Network.CreateBlock();
block.AddTransaction(coinBaseTx);
block.AddTransaction(coinstakeTx);
block.BlockSignature = new BlockSignature { Signature = new byte[] { 0x2, 0x3 } };
return block;
}
/// <returns>Tip of a created chain of headers.</returns>
public ChainedHeader BuildChainWithProvenHeaders(int blockCount)
{
ChainedHeader currentHeader = ChainedHeadersHelper.CreateGenesisChainedHeader(this.Network);
for (int i = 1; i < blockCount; i++)
{
PosBlock block = this.CreatePosBlockMock();
ProvenBlockHeader header = ((PosConsensusFactory)this.Network.Consensus.ConsensusFactory).CreateProvenBlockHeader(block);
header.Nonce = RandomUtils.GetUInt32();
header.HashPrevBlock = currentHeader.HashBlock;
header.Bits = Target.Difficulty1;
ChainedHeader prevHeader = currentHeader;
currentHeader = new ChainedHeader(header, header.GetHash(), i);
currentHeader.SetPrivatePropertyValue("Previous", prevHeader);
prevHeader.Next.Add(currentHeader);
}
return currentHeader;
}
public SortedDictionary<int, ProvenBlockHeader> ConvertToDictionaryOfProvenHeaders(ChainedHeader tip)
{
var headers = new SortedDictionary<int, ProvenBlockHeader>();
ChainedHeader currentHeader = tip;
while (currentHeader.Height != 0)
{
headers.Add(currentHeader.Height, currentHeader.Header as ProvenBlockHeader);
currentHeader = currentHeader.Previous;
}
return headers;
}
}
} | 43.884259 | 183 | 0.622851 | [
"MIT"
] | bumplzz69/StratisBitcoinFullNode | src/Stratis.Bitcoin.Tests.Common/TestBase.cs | 9,481 | C# |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System.Xml;
using XenAPI;
namespace XenAdmin.XenSearch
{
public class Query
{
private QueryScope scope;
private QueryFilter filter;
public Query(QueryScope scope, QueryFilter filter)
{
if (scope == null)
this.scope = new QueryScope(ObjectTypes.AllExcFolders);
else
this.scope = scope;
this.filter = filter; // null is OK
}
public Query(XmlNode node)
{
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType != XmlNodeType.Element)
continue;
else if (child.Name == "QueryScope")
this.scope = new QueryScope(child);
else
this.filter = (QueryFilter)SearchMarshalling.FromXmlNode(child);
}
}
public QueryScope QueryScope
{
get
{
return scope;
}
}
public QueryFilter QueryFilter
{
get
{
return filter;
}
}
public bool Match(IXenObject o)
{
return (scope.WantType(o) && o.Show(XenAdminConfigManager.Provider.ShowHiddenVMs) && (filter == null || filter.Match(o) != false));
}
public QueryFilter GetSubQueryFor(PropertyNames property)
{
return (filter == null ? null : filter.GetSubQueryFor(property));
}
public override bool Equals(object obj)
{
Query other = obj as Query;
if (other == null)
return false;
if (!((filter == null && other.filter == null) || (filter != null && filter.Equals(other.filter))))
return false;
return scope.Equals(other.scope);
}
public override int GetHashCode()
{
return filter == null ? scope.GetHashCode() : (filter.GetHashCode() + 1) * scope.GetHashCode();
}
#region Marshalling
public virtual XmlNode ToXmlNode(XmlDocument doc)
{
XmlNode node = doc.CreateElement(SearchMarshalling.GetClassName(this));
node.AppendChild(scope.ToXmlNode(doc));
XmlNode filterNode = (filter == null ? null : filter.ToXmlNode(doc));
if (filterNode != null)
node.AppendChild(filterNode);
return node;
}
#endregion
}
}
| 33.130081 | 144 | 0.575951 | [
"BSD-2-Clause"
] | AaronRobson/xenadmin | XenModel/XenSearch/Query.cs | 4,077 | C# |
using System;
namespace Arbiter.MSBuild
{
public class SolutionProject
{
public Guid Id { get; }
public Guid TypeId { get; }
public string Name { get; }
public string FilePath { get; }
public SolutionProject(Guid id, Guid typeId, string name, string path)
{
Id = id;
TypeId = typeId;
Name = name;
FilePath = path;
}
}
}
| 20.904762 | 78 | 0.52164 | [
"MIT"
] | ohlookitsben/arbiter | src/Arbiter.MSBuild/SolutionProject.cs | 441 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Techno.DAL.Entities;
namespace Techno.DAL.EntityConfigs
{
class SectionConfig : IEntityTypeConfiguration<Section>
{
public void Configure(EntityTypeBuilder<Section> builder)
{
builder.ToTable(nameof(Section));
builder.HasKey(s => s.Id);
builder.Property(s => s.Name).IsRequired().HasMaxLength(50);
builder.Property(s => s.Description).IsRequired();
}
}
}
| 26.28 | 72 | 0.694064 | [
"MIT"
] | nicode-io/The_Junior_Way | 05-Bootcamps/05-02-dotNet_BI/03-ASP_dotNet/02-ASP.Net/02-02-Code/01-EF-ASP_Transition/Techno.DAL/EntityConfigs/SectionConfig.cs | 659 | C# |
// SPDX-License-Identifier: MIT
// Copyright (c) 2015-2020 David Lechner <david@lechnology.com>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Gtk;
using GISharp.Lib.GIRepository;
namespace GISharp.TypelibBrowser
{
public class InfoTreeModelImpl : global::GLib.Object, TreeModelImplementor
{
readonly IReadOnlyList<Group> topLevelGroups;
public InfoTreeModelImpl (IEnumerable<BaseInfo> topLevelInfos)
{
topLevelGroups = recursiveAddGroupings (topLevelInfos.GroupBy (i => i.InfoType.ToString ()), null);
}
#region TreeModelImplementor implementation
public global::GLib.GType GetColumnType (int index)
{
switch (index) {
case 0:
case 2:
return global::GLib.GType.String;
case 1:
return global::GLib.GType.Boolean;
}
throw new ArgumentOutOfRangeException ("index");
}
public bool GetIter (out TreeIter iter, TreePath path)
{
iter = TreeIter.Zero;
try {
IReadOnlyList<INode> currentList = topLevelGroups;
foreach (var index in path.Indices) {
iter = currentList [index].Iter;
currentList = currentList [index].Children;
}
return true;
} catch {
return false;
}
}
public TreePath GetPath (TreeIter iter)
{
var path = new TreePath ();
var node = GetNode (iter);
while (node is not null) {
path.PrependIndex (node.Index);
node = node.Parent;
}
return path;
}
public void GetValue (TreeIter iter, int column, ref global::GLib.Value value)
{
var node = GetNode (iter);
if (node is null) {
return;
}
switch (column) {
case 0: // name column
value = new global::GLib.Value (node.Name);
break;
case 1: // strikethrough
value = new global::GLib.Value (node.Deprecated);
break;
case 2: // color
if (node is Group) {
value = new global::GLib.Value ("green");
} else if (node.IsErrorDomain) {
value = new global::GLib.Value ("orange");
} else if (node.IsGType) {
value = new global::GLib.Value ("blue");
} else if (node.IsGTypeStruct) {
value = new global::GLib.Value ("magenta");
} else {
value = new global::GLib.Value ("black");
}
break;
default:
throw new ArgumentOutOfRangeException (nameof(column));
}
}
public bool IterNext (ref TreeIter iter)
{
var node = GetNode (iter);
if (node is null) {
return false;
}
var siblings = node.Parent is null ? topLevelGroups : node.Parent.Children;
if (node.Index + 1 >= siblings.Count) {
return false;
}
iter = siblings [node.Index + 1].Iter;
return true;
}
public bool IterChildren (out TreeIter iter, TreeIter parent)
{
var result = IterNthChild (out iter, parent, 0);
return result;
}
public bool IterHasChild (TreeIter iter)
{
var count = IterNChildren (iter);
return count > 0;
}
public int IterNChildren (TreeIter iter)
{
var node = GetNode (iter);
if (node is null) {
return topLevelGroups.Count;
}
return node.Children.Count;
}
public bool IterNthChild (out TreeIter iter, TreeIter parent, int n)
{
iter = TreeIter.Zero;
var node = GetNode (parent);
var children = node is null ? topLevelGroups : node.Children;
if (n >= children.Count) {
return false;
}
iter = children[n].Iter;
return true;
}
public bool IterParent (out TreeIter iter, TreeIter child)
{
iter = TreeIter.Zero;
var node = GetNode (child);
if (node is null || node.Parent is null) {
return false;
}
iter = node.Parent.Iter;
return true;
}
public void RefNode (TreeIter iter)
{
}
public void UnrefNode (TreeIter iter)
{
}
public TreeModelFlags Flags {
get {
return TreeModelFlags.ItersPersist;
}
}
public int NColumns {
get {
return 3;
}
}
#endregion
static IReadOnlyList<Group> recursiveAddGroupings (IEnumerable<IGrouping<string,BaseInfo>> groupings, Info parent)
{
var list = new List<Group> ();
foreach (var grouping in groupings) {
var group = new Group (grouping.Key, list.Count, parent, grouping);
list.Add (group);
}
return list.AsReadOnly ();
}
static IReadOnlyList<Info> recursiveAddInfos (IEnumerable<BaseInfo> children, Group parent)
{
var list = new List<Info> ();
foreach (var child in children) {
var info = new Info (child, list.Count, parent);
list.Add (info);
}
return list.AsReadOnly ();
}
static INode GetNode (TreeIter iter)
{
if (iter.UserData == IntPtr.Zero) {
return null;
}
return (INode)GCHandle.FromIntPtr (iter.UserData).Target;
}
public interface INode
{
TreeIter Iter { get; }
int Index { get; }
string Name { get; }
string Path { get; }
bool Deprecated { get; }
bool IsGType { get; }
bool IsGTypeStruct { get; }
bool IsErrorDomain { get; }
INode Parent { get; }
IReadOnlyList<INode> Children { get; }
}
public class Group : INode
{
public TreeIter Iter { get; }
public int Index { get; }
public string Name { get; }
public string Path {
get {
if (Parent is null) {
return Name;
}
return Parent.Path + "." + Name;
}
}
public bool Deprecated { get { return false; } }
public bool IsGType { get { return false; } }
public bool IsGTypeStruct { get { return false; } }
public bool IsErrorDomain { get { return false; } }
public Info Parent { get; }
INode INode.Parent { get { return Parent; } }
public IReadOnlyList<Info> Children { get; }
IReadOnlyList<INode> INode.Children { get { return Children; } }
public Group (string name, int index, Info parent, IEnumerable<BaseInfo> children)
{
Iter = new TreeIter () {
UserData = (IntPtr)GCHandle.Alloc (this)
};
Name = name;
Index = index;
Parent = parent;
Children = InfoTreeModelImpl.recursiveAddInfos (children, this);
}
}
public class Info : INode
{
public BaseInfo BaseInfo { get; }
public TreeIter Iter { get; }
public int Index { get; }
public string Namespace { get { return BaseInfo.Namespace; } }
public string Name { get { return BaseInfo.Name.ToString() ?? "<unnamed>"; } }
public string Path { get { return Parent.Path + "." + Name; } }
public bool Deprecated { get { return BaseInfo.IsDeprecated; } }
public bool IsGType {
get {
var typeInfo = BaseInfo as RegisteredTypeInfo;
if (typeInfo is null) {
return false;
}
return !string.IsNullOrEmpty(typeInfo.TypeInit);
}
}
public bool IsGTypeStruct {
get {
var structInfo = BaseInfo as StructInfo;
if (structInfo is null) {
return false;
}
return structInfo.IsGTypeStruct;
}
}
public bool IsErrorDomain {
get {
var enumInfo = BaseInfo as EnumInfo;
if (enumInfo is null) {
return false;
}
return enumInfo.ErrorDomain is not null;
}
}
public Group Parent { get; }
INode INode.Parent { get { return Parent; } }
Lazy<IReadOnlyList<Group>> _Children;
public IReadOnlyList<Group> Children { get { return _Children.Value; } }
IReadOnlyList<INode> INode.Children { get { return Children; } }
public Info (BaseInfo info, int index, Group parent)
{
if (info is null) {
throw new ArgumentNullException ("info");
}
BaseInfo = info;
Iter = new TreeIter () {
UserData = (IntPtr)GCHandle.Alloc (this)
};
Index = index;
Parent = parent;
_Children = new Lazy<IReadOnlyList<Group>> (() => {
var childGroups = new List<InfoGrouping> ();
foreach (var property in info.GetType().GetProperties ()) {
if (typeof(IEnumerable<BaseInfo>).IsAssignableFrom (property.PropertyType)) {
childGroups.Add (new InfoGrouping (property.Name,
(IEnumerable<BaseInfo>)property.GetValue (info)));
} else if (typeof(TypeInfo).IsAssignableFrom(property.PropertyType)) {
// type info will be show with parent
continue;
} else if (typeof(PropertyInfo).IsAssignableFrom(property.PropertyType)) {
var value = (BaseInfo)property.GetValue (info);
childGroups.Add (new InfoGrouping (property.Name,
value is null ? new BaseInfo[] { } : new [] { value }));
}
}
return recursiveAddGroupings (childGroups, this);
});
}
}
class InfoGrouping: IGrouping<string, BaseInfo>
{
readonly List<BaseInfo> infoList;
#region IEnumerable implementation
public IEnumerator<BaseInfo> GetEnumerator ()
{
return infoList.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
#region IGrouping implementation
public string Key { get; }
#endregion
public InfoGrouping (string key, IEnumerable<BaseInfo> infos)
{
Key = key;
infoList = infos.ToList ();
}
}
}
}
| 33.497222 | 122 | 0.481217 | [
"MIT"
] | dlech/gisharp | junk/TypelibBrowser/InfoTreeModelImpl.cs | 12,061 | C# |
using Headstart.API.Commands;
using Headstart.Common;
using Headstart.Models.Headstart;
using NSubstitute;
using NUnit.Framework;
using OrderCloud.SDK;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Headstart.Models;
namespace Headstart.Tests
{
class ValidUnitPriceTests
{
private IOrderCloudClient _oc;
private LineItemCommand _commandSub;
private List<HSLineItem> _existingLineItems;
[SetUp]
public void Setup()
{
var settings = Substitute.For<AppSettings>();
_oc = Substitute.For<IOrderCloudClient>();
_commandSub = Substitute.ForPartsOf<LineItemCommand>(default, _oc, default, default, default, default, settings);
_existingLineItems = BuildMockExistingLineItemData(); // Mock data consists of two total line items for one product (with different specs)
Substitute.For<ILineItemsResource>().PatchAsync<HSLineItem>(OrderDirection.Incoming, default, default, default).ReturnsForAnyArgs((Task)null);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_NoMarkups_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(4, 0); // Existing line items with different specs (quantity 2) cannot combine with this quantity (4). Does not hit discount price break (minimum quantity 5).
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 5);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_NoMarkups_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(5, 0);
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 3.5);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_OneMarkup_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(4, 1); // Existing line items with different specs (quantity 2) cannot combine with this quantity (4). Does not hit discount price break (minimum quantity 5).
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 7.25);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_OneMarkup_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(5, 1);
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 5.75);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_TwoMarkups_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(4, 2); // Existing line items with different specs (quantity 2) cannot combine with this quantity (4). Does not hit discount price break (minimum quantity 5).
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 11.25);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_TwoMarkups_CumulativeQtyFalse()
{
var product = BuildMockProductData(false);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(5, 2);
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 9.75);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_NoMarkups_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(2, 0); // Does not hit discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 5);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_NoMarkups_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(3, 0); // Hits discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 3.5m);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_OneMarkup_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(2, 1); // Does not hit discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 7.25);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_OneMarkup_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(3, 1); // Hits discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 5.75m);
}
[Test]
public async Task GetUnitPrice_FirstPriceBreak_TwoMarkups_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(2, 2); // Does not hit discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 11.25);
}
[Test]
public async Task GetUnitPrice_SecondPriceBreak_TwoMarkups_CumulativeQtyTrue()
{
var product = BuildMockProductData(true);
var lineItem = SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(3, 2); // Hits discount price break (minimum quantity 5) when adding existing line item quantity (2)
var lineItemTotal = await _commandSub.ValidateLineItemUnitCost(default, product, _existingLineItems, lineItem);
Assert.AreEqual(lineItemTotal, 9.75m);
}
private SuperHSMeProduct BuildMockProductData(bool UseCumulativeQty)
{
var product = Substitute.For<SuperHSMeProduct>();
product.PriceSchedule = Substitute.For<PriceSchedule>();
product.PriceSchedule.UseCumulativeQuantity = UseCumulativeQty;
var priceBreak1 = Substitute.For<PriceBreak>();
priceBreak1.Quantity = 1;
priceBreak1.Price = 5;
var priceBreak2 = Substitute.For<PriceBreak>();
priceBreak2.Quantity = 5;
priceBreak2.Price = 3.5M;
product.PriceSchedule.PriceBreaks = new List<PriceBreak> { priceBreak1, priceBreak2 };
var prodSpecSize = Substitute.For<Spec>();
prodSpecSize.ID = "Size";
prodSpecSize.Options = new List<SpecOption>() { new PartialSpecOption { ID = "Small", Value = "Small" }, new PartialSpecOption { ID = "Medium", Value = "Medium" }, new PartialSpecOption { ID = "Large", Value = "Large", PriceMarkup = 2.25M } };
var prodSpecColor = Substitute.For<Spec>();
prodSpecColor.ID = "Color";
prodSpecColor.Options = new List<SpecOption>() { new PartialSpecOption { ID = "Blue", Value = "Blue" }, new PartialSpecOption { ID = "Red", Value = "Red" }, new PartialSpecOption { ID = "Green", Value = "Green", PriceMarkup = 4 } };
product.Specs = new List<Spec> { prodSpecSize, prodSpecColor };
return product;
}
private List<HSLineItem> BuildMockExistingLineItemData()
{
var existingLineItem1 = Substitute.For<HSLineItem>();
existingLineItem1.Quantity = 1;
existingLineItem1.xp = new LineItemXp()
{
PrintArtworkURL = null
};
var existingLineItem2 = Substitute.For<HSLineItem>();
existingLineItem2.Quantity = 1;
existingLineItem2.xp = new LineItemXp()
{
PrintArtworkURL = null
};
var liSpecSizeSmall = Substitute.For<LineItemSpec>();
liSpecSizeSmall.SpecID = "Size";
liSpecSizeSmall.OptionID = "Small";
liSpecSizeSmall.Value = "Small";
var liSpecSizeMedium = Substitute.For<LineItemSpec>();
liSpecSizeMedium.SpecID = "Size";
liSpecSizeMedium.OptionID = "Medium";
liSpecSizeMedium.Value = "Medium";
var liSpecColorRed = Substitute.For<LineItemSpec>();
liSpecColorRed.SpecID = "Color";
liSpecColorRed.OptionID = "Red";
liSpecColorRed.Value = "Red";
existingLineItem1.Specs = new List<LineItemSpec> { liSpecSizeSmall, liSpecColorRed };
existingLineItem2.Specs = new List<LineItemSpec> { liSpecSizeMedium, liSpecColorRed };
var existingLineItems = new List<HSLineItem> { existingLineItem1, existingLineItem2 };
return existingLineItems;
}
private HSLineItem SetMockLineItemQtyAndMockNumberOfMarkedUpSpecs(int quantity, int numberOfMarkedUpSpecs)
{
var lineItem = Substitute.For<HSLineItem>();
lineItem.Quantity = quantity;
var liSpecSizeSmall = Substitute.For<LineItemSpec>();
liSpecSizeSmall.SpecID = "Size";
liSpecSizeSmall.OptionID = "Small";
var liSpecSizeLarge = Substitute.For<LineItemSpec>();
liSpecSizeLarge.SpecID = "Size";
liSpecSizeLarge.OptionID = "Large";
var liSpecColorBlue = Substitute.For<LineItemSpec>();
liSpecColorBlue.SpecID = "Color";
liSpecColorBlue.OptionID = "Blue";
var liSpecColorGreen = Substitute.For<LineItemSpec>();
liSpecColorGreen.SpecID = "Color";
liSpecColorGreen.OptionID = "Green";
if (numberOfMarkedUpSpecs == 0)
{
lineItem.Specs = new List<LineItemSpec> { liSpecSizeSmall, liSpecColorBlue };
}
else if (numberOfMarkedUpSpecs == 1)
{
lineItem.Specs = new List<LineItemSpec> { liSpecSizeLarge, liSpecColorBlue };
}
else if (numberOfMarkedUpSpecs == 2)
{
lineItem.Specs = new List<LineItemSpec> { liSpecSizeLarge, liSpecColorGreen };
}
else
{
throw new Exception(@"The number of marked up specs for this unit test must be 0, 1, or 2.");
}
return lineItem;
}
}
}
| 40 | 246 | 0.760603 | [
"MIT"
] | ppatel-sitecore/headstart | src/Middleware/tests/Headstart.Tests/ValidUnitPriceTests.cs | 10,282 | C# |
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
using System.Threading;
using System.Text;
using FungusBot.Services;
using Microsoft.Extensions.DependencyInjection;
namespace FungusBot {
class Program {
static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
private DiscordSocketClient _client;
private IConfiguration _config;
private MemoryService memory;
private StateService state;
private GameState gameState;
private GameState lastGameState;
public async Task MainAsync() {
_config = BuildConfig();
var services = ConfigureServices();
memory = services.GetRequiredService<MemoryService>();
state = services.GetRequiredService<StateService>();
_client = services.GetRequiredService<DiscordSocketClient>();
_client.Log += LogAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;
_client.Ready += ReadyAsync;
await _client.LoginAsync(TokenType.Bot, _config["token"]);
await _client.StartAsync();
await services.GetRequiredService<CommandHandlingService>().InitializeAsync();
await Task.Delay(Timeout.Infinite);
}
private Task ReadyAsync() {
_ = Task.Run(async () => {
while (true) {
gameState = memory.ReadGameState();
if (lastGameState != null && gameState.voteState != lastGameState.voteState) {
if (gameState.voteState == GameState.VoteState.Voting) {
await state.SetDead(x => {
x.Mute = true;
x.Deaf = false;
});
await state.SetAlive(x => {
x.Mute = false;
x.Deaf = false;
});
} else if (gameState.voteState == GameState.VoteState.InGame) {
await Task.Delay(5000);
await state.SetAlive(x => {
x.Mute = true;
x.Deaf = true;
});
await state.SetDead(x => {
x.Mute = false;
});
}
}
lastGameState = gameState;
await Task.Delay(100);
}
});
return Task.CompletedTask;
}
private Task LogAsync(LogMessage log) {
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private IConfiguration BuildConfig() {
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json")
.Build();
}
private ServiceProvider ConfigureServices() {
return new ServiceCollection()
.AddSingleton<MemoryService>()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<CommandService>()
.AddSingleton<CommandHandlingService>()
.AddSingleton<StateService>()
.AddSingleton(_config)
.BuildServiceProvider();
}
}
}
| 33.740741 | 98 | 0.509605 | [
"MIT"
] | Penple03/FungusBot | FungusBot/Program.cs | 3,646 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DanpheEMR.ServerModel
{
public class BillingPackageModel
{
[Key]
public int BillingPackageId { get; set; }
public string BillingPackageName { get; set; }
public string Description { get; set; }
public double TotalPrice { get; set; }
public double DiscountPercent { get; set; }
public string BillingItemsXML { get; set; }
public string PackageCode { get; set; }
public int? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public int? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public bool IsActive { get; set; }
public bool InsuranceApplicable { get; set; }
}
}
| 32.793103 | 54 | 0.661409 | [
"MIT"
] | MenkaChaugule/hospital-management-emr | Code/Components/DanpheEMR.ServerModel/BillingModels/BillingPackageModel.cs | 953 | C# |
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
namespace Microsoft.Boogie
{
public class Duplicator : StandardVisitor
{
// This is used to ensure that Procedures get duplicated only once
// and that Implementation.Proc is resolved to the correct duplicated
// Procedure.
private Dictionary<Procedure, Procedure> OldToNewProcedureMap = null;
public override Absy Visit(Absy node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Absy>() != null);
node = base.Visit(node);
return node;
}
public override Cmd VisitAssertCmd(AssertCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssertCmd((AssertCmd) node.Clone());
}
public override Cmd VisitAssertEnsuresCmd(AssertEnsuresCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssertEnsuresCmd((AssertEnsuresCmd) node.Clone());
}
public override Cmd VisitAssertRequiresCmd(AssertRequiresCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssertRequiresCmd((AssertRequiresCmd) node.Clone());
}
public override Cmd VisitAssignCmd(AssignCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
AssignCmd clone = (AssignCmd) node.Clone();
clone.Lhss = new List<AssignLhs /*!*/>(clone.Lhss);
clone.Rhss = new List<Expr /*!*/>(clone.Rhss);
return base.VisitAssignCmd(clone);
}
public override Cmd VisitAssumeCmd(AssumeCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssumeCmd((AssumeCmd) node.Clone());
}
public override AtomicRE VisitAtomicRE(AtomicRE node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<AtomicRE>() != null);
return base.VisitAtomicRE((AtomicRE) node.Clone());
}
public override Axiom VisitAxiom(Axiom node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Axiom>() != null);
return base.VisitAxiom((Axiom) node.Clone());
}
public override Type VisitBasicType(BasicType node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (BasicType) node.Clone();
}
public override Block VisitBlock(Block node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Block>() != null);
return base.VisitBlock((Block) node.Clone());
}
public override Expr VisitBvConcatExpr(BvConcatExpr node)
{
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitBvConcatExpr((BvConcatExpr) node.Clone());
}
public override Expr VisitBvExtractExpr(BvExtractExpr node)
{
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitBvExtractExpr((BvExtractExpr) node.Clone());
}
public override Expr VisitCodeExpr(CodeExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
CodeExpr clone = (CodeExpr) base.VisitCodeExpr((CodeExpr) node.Clone());
// Before returning, fix up the resolved goto targets
Contract.Assert(node.Blocks.Count == clone.Blocks.Count);
Dictionary<Block, Block> subst = new Dictionary<Block, Block>();
for (int i = 0; i < node.Blocks.Count; i++)
{
subst.Add(node.Blocks[i], clone.Blocks[i]);
}
foreach (Block /*!*/ b in clone.Blocks)
{
Contract.Assert(b != null);
GotoCmd g = b.TransferCmd as GotoCmd;
if (g != null)
{
List<Block> targets = new List<Block>();
foreach (Block t in cce.NonNull(g.labelTargets))
{
Block nt = subst[t];
targets.Add(nt);
}
g.labelTargets = targets;
}
}
return clone;
}
public override List<Block> VisitBlockSeq(List<Block> blockSeq)
{
//Contract.Requires(blockSeq != null);
Contract.Ensures(Contract.Result<List<Block>>() != null);
return base.VisitBlockSeq(new List<Block>(blockSeq));
}
public override List<Block /*!*/> /*!*/ VisitBlockList(List<Block /*!*/> /*!*/ blocks)
{
//Contract.Requires(cce.NonNullElements(blocks));
Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
return base.VisitBlockList(new List<Block /*!*/>(blocks));
}
public override BoundVariable VisitBoundVariable(BoundVariable node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<BoundVariable>() != null);
return base.VisitBoundVariable((BoundVariable) node.Clone());
}
public override Type VisitBvType(BvType node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (BvType) node.Clone();
}
public override Cmd VisitCallCmd(CallCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
CallCmd clone = (CallCmd) node.Clone();
Contract.Assert(clone != null);
clone.Ins = new List<Expr>(clone.Ins);
clone.Outs = new List<IdentifierExpr>(clone.Outs);
return base.VisitCallCmd(clone);
}
public override Choice VisitChoice(Choice node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Choice>() != null);
return base.VisitChoice((Choice) node.Clone());
}
public override List<Cmd> VisitCmdSeq(List<Cmd> cmdSeq)
{
//Contract.Requires(cmdSeq != null);
Contract.Ensures(Contract.Result<List<Cmd>>() != null);
return base.VisitCmdSeq(new List<Cmd>(cmdSeq));
}
public override Constant VisitConstant(Constant node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Constant>() != null);
return base.VisitConstant((Constant) node.Clone());
}
public override CtorType VisitCtorType(CtorType node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<CtorType>() != null);
// do /not/ clone the type recursively
return (CtorType) node.Clone();
}
public override Declaration VisitDeclaration(Declaration node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Declaration>() != null);
return base.VisitDeclaration((Declaration) node.Clone());
}
public override List<Declaration /*!*/> /*!*/ VisitDeclarationList(List<Declaration /*!*/> /*!*/ declarationList)
{
//Contract.Requires(cce.NonNullElements(declarationList));
Contract.Ensures(cce.NonNullElements(Contract.Result<List<Declaration>>()));
// For Implementation.Proc to resolve correctly to duplicated Procedures
// we need to visit the procedures first
for (int i = 0, n = declarationList.Count; i < n; i++)
{
if (!(declarationList[i] is Procedure))
continue;
declarationList[i] = cce.NonNull((Declaration) this.Visit(declarationList[i]));
}
// Now visit everything else
for (int i = 0, n = declarationList.Count; i < n; i++)
{
if (declarationList[i] is Procedure)
continue;
declarationList[i] = cce.NonNull((Declaration) this.Visit(declarationList[i]));
}
return declarationList;
}
public override DeclWithFormals VisitDeclWithFormals(DeclWithFormals node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<DeclWithFormals>() != null);
return base.VisitDeclWithFormals((DeclWithFormals) node.Clone());
}
public override Ensures VisitEnsures(Ensures node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Ensures>() != null);
return base.VisitEnsures((Ensures) node.Clone());
}
public override List<Ensures> VisitEnsuresSeq(List<Ensures> ensuresSeq)
{
//Contract.Requires(ensuresSeq != null);
Contract.Ensures(Contract.Result<List<Ensures>>() != null);
return base.VisitEnsuresSeq(new List<Ensures>(ensuresSeq));
}
public override Expr VisitExistsExpr(ExistsExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitExistsExpr((ExistsExpr) node.Clone());
}
public override Expr VisitExpr(Expr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitExpr((Expr) node.Clone());
}
public override IList<Expr> VisitExprSeq(IList<Expr> list)
{
//Contract.Requires(list != null);
Contract.Ensures(Contract.Result<IList<Expr>>() != null);
return base.VisitExprSeq(new List<Expr>(list));
}
public override Expr VisitForallExpr(ForallExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitForallExpr((ForallExpr) node.Clone());
}
public override Formal VisitFormal(Formal node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Formal>() != null);
return base.VisitFormal((Formal) node.Clone());
}
public override Function VisitFunction(Function node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Function>() != null);
return base.VisitFunction((Function) node.Clone());
}
public override GlobalVariable VisitGlobalVariable(GlobalVariable node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<GlobalVariable>() != null);
return base.VisitGlobalVariable((GlobalVariable) node.Clone());
}
public override GotoCmd VisitGotoCmd(GotoCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<GotoCmd>() != null);
// NOTE: This doesn't duplicate the labelTarget basic blocks
// or resolve them to the new blocks
// VisitImplementation() and VisitBlock() handle this
return base.VisitGotoCmd((GotoCmd) node.Clone());
}
public override Cmd VisitHavocCmd(HavocCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitHavocCmd((HavocCmd) node.Clone());
}
public override Expr VisitIdentifierExpr(IdentifierExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitIdentifierExpr((IdentifierExpr) node.Clone());
}
public override List<IdentifierExpr> VisitIdentifierExprSeq(List<IdentifierExpr> identifierExprSeq)
{
//Contract.Requires(identifierExprSeq != null);
Contract.Ensures(Contract.Result<List<IdentifierExpr>>() != null);
return base.VisitIdentifierExprSeq(new List<IdentifierExpr>(identifierExprSeq));
}
public override Implementation VisitImplementation(Implementation node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Implementation>() != null);
var impl = base.VisitImplementation((Implementation) node.Clone());
var blockDuplicationMapping = new Dictionary<Block, Block>();
// Compute the mapping between the blocks of the old implementation (node)
// and the new implementation (impl).
foreach (var blockPair in node.Blocks.Zip(impl.Blocks))
{
blockDuplicationMapping.Add(blockPair.Item1, blockPair.Item2);
}
// The GotoCmds and blocks have now been duplicated.
// Resolve GotoCmd targets to the duplicated blocks
foreach (GotoCmd gotoCmd in impl.Blocks.Select(bb => bb.TransferCmd).OfType<GotoCmd>())
{
var newLabelTargets = new List<Block>();
var newLabelNames = new List<string>();
for (int index = 0; index < gotoCmd.labelTargets.Count; ++index)
{
var newBlock = blockDuplicationMapping[gotoCmd.labelTargets[index]];
newLabelTargets.Add(newBlock);
newLabelNames.Add(newBlock.Label);
}
gotoCmd.labelTargets = newLabelTargets;
gotoCmd.labelNames = newLabelNames;
}
return impl;
}
public override Expr VisitLetExpr(LetExpr node)
{
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitLetExpr((LetExpr) node.Clone());
}
public override Expr VisitLiteralExpr(LiteralExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitLiteralExpr((LiteralExpr) node.Clone());
}
public override LocalVariable VisitLocalVariable(LocalVariable node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<LocalVariable>() != null);
return base.VisitLocalVariable((LocalVariable) node.Clone());
}
public override AssignLhs VisitMapAssignLhs(MapAssignLhs node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<AssignLhs>() != null);
MapAssignLhs clone = (MapAssignLhs) node.Clone();
clone.Indexes = new List<Expr /*!*/>(clone.Indexes);
return base.VisitMapAssignLhs(clone);
}
public override MapType VisitMapType(MapType node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<MapType>() != null);
// do /not/ clone the type recursively
return (MapType) node.Clone();
}
public override Expr VisitNAryExpr(NAryExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitNAryExpr((NAryExpr) node.Clone());
}
public override Expr VisitOldExpr(OldExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return base.VisitOldExpr((OldExpr) node.Clone());
}
public override Cmd VisitParCallCmd(ParCallCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
ParCallCmd clone = (ParCallCmd) node.Clone();
Contract.Assert(clone != null);
clone.CallCmds = new List<CallCmd>(node.CallCmds);
return base.VisitParCallCmd(clone);
}
public override Procedure VisitProcedure(Procedure node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Procedure>() != null);
Procedure newProcedure = null;
if (OldToNewProcedureMap != null && OldToNewProcedureMap.ContainsKey(node))
{
newProcedure = OldToNewProcedureMap[node];
}
else
{
newProcedure = base.VisitProcedure((Procedure) node.Clone());
if (OldToNewProcedureMap != null)
OldToNewProcedureMap[node] = newProcedure;
}
return newProcedure;
}
public override Program VisitProgram(Program node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Program>() != null);
// If cloning an entire program we need to ensure that
// Implementation.Proc gets resolved to the right Procedure
// (i.e. we don't duplicate Procedure twice) and CallCmds
// call the right Procedure.
// The map below is used to achieve this.
OldToNewProcedureMap = new Dictionary<Procedure, Procedure>();
var newProgram = base.VisitProgram((Program) node.Clone());
// We need to make sure that CallCmds get resolved to call Procedures we duplicated
// instead of pointing to procedures in the old program
var callCmds = newProgram.Blocks().SelectMany(b => b.Cmds).OfType<CallCmd>();
foreach (var callCmd in callCmds)
{
callCmd.Proc = OldToNewProcedureMap[callCmd.Proc];
}
OldToNewProcedureMap = null; // This Visitor could be used for other things later so remove the map.
return newProgram;
}
public override QKeyValue VisitQKeyValue(QKeyValue node)
{
//Contract.Requires(node != null);
var newParams = new List<object>();
foreach (var o in node.Params)
{
var e = o as Expr;
if (e == null)
{
newParams.Add(o);
}
else
{
newParams.Add((Expr) this.Visit(e));
}
}
QKeyValue next = node.Next == null ? null : (QKeyValue) this.Visit(node.Next);
return new QKeyValue(node.tok, node.Key, newParams, next);
}
public override BinderExpr VisitBinderExpr(BinderExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<BinderExpr>() != null);
return base.VisitBinderExpr((BinderExpr) node.Clone());
}
public override Requires VisitRequires(Requires node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Requires>() != null);
return base.VisitRequires((Requires) node.Clone());
}
public override List<Requires> VisitRequiresSeq(List<Requires> requiresSeq)
{
//Contract.Requires(requiresSeq != null);
Contract.Ensures(Contract.Result<List<Requires>>() != null);
return base.VisitRequiresSeq(new List<Requires>(requiresSeq));
}
public override Cmd VisitRE(RE node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitRE((RE) node.Clone());
}
public override List<RE> VisitRESeq(List<RE> reSeq)
{
//Contract.Requires(reSeq != null);
Contract.Ensures(Contract.Result<List<RE>>() != null);
return base.VisitRESeq(new List<RE>(reSeq));
}
public override ReturnCmd VisitReturnCmd(ReturnCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<ReturnCmd>() != null);
return base.VisitReturnCmd((ReturnCmd) node.Clone());
}
public override ReturnExprCmd VisitReturnExprCmd(ReturnExprCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<ReturnExprCmd>() != null);
return base.VisitReturnExprCmd((ReturnExprCmd) node.Clone());
}
public override Sequential VisitSequential(Sequential node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Sequential>() != null);
return base.VisitSequential((Sequential) node.Clone());
}
public override AssignLhs VisitSimpleAssignLhs(SimpleAssignLhs node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<AssignLhs>() != null);
return base.VisitSimpleAssignLhs((SimpleAssignLhs) node.Clone());
}
public override Cmd VisitStateCmd(StateCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitStateCmd((StateCmd) node.Clone());
}
public override TransferCmd VisitTransferCmd(TransferCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<TransferCmd>() != null);
return base.VisitTransferCmd((TransferCmd) node.Clone());
}
public override Trigger VisitTrigger(Trigger node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Trigger>() != null);
return base.VisitTrigger((Trigger) node.Clone());
}
public override Type VisitType(Type node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (Type) node.Clone();
}
public override TypedIdent VisitTypedIdent(TypedIdent node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<TypedIdent>() != null);
return base.VisitTypedIdent((TypedIdent) node.Clone());
}
public override Variable VisitVariable(Variable node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Variable>() != null);
return node;
}
public override List<Variable> VisitVariableSeq(List<Variable> variableSeq)
{
//Contract.Requires(variableSeq != null);
Contract.Ensures(Contract.Result<List<Variable>>() != null);
return base.VisitVariableSeq(new List<Variable>(variableSeq));
}
public override YieldCmd VisitYieldCmd(YieldCmd node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<YieldCmd>() != null);
return base.VisitYieldCmd((YieldCmd) node.Clone());
}
}
#region A duplicator that also does substitutions for a set of variables
/// <summary>
/// A substitution is a partial mapping from Variables to Exprs.
/// </summary>
public delegate Expr /*?*/ Substitution(Variable /*!*/ v);
public static class Substituter
{
public static Substitution SubstitutionFromHashtable(Dictionary<Variable, Expr> map, bool fallBackOnName = false,
Procedure proc = null)
{
Contract.Requires(map != null);
Contract.Ensures(Contract.Result<Substitution>() != null);
// TODO: With Whidbey, could use anonymous functions.
return new Substitution(new CreateSubstitutionClosure(map, fallBackOnName, proc).Method);
}
private sealed class CreateSubstitutionClosure
{
Dictionary<Variable /*!*/, Expr /*!*/> /*!*/
map;
Dictionary<string /*!*/, Expr /*!*/> /*!*/
nameMap;
Procedure proc;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(map != null);
}
static string UniqueName(Variable variable, Procedure proc)
{
// TODO(wuestholz): Maybe we should define structural equality for variables instead.
var scope = "#global_scope#";
if (proc != null && !(variable is GlobalVariable || variable is Constant))
{
scope = proc.Name;
}
return string.Format("{0}.{1}", scope, variable.Name);
}
public CreateSubstitutionClosure(Dictionary<Variable, Expr> map, bool fallBackOnName = false,
Procedure proc = null)
: base()
{
Contract.Requires(map != null);
this.map = map;
this.proc = proc;
if (fallBackOnName && proc != null)
{
this.nameMap = map.ToDictionary(kv => UniqueName(kv.Key, proc), kv => kv.Value);
}
}
public Expr /*?*/ Method(Variable v)
{
Contract.Requires(v != null);
if (map.ContainsKey(v))
{
return map[v];
}
Expr e;
if (nameMap != null && proc != null && nameMap.TryGetValue(UniqueName(v, proc), out e))
{
return e;
}
return null;
}
}
// ----------------------------- Substitutions for Expr -------------------------------
/// <summary>
/// Apply a substitution to an expression. Any variables not in domain(subst)
/// is not changed. The substitutions apply within the "old", but the "old"
/// expression remains.
/// </summary>
public static Expr Apply(Substitution subst, Expr expr)
{
Contract.Requires(subst != null);
Contract.Requires(expr != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return (Expr) new NormalSubstituter(subst).Visit(expr);
}
/// <summary>
/// Apply a substitution to an expression.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static Expr Apply(Substitution always, Substitution forold, Expr expr)
{
Contract.Requires(always != null);
Contract.Requires(forold != null);
Contract.Requires(expr != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return (Expr) new NormalSubstituter(always, forold).Visit(expr);
}
/// <summary>
/// Apply a substitution to an expression replacing "old" expressions.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static Expr ApplyReplacingOldExprs(Substitution always, Substitution forOld, Expr expr)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(expr != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return (Expr) new ReplacingOldSubstituter(always, forOld).Visit(expr);
}
public static Expr FunctionCallReresolvingApplyReplacingOldExprs(Substitution always, Substitution forOld,
Expr expr, Program program)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(expr != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return (Expr) new FunctionCallReresolvingReplacingOldSubstituter(program, always, forOld).Visit(expr);
}
public static Expr FunctionCallReresolvingApply(Substitution always, Substitution forOld, Expr expr,
Program program)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(expr != null);
Contract.Ensures(Contract.Result<Expr>() != null);
return (Expr) new FunctionCallReresolvingNormalSubstituter(program, always, forOld).Visit(expr);
}
// ----------------------------- Substitutions for Cmd -------------------------------
/// <summary>
/// Apply a substitution to a command. Any variables not in domain(subst)
/// is not changed. The substitutions apply within the "old", but the "old"
/// expression remains.
/// </summary>
public static Cmd Apply(Substitution subst, Cmd cmd)
{
Contract.Requires(subst != null);
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return (Cmd) new NormalSubstituter(subst).Visit(cmd);
}
/// <summary>
/// Apply a substitution to a command.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static Cmd Apply(Substitution always, Substitution forOld, Cmd cmd)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return (Cmd) new NormalSubstituter(always, forOld).Visit(cmd);
}
/// <summary>
/// Apply a substitution to a command replacing "old" expressions.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static Cmd ApplyReplacingOldExprs(Substitution always, Substitution forOld, Cmd cmd)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(cmd != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return (Cmd) new ReplacingOldSubstituter(always, forOld).Visit(cmd);
}
// ----------------------------- Substitutions for CmdSeq -------------------------------
/// <summary>
/// Apply a substitution to a command sequence. Any variables not in domain(subst)
/// is not changed. The substitutions apply within the "old", but the "old"
/// expression remains.
/// </summary>
public static List<Cmd> Apply(Substitution subst, List<Cmd> cmdSeq)
{
Contract.Requires(subst != null);
Contract.Requires(cmdSeq != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return new NormalSubstituter(subst).VisitCmdSeq(cmdSeq);
}
/// <summary>
/// Apply a substitution to a command sequence.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static List<Cmd> Apply(Substitution always, Substitution forOld, List<Cmd> cmdSeq)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(cmdSeq != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return new NormalSubstituter(always, forOld).VisitCmdSeq(cmdSeq);
}
/// <summary>
/// Apply a substitution to a command sequence replacing "old" expressions.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
/// domain(always) is not changed. Inside "old" expressions, apply map "forOld" to
/// variables in domain(forOld), apply map "always" to variables in
/// domain(always)-domain(forOld), and leave variable unchanged otherwise.
/// </summary>
public static List<Cmd> ApplyReplacingOldExprs(Substitution always, Substitution forOld, List<Cmd> cmdSeq)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
Contract.Requires(cmdSeq != null);
Contract.Ensures(Contract.Result<Cmd>() != null);
return new ReplacingOldSubstituter(always, forOld).VisitCmdSeq(cmdSeq);
}
// ----------------------------- Substitutions for QKeyValue -------------------------------
/// <summary>
/// Apply a substitution to a list of attributes. Any variables not in domain(subst)
/// is not changed. The substitutions apply within the "old", but the "old"
/// expression remains.
/// </summary>
public static QKeyValue Apply(Substitution subst, QKeyValue kv)
{
Contract.Requires(subst != null);
if (kv == null)
{
return null;
}
else
{
return (QKeyValue) new NormalSubstituter(subst).Visit(kv);
}
}
/// <summary>
/// Apply a substitution to a list of attributes replacing "old" expressions.
/// For a further description, see "ApplyReplacingOldExprs" above for Expr.
/// </summary>
public static QKeyValue ApplyReplacingOldExprs(Substitution always, Substitution forOld, QKeyValue kv)
{
Contract.Requires(always != null);
Contract.Requires(forOld != null);
if (kv == null)
{
return null;
}
else
{
return (QKeyValue) new ReplacingOldSubstituter(always, forOld).Visit(kv);
}
}
// ------------------------------------------------------------
private class NormalSubstituter : Duplicator
{
private readonly Substitution /*!*/
always;
private readonly Substitution /*!*/
forold;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(always != null);
Contract.Invariant(forold != null);
}
public NormalSubstituter(Substitution subst)
: base()
{
Contract.Requires(subst != null);
this.always = subst;
this.forold = Substituter.SubstitutionFromHashtable(new Dictionary<Variable, Expr>());
}
public NormalSubstituter(Substitution subst, Substitution forold)
: base()
{
Contract.Requires(subst != null);
this.always = subst;
this.forold = forold;
}
private bool insideOldExpr = false;
public override Expr VisitIdentifierExpr(IdentifierExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
Expr /*?*/
e = null;
if (insideOldExpr)
{
e = forold(cce.NonNull(node.Decl));
}
if (e == null)
{
e = always(cce.NonNull(node.Decl));
}
return e == null ? base.VisitIdentifierExpr(node) : e;
}
public override Expr VisitOldExpr(OldExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
bool previouslyInOld = insideOldExpr;
insideOldExpr = true;
Expr /*!*/
e = (Expr /*!*/) cce.NonNull(this.Visit(node.Expr));
insideOldExpr = previouslyInOld;
return new OldExpr(node.tok, e);
}
}
private sealed class FunctionCallReresolvingReplacingOldSubstituter : ReplacingOldSubstituter
{
readonly Program Program;
public FunctionCallReresolvingReplacingOldSubstituter(Program program, Substitution always, Substitution forold)
: base(always, forold)
{
Program = program;
}
public override Expr VisitNAryExpr(NAryExpr node)
{
var result = base.VisitNAryExpr(node);
var nAryExpr = result as NAryExpr;
if (nAryExpr != null)
{
var funCall = nAryExpr.Fun as FunctionCall;
if (funCall != null)
{
funCall.Func = Program.FindFunction(funCall.FunctionName);
}
}
return result;
}
}
private sealed class FunctionCallReresolvingNormalSubstituter : NormalSubstituter
{
readonly Program Program;
public FunctionCallReresolvingNormalSubstituter(Program program, Substitution always, Substitution forold)
: base(always, forold)
{
Program = program;
}
public override Expr VisitNAryExpr(NAryExpr node)
{
var result = base.VisitNAryExpr(node);
var nAryExpr = result as NAryExpr;
if (nAryExpr != null)
{
var funCall = nAryExpr.Fun as FunctionCall;
if (funCall != null)
{
funCall.Func = Program.FindFunction(funCall.FunctionName);
}
}
return result;
}
}
private class ReplacingOldSubstituter : Duplicator
{
private readonly Substitution /*!*/
always;
private readonly Substitution /*!*/
forold;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(always != null);
Contract.Invariant(forold != null);
}
public ReplacingOldSubstituter(Substitution always, Substitution forold)
: base()
{
Contract.Requires(forold != null);
Contract.Requires(always != null);
this.always = always;
this.forold = forold;
}
private bool insideOldExpr = false;
public override Expr VisitIdentifierExpr(IdentifierExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
Expr /*?*/
e = null;
if (insideOldExpr)
{
e = forold(cce.NonNull(node.Decl));
}
if (e == null)
{
e = always(cce.NonNull(node.Decl));
}
return e == null ? base.VisitIdentifierExpr(node) : e;
}
public override Expr VisitOldExpr(OldExpr node)
{
//Contract.Requires(node != null);
Contract.Ensures(Contract.Result<Expr>() != null);
bool previouslyInOld = insideOldExpr;
insideOldExpr = true;
Expr /*!*/
e = (Expr /*!*/) cce.NonNull(this.Visit(node.Expr));
insideOldExpr = previouslyInOld;
return e;
}
}
}
class BoundVarAndReplacingOldSubstituter : Duplicator
{
private Dictionary<Variable, Expr> subst;
private Dictionary<Variable, Expr> oldSubst;
private readonly string prefix;
private Dictionary<Variable, Expr> boundVarSubst;
private int insideOldExpr;
public static Expr Apply(Dictionary<Variable, Expr> subst, Dictionary<Variable, Expr> oldSubst, string prefix, Expr expr)
{
return (Expr) new BoundVarAndReplacingOldSubstituter(subst, oldSubst, prefix).Visit(expr);
}
public static Cmd Apply(Dictionary<Variable, Expr> subst, Dictionary<Variable, Expr> oldSubst, string prefix, Cmd cmd)
{
return (Cmd) new BoundVarAndReplacingOldSubstituter(subst, oldSubst, prefix).Visit(cmd);
}
private BoundVarAndReplacingOldSubstituter(Dictionary<Variable, Expr> subst, Dictionary<Variable, Expr> oldSubst, string prefix)
{
this.subst = subst;
this.oldSubst = oldSubst;
this.prefix = prefix;
this.boundVarSubst = new Dictionary<Variable, Expr>();
this.insideOldExpr = 0;
}
public override Expr VisitIdentifierExpr(IdentifierExpr node)
{
if (0 < insideOldExpr && oldSubst.ContainsKey(node.Decl))
{
return oldSubst[node.Decl];
}
if (subst.ContainsKey(node.Decl))
{
return subst[node.Decl];
}
if (boundVarSubst.ContainsKey(node.Decl))
{
return boundVarSubst[node.Decl];
}
return base.VisitIdentifierExpr(node);
}
public override Expr VisitOldExpr(OldExpr node)
{
insideOldExpr++;
Expr e = (Expr) this.Visit(node.Expr);
insideOldExpr--;
return e;
}
public override BinderExpr VisitBinderExpr(BinderExpr node)
{
var oldToNew = node.Dummies.ToDictionary(x => x,
x => new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, prefix + x.Name, x.TypedIdent.Type),
x.Attributes));
foreach (var x in node.Dummies)
{
boundVarSubst.Add(x, Expr.Ident(oldToNew[x]));
}
BinderExpr expr = base.VisitBinderExpr(node);
expr.Dummies = node.Dummies.Select(x => oldToNew[x]).ToList<Variable>();
// We process triggers of quantifier expressions here, because otherwise the
// substitutions for bound variables have to be leaked outside this procedure.
if (node is QuantifierExpr quantifierExpr)
{
if (quantifierExpr.Triggers != null)
{
((QuantifierExpr) expr).Triggers = this.VisitTrigger(quantifierExpr.Triggers);
}
}
foreach (var x in node.Dummies)
{
boundVarSubst.Remove(x);
}
return expr;
}
public override QuantifierExpr VisitQuantifierExpr(QuantifierExpr node)
{
// Don't remove this implementation! Triggers should be duplicated in VisitBinderExpr.
return (QuantifierExpr) this.VisitBinderExpr(node);
}
public override Expr VisitLetExpr(LetExpr node)
{
var oldToNew = node.Dummies.ToDictionary(x => x,
x => new BoundVariable(Token.NoToken, new TypedIdent(Token.NoToken, prefix + x.Name, x.TypedIdent.Type),
x.Attributes));
foreach (var x in node.Dummies)
{
boundVarSubst.Add(x, Expr.Ident(oldToNew[x]));
}
var expr = (LetExpr) base.VisitLetExpr(node);
expr.Dummies = node.Dummies.Select(x => oldToNew[x]).ToList<Variable>();
foreach (var x in node.Dummies)
{
boundVarSubst.Remove(x);
}
return expr;
}
}
#endregion
} | 34.722922 | 133 | 0.618111 | [
"MIT"
] | cbarrettfb/boogie | Source/Core/Duplicator.cs | 40,165 | C# |
namespace P02.Graphic_Editor
{
public class Square : IShape
{
private string type;
public Square(string type)
{
this.Type = type;
}
public string Type
{
get { return type; }
set { type = value; }
}
public override string ToString()
{
return $"Shape is {Type}!";
}
}
}
| 17.166667 | 41 | 0.451456 | [
"MIT"
] | Avarea/OOP-Advanced | SOLID/P02.Graphic_Editor/Square.cs | 414 | C# |
using System;
using System.Collections.Generic;
namespace BakkBenchmark.DotNet
{
public class Sort
{
public static void QuickSort(double[] list)
{
QuickSort(list, 0, list.Length);
}
private static void QuickSort(double[] list, int left, int right)
{
if (list == null || list.Length <= 1)
return;
if (left < right)
{
int pivotIdx = Partition(list, left, right);
//Console.WriteLine("MQS " + left + " " + right);
//DumpList(list);
QuickSort(list, left, pivotIdx - 1);
QuickSort(list, pivotIdx, right);
}
}
private static int Partition(double[] list, int left, int right)
{
int start = left;
double pivot = list[start];
left++;
right--;
while (true)
{
while (left <= right && list[left] <= pivot)
left++;
while (left <= right && list[right] > pivot)
right--;
if (left > right)
{
list[start] = list[left - 1];
list[left - 1] = pivot;
return left;
}
double temp = list[left];
list[left] = list[right];
list[right] = temp;
}
}
}
} | 24.8 | 73 | 0.417339 | [
"MIT"
] | stefan-schweiger/dotWasmBenchmark | dotWasmBenchmark.DotNet/Sort.cs | 1,488 | C# |
using System;
namespace Sekhmet.Serialization
{
public class AdviceRequestedEventArgs : EventArgs
{
public AdviceType Type { get; private set; }
public AdviceRequestedEventArgs(AdviceType type)
{
Type = type;
}
}
} | 19.428571 | 56 | 0.621324 | [
"MIT"
] | kimbirkelund/SekhmetSerialization | trunk/src/Sekhmet.Serialization/AdviceRequestedEventArgs.cs | 272 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Car_Rental_Sysytem.Properties
{
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Car_Rental_Sysytem.Properties.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;
}
}
}
}
| 38.791667 | 184 | 0.605084 | [
"MIT"
] | Tamim148/SWE_4202_Repository | LAB Task (EVEN) 4/Car Rental Sysytem/Properties/Resources.Designer.cs | 2,795 | C# |
/*
Copyright (C) 2018-2019 de4dot@gmail.com
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.
*/
#if !NO_ENCODER
using System;
using Iced.Intel;
using Xunit;
namespace Iced.UnitTests.Intel.EncoderTests {
public sealed class BlockEncoderTest64_jmp : BlockEncoderTest {
const int bitness = 64;
const ulong origRip = 0x8000;
const ulong newRip = 0x8000000000000000;
[Fact]
void Jmp_fwd() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 000000000000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x06,// jmp short 800000000000000Ah
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xEB, 0x02,// jmp short 800000000000000Ah
/*0008*/ 0xB0, 0x02,// mov al,2
/*000A*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0008,
0x000A,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_bwd() {
var originalData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xEB, 0xFB,// jmp short 0000000000008000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0xE9, 0xF4, 0xFF, 0xFF, 0xFF,// jmp near ptr 0000000000008000h
/*000C*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0x90,// nop
/*0001*/ 0xB0, 0x00,// mov al,0
/*0003*/ 0xEB, 0xFB,// jmp short 8000000000000000h
/*0005*/ 0xB0, 0x01,// mov al,1
/*0007*/ 0xEB, 0xF7,// jmp short 8000000000000000h
/*0009*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0001,
0x0003,
0x0005,
0x0007,
0x0009,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_short() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 000000000000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x0A,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xEB, 0x06,// jmp short 000000000000800Dh
/*0008*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x0008,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_near() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 000000000000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xE9, 0x06, 0xF0, 0xFF, 0xFF,// jmp near ptr 000000000000800Dh
/*0007*/ 0xB0, 0x01,// mov al,1
/*0009*/ 0xE9, 0xFF, 0xEF, 0xFF, 0xFF,// jmp near ptr 000000000000800Dh
/*000E*/ 0xB0, 0x02,// mov al,2
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0007,
0x0009,
0x000E,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.None;
EncodeBase(bitness, origRip, originalData, origRip + 0x1000, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_other_long() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 123456789ABCDE0Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x03, 0x00, 0x00, 0x00,// jmp near ptr 123456789ABCDE0Eh
/*000B*/ 0xB0, 0x02,// mov al,2
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xFF, 0x25, 0x10, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000018h]
/*0008*/ 0xB0, 0x01,// mov al,1
/*000A*/ 0xFF, 0x25, 0x10, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000020h]
/*0010*/ 0xB0, 0x02,// mov al,2
/*0012*/ 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC,
/*0018*/ 0x0D, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12,
/*0020*/ 0x0E, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12,
};
var expectedInstructionOffsets = new uint[] {
0x0000,
uint.MaxValue,
0x0008,
uint.MaxValue,
0x0010,
};
var expectedRelocInfos = new RelocInfo[] {
new RelocInfo(RelocKind.Offset64, 0x8000000000000018),
new RelocInfo(RelocKind.Offset64, 0x8000000000000020),
};
const BlockEncoderOptions options = BlockEncoderOptions.None;
const ulong origRip = 0x123456789ABCDE00;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
[Fact]
void Jmp_fwd_no_opt() {
var originalData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 000000000000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var newData = new byte[] {
/*0000*/ 0xB0, 0x00,// mov al,0
/*0002*/ 0xEB, 0x09,// jmp short 000000000000800Dh
/*0004*/ 0xB0, 0x01,// mov al,1
/*0006*/ 0xE9, 0x02, 0x00, 0x00, 0x00,// jmp near ptr 000000000000800Dh
/*000B*/ 0xB0, 0x02,// mov al,2
/*000D*/ 0x90,// nop
};
var expectedInstructionOffsets = new uint[] {
0x0000,
0x0002,
0x0004,
0x0006,
0x000B,
0x000D,
};
var expectedRelocInfos = Array.Empty<RelocInfo>();
const BlockEncoderOptions options = BlockEncoderOptions.DontFixBranches;
EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos);
}
}
}
#endif
| 34.823529 | 146 | 0.664371 | [
"MIT"
] | damageboy/iced | Iced.UnitTests/Intel/EncoderTests/BlockEncoderTest64_jmp.cs | 7,696 | C# |
// <auto-generated />
namespace Esso.Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class addISINIMORT : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(addISINIMORT));
string IMigrationMetadata.Id
{
get { return "201712060913033_addISINIMORT"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.233333 | 95 | 0.619339 | [
"MIT"
] | ismailllefe/ESOFT | Esso.Data/Migrations/201712060913033_addISINIMORT.Designer.cs | 817 | C# |
using System;
using System.Web.Http;
using WebChatBuilderService.Helpers;
using WebChatBuilderService.Icelib;
using WebChatBuilderService.Icelib.Availability;
using WebChatBuilderService.Icelib.Configurations;
using WebChatBuilderService.Icelib.Interactions;
using WebChatBuilderService.Icelib.People;
using WebChatBuilderService.Services;
namespace WebChatBuilderService.Controllers
{
[AuthorizeIpAddress]
public class ServicesController : ApiController
{
private Logging _logging;
private DateTime? _lastRestart = null;
[HttpGet]
public bool IsLicensed()
{
return LicenseService.ValidateLicense();
}
[HttpGet]
public string GetCicServer()
{
return IcelibInitializer.ActiveServer;
}
[HttpGet]
public int AgentsAvailable(int profileId)
{
return AgentAvailability.GetAgentAvailabilityByProfile(profileId);
}
[HttpGet]
public DateTime? GetLastScheduleUpdate()
{
return ScheduleConfigurations.LastUpdated;
}
//[HttpGet]
//public string GetLog()
//{
// var def = "...";
// try
// {
// var running = Logging.RunningLog;
// var log = !String.IsNullOrWhiteSpace(running) ? running : def;
// return log;
// }
// catch (Exception e)
// {
// _logging.TraceException(e,e.Message);
// }
// return def;
//}
[HttpGet]
public bool UpdateRefreshWatch()
{
WorkgroupPeople.RefreshWatch = true;
WorkgroupInteractions.RefreshWatch = true;
return true;
}
[HttpGet]
public bool RestartService()
{
try
{
var now = DateTime.Now;
if (_lastRestart.HasValue && _lastRestart.Value.AddMinutes(5) > now)
{
return false;
}
_lastRestart = now;
if (WcbService.IcelibInitializer != null)
{
WcbService.IcelibInitializer.Stop();
WcbService.IcelibInitializer.Start();
}
return true;
}
catch (Exception)
{
// ignored
}
return false;
}
}
}
| 26.083333 | 84 | 0.527157 | [
"MIT"
] | danielmcleod/WebchatBuilder_Open | WebchatBuilder/WebChatBuilderService/Controllers/ServicesController.cs | 2,506 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessRules.POC.ExternalData
{
public interface IExternalData<T, TResult>
{
TResult Get(T input);
}
}
| 15 | 46 | 0.721569 | [
"MIT"
] | SkillsFundingAgency/DC-Alpha-Azurefunctions-POC | src/BusinessRules.POC/ExternalData/IExternalData.cs | 257 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dotnet.Core.Simple.Services
{
public interface IEmailSender
{
Task SendEmailAsync(string email, string subject, string message);
}
}
| 20.153846 | 74 | 0.744275 | [
"MIT"
] | rzvdaniel/DotNetCoreAspBoilerplate | Services/IEmailSender.cs | 264 | C# |
using MiControl.Devices;
using MiLight;
using PlanckHome;
namespace Playground.Rooms
{
public static class LivingRoom
{
public static IMotionSensor MotionSensor => Devices.MotionLivingRoom;
public static IDimmableLightBulb MainLight => Devices.BulbA;
public static IDimmableLightBulb LampLight => Devices.BulbB;
public static DoubleKeySwitch LightSwitch => Devices.SwitchE;
}
} | 30.142857 | 77 | 0.741706 | [
"MIT"
] | ermac0/mi-home | Playground/Rooms/LivingRoom.cs | 422 | C# |
namespace RJCP.Diagnostics.Log.Constraints
{
using System;
using Dlt;
using Dlt.ControlArgs;
using NUnit.Framework;
[TestFixture(Category = "TraceReader.Constraints")]
public class DltConstraintExtensionsTest
{
[TestCase("ECUX", true)]
[TestCase("ECUx", false)]
public void DltEcuIdMatch(string constraint, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.GetResult();
Constraint c = new Constraint().DltEcuId(constraint);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[Test]
public void DltEcuIdNotPresent()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetApplicationId("APP1")
.GetResult();
Constraint c = new Constraint().DltEcuId(string.Empty);
Assert.That(c.Check(line), Is.False);
}
[Test]
public void DltEcuIdNull()
{
Assert.That(() => {
_ = new Constraint().DltEcuId(null);
}, Throws.TypeOf<ArgumentNullException>());
}
[TestCase("CTX1", true)]
[TestCase("CTX2", false)]
public void DltCtxIdMatch(string constraint, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.GetResult();
Constraint c = new Constraint().DltCtxId(constraint);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[Test]
public void DltCtxIdNotPresent()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECU1")
.GetResult();
Constraint c = new Constraint().DltCtxId(string.Empty);
Assert.That(c.Check(line), Is.False);
}
[Test]
public void DltCtxIdNull()
{
Assert.That(() => {
_ = new Constraint().DltCtxId(null);
}, Throws.TypeOf<ArgumentNullException>());
}
[TestCase("APP1", true)]
[TestCase("app2", false)]
public void DltAppIdMatch(string constraint, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.GetResult();
Constraint c = new Constraint().DltAppId(constraint);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[Test]
public void DltAppIdNotPresent()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECU1")
.GetResult();
Constraint c = new Constraint().DltAppId(string.Empty);
Assert.That(c.Check(line), Is.False);
}
[Test]
public void DltAppIdNull()
{
Assert.That(() => {
_ = new Constraint().DltAppId(null);
}, Throws.TypeOf<ArgumentNullException>());
}
[TestCase(DltType.LOG_FATAL, true)]
[TestCase(DltType.LOG_INFO, false)]
[TestCase(DltType.APP_TRACE_FUNCTION_IN, false)]
public void DltTypeMatch(DltType type, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.SetDltType(DltType.LOG_FATAL)
.GetResult();
Constraint c = new Constraint().DltType(type);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[TestCase(true, true)]
[TestCase(false, false)]
public void DltIsVerbose(bool isVerbose, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.SetDltType(DltType.LOG_FATAL)
.SetIsVerbose(true)
.GetResult();
Constraint c = new Constraint().DltIsVerbose(isVerbose);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[TestCase(true, false)]
[TestCase(false, true)]
public void DltIsVerboseControl(bool isVerbose, bool match)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.SetDltType(DltType.CONTROL_RESPONSE)
.SetControlPayload(new GetSoftwareVersionResponse(ControlResponse.StatusOk, "20w34.1"))
.GetResult();
Constraint c = new Constraint().DltIsVerbose(isVerbose);
Assert.That(c.Check(line), Is.EqualTo(match));
}
[Test]
public void DltIsControl()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.SetDltType(DltType.CONTROL_RESPONSE)
.SetControlPayload(new GetSoftwareVersionResponse(ControlResponse.StatusOk, "20w34.1"))
.GetResult();
Constraint c = new Constraint().DltIsControl();
Assert.That(c.Check(line), Is.True);
}
[Test]
public void DltIsControlFalse()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetEcuId("ECUX")
.SetApplicationId("APP1")
.SetContextId("CTX1")
.SetDltType(DltType.LOG_FATAL)
.SetIsVerbose(true)
.GetResult();
Constraint c = new Constraint().DltIsControl();
Assert.That(c.Check(line), Is.False);
}
[Test]
public void DltSessionIdMatchZero()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetSessionId(0)
.GetResult();
Constraint c = new Constraint().DltSessionId(0);
Assert.That(c.Check(line), Is.True);
}
[Test]
public void DltSessionIdNoMatch()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetSessionId(10)
.GetResult();
Constraint c = new Constraint().DltSessionId(0);
Assert.That(c.Check(line), Is.False);
}
[Test]
public void DltSessionIdNotPresent()
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetApplicationId("APP1")
.GetResult();
Constraint c = new Constraint().DltSessionId(0);
Assert.That(c.Check(line), Is.False);
}
[TestCase(0, 100, false)]
[TestCase(99, 100, false)]
[TestCase(100, 100, true)]
[TestCase(101, 100, true)]
public void Awake(int alive, int match, bool result)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetApplicationId("APP1")
.SetDeviceTimeStamp(alive * TimeSpan.TicksPerMillisecond)
.GetResult();
Constraint c = new Constraint().Awake(match);
Assert.That(c.Check(line), Is.EqualTo(result));
}
[Test]
public void AwakeNegative()
{
Assert.That(() => {
_ = new Constraint().Awake(-1);
}, Throws.TypeOf<ArgumentOutOfRangeException>());
}
[TestCase(0, 100, false)]
[TestCase(99, 100, false)]
[TestCase(100, 100, true)]
[TestCase(101, 100, true)]
public void AwakeTimeSpan(int alive, int match, bool result)
{
IDltLineBuilder builder = new DltLineBuilder();
DltTraceLineBase line = builder
.SetApplicationId("APP1")
.SetDeviceTimeStamp(alive * TimeSpan.TicksPerMillisecond)
.GetResult();
Constraint c = new Constraint().Awake(new TimeSpan(match * TimeSpan.TicksPerMillisecond));
Assert.That(c.Check(line), Is.EqualTo(result));
}
[Test]
public void AwakeNegativeTimeStamp()
{
Assert.That(() => {
_ = new Constraint().Awake(new TimeSpan(-10000));
}, Throws.TypeOf<ArgumentOutOfRangeException>());
}
[Test]
public void AwakeNegativeTimeStampLarge()
{
Assert.That(() => {
_ = new Constraint().Awake(new TimeSpan(int.MaxValue * TimeSpan.TicksPerMillisecond + 1));
}, Throws.TypeOf<ArgumentOutOfRangeException>());
}
}
}
| 34.708633 | 106 | 0.535392 | [
"MIT"
] | jcurl/RJCP.DLL.Log | TraceReader.Dlt/DltTraceReaderTest/Constraints/DltConstraintExtensionsTest.cs | 9,651 | C# |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Linq;
using XenAdmin.Actions.VMActions;
using XenAdmin.Controls;
using XenAPI;
namespace XenAdmin.Dialogs.VMDialogs
{
public partial class MoveVMDialog : XenDialogBase
{
private VM vm;
public MoveVMDialog(VM vm)
{
InitializeComponent();
this.vm = vm;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
EnableMoveButton();
var vdis = (from VBD vbd in vm.Connection.ResolveAll(vm.VBDs)
where vbd.GetIsOwner() && vbd.type != vbd_type.CD
let vdi = vm.Connection.Resolve(vbd.VDI)
where vdi != null
select vdi).ToArray();
srPicker1.PopulateAsync(SrPicker.SRPickerType.Move, vm.Connection,
vm.Home(), null, vdis);
}
private void EnableMoveButton()
{
buttonMove.Enabled = srPicker1.SR != null;
}
#region Control event handlers
private void srPicker1_DoubleClickOnRow(object sender, EventArgs e)
{
if (buttonMove.Enabled)
buttonMove.PerformClick();
}
private void buttonMove_Click(object sender, EventArgs e)
{
var action = new VMMoveAction(vm, srPicker1.SR, vm.GetStorageHost(false), vm.Name());
action.RunAsync();
Close();
}
private void srPicker1_SelectedIndexChanged(object sender, EventArgs e)
{
EnableMoveButton();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
#endregion
}
}
| 32.737374 | 98 | 0.621413 | [
"BSD-2-Clause"
] | CitrixChris/xenadmin | XenAdmin/Dialogs/VMDialogs/MoveVMDialog.cs | 3,243 | C# |
// Auto Generated Code
// Author roy
using System.Collections.Generic;
using System.Xml;
public class LevelUpConfig
{
public int Level;
public int PlayerLevelUpExp;
public string CardLevelUpRes;
public string CardDecomposeRes;
public static readonly string urlKey = "LevelUpConfig";
static Dictionary<int,LevelUpConfig> AllDatas;
public static void Parse(XmlNode node)
{
AllDatas = new Dictionary<int,LevelUpConfig>();
if (node != null)
{
XmlNodeList nodeList = node.ChildNodes;
if (nodeList != null && nodeList.Count > 0)
{
foreach (XmlElement el in nodeList)
{
LevelUpConfig config = new LevelUpConfig();
int.TryParse(el.GetAttribute ("Level"), out config.Level);
int.TryParse(el.GetAttribute ("PlayerLevelUpExp"), out config.PlayerLevelUpExp);
config.CardLevelUpRes = el.GetAttribute ("CardLevelUpRes");
config.CardDecomposeRes = el.GetAttribute ("CardDecomposeRes");
AllDatas.Add(config.Level, config);
}
}
}
}
public static LevelUpConfig Get(int key)
{
if (AllDatas != null && AllDatas.ContainsKey(key))
return AllDatas[key];
return null;
}
public static Dictionary<int,LevelUpConfig> Get()
{
return AllDatas;
}
}
| 22.127273 | 85 | 0.710764 | [
"MIT"
] | Roy0131/Excel2XmlAndCSFile | GenXmlTool/bin/client/configs/LevelUpConfig.cs | 1,219 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
namespace Contoso.GameNetCore.Proto.Features
{
public class ProtoRequestFeature : IProtoRequestFeature
{
public ProtoRequestFeature()
{
Headers = new HeaderDictionary();
Body = Stream.Null;
Protocol = string.Empty;
Scheme = string.Empty;
Method = string.Empty;
PathBase = string.Empty;
Path = string.Empty;
QueryString = string.Empty;
RawTarget = string.Empty;
}
public string Protocol { get; set; }
public string Scheme { get; set; }
public string Method { get; set; }
public string PathBase { get; set; }
public string Path { get; set; }
public string QueryString { get; set; }
public string RawTarget { get; set; }
public IHeaderDictionary Headers { get; set; }
public Stream Body { get; set; }
}
} | 34.424242 | 112 | 0.581866 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Proto/Proto/src/Features/HttpRequestFeature.cs | 1,136 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionResponse.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type AdministrativeUnitScopedRoleMembersCollectionResponse.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class AdministrativeUnitScopedRoleMembersCollectionResponse
{
/// <summary>
/// Gets or sets the <see cref="IAdministrativeUnitScopedRoleMembersCollectionPage"/> value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName ="value", Required = Newtonsoft.Json.Required.Default)]
public IAdministrativeUnitScopedRoleMembersCollectionPage Value { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData(ReadData = true)]
public IDictionary<string, object> AdditionalData { get; set; }
}
}
| 42.264706 | 153 | 0.631176 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/AdministrativeUnitScopedRoleMembersCollectionResponse.cs | 1,437 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SlicingWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DownloadController : ControllerBase
{
private string DataPath;
// for controlling the connection with Hololens application
public DownloadController(IConfiguration configuration)
{
var tmp = configuration as ConfigurationRoot;
var BasePath = configuration.GetValue<string>("OctoPrint:BasePath");
DataPath = Path.Combine(BasePath, "Meshes");
if (!Directory.Exists(DataPath))
Directory.CreateDirectory(DataPath);
}
// GET: api/<DownloadController>
[HttpGet]
public IEnumerable<string> Get()
{
return System.IO.Directory.GetFiles(DataPath, "*.zip");
}
[HttpGet("{filename}")]
public async Task<IActionResult> DownloadFile(string filename)
{
var filePath = Path.Combine(DataPath, filename + ".zip");
if (CheckFileAvailability(filename, filePath, out string message))
{
var memory = new MemoryStream();
using (var stream = new FileStream(filePath, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/zip", Path.GetFileName(filePath));
}
else
{
return StatusCode(404, message);
}
}
private bool CheckFileAvailability(string filename, string filepath, out string message)
{
message = "";
if (String.IsNullOrWhiteSpace(filename))
{
message = "filename not present";
return false;
}
if (!System.IO.File.Exists(filepath))
{
message = "The requested file was not found";
return false;
}
return true;
}
}
}
| 30.779221 | 116 | 0.572996 | [
"MIT"
] | FlorianJa/SlicerConnector | SlicingWebAPI/Controllers/DownloadController.cs | 2,372 | C# |
namespace Pitstop.WebApp.Commands;
public class RegisterCustomer : Command
{
public readonly string CustomerId;
public readonly string Name;
public readonly string Address;
public readonly string PostalCode;
public readonly string City;
public readonly string TelephoneNumber;
public readonly string EmailAddress;
public RegisterCustomer(Guid messageId, string customerId, string name, string address, string postalCode, string city,
string telephoneNumber, string emailAddress) : base(messageId)
{
CustomerId = customerId;
Name = name;
Address = address;
PostalCode = postalCode;
City = city;
TelephoneNumber = telephoneNumber;
EmailAddress = emailAddress;
}
} | 32 | 123 | 0.705729 | [
"Apache-2.0"
] | NileshGule/pitstop | src/WebApp/Commands/RegisterCustomer.cs | 770 | C# |
using Newtonsoft.Json.Linq;
using SolrExpress.Builder;
using SolrExpress.Configuration;
using SolrExpress.Options;
using SolrExpress.Search;
using SolrExpress.Search.Parameter;
using SolrExpress.Search.Parameter.Extension;
using SolrExpress.Search.Parameter.Validation;
using SolrExpress.Solr5.Search.Parameter;
using SolrExpress.Utility;
using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace SolrExpress.Solr5.UnitTests.Search.Parameter
{
public class SpatialFilterParameterTests
{
public static IEnumerable<object[]> Data
{
get
{
Action<ISpatialFilterParameter<TestDocument>> config1 = facet =>
{
facet.FieldExpression(q => q.Spatial).FunctionType(SpatialFunctionType.Geofilt).CenterPoint(new GeoCoordinate(-1.23456789M, -2.234567891M)).Distance(5.5M);
};
var expected1 = JObject.Parse(@"
{
params:{
fq:""{!geofilt sfield=_spatial_ pt=-1.23456789,-2.234567891 d=5.5}"",
}
}");
Action<ISpatialFilterParameter<TestDocument>> config2 = facet =>
{
facet.FieldExpression(q => q.Spatial).FunctionType(SpatialFunctionType.Bbox).CenterPoint(new GeoCoordinate(-1.23456789M, -2.234567891M)).Distance(5.5M);
};
var expected2 = JObject.Parse(@"
{
params:{
fq:""{!bbox sfield=_spatial_ pt=-1.23456789,-2.234567891 d=5.5}"",
}
}");
return new[]
{
new object[] { config1, expected1 },
new object[] { config2, expected2 }
};
}
}
/// <summary>
/// Where Using a SpatialFilterParameter instance
/// When Invoking method "Execute" using happy path configurations
/// What Create correct SOLR instructions
/// </summary>
[Theory]
[MemberData(nameof(Data))]
public void SpatialFilterParameterTheory001(Action<ISpatialFilterParameter<TestDocument>> config, JObject expectd)
{
// Arrange
var container = new JObject();
var solrOptions = new SolrExpressOptions();
var solrConnection = new FakeSolrConnection<TestDocument>();
var solrDocumentConfiguration = new SolrDocumentConfiguration<TestDocument>();
var expressionBuilder = new ExpressionBuilder<TestDocument>(solrOptions, solrDocumentConfiguration, solrConnection);
expressionBuilder.LoadDocument();
var parameter = (ISpatialFilterParameter<TestDocument>)new SpatialFilterParameter<TestDocument>(expressionBuilder);
config.Invoke(parameter);
// Act
((ISearchItemExecution<JObject>)parameter).Execute();
((ISearchItemExecution<JObject>)parameter).AddResultInContainer(container);
// Assert
Assert.Equal(expectd.ToString(), container.ToString());
}
/// <summary>
/// Where Using a SpatialFilterParameter instance
/// When Checking custom attributes of class
/// What Has FieldMustBeIndexedTrueAttribute
/// </summary>
[Fact]
public void SpatialFilterParameter001()
{
// Arrange / Act
var fieldMustBeIndexedTrueAttribute = typeof(SpatialFilterParameter<TestDocument>)
.GetTypeInfo()
.GetCustomAttribute<FieldMustBeIndexedTrueAttribute>(true);
// Assert
Assert.NotNull(fieldMustBeIndexedTrueAttribute);
}
}
}
| 38.474747 | 175 | 0.598845 | [
"MIT"
] | solr-express/solr-express | test/SolrExpress.Solr5.UnitTests/Search/Parameter/SpatialFilterParameterTests.cs | 3,811 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Auditing;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.Runtime.Validation;
using Et.Yhy.Authorization.Users;
using Et.Yhy.Complay;
namespace Et.Yhy.Users.Dto
{
[AutoMapTo(typeof(User))]
public class CreateUserDto : IShouldNormalize
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
public bool IsActive { get; set; }
public string[] RoleNames { get; set; }
[Required]
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
[DisableAuditing]
public string Password { get; set; }
public string WXid { get; set; }
public void Normalize()
{
if (RoleNames == null)
{
RoleNames = new string[0];
}
}
}
}
| 25.038462 | 58 | 0.619048 | [
"MIT"
] | ZtyMaster/ET.yhy | aspnet-core/src/Et.Yhy.Application/Users/Dto/CreateUserDto.cs | 1,302 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Elsa.Services;
namespace Elsa.Activities.Rebus.StartupTasks
{
public class CreateSubscriptions : IStartupTask
{
private readonly IServiceBusFactory _serviceBusFactory;
private readonly IEnumerable<Type> _messageTypes;
public CreateSubscriptions(IServiceBusFactory serviceBusFactory, IEnumerable<Type> messageTypes)
{
_serviceBusFactory = serviceBusFactory;
_messageTypes = messageTypes;
}
public int Order => 1000;
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
{
foreach (var messageType in _messageTypes)
{
var queueName = messageType.Name;
var bus = _serviceBusFactory.ConfigureServiceBus(new[] { messageType }, queueName);
await bus.Subscribe(messageType);
}
}
}
} | 31.375 | 104 | 0.665339 | [
"MIT"
] | AgnesGray/elsa-core | src/activities/Elsa.Activities.Rebus/StartupTasks/CreateSubscriptions.cs | 1,006 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace WP_Wrapper
{
class WpRequest : WebClient
{
private int _timeout;
public WpRequest(int TimeOutmiliseconds)
{
_timeout = TimeOutmiliseconds;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
request.Timeout = _timeout;
return request;
}
}
}
| 21.307692 | 64 | 0.599278 | [
"MIT"
] | EntropyDevelopments/WP-Wrapper | WpRequest.cs | 556 | C# |
//------------------------------------------------------------
// Game Framework v3.x
// Copyright © 2013-2018 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
using Icarus.GameFramework;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Icarus.UnityGameFramework.Editor.AssetBundleTools
{
internal sealed class SourceFolder
{
private static Texture s_CachedIcon = null;
private readonly List<SourceFolder> m_Folders;
private readonly List<SourceAsset> m_Assets;
public SourceFolder(string name, SourceFolder folder)
{
m_Folders = new List<SourceFolder>();
m_Assets = new List<SourceAsset>();
Name = name;
Folder = folder;
}
public string Name
{
get;
private set;
}
public SourceFolder Folder
{
get;
private set;
}
public string FromRootPath
{
get
{
return Folder == null ? string.Empty : (Folder.Folder == null ? Name : string.Format("{0}/{1}", Folder.FromRootPath, Name));
}
}
public int Depth
{
get
{
return Folder != null ? Folder.Depth + 1 : 0;
}
}
public static Texture Icon
{
get
{
if (s_CachedIcon == null)
{
s_CachedIcon = AssetDatabase.GetCachedIcon("Assets");
}
return s_CachedIcon;
}
}
public void Clear()
{
m_Folders.Clear();
m_Assets.Clear();
}
public SourceFolder[] GetFolders()
{
return m_Folders.ToArray();
}
public SourceFolder GetFolder(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Source folder name is invalid.");
}
foreach (SourceFolder folder in m_Folders)
{
if (folder.Name == name)
{
return folder;
}
}
return null;
}
public SourceFolder AddFolder(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Source folder name is invalid.");
}
SourceFolder folder = GetFolder(name);
if (folder != null)
{
throw new GameFrameworkException("Source folder is already exist.");
}
folder = new SourceFolder(name, this);
m_Folders.Add(folder);
return folder;
}
public SourceAsset[] GetAssets()
{
return m_Assets.ToArray();
}
public SourceAsset GetAsset(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Source asset name is invalid.");
}
foreach (SourceAsset asset in m_Assets)
{
if (asset.Name == name)
{
return asset;
}
}
return null;
}
public SourceAsset AddAsset(string guid, string path, string name)
{
if (string.IsNullOrEmpty(guid))
{
throw new GameFrameworkException("Source asset guid is invalid.");
}
if (string.IsNullOrEmpty(path))
{
throw new GameFrameworkException("Source asset path is invalid.");
}
if (string.IsNullOrEmpty(name))
{
throw new GameFrameworkException("Source asset name is invalid.");
}
SourceAsset asset = GetAsset(name);
if (asset != null)
{
throw new GameFrameworkException(string.Format("Source asset '{0}' is already exist.", name));
}
asset = new SourceAsset(guid, path, name, this);
m_Assets.Add(asset);
return asset;
}
}
}
| 25.589595 | 140 | 0.476169 | [
"MIT"
] | yika-aixi/IGameFrameWork | UnityGameFramework/Editor/AssetBundleEditor/SourceFolder.cs | 4,430 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(MVCMovie.Startup))]
namespace MVCMovie
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 17.733333 | 58 | 0.642857 | [
"MIT"
] | komitoff/Software-Technologies | MVC Movie Tutorial/MVCMovie/MVCMovie/Startup.cs | 268 | C# |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
namespace Facebook.Yoga
{
public enum YogaFlexDirection
{
Column,
ColumnReverse,
Row,
RowReverse,
}
}
| 19.555556 | 67 | 0.607955 | [
"MIT"
] | ReactUnity/core | Runtime/Yoga/YogaFlexDirection.cs | 352 | 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 guardduty-2017-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GuardDuty.Model
{
/// <summary>
/// Contains information about the remote IP address of the connection.
/// </summary>
public partial class RemoteIpDetails
{
private City _city;
private Country _country;
private GeoLocation _geoLocation;
private string _ipAddressV4;
private Organization _organization;
/// <summary>
/// Gets and sets the property City.
/// <para>
/// The city information of the remote IP address.
/// </para>
/// </summary>
public City City
{
get { return this._city; }
set { this._city = value; }
}
// Check to see if City property is set
internal bool IsSetCity()
{
return this._city != null;
}
/// <summary>
/// Gets and sets the property Country.
/// <para>
/// The country code of the remote IP address.
/// </para>
/// </summary>
public Country Country
{
get { return this._country; }
set { this._country = value; }
}
// Check to see if Country property is set
internal bool IsSetCountry()
{
return this._country != null;
}
/// <summary>
/// Gets and sets the property GeoLocation.
/// <para>
/// The location information of the remote IP address.
/// </para>
/// </summary>
public GeoLocation GeoLocation
{
get { return this._geoLocation; }
set { this._geoLocation = value; }
}
// Check to see if GeoLocation property is set
internal bool IsSetGeoLocation()
{
return this._geoLocation != null;
}
/// <summary>
/// Gets and sets the property IpAddressV4.
/// <para>
/// The IPv4 remote address of the connection.
/// </para>
/// </summary>
public string IpAddressV4
{
get { return this._ipAddressV4; }
set { this._ipAddressV4 = value; }
}
// Check to see if IpAddressV4 property is set
internal bool IsSetIpAddressV4()
{
return this._ipAddressV4 != null;
}
/// <summary>
/// Gets and sets the property Organization.
/// <para>
/// The ISP organization information of the remote IP address.
/// </para>
/// </summary>
public Organization Organization
{
get { return this._organization; }
set { this._organization = value; }
}
// Check to see if Organization property is set
internal bool IsSetOrganization()
{
return this._organization != null;
}
}
} | 29.218045 | 108 | 0.550437 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/GuardDuty/Generated/Model/RemoteIpDetails.cs | 3,886 | C# |
#nullable enable
using System;
using System.Dynamic;
using DevToys.Core;
using DevToys.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
namespace DevToys.Helpers.JsonYaml
{
internal static class YamlHelper
{
/// <summary>
/// Detects whether the given string is a valid YAML or not.
/// </summary>
internal static bool IsValidYaml(string? input)
{
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
input = input!.Trim();
try
{
object? result = new DeserializerBuilder().Build().Deserialize<object>(input);
return result is not null and not string;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Convert a Json string to Yaml
/// </summary>
internal static string? ConvertFromJson(string? input, Indentation indentationMode)
{
if (string.IsNullOrWhiteSpace(input))
{
return string.Empty;
}
try
{
object? jsonObject = null;
var token = JToken.Parse(input!);
if (token is null)
{
return string.Empty;
}
JsonSerializerSettings defaultJsonSerializerSettings = new()
{
FloatParseHandling = FloatParseHandling.Decimal
};
if (token is JArray)
{
jsonObject = JsonConvert.DeserializeObject<ExpandoObject[]>(input!, defaultJsonSerializerSettings);
}
else
{
jsonObject = JsonConvert.DeserializeObject<ExpandoObject>(input!, defaultJsonSerializerSettings);
}
if (jsonObject is not null and not string)
{
int indent = 0;
indent = indentationMode switch
{
Indentation.TwoSpaces => 2,
Indentation.FourSpaces => 4,
_ => throw new NotSupportedException(),
};
var serializer
= Serializer.FromValueSerializer(
new SerializerBuilder().BuildValueSerializer(),
EmitterSettings.Default.WithBestIndent(indent).WithIndentedSequences());
string? yaml = serializer.Serialize(jsonObject);
if (string.IsNullOrWhiteSpace(yaml))
{
return string.Empty;
}
return yaml;
}
return string.Empty;
}
catch (JsonReaderException ex)
{
return ex.Message;
}
catch (Exception ex)
{
Logger.LogFault("Yaml to Json Converter", ex);
return string.Empty;
}
}
}
}
| 29.572727 | 119 | 0.471565 | [
"MIT"
] | IHA114/DevToys | src/dev/impl/DevToys/Helpers/JsonYaml/YamlHelper.cs | 3,255 | C# |
// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;
namespace ExceptionFilters
{
class ReflectionThrowingFilter
{
static void Main()
{
Foo();
}
static void Foo()
{
try
{
Bar();
}
catch (Exception e) when (e.Message[10] == '!')
{
}
}
static void Bar()
{
throw new Exception("Bang!");
}
}
}
| 19.933333 | 147 | 0.463211 | [
"Apache-2.0"
] | 23dproject/DemoCode | Abusing CSharp/Code/ExceptionFilters/ReflectionThrowingFilter.cs | 600 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using UnitsNet.NumberExtensions.NumberToLinearDensity;
using Xunit;
namespace UnitsNet.Tests
{
public class NumberToLinearDensityExtensionsTests
{
[Fact]
public void NumberToGramsPerCentimeterTest() =>
Assert.Equal(LinearDensity.FromGramsPerCentimeter(2), 2.GramsPerCentimeter());
[Fact]
public void NumberToGramsPerMeterTest() =>
Assert.Equal(LinearDensity.FromGramsPerMeter(2), 2.GramsPerMeter());
[Fact]
public void NumberToGramsPerMillimeterTest() =>
Assert.Equal(LinearDensity.FromGramsPerMillimeter(2), 2.GramsPerMillimeter());
[Fact]
public void NumberToKilogramsPerCentimeterTest() =>
Assert.Equal(LinearDensity.FromKilogramsPerCentimeter(2), 2.KilogramsPerCentimeter());
[Fact]
public void NumberToKilogramsPerMeterTest() =>
Assert.Equal(LinearDensity.FromKilogramsPerMeter(2), 2.KilogramsPerMeter());
[Fact]
public void NumberToKilogramsPerMillimeterTest() =>
Assert.Equal(LinearDensity.FromKilogramsPerMillimeter(2), 2.KilogramsPerMillimeter());
[Fact]
public void NumberToMicrogramsPerCentimeterTest() =>
Assert.Equal(LinearDensity.FromMicrogramsPerCentimeter(2), 2.MicrogramsPerCentimeter());
[Fact]
public void NumberToMicrogramsPerMeterTest() =>
Assert.Equal(LinearDensity.FromMicrogramsPerMeter(2), 2.MicrogramsPerMeter());
[Fact]
public void NumberToMicrogramsPerMillimeterTest() =>
Assert.Equal(LinearDensity.FromMicrogramsPerMillimeter(2), 2.MicrogramsPerMillimeter());
[Fact]
public void NumberToMilligramsPerCentimeterTest() =>
Assert.Equal(LinearDensity.FromMilligramsPerCentimeter(2), 2.MilligramsPerCentimeter());
[Fact]
public void NumberToMilligramsPerMeterTest() =>
Assert.Equal(LinearDensity.FromMilligramsPerMeter(2), 2.MilligramsPerMeter());
[Fact]
public void NumberToMilligramsPerMillimeterTest() =>
Assert.Equal(LinearDensity.FromMilligramsPerMillimeter(2), 2.MilligramsPerMillimeter());
[Fact]
public void NumberToPoundsPerFootTest() =>
Assert.Equal(LinearDensity.FromPoundsPerFoot(2), 2.PoundsPerFoot());
[Fact]
public void NumberToPoundsPerInchTest() =>
Assert.Equal(LinearDensity.FromPoundsPerInch(2), 2.PoundsPerInch());
}
}
| 40.705882 | 125 | 0.666185 | [
"MIT-feh"
] | AIKICo/UnitsNet | UnitsNet.NumberExtensions.Tests/GeneratedCode/NumberToLinearDensityExtensionsTest.g.cs | 3,460 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using TinyJson;
using System.Linq;
public class WellOfDepthsScores : MonoBehaviour {
public int interval = 60;
public Text side;
private float time;
void Start() {
StartCoroutine(Fetch());
}
void Update() {
time += Time.deltaTime;
if (time > interval) {
time = 0;
StartCoroutine(Fetch());
}
}
private IEnumerator ReportToServer() {
ResourceController res = FindObjectOfType<ResourceController>();
PlayerController pc = FindObjectOfType<PlayerController>();
UnityWebRequest www = UnityWebRequest.Get("https://game.jdev.com.es/teddor/sprl?token=" + PlayerPrefs.GetString("teddor.token") + "&bstars=" + res.bstars + "&lvl=" + pc.stats.level + "&xp=" + (int) pc.stats.xp);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success) {
Debug.LogError("SPRL Report failed\n\n" + www.error);
yield break;
}
}
public IEnumerator Fetch() {
UnityWebRequest www = UnityWebRequest.Get("https://game.jdev.com.es/teddor/topscores?token=" + PlayerPrefs.GetString("teddor.token"));
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success) yield break;
yield return ReportToServer();
Dictionary<string, int> scores = www.downloadHandler.text.FromJson<Dictionary<string, int>>();
string[] keys = scores.Keys.ToArray();
side.text = "<color=yellow>1. ";
try {
side.text += keys[0] + " (";
side.text += scores[keys[0]] + ")";
} catch(System.Exception) {}
side.text += "</color>\n<color=orange>2. ";
try {
side.text += keys[1] + " (";
side.text += scores[keys[1]] + ")";
} catch (System.Exception) { }
side.text += "</color>\n3. ";
try {
side.text += keys[2] + " (";
side.text += scores[keys[2]] + ")";
} catch (System.Exception) { }
side.text += "\n4. ";
try {
side.text += keys[4] + " (";
side.text += scores[keys[4]] + ")";
} catch (System.Exception) { }
side.text += "\n5. ";
try {
side.text += keys[5] + " (";
side.text += scores[keys[5]] + ")";
} catch (System.Exception) { }
side.text += "\n\n<color>" + PlayerPrefs.GetInt("teddor.wod.score", 0) + " pts.</color>";
}
}
| 31.698795 | 219 | 0.555302 | [
"MIT"
] | JanCraft/teddor | Assets/Scripts/WellOfDepthsScores.cs | 2,631 | 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("MechanicalObject.Sandbox.DataSerializer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MechanicalObject.Sandbox.DataSerializer")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1238e7f8-9602-423f-8f0e-bae626d267f3")]
// 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.216216 | 84 | 0.751895 | [
"Apache-2.0"
] | mechanicalobject/sandbox | MechanicalObject.Sandbox.DataSerializer/MechanicalObject.Sandbox.DataSerializer/Properties/AssemblyInfo.cs | 1,454 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the organizations-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Organizations.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Organizations.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListAccountsForParent operation
/// </summary>
public class ListAccountsForParentResponseUnmarshaller : 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)
{
ListAccountsForParentResponse response = new ListAccountsForParentResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Accounts", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Account, AccountUnmarshaller>(AccountUnmarshaller.Instance);
response.Accounts = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = 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("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("AWSOrganizationsNotInUseException"))
{
return AWSOrganizationsNotInUseExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException"))
{
return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ParentNotFoundException"))
{
return ParentNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException"))
{
return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonOrganizationsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListAccountsForParentResponseUnmarshaller _instance = new ListAccountsForParentResponseUnmarshaller();
internal static ListAccountsForParentResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListAccountsForParentResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.830882 | 196 | 0.638601 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Organizations/Generated/Model/Internal/MarshallTransformations/ListAccountsForParentResponseUnmarshaller.cs | 5,689 | C# |
using System;
using System.Runtime.InteropServices;
namespace AM.E3dc.Rscp.Data.Values
{
/// <summary>
/// Value object used to transport messages with an <see cref="RscpErrorCode"/> payload.
/// </summary>
public sealed class RscpError : RscpValue<RscpErrorCode>
{
/// <summary>
/// Initializes a new instance of the <see cref="RscpError"/> class.
/// </summary>
/// <param name="tag">The tag of the value object.</param>
/// <param name="value">The value of the object.</param>
public RscpError(RscpTag tag, RscpErrorCode value)
: base(tag, 4, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RscpError"/> class.
/// </summary>
/// <param name="tag">The tag of the value object.</param>
/// <param name="data">The span containing the value of this object.</param>
internal RscpError(RscpTag tag, ReadOnlySpan<byte> data)
: base(tag, 4, MemoryMarshal.Read<RscpErrorCode>(data))
{
}
/// <inheritdoc />
public override RscpDataType DataType => RscpDataType.Error;
private protected override void OnWrite(Span<byte> destination)
{
var value = this.Value;
MemoryMarshal.Write(destination, ref value);
}
}
}
| 33.414634 | 92 | 0.593431 | [
"Apache-2.0"
] | Spontifixus/am-e3dc | Source/AM.E3dc.Rscp.Data/Values/RscpError.cs | 1,372 | C# |
using System;
using System.Windows;
using EventsDemo.FastClock;
namespace EventsDemo.FastClockWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
TheFastClock _fastClock = TheFastClock.Instance;
public MainWindow()
{
InitializeComponent();
}
private void MetroWindow_Initialized(object sender, EventArgs e)
{
DatePickerDate.SelectedDate = DateTime.Today;
TextBoxTime.Text = DateTime.Now.ToShortTimeString();
}
private void ButtonSetTime_Click(object sender, RoutedEventArgs e)
{
}
private void SetFastClockStartDateAndTime()
{
}
private void FastClockOneMinuteIsOver(object sender, DateTime fastClockTime)
{
TextBlockTime.Text = fastClockTime.ToShortTimeString();
}
private void CheckBoxClockRuns_Click(object sender, RoutedEventArgs e)
{
_fastClock.OneMinuteIsOver += FastClockOneMinuteIsOver;
_fastClock.Factor = Convert.ToInt32(TextBoxFactor.Text);
if (!_fastClock.IsRunning)
{
_fastClock.IsRunning = true;
}
else
{
_fastClock.IsRunning = false;
}
}
private void ButtonCreateView_Click(object sender, RoutedEventArgs e)
{
DigitalClock digitalClock = new DigitalClock();
digitalClock.Owner = this;
digitalClock.Show();
}
}
}
| 26.557377 | 84 | 0.588272 | [
"MIT"
] | mflieger/csharp_samples_events_fastclock-template | source/FastClock/EventsDemo.FastClockWpf/MainWindow.xaml.cs | 1,622 | C# |
using Grace.DependencyInjection;
using Grace.Tests.Classes.Simple;
using Xunit;
namespace Grace.Tests.DependencyInjection.ScopeExtensions
{
// ReSharper disable once InconsistentNaming
public class IExportLocatorScopeExtensionsTests
{
[Fact]
public void IExportLocatorScopeExtensions_GetInjectionScope()
{
var container = new DependencyInjectionContainer();
using (var lifetimeScope = container.BeginLifetimeScope())
{
Assert.NotNull(lifetimeScope);
Assert.Same(container, lifetimeScope.GetInjectionScope());
}
}
public class ImportPropertyClass
{
public IBasicService BasicService { get; set; }
}
[Fact]
public void IExportLocatorScopeExtensions_WhatDoIHave()
{
var container = new DependencyInjectionContainer();
container.Configure(c =>
{
c.Export<BasicService>().As<IBasicService>().Lifestyle.Singleton();
c.Export<DependentService<IBasicService>>().As<IDependentService<IBasicService>>();
c.Export<ImportPropertyClass>().ImportProperty(i => i.BasicService);
c.Export<MultipleService1>().AsKeyed<IMultipleService>(1);
});
using (var child = container.CreateChildScope())
{
var whatDoIHave = child.WhatDoIHave(consider: s => true);
Assert.False(string.IsNullOrEmpty(whatDoIHave));
Assert.Contains("Singleton", whatDoIHave);
Assert.Contains("Member Name", whatDoIHave);
Assert.Contains( "As Keyed Type: 1", whatDoIHave);
}
}
}
}
| 32.833333 | 99 | 0.599549 | [
"MIT"
] | Lex45x/Grace | tests/Grace.Tests/DependencyInjection/ScopeExtensions/IExportLocatorScopeExtensionsTests.cs | 1,775 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using OpenQA.Selenium;
namespace DevToolsX.Testing.Selenium
{
public class RadioGroup : CommandsBase
{
public RadioGroup(Browser browser, Element parent, string locator, string tagKind, string groupName, ImmutableArray<Element> items)
: base(browser)
{
this.Parent = parent;
this.Locator = locator;
this.TagKind = tagKind;
this.GroupName = groupName;
this.Items = items;
}
public bool Exists
{
get { return this.Items.Length > 0; }
}
public Element Parent { get; }
public string Locator { get; }
public string TagKind { get; }
public string GroupName { get; }
public ImmutableArray<Element> Items { get; }
public string LogName
{
get { return string.Format("{0} '{1}'", this.TagKind ?? "Radio group", this.Locator); }
}
public string Value
{
get
{
string radioValue = null;
this.TryGetRadioGroupValue(out radioValue);
return radioValue;
}
}
public bool IsSelected
{
get { return this.TryGetRadioGroupValue(out string value); }
}
public bool ShouldHaveValue(string value, string message = null, Microsoft.Extensions.Logging.LogLevel logLevel = Microsoft.Extensions.Logging.LogLevel.Information)
{
string radioValue = null;
string successMessage = "Radio group '{0}' is set to '{1}'.";
string failureMessage = null;
if (this.TryGetRadioGroupValue(out radioValue))
{
failureMessage = message ?? "Radio group '{0}' should have been set to '{1}' but was set to '{2}'.";
}
else
{
failureMessage = message ?? "Radio group '{0}' should have been set to '{1}' but had no selection.";
}
bool success = value == radioValue;
this.Browser.AssertSuccess(success, successMessage, failureMessage, this.GroupName, value, radioValue);
return success;
}
public bool ShouldNotBeSelected(string message = null, Microsoft.Extensions.Logging.LogLevel logLevel = Microsoft.Extensions.Logging.LogLevel.Information)
{
string radioValue = null;
bool selected = this.TryGetRadioGroupValue(out radioValue);
string successMessage = "Radio group '{0}' has no selection.";
string failureMessage = message ?? "Radio group '{0}' should not have had selection but was set to '{1}'.";
return this.Browser.AssertSuccess(selected, successMessage, failureMessage, this.GroupName, radioValue);
}
public void Select(string value)
{
Element radioButton = this.GetRadioButtonWithValue(value);
if (radioButton != null) radioButton.Select();
}
private bool TryGetRadioGroupValue(out string value)
{
bool selected = false;
value = null;
foreach (var element in this.Items)
{
if (element.IsSelected)
{
selected = true;
value = element.GetAttribute("value");
break;
}
}
return selected;
}
private Element GetRadioButtonWithValue(string value)
{
foreach (var element in this.Items)
{
if (element.GetAttribute("value") == value)
{
return element;
}
}
return null;
}
}
}
| 33.713043 | 172 | 0.551973 | [
"Apache-2.0"
] | balazssimon/devtools-cs | Src/Main/DevToolsX.Testing.Selenium/Commands/RadioGroup.cs | 3,879 | C# |
using System.Threading.Tasks;
using AllReady.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace AllReady.Areas.Admin.Features.Campaigns
{
public class DeleteCampaignCommandHandler : AsyncRequestHandler<DeleteCampaignCommand>
{
private AllReadyContext _context;
public DeleteCampaignCommandHandler(AllReadyContext context)
{
_context = context;
}
protected override async Task HandleCore(DeleteCampaignCommand message)
{
var campaign = await _context.Campaigns.SingleOrDefaultAsync(c => c.Id == message.CampaignId).ConfigureAwait(false);
if (campaign != null)
{
_context.Campaigns.Remove(campaign);
await _context.SaveChangesAsync().ConfigureAwait(false);
}
}
}
}
| 29.206897 | 128 | 0.664699 | [
"MIT"
] | digitaldrummerj-ionic/allReady | AllReadyApp/Web-App/AllReady/Areas/Admin/Features/Campaigns/DeleteCampaignCommandHandler.cs | 849 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SumNumbersASPWebForms
{
public partial class About
{
}
}
| 24.444444 | 81 | 0.415909 | [
"MIT"
] | primas23/Homewoks | ASP.NET-Web-Forms/01. Introduction-to-ASP.NET/SumNumbersASPWebForms/About.aspx.designer.cs | 442 | C# |
using System;
using System.Globalization;
using Bridge.Test.NUnit;
namespace Bridge.ClientTest.Batch3.BridgeIssues
{
[Category(Constants.MODULE_ISSUES)]
[TestFixture(TestNameFormat = "#2137 - {0}")]
public class Bridge2137
{
public static object E1 { get; } = new string('E', 3);
public static object E2 { get; } = E1 + new string('E', 3);
public object E3 { get; } = "test" + E1;
public object E4 { get; }
public Bridge2137()
{
this.E4 = "_" + E3;
}
[Test]
public static void TestPropertiesWithNonPrimitiveInitializers()
{
var c = new Bridge2137();
Assert.AreEqual("EEE", E1);
Assert.AreEqual("EEEEEE", E2);
Assert.AreEqual("testEEE", c.E3);
Assert.AreEqual("_testEEE", c.E4);
}
}
} | 27.967742 | 71 | 0.557093 | [
"Apache-2.0"
] | AndreyZM/Bridge | Tests/Batch3/BridgeIssues/2100/N2137.cs | 869 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.Caching.Memory;
namespace Microsoft.AspNetCore.ResponseCaching;
internal class MemoryResponseCache : IResponseCache
{
private readonly IMemoryCache _cache;
internal MemoryResponseCache(IMemoryCache cache)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
public IResponseCacheEntry? Get(string key)
{
var entry = _cache.Get(key);
if (entry is MemoryCachedResponse memoryCachedResponse)
{
return new CachedResponse
{
Created = memoryCachedResponse.Created,
StatusCode = memoryCachedResponse.StatusCode,
Headers = memoryCachedResponse.Headers,
Body = memoryCachedResponse.Body
};
}
else
{
return entry as IResponseCacheEntry;
}
}
public void Set(string key, IResponseCacheEntry entry, TimeSpan validFor)
{
if (entry is CachedResponse cachedResponse)
{
_cache.Set(
key,
new MemoryCachedResponse
{
Created = cachedResponse.Created,
StatusCode = cachedResponse.StatusCode,
Headers = cachedResponse.Headers,
Body = cachedResponse.Body
},
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = validFor,
Size = CacheEntryHelpers.EstimateCachedResponseSize(cachedResponse)
});
}
else
{
_cache.Set(
key,
entry,
new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = validFor,
Size = CacheEntryHelpers.EstimateCachedVaryByRulesySize(entry as CachedVaryByRules)
});
}
}
}
| 30.57971 | 103 | 0.565403 | [
"MIT"
] | 3ejki/aspnetcore | src/Middleware/ResponseCaching/src/MemoryResponseCache.cs | 2,110 | C# |
using SDFRendering;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NoneTaskHandle : ITaskHandle
{
public void Complete()
{
return;
}
public bool HasFinished()
{
return true;
}
}
| 14.777778 | 41 | 0.657895 | [
"BSD-3-Clause"
] | Joeoc2001/IsosurfaceRenderingEngine | Assets/Scripts/Rendering/PriorGenTaskHandles/NoneTaskHandle.cs | 268 | C# |
using Avalonia.Threading;
using AvaloniaEdit.Document;
using AvaloniaEdit.Text;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace MegaCom.UI.ViewModels
{
public class DebugViewModel : ViewModelBase, INotifyPropertyChanged
{
private ComHost m_host;
[Reactive]
public TextDocument Document { get; set; }
public DebugViewModel(ComHost host)
{
this.m_host = host;
this.Document = new TextDocument();
Log.LogWritten += s => Append($"{DateTime.Now} [HOST] {s}\n");
Document.UndoStack.SizeLimit = 1;
DebugProc();
}
private async void DebugProc()
{
while (true)
{
var debug = await m_host.recvFrame(ComType.DEBUG);
var msg = Encoding.UTF8.GetString(debug.data.ToArray());
Append($"{DateTime.Now} [MC] {msg}\n");
}
}
private void Append(string v)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
Document.Insert(Document.TextLength, v);
if (Document.LineCount > 1024)
{
var line = Document.Lines[0];
Document.Remove(line.Offset, line.Length + 1);
}
});
Updated();
}
public override string Name => "Debug";
public event Action Updated = delegate { };
}
}
| 25.966667 | 74 | 0.539153 | [
"MIT"
] | yatli/Camelotia | src/MegaCom.UI/ViewModels/DebugViewModel.cs | 1,560 | C# |
namespace ClassLib069
{
public class Class009
{
public static string Property => "ClassLib069";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib069/Class009.cs | 120 | 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;
using System.Threading;
internal delegate T GenDelegate<T>(T p1, out T p2);
internal class Foo
{
static public T Function<T>(T i, out T j)
{
j = i;
return i;
}
}
internal class Test_Delegate027
{
public static int Main()
{
int i, j;
GenDelegate<int> MyDelegate = new GenDelegate<int>(Foo.Function<int>);
i = MyDelegate(10, out j);
if ((i != 10) || (j != 10))
{
Console.WriteLine("Failed Sync Invokation");
return 1;
}
Console.WriteLine("Test Passes");
return 100;
}
}
| 20.378378 | 78 | 0.582228 | [
"MIT"
] | 333fred/runtime | src/tests/JIT/Generics/Instantiation/delegates/Delegate027.cs | 754 | C# |
#if !NET451
using System;
namespace RockLib.Messaging.DependencyInjection
{
/// <summary>
/// Represents a method that creates an <see cref="ISender"/>.
/// </summary>
/// <param name="serviceProvider">
/// The <see cref="IServiceProvider"/> that resolves dependencies necessary for the creation of the
/// <see cref="ISender"/>.
/// </param>
/// <returns>An <see cref="ISender"/>.</returns>
public delegate ISender SenderRegistration(IServiceProvider serviceProvider);
/// <summary>
/// Represents a method that creates an <see cref="ITransactionalSender"/>.
/// </summary>
/// <param name="serviceProvider">
/// The <see cref="IServiceProvider"/> that resolves dependencies necessary for the creation of the
/// <see cref="ITransactionalSender"/>.
/// </param>
/// <returns>An <see cref="ITransactionalSender"/>.</returns>
public delegate ITransactionalSender TransactionalSenderRegistration(IServiceProvider serviceProvider);
/// <summary>
/// Represents a method that creates an <see cref="IReceiver"/>.
/// </summary>
/// <param name="serviceProvider">
/// The <see cref="IServiceProvider"/> that resolves dependencies necessary for the creation of the
/// <see cref="IReceiver"/>.
/// </param>
/// <returns>An <see cref="IReceiver"/>.</returns>
public delegate IReceiver ReceiverRegistration(IServiceProvider serviceProvider);
}
#endif
| 39.297297 | 107 | 0.674003 | [
"MIT"
] | RockLib/RockLib.Messaging | RockLib.Messaging/DependencyInjection/RegistrationDelegates.cs | 1,456 | C# |
using Content.Server.Interfaces.GameObjects.Components.Items;
using Content.Shared.Audio;
using Content.Shared.GameObjects.Components.Rotation;
using Content.Shared.GameObjects.EntitySystems;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Shared.Interfaces.GameObjects;
namespace Content.Server.GameObjects.EntitySystems
{
[UsedImplicitly]
public class StandingStateSystem : SharedStandingStateSystem
{
protected override bool OnDown(IEntity entity, bool playSound = true, bool dropItems = true, bool force = false)
{
if (!entity.TryGetComponent(out AppearanceComponent appearance))
{
return false;
}
var newState = RotationState.Horizontal;
appearance.TryGetData<RotationState>(RotationVisuals.RotationState, out var oldState);
if (newState != oldState)
{
appearance.SetData(RotationVisuals.RotationState, newState);
}
if (playSound)
{
var file = AudioHelpers.GetRandomFileFromSoundCollection("bodyfall");
Get<AudioSystem>().PlayFromEntity(file, entity, AudioHelpers.WithVariation(0.25f));
}
return true;
}
protected override bool OnStand(IEntity entity)
{
if (!entity.TryGetComponent(out AppearanceComponent appearance)) return false;
appearance.TryGetData<RotationState>(RotationVisuals.RotationState, out var oldState);
var newState = RotationState.Vertical;
if (newState == oldState) return false;
appearance.SetData(RotationVisuals.RotationState, newState);
return true;
}
public override void DropAllItemsInHands(IEntity entity, bool doMobChecks = true)
{
base.DropAllItemsInHands(entity, doMobChecks);
if (!entity.TryGetComponent(out IHandsComponent hands)) return;
foreach (var heldItem in hands.GetAllHeldItems())
{
hands.Drop(heldItem.Owner, doMobChecks);
}
}
}
}
| 33.454545 | 120 | 0.649457 | [
"MIT"
] | ALMv1/space-station-14 | Content.Server/GameObjects/EntitySystems/StandingStateSystem.cs | 2,210 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#pragma warning disable 436 // The type 'type' in 'assembly' conflicts with the imported type 'type2' in 'assembly' (due to XenkoVersion being duplicated)
using Xenko.Core.Annotations;
using Xenko.Metrics;
namespace Xenko.GameStudio
{
public static class XenkoGameStudio
{
[NotNull]
public static string CopyrightText1 => "© 2018 Xenko contributors";
[NotNull]
public static string CopyrightText2 => "© 2011-2018 Silicon Studio Corp.";
[NotNull]
public static string EditorName => $"Xenko Game Studio {EditorVersion}";
[NotNull]
public static string EditorVersion => XenkoVersion.NuGetVersion;
[NotNull]
public static string EditorVersionWithMetadata => XenkoVersion.NuGetVersion + XenkoVersion.BuildMetadata;
public static string EditorVersionMajor => new System.Version(XenkoVersion.PublicVersion).ToString(2);
[NotNull]
public static string AnswersUrl => "http://answers.xenko.com/";
[NotNull]
public static string DocumentationUrl => $"https://doc.xenko.com/{EditorVersionMajor}/";
[NotNull]
public static string ForumsUrl => "https://forums.xenko.com/";
[NotNull]
public static string ReportIssueUrl => "https://github.com/xenko3d/xenko/issues/";
public static MetricsClient MetricsClient;
}
}
| 36.409091 | 154 | 0.69226 | [
"MIT"
] | Beefr/xenko | sources/editor/Xenko.GameStudio/XenkoGameStudio.cs | 1,604 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace EliteJournalReader.Events
{
public class CancelDropshipEvent : JournalEvent<CancelDropshipEvent.CancelDropshipEventArgs>
{
public CancelDropshipEvent() : base("CancelDropship") { }
public class CancelDropshipEventArgs : JournalEventArgs
{
public long Refund { get; set; }
}
}
}
| 24.5 | 96 | 0.714286 | [
"MIT"
] | ajhewett/streamdeck-elite | EliteJournalReader/Events/CancelDropshipEvent.cs | 490 | C# |
namespace Divstack.Company.Estimation.Tool.Users.Infrastructure.Identity.Users.Seeder;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
internal sealed class UsersSeederInitializer : IHostedService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
public UsersSeederInitializer(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var serviceScope = _serviceScopeFactory.CreateScope();
var usersSeeder = serviceScope.ServiceProvider.GetRequiredService<IUsersSeeder>();
await usersSeeder.SeedAdminUserAsync();
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
| 29.866667 | 90 | 0.777902 | [
"MIT"
] | kamilbaczek/estimation-tool | Src/Modules/Users/Divstack.Company.Estimation.Tool.Users.Infrastructure/Identity/Users/Seeder/UsersSeederInitializer.cs | 898 | C# |
namespace Maxstupo.YdlUi.Forms {
partial class FormPlaylistRangeEditor {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.btnAdd = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOkay = new System.Windows.Forms.Button();
this.btnAddRange = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.lbxPlaylistItems = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAdd.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnAdd.Location = new System.Drawing.Point(12, 204);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 1;
this.btnAdd.Text = "&Add...";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(427, 204);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "&Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOkay
//
this.btnOkay.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOkay.Location = new System.Drawing.Point(346, 204);
this.btnOkay.Name = "btnOkay";
this.btnOkay.Size = new System.Drawing.Size(75, 23);
this.btnOkay.TabIndex = 4;
this.btnOkay.Text = "&Okay";
this.btnOkay.UseVisualStyleBackColor = true;
this.btnOkay.Click += new System.EventHandler(this.btnOkay_Click);
//
// btnAddRange
//
this.btnAddRange.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAddRange.Location = new System.Drawing.Point(93, 204);
this.btnAddRange.Name = "btnAddRange";
this.btnAddRange.Size = new System.Drawing.Size(84, 23);
this.btnAddRange.TabIndex = 2;
this.btnAddRange.Text = "Add &Range...";
this.btnAddRange.UseVisualStyleBackColor = true;
this.btnAddRange.Click += new System.EventHandler(this.btnAddRange_Click);
//
// btnDelete
//
this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnDelete.Location = new System.Drawing.Point(183, 204);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(75, 23);
this.btnDelete.TabIndex = 3;
this.btnDelete.Text = "&Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// lbxPlaylistItems
//
this.lbxPlaylistItems.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lbxPlaylistItems.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbxPlaylistItems.FormattingEnabled = true;
this.lbxPlaylistItems.IntegralHeight = false;
this.lbxPlaylistItems.ItemHeight = 17;
this.lbxPlaylistItems.Location = new System.Drawing.Point(12, 12);
this.lbxPlaylistItems.Name = "lbxPlaylistItems";
this.lbxPlaylistItems.Size = new System.Drawing.Size(490, 174);
this.lbxPlaylistItems.TabIndex = 0;
this.lbxPlaylistItems.SelectedValueChanged += new System.EventHandler(this.lbxPlaylistItems_SelectedValueChanged);
//
// FormPlaylistRangeEditor
//
this.AcceptButton = this.btnOkay;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(514, 239);
this.ControlBox = false;
this.Controls.Add(this.lbxPlaylistItems);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAddRange);
this.Controls.Add(this.btnOkay);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnAdd);
this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.MinimumSize = new System.Drawing.Size(446, 167);
this.Name = "FormPlaylistRangeEditor";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Playlist Items Editor";
this.Load += new System.EventHandler(this.FormPlaylistRangeEditor_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOkay;
private System.Windows.Forms.Button btnAddRange;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.ListBox lbxPlaylistItems;
}
} | 52.835714 | 165 | 0.62282 | [
"MIT"
] | lkmvip/ydl-ui | YDL-UI/Forms/FormPlaylistRangeEditor.Designer.cs | 7,399 | C# |
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Organizations;
using AngularProjeto2.Authorization.Roles;
namespace AngularProjeto2.Authorization.Users
{
public class UserStore : AbpUserStore<Role, User>
{
public UserStore(
IRepository<User, long> userRepository,
IRepository<UserLogin, long> userLoginRepository,
IRepository<UserRole, long> userRoleRepository,
IRepository<Role> roleRepository,
IRepository<UserPermissionSetting, long> userPermissionSettingRepository,
IUnitOfWorkManager unitOfWorkManager,
IRepository<UserClaim, long> userClaimStore,
IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository)
: base(
userRepository,
userLoginRepository,
userRoleRepository,
roleRepository,
userPermissionSettingRepository,
unitOfWorkManager,
userClaimStore,
userOrganizationUnitRepository,
organizationUnitRoleRepository)
{
}
}
} | 37.176471 | 85 | 0.658228 | [
"MIT"
] | edsonaraujo1/AngularProjeto2 | AngularProjeto2.Core/Authorization/Users/UserStore.cs | 1,264 | 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("Sdl.Tridion.Api.Client.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SDL - Bristol")]
[assembly: AssemblyProduct("Sdl.Tridion.Api.Client.Tests")]
[assembly: AssemblyCopyright("Copyright © SDL - Bristol 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("28b0c39e-749e-4aed-87d6-84a78783d47f")]
// 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.324324 | 84 | 0.745704 | [
"Apache-2.0"
] | RWS/graphql-client-dotnet | net/src/Sdl.Tridion.Api.Client.Tests/Properties/AssemblyInfo.cs | 1,458 | 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.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class InitializerExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<InitializerExpressionSyntax>
{
protected override void CollectBlockSpans(
InitializerExpressionSyntax node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node.Parent is InitializerExpressionSyntax)
{
// We have something like:
//
// new Dictionary<int, string>
// {
// ...
// {
// ...
// },
// ...
// }
//
// In this case, we want to collapse the "{ ... }," (including the comma).
var nextToken = node.CloseBraceToken.GetNextToken();
var end = nextToken.Kind() == SyntaxKind.CommaToken
? nextToken.Span.End
: node.Span.End;
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: TextSpan.FromBounds(node.SpanStart, end),
hintSpan: TextSpan.FromBounds(node.SpanStart, end),
type: BlockTypes.Expression));
}
else
{
// Parent is something like:
//
// new Dictionary<int, string> {
// ...
// }
//
// The collapsed textspan should be from the > to the }
//
// However, the hint span should be the entire object creation.
var previousToken = node.OpenBraceToken.GetPreviousToken();
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: TextSpan.FromBounds(previousToken.Span.End, node.Span.End),
hintSpan: node.Parent.Span,
type: BlockTypes.Expression));
}
}
}
}
| 37.535211 | 124 | 0.517448 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs | 2,667 | C# |
using BDFramework.UI;
using UnityEngine;
using BDFramework.DataListener;
namespace Code.Game.Windows.MCX
{
public class ViewContrl_MVCTest : AViewContrlBase
{
public ViewContrl_MVCTest(DataListenerService data) : base(data)
{
}
/// <summary>
/// 自动绑定到button这个组件的 onclick事件
/// </summary>
private void OnClick_testButton()
{
var clickCount = this.Model.GetData<int>("ClickCount");
this.Model.SetData("ClickCount" , ++clickCount);
}
/// <summary>
/// 自动绑定
/// </summary>
private void OnValueChange_testSlider(float value)
{
this.Model.SetData("SliderValue" ,value);
}
/// <summary>
/// 自动绑定
/// </summary>
private void OnValueChange_testScrollBar(float value)
{
this.Model.SetData("ScrollBarValue" ,value);
}
}
} | 24.767442 | 72 | 0.497653 | [
"Apache-2.0"
] | HugoFang/BDFramework.Core | Assets/Code/Game@hotfix/demo3/Window_MVC/Contrl_MVCTest.cs | 1,107 | C# |
using AMKsGear.Architecture.Data;
using AMKsGear.Architecture.Modeling;
namespace AMKsGear.Architecture.Automation.Mapper
{
public interface IModelEntityMapper<TEntity, TModel> : IModelPairMapper<TEntity, TModel>
where TEntity : IEntity
where TModel : IModel
{
TEntity ModelToEntity(TModel model, object context);
TModel EntityToModel(TEntity entity, object context);
void FillModelFromEntity(TModel model, TEntity entity, object context);
void FillEntityFromModel(TEntity entity, TModel model, object context);
}
} | 36.0625 | 92 | 0.740035 | [
"Unlicense",
"MIT"
] | amkherad/AMKs-Gear.net | 00-Core/Architecture/Automation/Mapper/IModelEntityMapper`2.cs | 577 | C# |
// This file is part of the DSharpPlus project.
//
// Copyright (c) 2015 Mike Santiago
// Copyright (c) 2016-2022 DSharpPlus Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using Newtonsoft.Json;
namespace DSharpPlus.VoiceNext.Entities
{
internal sealed class VoiceSessionDescriptionPayload
{
[JsonProperty("secret_key")]
public byte[] SecretKey { get; set; }
[JsonProperty("mode")]
public string Mode { get; set; }
}
}
| 40.72973 | 81 | 0.741208 | [
"MIT"
] | Erisa/DSharpPlus | DSharpPlus.VoiceNext/Entities/VoiceSessionDescriptionPayload.cs | 1,507 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticache-2015-02-02.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.ElastiCache.Model
{
/// <summary>
/// The requested cluster is not in the <code>available</code> state.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InvalidCacheClusterStateException : AmazonElastiCacheException
{
/// <summary>
/// Constructs a new InvalidCacheClusterStateException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidCacheClusterStateException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidCacheClusterStateException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidCacheClusterStateException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidCacheClusterStateException
/// </summary>
/// <param name="innerException"></param>
public InvalidCacheClusterStateException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidCacheClusterStateException
/// </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 InvalidCacheClusterStateException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidCacheClusterStateException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidCacheClusterStateException(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 InvalidCacheClusterStateException 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 InvalidCacheClusterStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 48.209677 | 178 | 0.686517 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ElastiCache/Generated/Model/InvalidCacheClusterStateException.cs | 5,978 | C# |
namespace Registration
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string pattern = @"([U]\$)([A-Z][a-z]{2,})\1([P]\@\$)([a-z]{5,}[0-9]+)\3";
int numLine = int.Parse(Console.ReadLine());
int counter = 0;
for (int i = 0; i < numLine; i++)
{
string email = Console.ReadLine();
var match = Regex.Match(email, pattern);
if (match.Success)
{
counter++;
Console.WriteLine("Registration was successful");
Console.WriteLine($"Username: {match.Groups[2].ToString()}, Password: {match.Groups[4].ToString()}");
}
else
{
Console.WriteLine("Invalid username or password");
}
}
Console.WriteLine($"Successful registrations: {counter}");
}
}
}
| 29.428571 | 121 | 0.456311 | [
"MIT"
] | kkaraivanov/CSharpFundamentalsExams | FinalExam/TaskTwo/Registration/Program.cs | 1,032 | C# |
using System.Threading.Tasks;
namespace Microsoft.JSInterop
{
public static class PlaygroundJsRuntimeExtension
{
public static async Task SetToggleBodyOverflow(this IJSRuntime jsRuntime, bool isNavOpen)
{
await jsRuntime.InvokeVoidAsync("toggleBodyOverflow", isNavOpen);
}
public static async Task ScrollToElement(this IJSRuntime jsRuntime, string targetElementId)
{
await jsRuntime.InvokeVoidAsync("scrollToElement", targetElementId);
}
public static async Task CopyToClipboard(this IJSRuntime jsRuntime, string codeSampleContentForCopy)
{
await jsRuntime.InvokeVoidAsync("copyToClipboard", codeSampleContentForCopy);
}
}
}
| 32.565217 | 108 | 0.703605 | [
"MIT"
] | bit-foundation/bit-framework | src/Client/Web/Playground/Bit.Client.Web.BlazorUI.Playground/Web/Extensions/PlaygroundJsRuntimeExtension.cs | 751 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PHP.Core;
using System.Net;
using System.IO;
using System.Threading;
using System.Security;
namespace PHP.Library.Curl
{
internal class HttpFormDataUploader : HttpBitsUploader
{
//enum FormType
//{
// FORM_DATA, /* form metadata (convert to network encoding if necessary) */
// FORM_CONTENT, /* form content (never convert) */
// FORM_CALLBACK, /* 'line' points to the custom pointer we pass to the callback
// */
// FORM_FILE /* 'line' points to a file name we should read from
// to create the form data (never convert) */
//};
class DataSegment
{
//public FormType Type;
public byte[] Header;
public byte[] Data;
public byte[] Footer;
public Stream ReadStream;
}
private DataSegment currentData = new DataSegment();
private string boundary;
private LinkedList<DataSegment> data = new LinkedList<DataSegment>();
private StringBuilder sb = new StringBuilder();
private static readonly string table16 = "0123456789abcdef";
private const int BOUNDARY_LENGTH = 40;
public long ContentLength
{
get
{
long res = 0;
foreach (var dataItem in data)
{
res += dataItem.Header != null ? dataItem.Header.Length : 0;
res += dataItem.Data != null ? dataItem.Data.Length : 0;
res += dataItem.Footer != null ? dataItem.Footer.Length : 0;
if (dataItem.ReadStream != null && dataItem.ReadStream.CanSeek)
res += dataItem.ReadStream.Length;
}
return res;
}
}
public HttpFormDataUploader(HttpWebRequest request) : base(request){ }
/// <summary>
/// Curl_FormBoundary() creates a suitable boundary string
/// </summary>
/// <returns></returns>
private string Curl_FormBoundary()
{
StringBuilder retstring = new StringBuilder(BOUNDARY_LENGTH + 1);
retstring.Append("----------------------------");
var r = new Random();
for (int i = retstring.Length; i < BOUNDARY_LENGTH; i++)
retstring.Append( table16[r.Next() % 16] );
/* 28 dashes and 12 hexadecimal digits makes 12^16 (184884258895036416)
combinations */
return retstring.ToString();
}
/// <summary>
/// Adds String.Format-style formatted data to the data chain.
/// </summary>
/// <param name="str"></param>
/// <param name="args"></param>
private void AddFormDataf(string str, params string[] args)
{
sb.AppendFormat(str, args);
}
private void AddFormFile(string fileName)
{
//currentData.Type = FormType.FORM_FILE;
var filePath = Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, fileName);
//open a file
currentData.ReadStream = File.Open(filePath, FileMode.Open);
NextDataIsFooter();
}
private void AddFormData(object data)
{
//currentData.Type = FormType.FORM_CONTENT;
PhpBytes bytes = PhpVariable.AsBytes(data);
currentData.Data = bytes.ReadonlyData;
NextDataIsFooter();
}
/// <summary>
/// All calls to AddFormDataf is footer after calling this method.
/// </summary>
/// <remarks>
/// After call to method Done all calls to AddFormDataf are forming Header
/// </remarks>
private void NextDataIsFooter()
{
//Before this all AddFormData was header
if (sb.Length > 0)
{
currentData.Header = Encoding.ASCII.GetBytes(sb.ToString());
sb.Clear();
}
}
private void Done()
{
// this was footer
if (sb.Length > 0)
{
currentData.Footer = Encoding.ASCII.GetBytes(sb.ToString());
sb.Clear();
}
data.AddLast(currentData);
currentData = new DataSegment();
}
private long MaxFileSize()
{
long max = 0;
foreach (var dataItem in data)
{
if (dataItem.ReadStream != null && dataItem.ReadStream.CanSeek)
{
max = Math.Max(max, dataItem.ReadStream.Length);
}
}
return max;
}
private byte[] CreateFileReadBuffer()
{
long bufferSize;
long maxFileSize = MaxFileSize();
if (maxFileSize == 0)
return null;
bufferSize = Math.Min(0x2000, maxFileSize);
return new byte[bufferSize];
}
private void Upload()
{
byte[] fileBuffer = null;
bool lastItem;
Request.ContentType = "multipart/form-data; boundary=" + boundary;
Request.ContentLength = ContentLength;
try
{
var writeStream = Request.GetRequestStream();
foreach (var dataItem in data)
{
lastItem = dataItem == data.Last.Value;
if (dataItem.ReadStream != null)
{
if (fileBuffer == null)
fileBuffer = CreateFileReadBuffer();
//Send file
UploadBits(writeStream, dataItem.ReadStream, fileBuffer, dataItem.Header, dataItem.Footer, !lastItem);
//ReadStream was closed, just set it to null
dataItem.ReadStream = null;
}
else
{
//Send data
UploadBits(writeStream, null, dataItem.Data, dataItem.Header, dataItem.Footer, !lastItem);
}
}
}
catch (Exception exception)
{
//Close all possibly opened files
foreach (var dataItem in data)
{
if (dataItem.ReadStream != null)
{
dataItem.ReadStream.Close();
dataItem.ReadStream = null;
}
}
if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
{
throw;
}
if (!(exception is WebException) && !(exception is SecurityException))
{
exception = new WebException("Curl", exception);
}
AbortRequest();
throw exception;
}
Close();
}
private void Close()
{
data.Clear();
}
public void UploadForm(CurlForm form)
{
//Count this
//request.ContentLength = data.Length;//this is my responsability to set
boundary = Curl_FormBoundary();
CurlForm.FormFileItem fileItem = null;
/* Make the first line of the output */
// Assignment to Request.ContentType takes care about it
//AddFormDataStr("{0}; boundary={1}\r\n",
// /*custom_content_type != null ? custom_content_type :*/ "Content-Type: multipart/form-data",
// boundary);
/* we DO NOT include that line in the total size of the POST, since it'll be
part of the header! */
foreach (var item in form.Data)
{
AddFormDataf("\r\n");
/* boundary */
AddFormDataf("--{0}\r\n", boundary);
/* Maybe later this should be disabled when a custom_content_type is
passed, since Content-Disposition is not meaningful for all multipart
types.
*/
AddFormDataf("Content-Disposition: form-data; name=\"");
AddFormDataf(item.Name);
AddFormDataf("\"");
//TODO: we just support one file send
if (item.GetType() == typeof(CurlForm.FormFileItem))
{
fileItem = (CurlForm.FormFileItem)item;
//Path.GetFileName(fs.Name)
AddFormDataf(" ;filename=\"{0}\"",
fileItem.FileName);
if (fileItem.ContentType != null)
{
/* we have a specified type */
AddFormDataf("\r\nContent-Type: {0}",
fileItem.ContentType);
}
}
AddFormDataf("\r\n\r\n");
if (fileItem != null)
{
//AddFile
AddFormFile(fileItem.FileName);
}
else
{
AddFormData(item.Data);
}
if (item == form.Data.Last.Value) // Last item
{
/* end-boundary for everything */
AddFormDataf("\r\n--{0}--\r\n", boundary);
}
Done();
}
Upload();
}
}
}
| 31.256098 | 139 | 0.4603 | [
"Apache-2.0"
] | DEVSENSE/Phalanger | Source/Extensions/Curl/HttpFormDataUploader.cs | 10,254 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
namespace Microsoft.AspNet.SignalR.Hubs
{
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class HubMethodNameAttribute : Attribute
{
public HubMethodNameAttribute(string methodName)
{
if (String.IsNullOrEmpty(methodName))
{
throw new ArgumentNullException("methodName");
}
MethodName = methodName;
}
public string MethodName
{
get;
private set;
}
}
}
| 27.038462 | 132 | 0.618777 | [
"Apache-2.0"
] | AlaShiban/SignalR | src/Microsoft.AspNet.SignalR.Core/Hubs/HubMethodNameAttribute.cs | 705 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xamarin.Bundler;
namespace Xamarin.Utils
{
public class CompilerFlags
{
public Application Application { get { return Target.App; } }
public Target Target;
public HashSet<string> Frameworks; // if a file, "-F /path/to/X --framework X" and added to Inputs, otherwise "--framework X".
public HashSet<string> WeakFrameworks;
public HashSet<string> LinkWithLibraries; // X, added to Inputs
public HashSet<string> ForceLoadLibraries; // -force_load X, added to Inputs
public HashSet<string[]> OtherFlags; // X
public List<string> InitialOtherFlags; // same as OtherFlags, only that they're the first argument(s) to clang (because order matters!). This is a list to preserve order (fifo).
public HashSet<string> Defines; // -DX
public HashSet<string> UnresolvedSymbols; // -u X
public HashSet<string> SourceFiles; // X, added to Inputs
// Here we store a list of all the file-system based inputs
// to the compiler. This is used when determining if the
// compiler needs to be called in the first place (dependency
// tracking).
public List<string> Inputs;
public CompilerFlags (Target target)
{
if (target == null)
throw new ArgumentNullException (nameof (target));
this.Target = target;
}
public HashSet<string> AllLibraries {
get {
var rv = new HashSet<string> ();
if (LinkWithLibraries != null)
rv.UnionWith (LinkWithLibraries);
if (ForceLoadLibraries != null)
rv.UnionWith (ForceLoadLibraries);
return rv;
}
}
public void ReferenceSymbols (IEnumerable<Symbol> symbols)
{
if (UnresolvedSymbols == null)
UnresolvedSymbols = new HashSet<string> ();
foreach (var symbol in symbols)
UnresolvedSymbols.Add (symbol.Prefix + symbol.Name);
}
public void AddDefine (string define)
{
if (Defines == null)
Defines = new HashSet<string> ();
Defines.Add (define);
}
public void AddLinkWith (string library, bool force_load = false)
{
if (LinkWithLibraries == null)
LinkWithLibraries = new HashSet<string> ();
if (ForceLoadLibraries == null)
ForceLoadLibraries = new HashSet<string> ();
if (force_load) {
ForceLoadLibraries.Add (library);
} else {
LinkWithLibraries.Add (library);
}
}
public void AddLinkWith (IEnumerable<string> libraries, bool force_load = false)
{
if (libraries == null)
return;
foreach (var lib in libraries)
AddLinkWith (lib, force_load);
}
public void AddSourceFile (string file)
{
if (SourceFiles == null)
SourceFiles = new HashSet<string> ();
SourceFiles.Add (file);
}
public void AddStandardCppLibrary ()
{
if (Driver.XcodeVersion.Major < 10)
return;
// Xcode 10 doesn't ship with libstdc++, so use libc++ instead.
AddOtherFlag ("-stdlib=libc++");
}
public void AddOtherInitialFlag (string flag)
{
if (InitialOtherFlags == null)
InitialOtherFlags = new List<string> ();
InitialOtherFlags.Add (flag);
}
public void AddOtherFlag (IList<string> flags)
{
if (flags == null)
return;
AddOtherFlag ((string []) flags.ToArray ());
}
public void AddOtherFlag (params string [] flags)
{
if (flags == null || flags.Length == 0)
return;
if (OtherFlags == null)
OtherFlags = new HashSet<string[]> ();
OtherFlags.Add (flags);
}
public void LinkWithMono ()
{
var mode = Target.App.LibMonoLinkMode;
switch (mode) {
case AssemblyBuildTarget.DynamicLibrary:
case AssemblyBuildTarget.StaticObject:
AddLinkWith (Application.GetLibMono (mode));
break;
case AssemblyBuildTarget.Framework:
AddFramework (Application.GetLibMono (mode));
break;
default:
throw ErrorHelper.CreateError (100, Errors.MT0100, mode);
}
AddOtherFlag ("-lz");
AddOtherFlag ("-liconv");
}
public void LinkWithXamarin ()
{
var mode = Target.App.LibXamarinLinkMode;
switch (mode) {
case AssemblyBuildTarget.DynamicLibrary:
case AssemblyBuildTarget.StaticObject:
AddLinkWith (Application.GetLibXamarin (mode));
break;
case AssemblyBuildTarget.Framework:
AddFramework (Application.GetLibXamarin (mode));
break;
default:
throw ErrorHelper.CreateError (100, Errors.MT0100, mode);
}
AddFramework ("Foundation");
AddOtherFlag ("-lz");
if (Application.Platform != ApplePlatform.WatchOS && Application.Platform != ApplePlatform.TVOS)
AddFramework ("CFNetwork"); // required by xamarin_start_wwan
}
public void AddFramework (string framework)
{
if (Frameworks == null)
Frameworks = new HashSet<string> ();
Frameworks.Add (framework);
}
public void AddFrameworks (IEnumerable<string> frameworks, IEnumerable<string> weak_frameworks)
{
if (frameworks != null) {
if (Frameworks == null)
Frameworks = new HashSet<string> ();
Frameworks.UnionWith (frameworks);
}
if (weak_frameworks != null) {
if (WeakFrameworks == null)
WeakFrameworks = new HashSet<string> ();
WeakFrameworks.UnionWith (weak_frameworks);
}
}
public void Prepare ()
{
// Check for system frameworks that are only available in newer iOS versions,
// (newer than the deployment target), in which case those need to be weakly linked.
if (Frameworks != null) {
if (WeakFrameworks == null)
WeakFrameworks = new HashSet<string> ();
foreach (var fwk in Frameworks) {
if (!fwk.EndsWith (".framework", StringComparison.Ordinal)) {
var add_to = WeakFrameworks;
var framework = Driver.GetFrameworks (Application).Find (fwk);
if (framework != null) {
if (framework.Version > Application.SdkVersion)
continue;
add_to = Application.DeploymentTarget >= framework.Version ? Frameworks : WeakFrameworks;
}
add_to.Add (fwk);
} else {
// believe what we got about user frameworks.
}
}
// Make sure frameworks aren't duplicated, favoring any weak frameworks.
Frameworks.ExceptWith (WeakFrameworks);
}
// force_load libraries take precedence, so remove the libraries
// we need to force load from the list of libraries we just load.
if (LinkWithLibraries != null)
LinkWithLibraries.ExceptWith (ForceLoadLibraries);
}
void AddInput (string file)
{
if (Inputs == null)
return;
Inputs.Add (file);
}
public void WriteArguments (IList<string> args)
{
Prepare ();
if (InitialOtherFlags != null) {
var idx = 0;
foreach (var flag in InitialOtherFlags) {
args.Insert (idx, flag);
idx++;
}
}
ProcessFrameworksForArguments (args);
if (LinkWithLibraries != null) {
foreach (var lib in LinkWithLibraries) {
args.Add (lib);
AddInput (lib);
}
}
if (ForceLoadLibraries != null) {
foreach (var lib in ForceLoadLibraries) {
args.Add ("-force_load");
args.Add (lib);
AddInput (lib);
}
}
if (OtherFlags != null) {
foreach (var flags in OtherFlags) {
foreach (var flag in flags)
args.Add (flag);
}
}
if (Defines != null) {
foreach (var define in Defines) {
args.Add ("-D");
args.Add (define);
}
}
if (UnresolvedSymbols != null) {
foreach (var symbol in UnresolvedSymbols) {
args.Add ("-u");
args.Add (symbol);
}
}
if (SourceFiles != null) {
foreach (var src in SourceFiles) {
args.Add (src);
AddInput (src);
}
}
}
void ProcessFrameworksForArguments (IList<string> args)
{
bool any_user_framework = false;
if (Frameworks != null) {
foreach (var fw in Frameworks)
ProcessFrameworkForArguments (args, fw, false, ref any_user_framework);
}
if (WeakFrameworks != null) {
foreach (var fw in WeakFrameworks)
ProcessFrameworkForArguments (args, fw, true, ref any_user_framework);
}
if (any_user_framework) {
args.Add ("-Xlinker");
args.Add ("-rpath");
args.Add ("-Xlinker");
switch (Application.Platform) {
case ApplePlatform.iOS:
case ApplePlatform.TVOS:
case ApplePlatform.WatchOS:
args.Add ("@executable_path/Frameworks");
break;
case ApplePlatform.MacCatalyst:
case ApplePlatform.MacOSX:
args.Add ("@executable_path/../Frameworks");
break;
default:
throw ErrorHelper.CreateError (71, Errors.MX0071, Application.Platform, Application.ProductName);
}
if (Application.IsExtension) {
args.Add ("-Xlinker");
args.Add ("-rpath");
args.Add ("-Xlinker");
args.Add ("@executable_path/../../Frameworks");
}
}
if (Application.HasAnyDynamicLibraries) {
args.Add ("-Xlinker");
args.Add ("-rpath");
args.Add ("-Xlinker");
args.Add ("@executable_path/");
if (Application.IsExtension) {
args.Add ("-Xlinker");
args.Add ("-rpath");
args.Add ("-Xlinker");
args.Add ("@executable_path/../..");
}
}
}
void ProcessFrameworkForArguments (IList<string> args, string fw, bool is_weak, ref bool any_user_framework)
{
var name = Path.GetFileNameWithoutExtension (fw);
if (fw.EndsWith (".framework", StringComparison.Ordinal)) {
// user framework, we need to pass -F to the linker so that the linker finds the user framework.
any_user_framework = true;
AddInput (Path.Combine (fw, name));
args.Add ("-F");
args.Add (Path.GetDirectoryName (fw));
}
args.Add (is_weak ? "-weak_framework" : "-framework");
args.Add (name);
}
public string[] ToArray ()
{
var args = new List<string> ();
WriteArguments (args);
return args.ToArray ();
}
public override string ToString ()
{
return string.Join (" ", ToArray ());
}
public void PopulateInputs ()
{
var args = new List<string> ();
Inputs = new List<string> ();
WriteArguments (args);
}
}
}
| 26.493298 | 179 | 0.657762 | [
"BSD-3-Clause"
] | NormanChiflen/xamarin-all-IOS | tools/common/CompilerFlags.cs | 9,882 | C# |
/*
This file is part of pspsharp.
pspsharp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pspsharp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pspsharp. If not, see <http://www.gnu.org/licenses/>.
*/
namespace pspsharp.format.rco.anim
{
using FloatType = pspsharp.format.rco.type.FloatType;
using IntType = pspsharp.format.rco.type.IntType;
using ObjectType = pspsharp.format.rco.type.ObjectType;
public class FadeAnim : BaseAnim
{
[ObjectField(1)]
public ObjectType @ref;
[ObjectField( 2)]
public FloatType duration;
[ObjectField( 3)]
public IntType accelMode;
[ObjectField(4)]
public FloatType transparency;
}
} | 30.771429 | 68 | 0.767874 | [
"MIT"
] | xXxTheDarkprogramerxXx/PSPSHARP | PSP_EMU/format/rco/anim/FadeAnim.cs | 1,079 | C# |
using System;
using xServer.Core.Networking;
namespace xServer.Core.Packets.ServerPackets
{
[Serializable]
public class DoClientUninstall : IPacket
{
public DoClientUninstall()
{
}
public void Execute(Client client)
{
client.Send(this);
}
}
} | 18.777778 | 45 | 0.56213 | [
"MIT"
] | pavitra14/Xtremis-V2.0 | Server/Core/Packets/ServerPackets/DoClientUninstall.cs | 340 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RepositoryLayer;
using BusinessLayer;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
namespace P1_KemoAllen
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
////Session - review in detail
//services.AddDistributedMemoryCache();
//services.AddSession(options =>
//{
// //options.IdleTimeout = TimeSpan.FromSeconds(10);
// options.Cookie.HttpOnly = true;
// //options.Cookie.Name = "";
// options.Cookie.IsEssential = true;
//});
////Doesn't load automatically
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddDbContext<Store_DbContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddControllersWithViews();
services.AddScoped<StoreBusinessClass>();
services.AddScoped<StoreMapper>();
services.AddScoped<StoreRepository>();
services.AddScoped<Store_DbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
//app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 34.395349 | 144 | 0.586545 | [
"MIT"
] | Kallen15/StoreWebApplication | StoreWebApplication/P1_KemoAllen/Startup.cs | 2,958 | C# |
// Copyright (c) 2020-2021 Vladimir Popov zor1994@gmail.com https://github.com/ZorPastaman/Behavior-Tree
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using UnityEngine;
using Zor.BehaviorTree.DrawingAttributes;
using Zor.SimpleBlackboard.Core;
namespace Zor.BehaviorTree.Core.Leaves.Conditions
{
public sealed class CheckSphere : Condition,
ISetupable<BlackboardPropertyName, BlackboardPropertyName, LayerMask>,
ISetupable<string, string, LayerMask>
{
[BehaviorInfo] private BlackboardPropertyName m_positionPropertyName;
[BehaviorInfo] private BlackboardPropertyName m_radiusPropertyName;
[BehaviorInfo] private LayerMask m_layerMask;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ISetupable<BlackboardPropertyName, BlackboardPropertyName, LayerMask>.Setup(
BlackboardPropertyName positionPropertyName, BlackboardPropertyName radiusPropertyName,
LayerMask layerMask)
{
SetupInternal(positionPropertyName, radiusPropertyName, layerMask);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ISetupable<string, string, LayerMask>.Setup(string positionPropertyName,
string radiusPropertyName, LayerMask layerMask)
{
SetupInternal(new BlackboardPropertyName(positionPropertyName),
new BlackboardPropertyName(radiusPropertyName), layerMask);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetupInternal(BlackboardPropertyName positionPropertyName,
BlackboardPropertyName radiusPropertyName, LayerMask layerMask)
{
m_positionPropertyName = positionPropertyName;
m_radiusPropertyName = radiusPropertyName;
m_layerMask = layerMask;
}
[Pure]
protected override Status Execute()
{
bool hasValues = blackboard.TryGetStructValue(m_positionPropertyName, out Vector3 position) &
blackboard.TryGetStructValue(m_radiusPropertyName, out float radius);
return StateToStatusHelper.ConditionToStatus(Physics.CheckSphere(position, radius, m_layerMask),
hasValues);
}
}
}
| 36.472727 | 105 | 0.817049 | [
"MIT"
] | ZorPastaman/Behavior-Tree | Runtime/Core/Leaves/Conditions/CheckSphere.cs | 2,008 | C# |
/*
* Created by SharpDevelop.
* User: Peter Forstmeier
* Date: 21.06.2015
* Time: 10:37
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
using ICSharpCode.Reporting.Addin.TypeProvider;
namespace ICSharpCode.Reporting.Addin.Designer
{
/// <summary>
/// Description of ShapeDesigner.
/// </summary>
public class ImageDesigner:ControlDesigner
{
ISelectionService selectionService;
IComponentChangeService componentChangeService;
public ImageDesigner()
{
}
public override void Initialize(IComponent component){
if (component == null) {
throw new ArgumentNullException("component");
}
base.Initialize(component);
this.componentChangeService = (IComponentChangeService)component.Site.GetService(typeof(IComponentChangeService));
if (componentChangeService != null) {
componentChangeService.ComponentChanging += OnComponentChanging;
componentChangeService.ComponentChanged += OnComponentChanged;
componentChangeService.ComponentRename += new ComponentRenameEventHandler(OnComponentRename);
}
selectionService = GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null)
{
selectionService.SelectionChanged += OnSelectionChanged;
}
}
protected override void PostFilterProperties(System.Collections.IDictionary properties){
TypeProviderHelper.RemoveProperties(properties);
base.PostFilterProperties(properties);
}
void OnComponentChanging (object sender,ComponentChangingEventArgs e){
// System.Console.WriteLine("changing");
// System.Console.WriteLine("{0}",this.baseLine.ClientRectangle);
}
void OnComponentChanged(object sender,ComponentChangedEventArgs e){
// System.Console.WriteLine("changed");
// System.Console.WriteLine("{0}",this.baseLine.ClientRectangle);
}
void OnComponentRename(object sender,ComponentRenameEventArgs e) {
if (e.Component == Component) {
Control.Name = e.NewName;
Control.Invalidate();
}
}
void OnSelectionChanged(object sender, EventArgs e){
Control.Invalidate( );
}
protected override void Dispose(bool disposing){
if (this.componentChangeService != null) {
componentChangeService.ComponentChanging -= OnComponentChanging;
componentChangeService.ComponentChanged -= OnComponentChanged;
componentChangeService.ComponentRename -= OnComponentRename;
}
if (selectionService != null) {
selectionService.SelectionChanged -= OnSelectionChanged;
}
base.Dispose(disposing);
}
}
}
| 27.383838 | 117 | 0.74253 | [
"MIT"
] | TetradogOther/SharpDevelop | src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Designer/ImageDesigner.cs | 2,713 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading; //estas son nuevas
using System.Threading.Tasks; //bibliotecas
namespace Proyecto_de_Progra_ll
{
public abstract class abstracta_inteligencia:Comida
{
#region Propiedades
int puntos = 0;
public int Puntos
{
get { return puntos; }
set { puntos = value; }
}
#endregion
#region Las_clases_abstractas_NO_TIENEN_CONSTRUCTORES
#endregion
#region Metodos
//el override sobreescribe el metodo pero que no tiene estructura
public abstract void prueba(System.Drawing.Rectangle[] Serpiente_almacenadora_encapsulada, System.Drawing.Rectangle comidarec, Boolean alpha); //No se sabe como se van a comportar estos metodos y no llevan llaves {}
//os son los que respetan la famosa firma del metodo, pueden recibir parametros o no
//No se sabe como se van a comportar estos metodos y no llevan llaves {}
//Estos son los que respetan la famosa firma del metodo, pueden recibir parametros o no
public int palabras() {
return Puntos = Puntos + 1;
}
#endregion
}
}
| 28.040816 | 223 | 0.684134 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | pipear07/Aplicativo-WindowsForms-Juego-del-Snake-Inteligente | Proyecto_de_Progra_ll/Proyecto_de_Progra_ll/abstracta inteligencia.cs | 1,376 | C# |
using System;
using System.Collections.Generic;
using System.Text;
public class Person
{
private string name;
private int age;
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
}
| 15.590909 | 34 | 0.565598 | [
"MIT"
] | GMihalkow/CSharp | CSharp Fundamentals 2018/Csharp OOP Basics/Defining Classes - Exercise/01_Define_A_Class_Person/Person.cs | 345 | 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.Purview.Models.Api20210701
{
using static Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Extensions;
/// <summary>Metadata pertaining to creation and last modification of the resource.</summary>
public partial class TrackedResourceSystemData
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Purview.Models.Api20210701.ITrackedResourceSystemData.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Purview.Models.Api20210701.ITrackedResourceSystemData.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Purview.Models.Api20210701.ITrackedResourceSystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject json ? new TrackedResourceSystemData(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="TrackedResourceSystemData" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="TrackedResourceSystemData" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__systemData?.ToJson(container, serializationMode);
AfterToJson(ref container);
return container;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject into a new instance of <see cref="TrackedResourceSystemData" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject instance to deserialize from.</param>
internal TrackedResourceSystemData(Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__systemData = new Microsoft.Azure.PowerShell.Cmdlets.Purview.Models.Api20210701.SystemData(json);
AfterFromJson(json);
}
}
} | 63.943396 | 253 | 0.684863 | [
"MIT"
] | Agazoth/azure-powershell | src/Purview/Purview.Autorest/generated/api/Models/Api20210701/TrackedResourceSystemData.json.cs | 6,673 | C# |
//this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
public class UnityEngine_MonoBehaviourWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(UnityEngine.MonoBehaviour), typeof(UnityEngine.Behaviour));
L.RegFunction("IsInvoking", IsInvoking);
L.RegFunction("CancelInvoke", CancelInvoke);
L.RegFunction("Invoke", Invoke);
L.RegFunction("InvokeRepeating", InvokeRepeating);
L.RegFunction("StartCoroutine", StartCoroutine);
L.RegFunction("StopCoroutine", StopCoroutine);
L.RegFunction("StopAllCoroutines", StopAllCoroutines);
L.RegFunction("print", print);
L.RegFunction("__eq", op_Equality);
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("useGUILayout", get_useGUILayout, set_useGUILayout);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int IsInvoking(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
bool o = obj.IsInvoking();
LuaDLL.lua_pushboolean(L, o);
return 1;
}
else if (count == 2)
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
bool o = obj.IsInvoking(arg0);
LuaDLL.lua_pushboolean(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.MonoBehaviour.IsInvoking");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CancelInvoke(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
obj.CancelInvoke();
return 0;
}
else if (count == 2)
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
obj.CancelInvoke(arg0);
return 0;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.MonoBehaviour.CancelInvoke");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Invoke(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 3);
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
float arg1 = (float)LuaDLL.luaL_checknumber(L, 3);
obj.Invoke(arg0, arg1);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int InvokeRepeating(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 4);
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
float arg1 = (float)LuaDLL.luaL_checknumber(L, 3);
float arg2 = (float)LuaDLL.luaL_checknumber(L, 4);
obj.InvokeRepeating(arg0, arg1, arg2);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int StartCoroutine(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2 && TypeChecker.CheckTypes<System.Collections.IEnumerator>(L, 2))
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
System.Collections.IEnumerator arg0 = (System.Collections.IEnumerator)ToLua.ToObject(L, 2);
UnityEngine.Coroutine o = obj.StartCoroutine(arg0);
ToLua.PushSealed(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string>(L, 2))
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.ToString(L, 2);
UnityEngine.Coroutine o = obj.StartCoroutine(arg0);
ToLua.PushSealed(L, o);
return 1;
}
else if (count == 3)
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
object arg1 = ToLua.ToVarObject(L, 3);
UnityEngine.Coroutine o = obj.StartCoroutine(arg0, arg1);
ToLua.PushSealed(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.MonoBehaviour.StartCoroutine");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int StopCoroutine(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2 && TypeChecker.CheckTypes<string>(L, 2))
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
string arg0 = ToLua.ToString(L, 2);
obj.StopCoroutine(arg0);
return 0;
}
else if (count == 2 && TypeChecker.CheckTypes<UnityEngine.Coroutine>(L, 2))
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
UnityEngine.Coroutine arg0 = (UnityEngine.Coroutine)ToLua.ToObject(L, 2);
obj.StopCoroutine(arg0);
return 0;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Collections.IEnumerator>(L, 2))
{
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
System.Collections.IEnumerator arg0 = (System.Collections.IEnumerator)ToLua.ToObject(L, 2);
obj.StopCoroutine(arg0);
return 0;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.MonoBehaviour.StopCoroutine");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int StopAllCoroutines(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)ToLua.CheckObject<UnityEngine.MonoBehaviour>(L, 1);
obj.StopAllCoroutines();
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int print(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
object arg0 = ToLua.ToVarObject(L, 1);
UnityEngine.MonoBehaviour.print(arg0);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int op_Equality(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
UnityEngine.Object arg0 = (UnityEngine.Object)ToLua.ToObject(L, 1);
UnityEngine.Object arg1 = (UnityEngine.Object)ToLua.ToObject(L, 2);
bool o = arg0 == arg1;
LuaDLL.lua_pushboolean(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_useGUILayout(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)o;
bool ret = obj.useGUILayout;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index useGUILayout on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_useGUILayout(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.MonoBehaviour obj = (UnityEngine.MonoBehaviour)o;
bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
obj.useGUILayout = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index useGUILayout on a nil value");
}
}
}
| 28.27027 | 115 | 0.67794 | [
"MIT"
] | jdxjdx/my_framework | Assets/Plugins/Tolua/Source/Generate/UnityEngine_MonoBehaviourWrap.cs | 8,370 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public class MigrationNotReady : MigrationFault
{
protected string _reason;
public string Reason
{
get
{
return this._reason;
}
set
{
this._reason = value;
}
}
}
}
| 13.105263 | 48 | 0.654618 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/M/MigrationNotReady.cs | 249 | C# |
namespace InterpretadorSQL
{
partial class frmMain
{
/// <summary>
/// Variável de designer necessária.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpar os recursos que estão sendo usados.
/// </summary>
/// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código gerado pelo Windows Form Designer
/// <summary>
/// Método necessário para suporte ao Designer - não modifique
/// o conteúdo deste método com o editor de código.
/// </summary>
private void InitializeComponent()
{
this.btnSolicitacaoSQL = new System.Windows.Forms.Button();
this.txtSql = new System.Windows.Forms.TextBox();
this.txtResultado = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.txtPosFixa = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtIteracoes = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnSolicitacaoSQL
//
this.btnSolicitacaoSQL.Location = new System.Drawing.Point(231, 162);
this.btnSolicitacaoSQL.Name = "btnSolicitacaoSQL";
this.btnSolicitacaoSQL.Size = new System.Drawing.Size(153, 23);
this.btnSolicitacaoSQL.TabIndex = 3;
this.btnSolicitacaoSQL.Text = "Solicitação SQL";
this.btnSolicitacaoSQL.UseVisualStyleBackColor = true;
this.btnSolicitacaoSQL.Click += new System.EventHandler(this.btnSolicitacaoSQL_Click);
//
// txtSql
//
this.txtSql.Location = new System.Drawing.Point(13, 85);
this.txtSql.Multiline = true;
this.txtSql.Name = "txtSql";
this.txtSql.Size = new System.Drawing.Size(371, 71);
this.txtSql.TabIndex = 4;
this.txtSql.Text = "select 5 + ((7 / 6 + 7 + (sin(2*2-8 - cos(2) - 5 * 3 + 6 /4) * 3 + 6 - tan(34)) *" +
" 2 + 5 - 6) - 5) + 3 * 2";
//
// txtResultado
//
this.txtResultado.Location = new System.Drawing.Point(12, 218);
this.txtResultado.Name = "txtResultado";
this.txtResultado.Size = new System.Drawing.Size(174, 20);
this.txtResultado.TabIndex = 5;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 202);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(58, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Resultado:";
//
// txtPosFixa
//
this.txtPosFixa.Location = new System.Drawing.Point(12, 30);
this.txtPosFixa.Name = "txtPosFixa";
this.txtPosFixa.ReadOnly = true;
this.txtPosFixa.Size = new System.Drawing.Size(371, 20);
this.txtPosFixa.TabIndex = 7;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(9, 14);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(50, 13);
this.label2.TabIndex = 8;
this.label2.Text = "Pós Fixa:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 69);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(79, 13);
this.label3.TabIndex = 9;
this.label3.Text = "Comando SQL:";
//
// txtIteracoes
//
this.txtIteracoes.Location = new System.Drawing.Point(319, 62);
this.txtIteracoes.Name = "txtIteracoes";
this.txtIteracoes.Size = new System.Drawing.Size(64, 20);
this.txtIteracoes.TabIndex = 10;
this.txtIteracoes.Text = "1000";
this.txtIteracoes.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(219, 65);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 13);
this.label4.TabIndex = 11;
this.label4.Text = "Repetições:";
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(396, 424);
this.Controls.Add(this.label4);
this.Controls.Add(this.txtIteracoes);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtPosFixa);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtResultado);
this.Controls.Add(this.txtSql);
this.Controls.Add(this.btnSolicitacaoSQL);
this.Name = "frmMain";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnSolicitacaoSQL;
private System.Windows.Forms.TextBox txtSql;
private System.Windows.Forms.TextBox txtResultado;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtPosFixa;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtIteracoes;
private System.Windows.Forms.Label label4;
}
}
| 41.358974 | 124 | 0.558277 | [
"MIT"
] | grilo88/SuperFastDB | demo/demo2/InterpretadorSQL/frmMain.Designer.cs | 6,471 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System.Collections.Generic;
using SixLabors.Fonts.Exceptions;
namespace SixLabors.Fonts
{
/// <summary>
/// A readonly collection of fonts.
/// </summary>
public interface IReadOnlyFontCollection
{
/// <summary>
/// Gets the collection of <see cref="FontFamily"/> objects associated with this <see cref="FontCollection"/>.
/// </summary>
/// <value>
/// The families.
/// </value>
IEnumerable<FontFamily> Families { get; }
/// <summary>
/// Finds the specified font family.
/// </summary>
/// <param name="fontFamily">The font family.</param>
/// <returns>The family if installed otherwise throws <see cref="FontFamilyNotFoundException"/></returns>
FontFamily Find(string fontFamily);
/// <summary>
/// Finds the specified font family.
/// </summary>
/// <param name="fontFamily">The font family to find.</param>
/// <param name="family">The found family.</param>
/// <returns>true if a font of that family has been installed into the font collection.</returns>
bool TryFind(string fontFamily, out FontFamily family);
}
}
| 34.578947 | 118 | 0.615677 | [
"Apache-2.0"
] | Jjagg/Fonts | src/SixLabors.Fonts/IReadonlyFontCollection.cs | 1,316 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Interfaces;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This example demonstrates how to add options for a given underlying equity security.
/// It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
/// can inspect the option chain to pick a specific option contract to trade.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="options" />
/// <meta name="tag" content="filter selection" />
public class BasicTemplateOptionsAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private const string UnderlyingTicker = "GOOG";
public Symbol OptionSymbol;
public override void Initialize()
{
SetStartDate(2015, 12, 24);
SetEndDate(2015, 12, 24);
SetCash(100000);
var equity = AddEquity(UnderlyingTicker);
var option = AddOption(UnderlyingTicker);
OptionSymbol = option.Symbol;
// set our strike/expiry filter for this option chain
option.SetFilter(u => u.Strikes(-2, +2)
// Expiration method accepts TimeSpan objects or integer for days.
// The following statements yield the same filtering criteria
.Expiration(0, 180));
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(180)));
// use the underlying equity as the benchmark
SetBenchmark(equity.Symbol);
}
/// <summary>
/// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
/// </summary>
/// <param name="slice">The current slice of data keyed by symbol string</param>
public override void OnData(Slice slice)
{
if (!Portfolio.Invested && IsMarketOpen(OptionSymbol))
{
OptionChain chain;
if (slice.OptionChains.TryGetValue(OptionSymbol, out chain))
{
// we find at the money (ATM) put contract with farthest expiration
var atmContract = chain
.OrderByDescending(x => x.Expiry)
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
.ThenByDescending(x => x.Right)
.FirstOrDefault();
if (atmContract != null)
{
// if found, trade it
MarketOrder(atmContract.Symbol, 1);
MarketOnCloseOrder(atmContract.Symbol, -1);
}
}
}
}
/// <summary>
/// Order fill event handler. On an order fill update the resulting information is passed to this method.
/// </summary>
/// <param name="orderEvent">Order event details containing details of the evemts</param>
/// <remarks>This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects</remarks>
public override void OnOrderEvent(OrderEvent orderEvent)
{
Log(orderEvent.ToString());
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0%"},
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$2.00"},
{"Estimated Strategy Capacity", "$1300000.00"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "0"},
{"Return Over Maximum Drawdown", "0"},
{"Portfolio Turnover", "0"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "9d9f9248ee8fe30d87ff0a6f6fea5112"}
};
}
}
| 43.360759 | 175 | 0.569114 | [
"Apache-2.0"
] | BuildJet/Lean | Algorithm.CSharp/BasicTemplateOptionsAlgorithm.cs | 6,851 | 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.Windows.Forms
{
internal enum DataGridViewHitTestTypeCloseEdge
{
None = 0,
Left = 1,
Right = 2,
Top = 3,
Bottom = 4
}
}
| 24.625 | 71 | 0.64467 | [
"MIT"
] | 15835229565/winforms-1 | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewHitTestCloseEdge.cs | 396 | C# |
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
#pragma warning disable CS0108
using UE4.Engine.Native;
namespace UE4.Engine {
///<summary>Particle Module Trail Source</summary>
public unsafe partial class ParticleModuleTrailSource : ParticleModuleTrailBase {
///<summary>The source method for the trail.</summary>
public unsafe byte SourceMethod {
get {return ParticleModuleTrailSource_ptr->SourceMethod;}
set {ParticleModuleTrailSource_ptr->SourceMethod = value;}
}
///<summary>The name of the source - either the emitter or Actor.</summary>
public unsafe Name SourceName {
get {return ParticleModuleTrailSource_ptr->SourceName;}
set {ParticleModuleTrailSource_ptr->SourceName = value;}
}
///<summary>The strength of the tangent from the source point for each Trail.</summary>
public unsafe RawDistributionFloat SourceStrength {
get {return ParticleModuleTrailSource_ptr->SourceStrength;}
set {ParticleModuleTrailSource_ptr->SourceStrength = value;}
}
public bool bLockSourceStength {
get {return Main.GetGetBoolPropertyByName(this, "bLockSourceStength"); }
set {Main.SetGetBoolPropertyByName(this, "bLockSourceStength", value); }
}
///<summary>
///SourceOffsetCount
///The number of source offsets that can be expected to be found on the instance.
///</summary>
///<remarks>
///These must be named
/// TrailSourceOffset#
///</remarks>
public unsafe int SourceOffsetCount {
get {return ParticleModuleTrailSource_ptr->SourceOffsetCount;}
set {ParticleModuleTrailSource_ptr->SourceOffsetCount = value;}
}
//TODO: array not UObject TArray SourceOffsetDefaults
///<summary>Particle selection method, when using the SourceMethod of Particle.</summary>
public unsafe byte SelectionMethod {
get {return ParticleModuleTrailSource_ptr->SelectionMethod;}
set {ParticleModuleTrailSource_ptr->SelectionMethod = value;}
}
public bool bInheritRotation {
get {return Main.GetGetBoolPropertyByName(this, "bInheritRotation"); }
set {Main.SetGetBoolPropertyByName(this, "bInheritRotation", value); }
}
static ParticleModuleTrailSource() {
StaticClass = Main.GetClass("ParticleModuleTrailSource");
}
internal unsafe ParticleModuleTrailSource_fields* ParticleModuleTrailSource_ptr => (ParticleModuleTrailSource_fields*) ObjPointer.ToPointer();
///<summary>Convert from IntPtr to UObject</summary>
public static implicit operator ParticleModuleTrailSource(IntPtr p) => UObject.Make<ParticleModuleTrailSource>(p);
///<summary>Get UE4 Class</summary>
public static Class StaticClass {get; private set;}
///<summary>Get UE4 Default Object for this Class</summary>
public static ParticleModuleTrailSource DefaultObject => Main.GetDefaultObject(StaticClass);
///<summary>Spawn an object of this class</summary>
public static ParticleModuleTrailSource New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name);
}
}
| 48.283784 | 150 | 0.686818 | [
"MIT"
] | UE4DotNet/Plugin | DotNet/DotNet/UE4/Generated/Engine/ParticleModuleTrailSource.cs | 3,573 | C# |
#if XRMANAGEMENT_3_2_OR_NEWER
using UnityEngine;
using System;
using UnityEngine.XR.Management;
namespace Unity.MARS.XRSubsystem
{
/// <summary>
/// MARS XR Subsystems settings.
/// </summary>
[XRConfigurationData("MARS Simulation", MARSXRSubsystemLoader.SettingsKey)]
[Serializable]
public class MARSXRSubsystemSettings : ScriptableObject
{
}
}
#endif
| 21.5 | 79 | 0.726098 | [
"Apache-2.0"
] | bsides44/MARSGeofencing | MARS geofencing/Library/PackageCache/com.unity.mars-ar-foundation-providers@1.3.1/Editor/MARSXRSubsystem/MARSXRSubsystemSettings.cs | 389 | C# |
using BlazorMonacoYaml;
using System.Collections.Generic;
using Vs.VoorzieningenEnRegelingen.Site.ApiCalls;
namespace Vs.VoorzieningenEnRegelingen.Site.Model.Interfaces
{
public interface IEditorTabInfo : IYamlFileInfo
{
int TabId { get; set; }
int OrderNr { get; set; }
bool IsVisible { get; set; }
bool IsActive { get; set; }
bool HasChanges { get; }
bool HasExceptions { get; }
bool IsSaved { get; set; }
string DisplayName { get; }
string OriginalContent { get; set; }
string Content { get; set; }
string EditorId { get; }
IEnumerable<FormattingException> Exceptions { get; set; }
bool IsCompareMode { get; }
IYamlFileInfo CompareInfo { get; set; }
string CompareContent { get; set; }
MonacoEditorYaml MonacoEditorYaml { get; set; }
MonacoDiffEditorYaml MonacoDiffEditorYaml { get; set; }
void RemoveExceptions();
}
} | 33.793103 | 65 | 0.633673 | [
"MIT"
] | sjefvanleeuwen/morstead | src/Vs.VoorzieningenEnRegelingen.Site/Model/Interfaces/IEditorTabInfo.cs | 982 | C# |
namespace KK_Wardrobe
{
public enum Place
{
bathroom1f = 14,
bathroom2f = 15,
bathroom3f = 16,
bathroomm = 18,
lockerroom = 46,
shawerroom = 45 // This is how Illusion spelled it.
}
}
| 16.307692 | 54 | 0.622642 | [
"MIT"
] | FairBear/KK_Wardrobe | Constants/Place.cs | 214 | C# |
using System;
using Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed.Dependencies;
using Mono.Linker.Tests.Cases.Expectations.Assertions;
using Mono.Linker.Tests.Cases.Expectations.Metadata;
namespace Mono.Linker.Tests.Cases.Attributes.OnlyKeepUsed {
[KeepTypeForwarderOnlyAssemblies ("true")]
[SetupLinkerArgument ("--used-attrs-only", "true")]
[SetupCompileBefore ("library.dll", new[] { "Dependencies/UnusedAttributeWithTypeForwarderIsRemoved_Lib.cs" })]
[SetupCompileAfter ("implementation.dll", new[] { "Dependencies/UnusedAttributeWithTypeForwarderIsRemoved_Lib.cs" })]
[SetupCompileAfter ("library.dll", new[] { "Dependencies/UnusedAttributeWithTypeForwarderIsRemoved_Forwarder.cs" }, new[] { "implementation.dll" })]
[RemovedTypeInAssembly ("library.dll", typeof(UnusedAttributeWithTypeForwarderIsRemoved_LibAttribute))]
[RemovedTypeInAssembly ("implementation.dll", typeof (UnusedAttributeWithTypeForwarderIsRemoved_LibAttribute))]
class UnusedAttributeWithTypeForwarderIsRemoved {
static void Main ()
{
Method (null);
}
[Kept]
static void Method ([UnusedAttributeWithTypeForwarderIsRemoved_Lib ("")] string arg)
{
UnusedAttributeWithTypeForwarderIsRemoved_OtherUsedClass.UsedMethod ();
}
}
}
| 42.655172 | 149 | 0.795473 | [
"MIT"
] | GrabYourPitchforks/linker | test/Mono.Linker.Tests.Cases/Attributes/OnlyKeepUsed/UnusedAttributeWithTypeForwarderIsRemoved.cs | 1,239 | C# |
namespace SFA.DAS.ApplyService.Configuration
{
public interface IApplyConfig
{
InternalApiConfig InternalApi { get; set; }
string SignInPage { get; set; }
string SessionRedisConnectionString { get; set; }
string SessionCachingDatabase { get; set; }
string DataProtectionKeysDatabase { get; set; }
DfeSignInConfig DfeSignIn { get; set; }
string SqlConnectionString { get; set; }
FileStorageConfig FileStorage { get; set; }
NotificationsApiClientConfiguration NotificationsApiClientConfiguration { get; set; }
CompaniesHouseApiAuthentication CompaniesHouseApiAuthentication { get; set; }
OuterApiConfiguration OuterApiConfiguration { get; set; }
RoatpApiAuthentication RoatpApiAuthentication { get; set; }
QnaApiAuthentication QnaApiAuthentication { get; set; }
AzureActiveDirectoryConfiguration AzureActiveDirectoryConfiguration { get; set; }
FeatureToggles FeatureToggles { get; set; }
}
} | 35.482759 | 93 | 0.703596 | [
"MIT"
] | SkillsFundingAgency/das-assessor-apply | src/SFA.DAS.ApplyService.Configuration/IApplyConfig.cs | 1,029 | C# |
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using Microsoft.Xna.Framework;
using static Terraria.ModLoader.ModContent;
namespace BahiaMod.Items.Weapons
{
public class Atabaque : ModItem
{
public override void SetStaticDefaults()
{
Tooltip.SetDefault("Don't forget to bring it to the \"Roda\"");
}
public override void SetDefaults()
{
item.summon = true;
item.damage = 18;
item.width = 16;
item.height = 21;
item.useTime = 25;
item.useAnimation = 25;
item.useStyle = ItemUseStyleID.HoldingOut;
item.knockBack = 0;
item.value = Item.sellPrice(0,0,52,0);
item.shoot = mod.ProjectileType("BahiaNote");
item.shootSpeed = 4f;
item.rare = ItemRarityID.Orange;
item.autoReuse = true;
}
public override bool Shoot(Player player, ref Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack)
{
if (!Main.dedServ)
{
float cursorPosFromPlayer = (player.Distance(Main.MouseWorld) / ((Main.screenHeight / 2) / 24));
if (cursorPosFromPlayer > 24) cursorPosFromPlayer = 1;
else cursorPosFromPlayer = (cursorPosFromPlayer / 12) - 1;
if (cursorPosFromPlayer < 0) Main.PlaySound(SoundID.Item, (int)player.Center.X, (int)player.Center.Y, mod.GetSoundSlot(SoundType.Item, "Sounds/Item/AtabaqueKick"), 1, -cursorPosFromPlayer);
else Main.PlaySound(SoundID.Item, (int)player.Center.X, (int)player.Center.Y, mod.GetSoundSlot(SoundType.Item, "Sounds/Item/AtabaqueSnare"), 1, cursorPosFromPlayer);
}
return true;
}
}
} | 34.555556 | 193 | 0.713826 | [
"MIT"
] | lluckymou/BahiaMod | Items/Weapons/Atabaque.cs | 1,555 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using BenchmarkDotNet.Code;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Parameters;
using BenchmarkDotNet.Running;
namespace BenchmarkDotNet.Exporters
{
internal static class FullNameProvider
{
private static readonly IReadOnlyDictionary<Type, string> Aliases = new Dictionary<Type, string>
{
{ typeof(byte), "byte" },
{ typeof(sbyte), "sbyte" },
{ typeof(short), "short" },
{ typeof(ushort), "ushort" },
{ typeof(int), "int" },
{ typeof(uint), "uint" },
{ typeof(long), "long" },
{ typeof(ulong), "ulong" },
{ typeof(float), "float" },
{ typeof(double), "double" },
{ typeof(decimal), "decimal" },
{ typeof(object), "object" },
{ typeof(bool), "bool" },
{ typeof(char), "char" },
{ typeof(string), "string" },
{ typeof(byte?), "byte?" },
{ typeof(sbyte?), "sbyte?" },
{ typeof(short?), "short?" },
{ typeof(ushort?), "ushort?" },
{ typeof(int?), "int?" },
{ typeof(uint?), "uint?" },
{ typeof(long?), "long?" },
{ typeof(ulong?), "ulong?" },
{ typeof(float?), "float?" },
{ typeof(double?), "double?" },
{ typeof(decimal?), "decimal?" },
{ typeof(bool?), "bool?" },
{ typeof(char?), "char?" }
};
internal static string GetBenchmarkName(BenchmarkCase benchmarkCase)
{
var type = benchmarkCase.Descriptor.Type;
var method = benchmarkCase.Descriptor.WorkloadMethod;
// we can't just use type.FullName because we need sth different for generics (it reports SimpleGeneric`1[[System.Int32, mscorlib, Version=4.0.0.0)
var name = new StringBuilder();
if (!string.IsNullOrEmpty(type.Namespace))
name.Append(type.Namespace).Append('.');
name.Append(GetNestedTypes(type));
name.Append(GetTypeName(type)).Append('.');
name.Append(GetMethodName(benchmarkCase));
return name.ToString();
}
private static string GetNestedTypes(Type type)
{
string nestedTypes = "";
Type child = type, parent = type.DeclaringType;
while (child.IsNested && parent != null)
{
nestedTypes = parent.Name + "+" + nestedTypes;
child = parent;
parent = parent.DeclaringType;
}
return nestedTypes;
}
internal static string GetTypeName(Type type)
{
if (!type.IsGenericType)
return type.Name;
string mainName = type.Name.Substring(0, type.Name.IndexOf('`'));
string args = string.Join(", ", type.GetGenericArguments().Select(GetTypeName).ToArray());
return $"{mainName}<{args}>";
}
internal static string GetMethodName(BenchmarkCase benchmarkCase)
{
var name = new StringBuilder(benchmarkCase.Descriptor.WorkloadMethod.Name);
if (benchmarkCase.HasParameters)
name.Append(GetBenchmarkParameters(benchmarkCase.Descriptor.WorkloadMethod, benchmarkCase.Parameters));
return name.ToString();
}
private static string GetBenchmarkParameters(MethodInfo method, ParameterInstances benchmarkParameters)
{
var methodArguments = method.GetParameters();
var benchmarkParams = benchmarkParameters.Items.Where(parameter => !parameter.IsArgument).ToArray();
var parametersBuilder = new StringBuilder(methodArguments.Length * 20).Append('(');
for (int i = 0; i < methodArguments.Length; i++)
{
if (i > 0)
parametersBuilder.Append(", ");
parametersBuilder.Append(methodArguments[i].Name).Append(':').Append(' ');
parametersBuilder.Append(GetArgument(benchmarkParameters.GetArgument(methodArguments[i].Name).Value, methodArguments[i].ParameterType));
}
for (int i = 0; i < benchmarkParams.Length; i++)
{
var parameter = benchmarkParams[i];
if (methodArguments.Length > 0 || i > 0)
parametersBuilder.Append(", ");
parametersBuilder.Append(parameter.Name).Append(':').Append(' ');
parametersBuilder.Append(GetArgument(parameter.Value, parameter.Value?.GetType()));
}
return parametersBuilder.Append(')').ToString();
}
private static string GetArgument(object argumentValue, Type argumentType)
{
switch (argumentValue) {
case null:
return "null";
case IParam iparam:
return GetArgument(iparam.Value, argumentType);
case object[] array when array.Length == 1:
return GetArgument(array[0], argumentType);
case string text:
return $"\"{EscapeWhitespaces(text)}\"";
case char character:
return $"'{character}'";
case DateTime time:
return time.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
case Type type:
return $"typeof({GetTypeArgumentName(type)})";
}
if (argumentType != null && argumentType.IsArray)
return GetArray((IEnumerable)argumentValue);
return argumentValue.ToString();
}
// it's not generic so I can't simply use .Skip and all other LINQ goodness
private static string GetArray(IEnumerable collection)
{
var buffer = new StringBuilder().Append('[');
int index = 0;
foreach (var item in collection)
{
if (index > 0)
buffer.Append(", ");
if (index > 4)
{
buffer.Append("..."); // [0, 1, 2, 3, 4, ...]
break;
}
buffer.Append(GetArgument(item, item?.GetType()));
++index;
}
buffer.Append(']');
return buffer.ToString();
}
private static string EscapeWhitespaces(string text)
=> text.Replace("\t", "\\t")
.Replace("\r\n", "\\r\\n");
private static string GetTypeArgumentName(Type type)
{
if (Aliases.TryGetValue(type, out string alias))
return alias;
if (type.IsNullable())
return $"{GetTypeArgumentName(Nullable.GetUnderlyingType(type))}?";
if (!string.IsNullOrEmpty(type.Namespace))
return $"{type.Namespace}.{GetTypeName(type)}";
return GetTypeName(type);
}
}
}
| 35.593137 | 159 | 0.527751 | [
"MIT"
] | Dixin/BenchmarkDotNet | src/BenchmarkDotNet/Exporters/FullNameProvider.cs | 7,263 | C# |
namespace CL.Core.Domain;
public class Funcao
{
public int Id { get; set; }
public string Descricao { get; set; }
public ICollection<Usuario> Usuarios { get; set; }
} | 20.111111 | 54 | 0.662983 | [
"Apache-2.0"
] | NfeSistemas/Consultorio_Legal | CL.Core/Domain/Funcao.cs | 183 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using HilbertTransformationTests.Data;
using HilbertTransformation;
using Clustering;
namespace HilbertTransformationTests
{
[TestFixture]
/// <summary>
/// Test whether the test data generator does a good job.
/// </summary>
public class GaussianClusteringTests
{
/// <summary>
/// Test if the average distance of a point from the center of a randomnly generated spherical cluster
/// conforming to a Gaussian distribution is close to the expected value.
/// R = σ√D
/// where sigma is the standard deviation and D the number of dimensions.
/// </summary>
[Test]
public void VerifyGaussianRadius()
{
Logger.SetupForTests();
int maxCoordinate = 10000;
var N = new[] { 100, 200, 500, 1000, 2000 };
var D = new[] { 20, 50, 100, 200, 500, 1000, 2000 };
var SIGMAS = new[] { 100, 200, 500, 1000, 2000 };
var failures = "";
var failureCount = 0;
var maxPercentile = 0.0;
var minPercentile = 100.0;
var withinFivePercentCount = 0;
var totalCount = 0;
foreach( var n in N)
foreach(var d in D)
foreach(var sigma in SIGMAS)
{
var expectedRadius = sigma * Math.Sqrt(d);
var percentile = GaussianRadiusPercentile(n, d, maxCoordinate, sigma, expectedRadius);
maxPercentile = Math.Max(maxPercentile, percentile);
minPercentile = Math.Min(minPercentile, percentile);
var success = percentile >= 35 && percentile <= 75;
if (!success)
{
failureCount++;
var errorMessage = $"Wrong radius for N = {n}, D = {d}, Sigma = {sigma}. Expected R = {expectedRadius}. Percentile = {percentile}";
failures += errorMessage + "\n";
Logger.Error(errorMessage);
}
else
{
var message = $"Correct radius for N = {n}, D = {d}, Sigma = {sigma}. Expected R = {expectedRadius}. Percentile = {percentile}";
Logger.Info(message);
}
totalCount++;
if (percentile >= 45 && percentile <= 55)
withinFivePercentCount++;
}
Logger.Info($"Percentiles ranged from {minPercentile} % to {maxPercentile} %");
Logger.Info($"Within five percent: {withinFivePercentCount} of {totalCount} total tests");
if (failureCount > 0)
Logger.Error($"{failureCount} failures");
else
Logger.Info("NO failures!");
Assert.AreEqual(0, failureCount, failures);
}
/// <summary>
/// Generate a sperical cluster of points conforming to a Gaussian distribution,
/// get the distances from each point to the centroid, and compute the deciles
/// for distance.
/// </summary>
/// <param name="n">Number of points.</param>
/// <param name="dimensions">Dimensions per point.</param>
/// <param name="maxCoordinate">Largest value permitted for a coordinate.</param>
/// <param name="sigma">Standard deviation used in the Guassian.</param>
/// <returns>An array of eleven values.
/// The first entry is the minimum distance from the cluster center to any point.
/// The last entry is the maximum value.
/// At index five is the mean.</returns>
static double[] GaussianRadiusDeciles(int n, int dimensions, int maxCoordinate, int sigma)
{
var distances = GaussianRadiusDistances(n, dimensions, maxCoordinate, sigma);
return Enumerable.Range(0, 11).Select(decile => distances[((n - 1) * decile) / 10]).ToArray();
}
/// <summary>
/// Compute the percentile of distances at which the given distance falls.
/// The distances are from points in a cluster to the center of the cluster.
/// </summary>
/// <param name="n">Numbner of points.</param>
/// <param name="dimensions">Number of dimensions.</param>
/// <param name="maxCoordinate">Maximum coordinate value.</param>
/// <param name="sigma">Standard deviation of coordinate spread.</param>
/// <param name="expectedRadius">Expected average distance from center to points in cluster.</param>
/// <returns> A percentile value, from zero to one hundred.</returns>
static double GaussianRadiusPercentile(int n, int dimensions, int maxCoordinate, int sigma, double expectedRadius)
{
var distances = GaussianRadiusDistances(n, dimensions, maxCoordinate, sigma);
var position = distances.BinarySearch(expectedRadius);
if (position < 0) position = ~position;
return 100.0 * position / n;
}
static List<double> GaussianRadiusDistances(int n, int dimensions, int maxCoordinate, int sigma)
{
var center = Enumerable.Range(0, dimensions).Select(i => maxCoordinate / 2).ToArray();
var deviations = Enumerable.Range(0, dimensions).Select(i => (double)sigma).ToArray();
var affectedIndices = Enumerable.Range(0, dimensions).ToArray();
var generator = new EllipsoidalGenerator(center, deviations, affectedIndices);
var tempPoint = new int[dimensions];
var centerPoint = new UnsignedPoint(center);
var points = Enumerable.Range(0, n).Select(i => new UnsignedPoint(generator.Generate(tempPoint))).ToList();
var distances = points.Select(p => centerPoint.Distance(p)).OrderBy(dist => dist).ToList();
return distances;
}
}
}
| 49.854839 | 159 | 0.573115 | [
"MIT"
] | paulchernoch/HilbertTransformation | HilbertTransformationTests/GaussianClusteringTests.cs | 6,187 | C# |
using System.Web.Http;
using System.Web.Mvc;
namespace NotifyWebApi.Areas.HelpPage
{
public class HelpPageAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "HelpPage";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HelpPage_Default",
"Help/{action}/{apiId}",
new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });
HelpPageConfig.Register(GlobalConfiguration.Configuration);
}
}
} | 25.769231 | 94 | 0.564179 | [
"MIT"
] | 1804-Apr-USFdotnet/Project2-TLM_Notifiy | NotifyWebApi/NotifyWebApi/Areas/HelpPage/HelpPageAreaRegistration.cs | 670 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Health.Core;
using Microsoft.Health.Fhir.Core.Features.Definition;
using Microsoft.Health.Fhir.Core.Features.Search.Parameters;
using Microsoft.Health.Fhir.Core.Features.Search.Registry;
using Microsoft.Health.Fhir.Core.Messages.Search;
using Microsoft.Health.Fhir.Core.Models;
using Microsoft.Health.Fhir.ValueSets;
using NSubstitute;
using Xunit;
namespace Microsoft.Health.Fhir.Core.UnitTests.Features.Search.Registry
{
public class SearchParameterStatusManagerTests
{
private static readonly string ResourceId = "http://hl7.org/fhir/SearchParameter/Resource-id";
private static readonly string ResourceLastupdated = "http://hl7.org/fhir/SearchParameter/Resource-lastUpdated";
private static readonly string ResourceProfile = "http://hl7.org/fhir/SearchParameter/Resource-profile";
private static readonly string ResourceSecurity = "http://hl7.org/fhir/SearchParameter/Resource-security";
private static readonly string ResourceQuery = "http://hl7.org/fhir/SearchParameter/Resource-query";
private readonly SearchParameterStatusManager _manager;
private readonly ISearchParameterStatusDataStore _searchParameterStatusDataStore;
private readonly ISearchParameterDefinitionManager _searchParameterDefinitionManager;
private readonly IMediator _mediator;
private readonly SearchParameterInfo[] _searchParameterInfos;
private readonly SearchParameterInfo _queryParameter;
private readonly ISearchParameterSupportResolver _searchParameterSupportResolver;
private readonly ResourceSearchParameterStatus[] _resourceSearchParameterStatuses;
public SearchParameterStatusManagerTests()
{
_searchParameterStatusDataStore = Substitute.For<ISearchParameterStatusDataStore>();
_searchParameterDefinitionManager = Substitute.For<ISearchParameterDefinitionManager>();
_searchParameterSupportResolver = Substitute.For<ISearchParameterSupportResolver>();
_mediator = Substitute.For<IMediator>();
_manager = new SearchParameterStatusManager(
_searchParameterStatusDataStore,
_searchParameterDefinitionManager,
_searchParameterSupportResolver,
_mediator,
NullLogger<SearchParameterStatusManager>.Instance);
_resourceSearchParameterStatuses = new[]
{
new ResourceSearchParameterStatus
{
Status = SearchParameterStatus.Enabled,
Uri = new Uri(ResourceId),
LastUpdated = Clock.UtcNow,
},
new ResourceSearchParameterStatus
{
Status = SearchParameterStatus.Enabled,
Uri = new Uri(ResourceLastupdated),
IsPartiallySupported = true,
LastUpdated = Clock.UtcNow,
},
new ResourceSearchParameterStatus
{
Status = SearchParameterStatus.Disabled,
Uri = new Uri(ResourceProfile),
LastUpdated = Clock.UtcNow,
},
new ResourceSearchParameterStatus
{
Status = SearchParameterStatus.Supported,
Uri = new Uri(ResourceSecurity),
LastUpdated = Clock.UtcNow,
},
};
_searchParameterStatusDataStore.GetSearchParameterStatuses(Arg.Any<CancellationToken>()).Returns(_resourceSearchParameterStatuses);
List<string> baseResourceTypes = new List<string>() { "Resource" };
List<string> targetResourceTypes = new List<string>() { "Patient" };
_queryParameter = new SearchParameterInfo("_query", "_query", SearchParamType.Token, new Uri(ResourceQuery));
_searchParameterInfos = new[]
{
new SearchParameterInfo("_id", "_id", SearchParamType.Token, new Uri(ResourceId), targetResourceTypes: targetResourceTypes, baseResourceTypes: baseResourceTypes),
new SearchParameterInfo("_lastUpdated", "_lastUpdated", SearchParamType.Token, new Uri(ResourceLastupdated), targetResourceTypes: targetResourceTypes, baseResourceTypes: baseResourceTypes),
new SearchParameterInfo("_profile", "_profile", SearchParamType.Token, new Uri(ResourceProfile), targetResourceTypes: targetResourceTypes),
new SearchParameterInfo("_security", "_security", SearchParamType.Token, new Uri(ResourceSecurity), targetResourceTypes: targetResourceTypes),
_queryParameter,
};
_searchParameterDefinitionManager.GetSearchParameters("Account")
.Returns(_searchParameterInfos);
_searchParameterDefinitionManager.AllSearchParameters
.Returns(_searchParameterInfos);
_searchParameterDefinitionManager.GetSearchParameter(ResourceQuery)
.Returns(_queryParameter);
_searchParameterSupportResolver
.IsSearchParameterSupported(Arg.Any<SearchParameterInfo>())
.Returns((false, false));
_searchParameterSupportResolver
.IsSearchParameterSupported(Arg.Is(_searchParameterInfos[4]))
.Returns((true, false));
}
[Fact]
public async Task GivenASPStatusManager_WhenInitializing_ThenSearchParameterIsUpdatedFromRegistry()
{
await _manager.EnsureInitializedAsync(CancellationToken.None);
var list = _searchParameterDefinitionManager.GetSearchParameters("Account").ToList();
Assert.True(list[0].IsSearchable);
Assert.True(list[0].IsSupported);
Assert.False(list[0].IsPartiallySupported);
Assert.True(list[1].IsSearchable);
Assert.True(list[1].IsSupported);
Assert.True(list[1].IsPartiallySupported);
Assert.False(list[2].IsSearchable);
Assert.False(list[2].IsSupported);
Assert.False(list[2].IsPartiallySupported);
Assert.False(list[3].IsSearchable);
Assert.True(list[3].IsSupported);
Assert.False(list[3].IsPartiallySupported);
Assert.False(list[4].IsSearchable);
Assert.True(list[4].IsSupported);
Assert.False(list[4].IsPartiallySupported);
}
[Fact]
public async Task GivenASPStatusManager_WhenInitializing_ThenUpdatedSearchParametersInNotification()
{
await _manager.EnsureInitializedAsync(CancellationToken.None);
// Id should not be modified in this test case
var modifiedItems = _searchParameterInfos.Skip(1).ToArray();
await _mediator
.Received()
.Publish(
Arg.Is<SearchParametersUpdatedNotification>(x => modifiedItems.Except(x.SearchParameters).Any() == false),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task GivenASPStatusManager_WhenInitializing_ThenRegistryShouldNotUpdateNewlyFoundParameters()
{
await _manager.EnsureInitializedAsync(CancellationToken.None);
await _searchParameterStatusDataStore
.DidNotReceive()
.UpsertStatuses(Arg.Any<List<ResourceSearchParameterStatus>>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GivenASPStatusManager_WhenInitializingAndResolverThrowsException_ThenCatchItAndReturnFalse()
{
_searchParameterSupportResolver
.IsSearchParameterSupported(Arg.Is(_searchParameterInfos[2]))
.Returns(x => throw new FormatException("Unable to resolve"));
await _manager.EnsureInitializedAsync(CancellationToken.None);
var list = _searchParameterDefinitionManager.GetSearchParameters("Account").ToList();
_searchParameterSupportResolver.Received(1).IsSearchParameterSupported(Arg.Is(_searchParameterInfos[2]));
Assert.False(list[2].IsSearchable);
Assert.False(list[2].IsSupported);
Assert.False(list[2].IsPartiallySupported);
}
}
}
| 47.904255 | 205 | 0.647346 | [
"MIT"
] | BearerPipelineTest/fhir-server | src/Microsoft.Health.Fhir.Core.UnitTests/Features/Search/Registry/SearchParameterStatusManagerTests.cs | 9,008 | C# |
namespace ETradeApiV1.Client.Dtos
{
public class Product
{
public string symbol { get; set; }
public string securityType { get; set; }
}
} | 20.875 | 48 | 0.610778 | [
"Apache-2.0"
] | omermina/ETradeApiV1 | ETradeApiV1.Client/Dtos/Product.cs | 169 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 26.01.2021.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.CastAs.SET_001.Double.String{
////////////////////////////////////////////////////////////////////////////////
using T_SOURCE_VALUE=System.Double;
using T_TARGET_VALUE=System.String;
using T_SOURCE_VALUE_U=System.Double;
////////////////////////////////////////////////////////////////////////////////
//class TestSet__002__const
public static class TestSet__002__const
{
private const string c_NameOf__TABLE="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_SOURCE="COL_DOUBLE";
private const int c_TARGET_VCH_LENGTH=32;
private const T_SOURCE_VALUE_U c_SRC_MIN=T_SOURCE_VALUE_U.MinValue;
private const T_SOURCE_VALUE_U c_SRC_MAX=T_SOURCE_VALUE_U.MaxValue;
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_SOURCE)]
public T_SOURCE_VALUE COL_SOURCE { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__m1_6()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=-1.6;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '-1.600000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001__m1_6
//-----------------------------------------------------------------------
[Test]
public static void Test_002__m1_5()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=-1.5;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '-1.500000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002__m1_5
//-----------------------------------------------------------------------
[Test]
public static void Test_003__m1_4()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=-1.4;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '-1.400000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_003__m1_4
//-----------------------------------------------------------------------
[Test]
public static void Test_004__m1()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=-1;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '-1.000000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_004__m1
//-----------------------------------------------------------------------
[Test]
public static void Test_005__zero()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=0;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '0.000000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_005__zero
//-----------------------------------------------------------------------
[Test]
public static void Test_006__p1()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=+1;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '1.000000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_006__p1
//-----------------------------------------------------------------------
[Test]
public static void Test_007__p1_4()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=1.4;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '1.400000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_007__p1_4
//-----------------------------------------------------------------------
[Test]
public static void Test_008__p1_5()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=1.5;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '1.500000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_008__p1_5
//-----------------------------------------------------------------------
[Test]
public static void Test_009__p1_6()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=1.6;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '1.600000000000000') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_009__p1_6
//-----------------------------------------------------------------------
[Test]
public static void Test_A001__p123456789_123456789()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=123456789.123456789;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '123456789.1234568') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_A001__p123456789_123456789
//-----------------------------------------------------------------------
[Test]
public static void Test_MM001__MIN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=c_SRC_MIN;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '-1.797693134862316e+308') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_MM001__MIN
//-----------------------------------------------------------------------
[Test]
public static void Test_MM002__MAX()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_SOURCE_VALUE_U c_valueSource_=c_SRC_MAX;
System.Int64? testID=Helper__InsertRow(db,c_valueSource_);
var recs=db.testTable.Where(r => (T_TARGET_VALUE)(object)r.COL_SOURCE==(T_TARGET_VALUE)(object)(c_valueSource_) && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_valueSource_,
r.COL_SOURCE);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_SOURCE).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N_AS_VCH("t",c_NameOf__COL_SOURCE,c_TARGET_VCH_LENGTH).T(" = _utf8 '1.797693134862316e+308') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_MM002__MAX
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_SOURCE_VALUE valueForColSource)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_SOURCE =valueForColSource;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_SOURCE).T(")").EOL()
.T("VALUES (").P("p0").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p1").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet__002__const
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.CastAs.SET_001.Double.String
| 25.661917 | 177 | 0.570289 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/CastAs/SET_001/Double/String/TestSet__002__const.cs | 19,813 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Security;
public class UserCode
{
[SecuritySafeCritical]
public static bool StubCriticalCallTransparent()
{
bool retVal = true;
try
{
retVal = CriticalCallTransparent();
if (!retVal)
{
TestLibrary.TestFramework.LogError("001", "Transparent UserCode should be able to call SecurityTreatAsSafe PlatformCode");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static bool CriticalCallTransparent()
{
return true;
}
}
| 18.410256 | 126 | 0.721448 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/Regressions/coreclr/0341/usercode.cs | 718 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.