content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
namespace Problem2.Vapor_Store
{
class VaporStore
{
static void Main(string[] args)
{
Dictionary<string, decimal> gamesByPrice = new Dictionary<string, decimal>();
FillDictionary(gamesByPrice);
decimal moneyAmount = decimal.Parse(Console.ReadLine());
decimal moneySpent = 0m;
string input = Console.ReadLine();
while (input != "Game Time")
{
//if (moneyAmount == 0m)
//{
// Console.WriteLine("Out of money!");
// return;
//}
if (!gamesByPrice.ContainsKey(input))
{
Console.WriteLine("Not Found");
}
else if (gamesByPrice[input] > moneyAmount)
{
Console.WriteLine("Too Expensive");
}
else
{
decimal gamePrice = gamesByPrice[input];
moneyAmount -= gamePrice;
moneySpent += gamePrice;
Console.WriteLine("Bought " + input);
}
input = Console.ReadLine();
}
Console.WriteLine("Total spent: ${0}. Remaining: ${1}", moneySpent.ToString("0.00"), moneyAmount.ToString("0.00"));
}
static void FillDictionary(Dictionary<string,decimal> gamesByPrice)
{
if (gamesByPrice == null)
{
gamesByPrice = new Dictionary<string, decimal>();
}
gamesByPrice.Add("OutFall 4", 39.99m);
gamesByPrice.Add("CS: OG", 15.99m);
gamesByPrice.Add("Zplinter Zell", 19.99m);
gamesByPrice.Add("Honored 2", 59.99m);
gamesByPrice.Add("RoverWatch", 29.99m);
gamesByPrice.Add("RoverWatch Origins Edition", 39.99m);
}
}
} | 28.985507 | 127 | 0.4845 | [
"MIT"
] | Supbads/Softuni-Education | 07 ProgrammingFundamentals 05.17/03. CSharp-Basics-More-Exercises/Problem2. Vapor Store/VaporStore.cs | 2,002 | C# |
//-----------------------------------------------------------------------
// <copyright file="BlobDataRepository.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using WWTMVC5.Extensions;
using WWTMVC5.Models;
using WWTMVC5.Repositories.Interfaces;
namespace WWTMVC5.Repositories
{
/// <summary>
/// Class representing the Blob Data Repository having methods for adding/retrieving files from
/// Azure blob storage.
/// </summary>
public class BlobDataRepository : IBlobDataRepository
{
private static CloudBlobClient _blobClient;
private CloudStorageAccount _storageAccount;
/// <summary>
/// Initializes a new instance of the <see cref="BlobDataRepository"/> class.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
Justification =
"Code does not grant its callers access to operations or resources that can be used in a destructive manner."
)]
public BlobDataRepository()
{
try
{
_storageAccount = CloudStorageAccount.Parse(ConfigReader<string>.GetSetting("EarthOnlineStorage"));
_blobClient = _storageAccount.CreateCloudBlobClient();
}
catch (Exception) { }// setting not available
}
/// <summary>
/// Gets the container URL.
/// </summary>
public static Uri ContainerUrl
{
get
{
return new Uri(string.Join(Constants.PathSeparator, new string[] { BlobClient.BaseUri.AbsolutePath, Constants.ContainerName }));
}
}
/// <summary>
/// Gets the CloudBlobClient instance from lazyclient.
/// </summary>
private static CloudBlobClient BlobClient
{
get
{
return _blobClient;
}
}
/// <summary>
/// Gets the blob content from azure as a stream.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <returns>
/// The blob details.
/// </returns>
public BlobDetails GetBlobContent(string blobName)
{
if (string.IsNullOrWhiteSpace(blobName))
{
throw new ArgumentNullException("blobName");
}
return GetBlob(blobName, Constants.ContainerName);
}
/// <summary>
/// Gets the thumbnail from azure as a stream.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <returns>
/// The blob details.
/// </returns>
public BlobDetails GetThumbnail(string blobName)
{
if (string.IsNullOrWhiteSpace(blobName))
{
throw new ArgumentNullException("blobName");
}
return GetBlob(blobName, Constants.ThumbnailContainerName);
}
/// <summary>
/// Gets the Temporary file (whether thumbnail or file) from azure as a stream.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <returns>
/// The blob details.
/// </returns>
public BlobDetails GetTemporaryFile(string blobName)
{
if (string.IsNullOrWhiteSpace(blobName))
{
throw new ArgumentNullException("blobName");
}
return GetBlob(blobName, Constants.TemporaryContainerName);
}
/// <summary>
/// Uploads a file to azure as a blob.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is uploaded successfully; otherwise false.
/// </returns>
public bool UploadFile(BlobDetails details)
{
this.CheckNotNull(() => details);
return UploadBlobContent(details, Constants.ContainerName);
}
/// <summary>
/// Move a file from temporary container to file container in azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is moved successfully; otherwise false.
/// </returns>
public bool MoveFile(BlobDetails details)
{
return MoveBlob(details, Constants.TemporaryContainerName, Constants.ContainerName);
}
/// <summary>
/// Move a thumbnail from temporary container to thumbnail container in azure.
/// </summary>
/// <param name="details">
/// Details of the thumbnail which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the thumbnail is moved successfully; otherwise false.
/// </returns>
public bool MoveThumbnail(BlobDetails details)
{
return MoveBlob(details, Constants.TemporaryContainerName, Constants.ThumbnailContainerName);
}
/// <summary>
/// Uploads a thumbnail to azure as a blob.
/// </summary>
/// <param name="details">
/// Details of the thumbnail which has to be uploaded.
/// </param>
/// <returns>
/// True if the thumbnail is uploaded successfully; otherwise false.
/// </returns>
public bool UploadThumbnail(BlobDetails details)
{
this.CheckNotNull(() => details);
return UploadBlobContent(details, Constants.ThumbnailContainerName);
}
/// <summary>
/// Uploads a file to azure as a blob in temporary container.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is uploaded successfully; otherwise false.
/// </returns>
public bool UploadTemporaryFile(BlobDetails details)
{
this.CheckNotNull(() => details);
return UploadBlobContent(details, Constants.TemporaryContainerName);
}
/// <summary>
/// Deletes a file from azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is deleted successfully; otherwise false.
/// </returns>
public bool DeleteFile(BlobDetails details)
{
return DeleteBlob(details, Constants.ContainerName);
}
/// <summary>
/// Deletes a thumbnail from azure.
/// </summary>
/// <param name="details">
/// Details of the thumbnail which has to be uploaded.
/// </param>
/// <returns>
/// True if the thumbnail is deleted successfully; otherwise false.
/// </returns>
public bool DeleteThumbnail(BlobDetails details)
{
return DeleteBlob(details, Constants.ThumbnailContainerName);
}
/// <summary>
/// Deletes a temporary file from azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is deleted successfully; otherwise false.
/// </returns>
public bool DeleteTemporaryFile(BlobDetails details)
{
return DeleteBlob(details, Constants.TemporaryContainerName);
}
/// <summary>
/// Gets the blob content from azure as a stream.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <returns>
/// The blob details.
/// </returns>
public BlobDetails GetAsset(string blobName)
{
if (string.IsNullOrWhiteSpace(blobName))
{
throw new ArgumentNullException("blobName");
}
return GetBlob(blobName, Constants.AssetContainerName);
}
/// <summary>
/// Uploads a file to azure as a blob.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is uploaded successfully; otherwise false.
/// </returns>
public bool UploadAsset(BlobDetails details)
{
this.CheckNotNull(() => details);
return UploadBlobContent(details, Constants.AssetContainerName);
}
/// <summary>
/// Deletes a file from azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be deleted.
/// </param>
/// <returns>
/// True if the file is deleted successfully; otherwise false.
/// </returns>
public bool DeleteAsset(BlobDetails details)
{
return DeleteBlob(details, Constants.AssetContainerName);
}
/// <summary>
/// Move a file from temporary container to asset container in azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be uploaded to azure.
/// </param>
/// <returns>
/// True if the file is moved successfully; otherwise false.
/// </returns>
public bool MoveAssetFile(BlobDetails details)
{
return MoveBlob(details, Constants.TemporaryContainerName, Constants.AssetContainerName);
}
/// <summary>
/// Checks a file in azure.
/// </summary>
/// <param name="details">
/// Details of the file which has to be checked.
/// </param>
/// <returns>
/// True if the file is found successfully; otherwise false.
/// </returns>
public bool CheckIfAssetExists(BlobDetails details)
{
return ExistsBlobContent(details, Constants.AssetContainerName);
}
/// <summary>
/// Gets the content from azure as a stream.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <param name="outputStream">
/// The content is exposed as output stream.
/// </param>
/// <param name="container">
/// COntainer where we could find the blob.
/// </param>
/// <returns>
/// The blob properties.
/// </returns>
private static BlobProperties GetContent(string blobName, Stream outputStream, CloudBlobContainer container)
{
var blob = container.GetBlobReferenceFromServer(blobName.ToUpperInvariant());
blob.DownloadToStream(outputStream);
return blob.Properties;
}
/// <summary>
/// Used to retrieve the container reference identified by the container name.
/// </summary>
/// <param name="containerName">
/// Name of the container.
/// </param>
/// <returns>
/// Container instance.
/// </returns>
private static CloudBlobContainer GetContainer(string containerName)
{
var container = _blobClient.GetContainerReference(containerName);
container.CreateIfNotExists();
return container;
}
/// <summary>
/// Gets the content of the blob from specified container.
/// </summary>
/// <param name="blobName">
/// Name of the blob.
/// </param>
/// <param name="containerName">
/// name of the container.
/// </param>
/// <returns>
/// The blob details.
/// </returns>
private static BlobDetails GetBlob(string blobName, string containerName)
{
Stream outputStream = null;
BlobProperties properties = null;
try
{
outputStream = new MemoryStream();
var container = GetContainer(containerName);
properties = GetContent(blobName, outputStream, container);
}
catch (InvalidOperationException)
{
// TODO: Add error handling logic
// "Error getting contents of blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, sc.Message
outputStream = null;
}
catch (StorageException exception)
{
// TODO: Add error handling logic
// ErrorCode and StatusCode can be used to identify the error.
// "Error getting contents of blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, sc.Message
// TODO: Need to add proper Exception handling.
outputStream = null;
}
return new BlobDetails()
{
Data = outputStream,
BlobID = blobName,
MimeType = properties != null ? properties.ContentType : Constants.DefaultMimeType
};
}
/// <summary>
/// Moves blob from source to destination.
/// </summary>
/// <param name="details">
/// Details of the blob.
/// </param>
/// <param name="sourceContainerName">
/// Name of Source container.
/// </param>
/// <param name="destinationContainerName">
/// Name of Destination container.
/// </param>
/// <returns>
/// True, if the blob is successfully moved;otherwise false.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Ignore all exceptions.")]
private static bool MoveBlob(BlobDetails details, string sourceContainerName, string destinationContainerName)
{
try
{
var sourceContainer = GetContainer(sourceContainerName);
var destinationContainer = GetContainer(destinationContainerName);
// TODO: Check if the input file type and then use either block blob or page blob.
// For plate file we need to upload the file as page blob.
var sourceBlob = sourceContainer.GetBlockBlobReference(details.BlobID.ToUpperInvariant());
var destinationBlob = destinationContainer.GetBlockBlobReference(details.BlobID.ToUpperInvariant());
destinationBlob.StartCopyFromBlob(sourceBlob);
destinationBlob.Properties.ContentType = sourceBlob.Properties.ContentType;
sourceBlob.Delete();
return true;
}
catch (Exception)
{
// "Error moving blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message
}
return false;
}
/// <summary>
/// Checks if the blob content is present in azure or not.
/// </summary>
/// <param name="details">
/// Details of the blob.
/// </param>
/// <param name="containerName">
/// Name of the container.
/// </param>
/// <returns>
/// True, if the blob is successfully found to azure;otherwise false.
/// </returns>
private static bool ExistsBlobContent(BlobDetails details, string containerName)
{
try
{
var container = GetContainer(containerName);
// TODO: Check if the input file type and then use either block blob or page blob.
// For plate file we need to upload the file as page blob.
var blob = container.GetBlobReferenceFromServer(details.BlobID.ToUpperInvariant());
blob.FetchAttributes();
return true;
}
catch (StorageException)
{
// "Error uploading blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message
}
return false;
}
/// <summary>
/// Deletes the specified file pointed by the blob.
/// </summary>
/// <param name="details">
/// Details of the blob.
/// </param>
/// <param name="containerName">
/// Name of the container.
/// </param>
private static bool DeleteBlob(BlobDetails details, string containerName)
{
try
{
var container = GetContainer(containerName);
container.GetBlobReferenceFromServer(details.BlobID.ToUpperInvariant()).Delete();
return true;
}
catch (InvalidOperationException)
{
// "Error deleting blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message
return false;
}
}
/// <summary>
/// Upload the blob content to azure.
/// </summary>
/// <param name="details">
/// Details of the blob.
/// </param>
/// <param name="containerName">
/// Name of the container.
/// </param>
/// <returns>
/// True, if the blob is successfully uploaded to azure;otherwise false.
/// </returns>
private bool UploadBlobContent(BlobDetails details, string containerName)
{
this.CheckNotNull(() => details);
try
{
var container = GetContainer(containerName);
// Seek to start.
details.Data.Position = 0;
// TODO: Check if the input file type and then use either block blob or page blob.
// For plate file we need to upload the file as page blob.
var blob = container.GetBlockBlobReference(details.BlobID.ToUpperInvariant());
blob.Properties.ContentType = details.MimeType;
blob.UploadFromStream(details.Data);
return true;
}
catch (InvalidOperationException)
{
// "Error uploading blob {0}: {1}", ContainerUrl + _PathSeparator + blobName, se.Message
}
return false;
}
}
} | 34.887661 | 144 | 0.543391 | [
"MIT"
] | wizard01/Emerald-server-web-server | WWTMVC5/Repositories/BlobDataRepository.cs | 18,946 | C# |
// Copyright 2016-2019, Pulumi Corporation
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Google.Protobuf;
using Pulumirpc;
namespace Pulumi
{
public partial class Deployment
{
void IDeploymentInternal.RegisterResourceOutputs(Resource resource, Output<IDictionary<string, object?>> outputs)
{
// RegisterResourceOutputs is called in a fire-and-forget manner. Make sure we keep track of
// this task so that the application will not quit until this async work completes.
_runner.RegisterTask(
$"{nameof(IDeploymentInternal.RegisterResourceOutputs)}: {resource.GetResourceType()}-{resource.GetResourceName()}",
RegisterResourceOutputsAsync(resource, outputs));
}
private async Task RegisterResourceOutputsAsync(
Resource resource, Output<IDictionary<string, object?>> outputs)
{
var opLabel = $"monitor.registerResourceOutputs(...)";
// The registration could very well still be taking place, so we will need to wait for its URN.
// Additionally, the output properties might have come from other resources, so we must await those too.
var urn = await resource.Urn.GetValueAsync().ConfigureAwait(false);
var props = await outputs.GetValueAsync().ConfigureAwait(false);
var serialized = await SerializeAllPropertiesAsync(opLabel, props).ConfigureAwait(false);
Log.Debug($"RegisterResourceOutputs RPC prepared: urn={urn}" +
(_excessiveDebugOutput ? $", outputs ={JsonFormatter.Default.Format(serialized)}" : ""));
await Monitor.RegisterResourceOutputsAsync(new RegisterResourceOutputsRequest
{
Urn = urn,
Outputs = serialized,
});
}
}
}
| 42.954545 | 132 | 0.664021 | [
"Apache-2.0"
] | 6a6f6a6f/pulumi | sdk/dotnet/Pulumi/Deployment/Deployment_RegisterResourceOutputs.cs | 1,892 | C# |
using System.Collections;
using System.Collections.Generic;
using TUF.Core;
using UnityEngine;
namespace TUF.Combat.Danmaku
{
[System.Serializable]
public struct DanmakuConfig
{
public Transform startPoint;
public Vector3 position;
public Vector3 rotation;
public Range3 speed;
public Range3 angularSpeed;
/// <summary>
/// Creates an state based on the config.
/// </summary>
/// <returns>a sampled state from the config's state space.</returns>
public DanmakuState CreateState()
{
return new DanmakuState
{
position = position,
rotation = rotation,
speed = speed.GetValue(),
angularSpeed = angularSpeed.GetValue()
};
}
}
} | 26.21875 | 77 | 0.574493 | [
"MIT"
] | christides11/touhou-unlimited-fantasies | Assets/_Project/Scripts/Combat/Danmaku/DanmakuConfig.cs | 841 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Foundatio.AsyncEx {
/// <summary>
/// Provides extension methods for the <see cref="Task"/> and <see cref="Task{T}"/> types.
/// </summary>
public static class TaskExtensions
{
/// <summary>
/// Asynchronously waits for the task to complete, or for the cancellation token to be canceled.
/// </summary>
/// <param name="this">The task to wait for. May not be <c>null</c>.</param>
/// <param name="cancellationToken">The cancellation token that cancels the wait.</param>
public static Task WaitAsync(this Task @this, CancellationToken cancellationToken)
{
if (@this == null)
throw new ArgumentNullException(nameof(@this));
if (!cancellationToken.CanBeCanceled)
return @this;
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
return DoWaitAsync(@this, cancellationToken);
}
private static async Task DoWaitAsync(Task task, CancellationToken cancellationToken)
{
using (var cancelTaskSource = new CancellationTokenTaskSource<object>(cancellationToken))
await await Task.WhenAny(task, cancelTaskSource.Task).ConfigureAwait(false);
}
private static async Task<TResult> DoWaitAsync<TResult>(Task<TResult> task, CancellationToken cancellationToken)
{
using (var cancelTaskSource = new CancellationTokenTaskSource<TResult>(cancellationToken))
return await await Task.WhenAny(task, cancelTaskSource.Task).ConfigureAwait(false);
}
}
} | 43.4 | 120 | 0.653802 | [
"Apache-2.0"
] | Leon99/Foundatio | src/Foundatio/Nito.AsyncEx.Tasks/TaskExtensions.cs | 1,736 | C# |
using System;
using System.Collections.Generic;
using Terraria;
using Terraria.ID;
using Terraria.GameContent.Creative;
using Terraria.ModLoader;
namespace GoldensMisc.Items.Weapons
{
public class DiamondStaff : ModItem
{
public override bool IsLoadingEnabled (Mod mod)
{
return ModContent.GetInstance<ServerConfig>().AltStaffs;
}
public override void SetStaticDefaults()
{
Item.staff[Item.type] = true;
CreativeItemSacrificesCatalog.Instance.SacrificeCountNeededByItemId[Type] = 1;
}
public override void SetDefaults()
{
Item.rare = ItemRarityID.Green;
Item.mana = 7;
Item.UseSound = SoundID.Item43;
Item.useStyle = ItemUseStyleID.Shoot;
Item.damage = 23;
Item.useAnimation = 25;
Item.useTime = 25;
Item.width = 40;
Item.height = 40;
Item.shoot = ProjectileID.DiamondBolt;
Item.shootSpeed = 9.25f;
Item.knockBack = 5.25f;
Item.value = Item.sellPrice(0, 0, 50);
Item.DamageType = DamageClass.Magic;
Item.noMelee = true;
Item.autoReuse = true;
}
public override void AddRecipes()
{
CreateRecipe()
.AddIngredient(ItemID.GoldBar, 10)
.AddIngredient(ItemID.Diamond, 8)
.AddTile(TileID.Anvils)
.Register();
}
}
}
| 22.648148 | 81 | 0.703189 | [
"MIT"
] | Pop000100/Miscellania | Items/Weapons/DiamondStaff.cs | 1,225 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace SourceExpander
{
public class ExpandConfig
{
public ExpandConfig()
: this(
true,
Array.Empty<string>(),
Array.Empty<Regex>(),
null,
null)
{ }
public ExpandConfig(
bool enabled,
string[] matchFilePatterns,
IEnumerable<Regex> ignoreFilePatterns,
string? staticEmbeddingText,
string? metadataExpandingFile)
{
Enabled = enabled;
MatchFilePatterns = ImmutableArray.Create(matchFilePatterns);
IgnoreFilePatterns = ImmutableArray.CreateRange(ignoreFilePatterns);
StaticEmbeddingText = staticEmbeddingText;
MetadataExpandingFile = metadataExpandingFile;
}
public bool Enabled { get; }
public ImmutableArray<string> MatchFilePatterns { get; }
public ImmutableArray<Regex> IgnoreFilePatterns { get; }
public string? StaticEmbeddingText { get; }
public string? MetadataExpandingFile { get; }
public bool IsMatch(string filePath)
=> (MatchFilePatterns.Length == 0
|| MatchFilePatterns.Any(p => filePath.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
&& IgnoreFilePatterns.All(regex => !regex.IsMatch(filePath));
public static ExpandConfig Parse(string sourceText)
{
if (JsonUtil.ParseJson<ExpandConfig>(sourceText) is { } config)
return config;
return new ExpandConfig();
}
static ExpandConfig()
{
JsonUtil.Converters.Add(new ExpandConfigConverter());
}
private class ExpandConfigConverter : JsonConverter<ExpandConfig?>
{
public override bool CanWrite => false;
public override ExpandConfig? ReadJson(JsonReader reader, Type objectType, ExpandConfig? existingValue, bool hasExistingValue, JsonSerializer serializer)
=> serializer.Deserialize<ExpandConfigData>(reader)?.ToImmutable();
public override void WriteJson(JsonWriter writer, ExpandConfig? value, JsonSerializer serializer)
=> throw new NotImplementedException("CanWrite is always false");
}
[DataContract]
private class ExpandConfigData
{
[DataMember(Name = "enabled")]
public bool? Enabled { set; get; }
[DataMember(Name = "match-file-pattern")]
public string[]? MatchFilePattern { set; get; }
[DataMember(Name = "metadata-expanding-file")]
public string? MetadataExpandingFile { set; get; }
[DataMember(Name = "ignore-file-pattern-regex")]
public string[]? IgnoreFilePatternRegex { set; get; }
[DataMember(Name = "static-embedding-text")]
public string? StaticEmbeddingText { set; get; }
public ExpandConfig ToImmutable() => new(
enabled: this.Enabled ?? true,
matchFilePatterns: this.MatchFilePattern ?? Array.Empty<string>(),
ignoreFilePatterns: this.IgnoreFilePatternRegex?.Select(s => new Regex(s))
?? Array.Empty<Regex>(),
staticEmbeddingText: this.StaticEmbeddingText,
metadataExpandingFile: MetadataExpandingFile);
}
}
}
| 40.94382 | 165 | 0.608397 | [
"MIT"
] | naminodarie/SourceExpander | Source/SourceExpander.Generator/ExpandConfig.cs | 3,646 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.TestHost;
using Xunit;
namespace Microsoft.Extensions.Localization
{
public class AcceptLanguageHeaderRequestCultureProviderTest
{
[Fact]
public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCultureList()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("ar-SA"),
new CultureInfo("en-US")
}
});
app.Run(context =>
{
var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
var requestCulture = requestCultureFeature.RequestCulture;
Assert.Equal("ar-SA", requestCulture.Culture.Name);
return Task.FromResult(0);
});
});
using (var server = new TestServer(builder))
{
var client = server.CreateClient();
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("jp,ar-SA,en-US");
var count = client.DefaultRequestHeaders.AcceptLanguage.Count;
var response = await client.GetAsync(string.Empty);
Assert.Equal(3, count);
}
}
[Fact]
public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguageListContainsSupportedCultures()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("fr-FR"),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("ar-SA"),
new CultureInfo("en-US")
}
});
app.Run(context =>
{
var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
var requestCulture = requestCultureFeature.RequestCulture;
Assert.Equal("ar-SA", requestCulture.Culture.Name);
return Task.FromResult(0);
});
});
using (var server = new TestServer(builder))
{
var client = server.CreateClient();
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-SA,en-US");
var count = client.DefaultRequestHeaders.AcceptLanguage.Count;
var response = await client.GetAsync(string.Empty);
}
}
[Fact]
public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotContainSupportedCultures()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("fr-FR"),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("ar-SA"),
new CultureInfo("af-ZA")
}
});
app.Run(context =>
{
var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
var requestCulture = requestCultureFeature.RequestCulture;
Assert.Equal("fr-FR", requestCulture.Culture.Name);
return Task.FromResult(0);
});
});
using (var server = new TestServer(builder))
{
var client = server.CreateClient();
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-MA,en-US");
var count = client.DefaultRequestHeaders.AcceptLanguage.Count;
var response = await client.GetAsync(string.Empty);
Assert.Equal(3, count);
}
}
[Fact]
public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_And_ShouldGetTheRightCulture()
{
var builder = new WebHostBuilder()
.Configure(app =>
{
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("ar-YE")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("ar-YE")
}
});
app.Run(context =>
{
var requestCultureFeature = context.Features.Get<IRequestCultureFeature>();
var requestCulture = requestCultureFeature.RequestCulture;
Assert.Equal("ar-YE", requestCulture.Culture.Name);
Assert.Equal("ar-YE", requestCulture.UICulture.Name);
return Task.FromResult(0);
});
});
using (var server = new TestServer(builder))
{
var client = server.CreateClient();
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-YE,en-US");
var count = client.DefaultRequestHeaders.AcceptLanguage.Count;
var response = await client.GetAsync(string.Empty);
Assert.Equal(3, count);
}
}
}
} | 42.866242 | 119 | 0.510253 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs | 6,730 | C# |
namespace NEventSocket.Tests.Sockets
{
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NEventSocket;
using NEventSocket.Logging;
using NEventSocket.Tests.Fakes;
using NEventSocket.Tests.TestSupport;
using Xunit;
public class OutboundListenerTests
{
public OutboundListenerTests()
{
PreventThreadPoolStarvation.Init();
Logger.Configure(LoggerFactory.Create(builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
.AddConsole();
}));
}
[Fact(Timeout = 2000)]
public void Disposing_the_listener_completes_the_connections_observable()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
bool completed = false;
listener.Connections.Subscribe(_ => { }, () => completed = true);
listener.Dispose();
Assert.True(completed);
}
}
[Fact(Timeout = 2000)]
public async Task Disposing_the_listener_disposes_any_connected_clients()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
bool connected = false;
bool disposed = false;
listener.Connections.Subscribe((socket) =>
{
connected = true;
socket.Disposed += (o, e) => disposed = true;
});
var client = new FakeFreeSwitchSocket(listener.Port);
await Wait.Until(() => connected);
listener.Dispose();
Assert.True(disposed);
}
}
[Fact(Timeout = 2000)]
public async Task Stopping_the_listener_does_not_dispose_any_connected_clients()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
bool connected = false;
bool disposed = false;
listener.Connections.Subscribe((socket) =>
{
connected = true;
socket.Disposed += (o, e) => disposed = true;
});
var _ = new FakeFreeSwitchSocket(listener.Port);
await Wait.Until(() => connected);
listener.Stop();
Assert.False(disposed);
listener.Dispose();
Assert.True(disposed);
}
}
[Fact(Timeout = 2000)]
public async Task Can_restart_the_listener_after_stopping()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
int counter = 0;
listener.Connections.Subscribe((socket) =>
{
counter++;
});
new FakeFreeSwitchSocket(listener.Port);
await Wait.Until(() => counter == 1);
listener.Stop();
//not listening
Assert.ThrowsAny<SocketException>(() => new FakeFreeSwitchSocket(listener.Port));
listener.Start();
new FakeFreeSwitchSocket(listener.Port);
await Wait.Until(() => counter == 2);
}
}
[Fact(Timeout = 2000)]
public async Task a_new_connection_produces_an_outbound_socket()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
bool connected = false;
listener.Connections.Subscribe((socket) => connected = true);
var client = new FakeFreeSwitchSocket(listener.Port);
await Wait.Until(() => connected);
Assert.True(connected);
}
}
[Fact(Timeout = 2000)]
public async Task each_new_connection_produces_a_new_outbound_socket_from_the_Connections_observable()
{
const int NumberOfConnections = 3;
using (var listener = new OutboundListener(0))
{
listener.Start();
var connected = 0;
listener.Connections.Subscribe((socket) => connected++);
for (int i = 0; i < NumberOfConnections; i++)
{
var client = new FakeFreeSwitchSocket(listener.Port);
}
await Wait.Until(() => connected == NumberOfConnections);
Assert.Equal(NumberOfConnections, connected);
}
}
[Fact(Timeout = TimeOut.TestTimeOutMs)]
public async Task ProblematicSocket_connect_errors_should_not_cause_subsequent_connections_to_fail()
{
var connectionsHandled = 0;
var observableCompleted = false;
using (var listener = new ProblematicListener(0))
{
listener.Start();
listener.Connections.Subscribe(_ => connectionsHandled++, ex => { }, () => observableCompleted = true);
using (var client = new FakeFreeSwitchSocket(listener.Port))
{
await Wait.Until(() => ProblematicListener.Counter == 1);
Assert.Equal(0, connectionsHandled);
Assert.Equal(1, ProblematicListener.Counter);
Assert.False(observableCompleted);
}
using (var client = new FakeFreeSwitchSocket(listener.Port))
{
await Wait.Until(() => connectionsHandled == 1);
Assert.Equal(1, connectionsHandled);
Assert.Equal(2, ProblematicListener.Counter);
Assert.False(observableCompleted);
}
}
Assert.True(observableCompleted);
}
[Fact(Timeout = 2000)]
public async Task IsStarted_is_false_when_initialized()
{
using (var listener = new OutboundListener(0))
{
Assert.False(listener.IsStarted);
}
}
[Fact(Timeout = 2000)]
public async Task IsStarted_is_true_when_started()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
Assert.True(listener.IsStarted);
}
}
[Fact(Timeout = 2000)]
public async Task IsStarted_is_false_when_stopped()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
Assert.True(listener.IsStarted);
listener.Stop();
Assert.False(listener.IsStarted);
}
}
[Fact(Timeout = 2000)]
public async Task IsStarted_is_false_when_disposed()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
listener.Dispose();
await Wait.Until(() => listener.IsStarted == false);
}
}
[Fact(Timeout = 2000)]
public async Task Starting_should_be_idempotent()
{
using (var listener = new OutboundListener(0))
{
listener.Start();
listener.Start();
Assert.True(listener.IsStarted);
}
}
}
} | 30.2607 | 119 | 0.506622 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Josbleuet/NEventSocket | NEventSocket.Tests/Sockets/OutboundListenerTests.cs | 7,779 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WebApi.Entities;
using WebApi.Models;
using WebApi.Services;
namespace WebApi.Controllers
{
//[Authorize]
[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase
{
private IUserService _userService;
public LoginController(IUserService userService)
{
_userService = userService;
}
[Authorize]
[HttpGet]
public IActionResult Authenticate() {
var identity = User.Identity.Name.Split("\\");
if (identity.Length < 2)
return BadRequest(new { message = "Client not authenticated" });
User user = new User { Username = identity[1] };
var response = _userService.Authenticate(user);
if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
return Ok(response);
}
[Authorize]
[HttpPost]
public IActionResult Authenticate(AuthenticateRequest req) {
var identity = User.Identity.Name.Split("\\");
if (identity.Length < 2)
return BadRequest(new { message = "Client not authenticated" });
User user = new User { Username = identity[1] };
var response = _userService.Authenticate(user);
if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
return Ok(response);
}
}
}
| 30.018182 | 90 | 0.571169 | [
"MIT"
] | sganis/dotnet-jwt | dotnet-jwt-login/Controllers/LoginController.cs | 1,653 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.XEvent;
using Microsoft.SqlTools.ServiceLayer.Connection.Contracts;
using Microsoft.SqlTools.ServiceLayer.Profiler.Contracts;
using Microsoft.SqlTools.Utility;
namespace Microsoft.SqlTools.ServiceLayer.Profiler
{
/// <summary>
/// Class to monitor active profiler sessions
/// </summary>
public class ProfilerSessionMonitor : IProfilerSessionMonitor
{
private const int PollingLoopDelay = 1000;
private object sessionsLock = new object();
private object listenersLock = new object();
private object pollingLock = new object();
private Task processorThread = null;
private struct Viewer
{
public string Id { get; set; }
public bool active { get; set; }
public int xeSessionId { get; set; }
public Viewer(string Id, bool active, int xeId)
{
this.Id = Id;
this.active = active;
this.xeSessionId = xeId;
}
};
// XEvent Session Id's matched to the Profiler Id's watching them
private Dictionary<int, List<string>> sessionViewers = new Dictionary<int, List<string>>();
// XEvent Session Id's matched to their Profiler Sessions
private Dictionary<int, ProfilerSession> monitoredSessions = new Dictionary<int, ProfilerSession>();
// ViewerId -> Viewer objects
private Dictionary<string, Viewer> allViewers = new Dictionary<string, Viewer>();
private List<IProfilerSessionListener> listeners = new List<IProfilerSessionListener>();
/// <summary>
/// Registers a session event Listener to receive a callback when events arrive
/// </summary>
public void AddSessionListener(IProfilerSessionListener listener)
{
lock (this.listenersLock)
{
this.listeners.Add(listener);
}
}
/// <summary>
/// Start monitoring the provided session
/// </summary>
public bool StartMonitoringSession(string viewerId, IXEventSession session)
{
lock (this.sessionsLock)
{
// start the monitoring thread
if (this.processorThread == null)
{
this.processorThread = Task.Factory.StartNew(ProcessSessions);
}
// create new profiling session if needed
if (!this.monitoredSessions.ContainsKey(session.Id))
{
var profilerSession = new ProfilerSession();
profilerSession.XEventSession = session;
this.monitoredSessions.Add(session.Id, profilerSession);
}
// create a new viewer, or configure existing viewer
Viewer viewer;
if (!this.allViewers.TryGetValue(viewerId, out viewer))
{
viewer = new Viewer(viewerId, true, session.Id);
allViewers.Add(viewerId, viewer);
}
else
{
viewer.active = true;
viewer.xeSessionId = session.Id;
}
// add viewer to XEvent session viewers
List<string> viewers;
if (this.sessionViewers.TryGetValue(session.Id, out viewers))
{
viewers.Add(viewerId);
}
else
{
viewers = new List<string>{ viewerId };
sessionViewers.Add(session.Id, viewers);
}
}
return true;
}
/// <summary>
/// Stop monitoring the session watched by viewerId
/// </summary>
public bool StopMonitoringSession(string viewerId, out ProfilerSession session)
{
lock (this.sessionsLock)
{
Viewer v;
if (this.allViewers.TryGetValue(viewerId, out v))
{
return RemoveSession(v.xeSessionId, out session);
}
else
{
session = null;
return false;
}
}
}
/// <summary>
/// Toggle the pause state for the viewer
/// </summary>
public void PauseViewer(string viewerId)
{
lock (this.sessionsLock)
{
Viewer v = this.allViewers[viewerId];
v.active = !v.active;
this.allViewers[viewerId] = v;
}
}
private bool RemoveSession(int sessionId, out ProfilerSession session)
{
lock (this.sessionsLock)
{
if (this.monitoredSessions.Remove(sessionId, out session))
{
//remove all viewers for this session
List<string> viewerIds;
if (sessionViewers.Remove(sessionId, out viewerIds))
{
foreach (String viewerId in viewerIds)
{
this.allViewers.Remove(viewerId);
}
return true;
}
else
{
session = null;
return false;
}
}
else
{
session = null;
return false;
}
}
}
public void PollSession(int sessionId)
{
lock (this.sessionsLock)
{
this.monitoredSessions[sessionId].pollImmediatly = true;
}
lock (this.pollingLock)
{
Monitor.Pulse(pollingLock);
}
}
/// <summary>
/// The core queue processing method
/// </summary>
/// <param name="state"></param>
private void ProcessSessions()
{
while (true)
{
lock (this.pollingLock)
{
lock (this.sessionsLock)
{
foreach (var session in this.monitoredSessions.Values)
{
List<string> viewers = this.sessionViewers[session.XEventSession.Id];
if (viewers.Any(v => allViewers[v].active))
{
ProcessSession(session);
}
}
}
Monitor.Wait(this.pollingLock, PollingLoopDelay);
}
}
}
/// <summary>
/// Process a session for new XEvents if it meets the polling criteria
/// </summary>
private void ProcessSession(ProfilerSession session)
{
if (session.TryEnterPolling())
{
Task.Factory.StartNew(() =>
{
var events = PollSession(session);
bool eventsLost = session.EventsLost;
if (events.Count > 0 || eventsLost)
{
// notify all viewers for the polled session
List<string> viewerIds = this.sessionViewers[session.XEventSession.Id];
foreach (string viewerId in viewerIds)
{
if (allViewers[viewerId].active)
{
SendEventsToListeners(viewerId, events, eventsLost);
}
}
}
});
}
}
private List<ProfilerEvent> PollSession(ProfilerSession session)
{
var events = new List<ProfilerEvent>();
try
{
if (session == null || session.XEventSession == null)
{
return events;
}
var targetXml = session.XEventSession.GetTargetXml();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(targetXml);
var nodes = xmlDoc.DocumentElement.GetElementsByTagName("event");
foreach (XmlNode node in nodes)
{
var profilerEvent = ParseProfilerEvent(node);
if (profilerEvent != null)
{
events.Add(profilerEvent);
}
}
}
catch (XEventException)
{
SendStoppedSessionInfoToListeners(session.XEventSession.Id);
ProfilerSession tempSession;
RemoveSession(session.XEventSession.Id, out tempSession);
}
catch (Exception ex)
{
Logger.Write(TraceEventType.Warning, "Failed to poll session. error: " + ex.Message);
}
finally
{
session.IsPolling = false;
}
session.FilterOldEvents(events);
return session.FilterProfilerEvents(events);
}
/// <summary>
/// Notify listeners about closed sessions
/// </summary>
private void SendStoppedSessionInfoToListeners(int sessionId)
{
lock (listenersLock)
{
foreach (var listener in this.listeners)
{
foreach(string viewerId in sessionViewers[sessionId])
{
listener.SessionStopped(viewerId, sessionId);
}
}
}
}
/// <summary>
/// Notify listeners when new profiler events are available
/// </summary>
private void SendEventsToListeners(string sessionId, List<ProfilerEvent> events, bool eventsLost)
{
lock (listenersLock)
{
foreach (var listener in this.listeners)
{
listener.EventsAvailable(sessionId, events, eventsLost);
}
}
}
/// <summary>
/// Parse a single event node from XEvent XML
/// </summary>
private ProfilerEvent ParseProfilerEvent(XmlNode node)
{
var name = node.Attributes["name"];
var timestamp = node.Attributes["timestamp"];
var profilerEvent = new ProfilerEvent(name.InnerText, timestamp.InnerText);
foreach (XmlNode childNode in node.ChildNodes)
{
var childName = childNode.Attributes["name"];
XmlNode typeNode = childNode.SelectSingleNode("type");
var typeName = typeNode.Attributes["name"];
XmlNode valueNode = childNode.SelectSingleNode("value");
if (!profilerEvent.Values.ContainsKey(childName.InnerText))
{
profilerEvent.Values.Add(childName.InnerText, valueNode.InnerText);
}
}
return profilerEvent;
}
}
}
| 33.410112 | 108 | 0.492265 | [
"MIT"
] | Bhaskers-Blu-Org2/sqltoolsservice | src/Microsoft.SqlTools.ServiceLayer/Profiler/ProfilerSessionMonitor.cs | 11,894 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
#if STRESS
using System;
using System.Reactive.Disposables;
using System.Reflection;
using System.Threading;
namespace ReactiveTests.Stress.Disposables
{
public class SingleAssignment
{
/// <summary>
/// Allocates a SingleAssignmentDisposable and assigns a disposable object at a random time. Also disposes the container at a random time.
/// Expected behavior is to see the assigned disposable getting disposed no matter what.
/// </summary>
public static void RandomAssignAndDispose()
{
Console.Title = MethodInfo.GetCurrentMethod().Name + " - 0% complete";
for (int i = 1; i <= 100; i++)
{
for (int j = 0; j < 10; j++)
{
Impl();
}
Console.Title = MethodInfo.GetCurrentMethod().Name + " - " + i + "% complete";
}
}
private static void Impl()
{
var rand = new Random();
for (int i = 0; i < 1000; i++)
{
var d = new SingleAssignmentDisposable();
var e = new ManualResetEvent(false);
var cd = new CountdownEvent(2);
var sleep1 = rand.Next(0, 1) == 0 ? 0 : rand.Next(2, 100);
var sleep2 = rand.Next(0, 1) == 0 ? 0 : rand.Next(2, 100);
ThreadPool.QueueUserWorkItem(_ =>
{
Helpers.SleepOrSpin(sleep1);
Console.Write("{DB} ");
d.Dispose();
Console.Write("{DE} ");
cd.Signal();
});
ThreadPool.QueueUserWorkItem(_ =>
{
Helpers.SleepOrSpin(sleep2);
Console.Write("{AB} ");
d.Disposable = Disposable.Create(() => e.Set());
Console.Write("{AE} ");
cd.Signal();
});
e.WaitOne();
cd.Wait();
Console.WriteLine(".");
}
}
}
}
#endif | 30.298701 | 146 | 0.484355 | [
"MIT"
] | 00mjk/reactive | Rx.NET/Source/tests/Tests.System.Reactive/Stress/Core/Disposables/SingleAssignment.cs | 2,335 | C# |
//-----------------------------------------------------------------------------
// Filename: Program.cs
//
// Description: An example program of how to use the SIPSorcery core library to
// place a SIP call and then place it on and off hold as well as demonstrate how
// a blind transfer can be initiated.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 25 Nov 2019 Aaron Clauson Created, Dublin, Ireland.
// 20 Feb 2020 Aaron Clauson Switched to RtpAVSession and simplified.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Serilog;
using SIPSorcery.Media;
using SIPSorcery.Net;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
namespace SIPSorcery
{
class Program
{
private static int SIP_LISTEN_PORT = 5060;
private static readonly string DEFAULT_DESTINATION_SIP_URI = "sip:7001@192.168.11.24";
//private static readonly string DEFAULT_DESTINATION_SIP_URI = "sip:7000@192.168.11.48";
private static readonly string TRANSFER_DESTINATION_SIP_URI = "sip:*60@192.168.11.24"; // The destination to transfer the initial call to.
private static readonly string SIP_USERNAME = "7000";
private static readonly string SIP_PASSWORD = "password";
private static int TRANSFER_TIMEOUT_SECONDS = 10; // Give up on transfer if no response within this period.
private const string AUDIO_FILE_PCMU = "media/Macroform_-_Simplicity.ulaw";
private static Microsoft.Extensions.Logging.ILogger Log = SIPSorcery.Sys.Log.Logger;
private static string _currentDir;
static void Main()
{
Console.WriteLine("SIPSorcery Call Hold and Blind Transfer example.");
Console.WriteLine("Press 'c' to initiate a call to the default destination.");
Console.WriteLine("Press 'h' to place an established call on and off hold.");
Console.WriteLine("Press 'H' to hangup an established call.");
Console.WriteLine("Press 't' to request a blind transfer on an established call.");
Console.WriteLine("Press 'q' or ctrl-c to exit.");
// Plumbing code to facilitate a graceful exit.
CancellationTokenSource exitCts = new CancellationTokenSource(); // Cancellation token to stop the SIP transport and RTP stream.
AddConsoleLogger();
// Set up a default SIP transport.
var sipTransport = new SIPTransport();
sipTransport.AddSIPChannel(new SIPUDPChannel(new IPEndPoint(IPAddress.Any, SIP_LISTEN_PORT)));
Console.WriteLine($"Listening for incoming calls on: {sipTransport.GetSIPChannels().First().ListeningEndPoint}.");
EnableTraceLogs(sipTransport);
_currentDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
RtpAVSession rtpAVSession = null;
// Create a client/server user agent to place a call to a remote SIP server along with event handlers for the different stages of the call.
var userAgent = new SIPUserAgent(sipTransport, null);
userAgent.RemotePutOnHold += () => Log.LogInformation("Remote call party has placed us on hold.");
userAgent.RemoteTookOffHold += () => Log.LogInformation("Remote call party took us off hold.");
sipTransport.SIPTransportRequestReceived += async (localEndPoint, remoteEndPoint, sipRequest) =>
{
if (sipRequest.Header.From != null &&
sipRequest.Header.From.FromTag != null &&
sipRequest.Header.To != null &&
sipRequest.Header.To.ToTag != null)
{
// This is an in-dialog request that will be handled directly by a user agent instance.
}
else if (sipRequest.Method == SIPMethodsEnum.INVITE)
{
if (userAgent?.IsCallActive == true)
{
Log.LogWarning($"Busy response returned for incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
// If we are already on a call return a busy response.
UASInviteTransaction uasTransaction = new UASInviteTransaction(sipTransport, sipRequest, null);
SIPResponse busyResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.BusyHere, null);
uasTransaction.SendFinalResponse(busyResponse);
}
else
{
Log.LogInformation($"Incoming call request from {remoteEndPoint}: {sipRequest.StatusLine}.");
var incomingCall = userAgent.AcceptCall(sipRequest);
rtpAVSession = new RtpAVSession(new AudioOptions { AudioSource = AudioSourcesEnum.CaptureDevice }, null);
await userAgent.Answer(incomingCall, rtpAVSession);
Log.LogInformation($"Answered incoming call from {sipRequest.Header.From.FriendlyDescription()} at {remoteEndPoint}.");
}
}
else
{
Log.LogDebug($"SIP {sipRequest.Method} request received but no processing has been set up for it, rejecting.");
SIPResponse notAllowedResponse = SIPResponse.GetResponse(sipRequest, SIPResponseStatusCodesEnum.MethodNotAllowed, null);
await sipTransport.SendResponseAsync(notAllowedResponse);
}
};
// At this point the call has been initiated and everything will be handled in an event handler.
Task.Run(async () =>
{
try
{
while (!exitCts.Token.WaitHandle.WaitOne(0))
{
var keyProps = Console.ReadKey();
if (keyProps.KeyChar == 'c')
{
if (!userAgent.IsCallActive)
{
rtpAVSession = new RtpAVSession(new AudioOptions { AudioSource = AudioSourcesEnum.CaptureDevice }, null);
bool callResult = await userAgent.Call(DEFAULT_DESTINATION_SIP_URI, SIP_USERNAME, SIP_PASSWORD, rtpAVSession);
Log.LogInformation($"Call attempt {((callResult) ? "successfull" : "failed")}.");
}
else
{
Log.LogWarning("There is already an active call.");
}
}
else if (keyProps.KeyChar == 'h')
{
// Place call on/off hold.
if (userAgent.IsCallActive)
{
if (userAgent.IsOnLocalHold)
{
Log.LogInformation("Taking the remote call party off hold.");
userAgent.TakeOffHold();
await (userAgent.MediaSession as RtpAVSession).SetSources(new AudioOptions { AudioSource = AudioSourcesEnum.CaptureDevice }, null);
}
else
{
Log.LogInformation("Placing the remote call party on hold.");
userAgent.PutOnHold();
await (userAgent.MediaSession as RtpAVSession).SetSources(new AudioOptions
{
AudioSource = AudioSourcesEnum.Music,
SourceFiles = new Dictionary<SDPMediaFormatsEnum, string>
{
{ SDPMediaFormatsEnum.PCMU, _currentDir + "/" + AUDIO_FILE_PCMU }
}
}, null);
}
}
else
{
Log.LogWarning("There is no active call to put on hold.");
}
}
else if (keyProps.KeyChar == 'H')
{
if (userAgent.IsCallActive)
{
Log.LogInformation("Hanging up call.");
userAgent.Hangup();
}
}
else if (keyProps.KeyChar == 't')
{
// Initiate a blind transfer to the remote call party.
if (userAgent.IsCallActive)
{
var transferURI = SIPURI.ParseSIPURI(TRANSFER_DESTINATION_SIP_URI);
bool result = await userAgent.BlindTransfer(transferURI, TimeSpan.FromSeconds(TRANSFER_TIMEOUT_SECONDS), exitCts.Token);
if (result)
{
// If the transfer was accepted the original call will already have been hungup.
// Wait a second for the transfer NOTIFY request to arrive.
await Task.Delay(1000);
exitCts.Cancel();
}
else
{
Log.LogWarning($"Transfer to {TRANSFER_DESTINATION_SIP_URI} failed.");
}
}
else
{
Log.LogWarning("There is no active call to transfer.");
}
}
else if (keyProps.KeyChar == 'q')
{
// Quit application.
exitCts.Cancel();
}
}
}
catch (Exception excp)
{
SIPSorcery.Sys.Log.Logger.LogError($"Exception Key Press listener. {excp.Message}.");
}
});
// Ctrl-c will gracefully exit the call at any point.
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
exitCts.Cancel();
};
// Wait for a signal saying the call failed, was cancelled with ctrl-c or completed.
exitCts.Token.WaitHandle.WaitOne();
#region Cleanup.
Log.LogInformation("Exiting...");
rtpAVSession?.Close("app exit");
if (userAgent != null)
{
if (userAgent.IsCallActive)
{
Log.LogInformation($"Hanging up call to {userAgent?.CallDescriptor?.To}.");
userAgent.Hangup();
}
// Give the BYE or CANCEL request time to be transmitted.
Log.LogInformation("Waiting 1s for call to clean up...");
Task.Delay(1000).Wait();
}
SIPSorcery.Net.DNSManager.Stop();
if (sipTransport != null)
{
Log.LogInformation("Shutting down SIP transport...");
sipTransport.Shutdown();
}
#endregion
}
/// <summary>
/// Adds a console logger. Can be omitted if internal SIPSorcery debug and warning messages are not required.
/// </summary>
private static void AddConsoleLogger()
{
var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
var loggerConfig = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Is(Serilog.Events.LogEventLevel.Debug)
.WriteTo.Console()
.CreateLogger();
loggerFactory.AddSerilog(loggerConfig);
SIPSorcery.Sys.Log.LoggerFactory = loggerFactory;
}
/// <summary>
/// Enable detailed SIP log messages.
/// </summary>
private static void EnableTraceLogs(SIPTransport sipTransport)
{
sipTransport.SIPRequestInTraceEvent += (localEP, remoteEP, req) =>
{
Log.LogDebug($"Request received: {localEP}<-{remoteEP}");
Log.LogDebug(req.ToString());
};
sipTransport.SIPRequestOutTraceEvent += (localEP, remoteEP, req) =>
{
Log.LogDebug($"Request sent: {localEP}->{remoteEP}");
Log.LogDebug(req.ToString());
};
sipTransport.SIPResponseInTraceEvent += (localEP, remoteEP, resp) =>
{
Log.LogDebug($"Response received: {localEP}<-{remoteEP}");
Log.LogDebug(resp.ToString());
};
sipTransport.SIPResponseOutTraceEvent += (localEP, remoteEP, resp) =>
{
Log.LogDebug($"Response sent: {localEP}->{remoteEP}");
Log.LogDebug(resp.ToString());
};
sipTransport.SIPRequestRetransmitTraceEvent += (tx, req, count) =>
{
Log.LogDebug($"Request retransmit {count} for request {req.StatusLine}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
};
sipTransport.SIPResponseRetransmitTraceEvent += (tx, resp, count) =>
{
Log.LogDebug($"Response retransmit {count} for response {resp.ShortDescription}, initial transmit {DateTime.Now.Subtract(tx.InitialTransmit).TotalSeconds.ToString("0.###")}s ago.");
};
}
}
}
| 47.728435 | 198 | 0.497423 | [
"BSD-3-Clause"
] | Yitzchok/sipsorcery | examples/SIPExamples/CallHoldAndTransfer/Program.cs | 14,941 | C# |
// Generated by Haxe 4.1.3
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds {
public class BalancedTree<K, V> : global::haxe.lang.HxObject, global::haxe.ds.BalancedTree, global::haxe.IMap<K, V> {
public BalancedTree(global::haxe.lang.EmptyObject empty) {
}
public BalancedTree() {
global::haxe.ds.BalancedTree<object, object>.__hx_ctor_haxe_ds_BalancedTree<K, V>(((global::haxe.ds.BalancedTree<K, V>) (this) ));
}
protected static void __hx_ctor_haxe_ds_BalancedTree<K_c, V_c>(global::haxe.ds.BalancedTree<K_c, V_c> __hx_this) {
}
public static object __hx_cast<K_c_c, V_c_c>(global::haxe.ds.BalancedTree me) {
return ( (( me != null )) ? (me.haxe_ds_BalancedTree_cast<K_c_c, V_c_c>()) : default(object) );
}
public virtual object haxe_ds_BalancedTree_cast<K_c, V_c>() {
if (( global::haxe.lang.Runtime.eq(typeof(K), typeof(K_c)) && global::haxe.lang.Runtime.eq(typeof(V), typeof(V_c)) )) {
return this;
}
global::haxe.ds.BalancedTree<K_c, V_c> new_me = new global::haxe.ds.BalancedTree<K_c, V_c>(global::haxe.lang.EmptyObject.EMPTY);
global::Array<string> fields = global::Reflect.fields(this);
int i = 0;
while (( i < fields.length )) {
string field = fields[i++];
global::Reflect.setField(new_me, field, global::Reflect.field(this, field));
}
return new_me;
}
public virtual object haxe_IMap_cast<K_c, V_c>() {
return this.haxe_ds_BalancedTree_cast<K, V>();
}
public global::haxe.ds.TreeNode<K, V> root;
public virtual void @set(K key, V @value) {
this.root = this.setLoop(key, @value, this.root);
}
public virtual global::haxe.lang.Null<V> @get(K key) {
global::haxe.ds.TreeNode<K, V> node = this.root;
while (( node != null )) {
int c = this.compare(key, node.key);
if (( c == 0 )) {
return new global::haxe.lang.Null<V>(node.@value, true);
}
if (( c < 0 )) {
node = node.left;
}
else {
node = node.right;
}
}
return default(global::haxe.lang.Null<V>);
}
public virtual global::haxe.ds.TreeNode<K, V> setLoop(K k, V v, global::haxe.ds.TreeNode<K, V> node) {
if (( node == null )) {
return new global::haxe.ds.TreeNode<K, V>(null, k, v, null, default(global::haxe.lang.Null<int>));
}
int c = this.compare(k, node.key);
if (( c == 0 )) {
return new global::haxe.ds.TreeNode<K, V>(node.left, k, v, node.right, new global::haxe.lang.Null<int>(( (( node == null )) ? (0) : (node._height) ), true));
}
else if (( c < 0 )) {
global::haxe.ds.TreeNode<K, V> nl = this.setLoop(k, v, node.left);
return this.balance(nl, node.key, node.@value, node.right);
}
else {
global::haxe.ds.TreeNode<K, V> nr = this.setLoop(k, v, node.right);
return this.balance(node.left, node.key, node.@value, nr);
}
}
public virtual global::haxe.ds.TreeNode<K, V> balance(global::haxe.ds.TreeNode<K, V> l, K k, V v, global::haxe.ds.TreeNode<K, V> r) {
unchecked {
int hl = ( (( l == null )) ? (0) : (l._height) );
int hr = ( (( r == null )) ? (0) : (r._height) );
if (( hl > ( hr + 2 ) )) {
global::haxe.ds.TreeNode<K, V> _this = l.left;
global::haxe.ds.TreeNode<K, V> _this1 = l.right;
if (( (( (( _this == null )) ? (0) : (_this._height) )) >= (( (( _this1 == null )) ? (0) : (_this1._height) )) )) {
return new global::haxe.ds.TreeNode<K, V>(l.left, l.key, l.@value, new global::haxe.ds.TreeNode<K, V>(l.right, k, v, r, default(global::haxe.lang.Null<int>)), default(global::haxe.lang.Null<int>));
}
else {
return new global::haxe.ds.TreeNode<K, V>(new global::haxe.ds.TreeNode<K, V>(l.left, l.key, l.@value, l.right.left, default(global::haxe.lang.Null<int>)), l.right.key, l.right.@value, new global::haxe.ds.TreeNode<K, V>(l.right.right, k, v, r, default(global::haxe.lang.Null<int>)), default(global::haxe.lang.Null<int>));
}
}
else if (( hr > ( hl + 2 ) )) {
global::haxe.ds.TreeNode<K, V> _this2 = r.right;
global::haxe.ds.TreeNode<K, V> _this3 = r.left;
if (( (( (( _this2 == null )) ? (0) : (_this2._height) )) > (( (( _this3 == null )) ? (0) : (_this3._height) )) )) {
return new global::haxe.ds.TreeNode<K, V>(new global::haxe.ds.TreeNode<K, V>(l, k, v, r.left, default(global::haxe.lang.Null<int>)), r.key, r.@value, r.right, default(global::haxe.lang.Null<int>));
}
else {
return new global::haxe.ds.TreeNode<K, V>(new global::haxe.ds.TreeNode<K, V>(l, k, v, r.left.left, default(global::haxe.lang.Null<int>)), r.left.key, r.left.@value, new global::haxe.ds.TreeNode<K, V>(r.left.right, r.key, r.@value, r.right, default(global::haxe.lang.Null<int>)), default(global::haxe.lang.Null<int>));
}
}
else {
return new global::haxe.ds.TreeNode<K, V>(l, k, v, r, new global::haxe.lang.Null<int>(( (( (( hl > hr )) ? (hl) : (hr) )) + 1 ), true));
}
}
}
public virtual int compare(K k1, K k2) {
return global::Reflect.compare<K>(global::haxe.lang.Runtime.genericCast<K>(k1), global::haxe.lang.Runtime.genericCast<K>(k2));
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties) {
unchecked {
switch (hash) {
case 1269755426:
{
this.root = ((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (@value) ))) );
return @value;
}
default:
{
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) {
unchecked {
switch (hash) {
case 57219237:
{
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(this, "compare", 57219237)) );
}
case 596483356:
{
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(this, "balance", 596483356)) );
}
case 222029606:
{
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(this, "setLoop", 222029606)) );
}
case 5144726:
{
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(this, "get", 5144726)) );
}
case 5741474:
{
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(this, "set", 5741474)) );
}
case 1269755426:
{
return this.root;
}
default:
{
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
}
public override object __hx_invokeField(string field, int hash, object[] dynargs) {
unchecked {
switch (hash) {
case 57219237:
{
return this.compare(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]), global::haxe.lang.Runtime.genericCast<K>(dynargs[1]));
}
case 596483356:
{
return this.balance(((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (dynargs[0]) ))) ), global::haxe.lang.Runtime.genericCast<K>(dynargs[1]), global::haxe.lang.Runtime.genericCast<V>(dynargs[2]), ((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (dynargs[3]) ))) ));
}
case 222029606:
{
return this.setLoop(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]), global::haxe.lang.Runtime.genericCast<V>(dynargs[1]), ((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (dynargs[2]) ))) ));
}
case 5144726:
{
return (this.@get(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]))).toDynamic();
}
case 5741474:
{
this.@set(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]), global::haxe.lang.Runtime.genericCast<V>(dynargs[1]));
break;
}
default:
{
return base.__hx_invokeField(field, hash, dynargs);
}
}
return null;
}
}
public override void __hx_getFields(global::Array<string> baseArr) {
baseArr.push("root");
base.__hx_getFields(baseArr);
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds {
[global::haxe.lang.GenericInterface(typeof(global::haxe.ds.BalancedTree<object, object>))]
public interface BalancedTree : global::haxe.lang.IHxObject, global::haxe.lang.IGenericObject {
object haxe_ds_BalancedTree_cast<K_c, V_c>();
object haxe_IMap_cast<K_c, V_c>();
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds {
public class TreeNode<K, V> : global::haxe.lang.HxObject, global::haxe.ds.TreeNode {
public TreeNode(global::haxe.lang.EmptyObject empty) {
}
public TreeNode(global::haxe.ds.TreeNode<K, V> l, K k, V v, global::haxe.ds.TreeNode<K, V> r, global::haxe.lang.Null<int> h) {
global::haxe.ds.TreeNode<object, object>.__hx_ctor_haxe_ds_TreeNode<K, V>(((global::haxe.ds.TreeNode<K, V>) (this) ), ((global::haxe.ds.TreeNode<K, V>) (l) ), global::haxe.lang.Runtime.genericCast<K>(k), global::haxe.lang.Runtime.genericCast<V>(v), ((global::haxe.ds.TreeNode<K, V>) (r) ), ((global::haxe.lang.Null<int>) (h) ));
}
protected static void __hx_ctor_haxe_ds_TreeNode<K_c, V_c>(global::haxe.ds.TreeNode<K_c, V_c> __hx_this, global::haxe.ds.TreeNode<K_c, V_c> l, K_c k, V_c v, global::haxe.ds.TreeNode<K_c, V_c> r, global::haxe.lang.Null<int> h) {
unchecked {
int h1 = ( ( ! (h.hasValue) ) ? (-1) : ((h).@value) );
__hx_this.left = l;
__hx_this.key = k;
__hx_this.@value = v;
__hx_this.right = r;
if (( h1 == -1 )) {
int tmp = default(int);
global::haxe.ds.TreeNode<K_c, V_c> _this = __hx_this.left;
global::haxe.ds.TreeNode<K_c, V_c> _this1 = __hx_this.right;
if (( (( (( _this == null )) ? (0) : (_this._height) )) > (( (( _this1 == null )) ? (0) : (_this1._height) )) )) {
global::haxe.ds.TreeNode<K_c, V_c> _this2 = __hx_this.left;
tmp = ( (( _this2 == null )) ? (0) : (_this2._height) );
}
else {
global::haxe.ds.TreeNode<K_c, V_c> _this3 = __hx_this.right;
tmp = ( (( _this3 == null )) ? (0) : (_this3._height) );
}
__hx_this._height = ( tmp + 1 );
}
else {
__hx_this._height = h1;
}
}
}
public static object __hx_cast<K_c_c, V_c_c>(global::haxe.ds.TreeNode me) {
return ( (( me != null )) ? (me.haxe_ds_TreeNode_cast<K_c_c, V_c_c>()) : default(object) );
}
public virtual object haxe_ds_TreeNode_cast<K_c, V_c>() {
if (( global::haxe.lang.Runtime.eq(typeof(K), typeof(K_c)) && global::haxe.lang.Runtime.eq(typeof(V), typeof(V_c)) )) {
return this;
}
global::haxe.ds.TreeNode<K_c, V_c> new_me = new global::haxe.ds.TreeNode<K_c, V_c>(global::haxe.lang.EmptyObject.EMPTY);
global::Array<string> fields = global::Reflect.fields(this);
int i = 0;
while (( i < fields.length )) {
string field = fields[i++];
global::Reflect.setField(new_me, field, global::Reflect.field(this, field));
}
return new_me;
}
public global::haxe.ds.TreeNode<K, V> left;
public global::haxe.ds.TreeNode<K, V> right;
public K key;
public V @value;
public int _height;
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties) {
unchecked {
switch (hash) {
case 1891834246:
{
this._height = ((int) (@value) );
return @value;
}
case 834174833:
{
this.@value = global::haxe.lang.Runtime.genericCast<V>(((object) (@value) ));
return ((double) (global::haxe.lang.Runtime.toDouble(((object) (@value) ))) );
}
case 5343647:
{
this.key = global::haxe.lang.Runtime.genericCast<K>(((object) (@value) ));
return ((double) (global::haxe.lang.Runtime.toDouble(((object) (@value) ))) );
}
default:
{
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties) {
unchecked {
switch (hash) {
case 1891834246:
{
this._height = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
return @value;
}
case 834174833:
{
this.@value = global::haxe.lang.Runtime.genericCast<V>(@value);
return @value;
}
case 5343647:
{
this.key = global::haxe.lang.Runtime.genericCast<K>(@value);
return @value;
}
case 1768164316:
{
this.right = ((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (@value) ))) );
return @value;
}
case 1202718727:
{
this.left = ((global::haxe.ds.TreeNode<K, V>) (global::haxe.ds.TreeNode<object, object>.__hx_cast<K, V>(((global::haxe.ds.TreeNode) (@value) ))) );
return @value;
}
default:
{
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) {
unchecked {
switch (hash) {
case 1891834246:
{
return this._height;
}
case 834174833:
{
return this.@value;
}
case 5343647:
{
return this.key;
}
case 1768164316:
{
return this.right;
}
case 1202718727:
{
return this.left;
}
default:
{
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties) {
unchecked {
switch (hash) {
case 1891834246:
{
return ((double) (this._height) );
}
case 834174833:
{
return ((double) (global::haxe.lang.Runtime.toDouble(((object) (this.@value) ))) );
}
case 5343647:
{
return ((double) (global::haxe.lang.Runtime.toDouble(((object) (this.key) ))) );
}
default:
{
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
}
public override void __hx_getFields(global::Array<string> baseArr) {
baseArr.push("_height");
baseArr.push("value");
baseArr.push("key");
baseArr.push("right");
baseArr.push("left");
base.__hx_getFields(baseArr);
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.ds {
[global::haxe.lang.GenericInterface(typeof(global::haxe.ds.TreeNode<object, object>))]
public interface TreeNode : global::haxe.lang.IHxObject, global::haxe.lang.IGenericObject {
object haxe_ds_TreeNode_cast<K_c, V_c>();
}
}
| 28.613383 | 414 | 0.592504 | [
"MIT"
] | NNNIC/haxe-test | test_1/m7_msbuild/TestApp/TestDll/src/src/haxe/ds/BalancedTree.cs | 15,394 | C# |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Lucene.Net.Analysis.Tokenattributes;
namespace Lucene.Net.Analysis.Th
{
/*
* {@link TokenFilter} that use {@link java.text.BreakIterator} to break each
* Token that is Thai into separate Token(s) for each Thai word.
* <p>WARNING: this filter may not work correctly with all JREs.
* It is known to work with Sun/Oracle and Harmony JREs.
*/
public sealed class ThaiWordFilter : TokenFilter
{
//private BreakIterator breaker = null;
private ITermAttribute termAtt;
private IOffsetAttribute offsetAtt;
private State thaiState = null;
// I'm sure this is far slower than if we just created a simple UnicodeBlock class
// considering this is used on a single char, we have to create a new string for it,
// via ToString(), so we can then run a costly(?) regex on it. Yikes.
private Regex _isThaiRegex = new Regex(@"\p{IsThai}", RegexOptions.Compiled);
public ThaiWordFilter(TokenStream input)
: base(input)
{
throw new NotSupportedException("PORT ISSUES");
//breaker = BreakIterator.getWordInstance(new Locale("th"));
//termAtt = AddAttribute<TermAttribute>();
//offsetAtt = AddAttribute<OffsetAttribute>();
}
public sealed override bool IncrementToken()
{
//int end;
//if (thaiState != null)
//{
// int start = breaker.Current();
// end = breaker.next();
// if (end != BreakIterator.DONE)
// {
// RestoreState(thaiState);
// termAtt.SetTermBuffer(termAtt.TermBuffer(), start, end - start);
// offsetAtt.SetOffset(offsetAtt.StartOffset() + start, offsetAtt.StartOffset() + end);
// return true;
// }
// thaiState = null;
//}
//if (input.IncrementToken() == false || termAtt.TermLength() == 0)
// return false;
//String text = termAtt.Term();
//if (!_isThaiRegex.Match(new string(new[]{text[0]})).Success)
//{
// termAtt.SetTermBuffer(text.ToLower());
// return true;
//}
//thaiState = CaptureState();
//breaker.SetText(text);
//end = breaker.next();
//if (end != BreakIterator.DONE)
//{
// termAtt.SetTermBuffer(text, 0, end);
// offsetAtt.SetOffset(offsetAtt.StartOffset(), offsetAtt.StartOffset() + end);
// return true;
//}
return false;
}
public override void Reset()
{
base.Reset();
thaiState = null;
}
}
}
| 36.566038 | 107 | 0.574303 | [
"Apache-2.0"
] | Anomalous-Software/Lucene.NET | src/contrib/Analyzers/Th/ThaiWordFilter.cs | 3,876 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace HelloDynamo.Stats
{
/// <summary>
/// Interaction logic for StatsWindow.xaml
/// </summary>
public partial class StatsWindow : Window
{
public StatsWindow()
{
InitializeComponent();
}
}
}
| 21.75 | 46 | 0.70936 | [
"MIT"
] | DynamoDS/DeveloperWorkshop | 2018/Developer/CBW227911 - Control Dynamo from the Web/Exercises/HelloDynamo/8-Hello-UI/HelloDynamo/Stats/StatsWindow.xaml.cs | 611 | C# |
#if NETFX_CORE && !WinRT
#define WinRT
#endif
namespace Caliburn.Micro
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Generic extension methods used by the framework.
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Get's the name of the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>The assembly's name.</returns>
public static string GetAssemblyName(this Assembly assembly)
{
return assembly.FullName.Remove(assembly.FullName.IndexOf(','));
}
/// <summary>
/// Gets all the attributes of a particular type.
/// </summary>
/// <typeparam name="T">The type of attributes to get.</typeparam>
/// <param name="member">The member to inspect for attributes.</param>
/// <param name="inherit">Whether or not to search for inherited attributes.</param>
/// <returns>The list of attributes found.</returns>
public static IEnumerable<T> GetAttributes<T>(this MemberInfo member, bool inherit)
{
#if WinRT
return member.GetCustomAttributes(inherit).OfType<T>();
#else
return Attribute.GetCustomAttributes(member, inherit).OfType<T>();
#endif
}
/// <summary>
/// Applies the action to each element in the list.
/// </summary>
/// <typeparam name="T">The enumerable item's type.</typeparam>
/// <param name="enumerable">The elements to enumerate.</param>
/// <param name="action">The action to apply to each item in the list.</param>
public static void Apply<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (var item in enumerable)
{
action(item);
}
}
/// <summary>
/// Converts an expression into a <see cref="MemberInfo"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>The member info.</returns>
public static MemberInfo GetMemberInfo(this Expression expression)
{
var lambda = (LambdaExpression)expression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
{
memberExpression = (MemberExpression)lambda.Body;
}
return memberExpression.Member;
}
#if WINDOWS_PHONE && !WP8
//Method missing in WP7.1 Linq
/// <summary>
/// Merges two sequences by using the specified predicate function.
/// </summary>
/// <typeparam name="TFirst">The type of the elements of the first input sequence.</typeparam>
/// <typeparam name="TSecond">The type of the elements of the second input sequence.</typeparam>
/// <typeparam name="TResult">The type of the elements of the result sequence.</typeparam>
/// <param name="first">The first sequence to merge.</param>
/// <param name="second">The second sequence to merge.</param>
/// <param name="resultSelector"> A function that specifies how to merge the elements from the two sequences.</param>
/// <returns>An System.Collections.Generic.IEnumerable<T> that contains merged elements of two input sequences.</returns>
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector) {
if (first == null) {
throw new ArgumentNullException("first");
}
if (second == null) {
throw new ArgumentNullException("second");
}
if (resultSelector == null) {
throw new ArgumentNullException("resultSelector");
}
var enumFirst = first.GetEnumerator();
var enumSecond = second.GetEnumerator();
while (enumFirst.MoveNext() && enumSecond.MoveNext()) {
yield return resultSelector(enumFirst.Current, enumSecond.Current);
}
}
#endif
#if WinRT
/// <summary>
/// Gets a collection of the public types defined in this assembly that are visible outside the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A collection of the public types defined in this assembly that are visible outside the assembly.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static IEnumerable<Type> GetExportedTypes(this Assembly assembly) {
if (assembly == null)
throw new ArgumentNullException("assembly");
return assembly.ExportedTypes;
}
/// <summary>
/// Returns a value that indicates whether the specified type can be assigned to the current type.
/// </summary>
/// <param name="target">The target type</param>
/// <param name="type">The type to check.</param>
/// <returns>true if the specified type can be assigned to this type; otherwise, false.</returns>
public static bool IsAssignableFrom(this Type target, Type type) {
return target.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo());
}
#endif
}
}
| 38.697183 | 176 | 0.628207 | [
"Apache-2.0"
] | alexmg/IocPerformance | IocPerformance/Caliburn.Micro/ExtensionMethods.cs | 5,497 | C# |
// Project: Aguafrommars/TheIdServer
// Copyright (c) 2021 @Olivier Lefebvre
using System;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace Aguacongas.IdentityServer.KeysRotation.MongoDb
{
public class MongoCollectionWrapper<TKey>
where TKey : IXmlKey
{
public IMongoCollection<TKey> Collection { get; }
public IMongoQueryable<TKey> Queryable { get; }
public MongoCollectionWrapper(IMongoCollection<TKey> collection)
:this(collection, collection.AsQueryable())
{
}
public MongoCollectionWrapper(IMongoCollection<TKey> collection, IMongoQueryable<TKey> queryable)
{
Collection = collection ?? throw new ArgumentNullException(nameof(collection));
Queryable = queryable ?? throw new ArgumentNullException(nameof(queryable));
}
}
}
| 30.821429 | 105 | 0.691773 | [
"Apache-2.0"
] | Aguafrommars/TheIdServer | src/IdentityServer/Aguacongas.IdentityServer.KeysRotation/MongoDb/MongoDatabaseWrapper.cs | 865 | C# |
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
using System;
using System.Numerics;
using System.ComponentModel;
namespace SC1prosumer
{
public class Prosumer : SmartContract
{
// token is the energy, 1 token = 1 kwh
public static readonly byte[] Owner = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y".ToScriptHash();
// neo assetId: scriptHash
public static byte[] neoAssetId = { 197, 111, 51, 252, 110, 207, 205, 12, 34, 92, 74, 179, 86, 254, 229, 147, 144, 175, 133, 96, 190, 14, 147, 15, 174, 190, 116, 166, 218, 255, 124, 155 };
public delegate void MyAction<T, T1, T2, T3>(T p0, T1 p1, T2 p2, T3 p3);
public static event MyAction<byte[], byte[], int, int> Transferred;
public static Object Main(string operation, params object[] args)
{
if (Runtime.Trigger == TriggerType.Verification)
{
if (Owner.Length == 20)
{
return Runtime.CheckWitness(Owner);
}
else if (Owner.Length == 33)
{
byte[] signature = operation.AsByteArray();
return VerifySignature(signature, Owner);
}
}
else if (Runtime.Trigger == TriggerType.Application)
{
if (operation == "sellSurplus")
{
// params: from, to, price, surplus volume
if (args.Length != 4) return false;
byte[] from = (byte[])args[0];
byte[] to = (byte[])args[1];
int price = (int)args[2];
int volume = (int)args[3];
return SellSurplus(from, to, price, volume);
}
if (operation == "txHistory")
{
// tbd
}
if (operation == "checksurplus")
{
// params: from
if (args.Length != 1) return false;
byte[] from = (byte[])args[0];
return CheckSurplus(from);
}
if (operation == "balanceOf")
{
if (args.Length != 1) return false;
byte[] from = (byte[])args[0];
return BalanceOf(from);
}
}
return false;
// make sure this is the client
//if (!VerifySignature(signature, client)) return false;
// get account of agent ad client
//Account ageAccount = Blockchain.GetAccount(agent);
// get balance (surplus) of agent's account
//long balance = ageAccount.GetBalance(assetId);
// see if there's enough surplus
//if (balance > volume * 100000000) return true;
//else return false;
// create contract -- tbd
}
public static bool SellSurplus(byte[] from, byte[] to, int price, int volume)
{
if (price < 0) return false;
if (volume < 0) return false;
if (!Runtime.CheckWitness(from)) return false;
if (from == to) return true;
int amount = price * volume;
// substract surplus volume from sc1 user(seller)
BigInteger from_volume = CheckSurplus(from);
if (volume > from_volume) return false;
if (from_volume == volume)
Storage.Delete(Storage.CurrentContext, from);
else
Storage.Put(Storage.CurrentContext, from, from_volume - volume);
// add balance to seller
BigInteger from_balance = Update_balance(from, amount);
// add surplus volume to buyer
BigInteger to_volume = Storage.Get(Storage.CurrentContext, to).AsBigInteger();
Storage.Put(Storage.CurrentContext, to, to_volume + volume);
// substract balance of buyer
BigInteger to_balance = Update_balance(to, -amount);
Transferred(from, to, price, volume);
return true;
}
public static BigInteger CheckSurplus(byte[] from)
{
return Storage.Get(Storage.CurrentContext, from).AsBigInteger();
}
public static BigInteger BalanceOf (byte[] from)
{
Account account = Blockchain.GetAccount(from);
long balance = account.GetBalance(neoAssetId);
return balance;
}
public static BigInteger Update_balance (byte[] addr, int amount)
{
BigInteger updated_balance = BalanceOf(addr) + amount;
return updated_balance;
}
}
}
| 37.890625 | 196 | 0.521856 | [
"MIT"
] | jinhu94/NeoEvePlus | SC1prosumer/SC1prosumer/Prosumer.cs | 4,852 | C# |
using Autofac;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Polly;
using Polly.Retry;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
{
public class EventBusRabbitMQ : IEventBus, IDisposable
{
const string BROKER_NAME = "eshop_event_bus";
private readonly IRabbitMQPersistentConnection _persistentConnection;
private readonly ILogger<EventBusRabbitMQ> _logger;
private readonly IEventBusSubscriptionsManager _subsManager;
private readonly ILifetimeScope _autofac;
private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus";
private readonly int _retryCount;
private IModel _consumerChannel;
private string _queueName;
public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger<EventBusRabbitMQ> logger,
ILifetimeScope autofac, IEventBusSubscriptionsManager subsManager, string queueName = null, int retryCount = 5)
{
_persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
_queueName = queueName;
_consumerChannel = CreateConsumerChannel();
_autofac = autofac;
_retryCount = retryCount;
_subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
}
private void SubsManager_OnEventRemoved(object sender, string eventName)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
using (var channel = _persistentConnection.CreateModel())
{
channel.QueueUnbind(queue: _queueName,
exchange: BROKER_NAME,
routingKey: eventName);
if (_subsManager.IsEmpty)
{
_queueName = string.Empty;
_consumerChannel.Close();
}
}
}
public void Publish(IntegrationEvent @event)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
var policy = RetryPolicy.Handle<BrokerUnreachableException>()
.Or<SocketException>()
.WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
{
_logger.LogWarning(ex.ToString());
});
using (var channel = _persistentConnection.CreateModel())
{
var eventName = @event.GetType()
.Name;
channel.ExchangeDeclare(exchange: BROKER_NAME,
type: "direct");
var message = JsonConvert.SerializeObject(@event);
var body = Encoding.UTF8.GetBytes(message);
policy.Execute(() =>
{
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; // persistent
channel.BasicPublish(exchange: BROKER_NAME,
routingKey: eventName,
mandatory:true,
basicProperties: properties,
body: body);
});
}
}
public void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
DoInternalSubscription(eventName);
_subsManager.AddDynamicSubscription<TH>(eventName);
}
public void Subscribe<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>
{
var eventName = _subsManager.GetEventKey<T>();
DoInternalSubscription(eventName);
_subsManager.AddSubscription<T, TH>();
}
private void DoInternalSubscription(string eventName)
{
var containsKey = _subsManager.HasSubscriptionsForEvent(eventName);
if (!containsKey)
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
using (var channel = _persistentConnection.CreateModel())
{
channel.QueueBind(queue: _queueName,
exchange: BROKER_NAME,
routingKey: eventName);
}
}
}
public void Unsubscribe<T, TH>()
where TH : IIntegrationEventHandler<T>
where T : IntegrationEvent
{
_subsManager.RemoveSubscription<T, TH>();
}
public void UnsubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
_subsManager.RemoveDynamicSubscription<TH>(eventName);
}
public void Dispose()
{
if (_consumerChannel != null)
{
_consumerChannel.Dispose();
}
_subsManager.Clear();
}
private IModel CreateConsumerChannel()
{
if (!_persistentConnection.IsConnected)
{
_persistentConnection.TryConnect();
}
var channel = _persistentConnection.CreateModel();
channel.ExchangeDeclare(exchange: BROKER_NAME,
type: "direct");
channel.QueueDeclare(queue: _queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += async (model, ea) =>
{
var eventName = ea.RoutingKey;
var message = Encoding.UTF8.GetString(ea.Body);
await ProcessEvent(eventName, message);
channel.BasicAck(ea.DeliveryTag,multiple:false);
};
channel.BasicConsume(queue: _queueName,
autoAck: false,
consumer: consumer);
channel.CallbackException += (sender, ea) =>
{
_consumerChannel.Dispose();
_consumerChannel = CreateConsumerChannel();
};
return channel;
}
private async Task ProcessEvent(string eventName, string message)
{
if (_subsManager.HasSubscriptionsForEvent(eventName))
{
using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
{
var subscriptions = _subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions)
{
if (subscription.IsDynamic)
{
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
dynamic eventData = JObject.Parse(message);
await handler.Handle(eventData);
}
else
{
var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var handler = scope.ResolveOptional(subscription.HandlerType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
}
}
}
}
}
}
}
| 36.797468 | 125 | 0.549249 | [
"MIT"
] | 07101994/eShopOnContainers | src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.cs | 8,723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using SemVer;
namespace Tests.Framework
{
public class SkipVersionAttribute : Attribute
{
public IList<Range> Ranges { get; }
public SkipVersionAttribute(string skipVersionRangesSeparatedByComma, string reason)
{
this.Ranges = skipVersionRangesSeparatedByComma.Split(',')
.Select(r => new Range(r))
.ToList();
}
}
}
| 20.35 | 86 | 0.739558 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Tests/Framework/XUnitPlumbing/SkipVersionAttribute.cs | 407 | C# |
using System;
using System.IO;
namespace Dm
{
public class DmBLobStream : Stream
{
private DmBlob m_BLob;
private bool m_CanRead = true;
private bool m_CanSeek = true;
private bool m_CanTimeOut = true;
private bool m_CanWrite = true;
private bool m_Closed;
private long m_CurPos = 1L;
private int m_ReadTimeout;
private int m_WriteTimeout;
private const int STREAM_CLOSED = -1;
public override bool CanRead => m_CanRead;
public override bool CanSeek => m_CanSeek;
public override bool CanTimeout => m_CanTimeOut;
public override bool CanWrite => m_CanWrite;
public override long Length => m_BLob.Length();
public override long Position
{
get
{
return m_CurPos;
}
set
{
m_CurPos = Position;
}
}
public override int ReadTimeout
{
get
{
return m_ReadTimeout;
}
set
{
ReadTimeout = m_ReadTimeout;
}
}
public override int WriteTimeout
{
get
{
return m_WriteTimeout;
}
set
{
m_WriteTimeout = WriteTimeout;
}
}
public DmBLobStream(DmBlob bLob)
{
m_BLob = bLob;
}
public bool StreamCheck()
{
if (m_Closed)
{
return true;
}
return false;
}
public override void Close()
{
m_CurPos = 0L;
m_Closed = true;
}
protected override void Dispose(bool disposing)
{
}
public override void Flush()
{
DmError.ThrowUnsupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (StreamCheck())
{
return -1;
}
byte[] bytes = m_BLob.GetBytes(m_CurPos, count);
m_CurPos += bytes.Length;
Array.Copy(bytes, 0, buffer, offset, bytes.Length);
return bytes.Length;
}
public override int ReadByte()
{
if (StreamCheck())
{
return -1;
}
byte[] bytes = m_BLob.GetBytes(m_CurPos, 1);
if (bytes == null)
{
return -1;
}
m_CurPos += bytes.Length;
return bytes[0];
}
public override long Seek(long offset, SeekOrigin origin)
{
if (StreamCheck())
{
return -1L;
}
long num = m_BLob.Length();
long num2 = 0L;
switch (origin)
{
case SeekOrigin.Begin:
num2 = 1L;
break;
case SeekOrigin.Current:
num2 = m_CurPos;
break;
case SeekOrigin.End:
num2 = num;
break;
default:
return -1L;
}
if (num2 + offset >= num)
{
m_CurPos = num - 1;
}
else if (num2 + offset < 0)
{
m_CurPos = 0L;
}
else
{
m_CurPos = num2 + offset;
}
return m_CurPos;
}
public override void SetLength(long value)
{
if (!StreamCheck())
{
m_BLob.truncate(value);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (m_Closed)
{
DmError.ThrowDmException(DmErrorDefinition.ECNET_RESULTSET_CLOSED);
}
if (offset + count > buffer.Length)
{
DmError.ThrowDmException(DmErrorDefinition.ECNET_INVALID_LENGTH_OR_OFFSET);
return;
}
m_BLob.SetBytes(m_CurPos, ref buffer, offset, count);
m_CurPos += count;
}
}
}
| 15.884817 | 79 | 0.623599 | [
"MIT"
] | dmdbms/DmProvider | src/DmProvider/Dm/DmBLobStream.cs | 3,034 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Injectify")]
namespace Injectify.Abstractions
{
/// <summary>
/// Annotates class for injecting members.
/// </summary>
internal interface IInjectable
{
/// <summary>
/// Bootstrap class members marked using Inject attribute.
/// </summary>
/// <typeparam name="TPage">Page type.</typeparam>
/// <typeparam name="TServiceProvider">Service provider type.</typeparam>
/// <param name="context">Injection context for the page, including service provider with registered services and service selectors.</param>
void Bootstrap<TPage, TServiceProvider>(InjectionContext<TPage, TServiceProvider> context)
where TPage : class;
}
}
| 35.818182 | 148 | 0.675127 | [
"MIT"
] | vladhrapov/injectify | packages/Injectify.Abstractions/Injectify.Abstractions/IInjectable.cs | 790 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReliefLib
{
public class ReliefConsistent : Relief
{
protected override int GetProcessedIndex(Random r, int i)
{
return i;
}
}
}
| 16.421053 | 59 | 0.75641 | [
"MIT"
] | jakubsenk/ReliefTool | Relief/ReliefConsistent.cs | 314 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
//////////////////////////////////////////////////////////////////////
// This file contains parts of the testing harness.
// You should not modify anything in this file.
// The tasks themselves can be found in Tasks.qs file.
//////////////////////////////////////////////////////////////////////
using Microsoft.Quantum.Simulation.XUnit;
using Microsoft.Quantum.Simulation.Simulators;
using Xunit.Abstractions;
using System.Diagnostics;
namespace Quantum.Kata.CHSHGame
{
public class TestSuiteRunner
{
private readonly ITestOutputHelper output;
public TestSuiteRunner(ITestOutputHelper output)
{
this.output = output;
}
/// <summary>
/// This driver will run all Q# tests (operations named "...Test")
/// that belong to namespace Quantum.Kata.CHSHGame.
/// </summary>
[OperationDriver(TestNamespace = "Quantum.Kata.CHSHGame")]
public void TestTarget(TestOperation op)
{
using (var sim = new QuantumSimulator())
{
// OnLog defines action(s) performed when Q# test calls function Message
sim.OnLog += (msg) => { output.WriteLine(msg); };
sim.OnLog += (msg) => { Debug.WriteLine(msg); };
op.TestOperationRunner(sim);
}
}
}
}
| 33.604651 | 88 | 0.561938 | [
"MIT"
] | 0AdityaD/QuantumKatas | CHSHGame/TestSuiteRunner.cs | 1,447 | C# |
using System;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using SharePointPnP.PowerShell.Commands.Base.PipeBinds;
using File = System.IO.File;
namespace SharePointPnP.PowerShell.Commands.Site
{
[Cmdlet(VerbsLifecycle.Install, "PnPSolution")]
[CmdletHelp("Installs a sandboxed solution to a site collection. WARNING! This method can delete your composed look gallery due to the method used to activate the solution. We recommend you to only to use this cmdlet if you are okay with that.",
Category = CmdletHelpCategory.Sites)]
[CmdletExample(
Code = @"PS:> Install-PnPSolution -PackageId c2f5b025-7c42-4d3a-b579-41da3b8e7254 -SourceFilePath mypackage.wsp",
Remarks = "Installs the package to the current site",
SortOrder = 1)]
public class InstallSolution : PnPSharePointCmdlet
{
[Parameter(Mandatory = true, HelpMessage="ID of the solution, from the solution manifest")]
public GuidPipeBind PackageId;
[Parameter(Mandatory = true, HelpMessage="Path to the sandbox solution package (.WSP) file")]
public string SourceFilePath;
[Parameter(Mandatory = false, HelpMessage="Optional major version of the solution, defaults to 1")]
public int MajorVersion = 1;
[Parameter(Mandatory = false, HelpMessage="Optional minor version of the solution, defaults to 0")]
public int MinorVersion = 0;
protected override void ExecuteCmdlet()
{
if (File.Exists(SourceFilePath))
{
ClientContext.Site.InstallSolution(PackageId.Id, SourceFilePath, MajorVersion, MinorVersion);
}
else
{
throw new Exception("File does not exist");
}
}
}
}
| 42.045455 | 249 | 0.687568 | [
"MIT"
] | Ashikpaul/PnP-PowerShell | Commands/Site/InstallSolution.cs | 1,852 | C# |
using System.Security.Claims;
using System;
namespace Notes.Extensions
{
public static class ClaimsPrincipalExtensions
{
/// <summary>
/// Extract username from principal.
/// </summary>
/// <param name="principal">The principal.</param>
/// <returns>The username.</returns>
public static string GetUserName(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirst(ClaimTypes.Name)?.Value;
}
/// <summary>
/// Extract the role from principal.
/// </summary>
/// <param name="principal">The principal.</param>
/// <returns>The role.</returns>
public static string GetUserRole(this ClaimsPrincipal principal)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
return principal.FindFirst(ClaimTypes.Role)?.Value;
}
}
} | 25.852941 | 66 | 0.704209 | [
"MIT"
] | virtualdreams/notes-core | src/Notes/Extensions/ClaimsPrincipalExtensions.cs | 879 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class MenuLogic : MonoBehaviour
{
UIDocument _menuDocument;
VisualElement _root;
public GameOfLife gameOfLife;
public GameOfLifeEditor gameOfLifeEditor;
Button _resumeButton;
Button _quitButton;
Slider _speedSlider;
Foldout _resolutionFoldout;
const int resolutionCount = 10;
List<ResolutionSelector> _resolutionSelectors = new List<ResolutionSelector>();
void Start()
{
_menuDocument = GetComponent<UIDocument>();
_root = _menuDocument.rootVisualElement;
_resumeButton = _root.Q<Button>("ResumeButton");
_quitButton = _root.Q<Button>("QuitButton");
_speedSlider = _root.Q<Slider>("SimSpeed");
_speedSlider.lowValue = 0.0f;
_speedSlider.highValue = 4.5f;
_speedSlider.value = Mathf.Log10(gameOfLife.settings.simulationSpeed);
_resolutionFoldout = _root.Q<Foldout>("ResolutionFoldout");
_resumeButton.clicked += Resume;
_quitButton.clicked += Quit;
InitResolutionFoldout();
Resume();
}
void InitResolutionFoldout()
{
for (int i = 0;i < resolutionCount;i++)
{
int res = (int)Mathf.Pow(2,i + 5);
Button button = new Button();
button.text = res.ToString();
button.AddToClassList("resolution_selector_button");
_resolutionFoldout.contentContainer.Add(button);
ResolutionSelector selector = new ResolutionSelector(this, res);
_resolutionSelectors.Add(selector);
button.clicked += selector.OnSelected;
}
_resolutionFoldout.text = gameOfLife.settings.resolution.ToString();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (_root.style.visibility == Visibility.Visible)
{
Resume();
}
else
{
Pause();
}
}
gameOfLife.settings.simulationSpeed = Mathf.Pow(10,_speedSlider.value);
}
void Resume()
{
gameOfLifeEditor.enabled = true;
_root.style.visibility = Visibility.Hidden;
}
void Pause()
{
gameOfLifeEditor.enabled = false;
_root.style.visibility = Visibility.Visible;
}
void Quit()
{
Application.Quit();
}
private class ResolutionSelector{
private MenuLogic _menu;
private int _resolution;
public ResolutionSelector(MenuLogic menu, int resolution)
{
_menu = menu;
_resolution = resolution;
}
public void OnSelected()
{
_menu.gameOfLife.settings.resolution = _resolution;
_menu._resolutionFoldout.text = _resolution.ToString();
_menu._resolutionFoldout.value = false;
}
}
}
| 28 | 83 | 0.613818 | [
"MIT"
] | Peter226/GPUGameOfLife | Assets/Scripts/MenuLogic.cs | 2,996 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Common.Logging;
namespace Rhino.Queues.Monitoring
{
public class InboundPerfomanceCounters : IInboundPerfomanceCounters
{
private readonly string instanceName;
public const string CATEGORY = "Rhino-Queues Inbound";
public const string ARRIVED_COUNTER_NAME = "Arrived Messages";
private readonly ILog logger = LogManager.GetLogger(typeof(InboundPerfomanceCounters));
public static IEnumerable<CounterCreationData> SupportedCounters()
{
yield return new CounterCreationData
{
CounterType = PerformanceCounterType.NumberOfItems32,
CounterName = ARRIVED_COUNTER_NAME,
CounterHelp = "Indicates the number of messages that have arrived in the queue but have not been received by the queue's client. Enable logging on the queue to get more detailed diagnostic information."
};
}
public static void AssertCountersExist()
{
if (!PerformanceCounterCategory.Exists(CATEGORY))
throw new ApplicationException(
string.Format(PerformanceCategoryCreator.CATEGORY_DOES_NOT_EXIST, CATEGORY));
}
public InboundPerfomanceCounters(string instanceName)
{
this.instanceName = instanceName;
try
{
arrivedMessages = new PerformanceCounter(CATEGORY, ARRIVED_COUNTER_NAME, instanceName, false);
}
catch (InvalidOperationException ex)
{
throw new ApplicationException(
string.Format(PerformanceCategoryCreator.CANT_CREATE_COUNTER_MSG, CATEGORY, ARRIVED_COUNTER_NAME),
ex);
}
}
private readonly PerformanceCounter arrivedMessages;
public int ArrivedMessages
{
get { return (int)arrivedMessages.RawValue; }
set
{
logger.DebugFormat("Setting UnsentMessages for instance '{0}' to {1}", instanceName, value);
arrivedMessages.RawValue = value;
}
}
}
} | 36.967213 | 223 | 0.622616 | [
"BSD-3-Clause"
] | hibernating-rhinos/rhino-queues | Rhino.Queues/Monitoring/InboundPerfomanceCounters.cs | 2,257 | C# |
using System.Collections;
using System.Collections.Generic;
using TerrainComposer2;
using UnityEngine;
using UnityEngine.Networking;
[ExecuteInEditMode]
public class RandomizeNode : MonoBehaviour
{
[Header("SEED")]
public int addSeed = 0;
[Header("RANDOM POSITION")]
public bool useTerrainAreaBounds = true;
public Vector2 posXRange = new Vector2(-512,512);
public Vector2 posYRange = new Vector2(-64,64);
public Vector2 posZRange = new Vector2(-512, 512);
[Header("RANDOM ROTATION")]
public Vector2 rotXRange = new Vector2(-5, 5);
public Vector2 rotYRange = new Vector2(-180, 180);
public Vector2 rotZRange = new Vector2(-5, 5);
[Header("RANDOM SCALE")]
public Vector2 scaleXZRange = new Vector2(0.5f, 2.5f);
public Vector2 scaleYRange = new Vector2(0.5f, 2.5f);
TC_ItemBehaviour node;
Transform t;
void OnValidate()
{
if (useTerrainAreaBounds) SetTerrainAreaBounds();
}
void OnEnable()
{
t = transform;
node = GetComponent<TC_ItemBehaviour>();
TC_Generate.AddEvent(node, Randomize);
if (useTerrainAreaBounds) SetTerrainAreaBounds();
}
void SetTerrainAreaBounds()
{
TC_TerrainArea terrainArea = TC_Area2D.instance.currentTerrainArea;
terrainArea.CalcTotalArea();
Rect area = terrainArea.area;
posXRange = new Vector2(area.xMin, area.xMax);
posZRange = new Vector2(area.yMin, area.yMax);
}
void OnDisable()
{
TC_Generate.RemoveEvent(node, Randomize);
}
void Randomize()
{
Random.InitState((int)((TC_Settings.instance.seed * 100) + addSeed));
t.position = GetRandomValue(posXRange, posYRange, posZRange);
t.eulerAngles = GetRandomValue(rotXRange, rotYRange, rotZRange);
float scaleXZ = GetRandomValue(scaleXZRange);
float scaleY = GetRandomValue(scaleYRange);
t.localScale = new Vector3(scaleXZ, scaleY, scaleXZ);
}
float GetRandomValue(Vector2 range)
{
return Random.Range(range.x, range.y);
}
Vector3 GetRandomValue(Vector2 rangeX, Vector2 rangeY, Vector2 rangeZ)
{
return new Vector3(GetRandomValue(rangeX), GetRandomValue(rangeY), GetRandomValue(rangeZ));
}
}
| 28.060976 | 99 | 0.66319 | [
"MIT"
] | MelDv/DistributedShooter | Assets/TerrainComposer2/Scripts/Runtime/RandomizeNode.cs | 2,303 | C# |
#region Copyright
/*
* Copyright (C) 2018 Larry Lopez
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#endregion Copyright
using System;
using System.Collections;
using System.Collections.Generic;
namespace Kettle.Collections.Trees.Common
{
/// <summary>
/// Defines methods to manipulate a generic binary tree.
/// </summary>
/// <typeparam name="T">The type of the elements in the binary tree.</typeparam>
public interface IBinaryTree<T> : ICollection<T>, ICollection, IReadOnlyCollection<T>
{
#region Properties
/// <summary>
/// Gets and sets the <see cref="IComparer{T}"/> used for comparing elements in a binary tree.
/// </summary>
/// <value>
/// An <see cref="IComparer{T}"/> used for comparing elements in a binary tree.
/// </value>
IComparer<T> Comparer { get; set; }
/// <summary>
/// Gets the height of a binary tree.
/// </summary>
/// <value>The height of a binary tree is the number of edges between the tree's root and its furthest leaf.</value>
int Height { get; }
/// <summary>
/// Gets the count of leaf nodes in the binary tree.
/// </summary>
/// <value>The total number of leaf nodes in the tree.</value>
int LeafCount { get; }
/// <summary>
/// Gets the maximum width of a binary tree.
/// </summary>
/// <value>The maximum width of the tree at all levels.</value>
int Width { get; }
#endregion Properties
#region Methods
/// <summary>
/// Traverses a binary tree Post-Order (LRN) and performs a callback <see cref="Action{T}"/> on each node.
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to perform on each node.</param>
void TraverseTreePostOrder(Action<T> action);
/// <summary>
/// Traverses a binary tree Pre-Order (NLR) and performs a callback <see cref="Action{T}"/> on each node.
/// </summary>
/// <param name="action">The <see cref="Action{T}"/> to perform on each node.</param>
void TraverseTreePreOrder(Action<T> action);
#endregion Methods
}
} | 38.411765 | 124 | 0.649923 | [
"MIT"
] | namralkeeg/kettle.net | src/Kettle/Collections/Trees/Common/IBinaryTree.cs | 3,267 | C# |
// PreprocessorControlLine.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
namespace ScriptSharp.Parser {
// #error/#warning
internal sealed class PreprocessorControlLine : PreprocessorLine {
private string _message;
public PreprocessorControlLine(PreprocessorTokenType type, string message)
: base(type) {
_message = message.Trim();
}
public string Message {
get {
return _message;
}
}
}
}
| 22.259259 | 90 | 0.617304 | [
"Apache-2.0"
] | AmanArnold/dsharp | src/Core/Compiler/Parser/PreprocessorControlLine.cs | 601 | C# |
using System;
namespace MigrationTools.Enrichers
{
public class PauseAfterEachItemOptions : ProcessorEnricherOptions
{
public override Type ToConfigure => typeof(PauseAfterEachItem);
public override void SetDefaults()
{
Enabled = true;
}
}
} | 21.428571 | 71 | 0.653333 | [
"MIT"
] | ACoderLife/azure-devops-migration-tools | src/MigrationTools/ProcessorEnrichers/PauseAfterEachItemOptions.cs | 302 | C# |
namespace Octokit.GraphQL.Model
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Octokit.GraphQL.Core;
using Octokit.GraphQL.Core.Builders;
/// <summary>
/// The connection type for Commit.
/// </summary>
public class CommitConnection : QueryableValue<CommitConnection>, IPagingConnection<Commit>
{
internal CommitConnection(Expression expression) : base(expression)
{
}
/// <summary>
/// A list of edges.
/// </summary>
public IQueryableList<CommitEdge> Edges => this.CreateProperty(x => x.Edges);
/// <summary>
/// A list of nodes.
/// </summary>
public IQueryableList<Commit> Nodes => this.CreateProperty(x => x.Nodes);
/// <summary>
/// Information to aid in pagination.
/// </summary>
public PageInfo PageInfo => this.CreateProperty(x => x.PageInfo, Octokit.GraphQL.Model.PageInfo.Create);
/// <summary>
/// Identifies the total count of items in the connection.
/// </summary>
public int TotalCount { get; }
IPageInfo IPagingConnection.PageInfo => PageInfo;
internal static CommitConnection Create(Expression expression)
{
return new CommitConnection(expression);
}
}
} | 30.222222 | 112 | 0.6125 | [
"MIT"
] | 0xced/octokit.graphql.net | Octokit.GraphQL/Model/CommitConnection.cs | 1,360 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.Test.Utility;
using Xunit;
namespace NuGet.Protocol.Plugins.Tests
{
public class EmbeddedSignatureVerifierTests
{
[PlatformFact(Platform.Windows)]
public void Create_ReturnsWindowsEmbeddedSignatureVerifierOnWindows()
{
var verifier = EmbeddedSignatureVerifier.Create();
Assert.IsType<WindowsEmbeddedSignatureVerifier>(verifier);
}
[PlatformFact(Platform.Darwin)]
public void Create_ReturnsUnixPlatformsEmbeddedSignatureVerifierOnMacOS()
{
var verifier = EmbeddedSignatureVerifier.Create();
Assert.IsType<UnixAndMonoPlatformsEmbeddedSignatureVerifier>(verifier);
}
[PlatformFact(Platform.Linux)]
public void Create_ReturnsUnixPlatformsEmbeddedSignatureVerifierOnLinux()
{
var verifier = EmbeddedSignatureVerifier.Create();
Assert.IsType<UnixAndMonoPlatformsEmbeddedSignatureVerifier>(verifier);
}
}
} | 33.285714 | 111 | 0.706438 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | test/NuGet.Core.Tests/NuGet.Protocol.Tests/Plugins/EmbeddedSignatureVerifierTests.cs | 1,165 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace StuffPacker.Persistence.Migrations
{
public partial class addProductGroup : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ProductGroups",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Owner = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Maximized = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductGroups", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ProductGroups");
}
}
}
| 31.3125 | 71 | 0.532934 | [
"MIT"
] | StuffPacker/StuffPacker | src/Site/StuffPacker.Persistence/Migrations/20200115170738_addProductGroup.cs | 1,004 | C# |
using Loogn.OrmLite;
namespace HttpQuartz.Server.dao.Models
{
/// <summary>
///
/// </summary>
public partial class SystemRole
{
[OrmLiteField(IsPrimaryKey = true, InsertIgnore = true)]
public long Id { get; set; }
/// <summary>
/// 角色名称
/// </summary>
public string Name { get; set; }
}
}
| 17.47619 | 64 | 0.531335 | [
"MIT"
] | loogn/httpquartz | src/HttpQuartz.Server/dao/Models/SystemRole.cs | 375 | C# |
namespace MattermostBot.ArtifactoryClient
{
public class WhereRepository : IWhereRepository
{
private readonly SearchQueryBuilder _query;
public WhereRepository(SearchQueryBuilder query)
{
_query = query;
}
public ISearchQueryBuilder Equal(string value)
{
_query.AddClause($"\"repo\": {{ \"$eq\": \"{value}\" }}");
return _query;
}
public ISearchQueryBuilder Match(string value)
{
_query.AddClause($"\"repo\": {{ \"$match\": \"{value}\" }}");
return _query;
}
public ISearchQueryBuilder NotEqual(string value)
{
_query.AddClause($"\"repo\": {{ \"$ne\": \"{value}\" }}");
return _query;
}
}
}
| 23.5 | 73 | 0.523154 | [
"MIT"
] | ponomNikita/MattermostBot | src/MattermostBot.ArtifactoryClient/WhereRepository.cs | 799 | C# |
using System;
using System.Collections.Immutable;
using Rocket.Libraries.TaskRunner.Schedules;
using Rocket.Libraries.TaskRunner.TaskDefinitions;
namespace Rocket.Libraries.TaskRunner.Runner
{
public interface IDueTasksFilter<TIdentifier> : IDisposable
{
ImmutableList<ITaskDefinition<TIdentifier>> GetWithOnlyDueTasks(ImmutableList<ITaskDefinition<TIdentifier>> candidateTasks, ImmutableList<ISchedule<TIdentifier>> schedules);
}
} | 37.833333 | 181 | 0.817181 | [
"MIT"
] | rocket-libs/Rocket.Libraries.TaskRunner | Rocket.Libraries.TaskRunner/Runner/IDueTasksFilter.cs | 456 | C# |
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using FashionNova.WebAPI.Database;
using FashionNova.WebAPI.Services;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FashionNova.WebAPI.Service
{
public class RecommenderService : IRecommender
{
protected readonly FashionNova.WebAPI.Database.IB170007Context _context;
protected readonly IMapper _mapper;
public RecommenderService(FashionNova.WebAPI.Database.IB170007Context context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
Dictionary<int, List<Database.Ocjene>> artikliOcjene = new Dictionary<int, List<Database.Ocjene>>();
public List<FashionNova.Model.Models.Artikli> GetSlicneArtikle(int artikalID)
{
var ocjene = _context.Ocjene.AsQueryable().ToList();
var tmp = LoadSimilar(artikalID);
var konacna= _mapper.Map<List<FashionNova.Model.Models.Artikli>>(tmp);
//prepravka
var bojeList = _context.Boja.AsQueryable().ToList();
var velicineList = _context.Velicina.AsQueryable().ToList();
var materijaliList = _context.Materijal.AsQueryable().ToList();
var vrstaArtiklaList = _context.VrstaArtikla.AsQueryable().ToList();
var ocjeneArtiklaList = _context.Ocjene.AsQueryable().ToList();
foreach (var item in konacna)
{
//morala sam ovako jer mapiranje ne sadrzi naziv-> bojaId/boja, materijalId/materijal
foreach (var b in bojeList)
{
if (item.BojaId == b.BojaId)
item.Boja = b.Naziv;
}
foreach (var va in vrstaArtiklaList)
{
if (item.VrstaArtiklaId == va.VrstaArtiklaId)
item.VrstaArtikla = va.Naziv;
}
foreach (var m in materijaliList)
{
if (item.MaterijalId == m.MaterijalId)
item.Materijal = m.Naziv;
}
foreach (var v in velicineList)
{
if (item.VelicinaId == v.VelicinaId)
item.Velicina = v.Oznaka;
}
}
//dodavanje prosjecjenocj
foreach (var item in konacna)
{
decimal suma = 0; int brojac = 0;
foreach (var ocj in ocjene)
{
if(item.ArtikliId==ocj.ArtikliId)
{
brojac++;
suma += ocj.Ocjena;
}
}
if (brojac > 0)
{
suma /= brojac;
item.prosjecnaOcjena = Math.Round(suma, 2);
}
else
{
item.prosjecnaOcjena = 0;
}
}
if(konacna.Count()==0 || konacna==null)
{
var lista = _context.Artikli.OrderBy(x => Guid.NewGuid()).Take(3);
konacna = _mapper.Map<List<FashionNova.Model.Models.Artikli>>(lista);
//dodavanje naziva za id(bojaId, materijalId,velicinaId, vrstaartiklaId); jer se to ne moze direktnim mapiranjem tj.prosljedjuju se samo kljucevi.
foreach (var item in konacna)
{
foreach (var b in bojeList)
{
if (item.BojaId == b.BojaId)
item.Boja = b.Naziv;
}
foreach (var va in vrstaArtiklaList)
{
if (item.VrstaArtiklaId == va.VrstaArtiklaId)
item.VrstaArtikla = va.Naziv;
}
foreach (var m in materijaliList)
{
if (item.MaterijalId == m.MaterijalId)
item.Materijal = m.Naziv;
}
foreach (var v in velicineList)
{
if (item.VelicinaId == v.VelicinaId)
item.Velicina = v.Oznaka;
}
}
//dodavanje prosjecne ocjene
foreach (var item in konacna)
{
decimal suma = 0; int brojac = 0;
foreach (var ocj in ocjene)
{
if (item.ArtikliId == ocj.ArtikliId)
{
brojac++;
suma += ocj.Ocjena;
}
}
if (brojac > 0)
{
suma /= brojac;
item.prosjecnaOcjena = Math.Round(suma, 2);
}
else
{
item.prosjecnaOcjena = 0;
}
}
}
return konacna;
}
private List<Database.Artikli> LoadSimilar(int artikalID)
{
LoadDifVehicles(artikalID);
List<Database.Ocjene> ratingsOfThis = _context.Ocjene.Where(e => e.ArtikliId == artikalID).OrderBy(e => e.KlijentiId).ToList();
List<Database.Ocjene> ratings1 = new List<Database.Ocjene>();
List<Database.Ocjene> ratings2 = new List<Database.Ocjene>();
List<Database.Artikli> recommendedVehicles = new List<Database.Artikli>();
foreach (var item in artikliOcjene)
{
foreach (Database.Ocjene rating in ratingsOfThis)
{
if (item.Value.Where(x => x.KlijentiId == rating.KlijentiId).Count() > 0)
{
ratings1.Add(rating);
ratings2.Add(item.Value.Where(x => x.KlijentiId == rating.KlijentiId).First());
}
}
double similarity = GetSimilarity(ratings1, ratings2);
if (similarity > 0.5)
{
recommendedVehicles.Add(_context.Artikli.Where(x => x.ArtikliId == item.Key)
//.Include(x => x.VrstaArtikla)
//.Include(x => x.VehicleModel.Manufacturer)
.FirstOrDefault());
}
ratings1.Clear();
ratings2.Clear();
}
return recommendedVehicles;
}
private double GetSimilarity(List<Database.Ocjene> ratings1, List<Database.Ocjene> ratings2)
{
if (ratings1.Count != ratings2.Count)
{
return 0;
}
double x = 0, y1 = 0, y2 = 0;
for (int i = 0; i < ratings1.Count; i++)
{
x += ratings1[i].Ocjena * ratings2[i].Ocjena;
y1 += ratings1[i].Ocjena * ratings1[i].Ocjena;
y2 += ratings2[i].Ocjena * ratings2[i].Ocjena;
}
y1 = Math.Sqrt(y1);
y2 = Math.Sqrt(y2);
double y = y1 * y2;
if (y == 0)
return 0;
return x / y;
}
private void LoadDifVehicles(int vehicleId)
{
var artikalVelicina = _context.Artikli.Find(vehicleId);
List<Database.Artikli> allVehicles = _context.Artikli.Where(e => e.ArtikliId != vehicleId && e.VelicinaId==artikalVelicina.VelicinaId).ToList();
List<Database.Ocjene> ratings = new List<Database.Ocjene>();
foreach (var item in allVehicles)
{
ratings = _context.Ocjene.Where(e => e.ArtikliId == item.ArtikliId).OrderBy(e => e.KlijentiId).ToList();
if (ratings.Count > 0)
artikliOcjene.Add(item.ArtikliId, ratings);
}
}
}
}
| 37.938967 | 162 | 0.469373 | [
"MIT"
] | nukicbelma/FashionNova | FashionNova/FashionNova/Services/RecommenderService.cs | 8,083 | C# |
using FreeCourse.Services.Order.Domain.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeCourse.Services.Order.Domain.OrderAggregate
{
public class Address : ValueObject
{
public string Province { get; private set; }
public string District { get; private set; }
public string Street { get; private set; }
public string ZipCode { get; private set; }
public string Line { get; private set; }
public Address(string province, string district, string street, string zipCode, string line)
{
Province = province;
District = district;
Street = street;
ZipCode = zipCode;
Line = line;
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Province;
yield return District;
yield return Street;
yield return ZipCode;
yield return Line;
}
}
} | 26.75 | 100 | 0.614019 | [
"MIT"
] | ardansisman/MicroserviceWorkshop | Services/Order/FreeCourse.Services.Order.Domain/OrderAggregate/Address.cs | 1,072 | C# |
using PipServices3.Commons.Config;
using PipServices3.Commons.Refer;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PipServices3.Components.Auth
{
/// <summary>
/// Credential store that keeps credentials in memory.
///
/// ### Configuration parameters ###
///
/// - [credential key 1]:
/// - ... credential parameters for key 1
/// - [credential key 2]:
/// - ... credential parameters for key N
/// </summary>
/// <example>
/// <code>
/// var config = ConfigParams.FromTuples(
/// "key1.user", "jdoe",
/// "key1.pass", "pass123",
/// "key2.user", "bsmith",
/// "key2.pass", "mypass" );
///
/// var credentialStore = new MemoryCredentialStore();
/// credentialStore.ReadCredentials(config);
/// credentialStore.LookupAsync("123", "key1");
/// </code>
/// </example>
/// See <see cref="ICredentialStore"/>, <see cref="CredentialParams"/>
public class MemoryCredentialStore : ICredentialStore, IReconfigurable
{
private Dictionary<string, CredentialParams> _items = new Dictionary<string, CredentialParams>();
private object _lock = new object();
/// <summary>
/// Creates a new instance of the credential store.
/// </summary>
public MemoryCredentialStore() { }
/// <summary>
/// Creates a new instance of the credential store.
/// </summary>
/// <param name="credentials">(optional) configuration with credential parameters.</param>
public MemoryCredentialStore(ConfigParams credentials)
{
Configure(credentials);
}
/// <summary>
/// Configures component by passing configuration parameters.
/// </summary>
/// <param name="config">configuration parameters to be set.</param>
public virtual void Configure(ConfigParams config)
{
ReadCredentials(config);
}
/// <summary>
/// Reads credentials from configuration parameters.
/// Each section represents an individual CredentialParams
/// </summary>
/// <param name="config">configuration parameters to be read</param>
public void ReadCredentials(ConfigParams config)
{
lock (_lock)
{
_items.Clear();
var sections = config.GetSectionNames();
foreach (var section in sections)
{
var value = config.GetSection(section);
var creadentials = CredentialParams.FromConfig(value);
_items.Add(section, creadentials);
}
}
}
/// <summary>
/// Stores credential parameters into the store.
/// </summary>
/// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
/// <param name="key">a key to uniquely identify the credential parameters.</param>
/// <param name="credential">a credential parameters to be stored.</param>
/// <returns></returns>
public async Task StoreAsync(string correlationId, string key, CredentialParams credential)
{
lock (_lock)
{
if (credential != null)
_items[key] = credential;
else
_items.Remove(key);
}
await Task.Delay(0);
}
/// <summary>
/// Lookups credential parameters by its key.
/// </summary>
/// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
/// <param name="key">a key to uniquely identify the credential parameters.</param>
/// <returns>resolved credential parameters or null if nothing was found.</returns>
public async Task<CredentialParams> LookupAsync(string correlationId, string key)
{
CredentialParams credential = null;
lock (_lock)
{
_items.TryGetValue(key, out credential);
}
return await Task.FromResult(credential);
}
}
}
| 35.691667 | 112 | 0.569227 | [
"MIT"
] | pip-services-dotnet/pip-services-components-dotnet | src/Auth/MemoryCredentialStore.cs | 4,285 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.S3Outposts")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon S3 on Outposts. Amazon S3 on Outposts expands object storage to on-premises AWS Outposts environments, enabling you to store and retrieve objects using S3 APIs and features.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.1.38")] | 47.625 | 260 | 0.752625 | [
"Apache-2.0"
] | bgrainger/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/S3Outposts/Properties/AssemblyInfo.cs | 1,524 | C# |
// OData .NET Libraries ver. 5.6.3
// Copyright (c) Microsoft Corporation
// All rights reserved.
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#if ASTORIA_OPEN_OBJECT
namespace System.Data.Services.Client
{
using System;
/// <summary>
/// Attribute to be annotated on class to designate the name of the instance property to store name-value pairs.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class OpenObjectAttribute : System.Attribute
{
/// <summary>
/// The name of the instance property returning an IDictionary<string,object>.
/// </summary>
private readonly string openObjectPropertyName;
/// <summary>
/// Constructor
/// </summary>
/// <param name="openObjectPropertyName">The name of the instance property returning an IDictionary<string,object>.</param>
public OpenObjectAttribute(string openObjectPropertyName)
{
Util.CheckArgumentNotEmpty(openObjectPropertyName, "openObjectPropertyName");
this.openObjectPropertyName = openObjectPropertyName;
}
/// <summary>
/// The name of the instance property returning an IDictionary<string,object>.
/// </summary>
public string OpenObjectPropertyName
{
get { return this.openObjectPropertyName; }
}
}
}
#endif
| 44.551724 | 138 | 0.68305 | [
"Apache-2.0"
] | tapika/choco | lib/Microsoft.Data.Services.Client/WCFDataService/Client/System/Data/Services/Client/OpenObjectAttribute.cs | 2,584 | C# |
namespace iPhoneTools
{
public static class MbdbEntryConverter
{
public static ManifestEntry ConvertToManifestEntry(this MbdbEntry item, ManifestEntryType includeType, bool isEncrypted)
{
ManifestEntry result = default;
var entryType = CommonHelpers.GetManifestEntryTypeFromMode(item.Mode);
if (entryType == includeType)
{
var id = item.GetSha1HashAsHexString();
result = new ManifestEntry
{
Id = id,
Domain = item.Domain,
RelativePath = item.RelativePath,
EntryType = entryType,
};
if (isEncrypted)
{
result.ProtectionClass = (ProtectionClass)item.Flags;
result.WrappedKey = item.WrappedKey;
}
}
return result;
}
}
}
| 29.181818 | 128 | 0.508827 | [
"MIT"
] | jim-dale/iPhoneTools | src/iPhoneTools/Services/MbdbEntryConverter.cs | 965 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace BrowserVersions.Data.Migrations
{
public partial class Add_SeedData : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 1, 1, 1 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 2, 2, 1 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 3, 3, 1 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 4, 1, 2 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 5, 2, 2 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 6, 3, 2 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 7, 1, 4 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 8, 2, 4 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 9, 3, 4 });
migrationBuilder.InsertData(
table: "Browsers",
columns: new[] { "BrowserId", "Platform", "Type" },
values: new object[] { 10, 1, 3 });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 2);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 3);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 4);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 5);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 6);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 7);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 8);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 9);
migrationBuilder.DeleteData(
table: "Browsers",
keyColumn: "BrowserId",
keyValue: 10);
}
}
}
| 33.078947 | 71 | 0.470432 | [
"MIT"
] | curtisy1/BrowserVersions | BrowserVersions.Data/Migrations/20210607204936_Add_SeedData.cs | 3,773 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Batch.V20200901.Outputs
{
[OutputType]
public sealed class CloudServiceConfigurationResponse
{
/// <summary>
/// Possible values are: 2 - OS Family 2, equivalent to Windows Server 2008 R2 SP1. 3 - OS Family 3, equivalent to Windows Server 2012. 4 - OS Family 4, equivalent to Windows Server 2012 R2. 5 - OS Family 5, equivalent to Windows Server 2016. 6 - OS Family 6, equivalent to Windows Server 2019. For more information, see Azure Guest OS Releases (https://azure.microsoft.com/documentation/articles/cloud-services-guestos-update-matrix/#releases).
/// </summary>
public readonly string OsFamily;
/// <summary>
/// The default value is * which specifies the latest operating system version for the specified OS family.
/// </summary>
public readonly string? OsVersion;
[OutputConstructor]
private CloudServiceConfigurationResponse(
string osFamily,
string? osVersion)
{
OsFamily = osFamily;
OsVersion = osVersion;
}
}
}
| 39.361111 | 453 | 0.681016 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Batch/V20200901/Outputs/CloudServiceConfigurationResponse.cs | 1,417 | C# |
using System;
using Scribe.Interpreter.BluePrints;
using Scribe.Interpreter.BluePrints.Attributes;
using Scribe.Interpreter.BluePrints.Interfaces;
namespace Scribe.Interpreter.Core.Type.U
{
[Keyword(Words = new []{"u08"})]
public class U08 : ValueType<ushort>
{
private ushort _value;
public override bool SetValueByObject(object obj)
{
if (string.IsNullOrWhiteSpace(obj.ToString()))
throw new RuntimeException("ERROR: Expected a Value");
if (!ushort.TryParse(obj.ToString(), out var value))
throw new RuntimeException("ERROR: Not a number");
Value = value;
return true;
}
public override ushort Value
{
get => _value;
set
{
if (value > 255)
throw new RuntimeException($"Value is out of the max range for {nameof(U08)}");
_value = value;
}
}
}
} | 29.411765 | 99 | 0.565 | [
"MIT"
] | thelazurite-cell/ScribeLang | src/ScribeLang.Interpreter/Scribe.Interpreter.Core/Type/U/U08.cs | 1,000 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("System.Diagnostics.Process.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("System.Diagnostics.Process.Tests")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| 40.235294 | 77 | 0.785088 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Diagnostics.Process/tests/Properties/AssemblyInfo.cs | 684 | C# |
using ImageWizard.Core.ImageFilters.Base;
using ImageWizard.Core.ImageFilters.Base.Attributes;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ImageWizard.Filters
{
/// <summary>
/// FilterAction
/// </summary>
public class SvgFilterAction<TFilter> : FilterAction<TFilter>
where TFilter : SvgFilter
{
public SvgFilterAction(IServiceProvider serviceProvider, Regex regex, MethodInfo method)
: base(serviceProvider, regex, method)
{
}
}
}
| 25.444444 | 96 | 0.727802 | [
"MIT"
] | usercode/ImageWizard | src/ImageWizard.SvgNet/Filters/Base/SvgFilterAction.cs | 689 | C# |
#region --- License ---
/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos
* See license.txt for license info
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Bind
{
[Serializable]
class Settings
{
public Settings()
{
OverridesFiles = new List<string>();
}
public string DefaultInputPath = "../../../Generator.Bind/Specifications";
public string DefaultOutputPath = "../../../Source/OpenTK/Graphics/OpenGL";
public string DefaultOutputNamespace = "OpenTK.Graphics.OpenGL";
public string DefaultDocPath = "../../../Generator.Bind/Specifications/Docs";
public string DefaultFallbackDocPath = "../../../Generator.Bind/Specifications/Docs/GL";
public string DefaultLicenseFile = "License.txt";
public string DefaultLanguageTypeMapFile = "csharp.tm";
public string DefaultKeywordEscapeCharacter = "@";
public string DefaultImportsFile = "Core.cs";
public string DefaultDelegatesFile = "Delegates.cs";
public string DefaultEnumsFile = "Enums.cs";
public string DefaultWrappersFile = "GL.cs";
public Legacy DefaultCompatibility = Legacy.NoDropMultipleTokens;
string inputPath, outputPath, outputNamespace, docPath, fallbackDocPath, licenseFile,
languageTypeMapFile, keywordEscapeCharacter, importsFile, delegatesFile, enumsFile,
wrappersFile;
Nullable<Legacy> compatibility;
public string InputPath { get { return inputPath ?? DefaultInputPath; } set { inputPath = value; } }
public string OutputPath { get { return outputPath ?? DefaultOutputPath; } set { outputPath = value; } }
public string OutputNamespace { get { return outputNamespace ?? DefaultOutputNamespace; } set { outputNamespace = value; } }
public string DocPath { get { return docPath ?? DefaultDocPath; } set { docPath = value; } }
public string FallbackDocPath { get { return fallbackDocPath ?? DefaultFallbackDocPath; } set { fallbackDocPath = value; } }
public string LicenseFile { get { return licenseFile ?? DefaultLicenseFile; } set { licenseFile = value; } }
public List<string> OverridesFiles { get; private set; }
public string LanguageTypeMapFile { get { return languageTypeMapFile ?? DefaultLanguageTypeMapFile; } set { languageTypeMapFile = value; } }
public string KeywordEscapeCharacter { get { return keywordEscapeCharacter ?? DefaultKeywordEscapeCharacter; } set { keywordEscapeCharacter = value; } }
public string ImportsFile { get { return importsFile ?? DefaultImportsFile; } set { importsFile = value; } }
public string DelegatesFile { get { return delegatesFile ?? DefaultDelegatesFile; } set { delegatesFile = value; } }
public string EnumsFile { get { return enumsFile ?? DefaultEnumsFile; } set { enumsFile = value; } }
public string WrappersFile { get { return wrappersFile ?? DefaultWrappersFile; } set { wrappersFile = value; } }
public Legacy Compatibility { get { return compatibility ?? DefaultCompatibility; } set { compatibility = value; } }
public string GLClass = "GL"; // Needed by Glu for the AuxEnumsClass. Can be set through -gl:"xxx".
public string OutputClass = "GL"; // The real output class. Can be set through -class:"xxx".
public string FunctionPrefix = "gl";
public string ConstantPrefix = "GL_";
public string EnumPrefix = "";
public string NamespaceSeparator = ".";
// TODO: This code is too fragile.
// Old enums code:
public string normalEnumsClassOverride = null;
public string NestedEnumsClass = "Enums";
public string NormalEnumsClass
{
get
{
return
normalEnumsClassOverride == null ?
String.IsNullOrEmpty(NestedEnumsClass) ? OutputClass : OutputClass + NamespaceSeparator + NestedEnumsClass :
normalEnumsClassOverride;
}
}
public string AuxEnumsClass
{
get { return GLClass + NamespaceSeparator + NestedEnumsClass; }
}
public string EnumsOutput
{
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
return OutputNamespace + NamespaceSeparator + OutputClass + NamespaceSeparator + NestedEnumsClass;
else
return String.IsNullOrEmpty(EnumsNamespace) ? OutputNamespace : OutputNamespace + NamespaceSeparator + EnumsNamespace;
}
}
public string EnumsAuxOutput
{
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
return OutputNamespace + NamespaceSeparator + GLClass + NamespaceSeparator + NestedEnumsClass;
else
return OutputNamespace + NamespaceSeparator + EnumsNamespace;
}
}
// New enums namespace (don't use a nested class).
public string EnumsNamespace = null;// = "Enums";
public string DelegatesClass = "Delegates";
public string ImportsClass = "Core";
/// <summary>
/// The name of the C# enum which holds every single OpenGL enum (for compatibility purposes).
/// </summary>
public string CompleteEnumName = "All";
[Flags]
public enum Legacy
{
/// <summary>Default value.</summary>
None = 0x00,
/// <summary>Leave enums as plain const ints.</summary>
ConstIntEnums = 0x01,
/// <summary>Leave enums in the default STRANGE_capitalization.ALL_CAPS form.</summary>
NoAdvancedEnumProcessing = 0x02,
/// <summary>Don't allow unsafe wrappers in the interface.</summary>
NoPublicUnsafeFunctions = 0x04,
/// <summary>Don't trim the [fdisub]v? endings from functions.</summary>
NoTrimFunctionEnding = NoPublicUnsafeFunctions,
/// <summary>Don't trim the [gl|wgl|glx|glu] prefixes from functions.</summary>
NoTrimFunctionPrefix = 0x08,
/// <summary>
/// Don't spearate functions in different namespaces, according to their extension category
/// (e.g. GL.Arb, GL.Ext etc).
/// </summary>
NoSeparateFunctionNamespaces = 0x10,
/// <summary>
/// No public void* parameters (should always be enabled. Disable at your own risk. Disabling
/// means that BitmapData.Scan0 and other .Net properties/functions must be cast to (void*)
/// explicitly, to avoid the 'object' overload from being called.)
/// </summary>
TurnVoidPointersToIntPtr = 0x20,
/// <summary>Generate all possible permutations for ref/array/pointer parameters.</summary>
GenerateAllPermutations = 0x40,
/// <summary>Nest enums inside the GL class.</summary>
NestedEnums = 0x80,
/// <summary>Turn GLboolean to int (Boolean enum), not bool.</summary>
NoBoolParameters = 0x100,
/// <summary>Keep all enum tokens, even if same value (e.g. FooARB, FooEXT and FooSGI).</summary>
NoDropMultipleTokens = 0x200,
/// <summary>Do not emit inline documentation.</summary>
NoDocumentation = 0x400,
/// <summary>Disables ErrorHelper generation.</summary>
NoDebugHelpers = 0x800,
/// <summary>Generate both typed and untyped ("All") signatures for enum parameters.</summary>
KeepUntypedEnums = 0x1000,
/// <summary>Marks deprecated functions as [Obsolete]</summary>
AddDeprecationWarnings = 0x2000,
/// <summary>Use DllImport declaration for core functions (do not generate entry point slots)</summary>
UseDllImports = 0x4000,
/// <summary>
/// Use in conjuction with UseDllImports, to create
/// bindings that are compatible with opengl32.dll on Windows.
/// This uses DllImports up to GL 1.1 and function pointers
/// for higher versions.
/// </summary>
UseWindowsCompatibleGL = 0x8000,
Tao = ConstIntEnums |
NoAdvancedEnumProcessing |
NoPublicUnsafeFunctions |
NoTrimFunctionEnding |
NoTrimFunctionPrefix |
NoSeparateFunctionNamespaces |
TurnVoidPointersToIntPtr |
NestedEnums |
NoBoolParameters |
NoDropMultipleTokens |
NoDocumentation |
NoDebugHelpers,
/*GenerateAllPermutations,*/
}
// Returns true if flag is enabled.
public bool IsEnabled(Legacy flag)
{
return (Compatibility & flag) != (Legacy)0;
}
// Enables the specified flag.
public void Enable(Legacy flag)
{
Compatibility |= flag;
}
// Disables the specified flag.
public void Disable(Legacy flag)
{
Compatibility &= ~flag;
}
/// <summary>True if multiple tokens should be dropped (e.g. FooARB, FooEXT and FooSGI).</summary>
public bool DropMultipleTokens
{
get { return (Compatibility & Legacy.NoDropMultipleTokens) == Legacy.None; }
set { if (value) Compatibility |= Legacy.NoDropMultipleTokens; else Compatibility &= ~Legacy.NoDropMultipleTokens; }
}
public string WindowsGDI = "OpenTK.Platform.Windows.API";
public Settings Clone()
{
IFormatter formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return (Settings)formatter.Deserialize(stream);
}
}
}
}
| 46.85 | 160 | 0.610653 | [
"BSD-3-Clause"
] | daerogami/opentk | src/Generator.Bind/Settings.cs | 10,307 | C# |
/**
* This file is part of the Drift Unreal Engine Integration.
*
* Copyright (C) 2016-2017 Directive Games Limited. All Rights Reserved.
*
* Licensed under the MIT License (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the license in the LICENSE file found at the top
* level directory of this module, and at https://mit-license.org/
*/
using UnrealBuildTool;
public class ErrorReporter : ModuleRules
{
public ErrorReporter(ReadOnlyTargetRules TargetRules) : base(TargetRules)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
#if UE_4_19_OR_LATER
PublicDefinitions.Add("ERROR_REPORTER_PACKAGE=1");
#else
Definitions.Add("ERROR_REPORTER_PACKAGE=1");
#endif
PublicDependencyModuleNames.AddRange(
new string[]
{
"Json",
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"Engine",
}
);
}
}
| 25.090909 | 77 | 0.616848 | [
"MIT"
] | directivegames/DriftUE4Base | ErrorReporter/ErrorReporter.Build.cs | 1,104 | C# |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hkaRagdollInstance : hkReferencedObject
{
public override uint Signature { get => 1414067300; }
public List<hkpRigidBody> m_rigidBodies;
public List<hkpConstraintInstance> m_constraints;
public List<int> m_boneToRigidBodyMap;
public hkaSkeleton m_skeleton;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
m_rigidBodies = des.ReadClassPointerArray<hkpRigidBody>(br);
m_constraints = des.ReadClassPointerArray<hkpConstraintInstance>(br);
m_boneToRigidBodyMap = des.ReadInt32Array(br);
m_skeleton = des.ReadClassPointer<hkaSkeleton>(br);
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
s.WriteClassPointerArray<hkpRigidBody>(bw, m_rigidBodies);
s.WriteClassPointerArray<hkpConstraintInstance>(bw, m_constraints);
s.WriteInt32Array(bw, m_boneToRigidBodyMap);
s.WriteClassPointer<hkaSkeleton>(bw, m_skeleton);
}
}
}
| 36.057143 | 81 | 0.661648 | [
"MIT"
] | SyllabusGames/DSMapStudio | HKX2/Autogen/hkaRagdollInstance.cs | 1,262 | C# |
namespace Model.Domain.MachineData.Press
{
public class PressMachineData : MachineDataBase
{
public PaperData PaperConsumption { get; set; }
}
}
| 20.75 | 55 | 0.692771 | [
"MIT"
] | killnine/MapperSample | src/Model/Domain/MachineData/Press/PressMachineData.cs | 168 | C# |
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* @brief デプス。コンフィグ。
*/
/** Fee.Depth
*/
namespace Fee.Depth
{
/** Config
*/
public class Config
{
/** ログ。
*/
public static bool LOG_ENABLE = false;
/** ログエラー。
*/
public static bool LOGERROR_ENABLE = true;
/** アサート。
*/
public static bool ASSERT_ENABLE = true;
/** デバッグリスロー。
*/
public static bool DEBUGRETHROW_ENABLE = false;
/** シェーダー名。
*/
public static string SHADER_NAME_DEPTHTEXTURE = "Fee/Depth/DepthTexture";
//public static string SHADER_NAME_CAMERADEPTHTEXTURE = "Fee/Depth/CameraDepthTexture";
/** デフォルト。ブレンド率。
*/
public static float DEFAULT_BLENDRATE = 0.5f;
}
}
| 16.347826 | 89 | 0.666223 | [
"MIT"
] | bluebackblue/fee | Script/Depth/Config.cs | 856 | C# |
using Krona.Cryptography.ECC;
using Krona.IO.Caching;
using Krona.IO.Data.LevelDB;
using Krona.IO.Wrappers;
using Krona.Ledger;
using System;
using System.Reflection;
namespace Krona.Persistence.LevelDB
{
public class LevelDBStore : Store, IDisposable
{
private readonly DB db;
public LevelDBStore(string path)
{
this.db = DB.Open(path, new Options { CreateIfMissing = true });
if (db.TryGet(ReadOptions.Default, SliceBuilder.Begin(Prefixes.SYS_Version), out Slice value) && Version.TryParse(value.ToString(), out Version version) && version >= Version.Parse("2.9.1"))
return;
WriteBatch batch = new WriteBatch();
ReadOptions options = new ReadOptions { FillCache = false };
using (Iterator it = db.NewIterator(options))
{
for (it.SeekToFirst(); it.Valid(); it.Next())
{
batch.Delete(it.Key());
}
}
db.Put(WriteOptions.Default, SliceBuilder.Begin(Prefixes.SYS_Version), Assembly.GetExecutingAssembly().GetName().Version.ToString());
db.Write(WriteOptions.Default, batch);
}
public void Dispose()
{
db.Dispose();
}
public override byte[] Get(byte prefix, byte[] key)
{
if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(prefix).Add(key), out Slice slice))
return null;
return slice.ToArray();
}
public override DataCache<UInt160, AccountState> GetAccounts()
{
return new DbCache<UInt160, AccountState>(db, null, null, Prefixes.ST_Account);
}
public override DataCache<UInt256, AssetState> GetAssets()
{
return new DbCache<UInt256, AssetState>(db, null, null, Prefixes.ST_Asset);
}
public override DataCache<UInt256, BlockState> GetBlocks()
{
return new DbCache<UInt256, BlockState>(db, null, null, Prefixes.DATA_Block);
}
public override DataCache<UInt160, ContractState> GetContracts()
{
return new DbCache<UInt160, ContractState>(db, null, null, Prefixes.ST_Contract);
}
public override Snapshot GetSnapshot()
{
return new DbSnapshot(db);
}
public override DataCache<UInt256, SpentCoinState> GetSpentCoins()
{
return new DbCache<UInt256, SpentCoinState>(db, null, null, Prefixes.ST_SpentCoin);
}
public override DataCache<StorageKey, StorageItem> GetStorages()
{
return new DbCache<StorageKey, StorageItem>(db, null, null, Prefixes.ST_Storage);
}
public override DataCache<UInt32Wrapper, StateRootState> GetStateRoots()
{
return new DbCache<UInt32Wrapper, StateRootState>(db, null, null, Prefixes.ST_StateRoot);
}
public override DataCache<UInt256, TransactionState> GetTransactions()
{
return new DbCache<UInt256, TransactionState>(db, null, null, Prefixes.DATA_Transaction);
}
public override DataCache<UInt256, UnspentCoinState> GetUnspentCoins()
{
return new DbCache<UInt256, UnspentCoinState>(db, null, null, Prefixes.ST_Coin);
}
public override DataCache<ECPoint, ValidatorState> GetValidators()
{
return new DbCache<ECPoint, ValidatorState>(db, null, null, Prefixes.ST_Validator);
}
public override DataCache<UInt32Wrapper, HeaderHashList> GetHeaderHashList()
{
return new DbCache<UInt32Wrapper, HeaderHashList>(db, null, null, Prefixes.IX_HeaderHashList);
}
public override MetaDataCache<ValidatorsCountState> GetValidatorsCount()
{
return new DbMetaDataCache<ValidatorsCountState>(db, null, null, Prefixes.IX_ValidatorsCount);
}
public override MetaDataCache<HashIndexState> GetBlockHashIndex()
{
return new DbMetaDataCache<HashIndexState>(db, null, null, Prefixes.IX_CurrentBlock);
}
public override MetaDataCache<HashIndexState> GetHeaderHashIndex()
{
return new DbMetaDataCache<HashIndexState>(db, null, null, Prefixes.IX_CurrentHeader);
}
public override MetaDataCache<RootHashIndex> GetStateRootHashIndex()
{
return new DbMetaDataCache<RootHashIndex>(db, null, null, Prefixes.IX_CurrentStateRoot);
}
public override void Put(byte prefix, byte[] key, byte[] value)
{
db.Put(WriteOptions.Default, SliceBuilder.Begin(prefix).Add(key), value);
}
public override void PutSync(byte prefix, byte[] key, byte[] value)
{
db.Put(new WriteOptions { Sync = true }, SliceBuilder.Begin(prefix).Add(key), value);
}
}
}
| 36.25 | 202 | 0.624544 | [
"MIT"
] | krona-project/krona | krona-core/Persistence/LevelDB/LevelDBStore.cs | 4,932 | C# |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
//namespace UnityStandardAssets.Characters.ThirdPerson
//{
[RequireComponent(typeof(ThirdPersonCharacterOwn))]
public class ThirdPersonUserControlOwn : MonoBehaviour
{
private ThirdPersonCharacterOwn m_Character; // A reference to the ThirdPersonCharacter on the object
private Transform m_Cam; // A reference to the main camera in the scenes transform
private Vector3 m_CamForward; // The current forward direction of the camera
private Vector3 m_Move;
// private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
private void Start()
{
// get the transform of the main camera
if (Camera.main != null)
{
m_Cam = Camera.main.transform;
}
else
{
Debug.LogWarning(
"Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
// we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
}
// get the third person character ( this should never be null due to require component )
m_Character = GetComponent<ThirdPersonCharacterOwn>();
}
private void Update()
{
/*if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}*/
}
// Fixed update is called in sync with physics
private void FixedUpdate()
{
// read inputs
float h = CrossPlatformInputManager.GetAxis("Horizontal");
float v = CrossPlatformInputManager.GetAxis("Vertical");
bool crouch = Input.GetKey(KeyCode.C);
// calculate move direction to pass to character
if (m_Cam != null)
{
// calculate camera relative direction to move:
m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
m_Move = v * m_CamForward + h * m_Cam.right;
}
else
{
// we use world-relative directions in the case of no main camera
m_Move = v * Vector3.forward + h * Vector3.right;
}
#if !MOBILE_INPUT
// walk speed multiplier
if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
#endif
// pass all parameters to the character control script
m_Character.Move(m_Move/*, crouch, m_Jump*/);
//m_Jump = false;
}
}
//}
| 34.394737 | 153 | 0.629686 | [
"MIT"
] | Miceroy/GGJ2019 | GGJ2019/Assets/Scripts/ThirdPerson/ThirdPersonUserControlOwn.cs | 2,614 | C# |
//@#$&+
//
//The MIT X11 License
//
//Copyright (c) 2010 - 2019 Icucom Corporation
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
//@#$&-
//using System;
//using System.Net.NetworkInformation;
//using System.Threading.Tasks;
//using PlatformAgileFramework.MVC.Views;
//namespace PlatformAgileFramework.MVC.Animation
//{
// /// <summary>
// /// These are animation helpers for views.
// /// </summary>
// /// <history>
// /// <contribution>
// /// <author> KRM </author>
// /// <date> 03jun19 </date>
// /// <description>
// /// New.
// /// </description>
// /// </contribution>
// /// </history>
// public static class AnimationHelpersAndExtensions
// {
// #region Methods
// public static IAnimatorFactory Factory
// {
// }
// /// <summary>
// /// We often use a content page and attach stuff to the content
// /// view and not the outer page. This just figures out if we are a content
// /// page and detaches the binding from the content, or, if not,
// /// detaches it from the view directly.
// /// </summary>
// public static Task TranslateVisibleObjectToAsync(this IViewBase view,
// double xShift, double yShift, uint length = 250, bool resetAfterAnimation = false)
// {
// if (view == null)
// throw new ArgumentNullException(nameof(view));
// var originalX = view.XUpperRight;
// var originalY = view.YUpperRight;
// TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
// Action<double> callback1 = (f =>
// {
// view.XUpperRight = f;
// });
// Action<double> callback2 = (Action<double>)(f =>
// {
// view.YUpperRight = f;
// });
// new Animation()
// {
// {
// 0.0,
// 1.0,
// new Animation(callback1, view.TranslationX, x, easing, (Action) null)
// },
// {
// 0.0,
// 1.0,
// new Animation(callback2, view.TranslationY, y, easing, (Action) null)
// }
// }.Commit((IAnimatable)view, nameof(TranslateTo), 16U, length, (Easing)null, (Action<double, bool>)((f, a) => tcs.SetResult(a)), (Func<bool>)null);
// return tcs.Task;
// }
// /// <summary>
// /// We often use a content page and attach stuff to the content
// /// view and not the outer page. This just figures out if we are a content
// /// page and attaches the binding to the content, or, if not,
// /// attaches it to the view directly.
// /// </summary>
// public static void AttachBindingOrContentBinding(this IViewBase view, object bindingObject)
// {
// if (view is IContentViewBase contentViewBase)
// {
// contentViewBase.Content.BindingObject = bindingObject;
// return;
// }
// view.BindingObject = bindingObject;
// }
// #endregion // Methods
// }
//}
| 35.361111 | 153 | 0.646504 | [
"MIT"
] | Platform-Agile-Software/PAF-Community | OptionalLibraries/PAF.MVC/Animation/AnimationHelpersAndExtensions.cs | 3,821 | C# |
using GitLabApiClient.Internal.Utilities;
using Newtonsoft.Json;
namespace GitLabApiClient.Models.Webhooks.Requests
{
/// <summary>
/// Used to create a webhook in a project.
/// </summary>
public sealed class CreateWebhookRequest
{
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("push_events")]
public bool? PushEvents { get; set; }
[JsonProperty("push_events_branch_filter")]
public string PushEventsBranchFilter { get; set; }
[JsonProperty("issues_events")]
public bool? IssuesEvents { get; set; }
[JsonProperty("confidential_issues_events")]
public bool? ConfidentialIssuesEvents { get; set; }
[JsonProperty("merge_requests_events")]
public bool? MergeRequestsEvents { get; set; }
[JsonProperty("tag_push_events")]
public bool? TagPushEvents { get; set; }
[JsonProperty("note_events")]
public bool? NoteEvents { get; set; }
[JsonProperty("job_events")]
public bool? JobEvents { get; set; }
[JsonProperty("pipeline_events")]
public bool? PipelineEvents { get; set; }
[JsonProperty("wiki_page_events")]
public bool? WikiPageEvents { get; set; }
[JsonProperty("enable_ssl_verification")]
public bool? EnableSslVerification { get; set; }
[JsonProperty("token")]
public string Token { get; set; }
public CreateWebhookRequest(string url)
{
Guard.NotEmpty(url, nameof(url));
Url = url;
}
}
}
| 28.157895 | 59 | 0.616199 | [
"MIT"
] | dimasrespect/GitLabApiClient | src/GitLabApiClient/Models/Webhooks/Requests/CreateWebhookRequest.cs | 1,607 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RxSandbox.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RxSandbox.Tests")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("32f5a28c-82be-4670-b4e2-490b41778201")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784 | 84 | 0.747496 | [
"MIT"
] | StanislavKhalash/learning-rx | RxSandbox/RxSandbox.Tests/Properties/AssemblyInfo.cs | 1,401 | C# |
using System.Collections.Generic;
namespace BuffettCodeCommon.Config
{
public static class DefaultUnitConfig
{
public static HashSet<string> MillionYenProperties = new HashSet<string> {
"accounts_payable",
"accounts_receivable",
"accrual",
"additional_capital_stock",
"advances_received",
"amortization",
"assets",
"bonds_issuance",
"bonds_payable",
"bonds_repayment",
"buildings",
"capital_stock",
"cash_and_deposits",
"cash_translation_difference",
"commercial_papers_liabilities",
"construction_in_progress",
"convertible_bond_type_bonds_with_subscription_rights",
"convertible_bonds",
"corporate_tax_payable",
"cost_of_sales",
"current_allowance_doubtful_accounts",
"current_assets",
"current_dta",
"current_lease_obligations",
"current_liabilities",
"current_portion_of_bonds",
"current_portion_of_bonds_with_subscription_rights",
"current_portion_of_convertible_bonds",
"current_portion_of_long_term_loans",
"current_securities",
"debt",
"decrease_inventories_op_cf",
"decrease_trade_receivables_op_cf",
"depreciation",
"dividend_payment",
"dividends_income",
"ebitda_actual",
"ebitda_forecast",
"enterprise_value",
"equity",
"equity_method_income",
"equity_method_loss",
"ex_net_income",
"ex_net_sales",
"ex_operating_income",
"ex_ordinary_income",
"extraordinary_income",
"extraordinary_loss",
"financial_cash_flow",
"free_cash_flow",
"gain_of_sales_investment_securities",
"gain_of_sales_non_current_assets",
"good_will",
"gross_profit",
"impairment_loss",
"income_before_income_taxes",
"income_before_taxes",
"income_taxes",
"increase_in_properties",
"increase_trade_payables_op_cf",
"intangible_assets",
"interest_and_dividends_income",
"interest_expense",
"interest_income",
"inventories",
"investment_cash_flow",
"investment_securities",
"investments_and_other_assets",
"land",
"lease_and_guarantee_deposits",
"lending",
"liabilities",
"long_term_debt_issuance",
"long_term_debt_repayment",
"long_term_loans_payable",
"loss_of_sales_non_current_assets",
"loss_of_valuation_investment_securities",
"machineries",
"market_capital",
"merchandise",
"net_assets",
"net_debt",
"net_income",
"net_sales",
"net_sales_per_employee",
"net_short_term_debt",
"non_controling_interests",
"non_controlling_interests",
"non_current_allowance_doubtful_accounts",
"non_current_assets",
"non_current_bonds_with_subscription_right",
"non_current_dta",
"non_current_dtl",
"non_current_lease_obligations",
"non_current_liabilities",
"non_operating_expenses",
"non_operating_income",
"notes_accounts_payable",
"notes_accounts_receivable",
"notes_payable",
"notes_receivable",
"operating_cash_flow",
"operating_income",
"operating_income_per_employee",
"ordinary_income",
"prepaid_expenses",
"profit_loss_attributable_to_owners_of_parent",
"purchase_of_intangible_assets",
"purchase_of_investment_securities",
"purchase_of_non_current_assets",
"purchase_of_property",
"purchase_of_securities",
"r_and_d_expenses",
"raw_materials_and_supplies",
"retained_earnings",
"return_of_lending",
"sale_of_intangible_assets",
"sale_of_investment_securities",
"sale_of_non_current_assets",
"sale_of_property",
"sale_of_securities",
"sga",
"share_repurchase",
"share_sales",
"shareholders_equity",
"short_term_bonds_payable",
"short_term_loans_payable",
"tangible_fixed_assets",
"trade_payables",
"trade_receivables",
"treasury_stock",
"valuation_and_translation_adjustments",
"work_in_process",
"working_capital"
};
}
} | 35.195804 | 82 | 0.561494 | [
"Apache-2.0"
] | BuffettCode/buffett-code-api-clinet-excel | BuffettCodeCommon/Config/DefaultUnitConfig.cs | 5,033 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FAManagementStudio.Views
{
/// <summary>
/// BasePathSettingsView.xaml の相互作用ロジック
/// </summary>
public partial class BasePathSettingsView : Window
{
public BasePathSettingsView()
{
InitializeComponent();
}
}
}
| 22.259259 | 54 | 0.717138 | [
"MIT"
] | degarashi0913/FAManagementStudio | FAManagementStudio/Views/BasePathSettingsView.xaml.cs | 621 | C# |
using Gov.Lclb.Cllb.Interfaces;
using Hangfire;
using Hangfire.Console;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.HealthChecks;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using SoapCore;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Exceptions;
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Server.Kestrel.Core;
namespace Gov.Lclb.Cllb.OneStopService
{
public class Startup
{
private readonly ILoggerFactory _loggerFactory;
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
if (!System.Diagnostics.Debugger.IsAttached)
builder.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Adjust Kestrel options to allow sync IO
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(Configuration);
services.AddSingleton<IReceiveFromHubService>(new ReceiveFromHubService(dynamicsClient, _loggerFactory.CreateLogger("IReceiveFromHubService"), Configuration));
services.AddSingleton<Microsoft.Extensions.Logging.ILogger>(_loggerFactory.CreateLogger("OneStopController"));
services.AddMvc(config =>
{
config.EnableEndpointRouting = false;
if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
}
});
// Other ConfigureServices() code...
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "JAG LCRB One Stop Service", Version = "v1" });
});
services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders();
if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
{
// Configure JWT authentication
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.SaveToken = true;
o.RequireHttpsMetadata = false;
o.TokenValidationParameters = new TokenValidationParameters()
{
RequireExpirationTime = false,
ValidIssuer = Configuration["JWT_VALID_ISSUER"],
ValidAudience = Configuration["JWT_VALID_AUDIENCE"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
};
});
}
services.AddHangfire(config =>
{
// Change this line if you wish to have Hangfire use persistent storage.
config.UseMemoryStorage();
// enable console logs for jobs
config.UseConsole();
});
// health checks.
services.AddHealthChecks(checks =>
{
checks.AddValueTaskCheck("HTTP Endpoint", () => new
ValueTask<IHealthCheckResult>(HealthCheckResult.Healthy("Ok")));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
// OneStop does not seem to set the SoapAction properly
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.Equals("/receiveFromHub"))
{
string soapAction = context.Request.Headers["SOAPAction"];
if (string.IsNullOrEmpty(soapAction) || soapAction.Equals("\"\""))
{
context.Request.Headers["SOAPAction"] = "http://tempuri.org/IReceiveFromHubService/receiveFromHub";
}
}
await next();
});
app.UseSoapEndpoint<IReceiveFromHubService>(path: "/receiveFromHub", binding: new BasicHttpBinding());
// , serializer: SoapSerializer.XmlSerializer, caseInsensitivePath: true
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
bool startHangfire = true;
#if DEBUG
// do not start Hangfire if we are running tests.
foreach (var assem in Assembly.GetEntryAssembly().GetReferencedAssemblies())
{
if (assem.FullName.ToLowerInvariant().StartsWith("xunit"))
{
startHangfire = false;
break;
}
}
#endif
if (startHangfire)
{
// enable Hangfire, using the default authentication model (local connections only)
app.UseHangfireServer();
DashboardOptions dashboardOptions = new DashboardOptions
{
AppPath = null
};
app.UseHangfireDashboard("/hangfire", dashboardOptions);
}
if (!string.IsNullOrEmpty(Configuration["ENABLE_HANGFIRE_JOBS"]))
{
SetupHangfireJobs(app, loggerFactory);
}
app.UseAuthentication();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "JAG LCRB One Stop Service");
});
// enable Splunk logger using Serilog
if (!string.IsNullOrEmpty(Configuration["SPLUNK_COLLECTOR_URL"]) &&
!string.IsNullOrEmpty(Configuration["SPLUNK_TOKEN"])
)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithExceptionDetails()
.WriteTo.EventCollector(Configuration["SPLUNK_COLLECTOR_URL"],
Configuration["SPLUNK_TOKEN"], restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error)
.CreateLogger();
}
}
/// <summary>
/// Setup the Hangfire jobs.
/// </summary>
/// <param name="app"></param>
/// <param name="loggerFactory"></param>
private void SetupHangfireJobs(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
Microsoft.Extensions.Logging.ILogger log = loggerFactory.CreateLogger(typeof(Startup));
log.LogInformation("Starting setup of Hangfire job ...");
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
log.LogInformation("Creating Hangfire jobs for License issuance check ...");
Microsoft.Extensions.Logging.ILogger oneStopLog = loggerFactory.CreateLogger(typeof(OneStopUtils));
RecurringJob.AddOrUpdate(() => new OneStopUtils(Configuration, oneStopLog).CheckForNewLicences(null), Cron.Hourly());
log.LogInformation("Hangfire License issuance check jobs setup.");
}
}
catch (Exception e)
{
StringBuilder msg = new StringBuilder();
msg.AppendLine("Failed to setup Hangfire job.");
log.LogCritical(new EventId(-1, "Hangfire job setup failed"), e, msg.ToString());
}
}
}
}
| 37.155642 | 171 | 0.577128 | [
"Apache-2.0"
] | ElizabethWolfe/jag-lcrb-carla-public | one-stop-service/Startup.cs | 9,551 | C# |
namespace Perfolizer.Tool
{
internal static class KnowStrings
{
public const string ApplicationAlias = "perfolizer";
}
} | 20 | 60 | 0.685714 | [
"MIT"
] | AndreyAkinshin/perfolizer | src/Perfolizer/Perfolizer.Tool/KnowStrings.cs | 140 | C# |
using System;
using Xamarin.Forms;
using Industrious.ToDo.Forms.Pages;
using Industrious.ToDo.Forms.Views;
using Industrious.ToDo.ViewModels;
namespace Industrious.ToDo.Forms
{
/// <summary>
/// View builders for phone-sized devices (iPhone, Galaxy). Uses a separate page and
/// push navigation for the editor when an item is selected.
/// </summary>
public class PhonePresentation : IUiPresentation
{
private readonly AppState _appState;
private PhoneRootPage _rootPage;
private ItemEditorView _editorView;
public PhonePresentation(AppState appState)
{
_appState = appState;
}
public void OnAppLoadingStarted()
{
// show a loading page
Application.Current.MainPage = new NavigationPage(new LoadingPage());
}
public void OnAppLoadingComplete()
{
// show the main screen
_rootPage = new PhoneRootPage()
{
BindingContext = new RootPageModel(_appState),
Content = new ItemListView()
{
BindingContext = new ItemListViewModel(_appState)
}
};
Application.Current.MainPage = new NavigationPage(_rootPage);
}
public void OnItemSelected()
{
// navigate to the item editor, if I'm not there already
if (_editorView == null)
{
_editorView = new ItemEditorView()
{
BindingContext = new ItemEditorViewModel(_appState)
};
var page = new ItemEditorPage()
{
BindingContext = new ItemEditorPageModel(_appState),
Content = _editorView
};
_rootPage.Navigation.PushAsync(page);
}
}
public void OnItemSelectionCleared()
{
// dismiss the item editor; return to the main screen
if (_editorView != null)
{
// TODO: Find a better way; view should be able to clean up after itself
((ItemEditorViewModel)_editorView.BindingContext).Dispose();
_editorView = null;
_rootPage.Navigation.PopAsync();
}
}
}
}
| 21.976471 | 86 | 0.698608 | [
"MIT"
] | industriousone/industrious-todo | Industrious.ToDo.Forms/PhonePresentation.cs | 1,870 | C# |
// Copyright © Amer Koleci and Contributors.
// Licensed under the MIT License (MIT). See LICENSE in the repository root for more information.
using System.Numerics;
using Vortice.Mathematics;
namespace Vortice;
public readonly record struct VertexPositionColor(Vector3 Position, Color4 Color);
| 29.8 | 97 | 0.802013 | [
"MIT"
] | gerhard17/Vortice.Windows | src/samples/Vortice.SampleFramework/VertexPositionColor.cs | 299 | C# |
using System;
using System.Collections.Generic;
using Niue.Alipay.Response;
namespace Niue.Alipay.Request
{
/// <summary>
/// AOP API: alipay.open.public.contact.follow.batchquery
/// </summary>
public class AlipayOpenPublicContactFollowBatchqueryRequest : IAopRequest<AlipayOpenPublicContactFollowBatchqueryResponse>
{
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.open.public.contact.follow.batchquery";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.737864 | 126 | 0.617996 | [
"MIT"
] | P79N6A/abp-ant-design-pro-vue | Niue.Alipay/Request/AlipayOpenPublicContactFollowBatchqueryRequest.cs | 2,445 | C# |
using System;
namespace CodeContractNullability.Test
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
internal sealed class GitHubIssueAttribute : Attribute
{
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public int Id { get; }
internal GitHubIssueAttribute(int id)
{
Id = id;
}
}
}
| 25.777778 | 86 | 0.665948 | [
"Apache-2.0"
] | bkoelman/ResharperCodeContractNullability | src/CodeContractNullability/CodeContractNullability.Test/GitHubIssueAttribute.cs | 466 | C# |
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;
namespace AsyncSchedulerTest.TestUtils
{
public class XUnitLogger<T> : ILogger<T>, IDisposable
{
private readonly ITestOutputHelper _output;
public XUnitLogger(ITestOutputHelper output)
{
_output = output;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
_output.WriteLine($"T:{Thread.CurrentThread.ManagedThreadId:00} [{logLevel}]: {state} {exception}");
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public IDisposable BeginScope<TState>(TState state)
{
return this;
}
public void Dispose()
{
}
}
} | 25.742857 | 145 | 0.618202 | [
"MIT"
] | Brunni/DotNetAsyncScheduler | AsyncSchedulerTest/TestUtils/XUnitLogger.cs | 903 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.LanguageServer;
using Microsoft.VisualStudio.LanguageServer.Client;
using Microsoft.VisualStudio.Threading;
using Microsoft.VisualStudio.Utilities;
using Nerdbank.Streams;
using StreamJsonRpc;
using Trace = Microsoft.AspNetCore.Razor.LanguageServer.Trace;
namespace Microsoft.VisualStudio.LanguageServerClient.Razor
{
[ClientName(ClientName)]
[Export(typeof(ILanguageClient))]
[ContentType(RazorLSPContentTypeDefinition.Name)]
internal class RazorLanguageServerClient : ILanguageClient, ILanguageClientCustomMessage2
{
// ClientName enables us to turn on-off the ILanguageClient functionality for specific TextBuffers of content type RazorLSPContentTypeDefinition.Name.
// This typically is used in cloud scenarios where we want to utilize an ILanguageClient on the server but not the client; therefore we disable this
// ILanguageClient infrastructure on the guest to ensure that two language servers don't provide results.
public const string ClientName = "RazorLSPClientName";
private readonly RazorLanguageServerCustomMessageTarget _customMessageTarget;
private readonly ILanguageClientMiddleLayer _middleLayer;
[ImportingConstructor]
public RazorLanguageServerClient(RazorLanguageServerCustomMessageTarget customTarget, RazorLanguageClientMiddleLayer middleLayer)
{
if (customTarget is null)
{
throw new ArgumentNullException(nameof(customTarget));
}
if (middleLayer is null)
{
throw new ArgumentNullException(nameof(middleLayer));
}
_customMessageTarget = customTarget;
_middleLayer = middleLayer;
}
public string Name => "Razor Language Server Client";
public IEnumerable<string> ConfigurationSections => null;
public object InitializationOptions => null;
public IEnumerable<string> FilesToWatch => null;
public object MiddleLayer => _middleLayer;
public object CustomMessageTarget => _customMessageTarget;
public event AsyncEventHandler<EventArgs> StartAsync;
public event AsyncEventHandler<EventArgs> StopAsync
{
add { }
remove { }
}
public async Task<Connection> ActivateAsync(CancellationToken token)
{
var (clientStream, serverStream) = FullDuplexStream.CreatePair();
// Need an auto-flushing stream for the server because O# doesn't currently flush after writing responses. Without this
// performing the Initialize handshake with the LanguageServer hangs.
var autoFlushingStream = new AutoFlushingStream(serverStream);
var server = await RazorLanguageServer.CreateAsync(autoFlushingStream, autoFlushingStream, Trace.Verbose).ConfigureAwait(false);
// Fire and forget for Initialized. Need to allow the LSP infrastructure to run in order to actually Initialize.
_ = server.InitializedAsync(token);
var connection = new Connection(clientStream, clientStream);
return connection;
}
public async Task OnLoadedAsync()
{
await StartAsync.InvokeAsync(this, EventArgs.Empty).ConfigureAwait(false);
}
public Task OnServerInitializeFailedAsync(Exception e)
{
return Task.CompletedTask;
}
public Task OnServerInitializedAsync()
{
return Task.CompletedTask;
}
public Task AttachForCustomMessageAsync(JsonRpc rpc) => Task.CompletedTask;
private class AutoFlushingStream : Stream
{
private readonly Stream _inner;
public AutoFlushingStream(Stream inner)
{
_inner = inner;
}
public override bool CanRead => _inner.CanRead;
public override bool CanSeek => _inner.CanSeek;
public override bool CanWrite => _inner.CanWrite;
public override long Length => _inner.Length;
public override long Position { get => _inner.Position; set => _inner.Position = value; }
// We intentionally call FlushAsync then don't await the task because calling Flush syncronously causes
// exceptions that can crash the extension.
public override void Flush() => _inner.FlushAsync();
public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin);
public override void SetLength(long value) => _inner.SetLength(value);
public override void Write(byte[] buffer, int offset, int count)
{
_inner.Write(buffer, offset, count);
// We intentionally call FlushAsync then don't await the task because calling Flush syncronously causes
// exceptions that can crash the extension.
_inner.FlushAsync();
}
}
}
}
| 39.546763 | 158 | 0.67837 | [
"Apache-2.0"
] | terrajobst/aspnetcore-tooling | src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLanguageServerClient.cs | 5,499 | C# |
/*
* Copyright 2003 jRPM Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System; using java = biz.ritter.javapi;
using com.jguild.jrpm.io;
using com.jguild.jrpm.io.constant;
namespace com.jguild.jrpm.io.datatype
{
/**
* A representation of a rpm 8 byte integer array data object.
*
* @author kuss
* @version $Id: INT8.java,v 1.4 2005/11/11 08:27:40 mkuss Exp $
*/
public sealed class INT8 : DataTypeIf
{
private static readonly java.util.logging.Logger logger = RPMFile.logger;
private byte[] data;
private long size;
internal INT8(byte[] data)
{
this.data = data;
this.size = data.Length;
}
/**
* Get the rpm int8 array as a java byte array
*
* @return An array of bytes
*/
public byte[] getData()
{
return this.data;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#getData()
*/
public Object getDataObject()
{
return this.data;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#getType()
*/
public RPMIndexType getType()
{
return RPMIndexType.INT8;
}
/**
* Constructs a type froma stream
*
* @param inputStream An input stream
* @param indexEntry The index informations
* @return The size of the read data
* @throws IOException if an I/O error occurs.
*/
public static INT8 readFromStream(java.io.DataInputStream inputStream,
IndexEntry indexEntry)
{//throws IOException {
if (indexEntry.getType() != RPMIndexType.INT8)
{
throw new java.lang.IllegalArgumentException("Type <" + indexEntry.getType()
+ "> does not match <" + RPMIndexType.INT8 + ">");
}
byte[] data = new byte[(int)indexEntry.getCount()];
for (int pos = 0; pos < indexEntry.getCount(); pos++)
{
data[pos] = inputStream.readByte();
}
INT8 int8Object = new INT8(data);
if (logger.isLoggable(java.util.logging.Level.FINER))
{
logger.finer(int8Object.toString());
}
// int8Object.size = indexEntry.getType().getSize()
// * indexEntry.getCount();
return int8Object;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#isArray()
*/
public bool isArray()
{
return true;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#getElementCount()
*/
public long getElementCount()
{
return this.data.Length;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#getSize()
*/
public long getSize()
{
return this.size;
}
/*
* @see com.jguild.jrpm.io.datatype.DataTypeIf#get(int)
*/
public Object get(int i)
{
return new java.lang.Byte(this.data[i]);
}
/*
* @see java.lang.Object#toString()
*/
public override String ToString()
{
java.lang.StringBuffer buf = new java.lang.StringBuffer();
if (this.data.Length > 1)
{
buf.append("[");
}
for (int pos = 0; pos < this.data.Length; pos++)
{
buf.append(this.data[pos] & 0x0FF);
if (pos < (this.data.Length - 1))
{
buf.append(", ");
}
}
if (this.data.Length > 1)
{
buf.append("]");
}
return buf.toString();
}
}
} | 27.470588 | 93 | 0.492934 | [
"ECL-2.0",
"Apache-2.0"
] | bastie/NetSpider | archive/codeplex/JavApi jrpm/com/jguild/jrpm/io/datatype/INT8.cs | 4,670 | C# |
// Copyright (c) 2012-2020 VLINGO LABS. All rights reserved.
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0. If a copy of the MPL
// was not distributed with this file, You can obtain
// one at https://mozilla.org/MPL/2.0/.
using System;
using System.IO;
using System.Text;
using Xunit.Abstractions;
namespace Vlingo.Http.Tests
{
public class Converter : TextWriter
{
ITestOutputHelper _output;
public Converter(ITestOutputHelper output)
{
_output = output;
}
public override Encoding Encoding => Encoding.UTF8;
public override void WriteLine(string message)
{
try
{
_output.WriteLine(message);
}
catch (InvalidOperationException e)
{
if (e.Message != "There is no currently active test.")
{
throw;
}
}
}
public override void WriteLine(string format, params object[] args) => _output.WriteLine(format, args);
}
} | 26.348837 | 111 | 0.568402 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Luteceo/vlingo-all | vlingo-net-http/src/Vlingo.Http.Tests/Converter.cs | 1,135 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Numerics;
using System.Reflection;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Transforms;
using SixLabors.ImageSharp.Tests.TestUtilities.ImageComparison;
using Xunit;
using Xunit.Abstractions;
namespace SixLabors.ImageSharp.Tests.Processing.Transforms
{
public class AffineTransformTests
{
private readonly ITestOutputHelper output;
private static readonly ImageComparer ValidatorComparer = ImageComparer.TolerantPercentage(0.033F, 3);
/// <summary>
/// angleDeg, sx, sy, tx, ty
/// </summary>
public static readonly TheoryData<float, float, float, float, float> TransformValues
= new TheoryData<float, float, float, float, float>
{
{ 0, 1, 1, 0, 0 },
{ 50, 1, 1, 0, 0 },
{ 0, 1, 1, 20, 10 },
{ 50, 1, 1, 20, 10 },
{ 0, 1, 1, -20, -10 },
{ 50, 1, 1, -20, -10 },
{ 50, 1.5f, 1.5f, 0, 0 },
{ 50, 1.1F, 1.3F, 30, -20 },
{ 0, 2f, 1f, 0, 0 },
{ 0, 1f, 2f, 0, 0 },
};
public static readonly TheoryData<string> ResamplerNames = new TheoryData<string>
{
nameof(KnownResamplers.Bicubic),
nameof(KnownResamplers.Box),
nameof(KnownResamplers.CatmullRom),
nameof(KnownResamplers.Hermite),
nameof(KnownResamplers.Lanczos2),
nameof(KnownResamplers.Lanczos3),
nameof(KnownResamplers.Lanczos5),
nameof(KnownResamplers.Lanczos8),
nameof(KnownResamplers.MitchellNetravali),
nameof(KnownResamplers.NearestNeighbor),
nameof(KnownResamplers.Robidoux),
nameof(KnownResamplers.RobidouxSharp),
nameof(KnownResamplers.Spline),
nameof(KnownResamplers.Triangle),
nameof(KnownResamplers.Welch),
};
public static readonly TheoryData<string> Transform_DoesNotCreateEdgeArtifacts_ResamplerNames =
new TheoryData<string>
{
nameof(KnownResamplers.NearestNeighbor),
nameof(KnownResamplers.Triangle),
nameof(KnownResamplers.Bicubic),
nameof(KnownResamplers.Lanczos8),
};
public AffineTransformTests(ITestOutputHelper output) => this.output = output;
/// <summary>
/// The output of an "all white" image should be "all white" or transparent, regardless of the transformation and the resampler.
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
[Theory]
[WithSolidFilledImages(nameof(Transform_DoesNotCreateEdgeArtifacts_ResamplerNames), 5, 5, 255, 255, 255, 255, PixelTypes.Rgba32)]
public void Transform_DoesNotCreateEdgeArtifacts<TPixel>(TestImageProvider<TPixel> provider, string resamplerName)
where TPixel : unmanaged, IPixel<TPixel>
{
IResampler resampler = GetResampler(resamplerName);
using (Image<TPixel> image = provider.GetImage())
{
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(30);
image.Mutate(c => c.Transform(builder, resampler));
image.DebugSave(provider, resamplerName);
VerifyAllPixelsAreWhiteOrTransparent(image);
}
}
[Theory]
[WithTestPatternImages(nameof(TransformValues), 100, 50, PixelTypes.Rgba32)]
public void Transform_RotateScaleTranslate<TPixel>(
TestImageProvider<TPixel> provider,
float angleDeg,
float sx,
float sy,
float tx,
float ty)
where TPixel : unmanaged, IPixel<TPixel>
{
using (Image<TPixel> image = provider.GetImage())
{
image.DebugSave(provider, $"_original");
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(angleDeg)
.AppendScale(new SizeF(sx, sy))
.AppendTranslation(new PointF(tx, ty));
this.PrintMatrix(builder.BuildMatrix(image.Size()));
image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic));
FormattableString testOutputDetails = $"R({angleDeg})_S({sx},{sy})_T({tx},{ty})";
image.DebugSave(provider, testOutputDetails);
image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails);
}
}
[Theory]
[WithTestPatternImages(96, 96, PixelTypes.Rgba32, 50, 0.8f)]
public void Transform_RotateScale_ManuallyCentered<TPixel>(TestImageProvider<TPixel> provider, float angleDeg, float s)
where TPixel : unmanaged, IPixel<TPixel>
{
using (Image<TPixel> image = provider.GetImage())
{
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(angleDeg)
.AppendScale(new SizeF(s, s));
image.Mutate(i => i.Transform(builder, KnownResamplers.Bicubic));
FormattableString testOutputDetails = $"R({angleDeg})_S({s})";
image.DebugSave(provider, testOutputDetails);
image.CompareToReferenceOutput(ValidatorComparer, provider, testOutputDetails);
}
}
public static readonly TheoryData<int, int, int, int> Transform_IntoRectangle_Data =
new TheoryData<int, int, int, int>
{
{ 0, 0, 10, 10 },
{ 0, 0, 5, 10 },
{ 0, 0, 10, 5 },
{ 5, 0, 5, 10 },
{ -5, -5, 20, 20 }
};
/// <summary>
/// Testing transforms using custom source rectangles:
/// https://github.com/SixLabors/ImageSharp/pull/386#issuecomment-357104963
/// </summary>
/// <typeparam name="TPixel">The pixel type of the image.</typeparam>
[Theory]
[WithTestPatternImages(96, 48, PixelTypes.Rgba32)]
public void Transform_FromSourceRectangle1<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : unmanaged, IPixel<TPixel>
{
var rectangle = new Rectangle(48, 0, 48, 24);
using (Image<TPixel> image = provider.GetImage())
{
image.DebugSave(provider, $"_original");
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendScale(new SizeF(2, 1.5F));
image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline));
image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider);
}
}
[Theory]
[WithTestPatternImages(96, 48, PixelTypes.Rgba32)]
public void Transform_FromSourceRectangle2<TPixel>(TestImageProvider<TPixel> provider)
where TPixel : unmanaged, IPixel<TPixel>
{
var rectangle = new Rectangle(0, 24, 48, 24);
using (Image<TPixel> image = provider.GetImage())
{
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendScale(new SizeF(1F, 2F));
image.Mutate(i => i.Transform(rectangle, builder, KnownResamplers.Spline));
image.DebugSave(provider);
image.CompareToReferenceOutput(ValidatorComparer, provider);
}
}
[Theory]
[WithTestPatternImages(nameof(ResamplerNames), 150, 150, PixelTypes.Rgba32)]
public void Transform_WithSampler<TPixel>(TestImageProvider<TPixel> provider, string resamplerName)
where TPixel : unmanaged, IPixel<TPixel>
{
IResampler sampler = GetResampler(resamplerName);
using (Image<TPixel> image = provider.GetImage())
{
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(50)
.AppendScale(new SizeF(.6F, .6F));
image.Mutate(i => i.Transform(builder, sampler));
image.DebugSave(provider, resamplerName);
image.CompareToReferenceOutput(ValidatorComparer, provider, resamplerName);
}
}
[Theory]
[WithTestPatternImages(100, 100, PixelTypes.Rgba32, 21)]
public void WorksWithDiscoBuffers<TPixel>(TestImageProvider<TPixel> provider, int bufferCapacityInPixelRows)
where TPixel : unmanaged, IPixel<TPixel>
{
AffineTransformBuilder builder = new AffineTransformBuilder()
.AppendRotationDegrees(50)
.AppendScale(new SizeF(.6F, .6F));
provider.RunBufferCapacityLimitProcessorTest(
bufferCapacityInPixelRows,
c => c.Transform(builder));
}
private static IResampler GetResampler(string name)
{
PropertyInfo property = typeof(KnownResamplers).GetTypeInfo().GetProperty(name);
if (property is null)
{
throw new Exception($"No resampler named {name}");
}
return (IResampler)property.GetValue(null);
}
private static void VerifyAllPixelsAreWhiteOrTransparent<TPixel>(Image<TPixel> image)
where TPixel : unmanaged, IPixel<TPixel>
{
Assert.True(image.Frames.RootFrame.TryGetSinglePixelSpan(out Span<TPixel> data));
var white = new Rgb24(255, 255, 255);
foreach (TPixel pixel in data)
{
Rgba32 rgba = default;
pixel.ToRgba32(ref rgba);
if (rgba.A == 0)
{
continue;
}
Assert.Equal(white, rgba.Rgb);
}
}
private void PrintMatrix(Matrix3x2 a)
{
string s = $"{a.M11:F10},{a.M12:F10},{a.M21:F10},{a.M22:F10},{a.M31:F10},{a.M32:F10}";
this.output.WriteLine(s);
}
}
}
| 40.38403 | 137 | 0.576217 | [
"Apache-2.0"
] | CoenraadS/ImageSharp | tests/ImageSharp.Tests/Processing/Processors/Transforms/AffineTransformTests.cs | 10,621 | C# |
using JK.GuildWars2Api.V2;
using System.Collections.Generic;
namespace GuildWars2Tome.Models
{
public class Stash
{
public Stash(GuildStash stash, GuildUpgrade upgrade)
{
this.Items = new List<StashItem>();
this.Coins = stash.Coins;
this.Icon = upgrade.Icon;
this.Name = upgrade.Name;
this.Note = stash.Note;
}
public List<StashItem> Items { get; set; }
public int Coins { get; private set; }
public string Icon { get; private set; }
public string Name { get; private set; }
public string Note { get; private set; }
}
}
| 27.708333 | 60 | 0.577444 | [
"MIT"
] | jeremyknight-me/guildwars2tome | src/GuildWars2Tome/Models/Stash.cs | 667 | C# |
using Prism.Events;
namespace AntilopeGP.Shared.Events
{
public class AnalyticsEvent : PubSubEvent<AnalyticsReport>
{
}
}
| 14 | 59 | 0.777778 | [
"MIT"
] | Banou26/tcl-live-realtime-utils | decompiled/AntilopeGP.Shared.Events/AnalyticsEvent.cs | 126 | C# |
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace eOnlineCarShop.ViewModels
{
public class UserEditVM
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public DateTime BirthDate { get; set; }
public int CityID { get; set; }
public List<SelectListItem> City { get; set; }
public string Adress { get; set; }
[Required]
public string PhoneNumber { get; set; }
public int GenderID { get; set; }
public List<SelectListItem> Gender { get; set; }
}
}
| 25.1875 | 56 | 0.630273 | [
"MIT"
] | Haris-Basic/RSI-2020 | Webapp/eOnlineCarShop/ViewModels/UserEditVM.cs | 808 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyUSC.Account {
public partial class Login {
/// <summary>
/// RegisterHyperLink control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink RegisterHyperLink;
/// <summary>
/// LoginUser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Login LoginUser;
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new MyUSC.SiteMaster Master {
get {
return ((MyUSC.SiteMaster)(base.Master));
}
}
}
}
| 30.5 | 84 | 0.47541 | [
"Unlicense"
] | tlayson/MySC | MyUSC/Account/Login.aspx.designer.cs | 1,405 | C# |
namespace MK6.GameKeeper.AddIns.HostView
{
public interface GameKeeperAddIn
{
void Start();
void Stop();
AddInStatus Status { get; }
}
}
| 17.4 | 41 | 0.591954 | [
"MIT"
] | market6/MK6.GameKeeper | MK6.GameKeeper.AddIns.HostView/GameKeeperAddIn.cs | 176 | C# |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.9.1 informationa bout aggregating entities anc communicating information about the aggregated entities. requires manual intervention to fix the padding between entityID lists and silent aggregate sysem lists--this padding is dependent on how many entityIDs there are, and needs to be on a 32 bit word boundary. UNFINISHED
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EntityType))]
[XmlInclude(typeof(AggregateMarking))]
[XmlInclude(typeof(Vector3Float))]
[XmlInclude(typeof(Orientation))]
[XmlInclude(typeof(Vector3Double))]
[XmlInclude(typeof(AggregateID))]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EntityType))]
[XmlInclude(typeof(EntityType))]
[XmlInclude(typeof(VariableDatum))]
public partial class AggregateStatePdu : EntityManagementFamilyPdu, IEquatable<AggregateStatePdu>
{
/// <summary>
/// ID of aggregated entities
/// </summary>
private EntityID _aggregateID = new EntityID();
/// <summary>
/// force ID
/// </summary>
private byte _forceID;
/// <summary>
/// state of aggregate
/// </summary>
private byte _aggregateState;
/// <summary>
/// entity type of the aggregated entities
/// </summary>
private EntityType _aggregateType = new EntityType();
/// <summary>
/// formation of aggregated entities
/// </summary>
private uint _formation;
/// <summary>
/// marking for aggregate; first char is charset type, rest is char data
/// </summary>
private AggregateMarking _aggregateMarking = new AggregateMarking();
/// <summary>
/// dimensions of bounding box for the aggregated entities, origin at the center of mass
/// </summary>
private Vector3Float _dimensions = new Vector3Float();
/// <summary>
/// orientation of the bounding box
/// </summary>
private Orientation _orientation = new Orientation();
/// <summary>
/// center of mass of the aggregation
/// </summary>
private Vector3Double _centerOfMass = new Vector3Double();
/// <summary>
/// velocity of aggregation
/// </summary>
private Vector3Float _velocity = new Vector3Float();
/// <summary>
/// number of aggregates
/// </summary>
private ushort _numberOfDisAggregates;
/// <summary>
/// number of entities
/// </summary>
private ushort _numberOfDisEntities;
/// <summary>
/// number of silent aggregate types
/// </summary>
private ushort _numberOfSilentAggregateTypes;
/// <summary>
/// number of silent entity types
/// </summary>
private ushort _numberOfSilentEntityTypes;
/// <summary>
/// aggregates list
/// </summary>
private List<AggregateID> _aggregateIDList = new List<AggregateID>();
/// <summary>
/// entity ID list
/// </summary>
private List<EntityID> _entityIDList = new List<EntityID>();
/// <summary>
/// ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed
/// </summary>
private byte _pad2;
/// <summary>
/// silent entity types
/// </summary>
private List<EntityType> _silentAggregateSystemList = new List<EntityType>();
/// <summary>
/// silent entity types
/// </summary>
private List<EntityType> _silentEntitySystemList = new List<EntityType>();
/// <summary>
/// number of variable datum records
/// </summary>
private uint _numberOfVariableDatumRecords;
/// <summary>
/// variableDatums
/// </summary>
private List<VariableDatum> _variableDatumList = new List<VariableDatum>();
/// <summary>
/// Initializes a new instance of the <see cref="AggregateStatePdu"/> class.
/// </summary>
public AggregateStatePdu()
{
PduType = (byte)33;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(AggregateStatePdu left, AggregateStatePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(AggregateStatePdu left, AggregateStatePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._aggregateID.GetMarshalledSize(); // this._aggregateID
marshalSize += 1; // this._forceID
marshalSize += 1; // this._aggregateState
marshalSize += this._aggregateType.GetMarshalledSize(); // this._aggregateType
marshalSize += 4; // this._formation
marshalSize += this._aggregateMarking.GetMarshalledSize(); // this._aggregateMarking
marshalSize += this._dimensions.GetMarshalledSize(); // this._dimensions
marshalSize += this._orientation.GetMarshalledSize(); // this._orientation
marshalSize += this._centerOfMass.GetMarshalledSize(); // this._centerOfMass
marshalSize += this._velocity.GetMarshalledSize(); // this._velocity
marshalSize += 2; // this._numberOfDisAggregates
marshalSize += 2; // this._numberOfDisEntities
marshalSize += 2; // this._numberOfSilentAggregateTypes
marshalSize += 2; // this._numberOfSilentEntityTypes
for (int idx = 0; idx < this._aggregateIDList.Count; idx++)
{
AggregateID listElement = (AggregateID)this._aggregateIDList[idx];
marshalSize += listElement.GetMarshalledSize();
}
for (int idx = 0; idx < this._entityIDList.Count; idx++)
{
EntityID listElement = (EntityID)this._entityIDList[idx];
marshalSize += listElement.GetMarshalledSize();
}
marshalSize += 1; // this._pad2
for (int idx = 0; idx < this._silentAggregateSystemList.Count; idx++)
{
EntityType listElement = (EntityType)this._silentAggregateSystemList[idx];
marshalSize += listElement.GetMarshalledSize();
}
for (int idx = 0; idx < this._silentEntitySystemList.Count; idx++)
{
EntityType listElement = (EntityType)this._silentEntitySystemList[idx];
marshalSize += listElement.GetMarshalledSize();
}
marshalSize += 4; // this._numberOfVariableDatumRecords
for (int idx = 0; idx < this._variableDatumList.Count; idx++)
{
VariableDatum listElement = (VariableDatum)this._variableDatumList[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of aggregated entities
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "aggregateID")]
public EntityID AggregateID
{
get
{
return this._aggregateID;
}
set
{
this._aggregateID = value;
}
}
/// <summary>
/// Gets or sets the force ID
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "forceID")]
public byte ForceID
{
get
{
return this._forceID;
}
set
{
this._forceID = value;
}
}
/// <summary>
/// Gets or sets the state of aggregate
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "aggregateState")]
public byte AggregateState
{
get
{
return this._aggregateState;
}
set
{
this._aggregateState = value;
}
}
/// <summary>
/// Gets or sets the entity type of the aggregated entities
/// </summary>
[XmlElement(Type = typeof(EntityType), ElementName = "aggregateType")]
public EntityType AggregateType
{
get
{
return this._aggregateType;
}
set
{
this._aggregateType = value;
}
}
/// <summary>
/// Gets or sets the formation of aggregated entities
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "formation")]
public uint Formation
{
get
{
return this._formation;
}
set
{
this._formation = value;
}
}
/// <summary>
/// Gets or sets the marking for aggregate; first char is charset type, rest is char data
/// </summary>
[XmlElement(Type = typeof(AggregateMarking), ElementName = "aggregateMarking")]
public AggregateMarking AggregateMarking
{
get
{
return this._aggregateMarking;
}
set
{
this._aggregateMarking = value;
}
}
/// <summary>
/// Gets or sets the dimensions of bounding box for the aggregated entities, origin at the center of mass
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "dimensions")]
public Vector3Float Dimensions
{
get
{
return this._dimensions;
}
set
{
this._dimensions = value;
}
}
/// <summary>
/// Gets or sets the orientation of the bounding box
/// </summary>
[XmlElement(Type = typeof(Orientation), ElementName = "orientation")]
public Orientation Orientation
{
get
{
return this._orientation;
}
set
{
this._orientation = value;
}
}
/// <summary>
/// Gets or sets the center of mass of the aggregation
/// </summary>
[XmlElement(Type = typeof(Vector3Double), ElementName = "centerOfMass")]
public Vector3Double CenterOfMass
{
get
{
return this._centerOfMass;
}
set
{
this._centerOfMass = value;
}
}
/// <summary>
/// Gets or sets the velocity of aggregation
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "velocity")]
public Vector3Float Velocity
{
get
{
return this._velocity;
}
set
{
this._velocity = value;
}
}
/// <summary>
/// Gets or sets the number of aggregates
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfDisAggregates method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "numberOfDisAggregates")]
public ushort NumberOfDisAggregates
{
get
{
return this._numberOfDisAggregates;
}
set
{
this._numberOfDisAggregates = value;
}
}
/// <summary>
/// Gets or sets the number of entities
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfDisEntities method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "numberOfDisEntities")]
public ushort NumberOfDisEntities
{
get
{
return this._numberOfDisEntities;
}
set
{
this._numberOfDisEntities = value;
}
}
/// <summary>
/// Gets or sets the number of silent aggregate types
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfSilentAggregateTypes method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "numberOfSilentAggregateTypes")]
public ushort NumberOfSilentAggregateTypes
{
get
{
return this._numberOfSilentAggregateTypes;
}
set
{
this._numberOfSilentAggregateTypes = value;
}
}
/// <summary>
/// Gets or sets the number of silent entity types
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfSilentEntityTypes method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(ushort), ElementName = "numberOfSilentEntityTypes")]
public ushort NumberOfSilentEntityTypes
{
get
{
return this._numberOfSilentEntityTypes;
}
set
{
this._numberOfSilentEntityTypes = value;
}
}
/// <summary>
/// Gets the aggregates list
/// </summary>
[XmlElement(ElementName = "aggregateIDListList", Type = typeof(List<AggregateID>))]
public List<AggregateID> AggregateIDList
{
get
{
return this._aggregateIDList;
}
}
/// <summary>
/// Gets the entity ID list
/// </summary>
[XmlElement(ElementName = "entityIDListList", Type = typeof(List<EntityID>))]
public List<EntityID> EntityIDList
{
get
{
return this._entityIDList;
}
}
/// <summary>
/// Gets or sets the ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "pad2")]
public byte Pad2
{
get
{
return this._pad2;
}
set
{
this._pad2 = value;
}
}
/// <summary>
/// Gets the silent entity types
/// </summary>
[XmlElement(ElementName = "silentAggregateSystemListList", Type = typeof(List<EntityType>))]
public List<EntityType> SilentAggregateSystemList
{
get
{
return this._silentAggregateSystemList;
}
}
/// <summary>
/// Gets the silent entity types
/// </summary>
[XmlElement(ElementName = "silentEntitySystemListList", Type = typeof(List<EntityType>))]
public List<EntityType> SilentEntitySystemList
{
get
{
return this._silentEntitySystemList;
}
}
/// <summary>
/// Gets or sets the number of variable datum records
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")]
public uint NumberOfVariableDatumRecords
{
get
{
return this._numberOfVariableDatumRecords;
}
set
{
this._numberOfVariableDatumRecords = value;
}
}
/// <summary>
/// Gets the variableDatums
/// </summary>
[XmlElement(ElementName = "variableDatumListList", Type = typeof(List<VariableDatum>))]
public List<VariableDatum> VariableDatumList
{
get
{
return this._variableDatumList;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._aggregateID.Marshal(dos);
dos.WriteUnsignedByte((byte)this._forceID);
dos.WriteUnsignedByte((byte)this._aggregateState);
this._aggregateType.Marshal(dos);
dos.WriteUnsignedInt((uint)this._formation);
this._aggregateMarking.Marshal(dos);
this._dimensions.Marshal(dos);
this._orientation.Marshal(dos);
this._centerOfMass.Marshal(dos);
this._velocity.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._aggregateIDList.Count);
dos.WriteUnsignedShort((ushort)this._entityIDList.Count);
dos.WriteUnsignedShort((ushort)this._silentAggregateSystemList.Count);
dos.WriteUnsignedShort((ushort)this._silentEntitySystemList.Count);
for (int idx = 0; idx < this._aggregateIDList.Count; idx++)
{
AggregateID aAggregateID = (AggregateID)this._aggregateIDList[idx];
aAggregateID.Marshal(dos);
}
for (int idx = 0; idx < this._entityIDList.Count; idx++)
{
EntityID aEntityID = (EntityID)this._entityIDList[idx];
aEntityID.Marshal(dos);
}
dos.WriteUnsignedByte((byte)this._pad2);
for (int idx = 0; idx < this._silentAggregateSystemList.Count; idx++)
{
EntityType aEntityType = (EntityType)this._silentAggregateSystemList[idx];
aEntityType.Marshal(dos);
}
for (int idx = 0; idx < this._silentEntitySystemList.Count; idx++)
{
EntityType aEntityType = (EntityType)this._silentEntitySystemList[idx];
aEntityType.Marshal(dos);
}
dos.WriteUnsignedInt((uint)this._variableDatumList.Count);
for (int idx = 0; idx < this._variableDatumList.Count; idx++)
{
VariableDatum aVariableDatum = (VariableDatum)this._variableDatumList[idx];
aVariableDatum.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._aggregateID.Unmarshal(dis);
this._forceID = dis.ReadUnsignedByte();
this._aggregateState = dis.ReadUnsignedByte();
this._aggregateType.Unmarshal(dis);
this._formation = dis.ReadUnsignedInt();
this._aggregateMarking.Unmarshal(dis);
this._dimensions.Unmarshal(dis);
this._orientation.Unmarshal(dis);
this._centerOfMass.Unmarshal(dis);
this._velocity.Unmarshal(dis);
this._numberOfDisAggregates = dis.ReadUnsignedShort();
this._numberOfDisEntities = dis.ReadUnsignedShort();
this._numberOfSilentAggregateTypes = dis.ReadUnsignedShort();
this._numberOfSilentEntityTypes = dis.ReadUnsignedShort();
for (int idx = 0; idx < this.NumberOfDisAggregates; idx++)
{
AggregateID anX = new AggregateID();
anX.Unmarshal(dis);
this._aggregateIDList.Add(anX);
}
for (int idx = 0; idx < this.NumberOfDisEntities; idx++)
{
EntityID anX = new EntityID();
anX.Unmarshal(dis);
this._entityIDList.Add(anX);
}
this._pad2 = dis.ReadUnsignedByte();
for (int idx = 0; idx < this.NumberOfSilentAggregateTypes; idx++)
{
EntityType anX = new EntityType();
anX.Unmarshal(dis);
this._silentAggregateSystemList.Add(anX);
}
for (int idx = 0; idx < this.NumberOfSilentEntityTypes; idx++)
{
EntityType anX = new EntityType();
anX.Unmarshal(dis);
this._silentEntitySystemList.Add(anX);
}
this._numberOfVariableDatumRecords = dis.ReadUnsignedInt();
for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++)
{
VariableDatum anX = new VariableDatum();
anX.Unmarshal(dis);
this._variableDatumList.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<AggregateStatePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<aggregateID>");
this._aggregateID.Reflection(sb);
sb.AppendLine("</aggregateID>");
sb.AppendLine("<forceID type=\"byte\">" + this._forceID.ToString(CultureInfo.InvariantCulture) + "</forceID>");
sb.AppendLine("<aggregateState type=\"byte\">" + this._aggregateState.ToString(CultureInfo.InvariantCulture) + "</aggregateState>");
sb.AppendLine("<aggregateType>");
this._aggregateType.Reflection(sb);
sb.AppendLine("</aggregateType>");
sb.AppendLine("<formation type=\"uint\">" + this._formation.ToString(CultureInfo.InvariantCulture) + "</formation>");
sb.AppendLine("<aggregateMarking>");
this._aggregateMarking.Reflection(sb);
sb.AppendLine("</aggregateMarking>");
sb.AppendLine("<dimensions>");
this._dimensions.Reflection(sb);
sb.AppendLine("</dimensions>");
sb.AppendLine("<orientation>");
this._orientation.Reflection(sb);
sb.AppendLine("</orientation>");
sb.AppendLine("<centerOfMass>");
this._centerOfMass.Reflection(sb);
sb.AppendLine("</centerOfMass>");
sb.AppendLine("<velocity>");
this._velocity.Reflection(sb);
sb.AppendLine("</velocity>");
sb.AppendLine("<aggregateIDList type=\"ushort\">" + this._aggregateIDList.Count.ToString(CultureInfo.InvariantCulture) + "</aggregateIDList>");
sb.AppendLine("<entityIDList type=\"ushort\">" + this._entityIDList.Count.ToString(CultureInfo.InvariantCulture) + "</entityIDList>");
sb.AppendLine("<silentAggregateSystemList type=\"ushort\">" + this._silentAggregateSystemList.Count.ToString(CultureInfo.InvariantCulture) + "</silentAggregateSystemList>");
sb.AppendLine("<silentEntitySystemList type=\"ushort\">" + this._silentEntitySystemList.Count.ToString(CultureInfo.InvariantCulture) + "</silentEntitySystemList>");
for (int idx = 0; idx < this._aggregateIDList.Count; idx++)
{
sb.AppendLine("<aggregateIDList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"AggregateID\">");
AggregateID aAggregateID = (AggregateID)this._aggregateIDList[idx];
aAggregateID.Reflection(sb);
sb.AppendLine("</aggregateIDList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
for (int idx = 0; idx < this._entityIDList.Count; idx++)
{
sb.AppendLine("<entityIDList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"EntityID\">");
EntityID aEntityID = (EntityID)this._entityIDList[idx];
aEntityID.Reflection(sb);
sb.AppendLine("</entityIDList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("<pad2 type=\"byte\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>");
for (int idx = 0; idx < this._silentAggregateSystemList.Count; idx++)
{
sb.AppendLine("<silentAggregateSystemList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"EntityType\">");
EntityType aEntityType = (EntityType)this._silentAggregateSystemList[idx];
aEntityType.Reflection(sb);
sb.AppendLine("</silentAggregateSystemList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
for (int idx = 0; idx < this._silentEntitySystemList.Count; idx++)
{
sb.AppendLine("<silentEntitySystemList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"EntityType\">");
EntityType aEntityType = (EntityType)this._silentEntitySystemList[idx];
aEntityType.Reflection(sb);
sb.AppendLine("</silentEntitySystemList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("<variableDatumList type=\"uint\">" + this._variableDatumList.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatumList>");
for (int idx = 0; idx < this._variableDatumList.Count; idx++)
{
sb.AppendLine("<variableDatumList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">");
VariableDatum aVariableDatum = (VariableDatum)this._variableDatumList[idx];
aVariableDatum.Reflection(sb);
sb.AppendLine("</variableDatumList" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</AggregateStatePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as AggregateStatePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(AggregateStatePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._aggregateID.Equals(obj._aggregateID))
{
ivarsEqual = false;
}
if (this._forceID != obj._forceID)
{
ivarsEqual = false;
}
if (this._aggregateState != obj._aggregateState)
{
ivarsEqual = false;
}
if (!this._aggregateType.Equals(obj._aggregateType))
{
ivarsEqual = false;
}
if (this._formation != obj._formation)
{
ivarsEqual = false;
}
if (!this._aggregateMarking.Equals(obj._aggregateMarking))
{
ivarsEqual = false;
}
if (!this._dimensions.Equals(obj._dimensions))
{
ivarsEqual = false;
}
if (!this._orientation.Equals(obj._orientation))
{
ivarsEqual = false;
}
if (!this._centerOfMass.Equals(obj._centerOfMass))
{
ivarsEqual = false;
}
if (!this._velocity.Equals(obj._velocity))
{
ivarsEqual = false;
}
if (this._numberOfDisAggregates != obj._numberOfDisAggregates)
{
ivarsEqual = false;
}
if (this._numberOfDisEntities != obj._numberOfDisEntities)
{
ivarsEqual = false;
}
if (this._numberOfSilentAggregateTypes != obj._numberOfSilentAggregateTypes)
{
ivarsEqual = false;
}
if (this._numberOfSilentEntityTypes != obj._numberOfSilentEntityTypes)
{
ivarsEqual = false;
}
if (this._aggregateIDList.Count != obj._aggregateIDList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._aggregateIDList.Count; idx++)
{
if (!this._aggregateIDList[idx].Equals(obj._aggregateIDList[idx]))
{
ivarsEqual = false;
}
}
}
if (this._entityIDList.Count != obj._entityIDList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._entityIDList.Count; idx++)
{
if (!this._entityIDList[idx].Equals(obj._entityIDList[idx]))
{
ivarsEqual = false;
}
}
}
if (this._pad2 != obj._pad2)
{
ivarsEqual = false;
}
if (this._silentAggregateSystemList.Count != obj._silentAggregateSystemList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._silentAggregateSystemList.Count; idx++)
{
if (!this._silentAggregateSystemList[idx].Equals(obj._silentAggregateSystemList[idx]))
{
ivarsEqual = false;
}
}
}
if (this._silentEntitySystemList.Count != obj._silentEntitySystemList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._silentEntitySystemList.Count; idx++)
{
if (!this._silentEntitySystemList[idx].Equals(obj._silentEntitySystemList[idx]))
{
ivarsEqual = false;
}
}
}
if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords)
{
ivarsEqual = false;
}
if (this._variableDatumList.Count != obj._variableDatumList.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._variableDatumList.Count; idx++)
{
if (!this._variableDatumList[idx].Equals(obj._variableDatumList[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._aggregateID.GetHashCode();
result = GenerateHash(result) ^ this._forceID.GetHashCode();
result = GenerateHash(result) ^ this._aggregateState.GetHashCode();
result = GenerateHash(result) ^ this._aggregateType.GetHashCode();
result = GenerateHash(result) ^ this._formation.GetHashCode();
result = GenerateHash(result) ^ this._aggregateMarking.GetHashCode();
result = GenerateHash(result) ^ this._dimensions.GetHashCode();
result = GenerateHash(result) ^ this._orientation.GetHashCode();
result = GenerateHash(result) ^ this._centerOfMass.GetHashCode();
result = GenerateHash(result) ^ this._velocity.GetHashCode();
result = GenerateHash(result) ^ this._numberOfDisAggregates.GetHashCode();
result = GenerateHash(result) ^ this._numberOfDisEntities.GetHashCode();
result = GenerateHash(result) ^ this._numberOfSilentAggregateTypes.GetHashCode();
result = GenerateHash(result) ^ this._numberOfSilentEntityTypes.GetHashCode();
if (this._aggregateIDList.Count > 0)
{
for (int idx = 0; idx < this._aggregateIDList.Count; idx++)
{
result = GenerateHash(result) ^ this._aggregateIDList[idx].GetHashCode();
}
}
if (this._entityIDList.Count > 0)
{
for (int idx = 0; idx < this._entityIDList.Count; idx++)
{
result = GenerateHash(result) ^ this._entityIDList[idx].GetHashCode();
}
}
result = GenerateHash(result) ^ this._pad2.GetHashCode();
if (this._silentAggregateSystemList.Count > 0)
{
for (int idx = 0; idx < this._silentAggregateSystemList.Count; idx++)
{
result = GenerateHash(result) ^ this._silentAggregateSystemList[idx].GetHashCode();
}
}
if (this._silentEntitySystemList.Count > 0)
{
for (int idx = 0; idx < this._silentEntitySystemList.Count; idx++)
{
result = GenerateHash(result) ^ this._silentEntitySystemList[idx].GetHashCode();
}
}
result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode();
if (this._variableDatumList.Count > 0)
{
for (int idx = 0; idx < this._variableDatumList.Count; idx++)
{
result = GenerateHash(result) ^ this._variableDatumList[idx].GetHashCode();
}
}
return result;
}
}
}
| 37.101609 | 355 | 0.533674 | [
"BSD-2-Clause"
] | mastertnt/open-dis-csharp | Libs/CsharpDis6/Dis1998/Generated/AggregateStatePdu.cs | 43,817 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace hitmanstat.us.Migrations
{
public partial class RemoveStadiaFistCounter : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "H1st",
table: "UserReportCounter");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "H1st",
table: "UserReportCounter",
type: "int",
nullable: false,
defaultValue: 0);
}
}
}
| 27.04 | 71 | 0.566568 | [
"MIT"
] | hardware/hitmanstat.us.v2 | hitmanstat.us/Migrations/20200902123036_RemoveStadiaFistCounter.cs | 678 | C# |
using System.Text;
using AwesomeMPlayer.Api.Data;
using AwesomeMPlayer.Api.Models;
using AwesomeMPlayer.Api.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace AwesomeMPlayer.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<ApplicationDbContext>();
services.AddIdentityCore<User>()
.AddRoles<UserRole>()
.AddRoleManager<RoleManager<UserRole>>()
.AddSignInManager<SignInManager<User>>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<TokenManagement>(Configuration.GetSection("tokenManagement"));
var token = Configuration.GetSection("tokenManagement").Get<TokenManagement>();
var secret = Encoding.ASCII.GetBytes(token.Secret);
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = true;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
ValidIssuer = token.Issuer,
ValidAudience = token.Audience,
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
services.AddScoped<IUserManagementService, UserManagementService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseHsts();
app.UseHttpsRedirection();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader());
app.UseAuthentication();
app.UseMvc();
}
}
}
| 38.888889 | 111 | 0.588214 | [
"MIT"
] | suxrobGM/AwesomeMPlayer | src/AwesomeMPlayer.Api/Startup.cs | 2,802 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Model\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Windows Malware Information.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class WindowsMalwareInformation : Entity
{
/// <summary>
/// Gets or sets display name.
/// Malware name
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "displayName", Required = Newtonsoft.Json.Required.Default)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets additional information url.
/// Information URL to learn more about the malware
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "additionalInformationUrl", Required = Newtonsoft.Json.Required.Default)]
public string AdditionalInformationUrl { get; set; }
/// <summary>
/// Gets or sets severity.
/// Severity of the malware
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "severity", Required = Newtonsoft.Json.Required.Default)]
public WindowsMalwareSeverity? Severity { get; set; }
/// <summary>
/// Gets or sets category.
/// Category of the malware
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "category", Required = Newtonsoft.Json.Required.Default)]
public WindowsMalwareCategory? Category { get; set; }
/// <summary>
/// Gets or sets last detection date time.
/// The last time the malware is detected
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "lastDetectionDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? LastDetectionDateTime { get; set; }
/// <summary>
/// Gets or sets windows devices protection state.
/// List of devices' protection status affected with the current malware
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "windowsDevicesProtectionState", Required = Newtonsoft.Json.Required.Default)]
public IWindowsMalwareInformationWindowsDevicesProtectionStateCollectionPage WindowsDevicesProtectionState { get; set; }
}
}
| 43.928571 | 161 | 0.637398 | [
"MIT"
] | gurry/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/WindowsMalwareInformation.cs | 3,075 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Dist.Dme.Model.DTO
{
/// <summary>
/// 模型版本新增简单DTO
/// </summary>
public class ModelVersionSimpleAddDTO
{
/// <summary>
/// 模型id
/// </summary>
[Required]
public int ModelId { get; set; }
/// <summary>
/// 版本名称
/// </summary>
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
}
}
| 21.16 | 45 | 0.561437 | [
"Apache-2.0"
] | zhongshuiyuan/dme | src/Dist.Product.Dme/Dist.Dme.Model/DTO/ModelVersionSimpleAddDTO.cs | 559 | C# |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
namespace ClientSample
{
public class SocketSender
{
private readonly Socket _socket;
private readonly SocketAsyncEventArgs _eventArgs = new SocketAsyncEventArgs();
private readonly SocketAwaitable _awaitable;
private List<ArraySegment<byte>> _bufferList;
public SocketSender(Socket socket, PipeScheduler scheduler)
{
_socket = socket;
_awaitable = new SocketAwaitable(scheduler);
_eventArgs.UserToken = _awaitable;
_eventArgs.Completed += (_, e) => ((SocketAwaitable)e.UserToken).Complete(e.BytesTransferred, e.SocketError);
}
public SocketAwaitable SendAsync(in ReadOnlySequence<byte> buffers)
{
if (buffers.IsSingleSegment)
{
return SendAsync(buffers.First);
}
#if NETCOREAPP2_2
if (!_eventArgs.MemoryBuffer.Equals(Memory<byte>.Empty))
#else
if (_eventArgs.Buffer != null)
#endif
{
_eventArgs.SetBuffer(null, 0, 0);
}
_eventArgs.BufferList = GetBufferList(buffers);
if (!_socket.SendAsync(_eventArgs))
{
_awaitable.Complete(_eventArgs.BytesTransferred, _eventArgs.SocketError);
}
return _awaitable;
}
private SocketAwaitable SendAsync(ReadOnlyMemory<byte> memory)
{
// The BufferList getter is much less expensive then the setter.
if (_eventArgs.BufferList != null)
{
_eventArgs.BufferList = null;
}
#if NETCOREAPP2_2
_eventArgs.SetBuffer(MemoryMarshal.AsMemory(memory));
#else
var segment = memory.GetArray();
_eventArgs.SetBuffer(segment.Array, segment.Offset, segment.Count);
#endif
if (!_socket.SendAsync(_eventArgs))
{
_awaitable.Complete(_eventArgs.BytesTransferred, _eventArgs.SocketError);
}
return _awaitable;
}
private List<ArraySegment<byte>> GetBufferList(in ReadOnlySequence<byte> buffer)
{
Debug.Assert(!buffer.IsEmpty);
Debug.Assert(!buffer.IsSingleSegment);
if (_bufferList == null)
{
_bufferList = new List<ArraySegment<byte>>();
}
else
{
// Buffers are pooled, so it's OK to root them until the next multi-buffer write.
_bufferList.Clear();
}
foreach (var b in buffer)
{
_bufferList.Add(b.GetArray());
}
return _bufferList;
}
}
}
| 28.970297 | 121 | 0.583732 | [
"Apache-2.0"
] | FraserKillip/SignalR | samples/ClientSample/Tcp/SocketSender.cs | 2,928 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20161201.Inputs
{
/// <summary>
/// SKU of an application gateway
/// </summary>
public sealed class ApplicationGatewaySkuArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Capacity (instance count) of an application gateway.
/// </summary>
[Input("capacity")]
public Input<int>? Capacity { get; set; }
/// <summary>
/// Name of an application gateway SKU. Possible values are: 'Standard_Small', 'Standard_Medium', 'Standard_Large', 'WAF_Medium', and 'WAF_Large'.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Tier of an application gateway. Possible values are: 'Standard' and 'WAF'.
/// </summary>
[Input("tier")]
public Input<string>? Tier { get; set; }
public ApplicationGatewaySkuArgs()
{
}
}
}
| 30.487805 | 154 | 0.616 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20161201/Inputs/ApplicationGatewaySkuArgs.cs | 1,250 | C# |
using DSharpPlus.Entities;
using System;
namespace sisbase.Attributes
{
/// <summary>
/// Atribute that sets the emoji for the command group
/// </summary>
public class EmojiAttribute : Attribute
{
/// <summary>
/// The emoji that will be used by the command group
/// </summary>
public DiscordEmoji Emoji;
/// <summary>
/// Constructs a new EmojiAttribute from a <see cref="DiscordEmoji"/>
/// </summary>
/// <param name="emoji">The emoji</param>
public EmojiAttribute(DiscordEmoji emoji) => Emoji = emoji;
/// <summary>
/// Constructs a new EmojiAttribute from an unicode name <br></br>
/// Eg. :computer: , :white_check_mark:
/// </summary>
/// <param name="name">The discord name(requires being surrounded by colons)</param>
public EmojiAttribute(string name) => Emoji = DiscordEmoji.FromName(SisbaseBot.Instance.Client, name);
/// <summary>
/// Constructs a new EmojiAttribute from an known guild emoji id.
/// </summary>
/// <param name="id">The id</param>
public EmojiAttribute(ulong id) => Emoji = DiscordEmoji.FromGuildEmote(SisbaseBot.Instance.Client, id);
}
} | 32.911765 | 105 | 0.689008 | [
"MIT"
] | RORIdev/sisbase | Attributes/EmojiAttribute.cs | 1,119 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ApiRegistry.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ApiRegistry.Web")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("658da84d-ad6c-414a-9333-b89232911187")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.833333 | 84 | 0.748899 | [
"MIT"
] | QuinntyneBrown/api-registry | ApiRegistry.Web/Properties/AssemblyInfo.cs | 1,363 | C# |
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Swashbuckle.AspNetCore.SwaggerGen;
using HETSAPI.Models;
using HETSAPI.Services;
using HETSAPI.Authorization;
namespace HETSAPI.Controllers
{
/// <summary>
/// Equipment Type Controller
/// </summary>
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class EquipmentTypeController : Controller
{
private readonly IEquipmentTypeService _service;
/// <summary>
/// Equipment Type Controller Collection
/// </summary>
public EquipmentTypeController(IEquipmentTypeService service)
{
_service = service;
}
/// <summary>
/// Create bulk equipment type records
/// </summary>
/// <param name="items"></param>
/// <response code="201">EquipmentType created</response>
[HttpPost]
[Route("/api/equipmentTypes/bulk")]
[SwaggerOperation("EquipmentTypesBulkPost")]
[RequiresPermission(Permission.Admin)]
public virtual IActionResult EquipmentTypesBulkPost([FromBody]EquipmentType[] items)
{
return _service.EquipmentTypesBulkPostAsync(items);
}
/// <summary>
/// Get all equipment types
/// </summary>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/equipmentTypes")]
[SwaggerOperation("EquipmentTypesGet")]
[SwaggerResponse(200, type: typeof(List<EquipmentType>))]
[RequiresPermission(Permission.Login)]
public virtual IActionResult EquipmentTypesGet()
{
return _service.EquipmentTypesGetAsync();
}
}
}
| 31.436364 | 92 | 0.631579 | [
"Apache-2.0"
] | rstens/hets | Server/src/HETSAPI/Controllers/EquipmentTypeController.cs | 1,729 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.ResultSet
{
public class ColumnNameIdentifier : IColumnIdentifier, IEquatable<ColumnNameIdentifier>
{
public string Name { get; private set; }
public string Label => $"[{Name}]";
public ColumnNameIdentifier(string name)
{
Name = name;
}
public DataColumn GetColumn(DataTable dataTable) => dataTable.Columns[Name];
public object GetValue(DataRow dataRow) => dataRow[Name];
public override int GetHashCode() => Name.GetHashCode();
public override bool Equals(object value)
{
switch (value)
{
case ColumnNameIdentifier x: return Equals(x);
default: return false;
}
}
public bool Equals(ColumnNameIdentifier other)
=> !(other is null) && Name == other.Name;
}
}
| 26.153846 | 91 | 0.612745 | [
"Apache-2.0"
] | TheAutomatingMrLynch/NBi | NBi.Core/ResultSet/ColumnNameIdentifier.cs | 1,022 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
#pragma warning disable
using System;
using System.Collections;
namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1
{
/**
* Mutable class for building ASN.1 constructed objects such as SETs or SEQUENCEs.
*/
public class Asn1EncodableVector
: IEnumerable
{
internal static readonly Asn1Encodable[] EmptyElements = new Asn1Encodable[0];
private const int DefaultCapacity = 10;
private Asn1Encodable[] elements;
private int elementCount;
private bool copyOnWrite;
public static Asn1EncodableVector FromEnumerable(IEnumerable e)
{
Asn1EncodableVector v = new Asn1EncodableVector();
foreach (Asn1Encodable obj in e)
{
v.Add(obj);
}
return v;
}
public Asn1EncodableVector()
: this(DefaultCapacity)
{
}
public Asn1EncodableVector(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentException("must not be negative", "initialCapacity");
this.elements = (initialCapacity == 0) ? EmptyElements : new Asn1Encodable[initialCapacity];
this.elementCount = 0;
this.copyOnWrite = false;
}
public Asn1EncodableVector(params Asn1Encodable[] v)
: this()
{
Add(v);
}
public void Add(Asn1Encodable element)
{
if (null == element)
throw new ArgumentNullException("element");
int capacity = elements.Length;
int minCapacity = elementCount + 1;
if ((minCapacity > capacity) | copyOnWrite)
{
Reallocate(minCapacity);
}
this.elements[elementCount] = element;
this.elementCount = minCapacity;
}
public void Add(params Asn1Encodable[] objs)
{
foreach (Asn1Encodable obj in objs)
{
Add(obj);
}
}
public void AddOptional(params Asn1Encodable[] objs)
{
if (objs != null)
{
foreach (Asn1Encodable obj in objs)
{
if (obj != null)
{
Add(obj);
}
}
}
}
public void AddOptionalTagged(bool isExplicit, int tagNo, Asn1Encodable obj)
{
if (null != obj)
{
Add(new DerTaggedObject(isExplicit, tagNo, obj));
}
}
public void AddAll(Asn1EncodableVector other)
{
if (null == other)
throw new ArgumentNullException("other");
int otherElementCount = other.Count;
if (otherElementCount < 1)
return;
int capacity = elements.Length;
int minCapacity = elementCount + otherElementCount;
if ((minCapacity > capacity) | copyOnWrite)
{
Reallocate(minCapacity);
}
int i = 0;
do
{
Asn1Encodable otherElement = other[i];
if (null == otherElement)
throw new NullReferenceException("'other' elements cannot be null");
this.elements[elementCount + i] = otherElement;
}
while (++i < otherElementCount);
this.elementCount = minCapacity;
}
public Asn1Encodable this[int index]
{
get
{
if (index >= elementCount)
throw new IndexOutOfRangeException(index + " >= " + elementCount);
return elements[index];
}
}
public int Count
{
get { return elementCount; }
}
public IEnumerator GetEnumerator()
{
return CopyElements().GetEnumerator();
}
internal Asn1Encodable[] CopyElements()
{
if (0 == elementCount)
return EmptyElements;
Asn1Encodable[] copy = new Asn1Encodable[elementCount];
Array.Copy(elements, 0, copy, 0, elementCount);
return copy;
}
internal Asn1Encodable[] TakeElements()
{
if (0 == elementCount)
return EmptyElements;
if (elements.Length == elementCount)
{
this.copyOnWrite = true;
return elements;
}
Asn1Encodable[] copy = new Asn1Encodable[elementCount];
Array.Copy(elements, 0, copy, 0, elementCount);
return copy;
}
private void Reallocate(int minCapacity)
{
int oldCapacity = elements.Length;
int newCapacity = System.Math.Max(oldCapacity, minCapacity + (minCapacity >> 1));
Asn1Encodable[] copy = new Asn1Encodable[newCapacity];
Array.Copy(elements, 0, copy, 0, elementCount);
this.elements = copy;
this.copyOnWrite = false;
}
internal static Asn1Encodable[] CloneElements(Asn1Encodable[] elements)
{
return elements.Length < 1 ? EmptyElements : (Asn1Encodable[])elements.Clone();
}
}
}
#pragma warning restore
#endif
| 28.061224 | 104 | 0.520182 | [
"MIT"
] | Bregermann/TargetCrack | Target Crack/Assets/Best HTTP/Source/SecureProtocol/asn1/Asn1EncodableVector.cs | 5,500 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Unicode;
namespace GenUnicodeProp
{
internal static class Program
{
internal static bool Verbose = false;
internal static bool IncludeCasingData = false;
private const string SOURCE_NAME = "CharUnicodeInfoData.cs";
private static void Main(string[] args)
{
Verbose = args.Contains("-Verbose", StringComparer.OrdinalIgnoreCase);
IncludeCasingData = args.Contains("-IncludeCasingData", StringComparer.OrdinalIgnoreCase);
// First, read the data files and build up a list of all
// assigned code points.
Console.WriteLine("Reading Unicode data files...");
_ = UnicodeData.GetData(0); // processes files
Console.WriteLine("Finished.");
Console.WriteLine();
Console.WriteLine("Initializing maps...");
Dictionary<CategoryCasingInfo, byte> categoryCasingMap = new Dictionary<CategoryCasingInfo, byte>();
Dictionary<NumericGraphemeInfo, byte> numericGraphemeMap = new Dictionary<NumericGraphemeInfo, byte>();
// Next, iterate though all assigned code points, populating
// the category casing & numeric grapheme maps. Also put the
// data into the the DataTable structure, which will compute
// the tiered offset tables.
DataTable categoryCasingTable = new DataTable();
DataTable numericGraphemeTable = new DataTable();
for (int i = 0; i <= 0x10_FFFF; i++)
{
CodePoint thisCodePoint = UnicodeData.GetData(i);
CategoryCasingInfo categoryCasingInfo = new CategoryCasingInfo(thisCodePoint);
if (!categoryCasingMap.TryGetValue(categoryCasingInfo, out byte cciValue))
{
cciValue = (byte)categoryCasingMap.Count;
categoryCasingMap[categoryCasingInfo] = cciValue;
}
categoryCasingTable.AddData((uint)i, cciValue);
NumericGraphemeInfo numericGraphemeInfo = new NumericGraphemeInfo(thisCodePoint);
if (!numericGraphemeMap.TryGetValue(numericGraphemeInfo, out byte ngiValue))
{
ngiValue = (byte)numericGraphemeMap.Count;
numericGraphemeMap[numericGraphemeInfo] = ngiValue;
}
numericGraphemeTable.AddData((uint)i, ngiValue);
}
// Did anything overflow?
Console.WriteLine($"CategoryCasingMap contains {categoryCasingMap.Count} entries.");
if (categoryCasingMap.Count > 256)
{
throw new Exception("CategoryCasingMap exceeds max count of 256 entries!");
}
Console.WriteLine($"NumericGraphemeMap contains {numericGraphemeMap.Count} entries.");
if (numericGraphemeMap.Count > 256)
{
throw new Exception("NumericGraphemeMap exceeds max count of 256 entries!");
}
Console.WriteLine();
// Choose default ratios for the data tables we'll be generating.
TableLevels categoryCasingTableLevelBits = new TableLevels(5, 4);
TableLevels numericGraphemeTableLevelBits = new TableLevels(5, 4);
// Now generate the tables.
categoryCasingTable.GenerateTable("CategoryCasingTable", categoryCasingTableLevelBits.Level2Bits, categoryCasingTableLevelBits.Level3Bits);
numericGraphemeTable.GenerateTable("NumericGraphemeTable", numericGraphemeTableLevelBits.Level2Bits, numericGraphemeTableLevelBits.Level3Bits);
// If you want to see if a different ratio would have better compression
// statistics, uncomment the lines below and re-run the application.
// categoryCasingTable.CalculateTableVariants();
// numericGraphemeTable.CalculateTableVariants();
// Now generate the C# source file.
using (StreamWriter file = File.CreateText(SOURCE_NAME))
{
file.Write("// Licensed to the .NET Foundation under one or more agreements.\n");
file.Write("// The .NET Foundation licenses this file to you under the MIT license.\n");
file.Write("using System.Diagnostics;\n\n");
file.Write("namespace System.Globalization\n");
file.Write("{\n");
file.Write(" public static partial class CharUnicodeInfo\n {\n");
file.Write(" // THE FOLLOWING DATA IS AUTO GENERATED BY GenUnicodeProp program UNDER THE TOOLS FOLDER\n");
file.Write(" // PLEASE DON'T MODIFY BY HAND\n");
PrintAssertTableLevelsBitCountRoutine("CategoryCasing", file, categoryCasingTableLevelBits);
file.Write($"\n // {categoryCasingTableLevelBits} index table of the Unicode category & casing data.");
PrintSourceIndexArray("CategoryCasingLevel1Index", categoryCasingTable, file);
file.Write("\n // Contains Unicode category & bidi class information");
PrintValueArray("CategoriesValues", categoryCasingMap, CategoryCasingInfo.ToCategoryBytes, file);
if (IncludeCasingData)
{
// Only write out the casing data if we have been asked to do so.
file.Write("\n // Contains simple culture-invariant uppercase mappings");
PrintValueArray("UppercaseValues", categoryCasingMap, CategoryCasingInfo.ToUpperBytes, file);
file.Write("\n // Contains simple culture-invariant lowercase mappings");
PrintValueArray("LowercaseValues", categoryCasingMap, CategoryCasingInfo.ToLowerBytes, file);
file.Write("\n // Contains simple culture-invariant titlecase mappings");
PrintValueArray("TitlecaseValues", categoryCasingMap, CategoryCasingInfo.ToTitleBytes, file);
file.Write("\n // Contains simple culture-invariant case fold mappings");
PrintValueArray("CaseFoldValues", categoryCasingMap, CategoryCasingInfo.ToCaseFoldBytes, file);
}
PrintAssertTableLevelsBitCountRoutine("NumericGrapheme", file, numericGraphemeTableLevelBits);
file.Write($"\n // {numericGraphemeTableLevelBits} index table of the Unicode numeric & text segmentation data.");
PrintSourceIndexArray("NumericGraphemeLevel1Index", numericGraphemeTable, file);
file.Write("\n // Contains decimal digit values in high nibble; digit values in low nibble");
PrintValueArray("DigitValues", numericGraphemeMap, NumericGraphemeInfo.ToDigitBytes, file);
file.Write("\n // Contains numeric values");
PrintValueArray("NumericValues", numericGraphemeMap, NumericGraphemeInfo.ToNumericBytes, file);
file.Write("\n // Contains grapheme cluster segmentation values");
PrintValueArray("GraphemeSegmentationValues", numericGraphemeMap, NumericGraphemeInfo.ToGraphemeBytes, file);
file.Write("\n }\n}\n");
}
// Quick fixup: Replace \n with \r\n on Windows.
if (Environment.NewLine != "\n")
{
File.WriteAllText(SOURCE_NAME, File.ReadAllText(SOURCE_NAME).Replace("\n", Environment.NewLine));
}
Console.WriteLine("Completed!");
}
private static void PrintSourceIndexArray(string tableName, DataTable d, StreamWriter file)
{
Console.WriteLine(" ******************************** .");
var levels = d.GetBytes();
PrintByteArray(tableName, file, levels[0]);
PrintByteArray(tableName.Replace('1', '2'), file, levels[1]);
PrintByteArray(tableName.Replace('1', '3'), file, levels[2]);
}
private static void PrintValueArray<T>(string tableName, Dictionary<T, byte> d, Func<T, byte[]> getBytesCallback, StreamWriter file)
{
Console.WriteLine(" ******************************** .");
// Create reverse mapping of byte -> T,
// then dump each T to the response (as binary).
byte highestByteSeen = 0;
Dictionary<byte, T> reverseMap = new Dictionary<byte, T>();
foreach (var entry in d)
{
reverseMap.Add(entry.Value, entry.Key);
if (entry.Value > highestByteSeen)
{
highestByteSeen = entry.Value;
}
}
List<byte> binaryOutput = new List<byte>();
for (int i = 0; i <= highestByteSeen; i++)
{
binaryOutput.AddRange(getBytesCallback(reverseMap[(byte)i]));
}
PrintByteArray(tableName, file, binaryOutput.ToArray());
}
private static void PrintByteArray(string tableName, StreamWriter file, byte[] str)
{
file.Write("\n private static ReadOnlySpan<byte> " + tableName + " => new byte[" + str.Length + "]\n {\n");
file.Write(" 0x{0:x2}", str[0]);
for (var i = 1; i < str.Length; i++)
{
file.Write(i % 16 == 0 ? ",\n " : ", ");
file.Write("0x{0:x2}", str[i]);
}
file.Write("\n };\n");
}
private static void PrintAssertTableLevelsBitCountRoutine(string tableName, StreamWriter file, TableLevels expectedLevels)
{
file.Write("\n");
file.Write(" [Conditional(\"DEBUG\")]\n");
file.Write($" private static void Assert{tableName}TableLevels(int level1BitCount, int level2BitCount, int level3BitCount)\n");
file.Write(" {\n");
file.Write(" // Ensures that the caller expects the same L1:L2:L3 count as the actual backing data.\n");
file.Write($" Debug.Assert(level1BitCount == {expectedLevels.Level1Bits}, \"Unexpected level 1 bit count.\");\n");
file.Write($" Debug.Assert(level2BitCount == {expectedLevels.Level2Bits}, \"Unexpected level 2 bit count.\");\n");
file.Write($" Debug.Assert(level3BitCount == {expectedLevels.Level3Bits}, \"Unexpected level 3 bit count.\");\n");
file.Write(" }\n");
}
}
}
| 47.343478 | 155 | 0.597116 | [
"MIT"
] | 2m0nd/runtime | src/coreclr/src/System.Private.CoreLib/Tools/GenUnicodeProp/Program.cs | 10,889 | C# |
using Constants;
using Wasm;
namespace Domain
{
public class UrlHelper
{
public static string GetImagePath() => DeployedState.IsDeployed ? HttpConstant.Api_Image_Path_Deployed : HttpConstant.Api_Image_Path;
}
}
| 19.5 | 141 | 0.735043 | [
"MIT"
] | pragmatic-applications/Blazor_ToDo | _XXX/Wasm/Domain/UrlHelper.cs | 236 | C# |
using Amazon;
using Amazon.Elasticsearch;
using Amazon.Elasticsearch.Model;
using Amazon.Runtime;
namespace CloudOps.Elasticsearch
{
public class DescribePackagesOperation : Operation
{
public override string Name => "DescribePackages";
public override string Description => "Describes all packages available to Amazon ES. Includes options for filtering, limiting the number of results, and pagination.";
public override string RequestURI => "/2015-01-01/packages/describe";
public override string Method => "POST";
public override string ServiceName => "Elasticsearch";
public override string ServiceID => "Elasticsearch Service";
public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
{
AmazonElasticsearchConfig config = new AmazonElasticsearchConfig();
config.RegionEndpoint = region;
ConfigureClient(config);
AmazonElasticsearchClient client = new AmazonElasticsearchClient(creds, config);
DescribePackagesResponse resp = new DescribePackagesResponse();
do
{
DescribePackagesRequest req = new DescribePackagesRequest
{
NextToken = resp.NextToken
,
MaxResults = maxItems
};
resp = client.DescribePackages(req);
CheckError(resp.HttpStatusCode, "200");
foreach (var obj in resp.PackageDetailsList)
{
AddObject(obj);
}
}
while (!string.IsNullOrEmpty(resp.NextToken));
}
}
} | 35.211538 | 175 | 0.576188 | [
"MIT"
] | austindimmer/AWSRetriever | CloudOps/Generated/Elasticsearch/DescribePackagesOperation.cs | 1,831 | C# |
using System;
namespace dotless.Core.Utils
{
using System.Collections.Generic;
using Exceptions;
using Parser.Infrastructure;
using Parser.Infrastructure.Nodes;
using dotless.Core.Parser;
public static class Guard
{
public static void Expect(string expected, string actual, object @in, NodeLocation location)
{
if (actual == expected)
return;
var message = string.Format("Expected '{0}' in {1}, found '{2}'", expected, @in, actual);
throw new ParsingException(message, location);
}
public static void Expect(Func<bool> condition, string message, NodeLocation location)
{
if (condition())
return;
throw new ParsingException(message, location);
}
public static void ExpectNode<TExpected>(Node actual, object @in, NodeLocation location) where TExpected : Node
{
if (actual is TExpected)
return;
var expected = typeof (TExpected).Name.ToLowerInvariant();
var message = string.Format("Expected {0} in {1}, found {2}", expected, @in, actual.ToCSS(new Env()));
throw new ParsingException(message, location);
}
public static void ExpectNodeToBeOneOf<TExpected1, TExpected2>(Node actual, object @in, NodeLocation location) where TExpected1 : Node where TExpected2 : Node
{
if (actual is TExpected1 || actual is TExpected2)
return;
var expected1 = typeof(TExpected1).Name.ToLowerInvariant();
var expected2 = typeof(TExpected2).Name.ToLowerInvariant();
var message = string.Format("Expected {0} or {1} in {2}, found {3}", expected1, expected2, @in, actual.ToCSS(new Env()));
throw new ParsingException(message, location);
}
public static void ExpectAllNodes<TExpected>(IEnumerable<Node> actual, object @in, NodeLocation location) where TExpected : Node
{
foreach (var node in actual)
{
ExpectNode<TExpected>(node, @in, location);
}
}
public static void ExpectNumArguments(int expected, int actual, object @in, NodeLocation location)
{
if (actual == expected)
return;
var message = string.Format("Expected {0} arguments in {1}, found {2}", expected, @in, actual);
throw new ParsingException(message, location);
}
public static void ExpectMinArguments(int expected, int actual, object @in, NodeLocation location)
{
if (actual >= expected)
return;
var message = string.Format("Expected at least {0} arguments in {1}, found {2}", expected, @in, actual);
throw new ParsingException(message, location);
}
public static void ExpectMaxArguments(int expected, int actual, object @in, NodeLocation location)
{
if (actual <= expected)
return;
var message = string.Format("Expected at most {0} arguments in {1}, found {2}", expected, @in, actual);
throw new ParsingException(message, location);
}
}
} | 33.783505 | 166 | 0.596887 | [
"MIT"
] | Kooboo/Kooboo | Kooboo.Lib/Less/Utils/Guard.cs | 3,277 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using FileList = System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>;
using StringPair = System.Collections.Generic.KeyValuePair<string, object>;
namespace Microsoft.CodeAnalysis.UnitTests
{
/// <summary>
/// Flexible and extensible API to generate MSBuild projects and solutions without external files or resources.
/// </summary>
public static class SolutionGeneration
{
public const string NS = "http://schemas.microsoft.com/developer/msbuild/2003";
private const string CSharpProjectTemplate =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""12.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" />
<PropertyGroup>
<Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>
<Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>
</PropertyGroup>
<PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">
</PropertyGroup>
<PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">
</PropertyGroup>
<Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />
</Project>";
private const string SolutionTemplate =
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30110.0
MinimumVisualStudioVersion = 10.0.40219.1
{0}Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
";
public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001003bb5de1b79bee9bf5ba44bdb42974c6f40fdc4b329c8e1b833fa798cf0859529485b2bfc359a08e16f025fe57efd293c4dc3541cb2e0929b1c4a92db87eed7a9454dbd08beb7c7308941384b3bfb088de781b51caef23677f8f6defb671e97e1fc5e0979858e52828c86aca1d4ea1797f1f1254bf64073a28e5be520d5397fb0";
public const string PublicKeyToken = "39d7e8ec38707fde";
public static readonly byte[] KeySnk = MSBuildWorkspaceTests.GetResourceBytes("key.snk");
public static FileList GetSolutionFiles(params IBuilder[] inputs)
{
List<StringPair> list = new List<StringPair>();
var projectBuilders = inputs.OfType<ProjectBuilder>();
var files = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
int fileIndex = 1;
int projectIndex = 1;
// first make sure all projects have names, as a separate loop
foreach (var project in projectBuilders)
{
if (project.Name == null)
{
project.Name = "Project" + projectIndex;
projectIndex++;
}
}
foreach (var project in projectBuilders)
{
foreach (var document in project.Documents)
{
if (document.FilePath == null)
{
document.FilePath = "Document" + fileIndex + (project.Language == LanguageNames.VisualBasic ? ".vb" : ".cs");
fileIndex++;
}
}
foreach (var projectReference in project.ProjectReferences)
{
if (projectReference.Guid == Guid.Empty)
{
var referencedProject = projectBuilders.First(p => p.Name == projectReference.ProjectName);
projectReference.Guid = referencedProject.Guid;
projectReference.ProjectFileName = referencedProject.Name + referencedProject.Extension;
}
}
foreach (var kvp in project.Files)
{
if (files.Add(kvp.Key + kvp.Value))
{
list.Add(new StringPair(kvp.Key, kvp.Value));
}
}
}
list.Add(new KeyValuePair<string, object>("Solution.sln", GetSolutionContent(projectBuilders)));
return list;
}
public static IBuilder Project(params IBuilder[] inputs)
{
var projectReferences = inputs.OfType<ProjectReferenceBuilder>();
var documents = inputs.OfType<DocumentBuilder>().ToList();
var projectName = inputs.OfType<ProjectNameBuilder>().FirstOrDefault();
var properties = inputs.OfType<PropertyBuilder>().ToList();
var sign = inputs.OfType<SignBuilder>();
if (sign != null)
{
properties.Add((PropertyBuilder)Property("SignAssembly", "true"));
properties.Add((PropertyBuilder)Property("AssemblyOriginatorKeyFile", "key.snk"));
documents.Add((DocumentBuilder)Document(KeySnk, "key.snk", "None"));
}
return new ProjectBuilder
{
Name = projectName != null ? projectName.Name : null,
Documents = documents,
ProjectReferences = projectReferences,
Properties = properties
};
}
public static IBuilder ProjectReference(string projectName)
{
return new ProjectReferenceBuilder
{
ProjectName = projectName
};
}
public static IBuilder ProjectName(string projectName)
{
return new ProjectNameBuilder
{
Name = projectName
};
}
public static IBuilder Property(string propertyName, string propertyValue)
{
return new PropertyBuilder
{
Name = propertyName,
Value = propertyValue
};
}
public static IBuilder Sign
{
get
{
return new SignBuilder();
}
}
public static IBuilder Document(
object content = null,
string filePath = null,
string itemType = "Compile")
{
return new DocumentBuilder
{
FilePath = filePath,
Content = content,
ItemType = itemType
};
}
private static string GetSolutionContent(IEnumerable<ProjectBuilder> projects)
{
var sb = new StringBuilder();
foreach (var project in projects)
{
var fileName = project.Name + project.Extension;
var languageGuid = project.Language == LanguageNames.VisualBasic ?
"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}" :
"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";
sb.AppendLine(
string.Format(
@"Project(""{0}"") = ""{1}"", ""{2}"", ""{3}""",
languageGuid,
project.Name,
fileName,
project.Guid.ToString("B")));
sb.AppendLine("EndProject");
}
return string.Format(SolutionTemplate, sb.ToString());
}
public interface IBuilder
{
}
private class ProjectBuilder : IBuilder
{
public string Name { get; set; }
public string Language { get; set; }
public Guid Guid { get; set; }
public string OutputType { get; set; }
public string OutputPath { get; set; }
public IEnumerable<DocumentBuilder> Documents { get; set; }
public IEnumerable<ProjectReferenceBuilder> ProjectReferences { get; set; }
public IEnumerable<PropertyBuilder> Properties { get; set; }
public string Extension
{
get
{
return Language == LanguageNames.VisualBasic ? ".vbproj" : ".csproj";
}
}
public FileList Files
{
get
{
foreach (var document in Documents)
{
yield return new StringPair(document.FilePath, document.Content);
}
yield return new StringPair(Name + Extension, GetProjectContent());
}
}
private string GetProjectContent()
{
if (Language == LanguageNames.VisualBasic)
{
throw new NotImplementedException("Need VB support");
}
if (Guid == Guid.Empty)
{
Guid = Guid.NewGuid();
}
if (string.IsNullOrEmpty(OutputType))
{
OutputType = "Library";
}
if (string.IsNullOrEmpty(OutputPath))
{
OutputPath = ".";
}
var document = XDocument.Parse(CSharpProjectTemplate);
var propertyGroup = document.Root.Descendants(XName.Get("PropertyGroup", NS)).First();
AddXElement(propertyGroup, "ProjectGuid", Guid.ToString("B"));
AddXElement(propertyGroup, "OutputType", OutputType);
AddXElement(propertyGroup, "OutputPath", OutputPath);
AddXElement(propertyGroup, "AssemblyName", Name);
if (Properties != null)
{
foreach (var property in Properties)
{
AddXElement(propertyGroup, property.Name, property.Value);
}
}
var importTargets = document.Root.Elements().Last();
if (ProjectReferences != null && ProjectReferences.Any())
{
AddItemGroup(
importTargets,
_ => "ProjectReference",
ProjectReferences,
i => i.ProjectFileName,
(projectReference, xmlElement) =>
{
if (projectReference.Guid != Guid.Empty)
{
AddXElement(xmlElement, "Project", projectReference.Guid.ToString("B"));
}
AddXElement(xmlElement, "Name", Path.GetFileNameWithoutExtension(projectReference.ProjectName));
});
}
if (Documents != null)
{
AddItemGroup(
importTargets,
i => i.ItemType,
Documents,
i => i.FilePath);
}
return document.ToString();
}
private void AddItemGroup<T>(
XElement addBefore,
Func<T, string> itemTypeSelector,
IEnumerable<T> items,
Func<T, string> attributeValueGetter,
Action<T, XElement> elementModifier = null)
{
var itemGroup = CreateXElement("ItemGroup");
addBefore.AddBeforeSelf(itemGroup);
foreach (var item in items)
{
var itemElement = CreateXElement(itemTypeSelector(item));
itemElement.SetAttributeValue("Include", attributeValueGetter(item));
if (elementModifier != null)
{
elementModifier(item, itemElement);
}
itemGroup.Add(itemElement);
}
}
private XElement CreateXElement(string name)
{
return new XElement(XName.Get(name, NS));
}
private void AddXElement(XElement element, string elementName, string elementValue)
{
element.Add(new XElement(XName.Get(elementName, NS), elementValue));
}
}
private class ProjectReferenceBuilder : IBuilder
{
public string ProjectName { get; set; }
public Guid Guid { get; set; }
public string ProjectFileName { get; set; }
}
private class ProjectNameBuilder : IBuilder
{
public string Name { get; set; }
}
private class PropertyBuilder : IBuilder
{
public string Name { get; set; }
public string Value { get; set; }
}
private class SignBuilder : IBuilder { }
private class DocumentBuilder : IBuilder
{
public string FilePath { get; set; }
public object Content { get; set; }
public string ItemType { get; set; }
}
}
} | 36.943243 | 363 | 0.536177 | [
"Apache-2.0"
] | KashishArora/Roslyn | src/Workspaces/CoreTest/SolutionGeneration.cs | 13,671 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Domain
{
/// <summary>
/// AlipayInsSceneProductAgreementCancelModel Data Structure.
/// </summary>
public class AlipayInsSceneProductAgreementCancelModel : AlipayObject
{
/// <summary>
/// 签订协议商户支付宝用户ID
/// </summary>
[JsonPropertyName("alipay_user_id")]
public string AlipayUserId { get; set; }
/// <summary>
/// 渠道
/// </summary>
[JsonPropertyName("channel")]
public string Channel { get; set; }
/// <summary>
/// 产品协议号
/// </summary>
[JsonPropertyName("product_sign_no")]
public string ProductSignNo { get; set; }
}
}
| 25.551724 | 73 | 0.581646 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Domain/AlipayInsSceneProductAgreementCancelModel.cs | 779 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wincodecsdk.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IWICPersistStream" /> struct.</summary>
public static unsafe partial class IWICPersistStreamTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IWICPersistStream" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IWICPersistStream).GUID, Is.EqualTo(IID_IWICPersistStream));
}
/// <summary>Validates that the <see cref="IWICPersistStream" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IWICPersistStream>(), Is.EqualTo(sizeof(IWICPersistStream)));
}
/// <summary>Validates that the <see cref="IWICPersistStream" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IWICPersistStream).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IWICPersistStream" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IWICPersistStream), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IWICPersistStream), Is.EqualTo(4));
}
}
}
}
| 37.326923 | 145 | 0.639361 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/wincodecsdk/IWICPersistStreamTests.cs | 1,943 | C# |
using CleanArchitectureTemplate.Domain.Common;
namespace CleanArchitectureTemplate.Domain.Entities
{
public class Product : AuditableBaseEntity
{
public string Name { get; set; }
public string Barcode { get; set; }
public string Description { get; set; }
public decimal Rate { get; set; }
}
}
| 22.875 | 51 | 0.617486 | [
"MIT"
] | GheorgheVolosenco/CleanArchitectureSolutionTemplate | src/Domain/Entities/Product.cs | 368 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the networkmanager-2019-07-05.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.NetworkManager.Model
{
/// <summary>
/// Container for the parameters to the DisassociateCustomerGateway operation.
/// Disassociates a customer gateway from a device and a link.
/// </summary>
public partial class DisassociateCustomerGatewayRequest : AmazonNetworkManagerRequest
{
private string _customerGatewayArn;
private string _globalNetworkId;
/// <summary>
/// Gets and sets the property CustomerGatewayArn.
/// <para>
/// The Amazon Resource Name (ARN) of the customer gateway.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string CustomerGatewayArn
{
get { return this._customerGatewayArn; }
set { this._customerGatewayArn = value; }
}
// Check to see if CustomerGatewayArn property is set
internal bool IsSetCustomerGatewayArn()
{
return this._customerGatewayArn != null;
}
/// <summary>
/// Gets and sets the property GlobalNetworkId.
/// <para>
/// The ID of the global network.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string GlobalNetworkId
{
get { return this._globalNetworkId; }
set { this._globalNetworkId = value; }
}
// Check to see if GlobalNetworkId property is set
internal bool IsSetGlobalNetworkId()
{
return this._globalNetworkId != null;
}
}
} | 31.151899 | 112 | 0.645672 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/NetworkManager/Generated/Model/DisassociateCustomerGatewayRequest.cs | 2,461 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Chime.Model
{
/// <summary>
/// The Amazon Chime Voice Connector group configuration, including associated Amazon
/// Chime Voice Connectors. You can include Amazon Chime Voice Connectors from different
/// AWS Regions in your group. This creates a fault tolerant mechanism for fallback in
/// case of availability events.
/// </summary>
public partial class VoiceConnectorGroup
{
private DateTime? _createdTimestamp;
private string _name;
private DateTime? _updatedTimestamp;
private string _voiceConnectorGroupId;
private List<VoiceConnectorItem> _voiceConnectorItems = new List<VoiceConnectorItem>();
/// <summary>
/// Gets and sets the property CreatedTimestamp.
/// <para>
/// The Amazon Chime Voice Connector group creation time stamp, in ISO 8601 format.
/// </para>
/// </summary>
public DateTime CreatedTimestamp
{
get { return this._createdTimestamp.GetValueOrDefault(); }
set { this._createdTimestamp = value; }
}
// Check to see if CreatedTimestamp property is set
internal bool IsSetCreatedTimestamp()
{
return this._createdTimestamp.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the Amazon Chime Voice Connector group.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property UpdatedTimestamp.
/// <para>
/// The updated Amazon Chime Voice Connector group time stamp, in ISO 8601 format.
/// </para>
/// </summary>
public DateTime UpdatedTimestamp
{
get { return this._updatedTimestamp.GetValueOrDefault(); }
set { this._updatedTimestamp = value; }
}
// Check to see if UpdatedTimestamp property is set
internal bool IsSetUpdatedTimestamp()
{
return this._updatedTimestamp.HasValue;
}
/// <summary>
/// Gets and sets the property VoiceConnectorGroupId.
/// <para>
/// The Amazon Chime Voice Connector group ID.
/// </para>
/// </summary>
public string VoiceConnectorGroupId
{
get { return this._voiceConnectorGroupId; }
set { this._voiceConnectorGroupId = value; }
}
// Check to see if VoiceConnectorGroupId property is set
internal bool IsSetVoiceConnectorGroupId()
{
return this._voiceConnectorGroupId != null;
}
/// <summary>
/// Gets and sets the property VoiceConnectorItems.
/// <para>
/// The Amazon Chime Voice Connectors to which to route inbound calls.
/// </para>
/// </summary>
public List<VoiceConnectorItem> VoiceConnectorItems
{
get { return this._voiceConnectorItems; }
set { this._voiceConnectorItems = value; }
}
// Check to see if VoiceConnectorItems property is set
internal bool IsSetVoiceConnectorItems()
{
return this._voiceConnectorItems != null && this._voiceConnectorItems.Count > 0;
}
}
} | 32.788321 | 103 | 0.614871 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/VoiceConnectorGroup.cs | 4,492 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.