source
stringclasses
1 value
id
stringlengths
40
40
language
stringclasses
2 values
date
stringclasses
1 value
author
stringclasses
1 value
url
stringclasses
1 value
title
stringclasses
1 value
extra
stringlengths
528
1.53k
quality_signals
stringlengths
139
178
text
stringlengths
6
1.05M
TheStack
b401bb938330aff12d85b18793e0df46158d6c59
C#code:C#
{"size": 508, "ext": "cs", "max_stars_repo_path": "tests/Simple/mcs/gtest-anontype-07.cs", "max_stars_repo_name": "GrapeCity/pagefx", "max_stars_repo_stars_event_min_datetime": "2019-08-03T09:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T20:32:30.000Z", "max_issues_repo_path": "tests/Simple/mcs/gtest-anontype-07.cs", "max_issues_repo_name": "GrapeCity/pagefx", "max_issues_repo_issues_event_min_datetime": "2021-11-22T21:39:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T04:52:41.000Z", "max_forks_repo_path": "tests/Simple/mcs/gtest-anontype-07.cs", "max_forks_repo_name": "GrapeCity/pagefx", "max_forks_repo_forks_event_min_datetime": "2019-07-31T09:50:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T16:30:12.000Z"}
{"max_stars_count": 18.0, "max_issues_count": 1.0, "max_forks_count": 2.0, "avg_line_length": 16.3870967742, "max_line_length": 44, "alphanum_fraction": 0.4488188976}
using System; using System.Collections; public class Test { static void Main () { Console.WriteLine(Test1()); Console.WriteLine("<%END%>"); } private static int Test1() { var v1 = new { }; var v2 = new { }; if (v1.GetType () != v2.GetType ()) return 1; if (!v1.Equals (v2)) return 2; Console.WriteLine (v1); Console.WriteLine (v2); return 0; } }
TheStack
b40259cb5da6bfd8ced02197b3bab1b727b0d3b8
C#code:C#
{"size": 2330, "ext": "cs", "max_stars_repo_path": "src/MyLab.Search.EsAdapter/IEsClientProvider.cs", "max_stars_repo_name": "mylab-search-fx/es-adapter", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyLab.Search.EsAdapter/IEsClientProvider.cs", "max_issues_repo_name": "mylab-search-fx/es-adapter", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyLab.Search.EsAdapter/IEsClientProvider.cs", "max_forks_repo_name": "mylab-search-fx/es-adapter", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.1797752809, "max_line_length": 81, "alphanum_fraction": 0.556223176}
using System; using Elasticsearch.Net; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MyLab.Log.Dsl; using Nest; namespace MyLab.Search.EsAdapter { /// <summary> /// Holds connection with ES /// </summary> public interface IEsClientProvider { /// <summary> /// Provides /// </summary> /// <returns></returns> ElasticClient Provide(); } class EsClientProvider : IEsClientProvider, IDisposable { private readonly IConnectionPool _connectionPool; private readonly ElasticClient _client; /// <summary> /// Initializes a new instance of <see cref="IEsClientProvider"/> /// </summary> public EsClientProvider( ElasticsearchOptions options, ILogger<EsClientProvider> logger = null) { _connectionPool = new SingleNodeConnectionPool(new Uri(options.Url)); var settings = new ConnectionSettings(_connectionPool); if (logger != null) { var log = logger.Dsl(); settings.DisableDirectStreaming(); settings.OnRequestCompleted(details => { log.Debug("ElasticSearch request completed") .AndFactIs("dump", ApiCallDumper.ApiCallToDump(details)) .Write(); }); } _client = new ElasticClient(settings); } /// <summary> /// Initializes a new instance of <see cref="IEsClientProvider"/> /// </summary> public EsClientProvider( IOptions<ElasticsearchOptions> options, ILogger<EsClientProvider> logger = null) : this(options.Value, logger) { } public ElasticClient Provide() { return _client; } public void Dispose() { _connectionPool?.Dispose(); } } public class SingleEsClientProvider : IEsClientProvider { private readonly ElasticClient _client; public SingleEsClientProvider(ElasticClient client) { _client = client; } public ElasticClient Provide() { return _client; } } }
TheStack
b4044a7f09a14c8c0bd6b6a273e7f893dbd33dca
C#code:C#
{"size": 7198, "ext": "cs", "max_stars_repo_path": "src/AElf.Contracts.Genesis/BasicContractZero.cs", "max_stars_repo_name": "quangdo3112/AElf", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/AElf.Contracts.Genesis/BasicContractZero.cs", "max_issues_repo_name": "quangdo3112/AElf", "max_issues_repo_issues_event_min_datetime": "2019-05-07T22:13:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T22:13:41.000Z", "max_forks_repo_path": "src/AElf.Contracts.Genesis/BasicContractZero.cs", "max_forks_repo_name": "quangdo3112/AElf", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 33.0183486239, "max_line_length": 117, "alphanum_fraction": 0.5880800222}
using System; using AElf.Kernel; using AElf.Kernel.KernelAccount; using AElf.Sdk.CSharp; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; namespace AElf.Contracts.Genesis { public class BasicContractZero : BasicContractZeroContainer.BasicContractZeroBase, ISmartContractZero { #region Views public override UInt64Value CurrentContractSerialNumber(Empty input) { return new UInt64Value() {Value = State.ContractSerialNumber.Value}; } public override Kernel.ContractInfo GetContractInfo(Address input) { var info = State.ContractInfos[input]; if (info == null) { return new Kernel.ContractInfo(); } return info; } public override Address GetContractOwner(Address input) { var info = State.ContractInfos[input]; return info?.Owner; } public override Hash GetContractHash(Address input) { var info = State.ContractInfos[input]; return info?.CodeHash; } public override Address GetContractAddressByName(Hash input) { return State.NameAddressMapping[input]; } public override SmartContractRegistration GetSmartContractRegistrationByAddress(Address input) { var info = State.ContractInfos[input]; if (info == null) { return null; } return State.SmartContractRegistrations[info.CodeHash]; } #endregion Views #region Actions public override Address DeploySystemSmartContract(SystemContractDeploymentInput input) { var name = input.Name; var category = input.Category; var code = input.Code.ToByteArray(); var transactionMethodCallList = input.TransactionMethodCallList; var address = PrivateDeploySystemSmartContract(name, category, code); foreach (var methodCall in transactionMethodCallList.Value) { Context.SendInline(address, methodCall.MethodName, methodCall.Params); } return address; } private Address PrivateDeploySystemSmartContract(Hash name, int category, byte[] code) { if (name != null) Assert(State.NameAddressMapping[name] == null, "contract name already been registered"); var serialNumber = State.ContractSerialNumber.Value; // Increment State.ContractSerialNumber.Value = serialNumber + 1; var contractAddress = AddressHelper.BuildContractAddress(Context.ChainId, serialNumber); var codeHash = Hash.FromRawBytes(code); var info = new ContractInfo { SerialNumber = serialNumber, Owner = Context.Sender, Category = category, CodeHash = codeHash }; State.ContractInfos[contractAddress] = info; var reg = new SmartContractRegistration { Category = category, Code = ByteString.CopyFrom(code), CodeHash = codeHash }; State.SmartContractRegistrations[reg.CodeHash] = reg; Context.DeployContract(contractAddress, reg, name); Context.Fire(new ContractDeployed() { CodeHash = codeHash, Address = contractAddress, Creator = Context.Sender }); Context.LogDebug(() => "BasicContractZero - Deployment ContractHash: " + codeHash.ToHex()); Context.LogDebug(() => "BasicContractZero - Deployment success: " + contractAddress.GetFormatted()); if (name != null) State.NameAddressMapping[name] = contractAddress; return contractAddress; } public override Address DeploySmartContract(ContractDeploymentInput input) { return DeploySystemSmartContract(new SystemContractDeploymentInput() { Category = input.Category, Code = input.Code, TransactionMethodCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList() }); } public override Address UpdateSmartContract(ContractUpdateInput input) { var contractAddress = input.Address; var code = input.Code.ToByteArray(); var info = State.ContractInfos[contractAddress]; Assert(info != null, "Contract does not exist."); Assert(info.Owner.Equals(Context.Sender), "Only owner is allowed to update code."); var oldCodeHash = info.CodeHash; var newCodeHash = Hash.FromRawBytes(code); Assert(!oldCodeHash.Equals(newCodeHash), "Code is not changed."); info.CodeHash = newCodeHash; State.ContractInfos[contractAddress] = info; var reg = new SmartContractRegistration { Category = info.Category, Code = ByteString.CopyFrom(code), CodeHash = newCodeHash }; State.SmartContractRegistrations[reg.CodeHash] = reg; Context.UpdateContract(contractAddress, reg, null); Context.Fire(new CodeUpdated() { Address = contractAddress, OldCodeHash = oldCodeHash, NewCodeHash = newCodeHash }); Context.LogDebug(() => "BasicContractZero - update success: " + contractAddress.GetFormatted()); return contractAddress; } public override Empty ChangeContractOwner(ChangeContractOwnerInput input) { var contractAddress = input.ContractAddress; var newOwner = input.NewOwner; var info = State.ContractInfos[contractAddress]; Assert(info != null && info.Owner.Equals(Context.Sender), "no permission."); var oldOwner = info.Owner; info.Owner = input.NewOwner; State.ContractInfos[contractAddress] = info; Context.Fire(new OwnerChanged { Address = contractAddress, OldOwner = oldOwner, NewOwner = newOwner }); return new Empty(); } #endregion Actions } public static class AddressHelper { /// <summary> /// /// </summary> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public static Address BuildContractAddress(Hash chainId, ulong serialNumber) { var hash = Hash.FromTwoHashes(chainId, Hash.FromRawBytes(serialNumber.ToBytes())); return Address.FromBytes(hash.DumpByteArray()); } public static Address BuildContractAddress(int chainId, ulong serialNumber) { return BuildContractAddress(chainId.ComputeHash(), serialNumber); } } }
TheStack
b4046bf38c1b46ad0c6c23068b866b772e295162
C#code:C#
{"size": 1101, "ext": "cs", "max_stars_repo_path": "src/Ggj2020/Assets/Scripts/CarSystem/CarData.cs", "max_stars_repo_name": "sqeezy/ggj2020", "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:05:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:05:47.000Z", "max_issues_repo_path": "src/Ggj2020/Assets/Scripts/CarSystem/CarData.cs", "max_issues_repo_name": "sqeezy/ggj2020", "max_issues_repo_issues_event_min_datetime": "2020-01-31T08:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-21T05:48:31.000Z", "max_forks_repo_path": "src/Ggj2020/Assets/Scripts/CarSystem/CarData.cs", "max_forks_repo_name": "sqeezy/ggj2020", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 28.0, "max_forks_count": null, "avg_line_length": 19.6607142857, "max_line_length": 61, "alphanum_fraction": 0.7511353315}
using System; using System.Data.Common; using CarSystem; using UnityEngine; using Random = System.Random; public class CarData { public Vector3 Position; public float Velocity; public float RotationVelocity; public CarAcceleration Acceleration; public CarStearing Stearing; public uint ArmorLevel; public WeaponData WeaponData; public event Action DataChanged = () => { }; private static readonly Random Rng = new Random(); public int PlayerId { get; } = Rng.Next(); public void SetPosition(Vector3 newPosition) { Position = newPosition; DataChanged(); } public void SetRotationVelocity(float newRotationVelocity) { RotationVelocity = newRotationVelocity; DataChanged(); } public void SetVelocity(float newVelocity) { Velocity = newVelocity; DataChanged(); } public void SetAcceleration(CarAcceleration newAcceleration) { Acceleration = newAcceleration; DataChanged(); } public void SetStearing(CarStearing newStearing) { Stearing = newStearing; DataChanged(); } public void SetArmorLevel(uint armor) { ArmorLevel = armor; DataChanged(); } }
TheStack
b404f7c589dbb033ea316cf99118d3079614a9c3
C#code:C#
{"size": 1218, "ext": "cs", "max_stars_repo_path": "ShortcutHelper/Exceptions/ExceptionHelper.cs", "max_stars_repo_name": "OIL1I/ApplicationLauncher", "max_stars_repo_stars_event_min_datetime": "2022-01-01T19:45:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T19:45:28.000Z", "max_issues_repo_path": "ShortcutHelper/Exceptions/ExceptionHelper.cs", "max_issues_repo_name": "OIL1I/ApplicationLauncher", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShortcutHelper/Exceptions/ExceptionHelper.cs", "max_forks_repo_name": "OIL1I/ApplicationLauncher", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.8, "max_line_length": 110, "alphanum_fraction": 0.6165845649}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exceptions { public class ExceptionHelper { private List<Exception> _Exceptions; public ExceptionHelper() { _Exceptions = new List<Exception>(); } public IEnumerator<Exception> GetExceptions() => _Exceptions.GetEnumerator(); public Exception GetLastException() => _Exceptions.Last(); public Exception[] GetLastExceptions(int count) { if (count > _Exceptions.Count) throw new ArgumentOutOfRangeException(nameof(count)); List<Exception> result = new List<Exception>(); for (int i = _Exceptions.Count - count; i < _Exceptions.Count; i++) result.Add(_Exceptions[i]); return result.ToArray(); } public Exception GetException(int index) { if (index < 0 || index > _Exceptions.Count) throw new ArgumentOutOfRangeException(nameof(index)); return _Exceptions[index]; } public void OnEception(Exception exception) => _Exceptions.Add(exception); } }
TheStack
b4055047d8267a9cb50a078489bcd201de7d5020
C#code:C#
{"size": 334, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/JumpPlatforms.cs", "max_stars_repo_name": "andywater01/Assignment-3", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/JumpPlatforms.cs", "max_issues_repo_name": "andywater01/Assignment-3", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/JumpPlatforms.cs", "max_forks_repo_name": "andywater01/Assignment-3", "max_forks_repo_forks_event_min_datetime": "2021-11-01T18:54:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T18:54:46.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 23.8571428571, "max_line_length": 105, "alphanum_fraction": 0.748502994}
using System.Collections; using System.Collections.Generic; using UnityEngine; public class JumpPlatforms : MonoBehaviour { public float jumpForce = 5.0f; private void OnCollisionEnter2D(Collision2D col) { col.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse); } }
TheStack
b40584f4c869fd7cfa01614d03cf36c066c601d1
C#code:C#
{"size": 2785, "ext": "cs", "max_stars_repo_path": "src/FoodSplitApp/Model/Balance/BalanceBook.cs", "max_stars_repo_name": "balukin/slack-food-split", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FoodSplitApp/Model/Balance/BalanceBook.cs", "max_issues_repo_name": "balukin/slack-food-split", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FoodSplitApp/Model/Balance/BalanceBook.cs", "max_forks_repo_name": "balukin/slack-food-split", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.3837209302, "max_line_length": 124, "alphanum_fraction": 0.5540394973}
using System; using System.Collections.Generic; using System.Linq; using FoodSplitApp.Errors; namespace FoodSplitApp.Model.Balance { public class BalanceBook { public DateTimeOffset LastChange { get; set; } public Dictionary<string, PairBalance> Balances { get; set; } public BalanceBook() { Balances = new Dictionary<string, PairBalance>(); } /// <summary> /// Increases debtor's debt to creditor by specific amount. /// </summary> /// <param name="debtor">User losing credit.</param> /// <param name="creditor">User gaining credit.</param> /// <param name="amtLost">Positive number, amount of money lost.</param> /// <returns>New balance state.</returns> public PairBalance AddDebt(FoodUser debtor, FoodUser creditor, decimal amtLost) { if (debtor.UniqueId == creditor.UniqueId) { throw new BadRequestException("You can't add debt to yourself."); } var pair = GetBalance(debtor, creditor); pair.AddDebt(debtor, amtLost); LastChange = DateTimeOffset.UtcNow; return pair; } /// <summary> /// Returns balance between the given user pair. /// </summary> public PairBalance GetBalance(FoodUser a, FoodUser b) { var pairKey = PairBalance.CreateKey(a, b); if (!Balances.ContainsKey(pairKey)) { Balances.Add(pairKey, new PairBalance(a, b)); } return Balances[pairKey]; } /// <summary> /// Returns person that owes the most (in total to all others) or null if balance book is empty or everyone is even. /// </summary> public (FoodUser debtor, decimal totalDebt) FindBiggestDebtor() { var totalDebt = new Dictionary<string, decimal>(); var debtorLookup = new Dictionary<string, FoodUser>(); if (Balances.Count == 0) { return (null, 0); } foreach (var pair in Balances.Values) { var (debtor, debtValue) = pair.GetDebt(); if (!totalDebt.ContainsKey(debtor.UniqueId)) { totalDebt.Add(debtor.UniqueId, 0); } totalDebt[debtor.UniqueId] += debtValue; // Store for future reference debtorLookup[debtor.UniqueId] = debtor; } var biggestDebt = totalDebt.OrderByDescending(pair => pair.Value).First(); return biggestDebt.Value == 0 ? (null, 0) : (debtorLookup[biggestDebt.Key], biggestDebt.Value); } } }
TheStack
b407b32e66e54589ba85ab9801f348543ffdbcea
C#code:C#
{"size": 1154, "ext": "cs", "max_stars_repo_path": "sources/Leak.Common/PeerHash.cs", "max_stars_repo_name": "sora-jp/leak", "max_stars_repo_stars_event_min_datetime": "2016-05-15T18:09:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T11:36:34.000Z", "max_issues_repo_path": "sources/Leak.Common/PeerHash.cs", "max_issues_repo_name": "sora-jp/leak", "max_issues_repo_issues_event_min_datetime": "2016-12-08T07:51:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-23T20:32:21.000Z", "max_forks_repo_path": "sources/Leak.Common/PeerHash.cs", "max_forks_repo_name": "sora-jp/leak", "max_forks_repo_forks_event_min_datetime": "2016-11-05T15:32:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T09:45:50.000Z"}
{"max_stars_count": 76.0, "max_issues_count": 9.0, "max_forks_count": 25.0, "avg_line_length": 21.7735849057, "max_line_length": 69, "alphanum_fraction": 0.4948006932}
namespace Leak.Common { public class PeerHash { private readonly byte[] value; public PeerHash(byte[] value) { this.value = value; } public byte[] ToBytes() { return value; } public byte this[int index] { get { return value[index]; } } public override int GetHashCode() { return value[14] * 256 + value[15]; } public override bool Equals(object obj) { PeerHash other = obj as PeerHash; return other != null && Bytes.Equals(other.value, value); } public override string ToString() { return Bytes.ToString(value); } public static PeerHash Random() { return new PeerHash(Bytes.Random(20)); } public static PeerHash Random(string prefix) { byte[] value = Bytes.Parse(prefix); byte[] random = Bytes.Random(20 - value.Length); Bytes.Append(ref value, random); return new PeerHash(value); } } }
TheStack
b40845a8c9ec6b030b3de9e21fa95741383b1130
C#code:C#
{"size": 731, "ext": "cs", "max_stars_repo_path": "Arrays/MaximumSumOfElements/MaximumSumOfElements.cs", "max_stars_repo_name": "froddo/CSharp-More", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Arrays/MaximumSumOfElements/MaximumSumOfElements.cs", "max_issues_repo_name": "froddo/CSharp-More", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Arrays/MaximumSumOfElements/MaximumSumOfElements.cs", "max_forks_repo_name": "froddo/CSharp-More", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.4583333333, "max_line_length": 103, "alphanum_fraction": 0.6032831737}
/*Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum.*/ using System; class MaximumSumOfElements { static void Main() { Console.WriteLine("Enter two integers number for K < N: "); Console.Write("Enter integer number for N: "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter integer number for K: "); int k = int.Parse(Console.ReadLine()); int[] array = new int[n]; Console.WriteLine("Enter elements of array: "); for (int i = 0; i < array.Length; i++) { array[i] = int.Parse(Console.ReadLine()); } } }
TheStack
b4087631e1ef047f053a61828272410dd28c94f9
C#code:C#
{"size": 3668, "ext": "cs", "max_stars_repo_path": "FireEffect/FireGenerator.cs", "max_stars_repo_name": "ChrisLomont/FireEffect", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FireEffect/FireGenerator.cs", "max_issues_repo_name": "ChrisLomont/FireEffect", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FireEffect/FireGenerator.cs", "max_forks_repo_name": "ChrisLomont/FireEffect", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.6037735849, "max_line_length": 113, "alphanum_fraction": 0.4871864776}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hypnocube.LargeArtDriver.Model.ImageGenerator.Graphics; namespace FireEffect { // ported from here // http://lodev.org/cgtutor/fire.html // used to make fire for the Eggify art project class FireGenerator { public const int screenWidth = 30; public const int screenHeight = 100; // Y-coordinate first because we use horizontal scanlines uint[,] fire = new uint[screenHeight, screenWidth]; // image buffer, RGB, width filled first, then height byte [] buffer = new byte[screenHeight * screenWidth * 3]; //this is the buffer to be drawn to the screen byte [] palette = new byte [256*3]; //this will contain the color palette public FireGenerator() { Initialize(); } void Initialize() { var h = screenHeight; var w = screenWidth; //make sure the fire buffer is zero in the beginning for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) fire[y, x] = 0; //generate the palette for (var x = 0; x < 256; x++) { double r, g, b; //HSLtoRGB is used to generate colors: //Hue goes from 0 to 85: red to yellow //Saturation is always the maximum: 255 //Lightness is 0..255 for x=0..128, and 255 for x=128..255 var hue = x / 255.0; var lit = Math.Min(1.0, hue * 2); HslUtils.HslToRgb(hue / 3, 1.0,lit , out r, out g, out b); // color = HSLtoRGB(ColorHSL(x / 3, 255, std::min(255, x * 2))); //set the palette to the calculated RGB value palette[x * 3] = IntC(r); palette[x * 3 + 1] = IntC(g); palette[x * 3 + 2] = IntC(b); // palette[x] = RGBtoINT(color); } } byte IntC(double v) { var vv = (int) Math.Round(v*255); if (vv > 255) vv = 255; if (vv < 0) vv = 0; return (byte)vv; } Random rand = new Random(); // call 20 times per second // returns rgb buffer public byte[] Update() { //randomize the bottom row of the fire buffer for (int x = 0; x < screenWidth; x++) fire[screenHeight - 1, x] = (uint)(Math.Abs(32768 + rand.Next()) % 256); //do the fire calculations for every pixel, from top to bottom for (int y = 0; y < screenHeight - 1; y++) for (int x = 0; x < screenWidth; x++) { fire[y, x] = ((fire[(y + 1) % screenHeight, (x - 1 + screenWidth) % screenWidth] + fire[(y + 1) % screenHeight, (x) % screenWidth] + fire[(y + 1) % screenHeight, (x + 1) % screenWidth] + fire[(y + 2) % screenHeight, (x) % screenWidth]) * 32) / 129; } //set the drawing buffer to the fire buffer, using the palette colors for (int y = 0; y < screenHeight; y++) for (int x = 0; x < screenWidth; x++) { var index = (x + y * screenWidth) * 3; var color = fire[y, x] * 3; buffer[index] = palette[color]; buffer[index+1] = palette[color+1]; buffer[index+2] = palette[color+2]; } return buffer; } } }
TheStack
b40af3c31ec86beb6d1dc68b6c23d86b775cf7df
C#code:C#
{"size": 1838, "ext": "cshtml", "max_stars_repo_path": "WebAppBlog/BlogWeb/BlogWeb.WebUI/Views/Home/Index.cshtml", "max_stars_repo_name": "matin360/WebAppBlog", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WebAppBlog/BlogWeb/BlogWeb.WebUI/Views/Home/Index.cshtml", "max_issues_repo_name": "matin360/WebAppBlog", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WebAppBlog/BlogWeb/BlogWeb.WebUI/Views/Home/Index.cshtml", "max_forks_repo_name": "matin360/WebAppBlog", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.2769230769, "max_line_length": 106, "alphanum_fraction": 0.5854189336}
@using BlogWeb.WebUI.Models; @model IEnumerable<BlogWeb.WebUI.Models.PostViewModel> @{ Layout = "../Shared/_Layout.cshtml"; var posts = Model; ViewBag.Title = "Home"; } <section class="ftco-section ftco-no-pt ftco-no-pb"> <div class="container"> <div class="row d-flex"> <div class="col-lg-8 px-md-5 py-5"> <div class="row pt-md-4"> @if (posts != null) { foreach (var post in posts) { Html.RenderPartial("_SinglePostIndexPartial", post); } } </div><!-- END--> <div class="row"> <!--pagination--> <div class="col"> @Html.Action("Pages", "Pagination", new PageModel { Controller = "Home", Action = "Index" } ) </div> </div> </div> <div class="col-lg-4 sidebar ftco-animate bg-light pt-5"> <div class="sidebar-box pt-md-4"> @{ Html.RenderPartial("_SearchFormPartial"); } </div> <div class="sidebar-box ftco-animate"> <h3 class="sidebar-heading">Categories</h3> @Html.Action("All", "Category") </div> <div class="sidebar-box ftco-animate"> <h3 class="sidebar-heading">Popular Articles</h3> @Html.Action("AllPopular", "Post") </div> <div class="sidebar-box ftco-animate"> <h3 class="sidebar-heading">Tag Cloud</h3> @Html.Action("All", "Tag") </div> <div class="sidebar-box subs-wrap img py-4" style="background-image: url(/Content/images/bg_1.jpg);"> @{ Html.RenderPartial("_NewsLetterSideBarPartial"); } </div> <div class="sidebar-box ftco-animate"> <h3 class="sidebar-heading">Archives</h3> @Html.Action("All", "Archive") </div> <div class="sidebar-box ftco-animate"> @{ Html.RenderPartial("_SideBarBottomPartial"); } </div> </div><!-- END COL --> </div> </div> </section>
TheStack
b40b636784e223af53447337cdade7c19ee777a1
C#code:C#
{"size": 9909, "ext": "cs", "max_stars_repo_path": "Engine.Geometry/Objects/GraphicsObject.cs", "max_stars_repo_name": "Shkyrockett/engine", "max_stars_repo_stars_event_min_datetime": "2017-03-09T12:43:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-09T05:33:30.000Z", "max_issues_repo_path": "Engine.Geometry/Objects/GraphicsObject.cs", "max_issues_repo_name": "Shkyrockett/engine", "max_issues_repo_issues_event_min_datetime": "2017-01-21T07:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-06T07:12:09.000Z", "max_forks_repo_path": "Engine.Geometry/Objects/GraphicsObject.cs", "max_forks_repo_name": "Shkyrockett/engine", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 4.0, "max_issues_count": 26.0, "max_forks_count": null, "avg_line_length": 38.1115384615, "max_line_length": 163, "alphanum_fraction": 0.5920880008}
// <copyright file="GraphicsObject.cs" company="Shkyrockett" > // Copyright © 2005 - 2020 Shkyrockett. All rights reserved. // </copyright> // <author id="shkyrockett">Shkyrockett</author> // <license> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </license> // <summary></summary> // <remarks></remarks> using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Xml.Serialization; namespace Engine { /// <summary> /// Graphic objects base class. /// </summary> [DataContract, Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public abstract class GraphicsObject : IFormattable, INotifyPropertyChanging, INotifyPropertyChanged { #region Callbacks /// <summary> /// Action delegate for notifying callbacks on object updates. /// </summary> internal Action update; /// <summary> /// The property changed event of the <see cref="PropertyChangedEventHandler"/>. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// The property changing event of the <see cref="PropertyChangingEventHandler"/>. /// </summary> public event PropertyChangingEventHandler PropertyChanging; #endregion Callbacks #region Fields /// <summary> /// Property cache for commonly used properties that may take time to calculate. /// </summary> [XmlIgnore()] [NonSerialized()] protected Dictionary<object, object> propertyCache = new Dictionary<object, object>(); #endregion Fields #region Properties /// <summary> /// Gets the <see cref="Area"/> of a <see cref="Shape2D"/>. /// </summary> [IgnoreDataMember, XmlIgnore, SoapIgnore] [Category("Properties")] [Description("The area of the shape.")] public virtual double Area { get; set; } /// <summary> /// Gets the <see cref="Perimeter"/> of a <see cref="Shape2D"/>. /// </summary> [IgnoreDataMember, XmlIgnore, SoapIgnore] [Category("Properties")] [Description("The perimeter length of the shape.")] public virtual double Perimeter { get; set; } /// <summary> /// Gets the <see cref="Bounds"/> of a <see cref="Shape2D"/>. /// </summary> [IgnoreDataMember, XmlIgnore, SoapIgnore] [Category("Properties")] [Description("The bounding box of the shape.")] public virtual Rectangle2D Bounds { get; set; } #endregion Properties #region Interpolation /// <summary> /// Interpolates a <see cref="Shape2D"/>. /// </summary> /// <param name="t"></param> /// <returns></returns> public virtual Point2D Interpolate(double t) => new Point2D(); /// <summary> /// Retrieves a list of points interpolated from a<see cref="Shape2D"/>. /// </summary> /// <param name="count">The number of points desired.</param> /// <returns></returns> public virtual List<Point2D> InterpolatePoints(int count = 100) { var list = new List<Point2D>( from i in Enumerable.Range(0, count) select Interpolate(1d / count * i)) { Interpolate(1) }; return list; } /// <summary> /// The interpolate points. /// </summary> /// <param name="range">The range.</param> /// <returns>The <see cref="List{T}"/>.</returns> public virtual List<Point2D> InterpolatePoints(NumericRange range) { var points = new List<Point2D>(); foreach (var item in range) { points.Add(Interpolate(item)); } return points; } #endregion Interpolation #region Methods /// <summary> /// Test whether a point intersects with the object. /// </summary> /// <param name="point"></param> /// <returns>A <see cref="bool"/> value indicating whether the point intersects the object.</returns> public virtual bool Contains(Point2D point) => false; /// <summary> /// Register one or more methods to call when properties change to the shape. /// </summary> /// <param name="callback">The method to use.</param> /// <returns>A reference to object.</returns> internal GraphicsObject OnUpdate(Action callback) { if (update is null) { update = callback; } else { update += callback; } return this; } /// <summary> /// Raises the property changing event. /// </summary> /// <param name="name">The name.</param> protected void OnPropertyChanging([CallerMemberName] string name = "") => PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(name)); /// <summary> /// Raises the property changed event. /// </summary> /// <param name="name">The name.</param> protected void OnPropertyChanged([CallerMemberName] string name = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); /// <summary> /// This should be run anytime a property of the item is modified. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ClearCache() => propertyCache.Clear(); /// <summary> /// Private method for caching computationally and memory intensive properties of child objects /// so that the intensive properties only get recalculated and stored when necessary. /// </summary> /// <param name="property">The property.</param> /// <param name="name">The name.</param> /// <returns></returns> /// <remarks> /// <para>http://syncor.blogspot.com/2010/11/passing-getter-and-setter-of-c-property.html</para> /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] protected object CachingProperty(Func<object> property, [CallerMemberName] string name = "") { if (!propertyCache.ContainsKey(name)) { var value = property?.Invoke(); propertyCache.Add(name, value); return value; } return propertyCache[name]; } ///// <summary> ///// ///// </summary> ///// <returns></returns> //public virtual T Clone<T>() //{ // throw new NotImplementedException(); //} /// <summary> /// Creates a human-readable string that represents this <see cref="GraphicsObject"/> inherited class. /// </summary> /// <returns></returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public override string ToString() => ConvertToString(string.Empty /* format string */, CultureInfo.InvariantCulture /* format provider */); /// <summary> /// Creates a string representation of this <see cref="GraphicsObject"/> inherited class based on the IFormatProvider /// passed in. If the provider is null, the CurrentCulture is used. /// </summary> /// <param name="formatProvider">ToDo: describe provider parameter on ToString</param> /// <returns> /// A string representation of this object. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(IFormatProvider formatProvider) => ConvertToString(string.Empty /* format string */, formatProvider); /// <summary> /// Creates a string representation of this <see cref="GraphicsObject"/> inherited class based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <param name="format"></param> /// <param name="formatProvider"></param> /// <returns> /// A string representation of this object. /// </returns> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public string ToString(string format, IFormatProvider formatProvider) => ConvertToString(format /* format string */, formatProvider /* format provider */); /// <summary> /// Creates a string representation of this <see cref="GraphicsObject"/> inherited class based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <param name="format"></param> /// <param name="formatProvider"></param> /// <returns> /// A string representation of this object. /// </returns> public virtual string ConvertToString(string format, IFormatProvider formatProvider) { if (this is null) { return nameof(GraphicsObject); } //char sep = Tokenizer.GetNumericListSeparator(formatProvider); IFormattable formatable = $"{nameof(GraphicsObject)}"; return formatable.ToString(format, formatProvider); } #endregion Methods } }
TheStack
b40ceca85e22934a8d970f7c0c08b01c04d12f81
C#code:C#
{"size": 3755, "ext": "cs", "max_stars_repo_path": "Fakebook.Posts/Fakebook.Posts.UnitTests/PostTest.cs", "max_stars_repo_name": "2011-fakebook-project3/posts", "max_stars_repo_stars_event_min_datetime": "2020-12-29T19:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T19:40:14.000Z", "max_issues_repo_path": "Fakebook.Posts/Fakebook.Posts.UnitTests/PostTest.cs", "max_issues_repo_name": "2011-fakebook-project3/posts", "max_issues_repo_issues_event_min_datetime": "2020-12-29T21:04:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T21:57:34.000Z", "max_forks_repo_path": "Fakebook.Posts/Fakebook.Posts.UnitTests/PostTest.cs", "max_forks_repo_name": "2011-fakebook-project3/posts", "max_forks_repo_forks_event_min_datetime": "2021-04-01T21:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:49:42.000Z"}
{"max_stars_count": 1.0, "max_issues_count": 147.0, "max_forks_count": 2.0, "avg_line_length": 30.7786885246, "max_line_length": 142, "alphanum_fraction": 0.5739014647}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fakebook.Posts.Domain.Models; using Xunit; namespace Fakebook.Posts.UnitTests { public class PostTests { private const int Id = 1; [Fact] public void Post_Constructor_Pass() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; //act Post newpost = new Post(userEmail, Content); } [Fact] public void Post_ContentIsNotNull() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; //act Post newpost = new Post(userEmail, Content); //assert Assert.NotNull(newpost.Content); } [Fact] public void Post_EmailEquality() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; //act Post newpost = new Post(userEmail, Content); //assert Assert.Equal(userEmail, newpost.UserEmail); } /// <summary> /// Post_EmailFormationThrowsException_ReturnsArgumentException method checks to ensure that when an email is inputted incorrectly, /// an argument exception is thrown. /// </summary> [Fact] public void Post_EmailFormationThrowsException_ReturnsArgumentException() { const string content = "This is some content"; const string invalidEmail = "damion.silvertest.com"; Assert.Throws<ArgumentException>(() => new Post(invalidEmail, content)); } [Fact] public void Comment_Constructor_Pass() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; const int PostID = 1; //act Comment newcomment = new Comment(userEmail, Content, PostID); //assert Assert.NotNull(newcomment); } [Fact] public void Comment_EmailEquality() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; const int PostID = 1; //act Comment newcomment = new Comment(userEmail, Content,PostID ); //assert Assert.Equal(userEmail, newcomment.UserEmail); } [Fact] public void Comment_ContentIsNotNull() { //arrange const string Content = "This is some content"; const string userEmail = "[email protected]"; const int PostID = 1; //act Comment newcomment = new Comment(userEmail, Content,PostID); //assert Assert.NotNull(newcomment.Content); } /// <summary> /// Comment_EmailFormationThrowsException_ReturnsArgumentException method checks to ensure that when an email is inputted incorrectly, /// an argument exception is thrown. /// </summary> [Fact] public void Comment_EmailFormationThrowsException_ReturnsArgumentException() { const string content = "This is some content"; const string invalidEmail = "damion.silvertest.com"; const int PostID = 1; Assert.ThrowsAny<ArgumentException>(() => new Comment(invalidEmail, content,PostID)); } } }
TheStack
b40d87f65548ad4cbdb5902a4bb6deede94792b9
C#code:C#
{"size": 5233, "ext": "cs", "max_stars_repo_path": "B-DEV-500-LYN-5-1-dashboard/Dashboard/Pages/Global.cs", "max_stars_repo_name": "Neotoxic-off/Epitech2024", "max_stars_repo_stars_event_min_datetime": "2022-02-07T12:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T12:04:08.000Z", "max_issues_repo_path": "B-DEV-500-LYN-5-1-dashboard/Dashboard/Pages/Global.cs", "max_issues_repo_name": "Neotoxic-off/Epitech2024", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "B-DEV-500-LYN-5-1-dashboard/Dashboard/Pages/Global.cs", "max_forks_repo_name": "Neotoxic-off/Epitech2024", "max_forks_repo_forks_event_min_datetime": "2022-01-23T21:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T21:26:06.000Z"}
{"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 30.2485549133, "max_line_length": 89, "alphanum_fraction": 0.5549398051}
using System.Timers; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using SpotifyAPI.Web; using Newtonsoft.Json; using System; using System.IO; using System.Net.Http.Headers; using Microsoft.AspNetCore.Http.Extensions; namespace Dashboard.Pages { public static class Globals { public enum EImageWidget { Meme = 1, Duck = 1, Dog = 1, Cat = 1, } public static API.User CurrentUser { get; set; } public static string LastLoginError { get; set; } public static string LastRegisterError { get; set; } public static EImageWidget imageWidget { get; set; } public static bool factsWidget { get; set; } public static bool quoteWidget { get; set; } public static bool insultWidget { get; set; } public static List<string> CurrentWidgets = new List<string>(); public static Paging<SimpleAlbum> SpotifySearchResultsAlbum = null; public static SpotifyTrack.Root SpotifySearchResultsTrack = null; public static SpotifyArtist.Root SpotifySearchResultsArtist = null; public static SpotifyPlaylist.Root SpotifySearchResultsPlaylist = null; public static List<FullTrack> SpotifySearchResultsTop = null; } public class GlobalModels { public static SpotifyModel spotifyModel { get; set; } public static PanelModel panelModel { get; set; } public static CoffeeModel coffeeModel { get; set; } public static WeatherModel weatherModel { get; set; } } public class Clocks { SettingsWidgets.Root settingsWidgets = null; public Task load() { string path = "settings.json"; if (File.Exists(path) == true) { settingsWidgets = JsonConvert.DeserializeObject<SettingsWidgets.Root>( File.ReadAllText(path) ); } return (Task.CompletedTask); } public int get(string widget) { if (settingsWidgets == null) { load().Wait(); } foreach (SettingsWidgets.Clock clock in settingsWidgets.clocks) { if (clock.widget == widget) return (clock.time); } return (120); } public Task set(string widget, int value) { if (settingsWidgets == null) { load().Wait(); } foreach (SettingsWidgets.Clock clock in settingsWidgets.clocks) { if (clock.widget == widget) { clock.time = value; } } save().Wait(); return (Task.CompletedTask); } private Task save() { string path = "settings.json"; if (File.Exists(path) == true) File.Delete(path); File.WriteAllText(path, JsonConvert.SerializeObject(settingsWidgets)); return (Task.CompletedTask); } } public class ClockBuilder { public class Settings { public System.Timers.Timer timer = new System.Timers.Timer(); public int starter = -1; public int limit = 0; public string widget = null; public bool refresh = true; public int current = 0; } public Settings settings = new Settings(); Clocks clocks = new Clocks(); public ClockBuilder(string widget) { if (widget != null) { settings.widget = widget; settings.limit = clocks.get(settings.widget); } } public async Task<Task> edit(string item, int value) { if (File.Exists("settings.json") == true) { clocks.set(item, value); clocks = new Clocks(); } else { throw new Exception("widgets settings file not found"); } return (Task.CompletedTask); } public async Task start() { Console.WriteLine($"Starting clock {settings.widget} for {settings.limit}s"); settings.timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); settings.timer.Interval = 1000; settings.timer.Enabled = true; settings.timer.AutoReset = true; settings.starter = -1; settings.refresh = false; settings.current = 0; settings.timer.Start(); } private void OnTimedEvent(object source, ElapsedEventArgs e) { if (settings.starter < 0) settings.starter = e.SignalTime.Second; if (settings.current >= settings.limit) { Console.WriteLine($"It's time to refresh: {settings.widget}"); settings.refresh = true; settings.current = 0; settings.timer.Stop(); } settings.current++; } } }
TheStack
b40e15e10ce288214f4fbae5df39e9f4d638ff0c
C#code:C#
{"size": 2760, "ext": "cs", "max_stars_repo_path": "PlatformRacing3.Server/Game/Communication/Messages/JsonOutgoingPacketContext.cs", "max_stars_repo_name": "aromaa/Platform-Racing-3-Backend", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PlatformRacing3.Server/Game/Communication/Messages/JsonOutgoingPacketContext.cs", "max_issues_repo_name": "aromaa/Platform-Racing-3-Backend", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PlatformRacing3.Server/Game/Communication/Messages/JsonOutgoingPacketContext.cs", "max_forks_repo_name": "aromaa/Platform-Racing-3-Backend", "max_forks_repo_forks_event_min_datetime": "2021-08-28T18:30:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T18:30:17.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 55.2, "max_line_length": 79, "alphanum_fraction": 0.8507246377}
using System.Text.Json.Serialization; using PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; namespace PlatformRacing3.Server.Game.Communication.Messages; [JsonSerializable(typeof(JsonAddHatOutgoingMessage))] //[JsonSerializable(typeof(JsonAlertOutgoingMessage))] //[JsonSerializable(typeof(JsonBeginMatchOutgoingMessage))] //[JsonSerializable(typeof(JsonCoinsOutgoingMessage))] //[JsonSerializable(typeof(JsonEndGameOutgoingMessage))] //[JsonSerializable(typeof(JsonEventsOutgoingMessage))] //[JsonSerializable(typeof(JsonFinishDrawingOutgoingMessage))] //[JsonSerializable(typeof(JsonForceMatchOutgoingMessage))] //[JsonSerializable(typeof(JsonForfietOutgoingMessage))] //[JsonSerializable(typeof(JsonFriendsAndIgnoredOutgoingMessage))] //[JsonSerializable(typeof(JsonLegacyPingOutgoingMessage))] //[JsonSerializable(typeof(JsonLevelListOutgoingMessage))] //[JsonSerializable(typeof(JsonLoginErrorOutgoingMessage))] //[JsonSerializable(typeof(JsonLoginSuccessOutgoingMessage))] //[JsonSerializable(typeof(JsonLogoutTriggerOutgoingMessage))] //[JsonSerializable(typeof(JsonMatchCreatedOutgoingMessage))] //[JsonSerializable(typeof(JsonMatchesOutgoingMessage))] //[JsonSerializable(typeof(JsonMatchFailedOutgoingMessage))] //[JsonSerializable(typeof(JsonMatchOwnerOutgoingMessage))] //[JsonSerializable(typeof(JsonMemberListOutgoingMessage))] //[JsonSerializable(typeof(JsonMessageOutgoingMessage))] //[JsonSerializable(typeof(JsonPlayerFinishedOutgoingMessage))] //[JsonSerializable(typeof(JsonPmOutgoingMessage))] //[JsonSerializable(typeof(JsonPmsOutgoingMessage))] //[JsonSerializable(typeof(JsonPrizeOutgoingMessage))] //[JsonSerializable(typeof(JsonQuickJoinSuccessOutgoingMessage))] //[JsonSerializable(typeof(JsonReceiveLevelOfTheDayOutgoingMessage))] //[JsonSerializable(typeof(JsonRemoveHatOutgoingMessage))] //[JsonSerializable(typeof(JsonRoomsOutgoingMessage))] //[JsonSerializable(typeof(JsonRoomVarsOutgoingMessage))] //[JsonSerializable(typeof(JsonSetPlayerHatsOutgoingMessage))] //[JsonSerializable(typeof(JsonSocketIdOutgoingMessage))] //[JsonSerializable(typeof(JsonSpawnAliensOutgoingPacket))] //[JsonSerializable(typeof(JsonThingExistsOutgoingMessage))] //[JsonSerializable(typeof(JsonTournamentStatusOutgoingMessage))] //[JsonSerializable(typeof(JsonUserJoinRoomOutgoingMessage))] //[JsonSerializable(typeof(JsonUserLeaveRoomOutgoingMessage))] //[JsonSerializable(typeof(JsonUserListOutgoingMessage))] //[JsonSerializable(typeof(JsonUserPageOutgoingMessage))] //[JsonSerializable(typeof(JsonUserVarsOutgoingMessage))] //[JsonSerializable(typeof(JsonVersionOutgoingMessage))] //[JsonSerializable(typeof(JsonYouFinishedOutgoingMessage))] internal sealed partial class JsonOutgoingPacketContext : JsonSerializerContext { }
TheStack
b40e1f6e0ba9374fe188fcc50fe090051ffed436
C#code:C#
{"size": 5939, "ext": "cs", "max_stars_repo_path": "src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/HubSection.cs", "max_stars_repo_name": "olirobert/uno", "max_stars_repo_stars_event_min_datetime": "2019-06-27T02:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:07:25.000Z", "max_issues_repo_path": "src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/HubSection.cs", "max_issues_repo_name": "olirobert/uno", "max_issues_repo_issues_event_min_datetime": "2019-06-27T03:34:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:01:54.000Z", "max_forks_repo_path": "src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/HubSection.cs", "max_forks_repo_name": "olirobert/uno", "max_forks_repo_forks_event_min_datetime": "2019-06-27T23:31:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:50:25.000Z"}
{"max_stars_count": 5973.0, "max_issues_count": 6988.0, "max_forks_count": 636.0, "avg_line_length": 49.4916666667, "max_line_length": 143, "alphanum_fraction": 0.7432227648}
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Controls { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class HubSection : global::Windows.UI.Xaml.Controls.Control { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public bool IsHeaderInteractive { get { return (bool)this.GetValue(IsHeaderInteractiveProperty); } set { this.SetValue(IsHeaderInteractiveProperty, value); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.UI.Xaml.DataTemplate HeaderTemplate { get { return (global::Windows.UI.Xaml.DataTemplate)this.GetValue(HeaderTemplateProperty); } set { this.SetValue(HeaderTemplateProperty, value); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public object Header { get { return (object)this.GetValue(HeaderProperty); } set { this.SetValue(HeaderProperty, value); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.UI.Xaml.DataTemplate ContentTemplate { get { return (global::Windows.UI.Xaml.DataTemplate)this.GetValue(ContentTemplateProperty); } set { this.SetValue(ContentTemplateProperty, value); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static global::Windows.UI.Xaml.DependencyProperty ContentTemplateProperty { get; } = Windows.UI.Xaml.DependencyProperty.Register( nameof(ContentTemplate), typeof(global::Windows.UI.Xaml.DataTemplate), typeof(global::Windows.UI.Xaml.Controls.HubSection), new FrameworkPropertyMetadata(default(global::Windows.UI.Xaml.DataTemplate))); #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static global::Windows.UI.Xaml.DependencyProperty HeaderProperty { get; } = Windows.UI.Xaml.DependencyProperty.Register( nameof(Header), typeof(object), typeof(global::Windows.UI.Xaml.Controls.HubSection), new FrameworkPropertyMetadata(default(object))); #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static global::Windows.UI.Xaml.DependencyProperty HeaderTemplateProperty { get; } = Windows.UI.Xaml.DependencyProperty.Register( nameof(HeaderTemplate), typeof(global::Windows.UI.Xaml.DataTemplate), typeof(global::Windows.UI.Xaml.Controls.HubSection), new FrameworkPropertyMetadata(default(global::Windows.UI.Xaml.DataTemplate))); #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public static global::Windows.UI.Xaml.DependencyProperty IsHeaderInteractiveProperty { get; } = Windows.UI.Xaml.DependencyProperty.Register( nameof(IsHeaderInteractive), typeof(bool), typeof(global::Windows.UI.Xaml.Controls.HubSection), new FrameworkPropertyMetadata(default(bool))); #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public HubSection() : base() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.HubSection", "HubSection.HubSection()"); } #endif // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.HubSection() // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.Header.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.Header.set // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.HeaderTemplate.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.HeaderTemplate.set // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.ContentTemplate.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.ContentTemplate.set // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.IsHeaderInteractive.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.IsHeaderInteractive.set // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.HeaderProperty.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.HeaderTemplateProperty.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.ContentTemplateProperty.get // Forced skipping of method Windows.UI.Xaml.Controls.HubSection.IsHeaderInteractiveProperty.get } }
TheStack
b40eacedaa22067cf51234aa5897b661dea3ed39
C#code:C#
{"size": 1417, "ext": "cs", "max_stars_repo_path": "src/Cofoundry.Domain/Domain/Users/Queries/GetCurrentUserContextQuery.cs", "max_stars_repo_name": "BearerPipelineTest/cofoundry", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Cofoundry.Domain/Domain/Users/Queries/GetCurrentUserContextQuery.cs", "max_issues_repo_name": "BearerPipelineTest/cofoundry", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cofoundry.Domain/Domain/Users/Queries/GetCurrentUserContextQuery.cs", "max_forks_repo_name": "BearerPipelineTest/cofoundry", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.7096774194, "max_line_length": 99, "alphanum_fraction": 0.6626676076}
using Cofoundry.Domain.CQS; using System.ComponentModel.DataAnnotations; namespace Cofoundry.Domain { /// <summary> /// <para> /// Gets basic information about the currently logged in user. If the user is not /// logged in then <see cref="UserContext.Empty"/> is returned. If multiple user /// areas are implemented, then the returned user will depend on the "ambient" /// auth scheme, which is typically the default user area unless the ambient scheme /// has been changed during the flow of the request e.g. via an AuthorizeUserAreaAttribute. /// </para> /// <para> /// By default the <see cref="IUserContext"/> is cached for the lifetime of the service /// (per request in web apps). /// </para> /// </summary> public class GetCurrentUserContextQuery : IQuery<IUserContext> { /// <summary> /// If your project uses multiple user areas, then you can optionally specify which user /// area to return the user for. If <see cref="UserAreaCode"/> is not specified then the /// returned user will depend on the "ambient" auth scheme, which is typically the default /// user area unless the ambient scheme has been changed during the flow of the request /// e.g. via an AuthorizeUserAreaAttribute. /// </summary> [StringLength(3)] public string UserAreaCode { get; set; } } }
TheStack
b40f1801e89a18a678220a232f4653274753eb5d
C#code:C#
{"size": 3531, "ext": "cs", "max_stars_repo_path": "src/Handlebars/StringHelpers.cs", "max_stars_repo_name": "genyman/core", "max_stars_repo_stars_event_min_datetime": "2018-08-07T20:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-07T20:36:53.000Z", "max_issues_repo_path": "src/Handlebars/StringHelpers.cs", "max_issues_repo_name": "genyman/core", "max_issues_repo_issues_event_min_datetime": "2018-08-01T22:38:24.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-11T10:50:37.000Z", "max_forks_repo_path": "src/Handlebars/StringHelpers.cs", "max_forks_repo_name": "genyman/core", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 4.0, "max_forks_count": null, "avg_line_length": 33.9519230769, "max_line_length": 114, "alphanum_fraction": 0.6768620787}
using HandlebarsDotNet; namespace Genyman.Core.Handlebars { internal static class StringHelpers { internal static void Init(IHandlebars handlebars) { handlebars.RegisterHelper("append", (writer, context, parameters) => { if (!parameters.MustBeString() || !parameters.MustBeString(1)) return; writer.WriteSafeString(Concat(parameters[0].ToString(), parameters[1].ToString())); }); handlebars.RegisterHelper("prepend", (writer, context, parameters) => { if (!parameters.MustBeString() || !parameters.MustBeString(1)) return; writer.WriteSafeString(ConcatReverse(parameters[0].ToString(), parameters[1].ToString())); }); handlebars.RegisterHelper("remove", (writer, context, parameters) => { if (!parameters.MustBeString() || !parameters.MustBeString(1)) return; writer.WriteSafeString(Remove(parameters[0].ToString(), parameters[1].ToString())); }); handlebars.RegisterHelper("replace", (writer, context, parameters) => { if (!parameters.MustBeString() || !parameters.MustBeString(1) || !parameters.MustBeString(2)) return; writer.WriteSafeString(Replace(parameters[0].ToString(), parameters[1].ToString(), parameters[2].ToString())); }); handlebars.RegisterHelper("lower", (writer, context, parameters) => { if (!parameters.MustBeString()) return; writer.WriteSafeString(ToLower(parameters[0].ToString())); }); handlebars.RegisterHelper("upper", (writer, context, parameters) => { if (!parameters.MustBeString()) return; writer.WriteSafeString(ToUpper(parameters[0].ToString())); }); handlebars.RegisterHelper("camelcase", (writer, context, parameters) => { if (!parameters.MustBeString()) return; writer.WriteSafeString(ToCamelCase(parameters[0].ToString())); }); handlebars.RegisterHelper("pascalcase", (writer, context, parameters) => { if (!parameters.MustBeString()) return; writer.WriteSafeString(ToPascalCase(parameters[0].ToString())); }); handlebars.RegisterHelper("capitalize", (writer, context, parameters) => { if (!parameters.MustBeString()) return; writer.WriteSafeString(Capitalize(parameters[0].ToString())); }); } static string ToLower(string value) => value.ToLower(); static string ToUpper(string value) => value.ToUpper(); static string Concat(string value1, string value2) => string.Concat(value1, value2); static string ConcatReverse(string value1, string value2) => string.Concat(value2, value1); static string Remove(string value1, string value2) => value1.Replace(value2, ""); static string Replace(string value1, string value2, string value3) => value1.Replace(value2, value3); internal static string ToCamelCase(string value) { var parts = value.Split(' '); var result = parts[0].Substring(0, 1).ToLower() + parts[0].Substring(1); for (int i = 1; i < parts.Length; i++) { result += parts[i].Substring(0, 1).ToUpper() + parts[i].Substring(1); } return result; } static string Capitalize(string value) { var parts = value.Split(' '); var result = parts[0].Substring(0, 1).ToUpper() + parts[0].Substring(1); for (var i = 1; i < parts.Length; i++) { result += " " + parts[i]; } return result; } internal static string ToPascalCase(string value) { var parts = value.Split(' '); var result = string.Empty; for (var i = 0; i < parts.Length; i++) { result += parts[i].Substring(0, 1).ToUpper() + parts[i].Substring(1); } return result; } } }
TheStack
b40fad854541fbdab786131ed87578d7567fec23
C#code:C#
{"size": 989, "ext": "cs", "max_stars_repo_path": "src/DancingGoat/Models/Orders/OrderAddressViewModel.cs", "max_stars_repo_name": "jaberi232/mvc-project", "max_stars_repo_stars_event_min_datetime": "2015-12-04T14:06:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:28:01.000Z", "max_issues_repo_path": "src/DancingGoat/Models/Orders/OrderAddressViewModel.cs", "max_issues_repo_name": "jaberi232/mvc-project", "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:11:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-15T06:14:28.000Z", "max_forks_repo_path": "src/DancingGoat/Models/Orders/OrderAddressViewModel.cs", "max_forks_repo_name": "jaberi232/mvc-project", "max_forks_repo_forks_event_min_datetime": "2015-12-17T21:22:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T05:13:43.000Z"}
{"max_stars_count": 107.0, "max_issues_count": 11.0, "max_forks_count": 95.0, "avg_line_length": 21.9777777778, "max_line_length": 81, "alphanum_fraction": 0.5813953488}
using Kentico.Ecommerce; namespace DancingGoat.Models.Orders { public class OrderAddressViewModel { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string AddressCity { get; set; } public string AddressPostalCode { get; set; } public string AddressState { get; set; } public string AddressCountry { get; set; } public OrderAddressViewModel() { } public OrderAddressViewModel(OrderAddress address) { if (address == null) { return; } AddressLine1 = address.Line1; AddressLine2 = address.Line2; AddressCity = address.City; AddressPostalCode = address.PostalCode; AddressState = address.State?.StateDisplayName ?? string.Empty; AddressCountry = address.Country?.CountryDisplayName ?? string.Empty; } } }
TheStack
b411d62678f383f338b2461197af76084c84783f
C#code:C#
{"size": 4909, "ext": "cs", "max_stars_repo_path": "MyWeb.DataAccess/Model/Menu.cs", "max_stars_repo_name": "wangzhiqing999/my-csharp-project", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MyWeb.DataAccess/Model/Menu.cs", "max_issues_repo_name": "wangzhiqing999/my-csharp-project", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MyWeb.DataAccess/Model/Menu.cs", "max_forks_repo_name": "wangzhiqing999/my-csharp-project", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.7220216606, "max_line_length": 78, "alphanum_fraction": 0.4781014463}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MyWeb.Model { /// <summary> /// 菜单. /// </summary> [Serializable] [DataContract(Namespace = "")] [Table("mw_menu")] [ToString] public class Menu { /// <summary> /// 菜单代码 /// </summary> [DataMember] [Column("menu_code")] [Key] [Display(Name = "菜单代码")] [StringLength(32)] [Required] public string MenuCode { set; get; } #region 一对多. (归属网站) /// <summary> /// 网站代码 /// </summary> [DataMember] [Column("web_site_code")] [Display(Name = "网站代码")] [Required] [StringLength(64)] public string WebSiteCode { set; get; } /// <summary> /// 菜单所属的网站. /// </summary> [IgnoreDuringToString] public virtual WebSite MenuWebSite { set; get; } #endregion 一对多. #region 一对多的部分. (自己对自己 一对多, 实现树形结构) /// <summary> /// 父菜单编号 /// </summary> [DataMember] [Column("parent_menu_code")] [ForeignKey("ParentMenu")] [Display(Name = "父菜单编号")] [StringLength(32)] public string ParentMenuCode { set; get; } /// <summary> /// 父菜单. /// </summary> [InverseProperty("SubMenus")] [XmlIgnoreAttribute] [IgnoreDuringToString] public Menu ParentMenu { set; get; } /// <summary> /// 子菜单列表. /// </summary> [XmlIgnoreAttribute] [IgnoreDuringToString] public virtual List<Menu> SubMenus { set; get; } #endregion /// <summary> /// 显示顺序. /// </summary> [DataMember] [Column("display_index")] [Display(Name = "显示顺序")] public int DisplayIndex { set; get; } /// <summary> /// 菜单文本 /// </summary> [DataMember] [Column("menu_text")] [Display(Name = "菜单文本")] [Required] [StringLength(32)] public string MenuText { set; get; } /// <summary> /// 菜单备注 /// </summary> [DataMember] [Column("menu_desc")] [Display(Name = "菜单备注")] [StringLength(256)] public string MenuDesc { set; get; } /// <summary> /// 菜单目标. /// </summary> [DataMember] [Column("menu_target")] [Display(Name = "菜单目标")] [StringLength(32)] public string MenuTarget { set; get; } /// <summary> /// 是否是外部链接 /// </summary> [DataMember] [Column("is_outer_href")] [Display(Name = "是否是外部链接")] public bool IsOuterHref { set; get; } /// <summary> /// 菜单跳转地址. /// </summary> [DataMember] [Column("menu_href")] [Display(Name = "菜单跳转地址 (仅仅当外部链接的时候填写)")] [StringLength(512)] public string MenuHref { set; get; } #region 一对多. (指向页面, 仅仅当 IsOuterHref == false 时使用.) /// <summary> /// 页面代码 /// </summary> [DataMember] [Column("page_code")] [Display(Name = "页面代码 (仅仅当非外部链接的时候填写)")] [StringLength(64)] public string PageCode { set; get; } /// <summary> /// 菜单需要跳转的页面. /// </summary> public virtual Page MenuPage { set; get; } #endregion /// <summary> /// 菜单扩展信息 /// </summary> [DataMember] [Column("menu_expand")] [Display(Name = "菜单扩展信息")] [StringLength(512)] public string MenuExpand { set; get; } public string GetHtmlMenuHref() { if (this.IsOuterHref) { // 外部链接的情况下,直接返回外部链接. return this.MenuHref; } // 非外部链接的情况下,返回页面的链接. if (!String.IsNullOrEmpty(this.PageCode) && this.MenuPage != null) { // 有页面数据的情况下. return this.MenuPage.PagePath; } // 其他情况下. return "#"; } #region /// <summary> /// 菜单层次. /// /// 计算时使用,不存储在数据库中. /// </summary> [NotMapped] [XmlIgnoreAttribute] public int MenuLevel { set; get; } /// <summary> /// 子菜单列表. /// /// 计算时使用,不存储在数据库中. /// </summary> [NotMapped] [XmlIgnoreAttribute] public List<Menu> MenuSubMenuList { set; get; } #endregion } }
TheStack
b412a5feb33de26da8d4cf556f1aa06d39698a7b
C#code:C#
{"size": 404, "ext": "cs", "max_stars_repo_path": "src/TheTvdbDotNet/Repositories/TvdbBaseRepository.cs", "max_stars_repo_name": "a-jackson/TheTvdbDotNet", "max_stars_repo_stars_event_min_datetime": "2017-09-17T16:59:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-16T17:32:08.000Z", "max_issues_repo_path": "src/TheTvdbDotNet/Repositories/TvdbBaseRepository.cs", "max_issues_repo_name": "JTOne123/TheTvdbDotNet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TheTvdbDotNet/Repositories/TvdbBaseRepository.cs", "max_forks_repo_name": "JTOne123/TheTvdbDotNet", "max_forks_repo_forks_event_min_datetime": "2017-12-24T06:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-25T14:18:12.000Z"}
{"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 23.7647058824, "max_line_length": 74, "alphanum_fraction": 0.7153465347}
using TheTvdbDotNet.Http; namespace TheTvdbDotNet.Repositories { public abstract class TvdbBaseRepository { private readonly IAuthenticatedTvdbHttpClient httpClient; public TvdbBaseRepository(IAuthenticatedTvdbHttpClient httpClient) { this.httpClient = httpClient; } protected IAuthenticatedTvdbHttpClient HttpClient => httpClient; } }
TheStack
b41352c8b4ed6dfe3fced80386333404da09479c
C#code:C#
{"size": 966, "ext": "cs", "max_stars_repo_path": "UmbracoWithReactJs/Model Adapter/BlogModelAdapter.cs", "max_stars_repo_name": "dzolu/UmbracoWithReactJs", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UmbracoWithReactJs/Model Adapter/BlogModelAdapter.cs", "max_issues_repo_name": "dzolu/UmbracoWithReactJs", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UmbracoWithReactJs/Model Adapter/BlogModelAdapter.cs", "max_forks_repo_name": "dzolu/UmbracoWithReactJs", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.2, "max_line_length": 107, "alphanum_fraction": 0.6801242236}
using System.Linq; using Umbraco.Core.Models; using Umbraco.Web; using UmbracoWithReactJs.Models; using UmbracoWithReactJs.Model_Adapter.Interafaces; namespace UmbracoWithReactJs.Model_Adapter { public class BlogModelAdapter: IModelAdapter<BlogModel> { private readonly IModelAdapter<BlogPostModel> _blodPostModelAdapter; public BlogModelAdapter(IModelAdapter<BlogPostModel> blodPostModelAdapter) { _blodPostModelAdapter = blodPostModelAdapter; } public BlogModel Adapt(IPublishedContent content) { var numberOfBlopostToShown = content.GetPropertyValue<int>("howManyPostsShouldBeShown"); var blogPost=content.Children.OrderByDescending(x => x.CreateDate).Take(numberOfBlopostToShown) .Select(y=>_blodPostModelAdapter.Adapt(y)); return new BlogModel { BlogPost=blogPost }; } } }
TheStack
b4148433c5bed096b4b486089cd2d09cf11fb11b
C#code:C#
{"size": 7327, "ext": "cs", "max_stars_repo_path": "test/Benchmarks/Metrics/HistogramBenchmarks.cs", "max_stars_repo_name": "rajarella99/opentelemetry-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Benchmarks/Metrics/HistogramBenchmarks.cs", "max_issues_repo_name": "rajarella99/opentelemetry-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Benchmarks/Metrics/HistogramBenchmarks.cs", "max_forks_repo_name": "rajarella99/opentelemetry-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.79375, "max_line_length": 170, "alphanum_fraction": 0.5721304763}
// <copyright file="HistogramBenchmarks.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // 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. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Metrics; using BenchmarkDotNet.Attributes; using OpenTelemetry; using OpenTelemetry.Metrics; using OpenTelemetry.Tests; /* BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000 Intel Core i7-9700 CPU 3.00GHz, 1 CPU, 8 logical and 8 physical cores .NET SDK=6.0.200 [Host] : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT DefaultJob : .NET 6.0.2 (6.0.222.6406), X64 RyuJIT | Method | BoundCount | Mean | Error | StdDev | Allocated | |---------------------------- |----------- |----------:|---------:|---------:|----------:| | HistogramHotPath | 10 | 45.27 ns | 0.384 ns | 0.359 ns | - | | HistogramWith1LabelHotPath | 10 | 89.99 ns | 0.373 ns | 0.312 ns | - | | HistogramWith3LabelsHotPath | 10 | 185.34 ns | 3.184 ns | 3.667 ns | - | | HistogramWith5LabelsHotPath | 10 | 266.69 ns | 1.391 ns | 1.301 ns | - | | HistogramWith7LabelsHotPath | 10 | 323.20 ns | 1.834 ns | 1.531 ns | - | | HistogramHotPath | 20 | 48.69 ns | 0.347 ns | 0.307 ns | - | | HistogramWith1LabelHotPath | 20 | 93.84 ns | 0.696 ns | 0.651 ns | - | | HistogramWith3LabelsHotPath | 20 | 189.82 ns | 1.208 ns | 1.071 ns | - | | HistogramWith5LabelsHotPath | 20 | 269.23 ns | 2.027 ns | 1.693 ns | - | | HistogramWith7LabelsHotPath | 20 | 329.92 ns | 1.272 ns | 1.128 ns | - | | HistogramHotPath | 50 | 55.73 ns | 0.339 ns | 0.317 ns | - | | HistogramWith1LabelHotPath | 50 | 100.38 ns | 0.455 ns | 0.425 ns | - | | HistogramWith3LabelsHotPath | 50 | 200.02 ns | 1.011 ns | 0.844 ns | - | | HistogramWith5LabelsHotPath | 50 | 279.94 ns | 1.595 ns | 1.492 ns | - | | HistogramWith7LabelsHotPath | 50 | 346.88 ns | 1.064 ns | 0.943 ns | - | | HistogramHotPath | 100 | 66.39 ns | 0.167 ns | 0.148 ns | - | | HistogramWith1LabelHotPath | 100 | 114.98 ns | 1.340 ns | 1.253 ns | - | | HistogramWith3LabelsHotPath | 100 | 220.52 ns | 1.723 ns | 1.528 ns | - | | HistogramWith5LabelsHotPath | 100 | 299.10 ns | 1.950 ns | 1.629 ns | - | | HistogramWith7LabelsHotPath | 100 | 356.25 ns | 2.153 ns | 1.798 ns | - | */ namespace Benchmarks.Metrics { [MemoryDiagnoser] public class HistogramBenchmarks { private const int MaxValue = 1000; private Random random = new(); private Histogram<long> histogram; private MeterProvider provider; private Meter meter; private double[] bounds; private string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" }; [Params(10, 20, 50, 100)] public int BoundCount { get; set; } [GlobalSetup] public void Setup() { this.meter = new Meter(Utils.GetCurrentMethodName()); this.histogram = this.meter.CreateHistogram<long>("histogram"); // Evenly distribute the bound values over the range [0, MaxValue) this.bounds = new double[this.BoundCount]; for (int i = 0; i < this.bounds.Length; i++) { this.bounds[i] = i * MaxValue / this.bounds.Length; } var exportedItems = new List<Metric>(); this.provider = Sdk.CreateMeterProviderBuilder() .AddMeter(this.meter.Name) .AddInMemoryExporter(exportedItems, metricReaderOptions => { metricReaderOptions.MetricReaderType = MetricReaderType.Periodic; metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 1000; }) .AddView(this.histogram.Name, new ExplicitBucketHistogramConfiguration() { Boundaries = this.bounds }) .Build(); } [GlobalCleanup] public void Cleanup() { this.meter?.Dispose(); this.provider?.Dispose(); } [Benchmark] public void HistogramHotPath() { this.histogram.Record(this.random.Next(MaxValue)); } [Benchmark] public void HistogramWith1LabelHotPath() { var tag1 = new KeyValuePair<string, object>("DimName1", this.dimensionValues[this.random.Next(0, 2)]); this.histogram.Record(this.random.Next(MaxValue), tag1); } [Benchmark] public void HistogramWith3LabelsHotPath() { var tag1 = new KeyValuePair<string, object>("DimName1", this.dimensionValues[this.random.Next(0, 10)]); var tag2 = new KeyValuePair<string, object>("DimName2", this.dimensionValues[this.random.Next(0, 10)]); var tag3 = new KeyValuePair<string, object>("DimName3", this.dimensionValues[this.random.Next(0, 10)]); this.histogram.Record(this.random.Next(MaxValue), tag1, tag2, tag3); } [Benchmark] public void HistogramWith5LabelsHotPath() { var tags = new TagList { { "DimName1", this.dimensionValues[this.random.Next(0, 2)] }, { "DimName2", this.dimensionValues[this.random.Next(0, 2)] }, { "DimName3", this.dimensionValues[this.random.Next(0, 5)] }, { "DimName4", this.dimensionValues[this.random.Next(0, 5)] }, { "DimName5", this.dimensionValues[this.random.Next(0, 10)] }, }; this.histogram.Record(this.random.Next(MaxValue), tags); } [Benchmark] public void HistogramWith7LabelsHotPath() { var tags = new TagList { { "DimName1", this.dimensionValues[this.random.Next(0, 2)] }, { "DimName2", this.dimensionValues[this.random.Next(0, 2)] }, { "DimName3", this.dimensionValues[this.random.Next(0, 5)] }, { "DimName4", this.dimensionValues[this.random.Next(0, 5)] }, { "DimName5", this.dimensionValues[this.random.Next(0, 5)] }, { "DimName6", this.dimensionValues[this.random.Next(0, 2)] }, { "DimName7", this.dimensionValues[this.random.Next(0, 1)] }, }; this.histogram.Record(this.random.Next(MaxValue), tags); } } }
TheStack
b4159c2291def6d3edd779d6847289c5435c8d88
C#code:C#
{"size": 917, "ext": "cs", "max_stars_repo_path": "Assets/New Assets/New Standard Assets/Scripts/Editor Helpers/Editor Scripts/ReaddAllOptionEvents.cs", "max_stars_repo_name": "Master109/open-brush", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/New Assets/New Standard Assets/Scripts/Editor Helpers/Editor Scripts/ReaddAllOptionEvents.cs", "max_issues_repo_name": "Master109/open-brush", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/New Assets/New Standard Assets/Scripts/Editor Helpers/Editor Scripts/ReaddAllOptionEvents.cs", "max_forks_repo_name": "Master109/open-brush", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.1041666667, "max_line_length": 54, "alphanum_fraction": 0.7175572519}
#if UNITY_EDITOR using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Extensions; namespace EternityEngine { [ExecuteInEditMode] public class ReaddAllOptionEvents : EditorScript { public GameObject go; public override void Do () { _Do (); } [MenuItem("Game/Readd all Option events")] public static void _Do () { #if USE_UNITY_EVENTS LogicModule.instance.unityEvents.Clear(); LogicModule.instance.handUnityEvents.Clear(); #endif #if USE_EVENTS LogicModule.instance.events.Clear(); LogicModule.instance.handEvents.Clear(); #endif Option[] options = FindObjectsOfType<Option>(true); for (int i = 0; i < options.Length; i ++) { Option option = options[i]; option.addEvents = true; option.OnValidate (); } } } } #else namespace EternityEngine { public class ReaddAllOptionEvents : EditorScript { } } #endif
TheStack
b415e25635e7c93fea6122ad4bba20e564c5e8b4
C#code:C#
{"size": 16087, "ext": "cs", "max_stars_repo_path": "Assets/EasyMobile/Scripts/Modules/GameServices/SavedGames/Native/iOSSavedGameNative.cs", "max_stars_repo_name": "AndreeBurlamaqui/HyperBeatMIX", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/EasyMobile/Scripts/Modules/GameServices/SavedGames/Native/iOSSavedGameNative.cs", "max_issues_repo_name": "AndreeBurlamaqui/HyperBeatMIX", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/EasyMobile/Scripts/Modules/GameServices/SavedGames/Native/iOSSavedGameNative.cs", "max_forks_repo_name": "AndreeBurlamaqui/HyperBeatMIX", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.3682092555, "max_line_length": 137, "alphanum_fraction": 0.6357928762}
#if UNITY_IOS using System; using System.Linq; using System.Runtime.InteropServices; using AOT; using EasyMobile.Internal; namespace EasyMobile.Internal.GameServices.iOS { #region iOSSavedGame Native API internal static class iOSSavedGameNative { //---------------------------------------------------------- // Saved Games API //---------------------------------------------------------- internal delegate void OpenSavedGameCallback(IntPtr response, IntPtr callbackPtr); internal delegate void SaveGameDataCallback(IntPtr response, IntPtr callbackPtr); internal delegate void LoadSavedGameDataCallback(IntPtr response, IntPtr callbackPtr); internal delegate void FetchSavedGamesCallback(IntPtr response, IntPtr callbackPtr); internal delegate void ResolveConflictingSavedGamesCallback(IntPtr response, IntPtr callbackPtr); internal delegate void DeleteSavedGameCallback(IntPtr response, IntPtr callbackPtr); [DllImport("__Internal")] internal static extern void EM_OpenSavedGame( string name, OpenSavedGameCallback callback, IntPtr secondaryCallback ); [DllImport("__Internal")] internal static extern void EM_SaveGameData( IntPtr gkSavedGamePtr, byte[] data, int dataLength, SaveGameDataCallback callback, IntPtr secondaryCallback); [DllImport("__Internal")] internal static extern void EM_LoadSavedGameData( IntPtr gkSavedGamePtr, LoadSavedGameDataCallback callback, IntPtr secondaryCallback); [DllImport("__Internal")] internal static extern void EM_FetchSavedGames( FetchSavedGamesCallback callback, IntPtr secondaryCallback); [DllImport("__Internal")] internal static extern void EM_ResolveConflictingSavedGames( IntPtr[] conflictingSavedGamePtrs, int savedGamesCount, byte[] data, int dataLength, ResolveConflictingSavedGamesCallback callback, IntPtr secondaryCallback); [DllImport("__Internal")] internal static extern void EM_DeleteSavedGame( string name, DeleteSavedGameCallback callback, IntPtr secondaryCallback); } #endregion // iOSSavedGame Native API #region iOSGKSavedGame internal class iOSGKSavedGame : InteropObject { [DllImport("__Internal")] internal static extern void EM_GKSavedGame_Ref(HandleRef self); [DllImport("__Internal")] internal static extern void EM_GKSavedGame_Unref(HandleRef self); [DllImport("__Internal")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool EM_GKSavedGame_IsOpen(HandleRef self); [DllImport("__Internal")] internal static extern int EM_GKSavedGame_Name(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] internal static extern int EM_GKSavedGame_DeviceName(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] internal static extern long EM_GKSavedGame_ModificationDate(HandleRef self); internal iOSGKSavedGame(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_GKSavedGame_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_GKSavedGame_Unref(selfPointer); } internal static iOSGKSavedGame FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new iOSGKSavedGame(pointer); } internal bool IsOpen { get { return EM_GKSavedGame_IsOpen(SelfPtr()); } } internal string Name { get { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_GKSavedGame_Name(SelfPtr(), strBuffer, strLen)); } } internal string DeviceName { get { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_GKSavedGame_DeviceName(SelfPtr(), strBuffer, strLen)); } } internal DateTime ModificationDate { get { return Util.FromMillisSinceUnixEpoch( EM_GKSavedGame_ModificationDate(SelfPtr())); } } } #endregion // iOSGKSavedGame #region OpenSavedGameResponse internal class OpenSavedGameResponse : InteropObject { [DllImport("__Internal")] internal static extern void EM_OpenSavedGameResponse_Ref(HandleRef self); [DllImport("__Internal")] internal static extern void EM_OpenSavedGameResponse_Unref(HandleRef self); [DllImport("__Internal")] internal static extern int EM_OpenSavedGameResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] internal static extern int EM_OpenSavedGameResponse_GetData_Length(HandleRef self); [DllImport("__Internal")] internal static extern IntPtr EM_OpenSavedGameResponse_GetData_GetElement(HandleRef self, int index); internal OpenSavedGameResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_OpenSavedGameResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_OpenSavedGameResponse_Unref(selfPointer); } internal static OpenSavedGameResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new OpenSavedGameResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_OpenSavedGameResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } internal iOSGKSavedGame[] GetResultSavedGames() { return PInvokeUtil.ToEnumerable<iOSGKSavedGame>( EM_OpenSavedGameResponse_GetData_Length(SelfPtr()), index => iOSGKSavedGame.FromPointer(EM_OpenSavedGameResponse_GetData_GetElement(SelfPtr(), index)) ).Cast<iOSGKSavedGame>().ToArray(); } } #endregion // OpenSavedGameResponse #region SaveGameDataResponse internal class SaveGameDataResponse : InteropObject { [DllImport("__Internal")] internal static extern void EM_SaveGameDataResponse_Ref(HandleRef self); [DllImport("__Internal")] internal static extern void EM_SaveGameDataResponse_Unref(HandleRef self); [DllImport("__Internal")] internal static extern int EM_SaveGameDataResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] internal static extern IntPtr EM_SaveGameDataResponse_GetData(HandleRef self); internal SaveGameDataResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_SaveGameDataResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_SaveGameDataResponse_Unref(selfPointer); } internal static SaveGameDataResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new SaveGameDataResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_SaveGameDataResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } internal iOSGKSavedGame GetSavedGame() { return iOSGKSavedGame.FromPointer(EM_SaveGameDataResponse_GetData(SelfPtr())); } } #endregion // SavedGameDataResponse #region LoadSavedGameDataResponse internal class LoadSavedGameDataResponse : InteropObject { [DllImport("__Internal")] internal static extern void EM_LoadSavedGameDataResponse_Ref(HandleRef self); [DllImport("__Internal")] internal static extern void EM_LoadSavedGameDataResponse_Unref(HandleRef self); [DllImport("__Internal")] internal static extern int EM_LoadSavedGameDataResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] internal static extern int EM_LoadSavedGameDataResponse_GetData(HandleRef self, [In, Out] byte[] buffer, int byteCount); internal LoadSavedGameDataResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_LoadSavedGameDataResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_LoadSavedGameDataResponse_Unref(selfPointer); } internal static LoadSavedGameDataResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new LoadSavedGameDataResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_LoadSavedGameDataResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } internal byte[] GetData() { return PInvokeUtil.GetNativeArray<byte>((buffer, length) => EM_LoadSavedGameDataResponse_GetData(SelfPtr(), buffer, length)); } } #endregion // LoadSavedGameDataResponse #region FetchSavedGamesResponse internal class FetchSavedGamesResponse : InteropObject { [DllImport("__Internal")] private static extern void EM_FetchSavedGamesResponse_Ref(HandleRef self); [DllImport("__Internal")] private static extern void EM_FetchSavedGamesResponse_Unref(HandleRef self); [DllImport("__Internal")] private static extern int EM_FetchSavedGamesResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] private static extern int EM_FetchSavedGamesResponse_GetData_Length(HandleRef self); [DllImport("__Internal")] private static extern IntPtr EM_FetchSavedGamesResponse_GetData_GetElement(HandleRef self, int index); internal FetchSavedGamesResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_FetchSavedGamesResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_FetchSavedGamesResponse_Unref(selfPointer); } internal static FetchSavedGamesResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new FetchSavedGamesResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_FetchSavedGamesResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } internal iOSGKSavedGame[] GetFetchedSavedGames() { return PInvokeUtil.ToEnumerable<iOSGKSavedGame>( EM_FetchSavedGamesResponse_GetData_Length(SelfPtr()), index => iOSGKSavedGame.FromPointer(EM_FetchSavedGamesResponse_GetData_GetElement(SelfPtr(), index)) ).Cast<iOSGKSavedGame>().ToArray(); } } #endregion #region ResolveConflictResponse internal class ResolveConflictResponse : InteropObject { [DllImport("__Internal")] private static extern void EM_ResolveConflictResponse_Ref(HandleRef self); [DllImport("__Internal")] private static extern void EM_ResolveConflictResponse_Unref(HandleRef self); [DllImport("__Internal")] private static extern int EM_ResolveConflictResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); [DllImport("__Internal")] private static extern int EM_ResolveConflictResponse_GetData_Length(HandleRef self); [DllImport("__Internal")] private static extern IntPtr EM_ResolveConflictResponse_GetData_GetElement(HandleRef self, int index); internal ResolveConflictResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_ResolveConflictResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_ResolveConflictResponse_Unref(selfPointer); } internal static ResolveConflictResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new ResolveConflictResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_ResolveConflictResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } internal iOSGKSavedGame[] GetSavedGames() { return PInvokeUtil.ToEnumerable<iOSGKSavedGame>( EM_ResolveConflictResponse_GetData_Length(SelfPtr()), index => iOSGKSavedGame.FromPointer(EM_ResolveConflictResponse_GetData_GetElement(SelfPtr(), index)) ).Cast<iOSGKSavedGame>().ToArray(); } } #endregion // ResolveConflictResponse #region DeleteSavedGameResponse internal class DeleteSavedGameResponse : InteropObject { [DllImport("__Internal")] private static extern void EM_DeleteSavedGameResponse_Ref(HandleRef self); [DllImport("__Internal")] private static extern void EM_DeleteSavedGameResponse_Unref(HandleRef self); [DllImport("__Internal")] private static extern int EM_DeleteSavedGameResponse_ErrorDescription(HandleRef self, [In, Out] byte[] strBuffer, int strLen); internal DeleteSavedGameResponse(IntPtr selfPointer) : base(selfPointer) { } protected override void AttachHandle(HandleRef selfPointer) { EM_DeleteSavedGameResponse_Ref(selfPointer); } protected override void ReleaseHandle(HandleRef selfPointer) { EM_DeleteSavedGameResponse_Unref(selfPointer); } internal static DeleteSavedGameResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new DeleteSavedGameResponse(pointer); } internal string GetError() { return PInvokeUtil.GetNativeString((strBuffer, strLen) => EM_DeleteSavedGameResponse_ErrorDescription(SelfPtr(), strBuffer, strLen)); } } #endregion // DeleteSavedGameResponse } #endif
TheStack
b4174f85a3ffaafce807967ad22f8ec3975bda05
C#code:C#
{"size": 2128, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Services/PlayerStartsService.cs", "max_stars_repo_name": "gellios3/My-Sudoku", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Services/PlayerStartsService.cs", "max_issues_repo_name": "gellios3/My-Sudoku", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Services/PlayerStartsService.cs", "max_forks_repo_name": "gellios3/My-Sudoku", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.1304347826, "max_line_length": 79, "alphanum_fraction": 0.4816729323}
using Signals.MainGame; using System.Threading.Tasks; namespace Services { public class PlayerStartsService { /// <summary> /// Update moves signal /// </summary> [Inject] public UpdateMovesSignal UpdateMovesSignal { get; set; } /// <summary> /// On show finish game signal /// </summary> [Inject] public OnShowFinishGameSignal OnShowFinishGameSignal { get; set; } /// <summary> /// Update timer signal /// </summary> [Inject] public UpdateTimerSignal UpdateTimerSignal { get; set; } public bool HasPlaying { get; set; } public bool HasGameOver { get; set; } private int _elapsedSeconds; public int ElapsedSeconds { get => _elapsedSeconds; set { _elapsedSeconds = value; UpdateTimerSignal.Dispatch($"{value / 60:D2}:{value % 60:D2}"); } } private int _moves; public int Moves { get => _moves; set { _moves = value; UpdateMovesSignal.Dispatch($"{value:D3}"); } } public void CancelLevel() { // if (gameFinish.isActiveAndEnabled) // return; if (HasGameOver) return; HasPlaying = false; OnShowFinishGameSignal.Dispatch(false, _elapsedSeconds, _moves); } public void WinLevel() { OnShowFinishGameSignal.Dispatch(true, _elapsedSeconds, _moves); } private void OnDestroy() { HasPlaying = false; } private async void StartTimer() { while (HasPlaying) { await Task.Delay(1000); ElapsedSeconds++; } } public void BoardReadyToPlay() { HasPlaying = true; ElapsedSeconds = 0; Moves = 0; StartTimer(); } } }
TheStack
b418095b4e345f7c40d1229781a52d72a3e65b07
C#code:C#
{"size": 1728, "ext": "cs", "max_stars_repo_path": "ScrabbleScorer.Tests/ModelTests/Word.Tests.cs", "max_stars_repo_name": "MarielHamson/Scrabble-Scorer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ScrabbleScorer.Tests/ModelTests/Word.Tests.cs", "max_issues_repo_name": "MarielHamson/Scrabble-Scorer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScrabbleScorer.Tests/ModelTests/Word.Tests.cs", "max_forks_repo_name": "MarielHamson/Scrabble-Scorer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.4181818182, "max_line_length": 79, "alphanum_fraction": 0.6516203704}
using Microsoft.VisualStudio.TestTools.UnitTesting; using ScrabbleScorer.Models; using System.Collections.Generic; using System; namespace ScrabbleScorer.Tests { [TestClass] public class WordTests { [TestMethod] public void WordConstructor_CreatingInstanceOfWord_Word() { Word newWord = new Word("test"); //We pass in "test" as an argument here. Assert.AreEqual(typeof(Word), newWord.GetType()); } //Arrange //Act //Assert.AreEqual(ExpectedResult, Code_To_Test); [TestMethod] public void WordConstructor_WordReceivedIsWordReturned_True() { string input = "apple"; Word newWord = new Word(input); string output = newWord.Input; Assert.AreEqual(output, input); } [TestMethod] public void StringToLetterArray_WordReceivedIsSplitIntoArray_True() { string input = "apple"; Word newWord = new Word(input); string[] testArray = { "a", "p", "p", "l", "e" }; string[] letterArray = newWord.StringToLetterArray("test"); Assert.AreEqual(testArray.GetType(), letterArray.GetType()); // string input = "apple"; // Word newWord = new Word(input); // String.Split(","); // string output = newWord.Input; // string[] letterArray = output.StringToLetterArray(); // string[] appleArray = { "a", "p", "p", "l", "e" }; // Assert.AreEqual(appleArray, letterArray); } [TestMethod] public void CheckForScore_CharacterValuesAreSummed_True() { Word newWord = new Word("apple"); string[] lettersSeparated = newWord.StringToLetterArray(); int testScore = 9; int score = newWord.CheckForScore(); Assert.AreEqual(testScore, score); } } }
TheStack
b418a31308dc9ebd9de5ed13f9a8b94859aa1739
C#code:C#
{"size": 476, "ext": "cs", "max_stars_repo_path": "Core/TimeType.cs", "max_stars_repo_name": "Kussy/Risk-basedProjectValue", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Core/TimeType.cs", "max_issues_repo_name": "Kussy/Risk-basedProjectValue", "max_issues_repo_issues_event_min_datetime": "2018-02-23T13:26:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-20T01:13:49.000Z", "max_forks_repo_path": "Core/TimeType.cs", "max_forks_repo_name": "Kussy/Risk-basedProjectValue", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 18.0, "max_forks_count": null, "avg_line_length": 22.6666666667, "max_line_length": 38, "alphanum_fraction": 0.4558823529}
namespace Kussy.Analysis.Project.Core { /// <summary>時間種別列挙型</summary> public enum TimeType { /// <summary>年</summary> Year = 0, /// <summary>月</summary> Month = 1, /// <summary>週</summary> Week = 2, /// <summary>日</summary> Day = 3, /// <summary>時間</summary> Hour = 4, /// <summary>分</summary> Minute = 5, /// <summary>秒</summary> Second = 6, } }
TheStack
b418cda862dc694977e3c7a568ca9ca1149cd9a3
C#code:C#
{"size": 380, "ext": "cs", "max_stars_repo_path": "TwoCheckoutCore/Entities/AuthShippingAddress.cs", "max_stars_repo_name": "slamj1/2checkout-dotnetcore", "max_stars_repo_stars_event_min_datetime": "2015-07-14T13:02:32.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-19T14:39:44.000Z", "max_issues_repo_path": "TwoCheckoutCore/Entities/AuthShippingAddress.cs", "max_issues_repo_name": "slamj1/2checkout-dotnetcore", "max_issues_repo_issues_event_min_datetime": "2015-05-21T13:02:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T23:59:59.000Z", "max_forks_repo_path": "TwoCheckoutCore/Entities/AuthShippingAddress.cs", "max_forks_repo_name": "slamj1/2checkout-dotnetcore", "max_forks_repo_forks_event_min_datetime": "2015-02-04T18:36:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-21T07:29:06.000Z"}
{"max_stars_count": 12.0, "max_issues_count": 5.0, "max_forks_count": 13.0, "avg_line_length": 27.1428571429, "max_line_length": 45, "alphanum_fraction": 0.5815789474}
namespace TwoCheckout { public class AuthShippingAddress { public string name { get; set; } public string addrLine1 { get; set; } public string addrLine2 { get; set; } public string city { get; set; } public string state { get; set; } public string zipCode { get; set; } public string country { get; set; } } }
TheStack
b41ad50b3f92f8f405702d75e00016d369b79f8a
C#code:C#
{"size": 2141, "ext": "cs", "max_stars_repo_path": "GuiFunctions/MetaDraw/CrosslinkSpectrumMatchPlot.cs", "max_stars_repo_name": "Yuling1996/MetaMorpheus", "max_stars_repo_stars_event_min_datetime": "2017-03-03T04:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T22:22:32.000Z", "max_issues_repo_path": "GuiFunctions/MetaDraw/CrosslinkSpectrumMatchPlot.cs", "max_issues_repo_name": "Yuling1996/MetaMorpheus", "max_issues_repo_issues_event_min_datetime": "2017-01-06T00:08:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:50:50.000Z", "max_forks_repo_path": "GuiFunctions/MetaDraw/CrosslinkSpectrumMatchPlot.cs", "max_forks_repo_name": "Yuling1996/MetaMorpheus", "max_forks_repo_forks_event_min_datetime": "2016-12-27T17:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T15:17:22.000Z"}
{"max_stars_count": 62.0, "max_issues_count": 1002.0, "max_forks_count": 62.0, "avg_line_length": 42.82, "max_line_length": 178, "alphanum_fraction": 0.6861279776}
using EngineLayer; using MassSpectrometry; using Proteomics.Fragmentation; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace GuiFunctions { public class CrosslinkSpectrumMatchPlot : PeptideSpectrumMatchPlot { public CrosslinkSpectrumMatchPlot(OxyPlot.Wpf.PlotView plotView, Canvas sequenceDrawingCanvas, PsmFromTsv csm, MsDataScan scan) : base(plotView, sequenceDrawingCanvas, csm, scan, csm.MatchedIons) { SequenceDrawingCanvas.Height = 150; // annotate beta peptide base sequence AnnotateBaseSequence(csm.BetaPeptideBaseSequence, csm.BetaPeptideFullSequence, 100, csm.BetaPeptideMatchedIons); // annotate beta peptide matched ions AnnotateMatchedIons(isBetaPeptide: true, csm.BetaPeptideMatchedIons); // annotate crosslinker int alphaSite = int.Parse(Regex.Match(SpectrumMatch.FullSequence, @"\d+").Value); int betaSite = int.Parse(Regex.Match(SpectrumMatch.BetaPeptideFullSequence, @"\d+").Value); AnnotateCrosslinker(SequenceDrawingCanvas, new Point(alphaSite * MetaDrawSettings.AnnotatedSequenceTextSpacing, 50), new Point(betaSite * MetaDrawSettings.AnnotatedSequenceTextSpacing, 90), Colors.Black); ZoomAxes(csm.MatchedIons.Concat(csm.BetaPeptideMatchedIons), yZoom: 1.5); RefreshChart(); } private static void AnnotateCrosslinker(Canvas cav, Point alphaBotLoc, Point betaBotLoc, Color clr) { Polyline bot = new Polyline(); double distance = (betaBotLoc.Y - alphaBotLoc.Y) / 2; bot.Points = new PointCollection() { alphaBotLoc, new Point(alphaBotLoc.X, alphaBotLoc.Y + distance), new Point(betaBotLoc.X, alphaBotLoc.Y + distance), betaBotLoc }; bot.Stroke = new SolidColorBrush(clr); bot.StrokeThickness = 2; cav.Children.Add(bot); } } }
TheStack
b41b46f76e5d6da04c17763584145be34e28a142
C#code:C#
{"size": 5704, "ext": "cs", "max_stars_repo_path": "example/GetSocialSdkDemo/Assets/GetSocialDemo/Scripts/GUI/Sections/ChatMessagesView.cs", "max_stars_repo_name": "getsocial-im/getsocial-unity-sdk", "max_stars_repo_stars_event_min_datetime": "2015-02-26T16:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T04:47:32.000Z", "max_issues_repo_path": "example/GetSocialSdkDemo/Assets/GetSocialDemo/Scripts/GUI/Sections/ChatMessagesView.cs", "max_issues_repo_name": "Sohail8338/getsocial-unity-sdk", "max_issues_repo_issues_event_min_datetime": "2015-10-06T04:22:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T13:25:58.000Z", "max_forks_repo_path": "example/GetSocialSdkDemo/Assets/GetSocialDemo/Scripts/GUI/Sections/ChatMessagesView.cs", "max_forks_repo_name": "Sohail8338/getsocial-unity-sdk", "max_forks_repo_forks_event_min_datetime": "2016-12-28T04:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T12:03:19.000Z"}
{"max_stars_count": 21.0, "max_issues_count": 7.0, "max_forks_count": 7.0, "avg_line_length": 30.0210526316, "max_line_length": 110, "alphanum_fraction": 0.5873071529}
using System; using System.Collections.Generic; using UnityEngine; using GetSocialSdk.Core; using Assets.GetSocialDemo.Scripts.Utils; public class ChatMessagesView : DemoMenuSection { public ChatId _chatId; private string _messageText; private bool _useCustomImage; private bool _useCustomVideo; private ChatMessagesPagingQuery _pagingQuery; private string _refreshCursor; private string _nextCursor; private string _previousCursor; public ChatMessagesView() { } public void Awake() { if (_console == null) { _console = gameObject.GetComponent<DemoAppConsole>().Init(); } } public void SetChatId(ChatId chatId) { Debug.Log("Setting chatid: " + chatId); _chatId = chatId; LoadInitialMessages(); } protected override bool IsBackButtonActive() { return true; } private List<ChatMessage> _messages; protected override void DrawSectionBody() { GUILayout.BeginHorizontal(); _messageText = GUILayout.TextField(_messageText, GSStyles.TextField); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); DemoGuiUtils.DrawRow(() => { _useCustomImage = GUILayout.Toggle(_useCustomImage, "", GSStyles.Toggle); GUILayout.Label("Send Image", GSStyles.NormalLabelText, GUILayout.Width(Screen.width * 0.25f)); }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); DemoGuiUtils.DrawRow(() => { _useCustomVideo = GUILayout.Toggle(_useCustomVideo, "", GSStyles.Toggle); GUILayout.Label("Send Video", GSStyles.NormalLabelText, GUILayout.Width(Screen.width * 0.25f)); }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); DemoGuiUtils.DrawButton("Send", () => { SendChatMessage(); }, true, GSStyles.Button); DemoGuiUtils.DrawButton("Load Older", () => { LoadOlderMessages(); }, true, GSStyles.Button); DemoGuiUtils.DrawButton("Load Newer", () => { LoadNewerMessages(true); }, true, GSStyles.Button); GUILayout.EndHorizontal(); foreach (var message in _messages) { DemoGuiUtils.DrawRow(DrawMessage(message)); } } private Action DrawMessage(ChatMessage message) { return () => { GUILayout.Label("Author: " + message.Author.DisplayName, GSStyles.NormalLabelText); GUILayout.Label("Text: " + message.Text, GSStyles.NormalLabelText); DemoGuiUtils.DrawButton("Actions", () => ShowActions(message), style: GSStyles.Button); }; } private void ShowActions(ChatMessage message) { var popup = Dialog().WithTitle("Actions"); popup.AddAction("Info", () => _console.LogD(message.ToString())); popup.AddAction("Cancel", () => { }); popup.Show(); } protected override string GetTitle() { return "Chat with ";// + Receiver.DisplayName; } private void LoadInitialMessages() { _messages = new List<ChatMessage>(); _pagingQuery = new ChatMessagesPagingQuery(ChatMessagesQuery.InChat(_chatId)); LoadMessages((entries) => { _messages.AddAll(entries); LoadNewerMessages(false); }); } private void LoadOlderMessages() { if (_previousCursor != null && _previousCursor.Length > 0) { _pagingQuery = _pagingQuery.PreviousMessagesCursor(_previousCursor); LoadMessages((entries) => { _messages.InsertRange(0, entries); }); } } private void LoadNewerMessages(bool refresh) { if (_nextCursor != null && _nextCursor.Length > 0) { _pagingQuery = _pagingQuery.NextMessagesCursor(_nextCursor); LoadMessages((entries) => { _messages.AddAll(entries); LoadNewerMessages(false); }); } else if (_refreshCursor != null && refresh) { _pagingQuery = _pagingQuery.NextMessagesCursor(_refreshCursor); LoadMessages((entries) => { _messages.AddAll(entries); LoadNewerMessages(false); }); } } public void LoadMessages(Action<List<ChatMessage>> action) { Communities.GetChatMessages(_pagingQuery, (result) => { _previousCursor = result.PreviousMessagesCursor; _nextCursor = result.NextMessagesCursor; _refreshCursor = result.RefreshCursor; action(result.Messages); }, (error) => { _console.LogE("Failed to get messages, error: " + error); } ); } private void SendChatMessage() { var content = new ChatMessageContent(); content.Text = _messageText; if (_useCustomImage) { content.AddMediaAttachment(MediaAttachment.WithImage(Resources.Load<Texture2D>("activityImage"))); } if (_useCustomVideo) { content.AddMediaAttachment(MediaAttachment.WithVideo(DemoUtils.LoadSampleVideoBytes())); } Communities.SendChatMessage(content, _chatId, (message) => { _messageText = null; _useCustomImage = false; _useCustomVideo = false; LoadNewerMessages(true); }, (error) => { _console.LogE("Failed to send message, error: " + error); }); } }
TheStack
b41c00a50d480eb74c87e7f45d6b66a06d1b4dbe
C#code:C#
{"size": 646, "ext": "cs", "max_stars_repo_path": "test/DazPaz.UnitOfWork.Tests/Properties/AssemblyInfo.cs", "max_stars_repo_name": "dazpaz/UnitOfWork", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/DazPaz.UnitOfWork.Tests/Properties/AssemblyInfo.cs", "max_issues_repo_name": "dazpaz/UnitOfWork", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/DazPaz.UnitOfWork.Tests/Properties/AssemblyInfo.cs", "max_forks_repo_name": "dazpaz/UnitOfWork", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.7619047619, "max_line_length": 56, "alphanum_fraction": 0.7554179567}
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("DazPaz.UnitOfWork.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DazPaz.UnitOfWork.Tests")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("5501d2ac-aaa9-4a17-aec2-1f45cdf450f6")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.*")] [assembly: AssemblyFileVersion("0.1.0.0")]
TheStack
b41c07d1b2a0d7b7a7a083ea1c99e1293a1a28df
C#code:C#
{"size": 1245, "ext": "cs", "max_stars_repo_path": "StudyingPatterns/Classes/RandomGenerator.cs", "max_stars_repo_name": "KolyaNET/StudyingPatterns", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StudyingPatterns/Classes/RandomGenerator.cs", "max_issues_repo_name": "KolyaNET/StudyingPatterns", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StudyingPatterns/Classes/RandomGenerator.cs", "max_forks_repo_name": "KolyaNET/StudyingPatterns", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.4081632653, "max_line_length": 122, "alphanum_fraction": 0.6570281124}
using System; using System.Security.Cryptography; namespace Classes { /// <summary> /// https://stackoverflow.com/questions/42426420/how-to-generate-a-cryptographically-secure-random-integer-within-a-range /// TODO: Не потокобезопасно. /// </summary> public sealed class RandomGenerator { private readonly RNGCryptoServiceProvider _csp; public RandomGenerator() { _csp = new RNGCryptoServiceProvider(); } public int Next(int minValue, int maxExclusiveValue) { if (minValue >= maxExclusiveValue) throw new ArgumentOutOfRangeException(nameof(minValue), "MinValue must be lower than maxExclusiveValue"); var diff = (long)maxExclusiveValue - minValue; var upperBound = uint.MaxValue / diff * diff; uint ui; do { ui = GetRandomUInt(); } while (ui >= upperBound); return (int)(minValue + (ui % diff)); } private uint GetRandomUInt() { var randomBytes = GenerateRandomBytes(sizeof(uint)); return BitConverter.ToUInt32(randomBytes, 0); } private byte[] GenerateRandomBytes(int bytesNumber) { var buffer = new byte[bytesNumber]; _csp.GetBytes(buffer); return buffer; } } }
TheStack
b41d5c783430f3e5d06cec72310262baa6ce5c00
C#code:C#
{"size": 1328, "ext": "cs", "max_stars_repo_path": "Problems/SPP/TS4SPP/TS4SPP.cs", "max_stars_repo_name": "yasserglez/metaheuristics", "max_stars_repo_stars_event_min_datetime": "2015-02-05T17:46:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T11:35:17.000Z", "max_issues_repo_path": "Problems/SPP/TS4SPP/TS4SPP.cs", "max_issues_repo_name": "yasserglez/metaheuristics", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Problems/SPP/TS4SPP/TS4SPP.cs", "max_forks_repo_name": "yasserglez/metaheuristics", "max_forks_repo_forks_event_min_datetime": "2015-02-02T03:22:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T13:23:10.000Z"}
{"max_stars_count": 26.0, "max_issues_count": null, "max_forks_count": 13.0, "avg_line_length": 24.1454545455, "max_line_length": 96, "alphanum_fraction": 0.7010542169}
using System; namespace Metaheuristics { public class TS4SPP : IMetaheuristic, ITunableMetaheuristic { protected int timePenalty = 100; public double neighborChecksFactor = 0.25; public double tabuListFactor = 0.50; public double rclTreshold = 1.0; public void Start(string inputFile, string outputFile, int timeLimit) { SPPInstance instance = new SPPInstance(inputFile); int neighborChecks = (int) Math.Ceiling(neighborChecksFactor * (instance.NumberSubsets - 1)); int tabuListLength = (int) Math.Ceiling(tabuListFactor * instance.NumberItems); DiscreteTS ts = new DiscreteTS4SPP(instance, rclTreshold, tabuListLength, neighborChecks); ts.Run(timeLimit - timePenalty); SPPSolution solution = new SPPSolution(instance, ts.BestSolution); solution.Write(outputFile); } public string Name { get { return "TS for SPP"; } } public MetaheuristicType Type { get { return MetaheuristicType.TS; } } public ProblemType Problem { get { return ProblemType.SPP; } } public string[] Team { get { return About.Team; } } public void UpdateParameters (double[] parameters) { timePenalty = (int) parameters[0]; neighborChecksFactor = parameters[1]; tabuListFactor = parameters[2]; rclTreshold = parameters[3]; } } }
TheStack
b4234b5c0e102322895997f07e091db96efc659f
C#code:C#
{"size": 1439, "ext": "cs", "max_stars_repo_path": "GDAPI/GDAPI.Tests/Objects/Music/TimeSignatureTests.cs", "max_stars_repo_name": "Syudagye/GDAPI", "max_stars_repo_stars_event_min_datetime": "2019-08-16T05:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T04:55:07.000Z", "max_issues_repo_path": "GDAPI/GDAPI.Tests/Objects/Music/TimeSignatureTests.cs", "max_issues_repo_name": "gd-Pythagorean/GDAPI", "max_issues_repo_issues_event_min_datetime": "2019-08-13T11:18:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-21T02:23:16.000Z", "max_forks_repo_path": "GDAPI/GDAPI.Tests/Objects/Music/TimeSignatureTests.cs", "max_forks_repo_name": "gd-Pythagorean/GDAPI", "max_forks_repo_forks_event_min_datetime": "2019-08-15T14:55:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T12:06:05.000Z"}
{"max_stars_count": 14.0, "max_issues_count": 28.0, "max_forks_count": 12.0, "avg_line_length": 44.96875, "max_line_length": 168, "alphanum_fraction": 0.6511466296}
using GDAPI.Objects.Music; using NUnit.Framework; using NUnit.Framework.Constraints; using System; namespace GDAPI.Tests.Objects.Music { public class TimeSignatureTests { [Test] public void TimeSignatureStuff() { var commonTimeSignature = new TimeSignature(4, 4); Assert.Catch(() => commonTimeSignature.Denominator = 5, "The moment non-binary denominators are acceptable, call me at +306969696969"); Assert.Catch(() => commonTimeSignature.Beats = -2, "How would negative beats even be considered in a time signature?"); Assert.Catch(() => commonTimeSignature.Denominator = -5, "Somebody has to teach computers that negative denominators make even less sense in this context"); int den = 1; for (int i = 0; i < sizeof(int) * 8 - 1; i++, den <<= 1) Assert.DoesNotThrow(() => commonTimeSignature.Denominator = den, $"Unacceptable binary denominator {den}"); } [Test] public void Parse() { bool success = TimeSignature.TryParse("4/4", out var commonTimeSignature); Assert.IsTrue(success, "Cannot parse the string representation of the time signature which literally is splitting two values by this character: /"); Assert.AreEqual(new TimeSignature(4, 4), commonTimeSignature, "Apparently this is not 4/4, even if correctly parsed"); } } }
TheStack
b423519369a631f7371424dbe0d30ea494eac0c4
C#code:C#
{"size": 2122, "ext": "cs", "max_stars_repo_path": "Capgemini.Xrm.CdsDataMigrator/Capgemini.Xrm.CdsDataMigratorLibrary/Models/ImportConfigSettingscs.cs", "max_stars_repo_name": "Capgemini/xrm-datamigration-xrmtoolbox", "max_stars_repo_stars_event_min_datetime": "2021-02-14T09:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-06T18:53:14.000Z", "max_issues_repo_path": "Capgemini.Xrm.CdsDataMigrator/Capgemini.Xrm.CdsDataMigratorLibrary/Models/ImportConfigSettingscs.cs", "max_issues_repo_name": "Capgemini/xrm-datamigration-xrmtoolbox", "max_issues_repo_issues_event_min_datetime": "2020-12-31T09:44:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:46:35.000Z", "max_forks_repo_path": "Capgemini.Xrm.CdsDataMigrator/Capgemini.Xrm.CdsDataMigratorLibrary/Models/ImportConfigSettingscs.cs", "max_forks_repo_name": "Capgemini/xrm-datamigration-xrmtoolbox", "max_forks_repo_forks_event_min_datetime": "2020-09-25T20:37:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T18:48:55.000Z"}
{"max_stars_count": 7.0, "max_issues_count": 46.0, "max_forks_count": 4.0, "avg_line_length": 29.4722222222, "max_line_length": 140, "alphanum_fraction": 0.5810556079}
using System; using System.Collections.Generic; using System.Text; namespace Capgemini.Xrm.CdsDataMigratorLibrary.Models { public class ImportConfigSettingscs { public string JsonFilePath { get; set; } public string JsonFilePathLoad { get; set; } public Dictionary<string, Dictionary<Guid, Guid>> Mappings { get; private set; } = new Dictionary<string, Dictionary<Guid, Guid>>(); public bool FailedValidation { get; set; } public bool FailedValidationLoading { get; set; } public string FailedValidationLoadingMessage { get; set; } public string FailedValidationMessage { get; set; } public string SuccessValidationMessage { get; set; } public string SuccessValidationMessageLoading { get; set; } public void ValidateAll() { ValidateFailure(); ValidateSuccessss(); } public void ValidateLoading() { FailedValidationLoading = false; var message = new StringBuilder(); if (string.IsNullOrEmpty(JsonFilePathLoad) || JsonFilePathLoad == null) { FailedValidationLoading = true; message.AppendLine("Json file path is empty"); } else { message.AppendLine("Loading Success"); SuccessValidationMessageLoading = message.ToString(); } FailedValidationLoadingMessage = message.ToString(); } private void ValidateFailure() { FailedValidation = false; var message = new StringBuilder(); if (string.IsNullOrEmpty(JsonFilePath)) { message.AppendLine("Import config file path is empty"); FailedValidation = true; } FailedValidationMessage = message.ToString(); } private void ValidateSuccessss() { if (!FailedValidation) { SuccessValidationMessage = "Successfully created json file"; } } } }
TheStack
b4248bfd269a169554a8dd1b02c9ff45546f997d
C#code:C#
{"size": 444, "ext": "cs", "max_stars_repo_path": "src/Amazon.Sqs/Responses/ChangeMessageVisibilityResponse.cs", "max_stars_repo_name": "TheJVaughan/Amazon", "max_stars_repo_stars_event_min_datetime": "2016-11-18T21:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T13:19:03.000Z", "max_issues_repo_path": "src/Amazon.Sqs/Responses/ChangeMessageVisibilityResponse.cs", "max_issues_repo_name": "TheJVaughan/Amazon", "max_issues_repo_issues_event_min_datetime": "2017-09-22T17:16:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T16:31:42.000Z", "max_forks_repo_path": "src/Amazon.Sqs/Responses/ChangeMessageVisibilityResponse.cs", "max_forks_repo_name": "TheJVaughan/Amazon", "max_forks_repo_forks_event_min_datetime": "2017-03-02T11:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T17:13:07.000Z"}
{"max_stars_count": 22.0, "max_issues_count": 8.0, "max_forks_count": 12.0, "avg_line_length": 23.3684210526, "max_line_length": 68, "alphanum_fraction": 0.740990991}
#nullable disable using System.Xml.Serialization; namespace Amazon.Sqs.Models; public sealed class ChangeMessageVisibilityResponse { [XmlElement("ResponseMetadata")] public ResponseMetadata ResponseMetadata { get; init; } } /* <ChangeMessageVisibilityResponse> <ResponseMetadata> <RequestId>6a7a282a-d013-4a59-aba9-335b0fa48bed</RequestId> </ResponseMetadata> </ChangeMessageVisibilityResponse> */
TheStack
b4285fd1becdf8c492fed471ab6a5c1526dc73f1
C#code:C#
{"size": 876, "ext": "cs", "max_stars_repo_path": "ReloadableRFID.Library/Repositories/AccountTypeRepository.cs", "max_stars_repo_name": "aplasca23/dumapit_clavaton_rfid", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ReloadableRFID.Library/Repositories/AccountTypeRepository.cs", "max_issues_repo_name": "aplasca23/dumapit_clavaton_rfid", "max_issues_repo_issues_event_min_datetime": "2021-01-19T17:21:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T17:21:09.000Z", "max_forks_repo_path": "ReloadableRFID.Library/Repositories/AccountTypeRepository.cs", "max_forks_repo_name": "aplasca23/dumapit_clavaton_rfid", "max_forks_repo_forks_event_min_datetime": "2021-01-13T05:43:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T17:11:40.000Z"}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": 3.0, "avg_line_length": 32.4444444444, "max_line_length": 108, "alphanum_fraction": 0.6872146119}
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Dapper; using MySql.Data.MySqlClient; using ReloadableRFID.Library.Models; namespace ReloadableRFID.Library.Repositories { public class AccountTypeRepository { public static async Task<int> InsertAccountTypeAsync(AccountTypeModel model) { using (IDbConnection connection = new MySqlConnection(DBConnectionString.GetConnectionString())) { string query = "insert into account_types (AccountType) values (upper(@AccountType))"; var parameters = new DynamicParameters(); parameters.Add("AccountType", model.AccountType, DbType.String); return await connection.ExecuteAsync(query, parameters); } } } }
TheStack
b4288c958d7ea7d8b64f3e04abd366fe11155343
C#code:C#
{"size": 3827, "ext": "cs", "max_stars_repo_path": "src/Audit.EntityFramework/ConfigurationApi/EntityFrameworkProviderConfigurator.cs", "max_stars_repo_name": "VictorioBerra/Audit.NET", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Audit.EntityFramework/ConfigurationApi/EntityFrameworkProviderConfigurator.cs", "max_issues_repo_name": "VictorioBerra/Audit.NET", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Audit.EntityFramework/ConfigurationApi/EntityFrameworkProviderConfigurator.cs", "max_forks_repo_name": "VictorioBerra/Audit.NET", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.1696428571, "max_line_length": 178, "alphanum_fraction": 0.5994251372}
using System; using Audit.Core; using System.Reflection; #if NETSTANDARD1_5 || NETSTANDARD2_0 || NET461 using Microsoft.EntityFrameworkCore; #elif NET45 using System.Data.Entity; #endif namespace Audit.EntityFramework.ConfigurationApi { public class EntityFrameworkProviderConfigurator : IEntityFrameworkProviderConfigurator, IEntityFrameworkProviderConfiguratorAction, IEntityFrameworkProviderConfiguratorExtra { internal bool _ignoreMatchedProperties = false; internal Func<Type, Type> _auditTypeMapper; internal Func<AuditEvent, EventEntry, object, bool> _auditEntityAction; internal Func<AuditEventEntityFramework, DbContext> _dbContextBuilder; public IEntityFrameworkProviderConfigurator UseDbContext(Func<AuditEventEntityFramework, DbContext> dbContextBuilder) { _dbContextBuilder = dbContextBuilder; return this; } public IEntityFrameworkProviderConfigurator UseDbContext<T>(params object[] constructorArgs) where T : DbContext { _dbContextBuilder = ev => (T)Activator.CreateInstance(typeof(T), constructorArgs); return this; } public IEntityFrameworkProviderConfiguratorAction AuditTypeMapper(Func<Type, Type> mapper) { _auditTypeMapper = mapper; return this; } public IEntityFrameworkProviderConfiguratorAction AuditTypeNameMapper(Func<string, string> mapper) { _auditTypeMapper = t => { var mappedTypeName = mapper.Invoke(t.Name); Type mappedType = null; if (!string.IsNullOrWhiteSpace(mappedTypeName)) { var aqTypeName = $"{t.Namespace}.{mappedTypeName}, {t.GetTypeInfo().Assembly.FullName}"; mappedType = Type.GetType(aqTypeName, false); } return mappedType; }; return this; } public IEntityFrameworkProviderConfiguratorExtra AuditTypeExplicitMapper(Action<IAuditEntityMapping> config) { var mapping = new AuditEntityMapping(); config.Invoke(mapping); _auditTypeMapper = mapping.GetMapper(); _auditEntityAction = mapping.GetAction(); return this; } public IEntityFrameworkProviderConfiguratorExtra AuditEntityAction(Action<AuditEvent, EventEntry, object> action) { _auditEntityAction = (ev, ent, obj) => { action.Invoke(ev, ent, obj); return true; }; return this; } public IEntityFrameworkProviderConfiguratorExtra AuditEntityAction(Func<AuditEvent, EventEntry, object, bool> function) { _auditEntityAction = function; return this; } public IEntityFrameworkProviderConfiguratorExtra AuditEntityAction<T>(Action<AuditEvent, EventEntry, T> action) { _auditEntityAction = (ev, ent, obj) => { if (obj is T) { action.Invoke(ev, ent, (T)obj); } return true; }; return this; } public IEntityFrameworkProviderConfiguratorExtra AuditEntityAction<T>(Func<AuditEvent, EventEntry, T, bool> function) { _auditEntityAction = (ev, ent, obj) => { if (obj is T) { return function.Invoke(ev, ent, (T)obj); } return true; }; return this; } public void IgnoreMatchedProperties(bool ignore = false) { _ignoreMatchedProperties = ignore; } } }
TheStack
b429614061fbfa27b3ba4ddf67baf12e15953361
C#code:C#
{"size": 4123, "ext": "cs", "max_stars_repo_path": "sdk/src/Services/SageMaker/Generated/Model/UpdateActionRequest.cs", "max_stars_repo_name": "ChristopherButtars/aws-sdk-net", "max_stars_repo_stars_event_min_datetime": "2015-01-15T19:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:25:23.000Z", "max_issues_repo_path": "sdk/src/Services/SageMaker/Generated/Model/UpdateActionRequest.cs", "max_issues_repo_name": "ChristopherButtars/aws-sdk-net", "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:40:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:57:40.000Z", "max_forks_repo_path": "sdk/src/Services/SageMaker/Generated/Model/UpdateActionRequest.cs", "max_forks_repo_name": "ChristopherButtars/aws-sdk-net", "max_forks_repo_forks_event_min_datetime": "2015-01-17T12:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:59:50.000Z"}
{"max_stars_count": 1705.0, "max_issues_count": 1811.0, "max_forks_count": 839.0, "avg_line_length": 30.0948905109, "max_line_length": 107, "alphanum_fraction": 0.5823429542}
/* * 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 sagemaker-2017-07-24.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.SageMaker.Model { /// <summary> /// Container for the parameters to the UpdateAction operation. /// Updates an action. /// </summary> public partial class UpdateActionRequest : AmazonSageMakerRequest { private string _actionName; private string _description; private Dictionary<string, string> _properties = new Dictionary<string, string>(); private List<string> _propertiesToRemove = new List<string>(); private ActionStatus _status; /// <summary> /// Gets and sets the property ActionName. /// <para> /// The name of the action to update. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=120)] public string ActionName { get { return this._actionName; } set { this._actionName = value; } } // Check to see if ActionName property is set internal bool IsSetActionName() { return this._actionName != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The new description for the action. /// </para> /// </summary> [AWSProperty(Max=3072)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property Properties. /// <para> /// The new list of properties. Overwrites the current property list. /// </para> /// </summary> [AWSProperty(Max=30)] public Dictionary<string, string> Properties { get { return this._properties; } set { this._properties = value; } } // Check to see if Properties property is set internal bool IsSetProperties() { return this._properties != null && this._properties.Count > 0; } /// <summary> /// Gets and sets the property PropertiesToRemove. /// <para> /// A list of properties to remove. /// </para> /// </summary> public List<string> PropertiesToRemove { get { return this._propertiesToRemove; } set { this._propertiesToRemove = value; } } // Check to see if PropertiesToRemove property is set internal bool IsSetPropertiesToRemove() { return this._propertiesToRemove != null && this._propertiesToRemove.Count > 0; } /// <summary> /// Gets and sets the property Status. /// <para> /// The new status for the action. /// </para> /// </summary> public ActionStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
TheStack
b429e8caafab9bfe1d4677bbb9ae3e22c6fcb90e
C#code:C#
{"size": 935, "ext": "cs", "max_stars_repo_path": "Chess Unity2d/Assets/Scripts/Utilities/ConcurrentQueue.cs", "max_stars_repo_name": "KovalenkoILja/Chess-on-Unity2d", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chess Unity2d/Assets/Scripts/Utilities/ConcurrentQueue.cs", "max_issues_repo_name": "KovalenkoILja/Chess-on-Unity2d", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chess Unity2d/Assets/Scripts/Utilities/ConcurrentQueue.cs", "max_forks_repo_name": "KovalenkoILja/Chess-on-Unity2d", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.6052631579, "max_line_length": 93, "alphanum_fraction": 0.5561497326}
using System.Collections.Generic; /// <summary> /// Alternative to System.Collections.Concurrent.ConcurrentQueue /// (It's only available in .NET 4.0 and greater) /// </summary> /// <remarks> /// It's a bit slow (as it uses locks), and only provides a small subset of the interface /// Overall, the implementation is intended to be simple & robust /// </remarks> public class ConcurrentQueue<T> { private readonly Queue<T> queue = new Queue<T>(); private readonly object queueLock = new object(); public void Enqueue(T item) { lock (queueLock) { queue.Enqueue(item); } } public bool TryDequeue(out T result) { lock (queueLock) { if (queue.Count == 0) { result = default; return false; } result = queue.Dequeue(); return true; } } }
TheStack
b429ebc7eb8d4fac995f0739ce35fac73101145b
C#code:C#
{"size": 819, "ext": "cs", "max_stars_repo_path": "Users/Users.iOS/UsersViewCell.cs", "max_stars_repo_name": "gsachin/Xamarin.iOS-with-MVVMCross-", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Users/Users.iOS/UsersViewCell.cs", "max_issues_repo_name": "gsachin/Xamarin.iOS-with-MVVMCross-", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Users/Users.iOS/UsersViewCell.cs", "max_forks_repo_name": "gsachin/Xamarin.iOS-with-MVVMCross-", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.475, "max_line_length": 68, "alphanum_fraction": 0.5836385836}
using Foundation; using System; using System.CodeDom.Compiler; using MvvmCross.Binding.BindingContext; using MvvmCross.Binding.iOS.Views; using Users.Core.Model; using UIKit; namespace Users.iOS { partial class UserCell : MvxTableViewCell { public UserCell (IntPtr handle) : base (handle) { } internal static NSString Identifier = new NSString("UserCell"); private void CreateBindings() { var set = this.CreateBindingSet<UserCell, User>(); set.Bind(UserName) .To(vm => vm.UserName); set.Bind(Password) .To(vm => vm.Password); set.Apply(); } public override void LayoutSubviews() { base.LayoutSubviews(); CreateBindings(); } } }
TheStack
b42a646eaeaa6a9104e6a0043094e6b483e08b31
C#code:C#
{"size": 2742, "ext": "cs", "max_stars_repo_path": "MetadataExtractor/Formats/FileType/FileTypeDirectory.cs", "max_stars_repo_name": "XelaNimed/metadata-extractor-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MetadataExtractor/Formats/FileType/FileTypeDirectory.cs", "max_issues_repo_name": "XelaNimed/metadata-extractor-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MetadataExtractor/Formats/FileType/FileTypeDirectory.cs", "max_forks_repo_name": "XelaNimed/metadata-extractor-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.5616438356, "max_line_length": 128, "alphanum_fraction": 0.6765134938}
#region License // // Copyright 2002-2019 Drew Noakes // Ported from Java to C# by Yakov Danilov for Imazen LLC in 2014 // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/metadata-extractor-dotnet // https://drewnoakes.com/code/exif/ // #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using MetadataExtractor.Util; namespace MetadataExtractor.Formats.FileType { /// <author>Drew Noakes https://drewnoakes.com</author> [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class FileTypeDirectory : Directory { public const int TagDetectedFileTypeName = 1; public const int TagDetectedFileTypeLongName = 2; public const int TagDetectedFileMimeType = 3; public const int TagExpectedFileNameExtension = 4; private static readonly Dictionary<int, string> _tagNameMap = new Dictionary<int, string> { { TagDetectedFileTypeName, "Detected File Type Name" }, { TagDetectedFileTypeLongName, "Detected File Type Long Name" }, { TagDetectedFileMimeType, "Detected MIME Type" }, { TagExpectedFileNameExtension, "Expected File Name Extension" }, }; [SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] public FileTypeDirectory(Util.FileType fileType) { SetDescriptor(new FileTypeDescriptor(this)); var name = fileType.GetName(); Set(TagDetectedFileTypeName, name); Set(TagDetectedFileTypeLongName, fileType.GetLongName()); var mimeType = fileType.GetMimeType(); if (mimeType != null) Set(TagDetectedFileMimeType, mimeType); var extension = fileType.GetCommonExtension(); if (extension != null) Set(TagExpectedFileNameExtension, extension); } public override string Name => "File Type"; protected override bool TryGetTagName(int tagType, out string tagName) => _tagNameMap.TryGetValue(tagType, out tagName); } }
TheStack
b42ae8d228dd6bef35e4b6a94b4bb3467ef4e395
C#code:C#
{"size": 1610, "ext": "cs", "max_stars_repo_path": "TournamentAssistant/UI/ViewControllers/IPConnection.cs", "max_stars_repo_name": "ByteAlex/TournamentAssistant", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TournamentAssistant/UI/ViewControllers/IPConnection.cs", "max_issues_repo_name": "ByteAlex/TournamentAssistant", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TournamentAssistant/UI/ViewControllers/IPConnection.cs", "max_forks_repo_name": "ByteAlex/TournamentAssistant", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.9615384615, "max_line_length": 115, "alphanum_fraction": 0.6161490683}
#pragma warning disable IDE0044 using BeatSaberMarkupLanguage.Attributes; using BeatSaberMarkupLanguage.ViewControllers; using System; using TournamentAssistantShared.Models; using UnityEngine; namespace TournamentAssistant.UI.ViewControllers { internal class IPConnection : BSMLResourceViewController { // For this method of setting the ResourceName, this class must be the first class in the file. public override string ResourceName => string.Join(".", GetType().Namespace, GetType().Name); public event Action<CoreServer> ServerSelected; protected override void DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { base.DidActivate(firstActivation, addedToHierarchy, screenSystemEnabling); BackgroundOpacity(); } [UIObject("Background")] internal GameObject Background = null; void BackgroundOpacity() //<- stolen from BS+ { var Image = Background?.GetComponent<HMUI.ImageView>() ?? null; var Color = Image.color; Color.a = 0.5f; Image.color = Color; } [UIValue("ip")] private string ip = string.Empty; [UIValue("port")] private string port = "2052"; [UIAction("ipConnect")] public void OnConnect() { CoreServer server = new() { Name = "Custom server", Address = ip, Port = Int32.Parse(port) }; ServerSelected?.Invoke(server); } } }
TheStack
b42b14d2262659608f6998e79c660d9575567600
C#code:C#
{"size": 1083, "ext": "cs", "max_stars_repo_path": "OpenNefia.Packaging/Program.cs", "max_stars_repo_name": "Zechsu/OpenNefia", "max_stars_repo_stars_event_min_datetime": "2022-01-02T11:33:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:52:35.000Z", "max_issues_repo_path": "OpenNefia.Packaging/Program.cs", "max_issues_repo_name": "Zechsu/OpenNefia", "max_issues_repo_issues_event_min_datetime": "2021-12-22T09:01:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T08:12:54.000Z", "max_forks_repo_path": "OpenNefia.Packaging/Program.cs", "max_forks_repo_name": "Zechsu/OpenNefia", "max_forks_repo_forks_event_min_datetime": "2022-01-04T21:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T11:39:31.000Z"}
{"max_stars_count": 38.0, "max_issues_count": 71.0, "max_forks_count": 3.0, "avg_line_length": 28.5, "max_line_length": 121, "alphanum_fraction": 0.5558633426}
using Cake.Core; using Cake.Frosting; namespace OpenNefia.Packaging { /// <summary> /// "I prefer cakes and candies to alcoholic drinks. You want [build artifacts]? Gimme [<see cref="ICakeContext"/>]!" /// </summary> public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .Run(args); } } public class BuildContext : FrostingContext { /// <summary> /// Build configuration, like "Debug" or "Release". /// </summary> public string BuildConfig { get; set; } = "Release"; /// <summary> /// RID of the .NET runtime to build for. /// </summary> public string Runtime { get; set; } = "win-x64"; public BuildContext(ICakeContext context) : base(context) { BuildConfig = context.Arguments.GetArgument("config") ?? BuildConfig; Runtime = context.Arguments.GetArgument("runtime") ?? Runtime; } } }
TheStack
b42fe958bf7e84e668449e04235f64ff0b3b063d
C#code:C#
{"size": 2205, "ext": "cs", "max_stars_repo_path": "src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunctionDeclareDecl.cs", "max_stars_repo_name": "ffMathy/roslyn", "max_stars_repo_stars_event_min_datetime": "2015-01-14T23:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:10:52.000Z", "max_issues_repo_path": "src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunctionDeclareDecl.cs", "max_issues_repo_name": "ffMathy/roslyn", "max_issues_repo_issues_event_min_datetime": "2015-01-15T00:29:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:48:56.000Z", "max_forks_repo_path": "src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunctionDeclareDecl.cs", "max_forks_repo_name": "ffMathy/roslyn", "max_forks_repo_forks_event_min_datetime": "2015-01-14T23:40:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T20:15:03.000Z"}
{"max_stars_count": 17923.0, "max_issues_count": 48991.0, "max_forks_count": 5209.0, "avg_line_length": 31.9565217391, "max_line_length": 95, "alphanum_fraction": 0.6675736961}
// 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; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using EnvDTE; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public sealed class CodeFunctionDeclareDecl : CodeFunction { internal static new EnvDTE.CodeFunction Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static new EnvDTE.CodeFunction CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override vsCMElement Kind { get { return vsCMElement.vsCMElementDeclareDecl; } } } }
TheStack
b4321126a32fc5afbce07e877b2b4cc89fedb258
C#code:C#
{"size": 897, "ext": "cs", "max_stars_repo_path": "Rx.NET/Source/src/System.Reactive/Joins/QueryablePlan.cs", "max_stars_repo_name": "tralivali1234/reactive", "max_stars_repo_stars_event_min_datetime": "2019-01-10T18:54:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-10T18:54:48.000Z", "max_issues_repo_path": "Rx.NET/Source/src/System.Reactive/Joins/QueryablePlan.cs", "max_issues_repo_name": "tralivali1234/reactive", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rx.NET/Source/src/System.Reactive/Joins/QueryablePlan.cs", "max_forks_repo_name": "tralivali1234/reactive", "max_forks_repo_forks_event_min_datetime": "2021-01-15T22:00:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T19:29:51.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 30.9310344828, "max_line_length": 91, "alphanum_fraction": 0.6755852843}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #pragma warning disable 1591 using System.Linq.Expressions; namespace System.Reactive.Joins { /// <summary> /// Represents an execution plan for join patterns represented by an expression tree. /// </summary> /// <typeparam name="TResult">The type of the results produced by the plan.</typeparam> public class QueryablePlan<TResult> { internal QueryablePlan(Expression expression) { Expression = expression; } /// <summary> /// Gets the expression tree representing the join pattern execution plan. /// </summary> public Expression Expression { get; } } } #pragma warning restore 1591
TheStack
b432621f7f0ea0e2c2a5ee87cf817fc3f150cd67
C#code:C#
{"size": 7172, "ext": "cs", "max_stars_repo_path": "src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs", "max_stars_repo_name": "Fortranm/BizHawk", "max_stars_repo_stars_event_min_datetime": "2015-06-28T09:57:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T03:51:10.000Z", "max_issues_repo_path": "src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs", "max_issues_repo_name": "Fortranm/BizHawk", "max_issues_repo_issues_event_min_datetime": "2015-06-25T01:45:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T08:44:18.000Z", "max_forks_repo_path": "src/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/NesBoardBase.cs", "max_forks_repo_name": "Fortranm/BizHawk", "max_forks_repo_forks_event_min_datetime": "2015-06-29T04:28:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T18:24:17.000Z"}
{"max_stars_count": 1414.0, "max_issues_count": 2369.0, "max_forks_count": 430.0, "avg_line_length": 23.0610932476, "max_line_length": 151, "alphanum_fraction": 0.6518404908}
using System; using System.Collections.Generic; using BizHawk.Common; namespace BizHawk.Emulation.Cores.Nintendo.NES { /// <summary> /// These are used by SetMirroring() to provide the base class nametable mirroring service. /// Apparently, these are not used for internal build configuration logic /// </summary> internal enum EMirrorType { Vertical, Horizontal, OneScreenA, OneScreenB } [NesBoardImpl] internal abstract class NesBoardBase : INesBoard { public virtual void Create(NES nes) { NES = nes; } public virtual void NesSoftReset() { } public Dictionary<string, string> InitialRegisterValues { get; set; } public abstract bool Configure(EDetectionOrigin origin); public virtual void ClockPpu() { } public virtual void ClockCpu() { } public virtual void AtVsyncNmi() { } public CartInfo Cart => NES.cart; public NES NES { get; set; } //this is set to true when SyncState is called, so that we know the base class SyncState was used public bool SyncStateFlag; public virtual NES.CDLog_MapResults MapMemory(ushort addr, bool write) { NES.CDLog_MapResults ret = new NES.CDLog_MapResults(); ret.Type = NES.CDLog_AddrType.None; if (addr < 0x2000) { ret.Type = NES.CDLog_AddrType.MainRAM; ret.Address = addr & 0x7FF; } return ret; } public virtual void SyncState(Serializer ser) { ser.Sync(nameof(_vram), ref _vram, true); ser.Sync(nameof(_wram), ref _wram, true); for (int i = 0; i < 4; i++) ser.Sync("mirroring" + i, ref _mirroring[i]); ser.Sync(nameof(_irqSignal), ref _irqSignal); SyncStateFlag = true; } public virtual void SyncIRQ(bool flag) { IrqSignal = flag; } private bool _irqSignal; public bool IrqSignal { get => _irqSignal; set => _irqSignal = value; } private readonly int[] _mirroring = new int[4]; protected void SetMirroring(int a, int b, int c, int d) { _mirroring[0] = a; _mirroring[1] = b; _mirroring[2] = c; _mirroring[3] = d; } protected void ApplyMemoryMapMask(int mask, byte[] map) { byte byteMask = (byte)mask; for (int i = 0; i < map.Length; i++) { map[i] &= byteMask; } } // make sure you have bank-masked the map protected int ApplyMemoryMap(int blockSizeBits, byte[] map, int addr) { int bank = addr >> blockSizeBits; int ofs = addr & ((1 << blockSizeBits) - 1); bank = map[bank]; addr = (bank << blockSizeBits) | ofs; return addr; } public static EMirrorType CalculateMirrorType(int pad_h, int pad_v) { if (pad_h == 0) { return pad_v == 0 ? EMirrorType.OneScreenA : EMirrorType.Horizontal; } if (pad_v == 0) { return EMirrorType.Vertical; } return EMirrorType.OneScreenB; } protected void SetMirrorType(int pad_h, int pad_v) { SetMirrorType(CalculateMirrorType(pad_h, pad_v)); } public void SetMirrorType(EMirrorType mirrorType) { switch (mirrorType) { case EMirrorType.Horizontal: SetMirroring(0, 0, 1, 1); break; case EMirrorType.Vertical: SetMirroring(0, 1, 0, 1); break; case EMirrorType.OneScreenA: SetMirroring(0, 0, 0, 0); break; case EMirrorType.OneScreenB: SetMirroring(1, 1, 1, 1); break; default: SetMirroring(-1, -1, -1, -1); break; //crash! } } protected int ApplyMirroring(int addr) { int block = (addr >> 10) & 3; block = _mirroring[block]; int ofs = addr & 0x3FF; return (block << 10) | ofs; } protected byte HandleNormalPRGConflict(int addr, byte value) { value &= ReadPrg(addr); //Debug.Assert(old_value == value, "Found a test case of bus conflict. please report."); //report: pinball quest (J). also: double dare return value; } public virtual byte ReadPrg(int addr) => Rom[addr]; public virtual void WritePrg(int addr, byte value) { } public virtual void WriteWram(int addr, byte value) { if (_wram != null) { _wram[addr & _wramMask] = value; } } private int _wramMask; public virtual void PostConfigure() { _wramMask = (Cart.WramSize * 1024) - 1; } public virtual byte ReadWram(int addr) { return _wram?[addr & _wramMask] ?? NES.DB; } public virtual void WriteExp(int addr, byte value) { } public virtual byte ReadExp(int addr) { return NES.DB; } public virtual byte ReadReg2xxx(int addr) { return NES.ppu.ReadReg(addr & 7); } public virtual byte PeekReg2xxx(int addr) { return NES.ppu.PeekReg(addr & 7); } public virtual void WriteReg2xxx(int addr, byte value) { NES.ppu.WriteReg(addr, value); } public virtual void WritePpu(int addr, byte value) { if (addr < 0x2000) { if (Vram != null) { Vram[addr] = value; } } else { NES.CIRAM[ApplyMirroring(addr)] = value; } } public virtual void AddressPpu(int addr) { } public virtual byte PeekPPU(int addr) => ReadPpu(addr); protected virtual byte ReadPPUChr(int addr) { return Vrom?[addr] ?? Vram[addr]; } public virtual byte ReadPpu(int addr) { if (addr < 0x2000) { return Vrom?[addr] ?? Vram[addr]; } return NES.CIRAM[ApplyMirroring(addr)]; } /// <summary> /// derived classes should override this if they have peek-unsafe logic /// </summary> public virtual byte PeekCart(int addr) { byte ret; if (addr >= 0x8000) { ret = ReadPrg(addr - 0x8000); // easy optimization, since rom reads are so common, move this up (reordering the rest of these else ifs is not easy) } else if (addr < 0x6000) { ret = ReadExp(addr - 0x4000); } else { ret = ReadWram(addr - 0x6000); } return ret; } public virtual byte[] SaveRam => Cart.WramBattery ? Wram : null; public byte[] Wram { get => _wram; set => _wram = value; } public byte[] Vram { get => _vram; set => _vram = value; } public byte[] Rom { get; set; } public byte[] Vrom { get; set; } private byte[] _wram, _vram; protected void Assert(bool test, string comment, params object[] args) { if (!test) throw new Exception(string.Format(comment, args)); } protected void Assert(bool test) { if (!test) throw new Exception("assertion failed in board setup!"); } protected void AssertPrg(params int[] prg) => AssertMemType(Cart.PrgSize, "prg", prg); protected void AssertChr(params int[] chr) => AssertMemType(Cart.ChrSize, "chr", chr); protected void AssertWram(params int[] wram) => AssertMemType(Cart.WramSize, "wram", wram); protected void AssertVram(params int[] vram) => AssertMemType(Cart.VramSize, "vram", vram); protected void AssertMemType(int value, string name, int[] valid) { // only disable vram and wram asserts, as UNIF knows its prg and chr sizes if (DisableConfigAsserts && (name == "wram" || name == "vram")) return; foreach (int i in valid) if (value == i) return; Assert(false, "unhandled {0} size of {1}", name,value); } protected void AssertBattery(bool hasBattery) => Assert(Cart.WramBattery == hasBattery); public virtual void ApplyCustomAudio(short[] samples) { } public bool DisableConfigAsserts { get; set; } } }
TheStack
b43432deb4aa94b97bca4fb87defc15edf702bbf
C#code:C#
{"size": 1356, "ext": "cs", "max_stars_repo_path": "src/Microsoft.DotNet.CodeFormatting/Filters/UsableFileFilter.cs", "max_stars_repo_name": "masa-suzu/dn-fmt", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Microsoft.DotNet.CodeFormatting/Filters/UsableFileFilter.cs", "max_issues_repo_name": "masa-suzu/dn-fmt", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Microsoft.DotNet.CodeFormatting/Filters/UsableFileFilter.cs", "max_forks_repo_name": "masa-suzu/dn-fmt", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.8510638298, "max_line_length": 100, "alphanum_fraction": 0.6231563422}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.DotNet.CodeFormatting.Filters { [Export(typeof(IFormattingFilter))] internal sealed class UsableFileFilter : IFormattingFilter { private readonly Options m_options; [ImportingConstructor] internal UsableFileFilter(Options options) { m_options = options; } public bool ShouldBeProcessed(Document document) { if (document.FilePath == null) { return true; } var fileInfo = new FileInfo(document.FilePath); if (!fileInfo.Exists || fileInfo.IsReadOnly) { m_options.FormatLogger.WriteLine("warning: skipping document '{0}' because it {1}.", document.FilePath, fileInfo.IsReadOnly ? "is read-only" : "does not exist"); return false; } return true; } } }
TheStack
b43473450a32fed1c6d7c4d6f3b62f9e19ce893f
C#code:C#
{"size": 614, "ext": "cs", "max_stars_repo_path": "src/Deviax.QueryBuilder.Shared/Parts/Null.cs", "max_stars_repo_name": "sebastianhoffmann/querybuilder", "max_stars_repo_stars_event_min_datetime": "2016-10-25T15:07:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T16:08:32.000Z", "max_issues_repo_path": "src/Deviax.QueryBuilder.Shared/Parts/Null.cs", "max_issues_repo_name": "sebastianhoffmann/querybuilder", "max_issues_repo_issues_event_min_datetime": "2017-06-24T13:11:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T12:25:13.000Z", "max_forks_repo_path": "src/Deviax.QueryBuilder.Shared/Parts/Null.cs", "max_forks_repo_name": "sebastianhoffmann/querybuilder", "max_forks_repo_forks_event_min_datetime": "2017-06-24T13:13:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T15:48:23.000Z"}
{"max_stars_count": 5.0, "max_issues_count": 3.0, "max_forks_count": 2.0, "avg_line_length": 21.9285714286, "max_line_length": 81, "alphanum_fraction": 0.6107491857}
using Deviax.QueryBuilder.Visitors; namespace Deviax.QueryBuilder.Parts { public class IsNullPart : Part, IBooleanPart { public readonly IPart Part; public IsNullPart(IPart part) { Part = part; } public override void Accept(INodeVisitor visitor) => visitor.Visit(this); } public class IsNotNullPart : Part, IBooleanPart { internal readonly IPart Part; public IsNotNullPart(IPart part) { Part = part; } public override void Accept(INodeVisitor visitor) => visitor.Visit(this); } }
TheStack
b434d19777fffe4838ebd36c7b986625713a9a02
C#code:C#
{"size": 10709, "ext": "cs", "max_stars_repo_path": "AnimatorEditor/ActorAnimatorController.cs", "max_stars_repo_name": "StephanSchue/Unity-Utilities", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AnimatorEditor/ActorAnimatorController.cs", "max_issues_repo_name": "StephanSchue/Unity-Utilities", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AnimatorEditor/ActorAnimatorController.cs", "max_forks_repo_name": "StephanSchue/Unity-Utilities", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.749235474, "max_line_length": 153, "alphanum_fraction": 0.5750303483}
using System; using System.Collections; using System.Collections.Generic; using EH.Game.Actors; using EH.Utils; using UnityEngine; using UnityEngine.Events; namespace EH.Animations { public abstract class ActorAnimatorController : MonoBehaviour { // --- Definitions --- public struct BlendFloatInfo { public string label; public Timer timer; public float startValue; public float destinationValue; public BlendFloatInfo(string label, float duration, float startValue, float destinationValue) { this.label = label; this.timer = new Timer(duration); this.startValue = startValue; this.destinationValue = destinationValue; } } // --- Components/Settings/Variables --- [Header("Components")] public Animator animator; public RuntimeAnimatorController animatorController; [Header("Settings")] public bool debug = false; protected BaseState currentState; protected AnimationObject currentAnimation; protected List<BlendFloatInfo> blendFloatInfos = new List<BlendFloatInfo>(); protected bool blendFloatActive = false; // General Animation Callback protected UnityAction currentAnimationCallback; // Modular Animation Callbacks protected UnityAction[] currentModularAnimationCallbacks; public BaseState CurrentState { get { return currentState; } } public AnimationObject CurrentAnimation { get { return currentAnimation; } } private void Reset() { animator = GetComponent<Animator>(); animatorController = animator != null ? animator.runtimeAnimatorController : null; } protected void Awake() { if(animator.runtimeAnimatorController == null) animator.runtimeAnimatorController = animatorController; } public virtual void Initialize() { } protected void FixedUpdate() { if(blendFloatActive) UpdateBlendFloat(Time.fixedDeltaTime); } public virtual BaseState ChangeState(string state, string substate = "") { return null; } public BaseState ChangeState(BaseState state) { LogFormat("ChangeState from '{0}' to '{1}'", currentState, state); if(currentState != null) animator.SetBool(currentState.Name, false); currentState = state; animator.SetBool(currentState.Name, true); return state; } public bool ContainsAnimation(string keyword) { return currentState.ContainsAnimation(keyword); } public abstract bool ContainsAnimation(string keyword, ActorAnimatorLayer layer); #region Play Animation public bool PlayAnimation(AnimationBaseDefinition definition, UnityAction callback = null, bool forceAnimation=false) { if(currentState == null) return false; if(!forceAnimation && currentAnimation != null && definition.animationLabel == currentAnimation.label) { LogFormat("ActorAnimatorController: Try to trigger Animation twice '{0}'", definition.animationLabel); return false; } // --- Search Animation --- AnimationObject animationObj = currentState.GetAnimation(definition); // --- Play Animation --- bool status = false; if(animationObj != null && animationObj.clip != null) status = PlayAnimation(animationObj, callback, forceAnimation); else if(animationObj != null && animationObj.clip == null) LogErrorFormat("{0}[{2}] (ActorAnimatorController): AnimationClip is not set '{1}'", name, animationObj.label, currentState.Name); else LogErrorFormat("{0}[{2}] (ActorAnimatorController): Animation is not found: '{1}'", name, definition.animationLabel, currentState.Name); return status; } public AnimationObject GetAnimation(AnimationBaseDefinition definition) { return currentState.GetAnimation(definition); } public virtual bool PlayModularAnimation(string label, ActorAnimatorLayer layer, string subState, UnityAction callback=null) { throw new NotImplementedException(); } public virtual void StopModularAnimation(ActorAnimatorLayer layer, string subState) { throw new NotImplementedException(); } protected bool PlayAnimation(AnimationObject animation, UnityAction callback = null, bool forceAnimation = false) { if(animation == null) return false; if(!forceAnimation && currentAnimation != null && animation == currentAnimation) { LogFormat("{0}[{2}] (ActorAnimatorController): Try to trigger Animation twice '{1}'", name, animation.label, currentState.Name); return false; } LogFormat("{0} (ActorAnimatorController): Play Animation '{1}' ({2})", name, animation.label, animation.clip.name); animator.SetTrigger(animation.label); currentAnimation = animation; currentAnimationCallback = callback; return true; } public void OnAnimationEnd() { if(currentAnimationCallback != null) { UnityAction unityAction = currentAnimationCallback.Clone() as UnityAction; currentAnimationCallback = null; unityAction.Raise(); } } public void OnModularAnimationEnd(string layerName) { //Debug.Log("OnModularAnimationEnd"); int modularCallbackIndex = -1; string _layerName = ""; if(currentModularAnimationCallbacks.Length == 1) { if(animator.GetLayerIndex(string.Format("{0} Layer", layerName)) > 0) modularCallbackIndex = 0; } else { for(int i = 0; i < currentModularAnimationCallbacks.Length; i++) { _layerName = Enum.GetName(typeof(ActorAnimatorLayer), (ActorAnimatorLayer)(i+1)); if(layerName == _layerName) { modularCallbackIndex = i; break; } } } if(modularCallbackIndex == -1 || modularCallbackIndex >= currentModularAnimationCallbacks.Length) { LogErrorFormat("OnModularAnimationEnd: Called layerIndex ({0}) that is bigger than layers on the model", modularCallbackIndex); return; } currentModularAnimationCallbacks[modularCallbackIndex].Raise(); currentModularAnimationCallbacks[modularCallbackIndex] = null; } public void SetTrigger(string label) { LogFormat(string.Format("SetTrigger: {0}", label)); animator.SetTrigger(label); } public void ResetTrigger(string label) { //LogFormat(string.Format("ResetTrigger: {0}", label)); animator.ResetTrigger(label); } public void SetFloat(string label, float value) { //LogFormat(string.Format("SetFloat: {0} ({1})", label, value)); animator.SetFloat(label, value); } public float GetFloat(string label) { return animator.GetFloat(label); } public void SetBool(string label, bool active) { //LogFormat(string.Format("SetBool: {0} ({1})", label, active)); animator.SetBool(label, active); } public bool GetBool(string label) { return animator.GetBool(label); } #endregion #region BlendTree Methods public void StartBlendFloat(string label, float destinationValue, float duration) { int infoIndex = 0; bool found = false; for(int i = 0; i < blendFloatInfos.Count; i++) { if(label == blendFloatInfos[i].label) { infoIndex = i; found = true; if(Mathf.Abs(destinationValue - blendFloatInfos[i].destinationValue) < 0.01f) return; } } if(found) // --- Existing --- blendFloatInfos.RemoveAt(infoIndex); // --- Create new Blend --- BlendFloatInfo info = new BlendFloatInfo(label, duration, animator.GetFloat(label), destinationValue); blendFloatInfos.Add(info); blendFloatActive = true; } protected virtual void UpdateBlendFloat(float dt) { List<BlendFloatInfo> finishedBlends = new List<BlendFloatInfo>(); for(int i = 0; i < blendFloatInfos.Count; i++) { BlendFloatInfo info = blendFloatInfos[i]; SetFloat(info.label, Mathf.Lerp(info.startValue, info.destinationValue, 1f - info.timer.percentage)); if(info.timer.Update(dt)) finishedBlends.Add(info); } for(int x = 0; x < finishedBlends.Count; x++) blendFloatInfos.Remove(finishedBlends[x]); if(blendFloatInfos.Count == 0) StopBlendFloat(); } public void StopBlendFloat() { blendFloatActive = false; } #endregion #region Blend public virtual int GetBlendValue(AnimationBaseDefinition definition) { return currentState.GetBlendValue(definition); } #endregion #region Editor Messages protected void LogErrorFormat(string message, params object[] args) { if(debug) Debug.LogErrorFormat(gameObject, message, args); } protected void LogFormat(string message, params object[] args) { if(debug) Debug.LogFormat(gameObject, message, args); } protected abstract bool IsModularStateExisting(ActorAnimatorLayer layer, string subState, out ModularBaseState modularState, out int layerIndex); #endregion } }
TheStack
b436338217dd794be568eb23a8f681c20f0ed7bb
C#code:C#
{"size": 2802, "ext": "cs", "max_stars_repo_path": "Src/Dev/Toolbox.Core/Toolbox.Standard/Tools/Pipeline/Pipeline.cs", "max_stars_repo_name": "khooversoft/Toolbox.Core", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Src/Dev/Toolbox.Core/Toolbox.Standard/Tools/Pipeline/Pipeline.cs", "max_issues_repo_name": "khooversoft/Toolbox.Core", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/Dev/Toolbox.Core/Toolbox.Standard/Tools/Pipeline/Pipeline.cs", "max_forks_repo_name": "khooversoft/Toolbox.Core", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.4947368421, "max_line_length": 115, "alphanum_fraction": 0.5685224839}
// Copyright (c) KhooverSoft. All rights reserved. // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Khooversoft.Toolbox.Standard { /// <summary> /// Delegate for executing a pipeline /// </summary> /// <typeparam name="TContext">execution context</typeparam> /// <typeparam name="T">message type</typeparam> /// <param name="context">execution context</param> /// <param name="message">message to process</param> /// <returns>true if pipeline was successful</returns> public delegate bool PipelineFunc<TContext, T>(TContext context, T message); /// <summary> /// Pipeline container, executes all actions until false is returned /// </summary> /// <typeparam name="TContext">execution context</typeparam> /// <typeparam name="T">message type</typeparam> public class Pipeline<TContext, T> : IReadOnlyList<PipelineFunc<TContext, T>>, IPipeline<TContext, T> { private readonly List<PipelineFunc<TContext, T>> _pipelines = new List<PipelineFunc<TContext, T>>(); private readonly object _lock = new object(); public Pipeline() { } public PipelineFunc<TContext, T> this[int index] => _pipelines[index]; public int Count => _pipelines.Count; public Pipeline<TContext, T> Add(PipelineFunc<TContext, T> actor) { actor.Verify(nameof(actor)).IsNotNull(); lock (_lock) { _pipelines.Add(actor); } return this; } public bool Post(TContext context, T message) { lock (_lock) { foreach (var item in _pipelines) { if (!item.Invoke(context, message)) { return false; } } } return true; } public IEnumerator<PipelineFunc<TContext, T>> GetEnumerator() { lock (_pipelines) { return _pipelines .ToList() .GetEnumerator(); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public static Pipeline<TContext, T> operator +(Pipeline<TContext, T> self, PipelineFunc<TContext, T> actor) { self.Verify(nameof(self)).IsNotNull(); actor.Verify(nameof(actor)).IsNotNull(); self.Add(actor); return self; } } }
TheStack
b4363f3d303ee36faecf26e3ff770d35f1d8a538
C#code:C#
{"size": 5788, "ext": "cs", "max_stars_repo_path": "src/Microsoft.Graph/Requests/Generated/IDeviceEnrollmentLimitConfigurationRequest.cs", "max_stars_repo_name": "peombwa/msgraph-sdk-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Microsoft.Graph/Requests/Generated/IDeviceEnrollmentLimitConfigurationRequest.cs", "max_issues_repo_name": "peombwa/msgraph-sdk-dotnet", "max_issues_repo_issues_event_min_datetime": "2019-03-14T19:20:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T19:20:52.000Z", "max_forks_repo_path": "src/Microsoft.Graph/Requests/Generated/IDeviceEnrollmentLimitConfigurationRequest.cs", "max_forks_repo_name": "peombwa/msgraph-sdk-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 54.0934579439, "max_line_length": 200, "alphanum_fraction": 0.6903939185}
// ------------------------------------------------------------------------------ // 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: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceEnrollmentLimitConfigurationRequest. /// </summary> public partial interface IDeviceEnrollmentLimitConfigurationRequest : IBaseRequest { /// <summary> /// Creates the specified DeviceEnrollmentLimitConfiguration using PUT. /// </summary> /// <param name="deviceEnrollmentLimitConfigurationToCreate">The DeviceEnrollmentLimitConfiguration to create.</param> /// <returns>The created DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> CreateAsync(DeviceEnrollmentLimitConfiguration deviceEnrollmentLimitConfigurationToCreate); /// <summary> /// Creates the specified DeviceEnrollmentLimitConfiguration using PUT. /// </summary> /// <param name="deviceEnrollmentLimitConfigurationToCreate">The DeviceEnrollmentLimitConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> CreateAsync(DeviceEnrollmentLimitConfiguration deviceEnrollmentLimitConfigurationToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified DeviceEnrollmentLimitConfiguration. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified DeviceEnrollmentLimitConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified DeviceEnrollmentLimitConfiguration. /// </summary> /// <returns>The DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> GetAsync(); /// <summary> /// Gets the specified DeviceEnrollmentLimitConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified DeviceEnrollmentLimitConfiguration using PATCH. /// </summary> /// <param name="deviceEnrollmentLimitConfigurationToUpdate">The DeviceEnrollmentLimitConfiguration to update.</param> /// <returns>The updated DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> UpdateAsync(DeviceEnrollmentLimitConfiguration deviceEnrollmentLimitConfigurationToUpdate); /// <summary> /// Updates the specified DeviceEnrollmentLimitConfiguration using PATCH. /// </summary> /// <param name="deviceEnrollmentLimitConfigurationToUpdate">The DeviceEnrollmentLimitConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DeviceEnrollmentLimitConfiguration.</returns> System.Threading.Tasks.Task<DeviceEnrollmentLimitConfiguration> UpdateAsync(DeviceEnrollmentLimitConfiguration deviceEnrollmentLimitConfigurationToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceEnrollmentLimitConfigurationRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceEnrollmentLimitConfigurationRequest Expand(Expression<Func<DeviceEnrollmentLimitConfiguration, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceEnrollmentLimitConfigurationRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceEnrollmentLimitConfigurationRequest Select(Expression<Func<DeviceEnrollmentLimitConfiguration, object>> selectExpression); } }
TheStack
b43707ec0cd2505136f80086cbdb8a0157c82924
C#code:C#
{"size": 1342, "ext": "cs", "max_stars_repo_path": "src/MockHttpClient/Content/XmlContent.cs", "max_stars_repo_name": "cternes/MockHttpClient", "max_stars_repo_stars_event_min_datetime": "2018-08-13T00:37:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T08:23:15.000Z", "max_issues_repo_path": "src/MockHttpClient/Content/XmlContent.cs", "max_issues_repo_name": "cternes/MockHttpClient", "max_issues_repo_issues_event_min_datetime": "2018-11-01T12:49:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-30T21:26:51.000Z", "max_forks_repo_path": "src/MockHttpClient/Content/XmlContent.cs", "max_forks_repo_name": "cternes/MockHttpClient", "max_forks_repo_forks_event_min_datetime": "2018-10-30T19:34:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T19:26:02.000Z"}
{"max_stars_count": 6.0, "max_issues_count": 5.0, "max_forks_count": 2.0, "avg_line_length": 28.5531914894, "max_line_length": 88, "alphanum_fraction": 0.6140089419}
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace MockHttpClient.Content { /// <summary> /// Represents Xml content. /// </summary> /// <seealso cref="System.Net.Http.StringContent" /> public class XmlContent : StringContent { private static readonly string DefaultMediaType = "application/xml"; /// <summary> /// Initializes a new instance of the <see cref="XmlContent"/> class. /// </summary> /// <param name="obj">The object to serialize.</param> /// <param name="mediaType">The media type. Defaults to application/xml.</param> public XmlContent(object obj, string mediaType = null) : base(ToXmlString(obj), null, mediaType ?? DefaultMediaType) { } private static string ToXmlString(object input) { if (input == null) return ""; using (var writer = new StringWriter()) { new XmlSerializer(input.GetType()).Serialize(writer, input); return writer.ToString(); } } } }
TheStack
b437634f7d2fe0772cdf2efc34e0de02c3816873
C#code:C#
{"size": 1839, "ext": "cs", "max_stars_repo_path": "DB Advanced/BusTicketsSystem/BusTicketsSystem.App/Core/Commands/PrintInfoCommand.cs", "max_stars_repo_name": "radoikoff/SoftUni", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DB Advanced/BusTicketsSystem/BusTicketsSystem.App/Core/Commands/PrintInfoCommand.cs", "max_issues_repo_name": "radoikoff/SoftUni", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DB Advanced/BusTicketsSystem/BusTicketsSystem.App/Core/Commands/PrintInfoCommand.cs", "max_forks_repo_name": "radoikoff/SoftUni", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.1475409836, "max_line_length": 124, "alphanum_fraction": 0.6101141925}
namespace BusTicketsSystem.App.Core.Commands { using Contracts; using BusTicketsSystem.Services.Contracts; using System; using System.Linq; using System.Text; using DTOs; public class PrintInfoCommand : ICommand { private readonly ITripService tripService; private readonly IStationService stationService; public PrintInfoCommand(ITripService tripService, IStationService stationService) { this.tripService = tripService; this.stationService = stationService; } public string Execute(string[] data) { int stationId = int.Parse(data[0]); bool stationExists = this.stationService.Exists(stationId); if (!stationExists) { throw new ArgumentException($"Bus station with Is {stationId} not found!"); } var station = this.stationService.ById<StationDto>(stationId); var tripsArrivals = this.tripService.ByDestinationStationId<ArrivalsTripDto>(stationId); var tripsDepartures = this.tripService.ByOriginStationId<DepartureTripDto>(stationId); StringBuilder sb = new StringBuilder(); sb.AppendLine($"{station.Name}, {station.TownName}"); sb.AppendLine("Arrivals:"); foreach (var trip in tripsArrivals) { sb.AppendLine($"From {trip.OriginStationName} | Arrive at: {trip.ArrivalTime} | Status: {trip.Status}"); } sb.AppendLine("Departures:"); foreach (var trip in tripsDepartures) { sb.AppendLine($"To {trip.DestinationStationName} | Depart at: {trip.DepartureTime} | Status {trip.Status}"); } return sb.ToString().TrimEnd(); } } }
TheStack
b437dbb98ac836b2fc2debe326df4d7097dcf141
C#code:C#
{"size": 2635, "ext": "cs", "max_stars_repo_path": "ApolloDemo/ApolloConfigDemo.cs", "max_stars_repo_name": "307209239/apollo-net", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ApolloDemo/ApolloConfigDemo.cs", "max_issues_repo_name": "307209239/apollo-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ApolloDemo/ApolloConfigDemo.cs", "max_forks_repo_name": "307209239/apollo-net", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.3544303797, "max_line_length": 192, "alphanum_fraction": 0.5734345351}
using Com.Ctrip.Framework.Apollo; using Com.Ctrip.Framework.Apollo.Model; using Com.Ctrip.Framework.Foundation; using System; using System.Configuration; namespace ApolloDemo { class ApolloConfigDemo { private string DEFAULT_VALUE = "undefined"; private Config config; private Config anotherConfig; public ApolloConfigDemo() { config = Com.Ctrip.Framework.Apollo.ConfigService.GetAppConfig(); foreach (var key in ConfigurationManager.AppSettings.AllKeys) { Console.WriteLine($"{key}*******{ConfigurationManager.AppSettings[key]}"); } } private string GetConfig(string key) { string result = config.GetProperty(key, DEFAULT_VALUE); if (result.Equals(DEFAULT_VALUE)) { result = anotherConfig.GetProperty(key, DEFAULT_VALUE); } Console.WriteLine("Loading key: {0} with value: {1}", key, result); return result; } public static void Main(string[] args) { ApolloConfigDemo apolloConfigDemo = new ApolloConfigDemo(); apolloConfigDemo.PrintEnvInfo(); Console.WriteLine("Apollo Config Demo. Please input key to get the value. Input quit to exit."); while (true) { Console.Write("> "); string input = Console.ReadLine(); if (input == null || input.Length == 0) { continue; } input = input.Trim(); if (input.Equals("quit", StringComparison.CurrentCultureIgnoreCase)) { Environment.Exit(0); } apolloConfigDemo.GetConfig(input); } } private void OnChanged(object sender, ConfigChangeEventArgs changeEvent) { Console.WriteLine("Changes for namespace {0}", changeEvent.Namespace); foreach (string key in changeEvent.ChangedKeys) { ConfigChange change = changeEvent.GetChange(key); Console.WriteLine("Change - key: {0}, oldValue: {1}, newValue: {2}, changeType: {3}", change.PropertyName, change.OldValue, change.NewValue, change.ChangeType); } } private void PrintEnvInfo() { string message = string.Format("AppId: {0}, Env: {1}, DC: {2}, IP: {3}", Foundation.App.AppId, Foundation.Server.EnvType, Foundation.Server.DataCenter, Foundation.Net.HostAddress); Console.WriteLine(message); } } }
TheStack
b438cd69600bae28697288835c7fbe14886701a2
C#code:C#
{"size": 619, "ext": "cs", "max_stars_repo_path": "src/System.Reflection/tests/Assembly/Assembly_EntryPointTests.cs", "max_stars_repo_name": "Priya91/corefx-1", "max_stars_repo_stars_event_min_datetime": "2019-05-03T19:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-03T19:27:45.000Z", "max_issues_repo_path": "datasets/corefx-1.0.4/src/System.Reflection/tests/Assembly/Assembly_EntryPointTests.cs", "max_issues_repo_name": "yijunyu/demo-vscode-fast", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "datasets/corefx-1.0.4/src/System.Reflection/tests/Assembly/Assembly_EntryPointTests.cs", "max_forks_repo_name": "yijunyu/demo-vscode-fast", "max_forks_repo_forks_event_min_datetime": "2021-05-14T07:51:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T07:51:44.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 25.7916666667, "max_line_length": 83, "alphanum_fraction": 0.7237479806}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Globalization; using Xunit; namespace System.Reflection.Tests { public class EntryPointTests { [Fact] public void CurrentAssemblyDoesNotHaveAnEntryPoint() { Assert.Null(typeof(EntryPointTests).GetTypeInfo().Assembly.EntryPoint); } } }
TheStack
b439ecb06c1b0ae6212c521a6d00a5491694ba28
C#code:C#
{"size": 12165, "ext": "cs", "max_stars_repo_path": "Sharparam.SwitchBladeSteam/Windows/ChatWindow.xaml.cs", "max_stars_repo_name": "Sharparam/SwitchBladeSteam", "max_stars_repo_stars_event_min_datetime": "2015-01-08T20:23:26.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-28T04:23:31.000Z", "max_issues_repo_path": "Sharparam.SwitchBladeSteam/Windows/ChatWindow.xaml.cs", "max_issues_repo_name": "Sharparam/SwitchBladeSteam", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sharparam.SwitchBladeSteam/Windows/ChatWindow.xaml.cs", "max_forks_repo_name": "Sharparam/SwitchBladeSteam", "max_forks_repo_forks_event_min_datetime": "2019-03-17T23:21:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-17T23:21:55.000Z"}
{"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 35.8849557522, "max_line_length": 124, "alphanum_fraction": 0.5816687217}
using System; using System.Collections.Specialized; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using Sharparam.SteamLib; using Sharparam.SteamLib.Events; using Sharparam.SwitchBladeSteam.Lib; using Sharparam.SwitchBladeSteam.ViewModels; using SharpBlade.Native; using SharpBlade.Razer; using SharpBlade.Razer.Events; using Steam4NET; namespace Sharparam.SwitchBladeSteam.Windows { /// <summary> /// Interaction logic for ChatWindow.xaml /// </summary> public partial class ChatWindow : ISwitchbladeWindow { private const string DefaultInputMessage = "Tap to type a message..."; private const string TitleFormat = "{0}"; private const int ScrollThreshold = 10; private static readonly SolidColorBrush IdleColor = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); private static readonly SolidColorBrush ActiveColor = new SolidColorBrush(Color.FromArgb(100, 51, 153, 0)); private readonly RazerManager _razer; private readonly Friend _friend; private readonly OverlayHelper _overlayHelper; private bool _activated; private Friend _lastMessageFriend; private ScrollViewer _historyBoxScroller; private int _pressYPos; private int _lastYPos; private int _deltaYPos; public ChatWindow(Friend friend) { InitializeComponent(); _friend = friend; _overlayHelper = new OverlayHelper(NewMessageOverlay, NewMessageOverlayLabel); TitleLabel.Content = String.Format(TitleFormat, _friend.Name); _friend.TypingMessageReceived += FriendOnTypingMessageReceived; _friend.ChatMessageReceived += FriendOnChatMessageReceived; Provider.Steam.MessageReceived += SteamOnMessageReceived; var viewModel = FriendViewModel.GetViewModel(_friend); DataContext = viewModel; ((INotifyCollectionChanged) viewModel.Messages.Messages).CollectionChanged += MessagesCollectionChanged; _razer = Provider.Razer; ActivateApp(); Provider.CurrentWindow = this; } public void ActivateApp() { if (_activated) return; _razer.Touchpad.SetWindow(this, RenderMethod.Polling, new TimeSpan(0, 0, 0, 0, 42)); _razer.Touchpad.EnableGesture(RazerAPI.GestureType.Press); _razer.Touchpad.EnableGesture(RazerAPI.GestureType.Tap); _razer.Touchpad.EnableGesture(RazerAPI.GestureType.Move); _razer.Touchpad.Gesture += TouchpadOnGesture; // Set up dynamic keys _razer.EnableDynamicKey(RazerAPI.DynamicKeyType.DK1, FriendsKeyPressed, @"Default\Images\dk_friends.png", @"Default\Images\dk_friends_pressed.png", true); _razer.EnableDynamicKey(RazerAPI.DynamicKeyType.DK2, GamesKeyPressed, @"Default\Images\dk_games.png", @"Default\Images\dk_games_pressed.png", true); _razer.EnableDynamicKey(RazerAPI.DynamicKeyType.DK10, (s, e) => ScrollHistoryBoxUp(), @"Default\Images\dk_up.png", @"Default\Images\dk_up_pressed.png", true); _razer.EnableDynamicKey(RazerAPI.DynamicKeyType.DK5, (s, e) => ScrollHistoryBoxDown(), @"Default\Images\dk_down.png", @"Default\Images\dk_down_pressed.png", true); _razer.EnableDynamicKey(RazerAPI.DynamicKeyType.DK4, (s, e) => ScrollHistoryBoxToEnd(), @"Default\Images\dk_bottom.png", @"Default\Images\dk_bottom_pressed.png", true); _activated = true; } public void DeactivateApp() { if (!_activated) return; Provider.Steam.MessageReceived -= SteamOnMessageReceived; if (_razer.KeyboardCapture) _razer.SetKeyboardCapture(false); _razer.Touchpad.DisableGesture(RazerAPI.GestureType.Press); _razer.Touchpad.DisableGesture(RazerAPI.GestureType.Tap); _razer.Touchpad.DisableGesture(RazerAPI.GestureType.Move); _razer.DisableDynamicKey(RazerAPI.DynamicKeyType.DK1); _razer.DisableDynamicKey(RazerAPI.DynamicKeyType.DK10); _razer.DisableDynamicKey(RazerAPI.DynamicKeyType.DK5); _razer.DisableDynamicKey(RazerAPI.DynamicKeyType.DK4); _razer.Touchpad.Gesture -= TouchpadOnGesture; _razer.Touchpad.Clear(); _activated = false; } private void SteamOnMessageReceived(object sender, MessageEventArgs messageEventArgs) { var id = messageEventArgs.Message.Sender; if (messageEventArgs.Message.Type != EChatEntryType.k_EChatEntryTypeChatMsg || id == Provider.Steam.LocalUser || _friend == id) return; var friend = Provider.Steam.Friends.GetFriendById(id); if (friend == null) return; _lastMessageFriend = friend; _overlayHelper.Show(_lastMessageFriend.Name, 5000); } private void SetTitle(string content) { if (TitleLabel.Dispatcher.CheckAccess()) TitleLabel.Content = content; else TitleLabel.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => SetTitle(content))); } private void ScrollHistoryBoxToEnd() { try { if (_historyBoxScroller.Dispatcher.CheckAccess()) _historyBoxScroller.ScrollToEnd(); else _historyBoxScroller.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (ScrollHistoryBoxToEnd)); } catch (NullReferenceException) { } } private void ScrollHistoryBoxUp() { try { if (_historyBoxScroller.Dispatcher.CheckAccess()) _historyBoxScroller.LineUp(); else _historyBoxScroller.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(ScrollHistoryBoxUp)); } catch (NullReferenceException) { } } private void ScrollHistoryBoxDown() { try { if (_historyBoxScroller.Dispatcher.CheckAccess()) _historyBoxScroller.LineDown(); else _historyBoxScroller.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(ScrollHistoryBoxDown)); } catch (NullReferenceException) { } } private void WindowLoaded(object sender, RoutedEventArgs e) { Helper.ExtendWindowStyleWithTool(this); _historyBoxScroller = Helper.GetDescendantByType<ScrollViewer>(HistoryBox); if (HistoryBox.SelectedIndex > -1) HistoryBox.SelectedIndex = -1; ScrollHistoryBoxToEnd(); } private void FriendOnTypingMessageReceived(object sender, MessageEventArgs messageEventArgs) { if (TitleLabel.Dispatcher.CheckAccess()) SetTitle(TitleLabel.Content + " is typing..."); else TitleLabel.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() => SetTitle(TitleLabel.Content + " is typing..."))); } private void FriendOnChatMessageReceived(object sender, MessageEventArgs messageEventArgs) { SetTitle(String.Format(TitleFormat, _friend.Name)); } private void MessagesCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) { ScrollHistoryBoxToEnd(); } private void FriendsKeyPressed(object sender, EventArgs eventArgs) { DeactivateApp(); Application.Current.MainWindow = new FriendsWindow(); Close(); Application.Current.MainWindow.Show(); } private void GamesKeyPressed(object sender, EventArgs eventArgs) { DeactivateApp(); Application.Current.MainWindow = new GamesWindow(); Close(); Application.Current.MainWindow.Show(); } private void StartChatWithFriend(Friend friend) { if (friend == null) return; Provider.Steam.MessageReceived -= SteamOnMessageReceived; DeactivateApp(); Application.Current.MainWindow = new ChatWindow(friend); Close(); Application.Current.MainWindow.Show(); } private void TouchpadOnGesture(object sender, GestureEventArgs args) { var pos = new Point(args.X, args.Y); switch (args.GestureType) { case RazerAPI.GestureType.Press: _pressYPos = args.Y; _lastYPos = _pressYPos; _deltaYPos = 0; break; case RazerAPI.GestureType.Move: var yPos = args.Y; var change = yPos - _lastYPos; _deltaYPos += change; if (Math.Abs(_deltaYPos) > ScrollThreshold) { if (_deltaYPos < 0) // Moved finger up ScrollHistoryBoxDown(); else // Moved finger down ScrollHistoryBoxUp(); _deltaYPos = 0; } _lastYPos = yPos; break; case RazerAPI.GestureType.Tap: if (NewMessageOverlay.IsVisible && _overlayHelper.IsPointInsideOverlay(pos, this)) StartChatWithFriend(_lastMessageFriend); else if (pos.Y < 433 && _razer.KeyboardCapture) StopKeyboardCapture(); else if (pos.Y >= 433 && !_razer.KeyboardCapture) StartKeyboardCapture(); break; } } private void InputBoxKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { StopKeyboardCapture(); return; } var msg = InputBox.Text; if (!String.IsNullOrEmpty(msg)) { msg = msg.Replace(" ", " "); InputBox.Text = msg; InputBox.CaretIndex = InputBox.Text.Length; var rect = InputBox.GetRectFromCharacterIndex(InputBox.CaretIndex); InputBox.ScrollToHorizontalOffset(rect.Right); } if (e.Key != Key.Return) { _friend.SendMessage(msg, EChatEntryType.k_EChatEntryTypeTyping); return; } if (String.IsNullOrEmpty(msg)) return; _friend.SendMessage(msg); InputBox.Text = String.Empty; InputBox.CaretIndex = InputBox.Text.Length; InputBox.ScrollToHorizontalOffset(InputBox.GetRectFromCharacterIndex(InputBox.CaretIndex).Right); } private void StartKeyboardCapture() { InputBox.Clear(); InputBox.Background = ActiveColor; _razer.StartWpfControlKeyboardCapture(InputBox, false); } private void StopKeyboardCapture() { InputBox.Background = IdleColor; _razer.SetKeyboardCapture(false); InputBox.Text = DefaultInputMessage; InputBox.CaretIndex = InputBox.Text.Length; InputBox.ScrollToHorizontalOffset(InputBox.GetRectFromCharacterIndex(InputBox.CaretIndex).Right); } } }
TheStack
b43d28cf65f2a1162153b84434a4901fd9e2a4a0
C#code:C#
{"size": 1266, "ext": "cs", "max_stars_repo_path": "Zilon.Core/Zilon.Core.Tests/Common/RangeExtensionsTests.cs", "max_stars_repo_name": "kreghek/Zilon_Roguelike", "max_stars_repo_stars_event_min_datetime": "2019-10-13T00:29:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T01:46:48.000Z", "max_issues_repo_path": "Zilon.Core/Zilon.Core.Tests/Common/RangeExtensionsTests.cs", "max_issues_repo_name": "kreghek/Zilon_Roguelike", "max_issues_repo_issues_event_min_datetime": "2018-11-25T23:44:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T14:29:58.000Z", "max_forks_repo_path": "Zilon.Core/Zilon.Core.Tests/Common/RangeExtensionsTests.cs", "max_forks_repo_name": "kreghek/Zilon_Roguelike", "max_forks_repo_forks_event_min_datetime": "2019-01-20T18:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T04:56:57.000Z"}
{"max_stars_count": 16.0, "max_issues_count": 912.0, "max_forks_count": 15.0, "avg_line_length": 27.5217391304, "max_line_length": 99, "alphanum_fraction": 0.541864139}
using NUnit.Framework; using Zilon.Core.Common; namespace Zilon.Core.Tests.Common { [TestFixture] [Parallelizable(ParallelScope.All)] public class RangeExtensionsTests { /// <summary> /// This is the range being checked. /// </summary> [TestCase(-2, 2, 1, ExpectedResult = 1)] [TestCase(-2, 2, -2, ExpectedResult = -2)] public int GetBounded_ValueInsideRange_ValueHaventBeCorrected(int min, int max, int value) { // ARRANGE var range = new Range<int>(min, max); // ACT var factValue = range.GetBounded(value); // ASSERT return factValue; } /// <summary> /// This is the range being checked. /// </summary> [TestCase(-2, 2, 3, ExpectedResult = 2)] [TestCase(-2, 2, -3, ExpectedResult = -2)] [TestCase(-2, 2, -30, ExpectedResult = -2)] public int ValueSetter_ValueOutsideRange_ValueShiftedIntoRange(int min, int max, int value) { // ARRANGE var range = new Range<int>(min, max); // ACT var factValue = range.GetBounded(value); // ASSERT return factValue; } } }
TheStack
b43dece6d3bc04662f86a25ede12968bd008ce11
C#code:C#
{"size": 314, "ext": "cs", "max_stars_repo_path": "ValueInjection.Test/Data/WrongSourcePropertyTestData.cs", "max_stars_repo_name": "peterwurzinger/ValueInjection", "max_stars_repo_stars_event_min_datetime": "2016-08-29T05:46:30.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-18T23:58:25.000Z", "max_issues_repo_path": "ValueInjection.Test/Data/WrongSourcePropertyTestData.cs", "max_issues_repo_name": "peterwurzinger/ValueInjection", "max_issues_repo_issues_event_min_datetime": "2016-11-09T12:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-10T09:03:49.000Z", "max_forks_repo_path": "ValueInjection.Test/Data/WrongSourcePropertyTestData.cs", "max_forks_repo_name": "peterwurzinger/ValueInjection", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 3.0, "max_issues_count": 2.0, "max_forks_count": null, "avg_line_length": 22.4285714286, "max_line_length": 89, "alphanum_fraction": 0.678343949}
using System; namespace ValueInjection.Test.Data { [Serializable] public class WrongSourcePropertyTestData { public int ValueKey { get; set; } [ValueInjection(typeof(RemoteTestData), nameof(ValueKey), "NotExistingProperty")] public string InjectedValue { get; set; } } }
TheStack
b43f3eab6f6973506911b5415c2d608ee00ec4fc
C#code:C#
{"size": 2964, "ext": "cs", "max_stars_repo_path": "Sitecore.Commerce.PaymentService/Models/CardPaymentException.cs", "max_stars_repo_name": "Sitecore/Commerce-Connect-StarterKit", "max_stars_repo_stars_event_min_datetime": "2016-02-21T18:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-19T19:19:02.000Z", "max_issues_repo_path": "Sitecore.Commerce.PaymentService/Models/CardPaymentException.cs", "max_issues_repo_name": "Sitecore/Commerce-Connect-StarterKit", "max_issues_repo_issues_event_min_datetime": "2016-05-13T19:56:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-21T04:50:49.000Z", "max_forks_repo_path": "Sitecore.Commerce.PaymentService/Models/CardPaymentException.cs", "max_forks_repo_name": "Sitecore/Commerce-Connect-StarterKit", "max_forks_repo_forks_event_min_datetime": "2016-05-18T16:24:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T11:06:54.000Z"}
{"max_stars_count": 15.0, "max_issues_count": 3.0, "max_forks_count": 7.0, "avg_line_length": 46.3125, "max_line_length": 168, "alphanum_fraction": 0.5833333333}
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CardPaymentException.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2016 // </copyright> // <summary> // Defines the CardPaymentException class. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2016 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // --------------------------------------------------------------------- namespace Sitecore.Commerce.PaymentService { using System; using System.Collections.Generic; /// <summary> /// Exception class for card payment errors. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "By Design. Sample only.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "Do not need serialization.")] public sealed class CardPaymentException : Exception { /// <summary> /// Initializes a new instance of the <see cref="CardPaymentException" /> class. /// </summary> public CardPaymentException() { } /// <summary> /// Initializes a new instance of the <see cref="CardPaymentException" /> class. /// </summary> /// <param name="message">The message describing the error that occurred.</param> public CardPaymentException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="CardPaymentException" /> class. /// </summary> /// <param name="message">The message describing the error that occurred.</param> /// <param name="paymentErrors">The payment errors causing the error.</param> public CardPaymentException(string message, IEnumerable<PaymentError> paymentErrors) : base(message) { this.PaymentErrors = paymentErrors; } /// <summary> /// Gets or sets payment errors. /// </summary> public IEnumerable<PaymentError> PaymentErrors { get; set; } } }
TheStack
b4419f626e6756506bd537a74d8462f317a83b9d
C#code:C#
{"size": 1384, "ext": "cs", "max_stars_repo_path": "Assets/02.Scripts/03.Loading/LoadManager.cs", "max_stars_repo_name": "SangwookYoo/SimpleTankGame-unity", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/02.Scripts/03.Loading/LoadManager.cs", "max_issues_repo_name": "SangwookYoo/SimpleTankGame-unity", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/02.Scripts/03.Loading/LoadManager.cs", "max_forks_repo_name": "SangwookYoo/SimpleTankGame-unity", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.137254902, "max_line_length": 95, "alphanum_fraction": 0.5592485549}
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class LoadManager : MonoBehaviour { public Slider progressbar; public Text loadtext; public string switchToScene; private void Start() { StartCoroutine(LoadScene()); } IEnumerator LoadScene() { yield return null; AsyncOperation operation = SceneManager.LoadSceneAsync(switchToScene); // 비동기 로드 시작 operation.allowSceneActivation = false; // 로드 전까지 씬을 실행하지 않음 loadtext.text = (progressbar.value * 100.0f).ToString() + "%"; while (!operation.isDone) { yield return null; if (progressbar.value < 0.9f) { progressbar.value = Mathf.MoveTowards(progressbar.value, 0.9f, Time.deltaTime); } else if (progressbar.value >= 0.9f) { progressbar.value = Mathf.MoveTowards(progressbar.value, 1f, Time.deltaTime); } if (progressbar.value >= 1f) { loadtext.text = "100%"; } if (progressbar.value >= 1f && operation.progress >= 0.9f) { operation.allowSceneActivation = true; // 90%가 넘어가면 씬 로드 } } } }
TheStack
b445668efc3918362a0dc42dfc602bcdd2691ac4
C#code:C#
{"size": 623, "ext": "cs", "max_stars_repo_path": "src/domain/Payment/Entry.cs", "max_stars_repo_name": "luigiberrettini/sales-taxes-kata", "max_stars_repo_stars_event_min_datetime": "2020-10-21T22:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-21T22:34:50.000Z", "max_issues_repo_path": "src/domain/Payment/Entry.cs", "max_issues_repo_name": "luigiberrettini/sales-taxes-kata", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/domain/Payment/Entry.cs", "max_forks_repo_name": "luigiberrettini/sales-taxes-kata", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.92, "max_line_length": 80, "alphanum_fraction": 0.5971107544}
using SalesTaxesKata.Domain.Shopping; namespace SalesTaxesKata.Domain.Payment { public struct Entry { public int Quantity { get; } public string Description { get; } public decimal TotalPriceWithTaxes { get; } public Entry(Item item) { Description = item.IsImported ? $"imported {item.Name}" : item.Name; Quantity = item.Quantity; TotalPriceWithTaxes = item.TotalPriceAfterTaxes; } public override string ToString() { return $"{Quantity} {Description}: {TotalPriceWithTaxes:F2}"; } } }
TheStack
b445a4e7fefd55440a74164c186cc74a303e5ec0
C#code:C#
{"size": 1962, "ext": "cs", "max_stars_repo_path": "Assets/DockingCrystalMaterials.cs", "max_stars_repo_name": "JayneGale/BlankSlate0", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/DockingCrystalMaterials.cs", "max_issues_repo_name": "JayneGale/BlankSlate0", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/DockingCrystalMaterials.cs", "max_forks_repo_name": "JayneGale/BlankSlate0", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.2954545455, "max_line_length": 56, "alphanum_fraction": 0.4745158002}
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DockingCrystalMaterials : MonoBehaviour { public Material[] matColours; public Sprite[] toolSprites; Material mat; Sprite toolSprite; public Material SetMaterial(Takeable.Colour colour) { if (colour == Takeable.Colour.red) { mat = matColours[0]; } if (colour == Takeable.Colour.orange) { mat = matColours[1]; } if (colour == Takeable.Colour.yellow) { mat = matColours[2]; } if (colour == Takeable.Colour.green) { mat = matColours[3]; } if (colour == Takeable.Colour.blue) { mat = matColours[4]; } if (colour == Takeable.Colour.indigo) { mat = matColours[5]; } if (colour == Takeable.Colour.violet) { mat = matColours[6]; } return mat; } public Sprite SetSprite(Takeable.Colour colour) { if (colour == Takeable.Colour.red) { toolSprite = toolSprites[0]; } if (colour == Takeable.Colour.orange) { toolSprite = toolSprites[1]; } if (colour == Takeable.Colour.yellow) { toolSprite = toolSprites[2]; } if (colour == Takeable.Colour.green) { toolSprite = toolSprites[3]; } if (colour == Takeable.Colour.blue) { toolSprite = toolSprites[4]; } if (colour == Takeable.Colour.indigo) { toolSprite = toolSprites[5]; } if (colour == Takeable.Colour.violet) { toolSprite = toolSprites[6]; } return toolSprite; } }
TheStack
b44726f22843d1c77f35e161db8662cf1a312c0b
C#code:C#
{"size": 26791, "ext": "cs", "max_stars_repo_path": "Source/Timer.cs", "max_stars_repo_name": "Mr-sB/UnityTimer", "max_stars_repo_stars_event_min_datetime": "2020-03-09T14:08:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T14:45:03.000Z", "max_issues_repo_path": "Source/Timer.cs", "max_issues_repo_name": "Mr-sB/UnityTimer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Timer.cs", "max_forks_repo_name": "Mr-sB/UnityTimer", "max_forks_repo_forks_event_min_datetime": "2021-05-19T04:31:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-12T02:39:46.000Z"}
{"max_stars_count": 15.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 34.7483787289, "max_line_length": 142, "alphanum_fraction": 0.5455563435}
using UnityEngine; using System; using System.Collections.Generic; using Object = UnityEngine.Object; namespace GameUtil { /// <summary> /// Allows you to run events on a delay without the use of <see cref="Coroutine"/>s /// or <see cref="MonoBehaviour"/>s. /// </summary> public abstract class Timer { #region Public Properties/Fields /// <summary> /// How long the timer takes to complete from start to finish. (seconds/frame) /// </summary> public float duration { get; protected set; } /// <summary> /// whether the timer is persistence /// </summary> public bool isPersistence { get; } /// <summary> /// Whether or not the timer completed running. This is false if the timer was cancelled. /// </summary> public bool isCompleted { get; protected set; } /// <summary> /// Whether the timer uses real-time or game-time. Real time is unaffected by changes to the timescale /// of the game(e.g. pausing, slow-mo), while game time is affected. /// </summary> public bool usesRealTime { get; protected set; } /// <summary> /// Whether the timer is currently paused. /// </summary> public bool isPaused { get { return this._timeElapsedBeforePause.HasValue; } } /// <summary> /// Whether or not the timer was cancelled. /// </summary> public bool isCancelled { get { return this._timeElapsedBeforeCancel.HasValue; } } /// <summary> /// Get whether or not the timer has finished running for any reason. /// </summary> public bool isDone { get { return this.isCompleted || this.isCancelled || this.isOwnerDestroyed; } } // after the auto destroy owner is destroyed, the timer will expire // this way you don't run into any annoying bugs with timers running and accessing objects // after they have been destroyed public Object autoDestroyOwner { get; } public bool hasAutoDestroyOwner { get; } private bool isOwnerDestroyed { get { if (!hasAutoDestroyOwner || autoDestroyOwner) return false; if (!_timeElapsedBeforeAutoDestroy.HasValue) _timeElapsedBeforeAutoDestroy = GetTimeElapsed(); return true; } } #endregion #region Public Static Methods public static DelayTimer DelayAction(float duration, Action onComplete, Action<float> onUpdate = null, bool useRealTime = false, Object autoDestroyOwner = null) { return DelayActionInternal(false, duration, onComplete, onUpdate, useRealTime, autoDestroyOwner); } public static DelayFrameTimer DelayFrameAction(int frame, Action onComplete, Action<float> onUpdate = null, Object autoDestroyOwner = null) { return DelayFrameActionInternal(false, frame, onComplete, onUpdate, autoDestroyOwner); } public static LoopTimer LoopAction(float interval, Action<int> onComplete, Action<float> onUpdate = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopActionInternal(false, interval, onComplete, onUpdate, useRealTime, executeOnStart, autoDestroyOwner); } public static LoopUntilTimer LoopUntilAction(float interval, Func<LoopUntilTimer, bool> loopUntil, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopUntilActionInternal(false, interval, loopUntil, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); } public static LoopCountTimer LoopCountAction(float interval, int loopCount, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopCountActionInternal(false, interval, loopCount, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); } //Persistence public static DelayTimer PersistenceDelayAction(float duration, Action onComplete, Action<float> onUpdate = null, bool useRealTime = false, Object autoDestroyOwner = null) { return DelayActionInternal(true, duration, onComplete, onUpdate, useRealTime, autoDestroyOwner); } public static DelayFrameTimer PersistenceDelayFrameAction(int frame, Action onComplete, Action<float> onUpdate = null, Object autoDestroyOwner = null) { return DelayFrameActionInternal(true, frame, onComplete, onUpdate, autoDestroyOwner); } public static LoopTimer PersistenceLoopAction(float interval, Action<int> onComplete, Action<float> onUpdate = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopActionInternal(true, interval, onComplete, onUpdate, useRealTime, executeOnStart, autoDestroyOwner); } public static LoopUntilTimer PersistenceLoopUntilAction(float interval, Func<LoopUntilTimer, bool> loopUntil, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopUntilActionInternal(true, interval, loopUntil, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); } public static LoopCountTimer PersistenceLoopCountAction(float interval, int loopCount, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { return LoopCountActionInternal(true, interval, loopCount, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); } /// <summary> /// Restart a timer. The main benefit of this over the method on the instance is that you will not get /// a <see cref="NullReferenceException"/> if the timer is null. /// </summary> /// <param name="timer">The timer to restart.</param> public static void Restart(Timer timer) { if (timer != null) { timer.Restart(); } } /// <summary> /// Cancels a timer. The main benefit of this over the method on the instance is that you will not get /// a <see cref="NullReferenceException"/> if the timer is null. /// </summary> /// <param name="timer">The timer to cancel.</param> public static void Cancel(Timer timer) { if (timer != null) { timer.Cancel(); } } /// <summary> /// Pause a timer. The main benefit of this over the method on the instance is that you will not get /// a <see cref="NullReferenceException"/> if the timer is null. /// </summary> /// <param name="timer">The timer to pause.</param> public static void Pause(Timer timer) { if (timer != null) { timer.Pause(); } } /// <summary> /// Resume a timer. The main benefit of this over the method on the instance is that you will not get /// a <see cref="NullReferenceException"/> if the timer is null. /// </summary> /// <param name="timer">The timer to resume.</param> public static void Resume(Timer timer) { if (timer != null) { timer.Resume(); } } public static void CancelAllRegisteredTimersByOwner(Object owner) { if (_manager != null) { _manager.CancelAllTimersByOwner(owner); } // if the manager doesn't exist, we don't have any registered timers yet, so don't // need to do anything in this case } public static void CancelAllRegisteredTimers() { if (_manager != null) { _manager.CancelAllTimers(); } // if the manager doesn't exist, we don't have any registered timers yet, so don't // need to do anything in this case } public static void PauseAllRegisteredTimers() { if (_manager != null) { _manager.PauseAllTimers(); } // if the manager doesn't exist, we don't have any registered timers yet, so don't // need to do anything in this case } public static void ResumeAllRegisteredTimers() { if (_manager != null) { _manager.ResumeAllTimers(); } // if the manager doesn't exist, we don't have any registered timers yet, so don't // need to do anything in this case } #endregion #region Public Methods /// <summary> /// Restart a timer that is in-progress or done. The timer's on completion callback will not be called. /// </summary> public void Restart() { //auto destroy. return if (isOwnerDestroyed) return; isCompleted = false; _startTime = GetWorldTime(); _lastUpdateTime = _startTime; _timeElapsedBeforeCancel = null; _timeElapsedBeforePause = null; _timeElapsedBeforeAutoDestroy = null; OnRestart(); Register(); } /// <summary> /// Stop a timer that is in-progress or paused. The timer's on completion callback will not be called. /// </summary> public void Cancel() { if (this.isDone) { return; } this._timeElapsedBeforeCancel = this.GetTimeElapsed(); this._timeElapsedBeforePause = null; } /// <summary> /// Pause a running timer. A paused timer can be resumed from the same point it was paused. /// </summary> public void Pause() { if (this.isPaused || this.isDone) { return; } this._timeElapsedBeforePause = this.GetTimeElapsed(); } /// <summary> /// Continue a paused timer. Does nothing if the timer has not been paused. /// </summary> public void Resume() { if (!this.isPaused || this.isDone) { return; } this._timeElapsedBeforePause = null; } /// <summary> /// Get how many seconds/frame have elapsed since the start of this timer's current cycle. /// </summary> /// <returns>The number of seconds that have elapsed since the start of this timer's current cycle, i.e. /// the current loop if the timer is looped, or the start if it isn't. /// /// If the timer has finished running, this is equal to the duration. /// /// If the timer was cancelled/paused, this is equal to the number of seconds that passed between the timer /// starting and when it was cancelled/paused.</returns> public float GetTimeElapsed() { if (this.isCompleted) { return this.duration; } return this._timeElapsedBeforeCancel ?? this._timeElapsedBeforePause ?? this._timeElapsedBeforeAutoDestroy ?? this.GetWorldTime() - this._startTime; } /// <summary> /// Get how many seconds/frame remain before the timer completes. /// </summary> /// <returns>The number of seconds that remain to be elapsed until the timer is completed. A timer /// is only elapsing time if it is not paused, cancelled, or completed. This will be equal to zero /// if the timer completed.</returns> public float GetTimeRemaining() { return this.duration - this.GetTimeElapsed(); } /// <summary> /// Get how much progress the timer has made from start to finish as a ratio. /// </summary> /// <returns>A value from 0 to 1 indicating how much of the timer's duration has been elapsed.</returns> public float GetRatioComplete() { return this.GetTimeElapsed() / this.duration; } /// <summary> /// Get how much progress the timer has left to make as a ratio. /// </summary> /// <returns>A value from 0 to 1 indicating how much of the timer's duration remains to be elapsed.</returns> public float GetRatioRemaining() { return this.GetTimeRemaining() / this.duration; } #endregion #region Private Static Methods private static void InitTimerManager() { if (_manager != null) return; // create a manager object to update all the timers if one does not already exist. _manager = Object.FindObjectOfType<TimerManager>(); if (_manager == null) _manager = new GameObject(nameof(TimerManager)).AddComponent<TimerManager>(); Object.DontDestroyOnLoad(_manager.transform.root.gameObject); } private static DelayTimer DelayActionInternal(bool isPersistence, float duration, Action onComplete, Action<float> onUpdate = null, bool useRealTime = false, Object autoDestroyOwner = null) { //Check if (duration <= 0) { SafeCall(onUpdate, 0); SafeCall(onComplete); return null; } var timer = new DelayTimer(isPersistence, duration, onComplete, onUpdate, useRealTime, autoDestroyOwner); timer.Init(); return timer; } private static DelayFrameTimer DelayFrameActionInternal(bool isPersistence, int frame, Action onComplete, Action<float> onUpdate = null, Object autoDestroyOwner = null) { //Check if (frame <= 0) { SafeCall(onUpdate, 0); SafeCall(onComplete); return null; } var timer = new DelayFrameTimer(isPersistence, frame, onComplete, onUpdate, autoDestroyOwner); timer.Init(); return timer; } private static LoopTimer LoopActionInternal(bool isPersistence, float interval, Action<int> onComplete, Action<float> onUpdate = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { var timer = new LoopTimer(isPersistence, interval, onComplete, onUpdate, useRealTime, executeOnStart, autoDestroyOwner); timer.Init(); return timer; } private static LoopUntilTimer LoopUntilActionInternal(bool isPersistence, float interval, Func<LoopUntilTimer, bool> loopUntil, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { var timer = new LoopUntilTimer(isPersistence, interval, loopUntil, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); timer.Init(); return timer; } private static LoopCountTimer LoopCountActionInternal(bool isPersistence, float interval, int loopCount, Action<int> onComplete, Action<float> onUpdate = null, Action onFinished = null, bool useRealTime = false, bool executeOnStart = false, Object autoDestroyOwner = null) { //Check if (loopCount <= 0) { SafeCall(onUpdate, 0); SafeCall(onComplete, 1); SafeCall(onFinished); return null; } var timer = new LoopCountTimer(isPersistence, interval, loopCount, onComplete, onUpdate, onFinished, useRealTime, executeOnStart, autoDestroyOwner); timer.Init(); return timer; } #endregion #region Private Static Properties/Fields // responsible for updating all registered timers private static TimerManager _manager; #endregion #region Private/Protected Properties/Fields // whether the timer is in TimeManager private bool _isInManager; protected Action<float> _onUpdate; protected float _startTime; private float _lastUpdateTime; // for pausing, we push the start time forward by the amount of time that has passed. // this will mess with the amount of time that elapsed when we're cancelled or paused if we just // check the start time versus the current world time, so we need to cache the time that was elapsed // before we paused/cancelled/autoDestroy private float? _timeElapsedBeforeCancel; private float? _timeElapsedBeforePause; private float? _timeElapsedBeforeAutoDestroy; private readonly LinkedListNode<Timer> _linkedListNode; #endregion #region Constructor (use static method to create new timer) static Timer() { InitTimerManager(); } protected Timer(bool isPersistence, float duration, Action<float> onUpdate, bool usesRealTime, Object autoDestroyOwner) { this.isPersistence = isPersistence; this.duration = duration; this._onUpdate = onUpdate; this.usesRealTime = usesRealTime; this.autoDestroyOwner = autoDestroyOwner; this.hasAutoDestroyOwner = autoDestroyOwner != null; _linkedListNode = new LinkedListNode<Timer>(this); } #endregion #region Private/Protected Methods private void Init() { //avoid virtual member call in constructor _startTime = GetWorldTime(); _lastUpdateTime = _startTime; Register(); OnInit(); } private void Register() { //no need to add if (_isInManager) return; _isInManager = true; _manager.Register(this); } protected float GetFireTime() { return _startTime + duration; } protected virtual float GetWorldTime() { return this.usesRealTime ? Time.realtimeSinceStartup : Time.time; } protected virtual void OnInit() { } protected abstract void Update(); protected virtual void OnRestart() { } protected bool CheckUpdate() { if (isDone) return false; if (isPaused) { var curTime = GetWorldTime(); _startTime += curTime - _lastUpdateTime; _lastUpdateTime = curTime; return false; } _lastUpdateTime = GetWorldTime(); return true; } protected static void SafeCall(Action action) { if (action == null) return; try { action(); } catch (Exception e) { Debug.LogError(e); } } protected static void SafeCall<T>(Action<T> action, T arg) { if (action == null) return; try { action(arg); } catch (Exception e) { Debug.LogError(e); } } protected static TResult SafeCall<TResult>(Func<TResult> func) { if (func == null) return default; try { return func(); } catch (Exception e) { Debug.LogError(e); return default; } } protected static TResult SafeCall<T, TResult>(Func<T, TResult> func, T arg) { if (func == null) return default; try { return func(arg); } catch (Exception e) { Debug.LogError(e); return default; } } #endregion #region Manager Class (implementation detail, spawned automatically and updates all registered timers) /// <summary> /// Manages updating all the <see cref="Timer"/>s that are running in the application. /// This will be instantiated the first time you create a timer -- you do not need to add it into the /// scene manually. /// </summary> private class TimerManager : MonoBehaviour { private readonly LinkedList<Timer> _persistenceTimers = new LinkedList<Timer>(); //can not be effected by Timer.xxAllRegisteredTimers() methods private readonly LinkedList<Timer> _timers = new LinkedList<Timer>(); // buffer adding timers so we don't edit a collection during iteration private readonly List<Timer> _timersToAdd = new List<Timer>(); private readonly List<Timer> _persistenceTimersToAdd = new List<Timer>(); public void CancelAllTimers() { foreach (Timer timer in _timers) { timer.Cancel(); timer._isInManager = false; } foreach (Timer timer in _timersToAdd) { timer.Cancel(); timer._isInManager = false; } _timers.Clear(); _timersToAdd.Clear(); } public void CancelAllTimersByOwner(Object owner) { if (!owner) return; CancelAllTimersByOwner(_timers, _timersToAdd, owner); CancelAllTimersByOwner(_persistenceTimers, _persistenceTimersToAdd, owner); } public void PauseAllTimers() { foreach (Timer timer in _timers) { timer.Pause(); } foreach (Timer timer in _timersToAdd) { timer.Pause(); } } public void ResumeAllTimers() { foreach (Timer timer in _timers) { timer.Resume(); } foreach (Timer timer in _timersToAdd) { timer.Resume(); } } public void Register(Timer timer) { if (!timer.isPersistence) _timersToAdd.Add(timer); else _persistenceTimersToAdd.Add(timer); } // update all the registered timers on every frame private void Update() { UpdateTimers(); UpdatePersistenceTimers(); } //Timer private void UpdateTimers() { UpdateTimersInternal(_timers, _timersToAdd); } //PersistenceTimer private void UpdatePersistenceTimers() { UpdateTimersInternal(_persistenceTimers, _persistenceTimersToAdd); } private static void UpdateTimersInternal(LinkedList<Timer> timers, List<Timer> timersToAdd) { int toAddCount = timersToAdd.Count; if (toAddCount > 0) { for (int i = 0; i < toAddCount; i++) timers.AddLast(timersToAdd[i]._linkedListNode); timersToAdd.Clear(); } var node = timers.First; while (node != null) { var timer = node.Value; timer.Update(); if (timer.isDone) { timer._isInManager = false; var toRemoveNode = node; node = node.Next; //remove timers.Remove(toRemoveNode); } else node = node.Next; } } private static void CancelAllTimersByOwner(LinkedList<Timer> timers, List<Timer> timersToAdd, Object owner) { var node = timers.First; while (node != null) { var timer = node.Value; if (!timer.isDone && timer.autoDestroyOwner == owner) { timer.Cancel(); timer._isInManager = false; var toRemoveNode = node; node = node.Next; //remove timers.Remove(toRemoveNode); } else node = node.Next; } for (int i = timersToAdd.Count - 1; i >= 0; i--) { var timer = timersToAdd[i]; if (!timer.isDone && timer.autoDestroyOwner != owner) continue; timer.Cancel(); timer._isInManager = false; //remove timersToAdd.RemoveAt(i); } } } #endregion } }
TheStack
b4487899a07d361b16423ab00da9ee110d88a03c
C#code:C#
{"size": 1625, "ext": "cs", "max_stars_repo_path": "Bot/Dialogs/GetDefaultBuildingDialog.cs", "max_stars_repo_name": "RightpointLabs/conference-room", "max_stars_repo_stars_event_min_datetime": "2016-10-13T01:55:55.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-03T15:46:51.000Z", "max_issues_repo_path": "Bot/Dialogs/GetDefaultBuildingDialog.cs", "max_issues_repo_name": "hnjm/conference-room", "max_issues_repo_issues_event_min_datetime": "2016-08-12T18:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-20T15:43:25.000Z", "max_forks_repo_path": "Bot/Dialogs/GetDefaultBuildingDialog.cs", "max_forks_repo_name": "hnjm/conference-room", "max_forks_repo_forks_event_min_datetime": "2016-10-13T01:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-23T14:44:00.000Z"}
{"max_stars_count": 3.0, "max_issues_count": 7.0, "max_forks_count": 3.0, "avg_line_length": 33.1632653061, "max_line_length": 135, "alphanum_fraction": 0.6664615385}
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using RightpointLabs.ConferenceRoom.Bot.Extensions; using RightpointLabs.ConferenceRoom.Bot.Models; namespace RightpointLabs.ConferenceRoom.Bot.Dialogs { [Serializable] public class GetDefaultBuildingDialog : IDialog<BuildingChoice> { private Uri _requestUri; public GetDefaultBuildingDialog(Uri requestUri) { _requestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri)); } public async Task StartAsync(IDialogContext context) { // without this wait, we'd double-process the last message recieved context.Wait(MessageReceivedAsync); } public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument) { var building = context.GetBuilding(); if (null != building) { context.Done(building); return; } await context.Forward(new ChooseBuildingDialog(_requestUri, null), GotBuilding, context.Activity, new CancellationToken()); } public async Task GotBuilding(IDialogContext context, IAwaitable<BuildingChoice> argument) { var building = await argument; context.SetBuilding(building); await context.PostAsync(context.CreateMessage($"Building set to {building.BuildingName}.", InputHints.AcceptingInput)); context.Done(building); } } }
TheStack
b449251f43c87c995cce4bc1fb49202fd5d02017
C#code:C#
{"size": 445, "ext": "cs", "max_stars_repo_path": "templates/templates/StarterWebMvc-CSharp/Data/ApplicationDbContext.cs", "max_stars_repo_name": "dlmelendez/identityazuretable", "max_stars_repo_stars_event_min_datetime": "2016-07-23T04:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:10:46.000Z", "max_issues_repo_path": "templates/templates/StarterWebMvc-CSharp/Data/ApplicationDbContext.cs", "max_issues_repo_name": "dlmelendez/identityazuretable", "max_issues_repo_issues_event_min_datetime": "2016-08-04T07:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T22:00:30.000Z", "max_forks_repo_path": "templates/templates/StarterWebMvc-CSharp/Data/ApplicationDbContext.cs", "max_forks_repo_name": "dlmelendez/identityazuretable", "max_forks_repo_forks_event_min_datetime": "2016-09-05T20:44:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T14:28:26.000Z"}
{"max_stars_count": 101.0, "max_issues_count": 69.0, "max_forks_count": 38.0, "avg_line_length": 22.25, "max_line_length": 80, "alphanum_fraction": 0.7033707865}
using ElCamino.AspNetCore.Identity.AzureTable; using ElCamino.AspNetCore.Identity.AzureTable.Model; using System; using System.Collections.Generic; using System.Text; namespace samplemvccore5.Data { public class ApplicationDbContext : IdentityCloudContext { public ApplicationDbContext() : base() { } public ApplicationDbContext(IdentityConfiguration config) : base(config) { } } }
TheStack
b44a6837d09c23a1f117d5e075fcb8bb6e05e905
C#code:C#
{"size": 11820, "ext": "cs", "max_stars_repo_path": "Libraries/_SourceGrid/SourceGrid/Common/ColumnsBase.cs", "max_stars_repo_name": "alexfordc/Au", "max_stars_repo_stars_event_min_datetime": "2020-04-17T12:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T12:25:07.000Z", "max_issues_repo_path": "Libraries/_SourceGrid/SourceGrid/Common/ColumnsBase.cs", "max_issues_repo_name": "alexfordc/Au", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libraries/_SourceGrid/SourceGrid/Common/ColumnsBase.cs", "max_forks_repo_name": "alexfordc/Au", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.474137931, "max_line_length": 114, "alphanum_fraction": 0.6292724196}
using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.Windows.Forms; using System.ComponentModel; namespace SourceGrid { /// <summary> /// Abstract base class for manage columns informations. /// </summary> public abstract class ColumnsBase { private GridVirtual mGrid; public ColumnsBase(GridVirtual grid) { mGrid = grid; } public GridVirtual Grid { get{return mGrid;} } #region Abstract methods public abstract int Count { get; } /// <summary> /// Gets the width of the specified column. /// </summary> /// <param name="column"></param> /// <returns></returns> public abstract int GetWidth(int column); /// <summary> /// Sets the width of the specified column. /// </summary> /// <param name="column"></param> /// <param name="width"></param> public abstract void SetWidth(int column, int width); public abstract AutoSizeMode GetAutoSizeMode(int column); #endregion /// <summary> /// Autosize column using default auto size mode /// </summary> /// <param name="column"></param> public void AutoSizeColumn(int column) { AutoSizeColumn(column, true); } /// <summary> /// Autosize column using default auto size mode /// </summary> public void AutoSizeColumn(int column, bool useRowHeight) { int minRow = 0; int maxRow = Grid.Rows.Count - 1; if ((GetAutoSizeMode(column) & AutoSizeMode.EnableAutoSizeView) == AutoSizeMode.EnableAutoSizeView) { bool isColumnVisible = this.Grid.GetVisibleColumns(true).Contains(column); if (isColumnVisible == false) return; List<int> visibleRows = Grid.GetVisibleRows(true); visibleRows.Sort(); if (visibleRows.Count == 0) return; minRow = visibleRows[0]; maxRow = visibleRows[visibleRows.Count - 1]; } AutoSizeColumn(column, useRowHeight, minRow, maxRow); } public void AutoSizeColumn(int column, bool useRowHeight, int StartRow, int EndRow) { if ((GetAutoSizeMode(column) & AutoSizeMode.EnableAutoSize) == AutoSizeMode.EnableAutoSize && IsColumnVisible(column) ) SetWidth(column, MeasureColumnWidth(column, useRowHeight, StartRow, EndRow) ); } /// <summary> /// Measures the current column when drawn with the specified cells. /// </summary> /// <param name="column"></param> /// <param name="useRowHeight">True to fix the row height when measure the column width.</param> /// <param name="StartRow">Start row to measure</param> /// <param name="EndRow">End row to measure</param> /// <returns>Returns the required width</returns> public int MeasureColumnWidth(int column, bool useRowHeight, int StartRow, int EndRow) { int min = Grid.MinimumWidth; if ((GetAutoSizeMode(column) & AutoSizeMode.MinimumSize) == AutoSizeMode.MinimumSize) return min; for (int r = StartRow; r <= EndRow; r++) { Cells.ICellVirtual cell = Grid.GetCell(r, column); if (cell != null) { Position cellPosition = new Position(r, column); Size maxLayout = Size.Empty; //Use the width of the actual cell (considering spanned cells) if (useRowHeight) maxLayout.Height = Grid.RangeToSize(Grid.PositionToCellRange(cellPosition)).Height; CellContext cellContext = new CellContext(Grid, cellPosition, cell); Size cellSize = cellContext.Measure(maxLayout); if (cellSize.Width > min) min = cellSize.Width; } } return min; } public void AutoSize(bool useRowHeight) { SuspendLayout(); for (int i = 0; i < Count; i++) { AutoSizeColumn(i, useRowHeight); } ResumeLayout(); } /// <summary> /// Auto size all the columns with the max required width of all cells. /// </summary> /// <param name="useRowHeight">True to fix the row height when measure the column width.</param> /// <param name="StartRow">Start row to measure</param> /// <param name="EndRow">End row to measure</param> public void AutoSize(bool useRowHeight, int StartRow, int EndRow) { SuspendLayout(); for (int i = 0; i < Count; i++) { AutoSizeColumn(i, useRowHeight, StartRow, EndRow); } ResumeLayout(); } /// <summary> /// stretch the columns width to always fit the available space when the contents of the cell is smaller. /// </summary> public virtual void StretchToFit() { SuspendLayout(); Rectangle displayRect = Grid.DisplayRectangle; if (Count > 0 && displayRect.Width > 0) { List<int> visibleIndex = ColumnsInsideRegion(displayRect.X, displayRect.Width); //Continue only if the columns are all visible, otherwise this method cannot shirnk the columns if (visibleIndex.Count >= Count) { int? current = GetRight(Count - 1); if (current != null && displayRect.Width > current.Value) { //Calculate the columns to stretch int countToStretch = 0; for (int i = 0; i < Count; i++) { if ((GetAutoSizeMode(i) & AutoSizeMode.EnableStretch) == AutoSizeMode.EnableStretch && IsColumnVisible(i) ) countToStretch++; } if (countToStretch > 0) { int deltaPerColumn = (displayRect.Width - current.Value) / countToStretch; for (int i = 0; i < Count; i++) { if ((GetAutoSizeMode(i) & AutoSizeMode.EnableStretch) == AutoSizeMode.EnableStretch && IsColumnVisible(i) ) SetWidth(i, GetWidth(i) + deltaPerColumn); } } } } } ResumeLayout(); } /// <summary> /// Gets the columns index inside the specified display area. /// </summary> /// <returns></returns> public List<int> ColumnsInsideRegion(int x, int width) { return ColumnsInsideRegion(x, width, true, true); } /// <summary> /// Gets the columns index inside the specified display area. /// The list returned is ordered by the index. /// Note that this method returns also invisible rows. /// </summary> /// <param name="returnsPartial">True to returns also partial columns</param> /// <param name="x"></param> /// <param name="width"></param> /// <param name="returnsFixedColumns"></param> /// <returns></returns> public List<int> ColumnsInsideRegion(int x, int width, bool returnsPartial, bool returnsFixedColumns) { int right = x + width; List<int> list = new List<int>(); //Add the fixed columns // Loop until the currentHeight is smaller then the requested displayRect for (int fr = 0; fr < Grid.FixedColumns && fr < Count; fr++) { int leftDisplay = GetLeft(fr); int rightDisplay = leftDisplay + GetWidth(fr); //If the column is inside the view if (right >= leftDisplay && x <= rightDisplay && (returnsPartial || (rightDisplay <= right && leftDisplay >= x))) { if (returnsFixedColumns) list.Add(fr); } if (rightDisplay > right) break; } int? relativeCol = FirstVisibleScrollableColumn; if (relativeCol != null) { //Add the standard columns for (int r = relativeCol.Value; r < Count; r++) { int leftDisplay = GetLeft(r); int rightDisplay = leftDisplay + GetWidth(r); //If the column is inside the view if (right >= leftDisplay && x <= rightDisplay && (returnsPartial || (rightDisplay <= right && leftDisplay >= x)) ) { list.Add(r); } if (rightDisplay > right) break; } } return list; } /// <summary> /// Calculate the Column that have the Left value smaller or equal than the point p_X, or -1 if not found found. /// </summary> /// <param name="x">X Coordinate to search for a column</param> /// <returns></returns> public int? ColumnAtPoint(int x) { List<int> list = ColumnsInsideRegion(x, 1); if (list.Count == 0) return null; else return list[0]; } /// <summary> /// Returns the first visible scrollable column. /// Return null if there isn't a visible column. /// </summary> /// <returns></returns> public int? FirstVisibleScrollableColumn { get { int firstVisible = Grid.CustomScrollPosition.X + Grid.FixedColumns; if (firstVisible >= Count) return null; else return firstVisible; } } /// <summary> /// Returns the last visible scrollable column. /// Return null if there isn't a visible column. /// </summary> /// <returns></returns> public int? LastVisibleScrollableColumn { get { int? first = FirstVisibleScrollableColumn; if (first == null) return null; Rectangle scrollableArea = Grid.GetScrollableArea(); int right = GetLeft(first.Value); int c = first.Value; for (; c < Count; c++) { right += GetWidth(c); if (right >= scrollableArea.Right) return c; } return c - 1; } } public GridRange GetRange(int column) { return new GridRange(0, column, Grid.Rows.Count-1, column); } #region Layout private int mSuspendedCount = 0; public void SuspendLayout() { mSuspendedCount++; } public void ResumeLayout() { if (mSuspendedCount > 0) mSuspendedCount--; PerformLayout(); } public void PerformLayout() { if (mSuspendedCount == 0) OnLayout(); } protected virtual void OnLayout() { Grid.OnCellsAreaChanged(); } #endregion /// <summary> /// Fired when the numbes of columns changed. /// </summary> public void ColumnsChanged() { PerformLayout(); } #region Left/Right public int GetAbsoluteLeft(int column) { if (column < 0) throw new ArgumentException("Must be a valid index"); int left = 0; int index = 0; while (index < column) { left += GetWidth(index); index++; } return left; } public int GetAbsoluteRight(int column) { int left = GetAbsoluteLeft(column); return left + GetWidth(column); } /// <summary> /// Gets the column left position. /// The Left is relative to the specified start position. /// Calculate the left using also the FixedColumn if present. /// </summary> public int GetLeft(int column) { int actualFixedColumns = Math.Min(Grid.FixedColumns, Count); int left = 0; //Calculate fixed left cells for (int i = 0; i < actualFixedColumns; i++) { if (i == column) return left; left += GetWidth(i); } int? relativeColumn = FirstVisibleScrollableColumn; if (relativeColumn == null) relativeColumn = Count; if (relativeColumn == column) return left; else if (relativeColumn < column) { for (int i = relativeColumn.Value; i < Count; i++) { if (i == column) return left; left += GetWidth(i); } } else if (relativeColumn > column) { for (int i = relativeColumn.Value - 1; i >= 0; i--) { left -= GetWidth(i); if (i == column) return left; } } throw new IndexOutOfRangeException(); } /// <summary> /// Gets the column right position. GetLeft + GetWidth. /// </summary> public int GetRight(int column) { int left = GetLeft(column); return left + GetWidth(column); } #endregion /// <summary> /// Show a column (set the width to default width) /// </summary> /// <param name="column"></param> public abstract void ShowColumn(int column); /// <summary> /// Hide the specified column (set the width to 0) /// </summary> /// <param name="column"></param> public abstract void HideColumn(int column); /// <summary> /// Returns true if the specified column is visible /// </summary> /// <param name="column"></param> /// <returns></returns> public abstract bool IsColumnVisible(int column); } }
TheStack
b44b0cbe44f6837a755e32cc8efe25057e1eaf90
C#code:C#
{"size": 633, "ext": "cs", "max_stars_repo_path": "AspNetCoreInAzureFunctions.Sample/SampleController.cs", "max_stars_repo_name": "julienblin/AspNetCoreInAzureFunctions", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AspNetCoreInAzureFunctions.Sample/SampleController.cs", "max_issues_repo_name": "julienblin/AspNetCoreInAzureFunctions", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AspNetCoreInAzureFunctions.Sample/SampleController.cs", "max_forks_repo_name": "julienblin/AspNetCoreInAzureFunctions", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.375, "max_line_length": 66, "alphanum_fraction": 0.5939968404}
using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; namespace AspNetCoreInAzureFunctions.Sample { [ApiController] public class SampleController : ControllerBase { [HttpGet("")] [SwaggerOperation(Summary = "Simple index response")] public IActionResult Index() { return Ok(new { Message = "Index" }); } [HttpGet("hello")] [SwaggerOperation(Summary = "Hello world!")] public IActionResult Hello([FromQuery] string name = null) { return Ok(new { Info = $"Hello, {name ?? "world"}" }); } } }
TheStack
b44b6006f9f9e0433a3d9c691cc2c9494d32dda1
C#code:C#
{"size": 2741, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Interaction/CameraHandler.cs", "max_stars_repo_name": "five3025/innersphereonline", "max_stars_repo_stars_event_min_datetime": "2017-01-22T17:33:38.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-22T17:33:38.000Z", "max_issues_repo_path": "Assets/Scripts/Interaction/CameraHandler.cs", "max_issues_repo_name": "five3025/innersphereonline", "max_issues_repo_issues_event_min_datetime": "2017-01-18T05:47:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-22T20:07:16.000Z", "max_forks_repo_path": "Assets/Scripts/Interaction/CameraHandler.cs", "max_forks_repo_name": "five3025/innersphereonline", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 5.0, "max_forks_count": null, "avg_line_length": 31.1477272727, "max_line_length": 146, "alphanum_fraction": 0.7307551988}
using System; using UnityEngine; using Zenject; public class CameraHandler : ITickable { [Inject] readonly Settings _settings; private float _cameraDistance = 0f; private bool _gliding = false; private Vector3 _startMarker; private Vector3 _endMarker; private float _glideSpeed = 0F; private float _startTime; private float _journeyLength; readonly Camera _camera; // Allow camera movement to be enabled and disabled public bool CameraMovementEnabled = false; public CameraHandler( [Inject(Id = "MainCamera")] Camera camera ) { _camera = camera; } public void StartGlide ( Vector3 destination ) { _gliding = true; _startTime = Time.time; _startMarker = _camera.transform.position; _endMarker = destination; _journeyLength = Vector3.Distance(_startMarker, _endMarker); _glideSpeed = _journeyLength / _settings.GlideSpeedBase; } // TODO: Abstract away direct references to Input public void Tick () { if ( !CameraMovementEnabled ) return; if ( _gliding ) { float distCovered = (Time.time - _startTime) * _glideSpeed; float fracJourney = distCovered / _journeyLength; _camera.transform.position = Vector3.Lerp(_startMarker, _endMarker, Mathf.SmoothStep(0.0F, 1.0F, fracJourney)); if (_camera.transform.position == _endMarker) _gliding = false; return; } float speed = 80.0F; if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) speed *= 3; float moveV = Input.GetAxis("Vertical") * speed * Time.deltaTime; float moveH = Input.GetAxis("Horizontal") * speed * Time.deltaTime; _camera.transform.Translate(_camera.transform.InverseTransformVector(new Vector3(moveH, 0, moveV))); float scrolling = Input.GetAxis("Mouse ScrollWheel"); if ( scrolling != 0 ) { // Use smaller scroll incements the further in you've zoomed float invPercentScrolled = 1 - ((_cameraDistance - _settings.MinCameraDistance) / (_settings.MaxCameraDistance - _settings.MinCameraDistance)); float scrollModifier = invPercentScrolled > 0.05 ? Mathf.Exp( invPercentScrolled ) : Mathf.Exp( invPercentScrolled )*.5f; float cameraChange = scrolling * _settings.PanSpeed * scrollModifier; //Debug.Log( invPercentScrolled + ":" + scrollModifier + ":" + cameraChange + ":" + _cameraDistance); _cameraDistance += cameraChange; if ( _cameraDistance < _settings.MaxCameraDistance && _cameraDistance > _settings.MinCameraDistance ) _camera.transform.Translate(new Vector3(0, 0, cameraChange)); else _cameraDistance -= cameraChange; } } [Serializable] public class Settings { public float MaxCameraDistance; public float MinCameraDistance; public float PanSpeed; public float GlideSpeedBase; } }
TheStack
b44c2854144dc5dae47aba093e6b1e7bf5281fd3
C#code:C#
{"size": 7607, "ext": "cs", "max_stars_repo_path": "Pokedex/Form1.Designer.cs", "max_stars_repo_name": "ShulkMaster/poo_tutorial", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pokedex/Form1.Designer.cs", "max_issues_repo_name": "ShulkMaster/poo_tutorial", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pokedex/Form1.Designer.cs", "max_forks_repo_name": "ShulkMaster/poo_tutorial", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.0118343195, "max_line_length": 146, "alphanum_fraction": 0.5930064414}
namespace Pokedex { partial class Form1 { /// <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.label2 = new System.Windows.Forms.Label(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.Id = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Picture = new System.Windows.Forms.DataGridViewImageColumn(); this.BtnPrevious = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.BtnNext = new System.Windows.Forms.Button(); this.BtnCancel = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(165, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(71, 15); this.label2.TabIndex = 1; this.label2.Text = "Page 1 of 23"; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.Id, this.NameColumn, this.Picture}); this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Bottom; this.dataGridView1.Location = new System.Drawing.Point(0, 100); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.RowTemplate.Height = 200; this.dataGridView1.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.Size = new System.Drawing.Size(800, 350); this.dataGridView1.TabIndex = 3; // // Id // this.Id.DataPropertyName = "Id"; this.Id.HeaderText = "Id"; this.Id.Name = "Id"; this.Id.ReadOnly = true; // // NameColumn // this.NameColumn.DataPropertyName = "Name"; this.NameColumn.HeaderText = "Name"; this.NameColumn.Name = "NameColumn"; this.NameColumn.ReadOnly = true; // // Picture // this.Picture.HeaderText = "Picture"; this.Picture.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Zoom; this.Picture.MinimumWidth = 50; this.Picture.Name = "Picture"; this.Picture.ReadOnly = true; this.Picture.Width = 200; // // BtnPrevious // this.BtnPrevious.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.BtnPrevious.Location = new System.Drawing.Point(3, 3); this.BtnPrevious.Name = "BtnPrevious"; this.BtnPrevious.Size = new System.Drawing.Size(75, 31); this.BtnPrevious.TabIndex = 4; this.BtnPrevious.Text = "< prev"; this.BtnPrevious.UseVisualStyleBackColor = true; this.BtnPrevious.Click += new System.EventHandler(this.BtnPrevious_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.BtnPrevious); this.flowLayoutPanel1.Controls.Add(this.BtnNext); this.flowLayoutPanel1.Controls.Add(this.label2); this.flowLayoutPanel1.Controls.Add(this.BtnCancel); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(800, 72); this.flowLayoutPanel1.TabIndex = 5; // // BtnNext // this.BtnNext.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point); this.BtnNext.Location = new System.Drawing.Point(84, 3); this.BtnNext.Name = "BtnNext"; this.BtnNext.Size = new System.Drawing.Size(75, 31); this.BtnNext.TabIndex = 5; this.BtnNext.Text = "Next >"; this.BtnNext.UseVisualStyleBackColor = true; this.BtnNext.Click += new System.EventHandler(this.BtnNext_Click); // // BtnCancel // this.BtnCancel.Enabled = false; this.BtnCancel.Location = new System.Drawing.Point(242, 3); this.BtnCancel.Name = "BtnCancel"; this.BtnCancel.Size = new System.Drawing.Size(75, 23); this.BtnCancel.TabIndex = 6; this.BtnCancel.Text = "Cancel"; this.BtnCancel.UseVisualStyleBackColor = true; this.BtnCancel.Click += new System.EventHandler(this.BtnCancel_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.flowLayoutPanel1); this.Controls.Add(this.dataGridView1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private Label label2; private DataGridView dataGridView1; private Button BtnPrevious; private FlowLayoutPanel flowLayoutPanel1; private Button BtnNext; private Button BtnCancel; private DataGridViewTextBoxColumn Id; private DataGridViewTextBoxColumn NameColumn; private DataGridViewImageColumn Picture; } }
TheStack
b44c3e5aa4b9526da4b7e5ced8503770045d8b76
C#code:C#
{"size": 903, "ext": "cs", "max_stars_repo_path": "Samples/CustomErrorHandling/WindowsUI/Program.cs", "max_stars_repo_name": "RobinsonMW/csla", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Samples/CustomErrorHandling/WindowsUI/Program.cs", "max_issues_repo_name": "RobinsonMW/csla", "max_issues_repo_issues_event_min_datetime": "2021-11-11T11:20:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:26:01.000Z", "max_forks_repo_path": "Samples/CustomErrorHandling/WindowsUI/Program.cs", "max_forks_repo_name": "peranborkett/csla", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 11.0, "max_forks_count": null, "avg_line_length": 27.3636363636, "max_line_length": 86, "alphanum_fraction": 0.6733111849}
using System; using System.Windows.Forms; using Csla; using Csla.Configuration; using Microsoft.Extensions.DependencyInjection; namespace WindowsUI { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var services = new ServiceCollection(); services.AddTransient<System.Net.Http.HttpClient>(); services.AddCsla(o => o .AddWindowsForms() .DataPortal(dpo => dpo .UseHttpProxy(hpo => hpo .DataPortalUrl = "https://localhost:44364/api/dataportal"))); var provider = services.BuildServiceProvider(); App.ApplicationContext = provider.GetRequiredService<Csla.ApplicationContext>(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
TheStack
b44d50815cc6f8a4e644fb020a1c63c5ea5b3aac
C#code:C#
{"size": 9161, "ext": "cs", "max_stars_repo_path": "shared/models/Offers.Query/QueryRanking.cs", "max_stars_repo_name": "BOONRewardsInc/rewards", "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:53:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T14:46:09.000Z", "max_issues_repo_path": "shared/models/Offers.Query/QueryRanking.cs", "max_issues_repo_name": "BOONRewardsInc/rewards", "max_issues_repo_issues_event_min_datetime": "2019-01-15T02:36:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T02:36:09.000Z", "max_forks_repo_path": "shared/models/Offers.Query/QueryRanking.cs", "max_forks_repo_name": "BOONRewardsInc/rewards", "max_forks_repo_forks_event_min_datetime": "2017-01-12T16:15:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T13:40:49.000Z"}
{"max_stars_count": 13.0, "max_issues_count": 1.0, "max_forks_count": 12.0, "avg_line_length": 47.9633507853, "max_line_length": 173, "alphanum_fraction": 0.5668595132}
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // namespace Lomo.DataModels.Offers.Query { using System; using System.Collections.Generic; using System.Linq; using Logging; /// <summary> /// Holds rakning info /// </summary> public class QueryRanking { /// <summary> /// Default number of top deals to randomize /// </summary> public const int DefaultDealsCountForRandomization = 20; /// <summary> /// Initializes a new instance of the <see cref="QueryRanking" /> class. /// </summary> /// <param name="client">the client</param> /// <param name="filters">query filters</param> /// <param name="flightKey">query flight key</param> public QueryRanking(Client client, QueryFilters filters, string flightKey) { var defaultRankingGroupSequence = RankingGroup.DefaultSequence; var pcfps = GetPlacementCfps(client, flightKey, true); var featureRankingGroupSequences = new List<int>(); var featureRankingGroupCounts = new List<byte>(); var sequenceToPlacementIndex = new Dictionary<int, string>(); var isFiltered = (filters.QueryKeywords != null && filters.QueryKeywords.Any()) || (filters.Categories != null && filters.Categories.Any()); foreach (var pcfp in pcfps.OrderBy(_ => _.Value.PlacementSequence)) { var cfpInt = pcfp.Value; RankingGroup rankingGroup; if (!RankingGroup.List.TryGetValue(cfpInt.RankingGroupKey, out rankingGroup)) { Log.Warn("QueryRanking: Ranking group for {0} key is not found.", cfpInt.RankingGroupKey); rankingGroup = RankingGroup.List.Values.FirstOrDefault(_ => _.Id == RankingGroup.DefaultId); if (rankingGroup == null) { Log.Warn("QueryRanking: RankingGroup.List.Count()={0}", RankingGroup.List.Count()); throw new Exception("QueryRanking: Default ranking group is not found."); } } // switch to unfiltered ranking group if query has explicit filters RankingGroup notFilteredRankingGroup; if (isFiltered && rankingGroup.NotFilteredKey != null && RankingGroup.List.TryGetValue(rankingGroup.NotFilteredKey, out notFilteredRankingGroup)) { rankingGroup = notFilteredRankingGroup; } var sequence = rankingGroup.QueryRankArraySequence != null ? rankingGroup.QueryRankArraySequence.Value : RankingGroup.DefaultSequence; if (cfpInt.Placement == "Default") { UseRandomDealSelection = rankingGroup.UseRandomDealSelection; defaultRankingGroupSequence = sequence; DealsCountForRandomization = cfpInt.DealsCountForRandomization; FallbackToOnlineDeals = cfpInt.FallbackToOnlineDeals; // There are cases when the same ranking group is used for default and other placements. // For these cases it better to have mapping to default if (sequenceToPlacementIndex.ContainsKey(sequence)) { sequenceToPlacementIndex.Remove(sequence); } sequenceToPlacementIndex.Add(sequence, cfpInt.Placement); } else { featureRankingGroupSequences.Add(sequence); featureRankingGroupCounts.Add(cfpInt.DefaultDealsCount); if (!sequenceToPlacementIndex.ContainsKey(sequence)) { sequenceToPlacementIndex.Add(sequence, cfpInt.Placement); } } } DefaultRankingGroupSequence = defaultRankingGroupSequence; FeatureRankingGroupSequences = featureRankingGroupSequences.ToList(); FeatureRankingGroupCounts = featureRankingGroupCounts.ToList(); SequenceToPlacementIndex = sequenceToPlacementIndex; RankArraySlot = RankingGroup.List.Values.FirstOrDefault().QueryRankArraySlot.Value; PublishingVersion = Query.PublishingVersion.List.FirstOrDefault().Key; } /// <summary> /// Gets a value indicating whether random selection of deals should be used /// </summary> public bool UseRandomDealSelection { get; private set; } /// <summary> /// Gets the ranking group id. /// </summary> public int DefaultRankingGroupSequence { get; private set; } /// <summary> /// Gets list of other ranking group ids. /// </summary> public IEnumerable<int> FeatureRankingGroupSequences { get; private set; } /// <summary> /// Gets list of ranking group counts. /// </summary> public IEnumerable<byte> FeatureRankingGroupCounts { get; private set; } /// <summary> /// Gets rank array slot used for querying. /// </summary> public byte RankArraySlot { get; private set; } /// <summary> /// Gets publishing version used for querying. /// </summary> public int PublishingVersion { get; private set; } /// <summary> /// Gets number of top deals to randomize. /// </summary> public int DealsCountForRandomization { get; private set; } /// <summary> /// Gets a value indicating whether to show online deals in case when no other deals are present /// </summary> public bool FallbackToOnlineDeals { get; private set; } /// <summary> /// Gets sequence-to-placement index /// </summary> public Dictionary<int, string> SequenceToPlacementIndex { get; private set; } /// <summary> /// (placement->client-flight-placement) dictonary for client and flight /// </summary> /// <param name="client">the client</param> /// <param name="flightKey">the flight key</param> /// <param name="allowToUseDefaultFlight">value indicating whether method is allowed to map to the default flight</param> /// <returns>(placement->client-flight-placement) dictonary</returns> public static Dictionary<string, ClientFlightPlacement> GetPlacementCfps(Client client, string flightKey, bool allowToUseDefaultFlight) { var clientFlightKey = ClientFlightPlacement.GetKey(client.Key, flightKey); Dictionary<string, ClientFlightPlacement> pcfps; if (!ClientFlightPlacement.Index.TryGetValue(clientFlightKey, out pcfps)) { clientFlightKey = ClientFlightPlacement.GetKey(Client.GetKey(client.Id, Client.AppAll), flightKey); if (!ClientFlightPlacement.Index.TryGetValue(clientFlightKey, out pcfps)) { var clientKey = Client.GetKey(Client.IdAll, Client.AppAll); clientFlightKey = ClientFlightPlacement.GetKey(clientKey, flightKey); if (!ClientFlightPlacement.Index.TryGetValue(clientFlightKey, out pcfps)) { if (allowToUseDefaultFlight) { Log.Warn("QueryRanking: Placement dictionary for {0} client with {1} flight is not found.", clientKey, flightKey); var cfp = ClientFlightPlacement.List.Values .Where(_ => _.ClientId == Client.IdAll && _.ClientAppId == Client.AppAll && _.FlightId == Flight.IdDefault) .OrderByDescending(_ => _.FlightVersion) .FirstOrDefault(); if (cfp != null) { clientFlightKey = ClientFlightPlacement.GetKey(Client.GetKey(cfp.ClientId, cfp.ClientAppId), Flight.GetKey(cfp.FlightId, cfp.FlightVersion)); ClientFlightPlacement.Index.TryGetValue(clientFlightKey, out pcfps); } else { Log.Warn("QueryRanking: ClientFlightPlacement.List.Count()={0}", ClientFlightPlacement.List.Count()); } if (pcfps == null) { throw new Exception("QueryRanking: Placement dictionary for *_* client with default flight is not found."); } } } } } return pcfps; } } }
TheStack
b44de75ccd461cdc5ad92b4cda8a8c141ab1d9d8
C#code:C#
{"size": 1556, "ext": "cs", "max_stars_repo_path": "Src/Library/GraphBuilder/SwitchBuilder.cs", "max_stars_repo_name": "LxLeChat/FlowChartCore", "max_stars_repo_stars_event_min_datetime": "2020-05-02T12:17:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T13:05:39.000Z", "max_issues_repo_path": "Src/Library/GraphBuilder/SwitchBuilder.cs", "max_issues_repo_name": "LxLeChat/FlowChartCore", "max_issues_repo_issues_event_min_datetime": "2020-04-27T14:58:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T11:54:09.000Z", "max_forks_repo_path": "Src/Library/GraphBuilder/SwitchBuilder.cs", "max_forks_repo_name": "LxLeChat/FlowChartCore", "max_forks_repo_forks_event_min_datetime": "2020-10-16T15:57:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T02:25:12.000Z"}
{"max_stars_count": 12.0, "max_issues_count": 71.0, "max_forks_count": 5.0, "avg_line_length": 25.5081967213, "max_line_length": 76, "alphanum_fraction": 0.5437017995}
using System.Collections.Generic; using DotNetGraph.Core; using DotNetGraph.Edge; using DotNetGraph.Node; namespace FlowChartCore.Graph { public class SwitchBuilder : IBuilder { public List<IDotElement> DotDefinition { get ; set; } private SwitchNode node; public SwitchBuilder(SwitchNode switchnode) { node = switchnode; DotDefinition = new List<IDotElement>(); CreateNode(); CreateEndNode(); CreateEdgeToFirstChildren(); CreateEdgeToNextSibling(); } public void CreateNode() { DotNode newnode = new DotNode(node.Id); // fix issue #54 if (node.flags != null) { newnode.Label = $"Switch {node.flags} {node.Condition}"; } else { newnode.Label = $"Switch {node.Condition}"; } DotDefinition.Add(newnode); } public void CreateEdgeToNextSibling() { DotEdge edge = new DotEdge(node.GetEndId(),node.GetNextId()); DotDefinition.Add(edge); } public void CreateEdgeToFirstChildren() { DotEdge edge = new DotEdge(node.Id,node.Children[0].Id); DotDefinition.Add(edge); } public void CreateEndNode() { DotNode endnode = new DotNode(node.GetEndId()); endnode.Shape = DotNodeShape.Diamond; DotDefinition.Add(endnode); } } }
TheStack
b44e2b3fddd48b2f1078f22ef4cb73aa30ca5f37
C#code:C#
{"size": 27295, "ext": "cs", "max_stars_repo_path": "sdk/test/Services/MigrationHub/UnitTests/Generated/Marshalling/MigrationHubMarshallingTests.cs", "max_stars_repo_name": "a-leontiev/aws-sdk-net", "max_stars_repo_stars_event_min_datetime": "2020-02-09T03:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-09T03:13:21.000Z", "max_issues_repo_path": "sdk/test/Services/MigrationHub/UnitTests/Generated/Marshalling/MigrationHubMarshallingTests.cs", "max_issues_repo_name": "lukeenterprise/aws-sdk-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/test/Services/MigrationHub/UnitTests/Generated/Marshalling/MigrationHubMarshallingTests.cs", "max_forks_repo_name": "lukeenterprise/aws-sdk-net", "max_forks_repo_forks_event_min_datetime": "2020-07-09T19:28:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T19:28:23.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 51.0186915888, "max_line_length": 161, "alphanum_fraction": 0.6568235941}
/* * 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 AWSMigrationHub-2017-05-31.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.MigrationHub; using Amazon.MigrationHub.Model; using Amazon.MigrationHub.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class MigrationHubMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("AWSMigrationHub"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void AssociateCreatedArtifactMarshallTest() { var request = InstantiateClassGenerator.Execute<AssociateCreatedArtifactRequest>(); var marshaller = new AssociateCreatedArtifactRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AssociateCreatedArtifactRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AssociateCreatedArtifact").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AssociateCreatedArtifactResponseUnmarshaller.Instance.Unmarshall(context) as AssociateCreatedArtifactResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void AssociateDiscoveredResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<AssociateDiscoveredResourceRequest>(); var marshaller = new AssociateDiscoveredResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<AssociateDiscoveredResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("AssociateDiscoveredResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = AssociateDiscoveredResourceResponseUnmarshaller.Instance.Unmarshall(context) as AssociateDiscoveredResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void CreateProgressUpdateStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateProgressUpdateStreamRequest>(); var marshaller = new CreateProgressUpdateStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateProgressUpdateStreamRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateProgressUpdateStream").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateProgressUpdateStreamResponseUnmarshaller.Instance.Unmarshall(context) as CreateProgressUpdateStreamResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void DeleteProgressUpdateStreamMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteProgressUpdateStreamRequest>(); var marshaller = new DeleteProgressUpdateStreamRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteProgressUpdateStreamRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteProgressUpdateStream").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteProgressUpdateStreamResponseUnmarshaller.Instance.Unmarshall(context) as DeleteProgressUpdateStreamResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void DescribeApplicationStateMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeApplicationStateRequest>(); var marshaller = new DescribeApplicationStateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeApplicationStateRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeApplicationState").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeApplicationStateResponseUnmarshaller.Instance.Unmarshall(context) as DescribeApplicationStateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void DescribeMigrationTaskMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeMigrationTaskRequest>(); var marshaller = new DescribeMigrationTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeMigrationTaskRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeMigrationTask").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeMigrationTaskResponseUnmarshaller.Instance.Unmarshall(context) as DescribeMigrationTaskResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void DisassociateCreatedArtifactMarshallTest() { var request = InstantiateClassGenerator.Execute<DisassociateCreatedArtifactRequest>(); var marshaller = new DisassociateCreatedArtifactRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DisassociateCreatedArtifactRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DisassociateCreatedArtifact").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DisassociateCreatedArtifactResponseUnmarshaller.Instance.Unmarshall(context) as DisassociateCreatedArtifactResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void DisassociateDiscoveredResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<DisassociateDiscoveredResourceRequest>(); var marshaller = new DisassociateDiscoveredResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DisassociateDiscoveredResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DisassociateDiscoveredResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DisassociateDiscoveredResourceResponseUnmarshaller.Instance.Unmarshall(context) as DisassociateDiscoveredResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ImportMigrationTaskMarshallTest() { var request = InstantiateClassGenerator.Execute<ImportMigrationTaskRequest>(); var marshaller = new ImportMigrationTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ImportMigrationTaskRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ImportMigrationTask").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ImportMigrationTaskResponseUnmarshaller.Instance.Unmarshall(context) as ImportMigrationTaskResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ListApplicationStatesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListApplicationStatesRequest>(); var marshaller = new ListApplicationStatesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListApplicationStatesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListApplicationStates").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListApplicationStatesResponseUnmarshaller.Instance.Unmarshall(context) as ListApplicationStatesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ListCreatedArtifactsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListCreatedArtifactsRequest>(); var marshaller = new ListCreatedArtifactsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListCreatedArtifactsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListCreatedArtifacts").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListCreatedArtifactsResponseUnmarshaller.Instance.Unmarshall(context) as ListCreatedArtifactsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ListDiscoveredResourcesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListDiscoveredResourcesRequest>(); var marshaller = new ListDiscoveredResourcesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListDiscoveredResourcesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListDiscoveredResources").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListDiscoveredResourcesResponseUnmarshaller.Instance.Unmarshall(context) as ListDiscoveredResourcesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ListMigrationTasksMarshallTest() { var request = InstantiateClassGenerator.Execute<ListMigrationTasksRequest>(); var marshaller = new ListMigrationTasksRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListMigrationTasksRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListMigrationTasks").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListMigrationTasksResponseUnmarshaller.Instance.Unmarshall(context) as ListMigrationTasksResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void ListProgressUpdateStreamsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListProgressUpdateStreamsRequest>(); var marshaller = new ListProgressUpdateStreamsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListProgressUpdateStreamsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListProgressUpdateStreams").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListProgressUpdateStreamsResponseUnmarshaller.Instance.Unmarshall(context) as ListProgressUpdateStreamsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void NotifyApplicationStateMarshallTest() { var request = InstantiateClassGenerator.Execute<NotifyApplicationStateRequest>(); var marshaller = new NotifyApplicationStateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<NotifyApplicationStateRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("NotifyApplicationState").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = NotifyApplicationStateResponseUnmarshaller.Instance.Unmarshall(context) as NotifyApplicationStateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void NotifyMigrationTaskStateMarshallTest() { var request = InstantiateClassGenerator.Execute<NotifyMigrationTaskStateRequest>(); var marshaller = new NotifyMigrationTaskStateRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<NotifyMigrationTaskStateRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("NotifyMigrationTaskState").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = NotifyMigrationTaskStateResponseUnmarshaller.Instance.Unmarshall(context) as NotifyMigrationTaskStateResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("MigrationHub")] public void PutResourceAttributesMarshallTest() { var request = InstantiateClassGenerator.Execute<PutResourceAttributesRequest>(); var marshaller = new PutResourceAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<PutResourceAttributesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("PutResourceAttributes").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = PutResourceAttributesResponseUnmarshaller.Instance.Unmarshall(context) as PutResourceAttributesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
TheStack
b44e2c772c6b5a691607bce9dec2e5e3b16720c5
C#code:C#
{"size": 2062, "ext": "cs", "max_stars_repo_path": "src/Command.Bot.Core.Tests/Runner/BatchFileTests.cs", "max_stars_repo_name": "rolfwessels/Command.Bot", "max_stars_repo_stars_event_min_datetime": "2016-01-20T07:36:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T21:25:37.000Z", "max_issues_repo_path": "src/Command.Bot.Core.Tests/Runner/BatchFileTests.cs", "max_issues_repo_name": "rolfwessels/Command.Bot", "max_issues_repo_issues_event_min_datetime": "2017-07-07T08:25:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T18:49:06.000Z", "max_forks_repo_path": "src/Command.Bot.Core.Tests/Runner/BatchFileTests.cs", "max_forks_repo_name": "rolfwessels/Command.Bot", "max_forks_repo_forks_event_min_datetime": "2016-03-29T15:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-28T05:02:54.000Z"}
{"max_stars_count": 11.0, "max_issues_count": 17.0, "max_forks_count": 9.0, "avg_line_length": 24.843373494, "max_line_length": 92, "alphanum_fraction": 0.5252182347}
using System.Reflection; using Command.Bot.Shared.Components.Runner; using FluentAssertions; using Serilog; using NUnit.Framework; namespace Command.Bot.Core.Tests.Runner { [TestFixture] [Category("windows-only")] public class BatchFileTests : TestsBase { private BatchFile _batFile; #region Setup/Teardown private void Setup() { _batFile = new BatchFile(); RiderFixForCurrentPathIssue(); } #endregion [Test] public void Constructor_WhenCalled_ShouldNotBeNull() { // arrange Setup(); // assert _batFile.Should().NotBeNull(); } [Test] public void Extension_WhenCalled_ShouldReturnPs1() { // arrange Setup(); // action var extension = _batFile.Extension; // assert extension.Should().Be(".bat"); } [Test] public void GetRunner_GivenFileName_ShouldReturnRunner() { // arrange Setup(); var fakeContext = new FakeContext(); var fileRunner = _batFile.GetRunner(@"Samples\batExample.bat"); // action fileRunner.Execute(fakeContext); // assert fakeContext.Response.Should().Contain("INFO:i am a bat file"); fakeContext.Response.Should().Contain("INFO:hello"); } [Test] public void GetRunner_GivenArgument_ShouldPassTheArgument() { // arrange Setup(); var fakeContext = new FakeContext() { Text = "batExample.bat --test" }; var fileRunner = _batFile.GetRunner(@"Samples\batExample.bat"); // action fileRunner.Execute(fakeContext); // assert fakeContext.Response.Should().Contain("INFO:Your first argument was '--test'"); } } }
TheStack
b451d4e9d6c62fbb4829a7add89a72da30e2e673
C#code:C#
{"size": 1721, "ext": "cs", "max_stars_repo_path": "Assets/UniGLTF/Editor/Animation/AnimationValidator.cs", "max_stars_repo_name": "arimas88/UniVRM", "max_stars_repo_stars_event_min_datetime": "2019-04-24T01:11:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:09:04.000Z", "max_issues_repo_path": "Assets/UniGLTF/Editor/Animation/AnimationValidator.cs", "max_issues_repo_name": "arimas88/UniVRM", "max_issues_repo_issues_event_min_datetime": "2019-04-24T06:38:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T04:19:57.000Z", "max_forks_repo_path": "Assets/UniGLTF/Editor/Animation/AnimationValidator.cs", "max_forks_repo_name": "miku8323/UnityGames", "max_forks_repo_forks_event_min_datetime": "2019-04-23T19:08:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:40:33.000Z"}
{"max_stars_count": 1128.0, "max_issues_count": 688.0, "max_forks_count": 232.0, "avg_line_length": 30.7321428571, "max_line_length": 101, "alphanum_fraction": 0.5345729227}
using System.Collections.Generic; using System.Linq; using UniGLTF.M17N; using UnityEditor; using UnityEngine; namespace UniGLTF.Animation { public static class AnimationValidator { private enum ExporterValidatorMessages { [LangMsg(Languages.ja, "ExportRootをanimateすることはできません")] [LangMsg(Languages.en, "ExportRoot cannot be animated")] ROOT_ANIMATED, } public static IEnumerable<Validation> Validate(GameObject root) { if (root == null) { yield break; } var animationClips = new List<AnimationClip>(); var animator = root.GetComponent<Animator>(); var animation = root.GetComponent<UnityEngine.Animation>(); if (animator != null) { animationClips = AnimationExporter.GetAnimationClips(animator); } else if (animation != null) { animationClips = AnimationExporter.GetAnimationClips(animation); } if (!animationClips.Any()) { yield break; } foreach (var animationClip in animationClips) { foreach (var editorCurveBinding in AnimationUtility.GetCurveBindings(animationClip)) { // is root included in animation? if (string.IsNullOrEmpty(editorCurveBinding.path)) { yield return Validation.Error(ExporterValidatorMessages.ROOT_ANIMATED.Msg()); yield break; } } } } } }
TheStack
b453b5e1cbe0c2134e4a4c3de167579956aae0f0
C#code:C#
{"size": 6395, "ext": "cs", "max_stars_repo_path": "Fluorite.Transport/Direct/PipelinedStream.cs", "max_stars_repo_name": "kekyo/Fluorite", "max_stars_repo_stars_event_min_datetime": "2021-09-08T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T00:44:01.000Z", "max_issues_repo_path": "Fluorite.Transport/Direct/PipelinedStream.cs", "max_issues_repo_name": "kekyo/Fluorite", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Fluorite.Transport/Direct/PipelinedStream.cs", "max_forks_repo_name": "kekyo/Fluorite", "max_forks_repo_forks_event_min_datetime": "2022-03-22T09:31:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:31:19.000Z"}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 31.6584158416, "max_line_length": 106, "alphanum_fraction": 0.5261923378}
//////////////////////////////////////////////////////////////////////////// // // Fluorite - Simplest and fully-customizable RPC standalone infrastructure. // Copyright (c) 2021 Kouji Matsui (@kozy_kekyo, @kekyo2) // // 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 Fluorite.Internal; using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Fluorite.Direct { internal struct PipelinedStreamPair { public readonly Stream ToWrite; public readonly Stream FromRead; internal PipelinedStreamPair(Stream toWrite, Stream fromRead) { this.ToWrite = toWrite; this.FromRead = fromRead; } } internal static class PipelinedStream { private sealed class WriterStream : Stream { private readonly StreamBridge bridge; public WriterStream(StreamBridge bridge) => this.bridge = bridge; public override void Flush() { } public override bool CanWrite => true; protected override void Dispose(bool disposing) { if (disposing) { this.bridge.Finished(); } base.Dispose(disposing); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { token.ThrowIfCancellationRequested(); var streamData = new StreamData(buffer, offset, count, token); this.bridge.Enqueue(streamData); return streamData.Task; } public override void Write(byte[] buffer, int offset, int count) => this.WriteAsync(buffer, offset, count, default). ConfigureAwait(false). GetAwaiter(). GetResult(); #region Unused public override bool CanSeek => false; public override bool CanRead => false; public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); public override void SetLength(long value) => throw new NotImplementedException(); #endregion } private sealed class ReaderStream : Stream { private readonly StreamBridge bridge; public ReaderStream(StreamBridge bridge) => this.bridge = bridge; public override void Flush() { } public override bool CanRead => true; public override async Task<int> ReadAsync( byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var position = offset; var remains = count; while (remains >= 1) { var streamData = await this.bridge.PeekAsync(cancellationToken). ConfigureAwait(false); if (streamData == null) { this.bridge.TryDequeue(out var _); break; } var data = streamData.GetData(); var csize = Math.Min(remains, data.Count); Buffer.BlockCopy(data.Array!, data.Offset, buffer, position, csize); position += csize; remains -= csize; streamData.Forward(csize); if (data.Count <= csize) { streamData.SetCompleted(); this.bridge.TryDequeue(out var _); } } return count - remains; } public override int Read(byte[] buffer, int offset, int count) => this.ReadAsync(buffer, offset, count, default). ConfigureAwait(false). GetAwaiter(). GetResult(); #region Unused public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException(); public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); public override void SetLength(long value) => throw new NotImplementedException(); #endregion } public static PipelinedStreamPair Create() { var bridge = new StreamBridge(); var toWrite = new WriterStream(bridge); var fromRead = new ReaderStream(bridge); return new PipelinedStreamPair(toWrite, fromRead); } } }
TheStack
b454308c44d6ea03007dafea6be2db53e49fcd58
C#code:C#
{"size": 115, "ext": "cs", "max_stars_repo_path": "ClubPenguin.UI/DraggableButtonType.cs", "max_stars_repo_name": "smdx24/CPI-Source-Code", "max_stars_repo_stars_event_min_datetime": "2019-06-04T19:49:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:39:41.000Z", "max_issues_repo_path": "ClubPenguin.UI/DraggableButtonType.cs", "max_issues_repo_name": "smdx24/CPI-Source-Code", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ClubPenguin.UI/DraggableButtonType.cs", "max_forks_repo_name": "smdx24/CPI-Source-Code", "max_forks_repo_forks_event_min_datetime": "2020-05-05T04:06:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T21:12:34.000Z"}
{"max_stars_count": 8.0, "max_issues_count": null, "max_forks_count": 5.0, "avg_line_length": 10.4545454545, "max_line_length": 31, "alphanum_fraction": 0.7565217391}
// DraggableButtonType public enum DraggableButtonType { INVENTORY, OUTFIT, TEMPLATE, FABRIC, DECAL, IGLOO }
TheStack
b45513b076c60bc811d97919d45e141f861f49c5
C#code:C#
{"size": 2160, "ext": "cs", "max_stars_repo_path": "src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs", "max_stars_repo_name": "pyracanda/runtime", "max_stars_repo_stars_event_min_datetime": "2019-11-25T23:26:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:19:41.000Z", "max_issues_repo_path": "src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs", "max_issues_repo_name": "pyracanda/runtime", "max_issues_repo_issues_event_min_datetime": "2019-11-25T23:30:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:58:30.000Z", "max_forks_repo_path": "src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs", "max_forks_repo_name": "pyracanda/runtime", "max_forks_repo_forks_event_min_datetime": "2019-11-25T23:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:52:28.000Z"}
{"max_stars_count": 9402.0, "max_issues_count": 37522.0, "max_forks_count": 3629.0, "avg_line_length": 37.8947368421, "max_line_length": 147, "alphanum_fraction": 0.6171296296}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Diagnostics { /// <devdoc> /// A process module component represents a DLL or EXE loaded into /// a particular process. Using this component, you can determine /// information about the module. /// </devdoc> [Designer("System.Diagnostics.Design.ProcessModuleDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public class ProcessModule : Component { private FileVersionInfo? _fileVersionInfo; internal ProcessModule() { } /// <devdoc> /// Returns the name of the Module. /// </devdoc> public string? ModuleName { get; internal set; } /// <devdoc> /// Returns the full file path for the location of the module. /// </devdoc> public string? FileName { get; internal set; } /// <devdoc> /// Returns the memory address that the module was loaded at. /// </devdoc> public IntPtr BaseAddress { get; internal set; } /// <devdoc> /// Returns the amount of memory required to load the module. This does /// not include any additional memory allocations made by the module once /// it is running; it only includes the size of the static code and data /// in the module file. /// </devdoc> public int ModuleMemorySize { get; internal set; } /// <devdoc> /// Returns the memory address for function that runs when the module is /// loaded and run. /// </devdoc> public IntPtr EntryPointAddress { get; internal set; } /// <devdoc> /// Returns version information about the module. /// </devdoc> public FileVersionInfo FileVersionInfo => _fileVersionInfo ?? (_fileVersionInfo = FileVersionInfo.GetVersionInfo(FileName!)); public override string ToString() => $"{base.ToString()} ({ModuleName})"; } }
TheStack
b456fe4526699e10c2d5c0ab995736f47ff8e2ba
C#code:C#
{"size": 2871, "ext": "cs", "max_stars_repo_path": "src/TM.Data.Pluralsight/Models/PluralsightCourse.cs", "max_stars_repo_name": "ssh-git/training-manager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TM.Data.Pluralsight/Models/PluralsightCourse.cs", "max_issues_repo_name": "ssh-git/training-manager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TM.Data.Pluralsight/Models/PluralsightCourse.cs", "max_forks_repo_name": "ssh-git/training-manager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.7972972973, "max_line_length": 129, "alphanum_fraction": 0.5952629746}
using System; using System.Collections.Generic; using TM.Shared; using TM.Shared.Parse; namespace TM.Data.Pluralsight { public class PluralsightCourse : ICourseParseModel { public int Id { get; set; } public string Title { get; set; } public string SiteUrl { get; set; } public string UrlName { get; set; } public string Description { get; set; } public bool HasClosedCaptions { get; set; } public CourseLevel Level { get; set; } public CourseRating Rating { get; set; } public TimeSpan Duration { get; set; } public DateTime ReleaseDate { get; set; } public List<PluralsightCourseAuthor> CourseAuthors { get; set; } public PluralsightCategory Category { get; set; } #region Equality Comparers private sealed class PropertiesEqualityComparer : IEqualityComparer<PluralsightCourse> { public bool Equals(PluralsightCourse x, PluralsightCourse y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; return string.Equals(x.Title, y.Title) && string.Equals(x.SiteUrl, y.SiteUrl) && string.Equals(x.UrlName, y.UrlName) && string.Equals(x.Description, y.Description) && x.HasClosedCaptions == y.HasClosedCaptions && x.Level == y.Level && Equals(x.Rating, y.Rating) && x.Duration.Equals(y.Duration) && x.ReleaseDate.Equals(y.ReleaseDate); } public int GetHashCode(PluralsightCourse obj) { unchecked { var hashCode = (obj.Title != null ? obj.Title.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.SiteUrl != null ? obj.SiteUrl.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.UrlName != null ? obj.UrlName.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.Description != null ? obj.Description.GetHashCode() : 0); hashCode = (hashCode * 397) ^ obj.HasClosedCaptions.GetHashCode(); hashCode = (hashCode * 397) ^ (int)obj.Level; hashCode = (hashCode * 397) ^ (obj.Rating != null ? obj.Rating.GetHashCode() : 0); hashCode = (hashCode * 397) ^ obj.Duration.GetHashCode(); hashCode = (hashCode * 397) ^ obj.ReleaseDate.GetHashCode(); return hashCode; } } } private static readonly IEqualityComparer<PluralsightCourse> PropertiesComparerInstance = new PropertiesEqualityComparer(); public static IEqualityComparer<PluralsightCourse> PropertiesComparer { get { return PropertiesComparerInstance; } } #endregion } }
TheStack
b45789a241b6b641639b2e1aeb822b10987b736e
C#code:C#
{"size": 1656, "ext": "cs", "max_stars_repo_path": "Todo-App-Api/Controllers/WeatherController.cs", "max_stars_repo_name": "edwinsoftwaredev/ToDoApp", "max_stars_repo_stars_event_min_datetime": "2021-05-11T05:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T05:58:11.000Z", "max_issues_repo_path": "Todo-App-Api/Controllers/WeatherController.cs", "max_issues_repo_name": "edwinsoftwaredev/ToDoApp", "max_issues_repo_issues_event_min_datetime": "2022-02-13T21:00:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T10:43:29.000Z", "max_forks_repo_path": "Todo-App-Api/Controllers/WeatherController.cs", "max_forks_repo_name": "edwinsoftwaredev/ToDoApp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 4.0, "max_forks_count": null, "avg_line_length": 33.7959183673, "max_line_length": 82, "alphanum_fraction": 0.6262077295}
using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace Todo_App_Api.Controllers { [ApiController] [Route("api/[controller]")] [Authorize(Policy = "TodoAppApiUser")] public class WeatherController : ControllerBase { readonly IHttpClientFactory _httpClientFactory; readonly IConfiguration _configuration; readonly ILogger<WeatherController> _logger; public WeatherController( IHttpClientFactory httpClientFactory, IConfiguration configuration, ILogger<WeatherController> logger ) { _httpClientFactory = httpClientFactory; _configuration = configuration; _logger = logger; } [HttpGet] public async Task<ActionResult<object>> GetWeather(string lat, string lon) { var apiKey = _configuration["WeatherApi_Key"]; var url = "https://api.openweathermap.org/data/2.5/weather?" + $"lat={lat}&" + $"lon={lon}&" + "units=imperial&" + $"appid={apiKey}"; using var httpClient = _httpClientFactory.CreateClient(); using var result = await httpClient.GetAsync(url); result.EnsureSuccessStatusCode(); var resultContent = await result.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(resultContent); } } }
TheStack
b457fdb5b952746fbfdc4ac00c23055c1b909a52
C#code:C#
{"size": 2722, "ext": "cshtml", "max_stars_repo_path": "src/Sir.HttpServer/Views/Crawl/Index.cshtml", "max_stars_repo_name": "didyougogo/commoncrawlcrawler", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Sir.HttpServer/Views/Crawl/Index.cshtml", "max_issues_repo_name": "didyougogo/commoncrawlcrawler", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sir.HttpServer/Views/Crawl/Index.cshtml", "max_forks_repo_name": "didyougogo/commoncrawlcrawler", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 46.1355932203, "max_line_length": 138, "alphanum_fraction": 0.5128581925}
@{ Layout = "~/Views/_Layout.cshtml"; } @{ var searchLink = $"{Context.Request.Path.Value.ToLower().Replace("/crawl", "/search")}{Context.Request.QueryString}"; var collections = ViewBag.Collection ?? Context.Request.Query["collection"].ToArray(); var q = (ViewBag.Q ?? Context.Request.Query["q"]).ToString(); var fields = (ViewBag.Field ?? Context.Request.Query["field"]).ToString(); var job = (string)ViewBag.Job??"CCC"; ViewBag.Title = $"Enrich - {q} - Crawl Crawler"; } <form action="/crawl/@Context.Request.QueryString" method="post"> <div class="blog-wrapper"> <a href="@searchLink">&#8592; Back to result</a> <h1>Enrich search result</h1> <p> You may enrich this search result with even more text data from Common Crawl or the WWW so that the next time you perform this query you'll get even more relevant hits. </p> @if (ViewBag.JobValidationError != null) { <div class="validation-error">@ViewBag.JobValidationError</div> } <p> <label> <input type="radio" name="job" value="CCC" @Html.Raw((job == "CCC") ? "checked" : "") /> Fetch and index web content from <strong>Common Crawl</strong>. </label> </p> <p> <label> <input type="radio" disabled="disabled" name="job" value="wc" @Html.Raw((job == "WC") ? "checked" : "") /> Fetch and index up-to-date web content from <strong>WWW</strong> (coming soon). </label> </p> <p> <label> <input type="radio" disabled="disabled" name="job" value="rwc" @Html.Raw((job == "RWC") ? "checked" : "") /> Fetch and index up-to-date web content from <strong>WWW, recurringly, at a very reasonable fee</strong> (coming soon). </label> </p> <p><input type="submit" /></p> <input type="hidden" id="q" value="@q" /> @foreach (var field in fields) { <input type="hidden" id="field" value="@field" /> } @foreach (var collection in collections) { <input type="hidden" id="collection" value="@collection" /> } @foreach (var field in Context.Request.Query["select"].ToArray()) { <input type="hidden" id="select" value="@field" /> } <input type="hidden" name="crawlid" id="crawlid" value="@ViewBag.CrawlId" /> </div> </form>
TheStack
b45888c88ba769b31bad62061e3c1d99f3e8137c
C#code:C#
{"size": 664, "ext": "cs", "max_stars_repo_path": "AzureSkies/AzureSkies/Models/FlightInfo.cs", "max_stars_repo_name": "SorviusN/AzureSkies", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AzureSkies/AzureSkies/Models/FlightInfo.cs", "max_issues_repo_name": "SorviusN/AzureSkies", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AzureSkies/AzureSkies/Models/FlightInfo.cs", "max_forks_repo_name": "SorviusN/AzureSkies", "max_forks_repo_forks_event_min_datetime": "2021-08-06T21:26:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T21:26:37.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 28.8695652174, "max_line_length": 52, "alphanum_fraction": 0.6506024096}
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AzureSkies.Models { public class FlightInfo { [Required] public int Id { get; set; } public string FlightDate { get; set; } public string FlightStatus { get; set; } public string DepartureAirport { get; set; } public string ArrivalAirport { get; set; } public string AirlineName { get; set; } public string FlightIcao { get; set; } public string FlightNumber { get; set; } public string PhoneNumbers { get; set; } } }
TheStack
b45b2d34923cccd46e2b6e6c959543af692796cf
C#code:C#
{"size": 620, "ext": "cs", "max_stars_repo_path": "Shared/Database/DatabaseContext.cs", "max_stars_repo_name": "Auros/TournamentAssistant", "max_stars_repo_stars_event_min_datetime": "2019-09-21T17:56:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T13:24:03.000Z", "max_issues_repo_path": "Shared/Database/DatabaseContext.cs", "max_issues_repo_name": "Auros/TournamentAssistant", "max_issues_repo_issues_event_min_datetime": "2021-01-23T19:57:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T23:39:28.000Z", "max_forks_repo_path": "Shared/Database/DatabaseContext.cs", "max_forks_repo_name": "Auros/TournamentAssistant", "max_forks_repo_forks_event_min_datetime": "2019-10-02T23:29:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T10:58:15.000Z"}
{"max_stars_count": 21.0, "max_issues_count": 10.0, "max_forks_count": 26.0, "avg_line_length": 25.8333333333, "max_line_length": 113, "alphanum_fraction": 0.6370967742}
using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; namespace TournamentAssistantShared.Database { public class DatabaseContext : DbContext { private string location; public DatabaseContext(string location) : base() { this.location = location; } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlite(new SqliteConnection() { ConnectionString = new SqliteConnectionStringBuilder() { DataSource = location }.ConnectionString }); } } }
TheStack
b45b5938242e7367ef9bfc150caaf126463d8ada
C#code:C#
{"size": 943, "ext": "cs", "max_stars_repo_path": "core/src/Backrole.Core.Abstractions/IServiceInjector.cs", "max_stars_repo_name": "neurnn/backrole", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/src/Backrole.Core.Abstractions/IServiceInjector.cs", "max_issues_repo_name": "neurnn/backrole", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/src/Backrole.Core.Abstractions/IServiceInjector.cs", "max_forks_repo_name": "neurnn/backrole", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.4333333333, "max_line_length": 84, "alphanum_fraction": 0.5927889714}
using System; using System.Reflection; namespace Backrole.Core.Abstractions { /// <summary> /// Creates an instance of the type or invokes a method of the target instance /// with the dependency injection. /// </summary> public interface IServiceInjector { /// <summary> /// Instantiate an instance with appending parameters. /// </summary> /// <param name="InstanceType"></param> /// <param name="Parameters"></param> /// <returns></returns> object Create(Type InstanceType, params object[] Parameters); /// <summary> /// Invoke a method with appending parameters. /// </summary> /// <param name="Method"></param> /// <param name="Target"></param> /// <param name="Parameters"></param> /// <returns></returns> object Invoke(MethodInfo Method, object Target, params object[] Parameters); } }
TheStack
b45c441dffa8126cbeeb4117e7a5748fd5d04252
C#code:C#
{"size": 4901, "ext": "cs", "max_stars_repo_path": "UW.ClassroomPresenter/Viewer/FilmStrips/LinkedSplitter.cs", "max_stars_repo_name": "Nishant163/CP3", "max_stars_repo_stars_event_min_datetime": "2018-04-02T23:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T21:25:10.000Z", "max_issues_repo_path": "UW.ClassroomPresenter/Viewer/FilmStrips/LinkedSplitter.cs", "max_issues_repo_name": "Nishant163/CP3", "max_issues_repo_issues_event_min_datetime": "2018-06-27T20:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T20:13:50.000Z", "max_forks_repo_path": "UW.ClassroomPresenter/Viewer/FilmStrips/LinkedSplitter.cs", "max_forks_repo_name": "Nishant163/CP3", "max_forks_repo_forks_event_min_datetime": "2017-09-24T19:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T05:09:00.000Z"}
{"max_stars_count": 16.0, "max_issues_count": 1.0, "max_forks_count": 15.0, "avg_line_length": 43.7589285714, "max_line_length": 137, "alphanum_fraction": 0.6086512957}
// $Id: LinkedSplitter.cs 2233 2013-09-27 22:17:28Z fred $ using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Windows.Forms; using System.Runtime.InteropServices; using UW.ClassroomPresenter.Model; using UW.ClassroomPresenter.Model.Presentation; namespace UW.ClassroomPresenter.Viewer.FilmStrips { /// <summary> /// A utility class that keeps its <see cref="Dock"/> property in sync /// with the associated <see cref="FilmStrip"/>. /// </summary> internal class LinkedSplitter : Splitter { private readonly Control m_Linked; private readonly Control m_MainViewer; private bool m_Disposed; public LinkedSplitter(Control linked, Control mainViewer) { this.m_Linked = linked; this.m_MainViewer = mainViewer; // Make the splitter very wide so it's easier to grab with a stylus. this.Name = "LinkedSplitter"; this.Width *= 4; this.MinExtra *= 16; this.MinSize *= 3; this.m_Linked.DockChanged += new EventHandler(this.HandleLinkedDockChanged); this.m_Linked.VisibleChanged += new EventHandler(this.HandleLinkedVisibleChanged); this.m_Linked.ParentChanged += new EventHandler(this.HandleLinkedParentChanged); // Initialize the linked state. this.HandleLinkedDockChanged(this, EventArgs.Empty); this.HandleLinkedVisibleChanged(this, EventArgs.Empty); // Do not bother calling HandleLinkedParentChanged, since this.Parent hasn't set initialized yet. } protected override void Dispose(bool disposing) { if(this.m_Disposed) return; try { if(disposing) { this.m_Linked.DockChanged -= new EventHandler(this.HandleLinkedDockChanged); this.m_Linked.VisibleChanged -= new EventHandler(this.HandleLinkedVisibleChanged); this.m_Linked.ParentChanged -= new EventHandler(this.HandleLinkedParentChanged); } } finally { base.Dispose(disposing); } this.m_Disposed = true; } private void HandleLinkedDockChanged(object sender, EventArgs args) { // Keep the dock in sync with the parent. this.Dock = this.m_Linked.Dock; } private void HandleLinkedVisibleChanged(object sender, EventArgs args) { // Keep the visible state in sync with the parent. this.Visible = this.m_Linked.Visible; } protected override void OnVisibleChanged(EventArgs e) { if(this.Visible) { // If this.Visible and m_Linked.Visible were both false when the parent control was first displayed, // the Z-orders won't be correct anymore. So whenever the control is made visible, we need to // readjust the Z-order so that the splitter is always just "above" m_Linked, and both are above // the main slideviewer. this.UpdateLinkedZOrder(); } base.OnVisibleChanged(e); } private void HandleLinkedParentChanged(object sender, EventArgs args) { this.UpdateLinkedZOrder(); } private void UpdateLinkedZOrder() { if(this.m_Linked.Parent != this.Parent) return; if(this.Parent != null) { //We want the indices of mainViewer, splitter and filmstrip to be in ascending order. //If an index is set to one that is already occupied, the existing control at that //index and above will be shifted up. //GetChildIndex returns -1 if the child control is not found int index = this.Parent.Controls.GetChildIndex(this.m_MainViewer, false); //Set the splitter to be one above main slide viewer, or zero if main slide viewer doesn't exist. this.Parent.Controls.SetChildIndex(this, index + 1); //Set the filmstrip to be one above the splitter. index = this.Parent.Controls.GetChildIndex(this, false); this.Parent.Controls.SetChildIndex(this.m_Linked, index + 1); //int ds = this.Parent.Controls.GetChildIndex(this.m_Linked, false); //int spl = this.Parent.Controls.GetChildIndex(this, false); //int m = this.Parent.Controls.GetChildIndex(this.m_MainViewer, false); //Debug.WriteLine("Post-update: main=" + m.ToString() + "; splitter=" + spl.ToString() + ";deckstrip=" + ds.ToString()); } } } }
TheStack
b45d674d2b139a858f54b6e8e1cc3771b141e2f5
C#code:C#
{"size": 3351, "ext": "cs", "max_stars_repo_path": "EmpowerBusiness/IP_Images.cs", "max_stars_repo_name": "HaloImageEngine/EmpowerClaim-hotfix-1.25.1", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EmpowerBusiness/IP_Images.cs", "max_issues_repo_name": "HaloImageEngine/EmpowerClaim-hotfix-1.25.1", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EmpowerBusiness/IP_Images.cs", "max_forks_repo_name": "HaloImageEngine/EmpowerClaim-hotfix-1.25.1", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 50.0149253731, "max_line_length": 128, "alphanum_fraction": 0.6347358997}
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EmpowerBusiness { using System; using System.Collections.Generic; public partial class IP_Images { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public IP_Images() { this.IP_ImagePhrase = new HashSet<IP_ImagePhrase>(); this.IP_Redaction = new HashSet<IP_Redaction>(); this.IW_VendorImage = new HashSet<IW_VendorImage>(); } public int ImageSysID { get; set; } public System.DateTime SysDate { get; set; } public int StatusID { get; set; } public System.DateTime StatusDate { get; set; } public string PathFileName { get; set; } public string ImageFormat { get; set; } public Nullable<int> CompanyID { get; set; } public Nullable<int> FolderSysID { get; set; } public Nullable<int> NumberOfPages { get; set; } public string SenderInfo { get; set; } public string SenderNumber { get; set; } public string BarcodeString { get; set; } public Nullable<int> LockedBySysID { get; set; } public Nullable<System.DateTime> LockDateTime { get; set; } public Nullable<int> PolicySysID { get; set; } public Nullable<int> ClaimSysID { get; set; } public Nullable<int> ImageTypeSysID { get; set; } public Nullable<int> EmailSysID { get; set; } public Nullable<int> LastUpdatedByID { get; set; } public Nullable<int> AgentID { get; set; } public Nullable<System.DateTime> MetaImageDate { get; set; } public Nullable<int> QuoteID { get; set; } public Nullable<int> MarketingLocationID { get; set; } public bool OCRScanned { get; set; } public string ApiFileId { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<IP_ImagePhrase> IP_ImagePhrase { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<IP_Redaction> IP_Redaction { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<IW_VendorImage> IW_VendorImage { get; set; } public virtual IP_ImageStatus IP_ImageStatus { get; set; } public virtual IW_Company IW_Company { get; set; } public virtual IW_User IW_User { get; set; } public virtual AUT_Policy AUT_Policy { get; set; } public virtual CMS_Claims CMS_Claims { get; set; } public virtual IP_ImageType IP_ImageType { get; set; } public virtual IW_User IW_User1 { get; set; } public virtual AGT_Agent AGT_Agent { get; set; } } }
TheStack
b45dde58ba247e6e7f9c0352f17c96f372743375
C#code:C#
{"size": 4946, "ext": "cs", "max_stars_repo_path": "Code/IPFilter/Core/Win32Api.cs", "max_stars_repo_name": "galeksandrp/ipfilter", "max_stars_repo_stars_event_min_datetime": "2015-01-02T07:15:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T18:45:29.000Z", "max_issues_repo_path": "Code/IPFilter/Core/Win32Api.cs", "max_issues_repo_name": "galeksandrp/ipfilter", "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:58:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T10:01:04.000Z", "max_forks_repo_path": "Code/IPFilter/Core/Win32Api.cs", "max_forks_repo_name": "galeksandrp/ipfilter", "max_forks_repo_forks_event_min_datetime": "2015-09-02T18:14:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T04:51:04.000Z"}
{"max_stars_count": 307.0, "max_issues_count": 79.0, "max_forks_count": 33.0, "avg_line_length": 57.511627907, "max_line_length": 276, "alphanum_fraction": 0.6257581884}
using System; using System.Runtime.InteropServices; namespace IPFilter.Cli { static class Win32Api { const string kernel32ClientBaseApi = "kernel32.dll"; /// <summary> /// Moves an existing file or directory, including its children, with various move options. /// </summary> /// <param name="existingFileName"> /// <p>The current name of the file or directory on the local computer.</p> /// <p>If <paramref name="moveFileFlags"/> specifies <see cref="MoveFileFlags.DelayUntilReboot"/>, /// the file cannot exist on a remote share, because delayed operations are performed /// before the network is available.</p> /// </param> /// <param name="newFileName"> /// <p>The new name of the file or directory on the local computer.</p> /// <p>When moving a file, the destination can be on a different file system or volume. /// If the destination is on another drive, you must set the <see cref="MoveFileFlags.CopyAllowed"/> flag in <paramref name="moveFileFlags"/>.</p> /// <p>When moving a directory, the destination must be on the same drive.</p> /// <p>If <paramref name="moveFileFlags"/> specifies <see cref="MoveFileFlags.DelayUntilReboot"/> and <paramref name="newFileName"/> is <c>null</c>, <see cref="MoveFileEx"/> registers the <paramref name="existingFileName"/> file to be deleted when the system restarts. /// If <paramref name="existingFileName"/> refers to a directory, the system removes the directory at restart only if the directory is empty.</p> /// </param> /// <param name="moveFileFlags">The options flags for the file or directory move. See <see cref="MoveFileFlags"/>.</param> /// <returns> /// <p>If the function succeeds, the return value is nonzero.</p> /// <p>If the function fails, the return value is zero (0). To get extended error information, call <see cref="Marshal.GetLastWin32Error"/>.</p> /// </returns> [DllImport(kernel32ClientBaseApi, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern bool MoveFileEx(string existingFileName, string newFileName, MoveFileFlags moveFileFlags); /// <summary> /// Flags for specifying options to <see cref="MoveFileEx"/>. /// </summary> [Flags] internal enum MoveFileFlags { /// <summary> /// <p>If a file named lpNewFileName exists, the function replaces its contents with the contents of the /// lpExistingFileName file, provided that security requirements regarding access control lists (ACLs) are met. /// For more information, see the Remarks section of this topic.</p> /// <p>This value cannot be used if newFileName or existingFileName names a directory.</p> /// </summary> ReplaceExisting = 0x00000001, /// <summary> /// If the file is to be moved to a different volume, the function simulates the move by using the /// CopyFile and DeleteFile functions. /// <p>This value cannot be used with <see cref="DelayUntilReboot"/>.</p> /// </summary> CopyAllowed = 0x00000002, /// <summary> /// <p>The system does not move the file until the operating system is restarted. /// The system moves the file immediately after AUTOCHK is executed, but before creating any paging files. /// Consequently, this parameter enables the function to delete paging files from previous startups.</p> /// <p>This value can be used only if the process is in the context of a user who belongs to the /// administrators group or the LocalSystem account.</p> /// <p>This value cannot be used with <see cref="CopyAllowed"/>.</p> /// </summary> DelayUntilReboot = 0x00000004, /// <summary> /// <p>The function does not return until the file is actually moved on the disk.</p> /// <p>Setting this value guarantees that a move performed as a copy and delete operation /// is flushed to disk before the function returns. The flush occurs at the end of the copy operation.</p> /// <p>This value has no effect if <see cref="DelayUntilReboot"/> is set.</p> /// </summary> WriteThrough = 0x00000008, /// <summary> /// Reserved for future use. /// </summary> CreateHardlink = 0x00000010, /// <summary> /// The function fails if the source file is a link source, but the file cannot be tracked after the move. /// This situation can occur if the destination is a volume formatted with the FAT file system. /// </summary> FailIfNotTrackable = 0x00000020 } } }
TheStack
b45e0d0c12c41f74be26c2de1cbcbd2dd967724e
C#code:C#
{"size": 7964, "ext": "cs", "max_stars_repo_path": "src/DataBox/DataBox/Common/Cmdlets/GetDataBoxJobCmdlet.cs", "max_stars_repo_name": "nimaller/azure-powershell", "max_stars_repo_stars_event_min_datetime": "2017-08-21T06:53:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T17:19:39.000Z", "max_issues_repo_path": "src/DataBox/DataBox/Common/Cmdlets/GetDataBoxJobCmdlet.cs", "max_issues_repo_name": "nimaller/azure-powershell", "max_issues_repo_issues_event_min_datetime": "2018-06-01T19:27:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-26T22:29:18.000Z", "max_forks_repo_path": "src/DataBox/DataBox/Common/Cmdlets/GetDataBoxJobCmdlet.cs", "max_forks_repo_name": "nimaller/azure-powershell", "max_forks_repo_forks_event_min_datetime": "2020-03-01T07:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T08:12:48.000Z"}
{"max_stars_count": 3.0, "max_issues_count": 4.0, "max_forks_count": 4.0, "avg_line_length": 44.9943502825, "max_line_length": 178, "alphanum_fraction": 0.5040180814}
// ---------------------------------------------------------------------------------- // // Copyright Microsoft 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 Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.DataBox; using Microsoft.Azure.Management.DataBox.Models; using Microsoft.Azure.PowerShell.Cmdlets.DataBox.Models; using Microsoft.Rest.Azure; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.DataBox.Common { [Cmdlet(VerbsCommon.Get, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DataBoxJob", DefaultParameterSetName = ListParameterSet), OutputType(typeof(PSDataBoxJob))] public class GetDataBoxJob : AzureDataBoxCmdletBase { private const string ListParameterSet = "ListParameterSet"; private const string GetByNameParameterSet = "GetByNameParameterSet"; private const string GetByResourceIdParameterSet = "GetByResourceIdParameterSet"; [Parameter(Mandatory = false, ParameterSetName = ListParameterSet)] [Parameter(Mandatory = true, ParameterSetName = GetByNameParameterSet)] [ValidateNotNullOrEmpty] [ResourceGroupCompleter] public string ResourceGroupName { get; set; } [Parameter(Mandatory = true, ParameterSetName = GetByNameParameterSet)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = GetByResourceIdParameterSet)] [ValidateNotNullOrEmpty] public string ResourceId { get; set; } [Parameter(Mandatory = false, ParameterSetName = ListParameterSet )] public SwitchParameter Completed { get; set; } = false; [Parameter(Mandatory = false, ParameterSetName = ListParameterSet)] public SwitchParameter CompletedWithError { get; set; } = false; [Parameter(Mandatory = false, ParameterSetName = ListParameterSet)] public SwitchParameter Cancelled { get; set; } = false; [Parameter(Mandatory = false, ParameterSetName = ListParameterSet)] public SwitchParameter Aborted { get; set; } = false; public override void ExecuteCmdlet() { if (this.ParameterSetName.Equals("GetByResourceIdParameterSet")) { this.ResourceGroupName = ResourceIdHandler.GetResourceGroupName(ResourceId); this.Name = ResourceIdHandler.GetResourceName(ResourceId); } if (!string.IsNullOrEmpty(this.Name)) { List<PSDataBoxJob> result = new List<PSDataBoxJob>(); result.Add(new PSDataBoxJob(JobsOperationsExtensions.Get( this.DataBoxManagementClient.Jobs, this.ResourceGroupName, this.Name, "details"))); WriteObject(result,true); } else if (!string.IsNullOrEmpty(this.ResourceGroupName)) { IPage<JobResource> jobPageList = null; List<JobResource> result = new List<JobResource>(); List<PSDataBoxJob> finalResult = new List<PSDataBoxJob>(); do { // Lists all the jobs available under resource group. if (jobPageList == null) { jobPageList = JobsOperationsExtensions.ListByResourceGroup( this.DataBoxManagementClient.Jobs, this.ResourceGroupName); } else { jobPageList = JobsOperationsExtensions.ListByResourceGroupNext( this.DataBoxManagementClient.Jobs, jobPageList.NextPageLink); } if (Completed || Cancelled || Aborted || CompletedWithError) { foreach (var job in jobPageList) { if ((Completed && job.Status == StageName.Completed) || (Cancelled && job.Status == StageName.Cancelled) || (Aborted && job.Status == StageName.Aborted) || (CompletedWithError && job.Status == StageName.CompletedWithErrors)) { result.Add(job); } } } else { result.AddRange(jobPageList.ToList()); } } while (!(string.IsNullOrEmpty(jobPageList.NextPageLink))); foreach(var job in result) { finalResult.Add(new PSDataBoxJob(job)); } WriteObject(finalResult, true); } else { IPage<JobResource> jobPageList = null; List<JobResource> result = new List<JobResource>(); List<PSDataBoxJob> finalResult = new List<PSDataBoxJob>(); do { // Lists all the jobs available under the subscription. if (jobPageList == null) { jobPageList = JobsOperationsExtensions.List( this.DataBoxManagementClient.Jobs); } else { jobPageList = JobsOperationsExtensions.ListNext( this.DataBoxManagementClient.Jobs, jobPageList.NextPageLink); } if (Completed || Cancelled || Aborted || CompletedWithError) { foreach (var job in jobPageList) { if ((Completed && job.Status == StageName.Completed) || (Cancelled && job.Status == StageName.Cancelled) || (Aborted && job.Status == StageName.Aborted) || (CompletedWithError && job.Status == StageName.CompletedWithErrors)) { result.Add(job); } } } else { result.AddRange(jobPageList.ToList()); } } while (!(string.IsNullOrEmpty(jobPageList.NextPageLink))); foreach (var job in result) { finalResult.Add(new PSDataBoxJob(job)); } WriteObject(finalResult, true); } } } }
TheStack
b45ed30e9c5177046484503d15112161552489d8
C#code:C#
{"size": 11283, "ext": "cs", "max_stars_repo_path": "src/Tizen.NUI.Components/Attributes/TextFieldAttributes.cs", "max_stars_repo_name": "yoowonyoung/TizenFX", "max_stars_repo_stars_event_min_datetime": "2021-05-13T13:42:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:42:39.000Z", "max_issues_repo_path": "src/Tizen.NUI.Components/Attributes/TextFieldAttributes.cs", "max_issues_repo_name": "yoowonyoung/TizenFX", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tizen.NUI.Components/Attributes/TextFieldAttributes.cs", "max_forks_repo_name": "yoowonyoung/TizenFX", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.259375, "max_line_length": 113, "alphanum_fraction": 0.5646547904}
/* * Copyright(c) 2019 Samsung Electronics Co., Ltd. * * 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.ComponentModel; namespace Tizen.NUI.Components { /// <summary> /// TextFieldAttributes is a class which saves TextField's ux data. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public class TextFieldAttributes : ViewAttributes { /// <summary> /// Creates a new instance of a TextField. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public TextFieldAttributes() : base() { } /// <summary> /// Creates a new instance of a TextField with style. /// </summary> /// <param name="attributes">Create TextField by special style defined in UX.</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public TextFieldAttributes(TextFieldAttributes attributes) : base(attributes) { if(null == attributes) { return; } if (null != attributes.Text) { Text = attributes.Text.Clone() as StringSelector; } if (null != attributes.PlaceholderText) { PlaceholderText = attributes.PlaceholderText.Clone() as StringSelector; } if (null != attributes.TranslatablePlaceholderText) { TranslatablePlaceholderText = attributes.TranslatablePlaceholderText.Clone() as StringSelector; } if (null != attributes.HorizontalAlignment) { HorizontalAlignment = attributes.HorizontalAlignment; } if (null != attributes.VerticalAlignment) { VerticalAlignment = attributes.VerticalAlignment; } if (null != attributes.EnableMarkup) { EnableMarkup = attributes.EnableMarkup; } if (null != attributes.TextColor) { TextColor = attributes.TextColor.Clone() as ColorSelector; } if (null != attributes.PlaceholderTextColor) { PlaceholderTextColor = attributes.PlaceholderTextColor.Clone() as ColorSelector; } if (null != attributes.PrimaryCursorColor) { PrimaryCursorColor = attributes.PrimaryCursorColor.Clone() as ColorSelector; } if (null != attributes.SecondaryCursorColor) { SecondaryCursorColor = attributes.SecondaryCursorColor.Clone() as ColorSelector; } if (null != attributes.FontFamily) { FontFamily = attributes.FontFamily; } if (null != attributes.PointSize) { PointSize = attributes.PointSize.Clone() as FloatSelector; } if (null != attributes.EnableCursorBlink) { EnableCursorBlink = attributes.EnableCursorBlink; } if (null != attributes.EnableSelection) { EnableSelection = attributes.EnableSelection; } if (null != attributes.CursorWidth) { CursorWidth = attributes.CursorWidth; } if (null != attributes.EnableEllipsis) { EnableEllipsis = attributes.EnableEllipsis; } } /// <summary> /// Gets or sets text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public StringSelector Text { get; set; } /// <summary> /// Gets or sets place holder text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public StringSelector PlaceholderText { get; set; } /// <summary> /// Gets or sets translatable place holder text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public StringSelector TranslatablePlaceholderText { get; set; } /// <summary> /// Gets or sets horizontal alignment of text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public HorizontalAlignment? HorizontalAlignment { get; set; } /// <summary> /// Gets or sets vertical alignment of text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public VerticalAlignment? VerticalAlignment { get; set; } /// <summary> /// Gets or sets enable mark up. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool? EnableMarkup { get; set; } /// <summary> /// Gets or sets text color. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ColorSelector TextColor { get; set; } /// <summary> /// Gets or sets place holder text color. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ColorSelector PlaceholderTextColor { get; set; } /// <summary> /// Gets or sets primary cursor color. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ColorSelector PrimaryCursorColor { get; set; } /// <summary> /// Gets or sets secondary cursor color. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public ColorSelector SecondaryCursorColor { get; set; } /// <summary> /// Gets or sets font family of text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string FontFamily { get; set; } /// <summary> /// Gets or sets point size of text. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public FloatSelector PointSize { get; set; } /// <summary> /// Gets or sets enable cursor blink. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool? EnableCursorBlink { get; set; } /// <summary> /// Gets or sets enable selection. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool? EnableSelection { get; set; } /// <summary> /// Gets or sets cursor width. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public int? CursorWidth { get; set; } /// <summary> /// Gets or sets if enable ellipsis. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool? EnableEllipsis { get; set; } /// <summary> /// Attributes's clone function. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_5.5 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public override Attributes Clone() { return new TextFieldAttributes(this); } } }
TheStack
b45ff3c76e3bd0a0e11e8e8e978fd0a706454879
C#code:C#
{"size": 681, "ext": "cs", "max_stars_repo_path": "VocaDbModel/DataContracts/Artists/ArchivedArtistVersionContract.cs", "max_stars_repo_name": "cazzar/VocaDbTagger", "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:28:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-31T15:28:45.000Z", "max_issues_repo_path": "VocaDbModel/DataContracts/Artists/ArchivedArtistVersionContract.cs", "max_issues_repo_name": "cazzar/VocaDbTagger", "max_issues_repo_issues_event_min_datetime": "2015-04-01T00:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-19T08:38:23.000Z", "max_forks_repo_path": "VocaDbModel/DataContracts/Artists/ArchivedArtistVersionContract.cs", "max_forks_repo_name": "cazzar/VocaDbTagger", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1.0, "max_issues_count": 5.0, "max_forks_count": null, "avg_line_length": 24.3214285714, "max_line_length": 118, "alphanum_fraction": 0.7885462555}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VocaDb.Model.Domain.Artists; namespace VocaDb.Model.DataContracts.Artists { public class ArchivedArtistVersionContract : ArchivedObjectVersionContract { public ArchivedArtistVersionContract() { } public ArchivedArtistVersionContract(ArchivedArtistVersion archivedVersion) : base(archivedVersion) { ChangedFields = (archivedVersion.Diff != null ? archivedVersion.Diff.ChangedFields : ArtistEditableFields.Nothing); Reason = archivedVersion.Reason; } public ArtistEditableFields ChangedFields { get; set; } public ArtistArchiveReason Reason { get; set; } } }
TheStack
b460eb12326aaa8c0dd181c49c4142a2897a8cea
C#code:C#
{"size": 659, "ext": "cs", "max_stars_repo_path": "Src/Kit.Core45/Extensions/TaskEx.cs", "max_stars_repo_name": "flostr/HockeySDK-Windows", "max_stars_repo_stars_event_min_datetime": "2015-01-30T00:45:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T13:05:57.000Z", "max_issues_repo_path": "Src/Kit.Core45/Extensions/TaskEx.cs", "max_issues_repo_name": "cxulo/HockeySDK-Windows", "max_issues_repo_issues_event_min_datetime": "2015-01-08T12:24:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-19T14:11:48.000Z", "max_forks_repo_path": "Src/Kit.Core45/Extensions/TaskEx.cs", "max_forks_repo_name": "cxulo/HockeySDK-Windows", "max_forks_repo_forks_event_min_datetime": "2015-04-12T17:48:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-17T20:27:22.000Z"}
{"max_stars_count": 102.0, "max_issues_count": 113.0, "max_forks_count": 82.0, "avg_line_length": 24.4074074074, "max_line_length": 65, "alphanum_fraction": 0.5887708649}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.HockeyApp.Extensions { /// <summary> /// TaskEx class to have a consistens interface with .net4.0 /// </summary> internal class TaskEx { /// <summary> /// wrapper for Task.Run() /// </summary> /// <typeparam name="T">result type</typeparam> /// <param name="func">funct to run asyncronously</param> /// <returns></returns> public static async Task<T> Run<T>(Func<T> func) { return await Task.Run<T>(func); } } }
TheStack
b461245ab9c6a9124e92a541d67b0958464e0696
C#code:C#
{"size": 1018, "ext": "cshtml", "max_stars_repo_path": "TPMApi/TPMApi/Views/Shared/_WooForm.cshtml", "max_stars_repo_name": "oeloe100/TriplePro-Migration-API", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TPMApi/TPMApi/Views/Shared/_WooForm.cshtml", "max_issues_repo_name": "oeloe100/TriplePro-Migration-API", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TPMApi/TPMApi/Views/Shared/_WooForm.cshtml", "max_forks_repo_name": "oeloe100/TriplePro-Migration-API", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.7037037037, "max_line_length": 97, "alphanum_fraction": 0.4656188605}
 <div class="woo-logo-container"> <img class="woo-logo" src="~/Images/woologo.png" alt="WooCommerce Logo" width="150px;" /> </div> <div class="row" style="display: grid; margin: 0px 50px;"> <div class="col form-input"> <form class="woo-form" method="post"> <div class="form-name"> Name: <input class="form-control" type="text" name="Name" /><br /> </div> <div class="client-secret"> Key: <input class="form-control" type="password" name="WooClientId" /><br /> </div> <div class="client-id"> Secret: <input class="form-control" type="password" name="WooClientSecret" /><br /> </div> </form> </div> <div class="button-box"> <button type="submit" class="woo-form-authorize">Authorize</button> </div> </div>
TheStack
b4616f8cdf013d4aab7144ca16dece7c006cacf7
C#code:C#
{"size": 5368, "ext": "cs", "max_stars_repo_path": "fieldservice/toa/cx/projects/Oracle.RightNow.Toa.WorkOrderAddIn/EventHandlers/PopulateContactDetailsHandler.cs", "max_stars_repo_name": "CVChrisWilson/Accelerators", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fieldservice/toa/cx/projects/Oracle.RightNow.Toa.WorkOrderAddIn/EventHandlers/PopulateContactDetailsHandler.cs", "max_issues_repo_name": "CVChrisWilson/Accelerators", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fieldservice/toa/cx/projects/Oracle.RightNow.Toa.WorkOrderAddIn/EventHandlers/PopulateContactDetailsHandler.cs", "max_forks_repo_name": "CVChrisWilson/Accelerators", "max_forks_repo_forks_event_min_datetime": "2018-06-27T07:35:58.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-27T07:35:58.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 44.7333333333, "max_line_length": 125, "alphanum_fraction": 0.4843517139}
/* * ******************************************************************************************* * This file is part of the Oracle Service Cloud Accelerator Reference Integration set published * by Oracle Service Cloud under the MIT license (MIT) included in the original distribution. * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. *********************************************************************************************** * Accelerator Package: OSvC + OFSC Reference Integration * link: http://www-content.oracle.com/technetwork/indexes/samplecode/accelerator-osvc-2525361.html * OSvC release: 15.2 (Feb 2015) * OFSC release: 15.2 (Feb 2015) * reference: 150622-000130 * date: Thu Sep 3 23:14:04 PDT 2015 * revision: rnw-15-11-fixes-release-03 * SHA1: $Id: eb41148d6af7e97f2495000ab681b94cb3dcab54 $ * ********************************************************************************************* * File: PopulateContactDetailsHandler.cs * ****************************************************************************************** */ using Oracle.RightNow.Toa.Client.Common; using Oracle.RightNow.Toa.Client.Rightnow; using Oracle.RightNow.Toa.Client.RightNowProxyService; using RightNow.AddIns.AddInViews; using RightNow.AddIns.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Oracle.RightNow.Toa.WorkOrderAddIn.EventHandlers { public class PopulateContactDetailsHandler { /// <summary> /// The current workspace record context. /// </summary> private IRecordContext _recordContext; ICustomObject _workOrderRecord { get; set; } public PopulateContactDetailsHandler(IRecordContext RecordContext) { _recordContext = RecordContext; _workOrderRecord = _recordContext.GetWorkspaceRecord(_recordContext.WorkspaceTypeName) as ICustomObject; } public void PopulateContactDetails() { IContact contactRecord = _recordContext.GetWorkspaceRecord(WorkspaceRecordType.Contact) as IContact; IIncident incidentRecord = _recordContext.GetWorkspaceRecord(WorkspaceRecordType.Incident) as IIncident; IList<IGenericField> fields = _workOrderRecord.GenericFields; foreach (IGenericField field in fields) { switch (field.Name) { case "Contact_Street": if (contactRecord != null && contactRecord.AddrStreet != null) { field.DataValue.Value = contactRecord.AddrStreet; } break; case "Contact_Province_State": if (contactRecord != null && contactRecord.AddrProvID != null) { field.DataValue.Value = contactRecord.AddrProvID; } break; case "Contact_City": if (contactRecord != null && contactRecord.AddrCity != null) { field.DataValue.Value = contactRecord.AddrCity; } break; case "Contact_Postal_Code": if (contactRecord != null && contactRecord.AddrPostalCode != null) { field.DataValue.Value = contactRecord.AddrPostalCode; } break; case "Contact_Email": if (contactRecord != null && contactRecord.EmailAddr != null) { field.DataValue.Value = contactRecord.EmailAddr; } break; case "Contact_Phone": if (contactRecord != null && contactRecord.PhHome != null) { field.DataValue.Value = contactRecord.PhHome; } else if (contactRecord != null && contactRecord.PhOffice != null) { field.DataValue.Value = contactRecord.PhOffice; } break; case "Contact_Mobile_Phone": if (contactRecord != null && contactRecord.PhMobile != null) { field.DataValue.Value = contactRecord.PhMobile; } break; case "Resolution_Due": string[] milestones = RightNowConnectService.GetService().GetResolutionDueFromID(incidentRecord.ID); if(milestones != null && milestones.Count() > 0) { field.DataValue.Value = milestones[0]; } break; } _recordContext.RefreshWorkspace(); } } } }
TheStack
b461bd0061d5b71ba2070a0ba51de0b272d40b0e
C#code:C#
{"size": 3875, "ext": "cs", "max_stars_repo_path": "BetterRide/BetterRideCamera.cs", "max_stars_repo_name": "dredhorse/BetterCameras", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BetterRide/BetterRideCamera.cs", "max_issues_repo_name": "dredhorse/BetterCameras", "max_issues_repo_issues_event_min_datetime": "2016-05-06T16:10:44.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-08T18:42:43.000Z", "max_forks_repo_path": "BetterRide/BetterRideCamera.cs", "max_forks_repo_name": "dredhorse/BetterCameras", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 5.0, "max_forks_count": null, "avg_line_length": 20.3947368421, "max_line_length": 87, "alphanum_fraction": 0.6756129032}
using System; using UnityEngine; using UnityEngine.VR; using System.Collections.Generic; using Parkitect.UI; namespace BetterCameras.BetterRide { public class BetterRideCamera : MonoBehaviour { private GameObject _coasterCam; private GameObject _origCam; private bool _isOnRide; public static BetterRideCamera Instance; private Camera _cam; float _fps; private readonly List<Transform> _seats = new List<Transform>(); private int _seatIndex; public KeyCode RideKey = KeyCode.R; private void Awake() { Instance = this; DontDestroyOnLoad(gameObject); } private void Update() { if (Input.GetKeyUp(RideKey) && !_isOnRide && !UIUtility.isInputFieldFocused()) { GameObject ride = GameObjectUnderMouse(); if (ride != null) { Attraction attr = ride.GetComponentInParent<Attraction>(); if (attr == null) { attr = ride.GetComponentInChildren<Attraction>(); } if (attr != null) { _seats.Clear(); _seatIndex = 0; Utility.recursiveFindTransformsStartingWith("seat", attr.transform, _seats); if (_seats.Count > 0) EnterCoasterCam(_seats[_seatIndex].gameObject); } } } else if (Input.GetKeyUp(RideKey)) { LeaveCoasterCam(); } if (_isOnRide && Input.GetKey(KeyCode.Escape)) { LeaveCoasterCam (); } if (_isOnRide) { if (Math.Abs(Input.GetAxis("Mouse ScrollWheel")) > 0.1) { LeaveCoasterCam(); if (Input.GetAxis("Mouse ScrollWheel") > 0) { if (++_seatIndex == _seats.Count) _seatIndex = 0; } if (Input.GetAxis("Mouse ScrollWheel") < 0) { if (--_seatIndex < 0) _seatIndex = _seats.Count - 1; } EnterCoasterCam(_seats[_seatIndex].gameObject); } AdaptFarClipPaneToFps(); } } private void AdaptFarClipPaneToFps() { _fps = 1.0f / Time.deltaTime; if (_fps < 50) { _cam.farClipPlane = Math.Max(40, _cam.farClipPlane - 0.3f); } if (_fps > 55) { _cam.farClipPlane = Math.Min(120, _cam.farClipPlane + 0.2f); } } private GameObject GameObjectUnderMouse() { GameController.Instance.enableVisibleMouseColliders(); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity)) { GameController.Instance.disableMouseColliders(); return hit.transform.gameObject; } GameController.Instance.disableMouseColliders(); return null; } public void EnterCoasterCam(GameObject onGo) { if (_isOnRide) return; UIWorldOverlayController.Instance.gameObject.SetActive(false); string tag = Camera.main.tag; _origCam = Camera.main.gameObject; _origCam.SetActive(false); _coasterCam = new GameObject(); _coasterCam.tag = tag; _coasterCam.AddComponent<Camera>(); _coasterCam.GetComponent<Camera>().nearClipPlane = 0.05f; _coasterCam.GetComponent<Camera>().farClipPlane = 100f; _coasterCam.GetComponent<Camera>().depthTextureMode = DepthTextureMode.DepthNormals; _coasterCam.AddComponent<AudioListener>(); _coasterCam.transform.parent = onGo.transform; _coasterCam.transform.localPosition = new Vector3(0, 0.35f, 0.1f); _coasterCam.transform.localRotation = Quaternion.identity; _coasterCam.AddComponent<BetterRideMouse>(); _cam = _coasterCam.GetComponent<Camera>(); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; _isOnRide = true; InputTracking.Recenter(); } public void LeaveCoasterCam() { if (!_isOnRide) return; _origCam.SetActive(true); Destroy(_coasterCam); UIWorldOverlayController.Instance.gameObject.SetActive(true); Cursor.lockState = CursorLockMode.None; Cursor.visible = true; _isOnRide = false; } void OnDestroy() { LeaveCoasterCam(); } } }
TheStack
b46298b4101fa41808d70ea4c53abc56ad220e85
C#code:C#
{"size": 543, "ext": "cs", "max_stars_repo_path": "CyberCAT.Core/Enums/Dumped Enums/ETextureCompression.cs", "max_stars_repo_name": "RakhithJK/CyberCAT", "max_stars_repo_stars_event_min_datetime": "2020-12-21T20:43:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T04:13:29.000Z", "max_issues_repo_path": "CyberCAT.Core/Enums/Dumped Enums/ETextureCompression.cs", "max_issues_repo_name": "RakhithJK/CyberCAT", "max_issues_repo_issues_event_min_datetime": "2020-12-23T00:15:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T10:32:06.000Z", "max_forks_repo_path": "CyberCAT.Core/Enums/Dumped Enums/ETextureCompression.cs", "max_forks_repo_name": "RakhithJK/CyberCAT", "max_forks_repo_forks_event_min_datetime": "2020-12-22T21:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T14:48:40.000Z"}
{"max_stars_count": 127.0, "max_issues_count": 26.0, "max_forks_count": 52.0, "avg_line_length": 20.1111111111, "max_line_length": 35, "alphanum_fraction": 0.7108655617}
namespace CyberCAT.Core.DumpedEnums { public enum ETextureCompression { TCM_None = 0, TCM_DXTNoAlpha = 1, TCM_DXTAlpha = 2, TCM_RGBE = 3, TCM_Normalmap = 4, TCM_Normals_DEPRECATED = 5, TCM_Normals = 5, TCM_NormalsHigh_DEPRECATED = 6, TCM_NormalsHigh = 6, TCM_NormalsGloss_DEPRECATED = 7, TCM_NormalsGloss = 7, TCM_TileMap = 8, TCM_DXTAlphaLinear = 9, TCM_QualityR = 10, TCM_QualityRG = 11, TCM_QualityColor = 12, TCM_HalfHDR_Unsigned = 13, TCM_HalfHDR = 13, TCM_HalfHDR_Signed = 14, TCM_Max = 15 } }
TheStack
b462bc0e1ffffbe3eb4656d10c0a99e909032686
C#code:C#
{"size": 641, "ext": "cs", "max_stars_repo_path": "v3.1/Models/DB/Epassenger.cs", "max_stars_repo_name": "LightosLimited/RailML", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "v3.1/Models/DB/Epassenger.cs", "max_issues_repo_name": "LightosLimited/RailML", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "v3.1/Models/DB/Epassenger.cs", "max_forks_repo_name": "LightosLimited/RailML", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.7083333333, "max_line_length": 63, "alphanum_fraction": 0.608424337}
using System; using System.Collections.Generic; namespace Models.DB { public partial class Epassenger { public Epassenger() { Ewagon = new HashSet<Ewagon>(); } public short EpassengerId { get; set; } public long Gangway { get; set; } public short Doors { get; set; } public long Tilting { get; set; } public virtual Edoors DoorsNavigation { get; set; } public virtual Tgangway GangwayNavigation { get; set; } public virtual Ttilting TiltingNavigation { get; set; } public virtual ICollection<Ewagon> Ewagon { get; set; } } }
TheStack
b463db0c4928d42081eafa98c05e38e9947169de
C#code:C#
{"size": 5110, "ext": "cs", "max_stars_repo_path": "cofetarie/RComenziClienti.cs", "max_stars_repo_name": "pir0galol/Sweetshop-v.1", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cofetarie/RComenziClienti.cs", "max_issues_repo_name": "pir0galol/Sweetshop-v.1", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cofetarie/RComenziClienti.cs", "max_forks_repo_name": "pir0galol/Sweetshop-v.1", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 45.2212389381, "max_line_length": 184, "alphanum_fraction": 0.5596868885}
using System; using System.Data; using System.Windows.Forms; using Npgsql; using Microsoft.Reporting.WinForms; namespace cofetarie { public partial class RComenziClienti : MetroFramework.Forms.MetroForm { static string conexiune = @"Server=127.0.0.1;Port=5432;Database=cofetarie;User Id=postgres; Password = postgres;"; NpgsqlConnection conn = new NpgsqlConnection(conexiune); int idcomanda { get; set; } public RComenziClienti() { InitializeComponent(); //Grid restrictii gridComenzi.ReadOnly = true; gridComenzi.AllowUserToAddRows = false; gridComenzi.AllowUserToDeleteRows = false; gridComenzi.AllowUserToResizeColumns = false; gridComenzi.AllowUserToResizeRows = false; gridComenzi.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders); gridComenzi.MultiSelect = false; gridComenzi.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; } private void btnAfisare_Click(object sender, EventArgs e) { string query = @"SELECT cc.comandac_id, c.client_nume, c.oras, c.telefon FROM CLIENTI c JOIN COMENZI_CLIENTI cc ON c.client_id = cc.client_id order by 1"; try { using (conn = new NpgsqlConnection(conexiune)) { conn.Open(); using (NpgsqlCommand comanda = new NpgsqlCommand(query, conn)) { comanda.CommandType = CommandType.Text; comanda.ExecuteNonQuery(); using (DataTable dt = new DataTable()) { using (NpgsqlDataReader reader = comanda.ExecuteReader()) { dt.Load(reader); gridComenzi.Columns[0].DataPropertyName = "comandac_id"; gridComenzi.Columns[1].DataPropertyName = "client_nume"; gridComenzi.Columns[2].DataPropertyName = "oras"; gridComenzi.Columns[3].DataPropertyName = "telefon"; gridComenzi.DataSource = dt; } } } } } catch (Exception ex) { MetroFramework.MetroMessageBox.Show(this, "A aparut o problema:\n" + ex, "Atentie!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void RComenziClienti_Load(object sender, EventArgs e) { } private void btnGenereaza_Click(object sender, EventArgs e) { if (gridComenzi.Rows.Count == 0) return; if (gridComenzi.SelectedRows.Count == 1) { try { idcomanda = int.Parse(gridComenzi.CurrentRow.Cells[0].Value.ToString()); // Instantiem un nou adapter si un nou dataTable din cadrul dataset-ului creat... DataSet_ComenziClientiTableAdapters.ComenziClientiTableAdapter adapter = new DataSet_ComenziClientiTableAdapters.ComenziClientiTableAdapter(); DataSet_ComenziClienti.ComenziClientiDataTable table = new DataSet_ComenziClienti.ComenziClientiDataTable(); adapter.Fill(table, idcomanda); DataSet_ComenziClientiTableAdapters.DetaliiComenziClientiTableAdapter adapter_detalii = new DataSet_ComenziClientiTableAdapters.DetaliiComenziClientiTableAdapter(); DataSet_ComenziClienti.DetaliiComenziClientiDataTable table_detalii = new DataSet_ComenziClienti.DetaliiComenziClientiDataTable(); adapter_detalii.Fill(table_detalii, idcomanda); ReportDataSource source = new ReportDataSource("ComenziClienti", (DataTable)table); ReportDataSource source2 = new ReportDataSource("DetaliiComenziClienti", (DataTable)table_detalii); using (RaportComenziClienti rc = new RaportComenziClienti()) { rc.report1.LocalReport.DataSources.Clear(); rc.report1.LocalReport.DataSources.Add(source); rc.report1.LocalReport.DataSources.Add(source2); rc.report1.LocalReport.Refresh(); rc.report1.RefreshReport(); rc.ShowDialog(); } } catch(Exception ex) { MetroFramework.MetroMessageBox.Show(this, "A aparut o problema:\n" + ex, "Atentie!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } private void btnRenunta_Click(object sender, EventArgs e) { Close(); } } }
TheStack
b46468a23e3dc2ee6743a391f881f924d34d369f
C#code:C#
{"size": 1499, "ext": "cs", "max_stars_repo_path": "08-ProgrammingBasicsExercises/15-ProgrammingBasicsExam-03September2017/02-Scholarship.cs", "max_stars_repo_name": "kavier/Programing-Basic-Csharp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "08-ProgrammingBasicsExercises/15-ProgrammingBasicsExam-03September2017/02-Scholarship.cs", "max_issues_repo_name": "kavier/Programing-Basic-Csharp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08-ProgrammingBasicsExercises/15-ProgrammingBasicsExam-03September2017/02-Scholarship.cs", "max_forks_repo_name": "kavier/Programing-Basic-Csharp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5918367347, "max_line_length": 101, "alphanum_fraction": 0.5290193462}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02.Scholarship { class Program { static void Main(string[] args) { double income = double.Parse(Console.ReadLine()); double grades = double.Parse(Console.ReadLine()); double lowestFare = double.Parse(Console.ReadLine()); double social = lowestFare * 0.35; double excelence = grades * 25; social = Math.Floor(social); excelence = Math.Floor(excelence); if (income <= lowestFare && grades >= 5.5 && social <= excelence) { Console.WriteLine($"You get a scholarship for excellent results {excelence:f0} BGN"); } else if (income <= lowestFare && grades >= 4.5 && social < excelence) { Console.WriteLine($"You get a Social scholarship {social:f0} BGN"); } else if (income <= lowestFare && grades >= 4.5 && social > excelence) { Console.WriteLine($"You get a Social scholarship {social:f0} BGN"); } else if(grades >= 5.5) { Console.WriteLine($"You get a scholarship for excellent results {excelence:f0} BGN"); } else { Console.WriteLine($"You cannot get a scholarship!"); } } } }