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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Runtime.Augments;
namespace System.Threading
{
/// <summary>
/// Ensures <c>Thread.CurrentThread</c> is initialized for a callback running on a thread pool thread.
/// If WinRT is enabled, also ensures the Windows Runtime is initialized during the execution of the callback.
/// </summary>
/// <remarks>
/// This structure does not implement <c>IDisposable</c> to save on exception support, which callers do not need.
/// </remarks>
internal struct ThreadPoolCallbackWrapper
{
private Thread _currentThread;
public static ThreadPoolCallbackWrapper Enter()
{
return new ThreadPoolCallbackWrapper
{
_currentThread = Thread.InitializeThreadPoolThread(),
};
}
public void Exit(bool resetThread = true)
{
if (resetThread)
{
_currentThread.ResetThreadPoolThread();
}
}
}
}
| 32.135135 | 117 | 0.638352 | [
"MIT"
] | LuisRGameloft/corert | src/System.Private.CoreLib/src/System/Threading/ThreadPoolCallbackWrapper.cs | 1,189 | C# |
using FrHello.NetLib.Core.Wpf.Event.EventArgs;
namespace FrHello.NetLib.Core.Wpf.Event
{
/// <summary>
/// RoutedPropertyEventHandler
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void RoutedPropertyEventHandler<T>(object sender, RoutedPropertyEventArgs<T> e);
}
| 29.076923 | 100 | 0.669312 | [
"MIT"
] | fengrui358/NetLibCore | NetLib.Core.Wpf/Event/RoutedPropertyEventHandler.cs | 380 | C# |
namespace FactoryMethodPattern
{
public class WeiXinPayFactory : AbstractPaymentMethodFactory
{
public override AbstractPaymentMethod GetPaymentMethod()
{
return new WeiXinPay();
}
}
}
| 21.272727 | 64 | 0.653846 | [
"MIT"
] | hzhhhbb/Design-Patterns | src/FactoryMethodPattern/WeiXinPayFactory.cs | 236 | 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.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type GroupUnsubscribeByMailRequestBuilder.
/// </summary>
public partial class GroupUnsubscribeByMailRequestBuilder : BaseGetMethodRequestBuilder<IGroupUnsubscribeByMailRequest>, IGroupUnsubscribeByMailRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="GroupUnsubscribeByMailRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public GroupUnsubscribeByMailRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IGroupUnsubscribeByMailRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new GroupUnsubscribeByMailRequest(functionUrl, this.Client, options);
return request;
}
}
}
| 41.444444 | 162 | 0.606434 | [
"MIT"
] | MIchaelMainer/GraphAPI | src/Microsoft.Graph/Requests/Generated/GroupUnsubscribeByMailRequestBuilder.cs | 1,865 | C# |
// Decompiled with JetBrains decompiler
// Type: SmokeBombBoxScript
// Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 5F8D6662-C74B-4D30-A4EA-D74F7A9A95B9
// Assembly location: C:\YandereSimulator\YandereSimulator_Data\Managed\Assembly-CSharp.dll
using UnityEngine;
public class SmokeBombBoxScript : MonoBehaviour
{
public AlphabetScript Alphabet;
public UITexture BombTexture;
public PromptScript Prompt;
public AudioSource MyAudio;
public bool Cheated;
public bool Amnesia;
public bool Stink;
private void Update()
{
if ((double) this.Prompt.Circle[0].fillAmount != 0.0)
return;
if (!this.Cheated)
{
++this.Alphabet.Cheats;
this.Alphabet.UpdateDifficultyLabel();
this.Cheated = true;
}
if (!this.Amnesia)
{
this.Alphabet.RemainingBombs = 5;
this.Alphabet.BombLabel.text = 5.ToString() ?? "";
}
else
{
this.Alphabet.RemainingBombs = 1;
this.Alphabet.BombLabel.text = 1.ToString() ?? "";
}
this.Prompt.Circle[0].fillAmount = 1f;
if (this.Stink)
{
this.BombTexture.color = new Color(0.0f, 0.5f, 0.0f, 1f);
this.Prompt.Yandere.Inventory.AmnesiaBomb = false;
this.Prompt.Yandere.Inventory.SmokeBomb = false;
this.Prompt.Yandere.Inventory.StinkBomb = true;
}
else if (this.Amnesia)
{
this.BombTexture.color = new Color(1f, 0.5f, 1f, 1f);
this.Prompt.Yandere.Inventory.AmnesiaBomb = true;
this.Prompt.Yandere.Inventory.SmokeBomb = false;
this.Prompt.Yandere.Inventory.StinkBomb = false;
}
else
{
this.BombTexture.color = new Color(0.5f, 0.5f, 0.5f, 1f);
this.Prompt.Yandere.Inventory.AmnesiaBomb = false;
this.Prompt.Yandere.Inventory.StinkBomb = false;
this.Prompt.Yandere.Inventory.SmokeBomb = true;
}
this.MyAudio.Play();
}
}
| 29.609375 | 91 | 0.672823 | [
"Unlicense"
] | JaydenB14/YandereSimulatorDecompiled | Assembly-CSharp/SmokeBombBoxScript.cs | 1,897 | 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.Batch.V20190801
{
public static class GetPool
{
/// <summary>
/// Contains information about a pool.
/// </summary>
public static Task<GetPoolResult> InvokeAsync(GetPoolArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetPoolResult>("azure-nextgen:batch/v20190801:getPool", args ?? new GetPoolArgs(), options.WithVersion());
}
public sealed class GetPoolArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the Batch account.
/// </summary>
[Input("accountName", required: true)]
public string AccountName { get; set; } = null!;
/// <summary>
/// The pool name. This must be unique within the account.
/// </summary>
[Input("poolName", required: true)]
public string PoolName { get; set; } = null!;
/// <summary>
/// The name of the resource group that contains the Batch account.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetPoolArgs()
{
}
}
[OutputType]
public sealed class GetPoolResult
{
public readonly string AllocationState;
public readonly string AllocationStateTransitionTime;
/// <summary>
/// The list of application licenses must be a subset of available Batch service application licenses. If a license is requested which is not supported, pool creation will fail.
/// </summary>
public readonly ImmutableArray<string> ApplicationLicenses;
/// <summary>
/// Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. There is a maximum of 10 application package references on any given pool.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationPackageReferenceResponse> ApplicationPackages;
/// <summary>
/// This property is set only if the pool automatically scales, i.e. autoScaleSettings are used.
/// </summary>
public readonly Outputs.AutoScaleRunResponse AutoScaleRun;
/// <summary>
/// For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory.
/// </summary>
public readonly ImmutableArray<Outputs.CertificateReferenceResponse> Certificates;
public readonly string CreationTime;
public readonly int CurrentDedicatedNodes;
public readonly int CurrentLowPriorityNodes;
/// <summary>
/// Using CloudServiceConfiguration specifies that the nodes should be creating using Azure Cloud Services (PaaS), while VirtualMachineConfiguration uses Azure Virtual Machines (IaaS).
/// </summary>
public readonly Outputs.DeploymentConfigurationResponse? DeploymentConfiguration;
/// <summary>
/// The display name need not be unique and can contain any Unicode characters up to a maximum length of 1024.
/// </summary>
public readonly string? DisplayName;
/// <summary>
/// The ETag of the resource, used for concurrency statements.
/// </summary>
public readonly string Etag;
/// <summary>
/// The ID of the resource.
/// </summary>
public readonly string Id;
/// <summary>
/// This imposes restrictions on which nodes can be assigned to the pool. Enabling this value can reduce the chance of the requested number of nodes to be allocated in the pool. If not specified, this value defaults to 'Disabled'.
/// </summary>
public readonly string? InterNodeCommunication;
/// <summary>
/// This is the last time at which the pool level data, such as the targetDedicatedNodes or autoScaleSettings, changed. It does not factor in node-level changes such as a compute node changing state.
/// </summary>
public readonly string LastModified;
/// <summary>
/// The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256.
/// </summary>
public readonly int? MaxTasksPerNode;
/// <summary>
/// The Batch service does not assign any meaning to metadata; it is solely for the use of user code.
/// </summary>
public readonly ImmutableArray<Outputs.MetadataItemResponse> Metadata;
/// <summary>
/// This supports Azure Files, NFS, CIFS/SMB, and Blobfuse.
/// </summary>
public readonly ImmutableArray<Outputs.MountConfigurationResponse> MountConfiguration;
/// <summary>
/// The name of the resource.
/// </summary>
public readonly string Name;
/// <summary>
/// The network configuration for a pool.
/// </summary>
public readonly Outputs.NetworkConfigurationResponse? NetworkConfiguration;
public readonly string ProvisioningState;
public readonly string ProvisioningStateTransitionTime;
/// <summary>
/// Describes either the current operation (if the pool AllocationState is Resizing) or the previously completed operation (if the AllocationState is Steady).
/// </summary>
public readonly Outputs.ResizeOperationStatusResponse ResizeOperationStatus;
/// <summary>
/// Defines the desired size of the pool. This can either be 'fixedScale' where the requested targetDedicatedNodes is specified, or 'autoScale' which defines a formula which is periodically reevaluated. If this property is not specified, the pool will have a fixed scale with 0 targetDedicatedNodes.
/// </summary>
public readonly Outputs.ScaleSettingsResponse? ScaleSettings;
/// <summary>
/// In an PATCH (update) operation, this property can be set to an empty object to remove the start task from the pool.
/// </summary>
public readonly Outputs.StartTaskResponse? StartTask;
/// <summary>
/// If not specified, the default is spread.
/// </summary>
public readonly Outputs.TaskSchedulingPolicyResponse? TaskSchedulingPolicy;
/// <summary>
/// The type of the resource.
/// </summary>
public readonly string Type;
public readonly ImmutableArray<Outputs.UserAccountResponse> UserAccounts;
/// <summary>
/// For information about available sizes of virtual machines for Cloud Services pools (pools created with cloudServiceConfiguration), see Sizes for Cloud Services (https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/). Batch supports all Cloud Services VM sizes except ExtraSmall. For information about available VM sizes for pools using images from the Virtual Machines Marketplace (pools created with virtualMachineConfiguration) see Sizes for Virtual Machines (Linux) (https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/) or Sizes for Virtual Machines (Windows) (https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/). Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series).
/// </summary>
public readonly string? VmSize;
[OutputConstructor]
private GetPoolResult(
string allocationState,
string allocationStateTransitionTime,
ImmutableArray<string> applicationLicenses,
ImmutableArray<Outputs.ApplicationPackageReferenceResponse> applicationPackages,
Outputs.AutoScaleRunResponse autoScaleRun,
ImmutableArray<Outputs.CertificateReferenceResponse> certificates,
string creationTime,
int currentDedicatedNodes,
int currentLowPriorityNodes,
Outputs.DeploymentConfigurationResponse? deploymentConfiguration,
string? displayName,
string etag,
string id,
string? interNodeCommunication,
string lastModified,
int? maxTasksPerNode,
ImmutableArray<Outputs.MetadataItemResponse> metadata,
ImmutableArray<Outputs.MountConfigurationResponse> mountConfiguration,
string name,
Outputs.NetworkConfigurationResponse? networkConfiguration,
string provisioningState,
string provisioningStateTransitionTime,
Outputs.ResizeOperationStatusResponse resizeOperationStatus,
Outputs.ScaleSettingsResponse? scaleSettings,
Outputs.StartTaskResponse? startTask,
Outputs.TaskSchedulingPolicyResponse? taskSchedulingPolicy,
string type,
ImmutableArray<Outputs.UserAccountResponse> userAccounts,
string? vmSize)
{
AllocationState = allocationState;
AllocationStateTransitionTime = allocationStateTransitionTime;
ApplicationLicenses = applicationLicenses;
ApplicationPackages = applicationPackages;
AutoScaleRun = autoScaleRun;
Certificates = certificates;
CreationTime = creationTime;
CurrentDedicatedNodes = currentDedicatedNodes;
CurrentLowPriorityNodes = currentLowPriorityNodes;
DeploymentConfiguration = deploymentConfiguration;
DisplayName = displayName;
Etag = etag;
Id = id;
InterNodeCommunication = interNodeCommunication;
LastModified = lastModified;
MaxTasksPerNode = maxTasksPerNode;
Metadata = metadata;
MountConfiguration = mountConfiguration;
Name = name;
NetworkConfiguration = networkConfiguration;
ProvisioningState = provisioningState;
ProvisioningStateTransitionTime = provisioningStateTransitionTime;
ResizeOperationStatus = resizeOperationStatus;
ScaleSettings = scaleSettings;
StartTask = startTask;
TaskSchedulingPolicy = taskSchedulingPolicy;
Type = type;
UserAccounts = userAccounts;
VmSize = vmSize;
}
}
}
| 47.364407 | 852 | 0.676329 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Batch/V20190801/GetPool.cs | 11,178 | C# |
//-----------------------------------------------------------------------
// <copyright file="ITestActorQueue.cs" company="Akka.NET Project">
// Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
namespace Akka.TestKit.Internal
{
/// <summary>
/// <remarks>Note! Part of internal API. Breaking changes may occur without notice. Use at own risk.</remarks>
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public interface ITestActorQueueProducer<in T>
{
/// <summary>Adds the specified item to the queue.</summary>
/// <param name="item">The item.</param>
void Enqueue(T item);
}
/// <summary>
/// <remarks>Note! Part of internal API. Breaking changes may occur without notice. Use at own risk.</remarks>
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public interface ITestActorQueue<T> : ITestActorQueueProducer<T>
{
/// <summary>
/// Copies all the items from the <see cref="ITestActorQueue{T}"/> instance into a new <see cref="List{T}"/>
/// </summary>
/// <returns>TBD</returns>
List<T> ToList();
/// <summary>
/// Get all messages.
/// </summary>
/// <returns>TBD</returns>
IEnumerable<T> GetAll();
}
}
| 36.142857 | 116 | 0.550066 | [
"Apache-2.0"
] | EajksEajks/Akka.NET | src/core/Akka.TestKit/Internal/ITestActorQueue.cs | 1,520 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using xkomZadanie.Entities;
namespace xkomZadanie.Repositories
{
public class MongoDbEventsRepository : IEvents
{
private const string databaseName = "catalog";
private const string collectionName = "events";
private readonly IMongoCollection<Event> eventCollection;
private readonly FilterDefinitionBuilder<Event> filterBuilder = Builders<Event>.Filter;
public MongoDbEventsRepository(IMongoClient mongoClient)
{
IMongoDatabase database = mongoClient.GetDatabase(databaseName);
eventCollection = database.GetCollection<Event>(collectionName);
}
public async Task CreateEventAsync(Event events)
{
await eventCollection.InsertOneAsync(events);
}
public async Task DeleteEventAsync(Guid id)
{
var filter = filterBuilder.Eq(events => events.Id, id);
await eventCollection.DeleteOneAsync(filter);
}
public async Task<Event> GetEventAsync(Guid id)
{
var filter = filterBuilder.Eq(events => events.Id, id);
return await eventCollection.Find(filter).SingleOrDefaultAsync();
}
public async Task<IEnumerable<Event>> GetEventsAsync()
{
//return await eventCollection.Find(new BsonDocument()).ToListAsync();
return await eventCollection.Find(_ => true).Project(b => new Event
{
Id = b.Id,
Name = b.Name,
CreatedDate = b.CreatedDate
}).ToListAsync();
}
public async Task UpdateEventAsync(Event events)
{
var filter = filterBuilder.Eq(existingEvent => existingEvent.Id, events.Id);
await eventCollection.ReplaceOneAsync(filter, events);
}
public async Task InsertUserIntoEventAsync(Event events)
{
var filter = filterBuilder.Eq(existingEvent => existingEvent.Id, events.Id);
await eventCollection.ReplaceOneAsync(filter, events);
}
}
}
| 29.636364 | 95 | 0.628834 | [
"MIT"
] | MZachura/.net5WebApi | xkomZadanie/Repositories/MongoDbEventsRepository.cs | 2,284 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smobiler.Core;
using Smobiler.Core.Controls;
namespace Smobiler.Tutorials.Samples.Layout
{
partial class demoLoginAbsoluteLayout : Smobiler.Core.Controls.MobileForm
{
public demoLoginAbsoluteLayout() : base()
{
//This call is required by the SmobilerForm.
InitializeComponent();
}
private void btnLogon_Click(object sender, EventArgs e)
{
}
private void btnRegister_Click(object sender, EventArgs e)
{
}
private void btnVerify_Click(object sender, EventArgs e)
{
}
private void button1_Press(object sender, EventArgs e)
{
}
private void title1_ImagePress(object sender, EventArgs e)
{
this.Close();
}
}
} | 20.906977 | 77 | 0.615128 | [
"MIT"
] | comsmobiler/SmobilerTutorials | Source/Samples/Layout/demoLoginAbsoluteLayout.cs | 901 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.SqlServer.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// SQL Server specific extension methods for <see cref="EntityTypeBuilder" />.
/// </summary>
public static class SqlServerEntityTypeBuilderExtensions
{
/// <summary>
/// Configures the table that the entity maps to when targeting SQL Server as memory-optimized.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static EntityTypeBuilder IsMemoryOptimized(
this EntityTypeBuilder entityTypeBuilder,
bool memoryOptimized = true)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
entityTypeBuilder.Metadata.SetIsMemoryOptimized(memoryOptimized);
return entityTypeBuilder;
}
/// <summary>
/// Configures the table that the entity maps to when targeting SQL Server as memory-optimized.
/// </summary>
/// <typeparam name="TEntity"> The entity type being configured. </typeparam>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static EntityTypeBuilder<TEntity> IsMemoryOptimized<TEntity>(
this EntityTypeBuilder<TEntity> entityTypeBuilder,
bool memoryOptimized = true)
where TEntity : class
=> (EntityTypeBuilder<TEntity>)IsMemoryOptimized((EntityTypeBuilder)entityTypeBuilder, memoryOptimized);
/// <summary>
/// Configures the table that the entity maps to when targeting SQL Server as memory-optimized.
/// </summary>
/// <param name="collectionOwnershipBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static OwnedNavigationBuilder IsMemoryOptimized(
this OwnedNavigationBuilder collectionOwnershipBuilder,
bool memoryOptimized = true)
{
Check.NotNull(collectionOwnershipBuilder, nameof(collectionOwnershipBuilder));
collectionOwnershipBuilder.OwnedEntityType.SetIsMemoryOptimized(memoryOptimized);
return collectionOwnershipBuilder;
}
/// <summary>
/// Configures the table that the entity maps to when targeting SQL Server as memory-optimized.
/// </summary>
/// <typeparam name="TEntity"> The entity type being configured. </typeparam>
/// <typeparam name="TRelatedEntity"> The entity type that this relationship targets. </typeparam>
/// <param name="collectionOwnershipBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static OwnedNavigationBuilder<TEntity, TRelatedEntity> IsMemoryOptimized<TEntity, TRelatedEntity>(
this OwnedNavigationBuilder<TEntity, TRelatedEntity> collectionOwnershipBuilder,
bool memoryOptimized = true)
where TEntity : class
where TRelatedEntity : class
=> (OwnedNavigationBuilder<TEntity, TRelatedEntity>)IsMemoryOptimized(
(OwnedNavigationBuilder)collectionOwnershipBuilder, memoryOptimized);
/// <summary>
/// Configures the table that the entity maps to when targeting SQL Server as memory-optimized.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? IsMemoryOptimized(
this IConventionEntityTypeBuilder entityTypeBuilder,
bool? memoryOptimized,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetIsMemoryOptimized(memoryOptimized, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetIsMemoryOptimized(memoryOptimized, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the mapped table can be configured as memory-optimized.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="memoryOptimized"> A value indicating whether the table is memory-optimized. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can be configured as memory-optimized. </returns>
public static bool CanSetIsMemoryOptimized(
this IConventionEntityTypeBuilder entityTypeBuilder,
bool? memoryOptimized,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.MemoryOptimized, memoryOptimized, fromDataAnnotation);
}
/// <summary>
/// Configures the table as temporal.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity being configured. </param>
/// <param name="temporal"> A value indicating whether the table is temporal. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? IsTemporal(
this IConventionEntityTypeBuilder entityTypeBuilder,
bool temporal = true,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetIsTemporal(temporal, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetIsTemporal(temporal, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the mapped table can be configured as temporal.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="temporal"> A value indicating whether the table is temporal. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can be configured as temporal. </returns>
public static bool CanSetIsTemporal(
this IConventionEntityTypeBuilder entityTypeBuilder,
bool temporal = true,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.IsTemporal, temporal, fromDataAnnotation);
}
/// <summary>
/// Configures a history table name for the entity mapped to a temporal table.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity being configured. </param>
/// <param name="name"> The name of the history table. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? UseHistoryTableName(
this IConventionEntityTypeBuilder entityTypeBuilder,
string name,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetHistoryTableName(name, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetHistoryTableName(name, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the given history table name can be set for the entity.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="name"> The name of the history table. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can have history table name. </returns>
public static bool CanSetHistoryTableName(
this IConventionEntityTypeBuilder entityTypeBuilder,
string name,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
Check.NotNull(name, nameof(name));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.TemporalHistoryTableName, name, fromDataAnnotation);
}
/// <summary>
/// Configures a history table schema for the entity mapped to a temporal table.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity being configured. </param>
/// <param name="schema"> The schema of the history table. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? UseHistoryTableSchema(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? schema,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetHistoryTableSchema(schema, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetHistoryTableSchema(schema, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the mapped table can have history table schema.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="schema"> The schema of the history table. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can have history table schema. </returns>
public static bool CanSetHistoryTableSchema(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? schema,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.TemporalHistoryTableSchema, schema, fromDataAnnotation);
}
/// <summary>
/// Configures a period start property for the entity mapped to a temporal table.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity being configured. </param>
/// <param name="propertyName"> The name of the period start property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? HasPeriodStart(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? propertyName,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetPeriodStart(propertyName, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetPeriodStartPropertyName(propertyName, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the mapped table can have period start property.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="propertyName"> The name of the period start property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can have period start property. </returns>
public static bool CanSetPeriodStart(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? propertyName,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.TemporalPeriodStartPropertyName, propertyName, fromDataAnnotation);
}
/// <summary>
/// Configures a period end property for the entity mapped to a temporal table.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity being configured. </param>
/// <param name="propertyName"> The name of the period end property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// The same builder instance if the configuration was applied,
/// <see langword="null" /> otherwise.
/// </returns>
public static IConventionEntityTypeBuilder? HasPeriodEnd(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? propertyName,
bool fromDataAnnotation = false)
{
if (entityTypeBuilder.CanSetPeriodEnd(propertyName, fromDataAnnotation))
{
entityTypeBuilder.Metadata.SetPeriodEndPropertyName(propertyName, fromDataAnnotation);
return entityTypeBuilder;
}
return null;
}
/// <summary>
/// Returns a value indicating whether the mapped table can have period end property.
/// </summary>
/// <param name="entityTypeBuilder"> The builder for the entity type being configured. </param>
/// <param name="propertyName"> The name of the period end property. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns> <see langword="true" /> if the mapped table can have period end property. </returns>
public static bool CanSetPeriodEnd(
this IConventionEntityTypeBuilder entityTypeBuilder,
string? propertyName,
bool fromDataAnnotation = false)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
return entityTypeBuilder.CanSetAnnotation(SqlServerAnnotationNames.TemporalPeriodEndPropertyName, propertyName, fromDataAnnotation);
}
}
}
| 51.861446 | 146 | 0.655535 | [
"MIT"
] | FelicePollano/efcore | src/EFCore.SqlServer/Extensions/SqlServerEntityTypeBuilderExtensions.cs | 17,218 | C# |
/*******************************************************************************
* You may amend and distribute as you like, but don't remove this header!
*
* EPPlus provides server-side generation of Excel 2007/2010 spreadsheets.
* See http://www.codeplex.com/EPPlus for details.
*
* Copyright (C) 2011 Jan Källman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php
* If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html
*
* All code and executables are provided "as is" with no warranty either express or implied.
* The author accepts no liability for any damage or loss of business that this product may cause.
*
* Code change notes:
*
* Author Change Date
* ******************************************************************************
* Eyal Seagull Conditional Formatting Adaption 2012-04-03
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OfficeOpenXml.ConditionalFormatting;
namespace OfficeOpenXml.ConditionalFormatting.Contracts
{
/// <summary>
/// IExcelConditionalFormattingNotBetween
/// </summary>
public interface IExcelConditionalFormattingNotBetween
: IExcelConditionalFormattingRule,
IExcelConditionalFormattingWithFormula2
{
#region Public Properties
#endregion Public Properties
}
} | 41.22 | 118 | 0.660844 | [
"MIT"
] | GlobalcachingEU/GAPP | EPPlus/ConditionalFormatting/Contracts/IExcelConditionalFormattingNotBetween.cs | 2,064 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using Microsoft.AspNet.SignalR;
namespace ChatServerCS
{
public class ChatHub : Hub<IClient>
{
private static int GameCount = 0;
private static bool InGame = false;
private static User CurrentHost;
private static QuizAnswerRepo AnswerList;
private static ConcurrentDictionary<string, User> UserList = new ConcurrentDictionary<string, User>();
//private static ConcurrentDictionary<string, Game> GameList = new ConcurrentDictionary<string, Game>();
public override Task OnDisconnected(bool stopCalled)
{
var userName = UserList.SingleOrDefault((c) => c.Value.ID == Context.ConnectionId).Key;
if (userName != null)
{
Clients.Others.ParticipantDisconnection(userName);
if(UserList.Count < 2 && InGame)
{
string notiMsg = "플레이어의 숫자가 적어 게임이 종료되었습니다.";
Clients.All.BroadcastGameEnd(notiMsg);
GameCount = 0;
InGame = false;
Console.WriteLine($"-- Game Ended");
}
Console.WriteLine($"<> {userName} disconnected");
}
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
var userName = UserList.SingleOrDefault((c) => c.Value.ID == Context.ConnectionId).Key;
if (userName != null)
{
Clients.Others.ParticipantReconnection(userName);
Console.WriteLine($"== {userName} reconnected");
}
return base.OnReconnected();
}
public List<User> Login(string name, byte[] photo)
{
if (!UserList.ContainsKey(name))
{
Console.WriteLine($"++ {name} logged in");
User newUser = new User { Name = name, ID = Context.ConnectionId, Photo = photo, seq = UserList.Count + 1 };
var added = UserList.TryAdd(name, newUser);
List<User> users = new List<User>(UserList.Values);
if (!added) return null;
Clients.CallerState.UserName = name;
Clients.Others.ParticipantLogin(newUser);
if (InGame)
{
string notiMsg = $"현재 게임 중입니다. 현재 출제자는 {CurrentHost.Name}님 입니다.";
Clients.Client(newUser.ID).BroadcastGameStart(notiMsg);
Clients.Client(newUser.ID).BroadcastSetHost(CurrentHost.Name, AnswerList.CurrentAnswer);
}
return users;
}
return null;
}
//// 이거 만들다 맘 ConcurrentDictionary<int, game>을 만들어야되나?
//public List<User> CreateGameRoom(string UserName, byte[] photo, string GameName)
//{
// if (!UserList.ContainsKey(UserName))
// {
// Console.WriteLine($"++ {UserName} create game titled : {GameName} ");
// int newGameNumber = GameList.Count + 1;
// List<User> users = new List<User>(UserList.Values);
// Game newGame = new Game { Name = GameName, Number = newGameNumber };
// User newUser = new User { Name = UserName, ID = Context.ConnectionId, Photo = photo };
// var added = GameList.TryAdd(GameName, newGame);
// if (!added) return null;
// Groups.Add(Context.ConnectionId, GameName);
// Clients.CallerState.UserName = UserName;
// Clients.Others.ParticipantLogin(newUser);
// return users;
// }
// return null;
//}
public void Logout()
{
var name = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(name))
{
User client = new User();
UserList.TryRemove(name, out client);
Clients.Others.ParticipantLogout(name);
if (UserList.Count < 2 && InGame)
{
string notiMsg = "플레이어의 숫자가 적어 게임이 종료되었습니다.";
Clients.All.BroadcastGameEnd(notiMsg);
GameCount = 0;
InGame = false;
Console.WriteLine($"-- Game Ended");
}
Console.WriteLine($"-- {name} logged out");
}
}
public void BeginGame()
{
var name = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(name) && !InGame)
{
InGame = true;
//User host = new User();
//CurrentHost = UserList.Values.SingleOrDefault((u) => u.seq == 1);
int minSeq = UserList.Min((u) => u.Value.seq);
CurrentHost = UserList.Values.SingleOrDefault((u) => u.seq == minSeq);
AnswerList = new QuizAnswerRepo();
string noticeMsg = $"{name}님이 게임을 시작했습니다. 출제자는 {CurrentHost.Name}님 입니다.";
Clients.All.BroadcastGameStart(noticeMsg);
Clients.All.BroadcastSetHost(CurrentHost.Name, AnswerList.GenerateAnwer());
Console.WriteLine($"-- {name} started the game / ingame : {InGame.ToString()}");
}
}
public void EndGame()
{
var name = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(name) && InGame)
{
InGame = false;
GameCount = 0;
string notiMsg = "게임이 종료되었습니다.";
Clients.All.BroadcastGameEnd(notiMsg);
Console.WriteLine($"-- Game Ended / ingmae : {InGame.ToString()}");
}
}
public void BroadcastTextMessage(string message)
{
var name = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(message))
{
Clients.Others.BroadcastTextMessage(name, message);
}
}
public void BroadcastImageMessage(byte[] img)
{
var name = Clients.CallerState.UserName;
if (img != null)
{
Clients.Others.BroadcastPictureMessage(name, img);
}
}
public void BroadcastStrokes(byte[] strokeArr)
{
var name = Clients.CallerState.UserName;
if (strokeArr != null)
{
Clients.Others.BroadcastStrokes(name, strokeArr);
}
}
public void UnicastTextMessage(string recepient, string message)
{
var sender = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(sender) && recepient != sender &&
!string.IsNullOrEmpty(message) && UserList.ContainsKey(recepient))
{
User client = new User();
UserList.TryGetValue(recepient, out client);
Clients.Client(client.ID).UnicastTextMessage(sender, message);
}
}
public void UnicastImageMessage(string recepient, byte[] img)
{
var sender = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(sender) && recepient != sender &&
img != null && UserList.ContainsKey(recepient))
{
User client = new User();
UserList.TryGetValue(recepient, out client);
Clients.Client(client.ID).UnicastPictureMessage(sender, img);
}
}
public void Typing(string recepient)
{
if (string.IsNullOrEmpty(recepient)) return;
var sender = Clients.CallerState.UserName;
User client = new User();
UserList.TryGetValue(recepient, out client);
Clients.Client(client.ID).ParticipantTyping(sender);
}
public void IsRight(string message)
{
var sender = Clients.CallerState.UserName;
if (!string.IsNullOrEmpty(sender) && !string.IsNullOrEmpty(message))
{
// 정답 이벤트 송출
if (InGame && message.Equals(AnswerList.CurrentAnswer)) {
Console.WriteLine($"{sender} solves the quiz!");
string notiMsg = $"{sender}님이 정답을 맞추셧습니다!";
Clients.All.BraodcastAnswerIsRight(notiMsg ,sender);
}
// 다음 턴 세팅
if (GameCount <= 10 && InGame)
{
//User oldHost = new User();
//UserList.TryGetValue(sender,out oldHost);
//User newHost;
if(UserList.Count >= CurrentHost.seq + 1)
{
for(int i = CurrentHost.seq + 1; i <= UserList.Count; i++)
{
var userName = UserList.SingleOrDefault((c) => c.Value.seq == i).Key;
if (userName != null)
{
CurrentHost = UserList.Values.SingleOrDefault((c) => c.seq == i);
break;
}
}
Console.WriteLine($"seq : {CurrentHost.seq}");
}
else
{
CurrentHost = UserList.Values.SingleOrDefault<User>((u) => u.seq == 1);
Console.WriteLine($"seq : {CurrentHost.seq}");
}
Clients.All.BroadcastSetHost(CurrentHost.Name, AnswerList.GenerateAnwer());
GameCount++;
}
else
{
string notiMsg = "게임이 종료되었습니다.";
Clients.All.BroadcastGameEnd(notiMsg);
GameCount = 0;
InGame = false;
}
}
}
}
} | 37.881041 | 124 | 0.501963 | [
"MIT"
] | obidkor/DrawingGame | ChatServerCS/ChatHub.cs | 10,458 | C# |
// ------------------------------------------------------------------------------------------------
// This code was generated by EntityFramework Reverse POCO Generator (http://www.reversepoco.com/).
// Created by Simon Hughes (https://about.me/simon.hughes).
//
// Do not make changes directly to this file - edit the template instead.
//
// The following connection settings were used to generate this file:
// Configuration file: "IntelliTestAndUnitTesting\App.config"
// Connection String Name: "AdventureWorks"
// Connection String: "Data Source=.\SQL2014;Initial Catalog=AdventureWorks2014;Integrated Security=true"
// ------------------------------------------------------------------------------------------------
// Database Edition : Express Edition (64-bit)
// Database Engine Edition: Express
// <auto-generated>
// ReSharper disable RedundantUsingDirective
// ReSharper disable DoNotCallOverridableMethodsInConstructor
// ReSharper disable InconsistentNaming
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable PartialMethodWithSinglePart
// ReSharper disable RedundantNameQualifier
// TargetFrameworkVersion = 4.51
#pragma warning disable 1591 // Ignore "Missing XML Comment" warning
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Data.Entity.Infrastructure;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data;
using System.Data.Entity.Core.Objects;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data.Entity.ModelConfiguration;
using System.Threading;
using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption;
namespace IntelliTestAndUnitTesting
{
// ************************************************************************
// Unit of work
public interface IMyDbContext : IDisposable
{
DbSet<Person_Address> Person_Addresses { get; set; } // Address
DbSet<Person_AddressType> Person_AddressTypes { get; set; } // AddressType
DbSet<Person_BusinessEntity> Person_BusinessEntities { get; set; } // BusinessEntity
DbSet<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; } // BusinessEntityAddress
DbSet<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; } // BusinessEntityContact
DbSet<Person_ContactType> Person_ContactTypes { get; set; } // ContactType
DbSet<Person_CountryRegion> Person_CountryRegions { get; set; } // CountryRegion
DbSet<Person_EmailAddress> Person_EmailAddresses { get; set; } // EmailAddress
DbSet<Person_Password> Person_Passwords { get; set; } // Password
DbSet<Person_Person> Person_People { get; set; } // Person
DbSet<Person_PersonPhone> Person_PersonPhones { get; set; } // PersonPhone
DbSet<Person_PhoneNumberType> Person_PhoneNumberTypes { get; set; } // PhoneNumberType
DbSet<Person_StateProvince> Person_StateProvinces { get; set; } // StateProvince
DbSet<Person_VAdditionalContactInfo> Person_VAdditionalContactInfoes { get; set; } // vAdditionalContactInfo
DbSet<Person_VStateProvinceCountryRegion> Person_VStateProvinceCountryRegions { get; set; } // vStateProvinceCountryRegion
int SaveChanges();
System.Threading.Tasks.Task<int> SaveChangesAsync();
System.Threading.Tasks.Task<int> SaveChangesAsync(CancellationToken cancellationToken);
// Stored Procedures
}
// ************************************************************************
// Database context
public class MyDbContext : DbContext, IMyDbContext
{
public DbSet<Person_Address> Person_Addresses { get; set; } // Address
public DbSet<Person_AddressType> Person_AddressTypes { get; set; } // AddressType
public DbSet<Person_BusinessEntity> Person_BusinessEntities { get; set; } // BusinessEntity
public DbSet<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; } // BusinessEntityAddress
public DbSet<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; } // BusinessEntityContact
public DbSet<Person_ContactType> Person_ContactTypes { get; set; } // ContactType
public DbSet<Person_CountryRegion> Person_CountryRegions { get; set; } // CountryRegion
public DbSet<Person_EmailAddress> Person_EmailAddresses { get; set; } // EmailAddress
public DbSet<Person_Password> Person_Passwords { get; set; } // Password
public DbSet<Person_Person> Person_People { get; set; } // Person
public DbSet<Person_PersonPhone> Person_PersonPhones { get; set; } // PersonPhone
public DbSet<Person_PhoneNumberType> Person_PhoneNumberTypes { get; set; } // PhoneNumberType
public DbSet<Person_StateProvince> Person_StateProvinces { get; set; } // StateProvince
public DbSet<Person_VAdditionalContactInfo> Person_VAdditionalContactInfoes { get; set; } // vAdditionalContactInfo
public DbSet<Person_VStateProvinceCountryRegion> Person_VStateProvinceCountryRegions { get; set; } // vStateProvinceCountryRegion
static MyDbContext()
{
System.Data.Entity.Database.SetInitializer<MyDbContext>(null);
}
public MyDbContext()
: base("Name=AdventureWorks")
{
}
public MyDbContext(string connectionString) : base(connectionString)
{
}
public MyDbContext(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model)
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
public bool IsSqlParameterNull(SqlParameter param)
{
var sqlValue = param.SqlValue;
var nullableValue = sqlValue as INullable;
if (nullableValue != null)
return nullableValue.IsNull;
return (sqlValue == null || sqlValue == DBNull.Value);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new Person_AddressConfiguration());
modelBuilder.Configurations.Add(new Person_AddressTypeConfiguration());
modelBuilder.Configurations.Add(new Person_BusinessEntityConfiguration());
modelBuilder.Configurations.Add(new Person_BusinessEntityAddressConfiguration());
modelBuilder.Configurations.Add(new Person_BusinessEntityContactConfiguration());
modelBuilder.Configurations.Add(new Person_ContactTypeConfiguration());
modelBuilder.Configurations.Add(new Person_CountryRegionConfiguration());
modelBuilder.Configurations.Add(new Person_EmailAddressConfiguration());
modelBuilder.Configurations.Add(new Person_PasswordConfiguration());
modelBuilder.Configurations.Add(new Person_PersonConfiguration());
modelBuilder.Configurations.Add(new Person_PersonPhoneConfiguration());
modelBuilder.Configurations.Add(new Person_PhoneNumberTypeConfiguration());
modelBuilder.Configurations.Add(new Person_StateProvinceConfiguration());
modelBuilder.Configurations.Add(new Person_VAdditionalContactInfoConfiguration());
modelBuilder.Configurations.Add(new Person_VStateProvinceCountryRegionConfiguration());
}
public static DbModelBuilder CreateModel(DbModelBuilder modelBuilder, string schema)
{
modelBuilder.Configurations.Add(new Person_AddressConfiguration(schema));
modelBuilder.Configurations.Add(new Person_AddressTypeConfiguration(schema));
modelBuilder.Configurations.Add(new Person_BusinessEntityConfiguration(schema));
modelBuilder.Configurations.Add(new Person_BusinessEntityAddressConfiguration(schema));
modelBuilder.Configurations.Add(new Person_BusinessEntityContactConfiguration(schema));
modelBuilder.Configurations.Add(new Person_ContactTypeConfiguration(schema));
modelBuilder.Configurations.Add(new Person_CountryRegionConfiguration(schema));
modelBuilder.Configurations.Add(new Person_EmailAddressConfiguration(schema));
modelBuilder.Configurations.Add(new Person_PasswordConfiguration(schema));
modelBuilder.Configurations.Add(new Person_PersonConfiguration(schema));
modelBuilder.Configurations.Add(new Person_PersonPhoneConfiguration(schema));
modelBuilder.Configurations.Add(new Person_PhoneNumberTypeConfiguration(schema));
modelBuilder.Configurations.Add(new Person_StateProvinceConfiguration(schema));
modelBuilder.Configurations.Add(new Person_VAdditionalContactInfoConfiguration(schema));
modelBuilder.Configurations.Add(new Person_VStateProvinceCountryRegionConfiguration(schema));
return modelBuilder;
}
// Stored Procedures
}
// ************************************************************************
// Fake Database context
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class FakeMyDbContext : IMyDbContext
{
public DbSet<Person_Address> Person_Addresses { get; set; }
public DbSet<Person_AddressType> Person_AddressTypes { get; set; }
public DbSet<Person_BusinessEntity> Person_BusinessEntities { get; set; }
public DbSet<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; }
public DbSet<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; }
public DbSet<Person_ContactType> Person_ContactTypes { get; set; }
public DbSet<Person_CountryRegion> Person_CountryRegions { get; set; }
public DbSet<Person_EmailAddress> Person_EmailAddresses { get; set; }
public DbSet<Person_Password> Person_Passwords { get; set; }
public DbSet<Person_Person> Person_People { get; set; }
public DbSet<Person_PersonPhone> Person_PersonPhones { get; set; }
public DbSet<Person_PhoneNumberType> Person_PhoneNumberTypes { get; set; }
public DbSet<Person_StateProvince> Person_StateProvinces { get; set; }
public DbSet<Person_VAdditionalContactInfo> Person_VAdditionalContactInfoes { get; set; }
public DbSet<Person_VStateProvinceCountryRegion> Person_VStateProvinceCountryRegions { get; set; }
public FakeMyDbContext()
{
Person_Addresses = new FakeDbSet<Person_Address>("AddressId");
Person_AddressTypes = new FakeDbSet<Person_AddressType>("AddressTypeId");
Person_BusinessEntities = new FakeDbSet<Person_BusinessEntity>("BusinessEntityId");
Person_BusinessEntityAddresses = new FakeDbSet<Person_BusinessEntityAddress>("BusinessEntityId", "AddressId", "AddressTypeId");
Person_BusinessEntityContacts = new FakeDbSet<Person_BusinessEntityContact>("BusinessEntityId", "PersonId", "ContactTypeId");
Person_ContactTypes = new FakeDbSet<Person_ContactType>("ContactTypeId");
Person_CountryRegions = new FakeDbSet<Person_CountryRegion>("CountryRegionCode");
Person_EmailAddresses = new FakeDbSet<Person_EmailAddress>("BusinessEntityId", "EmailAddressId");
Person_Passwords = new FakeDbSet<Person_Password>("BusinessEntityId");
Person_People = new FakeDbSet<Person_Person>("BusinessEntityId");
Person_PersonPhones = new FakeDbSet<Person_PersonPhone>("BusinessEntityId", "PhoneNumber", "PhoneNumberTypeId");
Person_PhoneNumberTypes = new FakeDbSet<Person_PhoneNumberType>("PhoneNumberTypeId");
Person_StateProvinces = new FakeDbSet<Person_StateProvince>("StateProvinceId");
Person_VAdditionalContactInfoes = new FakeDbSet<Person_VAdditionalContactInfo>("BusinessEntityId", "FirstName", "LastName", "Rowguid", "ModifiedDate");
Person_VStateProvinceCountryRegions = new FakeDbSet<Person_VStateProvinceCountryRegion>("StateProvinceId", "StateProvinceCode", "IsOnlyStateProvinceFlag", "StateProvinceName", "TerritoryId", "CountryRegionCode", "CountryRegionName");
}
public int SaveChangesCount { get; private set; }
public int SaveChanges()
{
++SaveChangesCount;
return 1;
}
public System.Threading.Tasks.Task<int> SaveChangesAsync()
{
++SaveChangesCount;
return System.Threading.Tasks.Task<int>.Factory.StartNew(() => 1);
}
public System.Threading.Tasks.Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
++SaveChangesCount;
return System.Threading.Tasks.Task<int>.Factory.StartNew(() => 1, cancellationToken);
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
}
// Stored Procedures
}
// ************************************************************************
// Fake DbSet
// Implementing Find:
// The Find method is difficult to implement in a generic fashion. If
// you need to test code that makes use of the Find method it is
// easiest to create a test DbSet for each of the entity types that
// need to support find. You can then write logic to find that
// particular type of entity, as shown below:
// public class FakeBlogDbSet : FakeDbSet<Blog>
// {
// public override Blog Find(params object[] keyValues)
// {
// var id = (int) keyValues.Single();
// return this.SingleOrDefault(b => b.BlogId == id);
// }
// }
// Read more about it here: https://msdn.microsoft.com/en-us/data/dn314431.aspx
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class FakeDbSet<TEntity> : DbSet<TEntity>, IQueryable, IEnumerable<TEntity>, IDbAsyncEnumerable<TEntity> where TEntity : class
{
private readonly System.Reflection.PropertyInfo[] _primaryKeys;
private readonly ObservableCollection<TEntity> _data;
private readonly IQueryable _query;
public FakeDbSet()
{
_data = new ObservableCollection<TEntity>();
_query = _data.AsQueryable();
}
public FakeDbSet(params string[] primaryKeys)
{
_primaryKeys = typeof(TEntity).GetProperties().Where(x => primaryKeys.Contains(x.Name)).ToArray();
_data = new ObservableCollection<TEntity>();
_query = _data.AsQueryable();
}
public override TEntity Find(params object[] keyValues)
{
if (_primaryKeys == null)
throw new ArgumentException("No primary keys defined");
if (keyValues.Length != _primaryKeys.Length)
throw new ArgumentException("Incorrect number of keys passed to Find method");
var keyQuery = this.AsQueryable();
keyQuery = keyValues
.Select((t, i) => i)
.Aggregate(keyQuery,
(current, x) =>
current.Where(entity => _primaryKeys[x].GetValue(entity, null).Equals(keyValues[x])));
return keyQuery.SingleOrDefault();
}
public override System.Threading.Tasks.Task<TEntity> FindAsync(CancellationToken cancellationToken, params object[] keyValues)
{
return System.Threading.Tasks.Task<TEntity>.Factory.StartNew(() => Find(keyValues), cancellationToken);
}
public override System.Threading.Tasks.Task<TEntity> FindAsync(params object[] keyValues)
{
return System.Threading.Tasks.Task<TEntity>.Factory.StartNew(() => Find(keyValues));
}
public override IEnumerable<TEntity> AddRange(IEnumerable<TEntity> entities)
{
if (entities == null) throw new ArgumentNullException("entities");
var items = entities.ToList();
foreach (var entity in items)
{
_data.Add(entity);
}
return items;
}
public override TEntity Add(TEntity item)
{
if (item == null) throw new ArgumentNullException("item");
_data.Add(item);
return item;
}
public override TEntity Remove(TEntity item)
{
if (item == null) throw new ArgumentNullException("item");
_data.Remove(item);
return item;
}
public override TEntity Attach(TEntity item)
{
if (item == null) throw new ArgumentNullException("item");
_data.Add(item);
return item;
}
public override TEntity Create()
{
return Activator.CreateInstance<TEntity>();
}
public override TDerivedEntity Create<TDerivedEntity>()
{
return Activator.CreateInstance<TDerivedEntity>();
}
public override ObservableCollection<TEntity> Local
{
get { return _data; }
}
Type IQueryable.ElementType
{
get { return _query.ElementType; }
}
Expression IQueryable.Expression
{
get { return _query.Expression; }
}
IQueryProvider IQueryable.Provider
{
get { return new FakeDbAsyncQueryProvider<TEntity>(_query.Provider); }
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator<TEntity> IEnumerable<TEntity>.GetEnumerator()
{
return _data.GetEnumerator();
}
IDbAsyncEnumerator<TEntity> IDbAsyncEnumerable<TEntity>.GetAsyncEnumerator()
{
return new FakeDbAsyncEnumerator<TEntity>(_data.GetEnumerator());
}
}
public class FakeDbAsyncQueryProvider<TEntity> : IDbAsyncQueryProvider
{
private readonly IQueryProvider _inner;
public FakeDbAsyncQueryProvider(IQueryProvider inner)
{
_inner = inner;
}
public IQueryable CreateQuery(Expression expression)
{
return new FakeDbAsyncEnumerable<TEntity>(expression);
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
return new FakeDbAsyncEnumerable<TElement>(expression);
}
public object Execute(Expression expression)
{
return _inner.Execute(expression);
}
public TResult Execute<TResult>(Expression expression)
{
return _inner.Execute<TResult>(expression);
}
public System.Threading.Tasks.Task<object> ExecuteAsync(Expression expression, CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(Execute(expression));
}
public System.Threading.Tasks.Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(Execute<TResult>(expression));
}
}
public class FakeDbAsyncEnumerable<T> : EnumerableQuery<T>, IDbAsyncEnumerable<T>, IQueryable<T>
{
public FakeDbAsyncEnumerable(IEnumerable<T> enumerable)
: base(enumerable)
{ }
public FakeDbAsyncEnumerable(Expression expression)
: base(expression)
{ }
public IDbAsyncEnumerator<T> GetAsyncEnumerator()
{
return new FakeDbAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
IDbAsyncEnumerator IDbAsyncEnumerable.GetAsyncEnumerator()
{
return GetAsyncEnumerator();
}
IQueryProvider IQueryable.Provider
{
get { return new FakeDbAsyncQueryProvider<T>(this); }
}
}
public class FakeDbAsyncEnumerator<T> : IDbAsyncEnumerator<T>
{
private readonly IEnumerator<T> _inner;
public FakeDbAsyncEnumerator(IEnumerator<T> inner)
{
_inner = inner;
}
public void Dispose()
{
_inner.Dispose();
}
public System.Threading.Tasks.Task<bool> MoveNextAsync(CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(_inner.MoveNext());
}
public T Current
{
get { return _inner.Current; }
}
object IDbAsyncEnumerator.Current
{
get { return Current; }
}
}
// ************************************************************************
// POCO classes
// Address
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_Address
{
///<summary>
/// Primary key for Address records.
///</summary>
public int AddressId { get; set; } // AddressID (Primary key)
///<summary>
/// First street address line.
///</summary>
public string AddressLine1 { get; set; } // AddressLine1
///<summary>
/// Second street address line.
///</summary>
public string AddressLine2 { get; set; } // AddressLine2
///<summary>
/// Name of the city.
///</summary>
public string City { get; set; } // City
///<summary>
/// Unique identification number for the state or province. Foreign key to StateProvince table.
///</summary>
public int StateProvinceId { get; set; } // StateProvinceID
///<summary>
/// Postal code for the street address.
///</summary>
public string PostalCode { get; set; } // PostalCode
///<summary>
/// Latitude and longitude of this address.
///</summary>
public System.Data.Entity.Spatial.DbGeography SpatialLocation { get; set; } // SpatialLocation
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; } // Many to many mapping
// Foreign keys
public virtual Person_StateProvince Person_StateProvince { get; set; } // FK_Address_StateProvince_StateProvinceID
public Person_Address()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
Person_BusinessEntityAddresses = new List<Person_BusinessEntityAddress>();
}
}
// AddressType
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_AddressType
{
///<summary>
/// Primary key for AddressType records.
///</summary>
public int AddressTypeId { get; set; } // AddressTypeID (Primary key)
///<summary>
/// Address type description. For example, Billing, Home, or Shipping.
///</summary>
public string Name { get; set; } // Name
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; } // Many to many mapping
public Person_AddressType()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
Person_BusinessEntityAddresses = new List<Person_BusinessEntityAddress>();
}
}
// BusinessEntity
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_BusinessEntity
{
///<summary>
/// Primary key for all customers, vendors, and employees.
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_BusinessEntityAddress> Person_BusinessEntityAddresses { get; set; } // Many to many mapping
public virtual ICollection<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; } // Many to many mapping
public virtual Person_Person Person_Person { get; set; } // Person.FK_Person_BusinessEntity_BusinessEntityID
public Person_BusinessEntity()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
Person_BusinessEntityAddresses = new List<Person_BusinessEntityAddress>();
Person_BusinessEntityContacts = new List<Person_BusinessEntityContact>();
}
}
// BusinessEntityAddress
public class Person_BusinessEntityAddress
{
///<summary>
/// Primary key. Foreign key to BusinessEntity.BusinessEntityID.
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Primary key. Foreign key to Address.AddressID.
///</summary>
public int AddressId { get; set; } // AddressID (Primary key)
///<summary>
/// Primary key. Foreign key to AddressType.AddressTypeID.
///</summary>
public int AddressTypeId { get; set; } // AddressTypeID (Primary key)
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
public virtual Person_Address Person_Address { get; set; } // FK_BusinessEntityAddress_Address_AddressID
public virtual Person_AddressType Person_AddressType { get; set; } // FK_BusinessEntityAddress_AddressType_AddressTypeID
public virtual Person_BusinessEntity Person_BusinessEntity { get; set; } // FK_BusinessEntityAddress_BusinessEntity_BusinessEntityID
public Person_BusinessEntityAddress()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
}
}
// BusinessEntityContact
public class Person_BusinessEntityContact
{
///<summary>
/// Primary key. Foreign key to BusinessEntity.BusinessEntityID.
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Primary key. Foreign key to Person.BusinessEntityID.
///</summary>
public int PersonId { get; set; } // PersonID (Primary key)
///<summary>
/// Primary key. Foreign key to ContactType.ContactTypeID.
///</summary>
public int ContactTypeId { get; set; } // ContactTypeID (Primary key)
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
public virtual Person_BusinessEntity Person_BusinessEntity { get; set; } // FK_BusinessEntityContact_BusinessEntity_BusinessEntityID
public virtual Person_ContactType Person_ContactType { get; set; } // FK_BusinessEntityContact_ContactType_ContactTypeID
public virtual Person_Person Person_Person { get; set; } // FK_BusinessEntityContact_Person_PersonID
public Person_BusinessEntityContact()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
}
}
// ContactType
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_ContactType
{
///<summary>
/// Primary key for ContactType records.
///</summary>
public int ContactTypeId { get; set; } // ContactTypeID (Primary key)
///<summary>
/// Contact type description.
///</summary>
public string Name { get; set; } // Name
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; } // Many to many mapping
public Person_ContactType()
{
ModifiedDate = System.DateTime.Now;
Person_BusinessEntityContacts = new List<Person_BusinessEntityContact>();
}
}
// CountryRegion
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_CountryRegion
{
///<summary>
/// ISO standard code for countries and regions.
///</summary>
public string CountryRegionCode { get; set; } // CountryRegionCode (Primary key)
///<summary>
/// Country or region name.
///</summary>
public string Name { get; set; } // Name
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_StateProvince> Person_StateProvinces { get; set; } // StateProvince.FK_StateProvince_CountryRegion_CountryRegionCode
public Person_CountryRegion()
{
ModifiedDate = System.DateTime.Now;
Person_StateProvinces = new List<Person_StateProvince>();
}
}
// EmailAddress
public class Person_EmailAddress
{
///<summary>
/// Primary key. Person associated with this email address. Foreign key to Person.BusinessEntityID
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Primary key. ID of this email address.
///</summary>
public int EmailAddressId { get; set; } // EmailAddressID (Primary key)
///<summary>
/// E-mail address for the person.
///</summary>
public string EmailAddress { get; set; } // EmailAddress
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
public virtual Person_Person Person_Person { get; set; } // FK_EmailAddress_Person_BusinessEntityID
public Person_EmailAddress()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
}
}
// Password
public class Person_Password
{
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Password for the e-mail account.
///</summary>
public string PasswordHash { get; set; } // PasswordHash
///<summary>
/// Random value concatenated with the password string before the password is hashed.
///</summary>
public string PasswordSalt { get; set; } // PasswordSalt
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
public virtual Person_Person Person_Person { get; set; } // FK_Password_Person_BusinessEntityID
public Person_Password()
{
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
}
}
// Person
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_Person
{
///<summary>
/// Primary key for Person records.
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Primary type of person: SC = Store Contact, IN = Individual (retail) customer, SP = Sales person, EM = Employee (non-sales), VC = Vendor contact, GC = General contact
///</summary>
public string PersonType { get; set; } // PersonType
///<summary>
/// 0 = The data in FirstName and LastName are stored in western style (first name, last name) order. 1 = Eastern style (last name, first name) order.
///</summary>
public bool NameStyle { get; set; } // NameStyle
///<summary>
/// A courtesy title. For example, Mr. or Ms.
///</summary>
public string Title { get; set; } // Title
///<summary>
/// First name of the person.
///</summary>
public string FirstName { get; set; } // FirstName
///<summary>
/// Middle name or middle initial of the person.
///</summary>
public string MiddleName { get; set; } // MiddleName
///<summary>
/// Last name of the person.
///</summary>
public string LastName { get; set; } // LastName
///<summary>
/// Surname suffix. For example, Sr. or Jr.
///</summary>
public string Suffix { get; set; } // Suffix
///<summary>
/// 0 = Contact does not wish to receive e-mail promotions, 1 = Contact does wish to receive e-mail promotions from AdventureWorks, 2 = Contact does wish to receive e-mail promotions from AdventureWorks and selected partners.
///</summary>
public int EmailPromotion { get; set; } // EmailPromotion
///<summary>
/// Additional contact information about the person stored in xml format.
///</summary>
public string AdditionalContactInfo { get; set; } // AdditionalContactInfo
///<summary>
/// Personal information such as hobbies, and income collected from online shoppers. Used for sales analysis.
///</summary>
public string Demographics { get; set; } // Demographics
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_BusinessEntityContact> Person_BusinessEntityContacts { get; set; } // Many to many mapping
public virtual ICollection<Person_EmailAddress> Person_EmailAddresses { get; set; } // Many to many mapping
public virtual ICollection<Person_PersonPhone> Person_PersonPhones { get; set; } // Many to many mapping
public virtual Person_Password Person_Password { get; set; } // Password.FK_Password_Person_BusinessEntityID
// Foreign keys
public virtual Person_BusinessEntity Person_BusinessEntity { get; set; } // FK_Person_BusinessEntity_BusinessEntityID
public Person_Person()
{
NameStyle = false;
EmailPromotion = 0;
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
Person_BusinessEntityContacts = new List<Person_BusinessEntityContact>();
Person_EmailAddresses = new List<Person_EmailAddress>();
Person_PersonPhones = new List<Person_PersonPhone>();
}
}
// PersonPhone
public class Person_PersonPhone
{
///<summary>
/// Business entity identification number. Foreign key to Person.BusinessEntityID.
///</summary>
public int BusinessEntityId { get; set; } // BusinessEntityID (Primary key)
///<summary>
/// Telephone number identification number.
///</summary>
public string PhoneNumber { get; set; } // PhoneNumber (Primary key)
///<summary>
/// Kind of phone number. Foreign key to PhoneNumberType.PhoneNumberTypeID.
///</summary>
public int PhoneNumberTypeId { get; set; } // PhoneNumberTypeID (Primary key)
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Foreign keys
public virtual Person_Person Person_Person { get; set; } // FK_PersonPhone_Person_BusinessEntityID
public virtual Person_PhoneNumberType Person_PhoneNumberType { get; set; } // FK_PersonPhone_PhoneNumberType_PhoneNumberTypeID
public Person_PersonPhone()
{
ModifiedDate = System.DateTime.Now;
}
}
// PhoneNumberType
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_PhoneNumberType
{
///<summary>
/// Primary key for telephone number type records.
///</summary>
public int PhoneNumberTypeId { get; set; } // PhoneNumberTypeID (Primary key)
///<summary>
/// Name of the telephone number type
///</summary>
public string Name { get; set; } // Name
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_PersonPhone> Person_PersonPhones { get; set; } // Many to many mapping
public Person_PhoneNumberType()
{
ModifiedDate = System.DateTime.Now;
Person_PersonPhones = new List<Person_PersonPhone>();
}
}
// StateProvince
[GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.17.1.0")]
public class Person_StateProvince
{
///<summary>
/// Primary key for StateProvince records.
///</summary>
public int StateProvinceId { get; set; } // StateProvinceID (Primary key)
///<summary>
/// ISO standard state or province code.
///</summary>
public string StateProvinceCode { get; set; } // StateProvinceCode
///<summary>
/// ISO standard country or region code. Foreign key to CountryRegion.CountryRegionCode.
///</summary>
public string CountryRegionCode { get; set; } // CountryRegionCode
///<summary>
/// 0 = StateProvinceCode exists. 1 = StateProvinceCode unavailable, using CountryRegionCode.
///</summary>
public bool IsOnlyStateProvinceFlag { get; set; } // IsOnlyStateProvinceFlag
///<summary>
/// State or province description.
///</summary>
public string Name { get; set; } // Name
///<summary>
/// ID of the territory in which the state or province is located. Foreign key to SalesTerritory.SalesTerritoryID.
///</summary>
public int TerritoryId { get; set; } // TerritoryID
///<summary>
/// ROWGUIDCOL number uniquely identifying the record. Used to support a merge replication sample.
///</summary>
public Guid Rowguid { get; set; } // rowguid
///<summary>
/// Date and time the record was last updated.
///</summary>
public DateTime ModifiedDate { get; set; } // ModifiedDate
// Reverse navigation
public virtual ICollection<Person_Address> Person_Addresses { get; set; } // Address.FK_Address_StateProvince_StateProvinceID
// Foreign keys
public virtual Person_CountryRegion Person_CountryRegion { get; set; } // FK_StateProvince_CountryRegion_CountryRegionCode
public Person_StateProvince()
{
IsOnlyStateProvinceFlag = true;
Rowguid = System.Guid.NewGuid();
ModifiedDate = System.DateTime.Now;
Person_Addresses = new List<Person_Address>();
}
}
// vAdditionalContactInfo
public class Person_VAdditionalContactInfo
{
public int BusinessEntityId { get; set; } // BusinessEntityID
public string FirstName { get; set; } // FirstName
public string MiddleName { get; set; } // MiddleName
public string LastName { get; set; } // LastName
public string TelephoneNumber { get; set; } // TelephoneNumber
public string TelephoneSpecialInstructions { get; set; } // TelephoneSpecialInstructions
public string Street { get; set; } // Street
public string City { get; set; } // City
public string StateProvince { get; set; } // StateProvince
public string PostalCode { get; set; } // PostalCode
public string CountryRegion { get; set; } // CountryRegion
public string HomeAddressSpecialInstructions { get; set; } // HomeAddressSpecialInstructions
public string EMailAddress { get; set; } // EMailAddress
public string EMailSpecialInstructions { get; set; } // EMailSpecialInstructions
public string EMailTelephoneNumber { get; set; } // EMailTelephoneNumber
public Guid Rowguid { get; set; } // rowguid
public DateTime ModifiedDate { get; set; } // ModifiedDate
}
// vStateProvinceCountryRegion
public class Person_VStateProvinceCountryRegion
{
public int StateProvinceId { get; set; } // StateProvinceID
public string StateProvinceCode { get; set; } // StateProvinceCode
public bool IsOnlyStateProvinceFlag { get; set; } // IsOnlyStateProvinceFlag
public string StateProvinceName { get; set; } // StateProvinceName
public int TerritoryId { get; set; } // TerritoryID
public string CountryRegionCode { get; set; } // CountryRegionCode
public string CountryRegionName { get; set; } // CountryRegionName
}
// ************************************************************************
// POCO Configuration
// Address
public class Person_AddressConfiguration : EntityTypeConfiguration<Person_Address>
{
public Person_AddressConfiguration()
: this("Person")
{
}
public Person_AddressConfiguration(string schema)
{
ToTable(schema + ".Address");
HasKey(x => x.AddressId);
Property(x => x.AddressId).HasColumnName("AddressID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.AddressLine1).HasColumnName("AddressLine1").IsRequired().HasColumnType("nvarchar").HasMaxLength(60);
Property(x => x.AddressLine2).HasColumnName("AddressLine2").IsOptional().HasColumnType("nvarchar").HasMaxLength(60);
Property(x => x.City).HasColumnName("City").IsRequired().HasColumnType("nvarchar").HasMaxLength(30);
Property(x => x.StateProvinceId).HasColumnName("StateProvinceID").IsRequired().HasColumnType("int");
Property(x => x.PostalCode).HasColumnName("PostalCode").IsRequired().HasColumnType("nvarchar").HasMaxLength(15);
Property(x => x.SpatialLocation).HasColumnName("SpatialLocation").IsOptional().HasColumnType("geography");
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_StateProvince).WithMany(b => b.Person_Addresses).HasForeignKey(c => c.StateProvinceId); // FK_Address_StateProvince_StateProvinceID
}
}
// AddressType
public class Person_AddressTypeConfiguration : EntityTypeConfiguration<Person_AddressType>
{
public Person_AddressTypeConfiguration()
: this("Person")
{
}
public Person_AddressTypeConfiguration(string schema)
{
ToTable(schema + ".AddressType");
HasKey(x => x.AddressTypeId);
Property(x => x.AddressTypeId).HasColumnName("AddressTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Name).HasColumnName("Name").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// BusinessEntity
public class Person_BusinessEntityConfiguration : EntityTypeConfiguration<Person_BusinessEntity>
{
public Person_BusinessEntityConfiguration()
: this("Person")
{
}
public Person_BusinessEntityConfiguration(string schema)
{
ToTable(schema + ".BusinessEntity");
HasKey(x => x.BusinessEntityId);
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// BusinessEntityAddress
public class Person_BusinessEntityAddressConfiguration : EntityTypeConfiguration<Person_BusinessEntityAddress>
{
public Person_BusinessEntityAddressConfiguration()
: this("Person")
{
}
public Person_BusinessEntityAddressConfiguration(string schema)
{
ToTable(schema + ".BusinessEntityAddress");
HasKey(x => new { x.BusinessEntityId, x.AddressId, x.AddressTypeId });
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.AddressId).HasColumnName("AddressID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.AddressTypeId).HasColumnName("AddressTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_Address).WithMany(b => b.Person_BusinessEntityAddresses).HasForeignKey(c => c.AddressId); // FK_BusinessEntityAddress_Address_AddressID
HasRequired(a => a.Person_AddressType).WithMany(b => b.Person_BusinessEntityAddresses).HasForeignKey(c => c.AddressTypeId); // FK_BusinessEntityAddress_AddressType_AddressTypeID
HasRequired(a => a.Person_BusinessEntity).WithMany(b => b.Person_BusinessEntityAddresses).HasForeignKey(c => c.BusinessEntityId); // FK_BusinessEntityAddress_BusinessEntity_BusinessEntityID
}
}
// BusinessEntityContact
public class Person_BusinessEntityContactConfiguration : EntityTypeConfiguration<Person_BusinessEntityContact>
{
public Person_BusinessEntityContactConfiguration()
: this("Person")
{
}
public Person_BusinessEntityContactConfiguration(string schema)
{
ToTable(schema + ".BusinessEntityContact");
HasKey(x => new { x.BusinessEntityId, x.PersonId, x.ContactTypeId });
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.PersonId).HasColumnName("PersonID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.ContactTypeId).HasColumnName("ContactTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_BusinessEntity).WithMany(b => b.Person_BusinessEntityContacts).HasForeignKey(c => c.BusinessEntityId); // FK_BusinessEntityContact_BusinessEntity_BusinessEntityID
HasRequired(a => a.Person_ContactType).WithMany(b => b.Person_BusinessEntityContacts).HasForeignKey(c => c.ContactTypeId); // FK_BusinessEntityContact_ContactType_ContactTypeID
HasRequired(a => a.Person_Person).WithMany(b => b.Person_BusinessEntityContacts).HasForeignKey(c => c.PersonId); // FK_BusinessEntityContact_Person_PersonID
}
}
// ContactType
public class Person_ContactTypeConfiguration : EntityTypeConfiguration<Person_ContactType>
{
public Person_ContactTypeConfiguration()
: this("Person")
{
}
public Person_ContactTypeConfiguration(string schema)
{
ToTable(schema + ".ContactType");
HasKey(x => x.ContactTypeId);
Property(x => x.ContactTypeId).HasColumnName("ContactTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Name).HasColumnName("Name").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// CountryRegion
public class Person_CountryRegionConfiguration : EntityTypeConfiguration<Person_CountryRegion>
{
public Person_CountryRegionConfiguration()
: this("Person")
{
}
public Person_CountryRegionConfiguration(string schema)
{
ToTable(schema + ".CountryRegion");
HasKey(x => x.CountryRegionCode);
Property(x => x.CountryRegionCode).HasColumnName("CountryRegionCode").IsRequired().HasColumnType("nvarchar").HasMaxLength(3).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Name).HasColumnName("Name").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// EmailAddress
public class Person_EmailAddressConfiguration : EntityTypeConfiguration<Person_EmailAddress>
{
public Person_EmailAddressConfiguration()
: this("Person")
{
}
public Person_EmailAddressConfiguration(string schema)
{
ToTable(schema + ".EmailAddress");
HasKey(x => new { x.BusinessEntityId, x.EmailAddressId });
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.EmailAddressId).HasColumnName("EmailAddressID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.EmailAddress).HasColumnName("EmailAddress").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_Person).WithMany(b => b.Person_EmailAddresses).HasForeignKey(c => c.BusinessEntityId); // FK_EmailAddress_Person_BusinessEntityID
}
}
// Password
public class Person_PasswordConfiguration : EntityTypeConfiguration<Person_Password>
{
public Person_PasswordConfiguration()
: this("Person")
{
}
public Person_PasswordConfiguration(string schema)
{
ToTable(schema + ".Password");
HasKey(x => x.BusinessEntityId);
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.PasswordHash).HasColumnName("PasswordHash").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(128);
Property(x => x.PasswordSalt).HasColumnName("PasswordSalt").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(10);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_Person).WithOptional(b => b.Person_Password); // FK_Password_Person_BusinessEntityID
}
}
// Person
public class Person_PersonConfiguration : EntityTypeConfiguration<Person_Person>
{
public Person_PersonConfiguration()
: this("Person")
{
}
public Person_PersonConfiguration(string schema)
{
ToTable(schema + ".Person");
HasKey(x => x.BusinessEntityId);
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.PersonType).HasColumnName("PersonType").IsRequired().IsFixedLength().HasColumnType("nchar").HasMaxLength(2);
Property(x => x.NameStyle).HasColumnName("NameStyle").IsRequired().HasColumnType("bit");
Property(x => x.Title).HasColumnName("Title").IsOptional().HasColumnType("nvarchar").HasMaxLength(8);
Property(x => x.FirstName).HasColumnName("FirstName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.MiddleName).HasColumnName("MiddleName").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.LastName).HasColumnName("LastName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.Suffix).HasColumnName("Suffix").IsOptional().HasColumnType("nvarchar").HasMaxLength(10);
Property(x => x.EmailPromotion).HasColumnName("EmailPromotion").IsRequired().HasColumnType("int");
Property(x => x.AdditionalContactInfo).HasColumnName("AdditionalContactInfo").IsOptional().HasColumnType("xml");
Property(x => x.Demographics).HasColumnName("Demographics").IsOptional().HasColumnType("xml");
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_BusinessEntity).WithOptional(b => b.Person_Person); // FK_Person_BusinessEntity_BusinessEntityID
}
}
// PersonPhone
public class Person_PersonPhoneConfiguration : EntityTypeConfiguration<Person_PersonPhone>
{
public Person_PersonPhoneConfiguration()
: this("Person")
{
}
public Person_PersonPhoneConfiguration(string schema)
{
ToTable(schema + ".PersonPhone");
HasKey(x => new { x.BusinessEntityId, x.PhoneNumber, x.PhoneNumberTypeId });
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.PhoneNumber).HasColumnName("PhoneNumber").IsRequired().HasColumnType("nvarchar").HasMaxLength(25).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.PhoneNumberTypeId).HasColumnName("PhoneNumberTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_Person).WithMany(b => b.Person_PersonPhones).HasForeignKey(c => c.BusinessEntityId); // FK_PersonPhone_Person_BusinessEntityID
HasRequired(a => a.Person_PhoneNumberType).WithMany(b => b.Person_PersonPhones).HasForeignKey(c => c.PhoneNumberTypeId); // FK_PersonPhone_PhoneNumberType_PhoneNumberTypeID
}
}
// PhoneNumberType
public class Person_PhoneNumberTypeConfiguration : EntityTypeConfiguration<Person_PhoneNumberType>
{
public Person_PhoneNumberTypeConfiguration()
: this("Person")
{
}
public Person_PhoneNumberTypeConfiguration(string schema)
{
ToTable(schema + ".PhoneNumberType");
HasKey(x => x.PhoneNumberTypeId);
Property(x => x.PhoneNumberTypeId).HasColumnName("PhoneNumberTypeID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Name).HasColumnName("Name").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// StateProvince
public class Person_StateProvinceConfiguration : EntityTypeConfiguration<Person_StateProvince>
{
public Person_StateProvinceConfiguration()
: this("Person")
{
}
public Person_StateProvinceConfiguration(string schema)
{
ToTable(schema + ".StateProvince");
HasKey(x => x.StateProvinceId);
Property(x => x.StateProvinceId).HasColumnName("StateProvinceID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.StateProvinceCode).HasColumnName("StateProvinceCode").IsRequired().IsFixedLength().HasColumnType("nchar").HasMaxLength(3);
Property(x => x.CountryRegionCode).HasColumnName("CountryRegionCode").IsRequired().HasColumnType("nvarchar").HasMaxLength(3);
Property(x => x.IsOnlyStateProvinceFlag).HasColumnName("IsOnlyStateProvinceFlag").IsRequired().HasColumnType("bit");
Property(x => x.Name).HasColumnName("Name").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.TerritoryId).HasColumnName("TerritoryID").IsRequired().HasColumnType("int");
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
// Foreign keys
HasRequired(a => a.Person_CountryRegion).WithMany(b => b.Person_StateProvinces).HasForeignKey(c => c.CountryRegionCode); // FK_StateProvince_CountryRegion_CountryRegionCode
}
}
// vAdditionalContactInfo
public class Person_VAdditionalContactInfoConfiguration : EntityTypeConfiguration<Person_VAdditionalContactInfo>
{
public Person_VAdditionalContactInfoConfiguration()
: this("Person")
{
}
public Person_VAdditionalContactInfoConfiguration(string schema)
{
ToTable(schema + ".vAdditionalContactInfo");
HasKey(x => new { x.BusinessEntityId, x.FirstName, x.LastName, x.Rowguid, x.ModifiedDate });
Property(x => x.BusinessEntityId).HasColumnName("BusinessEntityID").IsRequired().HasColumnType("int");
Property(x => x.FirstName).HasColumnName("FirstName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.MiddleName).HasColumnName("MiddleName").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.LastName).HasColumnName("LastName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.TelephoneNumber).HasColumnName("TelephoneNumber").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.TelephoneSpecialInstructions).HasColumnName("TelephoneSpecialInstructions").IsOptional().HasColumnType("nvarchar");
Property(x => x.Street).HasColumnName("Street").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.City).HasColumnName("City").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.StateProvince).HasColumnName("StateProvince").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.PostalCode).HasColumnName("PostalCode").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.CountryRegion).HasColumnName("CountryRegion").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.HomeAddressSpecialInstructions).HasColumnName("HomeAddressSpecialInstructions").IsOptional().HasColumnType("nvarchar");
Property(x => x.EMailAddress).HasColumnName("EMailAddress").IsOptional().HasColumnType("nvarchar").HasMaxLength(128);
Property(x => x.EMailSpecialInstructions).HasColumnName("EMailSpecialInstructions").IsOptional().HasColumnType("nvarchar");
Property(x => x.EMailTelephoneNumber).HasColumnName("EMailTelephoneNumber").IsOptional().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.Rowguid).HasColumnName("rowguid").IsRequired().HasColumnType("uniqueidentifier");
Property(x => x.ModifiedDate).HasColumnName("ModifiedDate").IsRequired().HasColumnType("datetime");
}
}
// vStateProvinceCountryRegion
public class Person_VStateProvinceCountryRegionConfiguration : EntityTypeConfiguration<Person_VStateProvinceCountryRegion>
{
public Person_VStateProvinceCountryRegionConfiguration()
: this("Person")
{
}
public Person_VStateProvinceCountryRegionConfiguration(string schema)
{
ToTable(schema + ".vStateProvinceCountryRegion");
HasKey(x => new { x.StateProvinceId, x.StateProvinceCode, x.IsOnlyStateProvinceFlag, x.StateProvinceName, x.TerritoryId, x.CountryRegionCode, x.CountryRegionName });
Property(x => x.StateProvinceId).HasColumnName("StateProvinceID").IsRequired().HasColumnType("int");
Property(x => x.StateProvinceCode).HasColumnName("StateProvinceCode").IsRequired().IsFixedLength().HasColumnType("nchar").HasMaxLength(3);
Property(x => x.IsOnlyStateProvinceFlag).HasColumnName("IsOnlyStateProvinceFlag").IsRequired().HasColumnType("bit");
Property(x => x.StateProvinceName).HasColumnName("StateProvinceName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
Property(x => x.TerritoryId).HasColumnName("TerritoryID").IsRequired().HasColumnType("int");
Property(x => x.CountryRegionCode).HasColumnName("CountryRegionCode").IsRequired().HasColumnType("nvarchar").HasMaxLength(3);
Property(x => x.CountryRegionName).HasColumnName("CountryRegionName").IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
}
}
// ************************************************************************
// Stored procedure return models
}
// </auto-generated>
| 45.264787 | 245 | 0.651204 | [
"Apache-2.0"
] | flcdrg/IntelliTestAndUnitTesting | IntelliTestAndUnitTesting/Database1.cs | 65,817 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Essgee.EventArguments
{
public class RenderScreenEventArgs : EventArgs
{
public int Width { get; private set; }
public int Height { get; private set; }
public byte[] FrameData { get; private set; }
public RenderScreenEventArgs(int width, int height, byte[] data)
{
Width = width;
Height = height;
FrameData = data;
}
}
}
| 20.608696 | 66 | 0.71519 | [
"MIT"
] | xdanieldzd/Essgee | Essgee/EventArguments/RenderScreenEventArgs.cs | 476 | C# |
version https://git-lfs.github.com/spec/v1
oid sha256:c662b75b96f0687b7aac642368540dace176eb7ff6a720850fa8379404209094
size 6482
| 32.25 | 75 | 0.883721 | [
"MIT"
] | Vakuzar/Multithreaded-Blood-Sim | Blood/Library/PackageCache/com.unity.shadergraph@8.1.0/Editor/Data/Nodes/Channel/FlipNode.cs | 129 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Managerofinvestigationsid.
/// </summary>
public static partial class ManagerofinvestigationsidExtensions
{
/// <summary>
/// Get adoxio_ManagerofInvestigationsId from adoxio_regions
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioRegionid'>
/// key: adoxio_regionid of adoxio_region
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMsystemuser Get(this IManagerofinvestigationsid operations, string adoxioRegionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetAsync(adoxioRegionid, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get adoxio_ManagerofInvestigationsId from adoxio_regions
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioRegionid'>
/// key: adoxio_regionid of adoxio_region
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMsystemuser> GetAsync(this IManagerofinvestigationsid operations, string adoxioRegionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(adoxioRegionid, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get adoxio_ManagerofInvestigationsId from adoxio_regions
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='adoxioRegionid'>
/// key: adoxio_regionid of adoxio_region
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<MicrosoftDynamicsCRMsystemuser> GetWithHttpMessages(this IManagerofinvestigationsid operations, string adoxioRegionid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetWithHttpMessagesAsync(adoxioRegionid, select, expand, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
| 44.054348 | 315 | 0.588206 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/ManagerofinvestigationsidExtensions.cs | 4,053 | C# |
using System;
using System.Globalization;
// ReSharper disable once CheckNamespace
namespace Hangfire.Azure.Documents.Helper
{
internal static class TimeHelper
{
private static readonly DateTime epochDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
internal static int ToEpoch(this DateTime date)
{
if (date.Equals(DateTime.MinValue)) return int.MinValue;
TimeSpan epochTimeSpan = date - epochDateTime;
return (int)epochTimeSpan.TotalSeconds;
}
internal static DateTime ToDateTime(this int totalSeconds) => epochDateTime.AddSeconds(totalSeconds);
internal static string TryParseToEpoch(this string s)
{
return DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime date)
? date.ToEpoch().ToString(CultureInfo.InvariantCulture)
: s;
}
internal static string TryParseEpochToDate(this string s)
{
return int.TryParse(s, out int epoch)
? epoch.ToDateTime().ToLocalTime().ToString("d/M/yyyy HH:mm:ss")
: s;
}
}
} | 35.117647 | 118 | 0.642379 | [
"MIT"
] | bzumhagen/Hangfire.AzureCosmosDb | src/Helper/TimeHelper.cs | 1,196 | C# |
using Uno.Extensions;
using Uno.Foundation.Logging;
using Uno.UI.DataBinding;
using Windows.UI.Xaml.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using Uno.Disposables;
using System.Runtime.CompilerServices;
using System.Text;
using System.Drawing;
namespace Windows.UI.Xaml.Controls
{
public partial class ScrollContentPresenter : ContentPresenter
{
public bool CanHorizontallyScroll { get; set; }
public bool CanVerticallyScroll { get; set; }
internal ScrollBarVisibility VerticalScrollBarVisibility { get; set; }
internal ScrollBarVisibility HorizontalScrollBarVisibility { get; set; }
}
}
| 24.730769 | 74 | 0.799378 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/Controls/ScrollContentPresenter/ScrollContentPresenter.netstdref.cs | 645 | 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("StyleInheritance.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StyleInheritance.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 36.413793 | 84 | 0.744318 | [
"Apache-2.0"
] | DLozanoNavas/xamarin-forms-book-samples | Chapter12/StyleInheritance/StyleInheritance/StyleInheritance.UWP/Properties/AssemblyInfo.cs | 1,057 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Scoring;
namespace osu.Game.Screens.Spectate
{
/// <summary>
/// An immutable spectator gameplay state.
/// </summary>
public class SpectatorGameplayState
{
/// <summary>
/// The score which the user is playing.
/// </summary>
public readonly Score Score;
/// <summary>
/// The ruleset which the user is playing.
/// </summary>
public readonly Ruleset Ruleset;
/// <summary>
/// The beatmap which the user is playing.
/// </summary>
public readonly WorkingBeatmap Beatmap;
public SpectatorGameplayState(Score score, Ruleset ruleset, WorkingBeatmap beatmap)
{
Score = score;
Ruleset = ruleset;
Beatmap = beatmap;
}
}
}
| 26.875 | 92 | 0.583256 | [
"MIT"
] | peppy/osu-new | osu.Game/Screens/Spectate/SpectatorGameplayState.cs | 1,036 | C# |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCMIS.ObjectModel;
using NCMIS.Produce;
using Kooboo.CMS.Content.Models;
using NCMIS.ObjectModel.MetaData;
namespace Kooboo.CMS.Content.Interoperability.CMIS
{
public interface IObjectService
{
string GetObjectId(object o);
bool TryPraseObjectId(string objectId, out string id);
void DeleteObject(string repositoryId, string objectId);
CmisObject GetObject(string objectId);
CmisObject GetParent(string repositoryId, string objectId);
IEnumerable<CmisObject> All(string repositoryId);
IEnumerable<CmisObject> GetChildren(string repositoryId, string objectId, string filter, IncludeRelationships includeRelationships);
AllowableActions GetAllowableActions(string repositoryId, string objectId);
NCMIS.ObjectModel.ContentStream GetContentStream(string repositoryId, string objectId, string streamId);
NCMIS.ObjectModel.CmisObject GetObject(string repositoryId, string objectId);
CmisProperties GetProperties(string repositoryId, string objectId);
void SetContentStream(string repositoryId, string documentId, NCMIS.ObjectModel.ContentStream contentStream, bool? overwriteFlag);
void UpdateProperties(string repositoryId, string objectId, NCMIS.ObjectModel.CmisProperties properties);
}
public static class ObjectService
{
static Dictionary<Type, IObjectService> services = new Dictionary<Type, IObjectService>()
{
{typeof(Folder), new FolderObjectService()},
{typeof(ContentBase),new DocumentObjectService()}
};
public static IObjectService GetService(Type type)
{
return services.Where(it => it.Key.IsAssignableFrom(type)).Select(it => it.Value).First();
}
public static string GetObjectId(object o)
{
return GetService(o.GetType()).GetObjectId(o);
}
public static IObjectService GetService(string objectId)
{
string id;
foreach (var service in services.Values)
{
if (service.TryPraseObjectId(objectId, out id))
{
return service;
}
}
return null;
}
}
}
| 36.188406 | 140 | 0.680817 | [
"BSD-3-Clause"
] | Bringsy/Kooboo.CMS | Kooboo.CMS/Kooboo.CMS.Web/Interoperability/CMIS/IObjectService.cs | 2,499 | C# |
// The following file is a part of the port of the project jp-verb-deconjugator to C#
// https://github.com/mistval/jp-verb-deconjugator
// the following is the license and the copyright notice of the original software
/*
MIT License
Copyright (c) 2017 mistval
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.Collections.Immutable;
using System.Linq;
namespace LibJpConjSharp.Deconjugation
{
internal class DerivationSequence
{
public ImmutableList<DerivationRule> AllDerivationsTaken { get; }
public ImmutableList<DerivationRule> NonSilentDerivationsTaken { get; }
public ImmutableList<string> NonSilentWordFormProgression { get; }
public DerivationSequence(
ImmutableList<DerivationRule> allDerivationsTaken,
ImmutableList<DerivationRule> nonSilentDerivationsTaken,
ImmutableList<string> nonSilentWordFormProgression)
{
AllDerivationsTaken = allDerivationsTaken ??
throw new ArgumentNullException(nameof(allDerivationsTaken));
NonSilentDerivationsTaken = nonSilentDerivationsTaken ??
throw new ArgumentNullException(nameof(nonSilentDerivationsTaken));
NonSilentWordFormProgression = nonSilentWordFormProgression ??
throw new ArgumentNullException(nameof(nonSilentWordFormProgression));
}
public DerivationSequence()
{
NonSilentDerivationsTaken = ImmutableList<DerivationRule>.Empty;
NonSilentWordFormProgression = ImmutableList<string>.Empty;
AllDerivationsTaken = ImmutableList<DerivationRule>.Empty;
}
public DerivationSequence With(
ImmutableList<DerivationRule> allDerivationsTaken = null,
ImmutableList<DerivationRule> nonSilentDerivationsTaken = null,
ImmutableList<string> nonSilentWordFormProgression = null)
{
return new DerivationSequence(
allDerivationsTaken ?? this.AllDerivationsTaken,
nonSilentDerivationsTaken ?? this.NonSilentDerivationsTaken,
nonSilentWordFormProgression ?? this.NonSilentWordFormProgression);
}
public DerivationSequence AddDerivation(DerivationRule derivationRule, string derivedWord)
{
bool derivationIsSilent = derivationRule.Attributes.Contains(DerivationAttribute.Silent);
return With(
allDerivationsTaken: AllDerivationsTaken.Add(derivationRule),
nonSilentDerivationsTaken: !derivationIsSilent ? NonSilentDerivationsTaken.Add(derivationRule) : null,
nonSilentWordFormProgression: !derivationIsSilent ? NonSilentWordFormProgression.Add(derivedWord) : null);
}
public bool IsInvalidDerivation()
{
/*
* Check if any derivation in the sequence follows a sequence of derivations
* that it's not allowed to follow.
*/
for (int i = 0; i < AllDerivationsTaken.Count; i++)
{
var derivation = AllDerivationsTaken[i];
foreach (var forbiddenPredecessorSequence in derivation.CannotFollow)
{
int nextDerivationOffset = 1;
/*
* The forbidden predecessor sequences are expressed in forward-order in derivations.js,
* because they are easier to think about that way. But the conjugation code works in
* reverse order, so we have to consider the forbidden predecessor sequences in reverse
* order also. So start at the back of the sequence.
*/
for (int g = forbiddenPredecessorSequence.Count - 1; g >= 0; --g, ++nextDerivationOffset)
{
var nextDerivation = AllDerivationsTaken.ElementAtOrDefault(i + nextDerivationOffset);
if (nextDerivation == null ||
nextDerivation.ConjugatedWordType != forbiddenPredecessorSequence[g])
{
break; // A forbidden predecessor sequence was matched. Return true.
}
if (g == 0)
{
return true;
}
}
}
}
return false; // No forbidden predecessor sequence was matched.
}
}
} | 45.145161 | 122 | 0.648267 | [
"Apache-2.0"
] | DidacticalEnigma/LibJpConjSharp | LibJpConjSharp/Deconjugation/DerivationSequence.cs | 5,598 | C# |
using JetBrains.Annotations;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
// ReSharper disable CheckNamespace
namespace SourceGeneratorDebugger
{
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
[Resource]
public sealed class SimpleNamespace : Identifiable<int>
{
[Attr]
public string? Value { get; set; }
}
}
| 22.647059 | 59 | 0.74026 | [
"MIT"
] | agentilo/JsonApiDotNetCore | test/SourceGeneratorDebugger/Models/SimpleNamespace.cs | 385 | C# |
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
namespace BookLovers.Base.Infrastructure.Queries
{
public class SqlHelper
{
private readonly List<SqlParameter> _sqlParameters;
internal readonly DbContext Context;
private SqlHelper()
{
}
protected SqlHelper(DbContext context)
{
Context = context;
_sqlParameters = new List<SqlParameter>();
}
public static SqlHelper Initialize(DbContext context) =>
new SqlHelper(context);
public SqlHelper AddParameter(SqlParameter parameter)
{
_sqlParameters.Add(parameter);
return this;
}
internal SqlParameter[] GetParameters() => _sqlParameters.ToArray();
}
} | 24.878788 | 76 | 0.628502 | [
"MIT"
] | kamilk08/BookLoversApi | BookLovers.Base.Infrastructure/Queries/SqlHelper.cs | 823 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mpdn.PlayerExtensions
{
public partial class RemoteControlConfig : RemoteControlConfigBase
{
#region Constructor
public RemoteControlConfig()
{
InitializeComponent();
}
#endregion
#region Protected Methods
protected override void LoadSettings()
{
txbPort.Text = Settings.ConnectionPort.ToString();
}
protected override void SaveSettings()
{
int portNum = Settings.ConnectionPort;
var portString = txbPort.Text;
int.TryParse(portString, out portNum);
Settings.ConnectionPort = portNum;
}
#endregion
#region Private Methods
private void validateTextBox(TextBox txb)
{
int value = 0;
if (!int.TryParse(txb.Text, out value))
{
try
{
int cursorIndex = txb.SelectionStart - 1;
txb.Text = txb.Text.Remove(cursorIndex, 1);
txb.SelectionStart = cursorIndex;
txb.SelectionLength = 0;
}
catch (Exception)
{
}
}
}
private void validatePortNumber()
{
var portString = txbPort.Text;
int port = 0;
int.TryParse(portString, out port);
if(port < 0 || port > 65535)
{
MessageBox.Show("Please enter a port between 1 and 65535", "Invalid Port Number", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txbPort.Text = Settings.ConnectionPort.ToString();
}
}
private void txbPort_KeyUp(object sender, KeyEventArgs e)
{
validateTextBox(txbPort);
validatePortNumber();
}
#endregion
}
public class RemoteControlConfigBase : ScriptConfigDialog<RemoteControlSettings>
{
}
}
| 27.382716 | 144 | 0.554554 | [
"MIT"
] | Shiandow/PlayerExtensions | PlayerExtensions/RemoteControlConfig.cs | 2,220 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RVTR.Account.ObjectModel.Models
{
/// <summary>
/// Represents the _Payment_ model
/// </summary>
[Table("Payments")]
public class PaymentModel : IValidatableObject
{
[ForeignKey("NameModel")]
public int Id { get; set; }
public DateTime CardExpirationDate { get; set; }
public string CardNumber { get; set; }
public string CardName { get; set; }
public int? AccountId { get; set; }
public virtual AccountModel Account { get; set; }
/// <summary>
/// Represents the _Payment_ `Validate` method
/// </summary>
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) => new List<ValidationResult>();
}
}
| 26.46875 | 119 | 0.70366 | [
"MIT"
] | 042020-dotnet-uta-p3/rvtr-api-account | aspnet/RVTR.Account.ObjectModel/Models/PaymentModel.cs | 847 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using OnlineBankingApp.Models;
using Microsoft.AspNetCore.Http;
namespace OnlineBankingApp.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<Customer> _userManager;
private readonly SignInManager<Customer> _signInManager;
private readonly ILogger<LoginModel> _logger;
public const string SessionKeyName = "_email";
public LoginModel(SignInManager<Customer> signInManager,
ILogger<LoginModel> logger,
UserManager<Customer> userManager)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
if (!string.IsNullOrEmpty(returnUrl))
{
if(SplitExist(returnUrl))
{
throw new InvalidOperationException(string.Format("Invalid character in the return url"));
}
}
else
{
returnUrl = Url.Content("~/");
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(returnUrl))
{
if(SplitExist(returnUrl))
{
throw new InvalidOperationException(string.Format("Invalid character in the return url"));
}
}
else
{
returnUrl = Url.Content("~/");
}
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
{
HttpContext.Session.SetString(SessionKeyName, Input.Email);
}
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
private bool SplitExist(string input)
{
foreach (var chr in input)
{
// 0x13 is Carriage Return and 0x10 is Line Feed
if (chr == 0x13 || chr == 0x10)
{
return true;
}
}
return false;
}
}
}
| 33.266234 | 142 | 0.552801 | [
"MIT"
] | JWilh/ASP.NET-Core-Secure-Coding-Cookbook | Chapter12/clickjacking/after/OnlineBankingApp/Areas/Identity/Pages/Account/Login.cshtml.cs | 5,123 | C# |
// This file contains auto-generated code.
namespace System
{
namespace Linq
{
// Generated from `System.Linq.EnumerableExecutor` in `System.Linq.Queryable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public abstract class EnumerableExecutor
{
internal EnumerableExecutor() => throw null;
}
// Generated from `System.Linq.EnumerableExecutor<>` in `System.Linq.Queryable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public class EnumerableExecutor<T> : System.Linq.EnumerableExecutor
{
public EnumerableExecutor(System.Linq.Expressions.Expression expression) => throw null;
}
// Generated from `System.Linq.EnumerableQuery` in `System.Linq.Queryable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public abstract class EnumerableQuery
{
internal EnumerableQuery() => throw null;
}
// Generated from `System.Linq.EnumerableQuery<>` in `System.Linq.Queryable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public class EnumerableQuery<T> : System.Linq.EnumerableQuery, System.Linq.IQueryable<T>, System.Linq.IQueryable, System.Linq.IQueryProvider, System.Linq.IOrderedQueryable<T>, System.Linq.IOrderedQueryable, System.Collections.IEnumerable, System.Collections.Generic.IEnumerable<T>
{
System.Linq.IQueryable<TElement> System.Linq.IQueryProvider.CreateQuery<TElement>(System.Linq.Expressions.Expression expression) => throw null;
System.Linq.IQueryable System.Linq.IQueryProvider.CreateQuery(System.Linq.Expressions.Expression expression) => throw null;
System.Type System.Linq.IQueryable.ElementType { get => throw null; }
public EnumerableQuery(System.Linq.Expressions.Expression expression) => throw null;
public EnumerableQuery(System.Collections.Generic.IEnumerable<T> enumerable) => throw null;
object System.Linq.IQueryProvider.Execute(System.Linq.Expressions.Expression expression) => throw null;
TElement System.Linq.IQueryProvider.Execute<TElement>(System.Linq.Expressions.Expression expression) => throw null;
System.Linq.Expressions.Expression System.Linq.IQueryable.Expression { get => throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null;
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() => throw null;
System.Linq.IQueryProvider System.Linq.IQueryable.Provider { get => throw null; }
public override string ToString() => throw null;
}
// Generated from `System.Linq.Queryable` in `System.Linq.Queryable, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public static class Queryable
{
public static TSource Aggregate<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TSource, TSource>> func) => throw null;
public static TResult Aggregate<TSource, TAccumulate, TResult>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<System.Func<TAccumulate, TSource, TAccumulate>> func, System.Linq.Expressions.Expression<System.Func<TAccumulate, TResult>> selector) => throw null;
public static TAccumulate Aggregate<TSource, TAccumulate>(this System.Linq.IQueryable<TSource> source, TAccumulate seed, System.Linq.Expressions.Expression<System.Func<TAccumulate, TSource, TAccumulate>> func) => throw null;
public static bool All<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static bool Any<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static bool Any<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TSource> Append<TSource>(this System.Linq.IQueryable<TSource> source, TSource element) => throw null;
public static System.Linq.IQueryable<TElement> AsQueryable<TElement>(this System.Collections.Generic.IEnumerable<TElement> source) => throw null;
public static System.Linq.IQueryable AsQueryable(this System.Collections.IEnumerable source) => throw null;
public static float? Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, float?>> selector) => throw null;
public static float? Average(this System.Linq.IQueryable<float?> source) => throw null;
public static float Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, float>> selector) => throw null;
public static float Average(this System.Linq.IQueryable<float> source) => throw null;
public static double? Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int?>> selector) => throw null;
public static double? Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, double?>> selector) => throw null;
public static double? Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Int64?>> selector) => throw null;
public static double? Average(this System.Linq.IQueryable<int?> source) => throw null;
public static double? Average(this System.Linq.IQueryable<double?> source) => throw null;
public static double? Average(this System.Linq.IQueryable<System.Int64?> source) => throw null;
public static double Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int>> selector) => throw null;
public static double Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, double>> selector) => throw null;
public static double Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Int64>> selector) => throw null;
public static double Average(this System.Linq.IQueryable<int> source) => throw null;
public static double Average(this System.Linq.IQueryable<double> source) => throw null;
public static double Average(this System.Linq.IQueryable<System.Int64> source) => throw null;
public static System.Decimal? Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Decimal?>> selector) => throw null;
public static System.Decimal? Average(this System.Linq.IQueryable<System.Decimal?> source) => throw null;
public static System.Decimal Average<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Decimal>> selector) => throw null;
public static System.Decimal Average(this System.Linq.IQueryable<System.Decimal> source) => throw null;
public static System.Linq.IQueryable<TResult> Cast<TResult>(this System.Linq.IQueryable source) => throw null;
public static System.Linq.IQueryable<TSource> Concat<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2) => throw null;
public static bool Contains<TSource>(this System.Linq.IQueryable<TSource> source, TSource item, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static bool Contains<TSource>(this System.Linq.IQueryable<TSource> source, TSource item) => throw null;
public static int Count<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static int Count<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TSource> DefaultIfEmpty<TSource>(this System.Linq.IQueryable<TSource> source, TSource defaultValue) => throw null;
public static System.Linq.IQueryable<TSource> DefaultIfEmpty<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TSource> Distinct<TSource>(this System.Linq.IQueryable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static System.Linq.IQueryable<TSource> Distinct<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TSource ElementAt<TSource>(this System.Linq.IQueryable<TSource> source, int index) => throw null;
public static TSource ElementAtOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, int index) => throw null;
public static System.Linq.IQueryable<TSource> Except<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static System.Linq.IQueryable<TSource> Except<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2) => throw null;
public static TSource First<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource First<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource FirstOrDefault<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TKey, System.Collections.Generic.IEnumerable<TSource>, TResult>> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TKey, System.Collections.Generic.IEnumerable<TSource>, TResult>> resultSelector) => throw null;
public static System.Linq.IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TSource, TElement>> elementSelector, System.Linq.Expressions.Expression<System.Func<TKey, System.Collections.Generic.IEnumerable<TElement>, TResult>> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TSource, TElement>> elementSelector, System.Linq.Expressions.Expression<System.Func<TKey, System.Collections.Generic.IEnumerable<TElement>, TResult>> resultSelector) => throw null;
public static System.Linq.IQueryable<System.Linq.IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<System.Linq.IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector) => throw null;
public static System.Linq.IQueryable<System.Linq.IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TSource, TElement>> elementSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<System.Linq.IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Linq.Expressions.Expression<System.Func<TSource, TElement>> elementSelector) => throw null;
public static System.Linq.IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this System.Linq.IQueryable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult>> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this System.Linq.IQueryable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, System.Collections.Generic.IEnumerable<TInner>, TResult>> resultSelector) => throw null;
public static System.Linq.IQueryable<TSource> Intersect<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static System.Linq.IQueryable<TSource> Intersect<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2) => throw null;
public static System.Linq.IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this System.Linq.IQueryable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> resultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) => throw null;
public static System.Linq.IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this System.Linq.IQueryable<TOuter> outer, System.Collections.Generic.IEnumerable<TInner> inner, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> resultSelector) => throw null;
public static TSource Last<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource Last<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TSource LastOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource LastOrDefault<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Int64 LongCount<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static System.Int64 LongCount<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TSource Max<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TResult Max<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TResult>> selector) => throw null;
public static TSource Min<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TResult Min<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TResult>> selector) => throw null;
public static System.Linq.IQueryable<TResult> OfType<TResult>(this System.Linq.IQueryable source) => throw null;
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null;
public static System.Linq.IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector) => throw null;
public static System.Linq.IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null;
public static System.Linq.IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector) => throw null;
public static System.Linq.IQueryable<TSource> Prepend<TSource>(this System.Linq.IQueryable<TSource> source, TSource element) => throw null;
public static System.Linq.IQueryable<TSource> Reverse<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TResult> Select<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, TResult>> selector) => throw null;
public static System.Linq.IQueryable<TResult> Select<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TResult>> selector) => throw null;
public static System.Linq.IQueryable<TResult> SelectMany<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, System.Collections.Generic.IEnumerable<TResult>>> selector) => throw null;
public static System.Linq.IQueryable<TResult> SelectMany<TSource, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Collections.Generic.IEnumerable<TResult>>> selector) => throw null;
public static System.Linq.IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, System.Collections.Generic.IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<System.Func<TSource, TCollection, TResult>> resultSelector) => throw null;
public static System.Linq.IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Collections.Generic.IEnumerable<TCollection>>> collectionSelector, System.Linq.Expressions.Expression<System.Func<TSource, TCollection, TResult>> resultSelector) => throw null;
public static bool SequenceEqual<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static bool SequenceEqual<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2) => throw null;
public static TSource Single<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource Single<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static TSource SingleOrDefault<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static TSource SingleOrDefault<TSource>(this System.Linq.IQueryable<TSource> source) => throw null;
public static System.Linq.IQueryable<TSource> Skip<TSource>(this System.Linq.IQueryable<TSource> source, int count) => throw null;
public static System.Linq.IQueryable<TSource> SkipLast<TSource>(this System.Linq.IQueryable<TSource> source, int count) => throw null;
public static System.Linq.IQueryable<TSource> SkipWhile<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, bool>> predicate) => throw null;
public static System.Linq.IQueryable<TSource> SkipWhile<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static int? Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int?>> selector) => throw null;
public static int? Sum(this System.Linq.IQueryable<int?> source) => throw null;
public static int Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int>> selector) => throw null;
public static int Sum(this System.Linq.IQueryable<int> source) => throw null;
public static float? Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, float?>> selector) => throw null;
public static float? Sum(this System.Linq.IQueryable<float?> source) => throw null;
public static float Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, float>> selector) => throw null;
public static float Sum(this System.Linq.IQueryable<float> source) => throw null;
public static double? Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, double?>> selector) => throw null;
public static double? Sum(this System.Linq.IQueryable<double?> source) => throw null;
public static double Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, double>> selector) => throw null;
public static double Sum(this System.Linq.IQueryable<double> source) => throw null;
public static System.Int64? Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Int64?>> selector) => throw null;
public static System.Int64? Sum(this System.Linq.IQueryable<System.Int64?> source) => throw null;
public static System.Int64 Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Int64>> selector) => throw null;
public static System.Int64 Sum(this System.Linq.IQueryable<System.Int64> source) => throw null;
public static System.Decimal? Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Decimal?>> selector) => throw null;
public static System.Decimal? Sum(this System.Linq.IQueryable<System.Decimal?> source) => throw null;
public static System.Decimal Sum<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, System.Decimal>> selector) => throw null;
public static System.Decimal Sum(this System.Linq.IQueryable<System.Decimal> source) => throw null;
public static System.Linq.IQueryable<TSource> Take<TSource>(this System.Linq.IQueryable<TSource> source, int count) => throw null;
public static System.Linq.IQueryable<TSource> TakeLast<TSource>(this System.Linq.IQueryable<TSource> source, int count) => throw null;
public static System.Linq.IQueryable<TSource> TakeWhile<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, bool>> predicate) => throw null;
public static System.Linq.IQueryable<TSource> TakeWhile<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static System.Linq.IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null;
public static System.Linq.IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector) => throw null;
public static System.Linq.IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector, System.Collections.Generic.IComparer<TKey> comparer) => throw null;
public static System.Linq.IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this System.Linq.IOrderedQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, TKey>> keySelector) => throw null;
public static System.Linq.IQueryable<TSource> Union<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2, System.Collections.Generic.IEqualityComparer<TSource> comparer) => throw null;
public static System.Linq.IQueryable<TSource> Union<TSource>(this System.Linq.IQueryable<TSource> source1, System.Collections.Generic.IEnumerable<TSource> source2) => throw null;
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, int, bool>> predicate) => throw null;
public static System.Linq.IQueryable<TSource> Where<TSource>(this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<System.Func<TSource, bool>> predicate) => throw null;
public static System.Linq.IQueryable<TResult> Zip<TFirst, TSecond, TResult>(this System.Linq.IQueryable<TFirst> source1, System.Collections.Generic.IEnumerable<TSecond> source2, System.Linq.Expressions.Expression<System.Func<TFirst, TSecond, TResult>> resultSelector) => throw null;
public static System.Linq.IQueryable<(TFirst, TSecond)> Zip<TFirst, TSecond>(this System.Linq.IQueryable<TFirst> source1, System.Collections.Generic.IEnumerable<TSecond> source2) => throw null;
}
}
}
| 160.118644 | 560 | 0.758795 | [
"MIT"
] | Bhagyanekraje/codeql | csharp/ql/test/resources/stubs/_frameworks/Microsoft.NETCore.App/System.Linq.Queryable.cs | 28,341 | C# |
using System;
using System.Collections.Generic;
namespace AspNetCoreOData.Service.Database
{
public partial class WorkOrderRouting
{
public int WorkOrderId { get; set; }
public int ProductId { get; set; }
public short OperationSequence { get; set; }
public short LocationId { get; set; }
public DateTime ScheduledStartDate { get; set; }
public DateTime ScheduledEndDate { get; set; }
public DateTime? ActualStartDate { get; set; }
public DateTime? ActualEndDate { get; set; }
public decimal? ActualResourceHrs { get; set; }
public decimal PlannedCost { get; set; }
public decimal? ActualCost { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual Location Location { get; set; }
public virtual WorkOrder WorkOrder { get; set; }
}
}
| 36 | 57 | 0.627778 | [
"MIT"
] | CloudBloq/AspNetCoreOData | AspNetCoreOData.Client/Database/WorkOrderRouting.cs | 902 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void BitwiseClear_Vector128_Byte()
{
var test = new SimpleBinaryOpTest__BitwiseClear_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__BitwiseClear_Vector128_Byte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if (
(alignment != 16 && alignment != 8)
|| (alignment * 2) < sizeOfinArray1
|| (alignment * 2) < sizeOfinArray2
|| (alignment * 2) < sizeOfoutArray
)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray1Ptr),
ref Unsafe.As<Byte, byte>(ref inArray1[0]),
(uint)sizeOfinArray1
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray2Ptr),
ref Unsafe.As<Byte, byte>(ref inArray2[0]),
(uint)sizeOfinArray2
);
}
public void* inArray1Ptr =>
Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr =>
Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr =>
Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1),
ref Unsafe.As<Byte, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2),
ref Unsafe.As<Byte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
return testStruct;
}
public void RunStructFldScenario(
SimpleBinaryOpTest__BitwiseClear_Vector128_Byte testClass
)
{
var result = AdvSimd.BitwiseClear(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(
SimpleBinaryOpTest__BitwiseClear_Vector128_Byte testClass
)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount =
Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount =
Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount =
Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__BitwiseClear_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1),
ref Unsafe.As<Byte, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2),
ref Unsafe.As<Byte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
}
public SimpleBinaryOpTest__BitwiseClear_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1),
ref Unsafe.As<Byte, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetByte();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2),
ref Unsafe.As<Byte, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetByte();
}
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetByte();
}
_dataTable = new DataTable(
_data1,
_data2,
new Byte[RetElementCount],
LargestVectorSize
);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.BitwiseClear(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.BitwiseClear),
new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }
)
.Invoke(
null,
new object[]
{
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.BitwiseClear),
new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }
)
.Invoke(
null,
new object[]
{
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.BitwiseClear(_clsVar1, _clsVar2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(pClsVar1)),
AdvSimd.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = AdvSimd.BitwiseClear(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = AdvSimd.BitwiseClear(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__BitwiseClear_Vector128_Byte();
var result = AdvSimd.BitwiseClear(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__BitwiseClear_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.BitwiseClear(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(pFld1)),
AdvSimd.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.BitwiseClear(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.BitwiseClear(
AdvSimd.LoadVector128((Byte*)(&test._fld1)),
AdvSimd.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(
Vector128<Byte> op1,
Vector128<Byte> op2,
void* result,
[CallerMemberName] string method = ""
)
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Byte, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
void* op1,
void* op2,
void* result,
[CallerMemberName] string method = ""
)
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Byte, byte>(ref inArray1[0]),
ref Unsafe.AsRef<byte>(op1),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Byte, byte>(ref inArray2[0]),
ref Unsafe.AsRef<byte>(op2),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Byte, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Byte>>()
);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(
Byte[] left,
Byte[] right,
Byte[] result,
[CallerMemberName] string method = ""
)
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.BitwiseClear(left[i], right[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation(
$"{nameof(AdvSimd)}.{nameof(AdvSimd.BitwiseClear)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"
);
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation(
$" result: ({string.Join(", ", result)})"
);
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 36.762997 | 129 | 0.538244 | [
"MIT"
] | belav/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/BitwiseClear.Vector128.Byte.cs | 24,043 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[System.Serializable]
public struct AI_condition {
public string condName;
public bool condTrue;
public int condNum;
public enum COND_TYPE {
VAR_EQ,
VAR_GR,
VAR_GR_EQ,
VAR_LESS_EQ,
VAR_LESS,
CHECK_IF_CHAR_EXIST_PARTY,
CHECK_IF_CHAR_EXIST_OPP
}
//For setting the target if the condition is true
public bool setTarget;
public string targName;
public COND_TYPE conditionType;
}
/*
[System.Serializable]
public class o_BattleCharAI
{
public AI_condition[] conditions;
public AI_condition[] effectConditions;
public AI_condition[] effects;
//Condition | Effect
public bool MatchActionsCond(bool flag, string flName)
{
bool boolean = false;
if (conditions.Length > 0)
{
foreach (var condition in conditions)
{
if (condition.condName == flName
&& condition.condTrue == flag)
{
boolean = true;
break;
}
}
}
else
{
boolean = true;
}
return boolean;
}
//The requirements that are needed to get this to trigger the effect
public bool MatchActionsEffectCond(bool flag, string flName)
{
bool boolean = false;
if (conditions.Length > 0)
{
foreach (var condition in effectConditions)
{
if (condition.condName == flName
&& condition.condTrue == flag)
{
boolean = true;
break;
}
}
}
else
{
boolean = true;
}
return boolean;
}
public bool MatchActionsEffect(AI_condition cond) {
bool boolean = false;
foreach (var condition in effects) {
if (condition.condName == cond.condName
&& condition.condTrue == cond.condTrue) {
boolean = true;
break;
}
}
return boolean;
}
public enum ACTION {
ATTACK,
SUPPORT,
NOTHING,
SPECIFIC
}
public d_move move;
public ACTION action;
}
*/
[System.Serializable]
public class o_BattleCharAI
{
public AI_condition[] conditions;
public enum TARG_MOVE {
ON_PARTY,
NOT_PARTY,
SPECIFIC
}
public d_move move;
}
| 23.903509 | 73 | 0.509725 | [
"MIT"
] | PixelBrownieSoftware/Please-don-t-hurt-each-other- | Assets/src/BattleSystem/Objects/o_BattleCharAI.cs | 2,725 | C# |
namespace Shooting2D
{
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(Rigidbody2D))]
internal sealed class ShootingPlayer : NetworkBehaviour
{
private new Camera camera;
private Rigidbody2D rb;
[SerializeField]
private Bullet bulletPrefab;
[SerializeField]
private Transform bulletSpawn;
[SerializeField]
private Healthbar healthbar;
[SerializeField]
private float speed = 1f, maxHealth = 100f;
[SyncVar(hook = "OnHealthChanged")]
private float health;
private float Health
{
get { return this.health; }
set { this.health = Mathf.Clamp(value, 0f, this.maxHealth); }
}
private void Awake()
{
this.camera = Camera.main;
this.rb = this.GetComponent<Rigidbody2D>();
}
[ServerCallback]
private void OnEnable()
{
this.health = this.maxHealth;
}
[ServerCallback]
private void OnDisable()
{
this.health = 0f;
}
private void Start()
{
Debug.Log(this.health);
this.UpdateHealthbar(this.health);
}
private void Update()
{
if (this.isLocalPlayer)
{
if (Input.GetButtonDown("Fire1"))
{
this.CmdShoot();
}
}
}
private void FixedUpdate()
{
if (this.isLocalPlayer)
{
var input = new Vector2(
Input.GetAxis("Horizontal"),
Input.GetAxis("Vertical"));
this.rb.AddForce(input * this.speed);
var screenPos = this.camera.WorldToScreenPoint(this.rb.position);
var mousePos = Input.mousePosition;
var lookDirection = (mousePos - screenPos).normalized;
this.rb.rotation = RotationHelper.DirectionToPhysicsRotation(lookDirection);
}
}
[Server]
public void Damage(float damage)
{
this.Health -= damage;
}
[Command]
private void CmdShoot()
{
var bullet = ShootingPlayer.Instantiate(this.bulletPrefab);
bullet.Initialize(this.bulletSpawn.position, this.transform.rotation);
NetworkServer.Spawn(bullet.gameObject);
}
private void OnHealthChanged(float health)
{
this.UpdateHealthbar(health);
}
private void UpdateHealthbar(float health)
{
this.healthbar.FillAmount = health / this.maxHealth;
}
}
} | 25.376147 | 92 | 0.528923 | [
"MIT"
] | mwnDK1402/unet | UNet/Assets/Shooting 2D/ShootingPlayer.cs | 2,768 | C# |
using System;
using System.Collections.Concurrent;
using System.IO.Pipelines;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CondenserDotNet.Core;
using CondenserDotNet.Server;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using CondenserDotNet.Server.DataContracts;
namespace CondenserDotNet.Middleware.Pipelines
{
public class ServiceWithCustomClient : IConsulService, IDisposable
{
private readonly System.Threading.CountdownEvent _waitUntilRequestsAreFinished = new System.Threading.CountdownEvent(1);
private string _address;
private int _port;
private byte[] _hostHeader;
private ICurrentState _stats;
private IPEndPoint _ipEndPoint;
private Version[] _supportedVersions;
private string[] _tags;
private string _serviceId;
private readonly ILogger _logger;
private int _calls;
private long _totalRequestTime;
private readonly ConcurrentQueue<IPipeConnection> _pooledConnections = new ConcurrentQueue<IPipeConnection>();
private readonly PipeFactory _factory;
private readonly RoutingData _routingData;
public ServiceWithCustomClient(ILoggerFactory loggingFactory, PipeFactory factory, RoutingData routingData)
{
_routingData = routingData;
_logger = loggingFactory?.CreateLogger<ServiceWithCustomClient>();
_pooledConnections = new ConcurrentQueue<IPipeConnection>();
_factory = factory;
}
public Version[] SupportedVersions => _supportedVersions;
public string[] Tags => _tags;
public string[] Routes { get; private set; }
public string ServiceId => _serviceId;
public string NodeId { get; private set; }
public int Calls => _calls;
public double TotalRequestTime => _totalRequestTime;
public IPEndPoint IpEndPoint => _ipEndPoint;
public async Task CallService(HttpContext context)
{
System.Threading.Interlocked.Increment(ref _calls);
var sw = Stopwatch.StartNew();
try
{
if (!_pooledConnections.TryDequeue(out IPipeConnection socket))
{
socket = await System.IO.Pipelines.Networking.Sockets.SocketConnection.ConnectAsync(IpEndPoint);
_logger?.LogInformation("Created new socket");
}
else
{
_logger?.LogInformation("Got a connection from the pool, current pool size {poolSize}", _pooledConnections.Count);
}
await socket.WriteHeadersAsync(context, _hostHeader);
await socket.WriteBodyAsync(context);
await socket.ReceiveHeaderAsync(context);
await socket.ReceiveBodyAsync(context, _logger);
_pooledConnections.Enqueue(socket);
}
catch
{
throw new NotImplementedException();
}
sw.Stop();
System.Threading.Interlocked.Add(ref _totalRequestTime, sw.ElapsedMilliseconds);
}
public override int GetHashCode() => ServiceId.GetHashCode();
public override bool Equals(object obj)
{
if (obj is ServiceWithCustomClient otherService)
{
if (otherService.ServiceId != ServiceId)
{
return false;
}
if (!Tags.SequenceEqual(otherService.Tags))
{
return false;
}
return true;
}
return false;
}
public void UpdateRoutes(string[] routes) => Routes = routes;
public async Task Initialise(string serviceId, string nodeId, string[] tags, string address, int port)
{
_stats = _routingData.GetStats(serviceId);
_stats.ResetUptime();
_address = address;
_port = port;
_tags = tags;
Routes = ServiceUtils.RoutesFromTags(tags);
_serviceId = serviceId;
NodeId = nodeId;
_hostHeader = Encoding.UTF8.GetBytes($"Host: {_address}:{_port}\r\n");
try
{
var result = await Dns.GetHostAddressesAsync(address);
_ipEndPoint = new IPEndPoint(result[0], port);
}
catch
{
_logger.LogError("Unable to get an ip address for {serverAddress}", address);
}
_supportedVersions = tags.Where(t => t.StartsWith("version=")).Select(t => new Version(t.Substring(8))).ToArray();
}
public void Dispose()
{
_waitUntilRequestsAreFinished.Signal();
_waitUntilRequestsAreFinished.Wait(5000);
_waitUntilRequestsAreFinished.Dispose();
}
public StatsSummary GetSummary() => _stats.GetSummary();
}
}
| 37.844444 | 134 | 0.604032 | [
"MIT"
] | geffzhang/CondenserDotNet | src/CondenserDotNet.Middleware.Pipelines/ServiceWithCustomClient.cs | 5,111 | 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.Purview.V20201201Preview.Inputs
{
/// <summary>
/// A private endpoint class.
/// </summary>
public sealed class PrivateEndpointArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The private endpoint identifier.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
public PrivateEndpointArgs()
{
}
}
}
| 25.206897 | 81 | 0.640219 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Purview/V20201201Preview/Inputs/PrivateEndpointArgs.cs | 731 | C# |
namespace RemoteDesktop
{
partial class ClientWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ClientWindow));
this.SuspendLayout();
//
// ClientWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.ClientSize = new System.Drawing.Size(796, 467);
this.DoubleBuffered = true;
this.Name = "ClientWindow";
this.Text = "ClientWindow";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ClientWindow_FormClosing);
this.ResizeEnd += new System.EventHandler(this.ClientWindow_ResizeEnd);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ClientWindow_KeyDown_1);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ClientWindow_MouseDown);
this.ResumeLayout(false);
}
#endregion
}
} | 36.381818 | 135 | 0.664168 | [
"MIT"
] | McMaartenz/RemoteDesktop | Windows/ClientWindow.Designer.cs | 2,003 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Search.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// Response from a List Indexes request. If successful, it includes the
/// full definitions of all indexes.
/// </summary>
public partial class IndexListResult
{
/// <summary>
/// Initializes a new instance of the IndexListResult class.
/// </summary>
public IndexListResult() { }
/// <summary>
/// Initializes a new instance of the IndexListResult class.
/// </summary>
public IndexListResult(IList<Index> indexes = default(IList<Index>))
{
Indexes = indexes;
}
/// <summary>
/// Gets the indexes in the Search service.
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<Index> Indexes { get; private set; }
}
}
| 29.73913 | 76 | 0.637427 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/Search/DataPlane/Microsoft.Azure.Search/GeneratedSearchService/Models/IndexListResult.cs | 1,368 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Internal;
namespace MQTTnet.Tests.Internal
{
[TestClass]
public class BlockingQueue_Tests
{
[TestMethod]
public void Preserve_Order()
{
var queue = new BlockingQueue<string>();
queue.Enqueue("a");
queue.Enqueue("b");
queue.Enqueue("c");
Assert.AreEqual(3, queue.Count);
Assert.AreEqual("a", queue.Dequeue());
Assert.AreEqual("b", queue.Dequeue());
Assert.AreEqual("c", queue.Dequeue());
}
[TestMethod]
public void Remove_First_Items()
{
var queue = new BlockingQueue<string>();
queue.Enqueue("a");
queue.Enqueue("b");
queue.Enqueue("c");
Assert.AreEqual("a", queue.RemoveFirst());
Assert.AreEqual("b", queue.RemoveFirst());
Assert.AreEqual(1, queue.Count);
Assert.AreEqual("c", queue.Dequeue());
}
[TestMethod]
public void Clear_Items()
{
var queue = new BlockingQueue<string>();
queue.Enqueue("a");
queue.Enqueue("b");
queue.Enqueue("c");
Assert.AreEqual(3, queue.Count);
queue.Clear();
Assert.AreEqual(0, queue.Count);
}
[TestMethod]
public async Task Wait_For_Item()
{
var queue = new BlockingQueue<string>();
string item = null;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(() =>
{
item = queue.Dequeue();
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
await Task.Delay(100);
Assert.AreEqual(0, queue.Count);
Assert.AreEqual(null, item);
queue.Enqueue("x");
await Task.Delay(100);
Assert.AreEqual("x", item);
Assert.AreEqual(0, queue.Count);
}
[TestMethod]
public void Wait_For_Items()
{
var number = 0;
var queue = new BlockingQueue<int>();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(async () =>
{
while (true)
{
queue.Enqueue(1);
await Task.Delay(100);
}
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
while (number < 50)
{
queue.Dequeue();
Interlocked.Increment(ref number);
}
}
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public void Use_Disposed_Queue()
{
var queue = new BlockingQueue<int>();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(() =>
{
Thread.Sleep(1000);
queue.Dispose();
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
queue.Dequeue(new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token);
}
}
} | 30.744186 | 138 | 0.565809 | [
"MIT"
] | 76541727/MQTTnet | Source/MQTTnet.Tests/Internal/BlockingQueue_Tests.cs | 3,966 | C# |
namespace SampleProject.Domain.ForeignExchange
{
using SharedKernel;
public class ConversionRate
{
public ConversionRate(string sourceCurrency, string targetCurrency, decimal factor)
{
SourceCurrency = sourceCurrency;
TargetCurrency = targetCurrency;
Factor = factor;
}
public string SourceCurrency { get; }
public string TargetCurrency { get; }
public decimal Factor { get; }
internal MoneyValue Convert(MoneyValue value)
{
return Factor * value;
}
}
} | 23.8 | 91 | 0.610084 | [
"MIT"
] | gabrielesteveslima/net-public-sample-dotnet-core-cqrs-api | src/SampleProject.Domain/ForeignExchange/ConversionRate.cs | 597 | 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class ParenthesizedExpressionSyntaxExtensions
{
public static bool CanRemoveParentheses(this ParenthesizedExpressionSyntax node)
{
var expression = node.Expression;
var parentExpression = node.Parent as ExpressionSyntax;
// Simplest cases:
// ((x)) -> (x)
if (expression.IsKind(SyntaxKind.ParenthesizedExpression) ||
parentExpression.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// (x); -> x;
if (node.IsParentKind(SyntaxKind.ExpressionStatement))
{
return true;
}
// Don't change (x?.Count).GetValueOrDefault() to x?.Count.GetValueOrDefault()
if (expression.IsKind(SyntaxKind.ConditionalAccessExpression) && parentExpression is MemberAccessExpressionSyntax)
{
return false;
}
// Easy statement-level cases:
// var y = (x); -> var y = x;
// var (y, z) = (x); -> var (y, z) = x;
// if ((x)) -> if (x)
// return (x); -> return x;
// yield return (x); -> yield return x;
// throw (x); -> throw x;
// switch ((x)) -> switch (x)
// while ((x)) -> while (x)
// do { } while ((x)) -> do { } while (x)
// for(;(x);) -> for(;x;)
// foreach (var y in (x)) -> foreach (var y in x)
// lock ((x)) -> lock (x)
// using ((x)) -> using (x)
// catch when ((x)) -> catch when (x)
if ((node.IsParentKind(SyntaxKind.EqualsValueClause) && ((EqualsValueClauseSyntax)node.Parent).Value == node) ||
(node.IsParentKind(SyntaxKind.VariableComponentAssignment) && ((VariableComponentAssignmentSyntax)node.Parent).Value == node) ||
(node.IsParentKind(SyntaxKind.IfStatement) && ((IfStatementSyntax)node.Parent).Condition == node) ||
(node.IsParentKind(SyntaxKind.ReturnStatement) && ((ReturnStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.YieldReturnStatement) && ((YieldStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.ThrowStatement) && ((ThrowStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.SwitchStatement) && ((SwitchStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.WhileStatement) && ((WhileStatementSyntax)node.Parent).Condition == node) ||
(node.IsParentKind(SyntaxKind.DoStatement) && ((DoStatementSyntax)node.Parent).Condition == node) ||
(node.IsParentKind(SyntaxKind.ForStatement) && ((ForStatementSyntax)node.Parent).Condition == node) ||
(node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachComponentStatement) && ((CommonForEachStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.LockStatement) && ((LockStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.UsingStatement) && ((UsingStatementSyntax)node.Parent).Expression == node) ||
(node.IsParentKind(SyntaxKind.CatchFilterClause) && ((CatchFilterClauseSyntax)node.Parent).FilterExpression == node))
{
return true;
}
// Handle expression-level ambiguities
if (RemovalMayIntroduceCastAmbiguity(node) ||
RemovalMayIntroduceCommaListAmbiguity(node) ||
RemovalMayIntroduceInterpolationAmbiguity(node))
{
return false;
}
// Cases:
// (C)(this) -> (C)this
if (node.IsParentKind(SyntaxKind.CastExpression) && expression.IsKind(SyntaxKind.ThisExpression))
{
return true;
}
// Cases:
// y((x)) -> y(x)
if (node.IsParentKind(SyntaxKind.Argument) && ((ArgumentSyntax)node.Parent).Expression == node)
{
return true;
}
// Cases:
// $"{(x)}" -> $"{x}"
if (node.IsParentKind(SyntaxKind.Interpolation))
{
return true;
}
// Cases:
// ($"{x}") -> $"{x}"
if (expression.IsKind(SyntaxKind.InterpolatedStringExpression))
{
return true;
}
// Cases:
// {(x)} -> {x}
if (node.Parent is InitializerExpressionSyntax)
{
// Assignment expressions are not allowed in initializers
if (expression.IsAnyAssignExpression())
{
return false;
}
return true;
}
// Cases:
// where (x + 1 > 14) -> where x + 1 > 14
if (node.Parent is QueryClauseSyntax)
{
return true;
}
// Cases:
// (x) -> x
// (x.y) -> x.y
if (IsSimpleOrDottedName(expression))
{
return true;
}
// Cases:
// ('') -> ''
// ("") -> ""
// (false) -> false
// (true) -> true
// (null) -> null
// (1) -> 1
if (expression.IsAnyLiteralExpression())
{
return true;
}
// x ?? (throw ...) -> x ?? throw ...
if (expression.IsKind(SyntaxKind.ThrowExpression) &&
node.IsParentKind(SyntaxKind.CoalesceExpression) &&
((BinaryExpressionSyntax)node.Parent).Right == node)
{
return true;
}
// Operator precedence cases:
// - If the parent is not an expression, do not remove parentheses
// - Otherwise, parentheses may be removed if doing so does not change operator associations.
return parentExpression != null
? !RemovalChangesAssociation(node, expression, parentExpression)
: false;
}
private static readonly ObjectPool<Stack<SyntaxNode>> s_nodeStackPool = new ObjectPool<Stack<SyntaxNode>>(() => new Stack<SyntaxNode>());
private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node)
{
// First, find the parenting interpolation. If we find a parenthesize expression first,
// we can bail out early.
InterpolationSyntax interpolation = null;
foreach (var ancestor in node.Parent.AncestorsAndSelf())
{
switch (ancestor.Kind())
{
case SyntaxKind.ParenthesizedExpression:
return false;
case SyntaxKind.Interpolation:
interpolation = (InterpolationSyntax)ancestor;
break;
}
}
if (interpolation == null)
{
return false;
}
// In order determine whether removing this parenthesized expression will introduce a
// parsing ambiguity, we must dig into the child tokens and nodes to determine whether
// they include any : or :: tokens. If they do, we can't remove the parentheses because
// the parser would assume that the first : would begin the format clause of the interpolation.
var stack = s_nodeStackPool.AllocateAndClear();
try
{
stack.Push(node.Expression);
while (stack.Count > 0)
{
var expression = stack.Pop();
foreach (var nodeOrToken in expression.ChildNodesAndTokens())
{
// Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous.
if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression))
{
stack.Push(nodeOrToken.AsNode());
}
else if (nodeOrToken.IsToken)
{
if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken))
{
return true;
}
}
}
}
}
finally
{
s_nodeStackPool.ClearAndFree(stack);
}
return false;
}
private static bool RemovalChangesAssociation(ParenthesizedExpressionSyntax node, ExpressionSyntax expression, ExpressionSyntax parentExpression)
{
var precedence = expression.GetOperatorPrecedence();
var parentPrecedence = parentExpression.GetOperatorPrecedence();
if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None)
{
// Be conservative if the expression or its parent has no precedence.
return true;
}
if (precedence > parentPrecedence)
{
// Association never changes if the expression's precedence is higher than its parent.
return false;
}
else if (precedence < parentPrecedence)
{
// Association always changes if the expression's precedence is lower that its parent.
return true;
}
else if (precedence == parentPrecedence)
{
// If the expression's precedence is the same as its parent, and both are binary expressions,
// check for associativity and commutability.
if (!(expression is BinaryExpressionSyntax || expression is AssignmentExpressionSyntax))
{
// If the expression is not a binary expression, association never changes.
return false;
}
var parentBinaryExpression = parentExpression as BinaryExpressionSyntax;
if (parentBinaryExpression != null)
{
// If both the expression and its parent are binary expressions and their kinds
// are the same, check to see if they are commutative (e.g. + or *).
if (parentBinaryExpression.IsKind(SyntaxKind.AddExpression, SyntaxKind.MultiplyExpression) &&
node.Expression.Kind() == parentBinaryExpression.Kind())
{
return false;
}
// Null-coalescing is right associative; removing parens from the LHS changes the association.
if (parentExpression.IsKind(SyntaxKind.CoalesceExpression))
{
return parentBinaryExpression.Left == node;
}
// All other binary operators are left associative; removing parens from the RHS changes the association.
return parentBinaryExpression.Right == node;
}
var parentAssignmentExpression = parentExpression as AssignmentExpressionSyntax;
if (parentAssignmentExpression != null)
{
// Assignment expressions are right associative; removing parens from the LHS changes the association.
return parentAssignmentExpression.Left == node;
}
// If the parent is not a binary expression, association never changes.
return false;
}
throw ExceptionUtilities.Unreachable;
}
private static bool RemovalMayIntroduceCastAmbiguity(ParenthesizedExpressionSyntax node)
{
// Be careful not to break the special case around (x)(-y)
// as defined in section 7.7.6 of the C# language specification.
if (node.IsParentKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)node.Parent;
if (castExpression.Type is PredefinedTypeSyntax)
{
return false;
}
var expression = node.Expression;
if (expression.IsKind(SyntaxKind.UnaryMinusExpression))
{
return true;
}
if (expression.IsKind(SyntaxKind.NumericLiteralExpression))
{
var numericLiteral = (LiteralExpressionSyntax)expression;
if (numericLiteral.Token.ValueText.StartsWith("-", StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
private static bool RemovalMayIntroduceCommaListAmbiguity(ParenthesizedExpressionSyntax node)
{
if (IsSimpleOrDottedName(node.Expression))
{
// We can't remove parentheses from an identifier name in the following cases:
// F((x) < x, x > (1 + 2))
// F(x < (x), x > (1 + 2))
// F(x < x, (x) > (1 + 2))
// {(x) < x, x > (1 + 2)}
// {x < (x), x > (1 + 2)}
// {x < x, (x) > (1 + 2)}
var binaryExpression = node.Parent as BinaryExpressionSyntax;
if (binaryExpression != null &&
binaryExpression.IsKind(SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression) &&
(binaryExpression.IsParentKind(SyntaxKind.Argument) || binaryExpression.Parent is InitializerExpressionSyntax))
{
if (binaryExpression.IsKind(SyntaxKind.LessThanExpression))
{
if ((binaryExpression.Left == node && IsSimpleOrDottedName(binaryExpression.Right)) ||
(binaryExpression.Right == node && IsSimpleOrDottedName(binaryExpression.Left)))
{
if (IsNextExpressionPotentiallyAmbiguous(binaryExpression))
{
return true;
}
}
return false;
}
else if (binaryExpression.IsKind(SyntaxKind.GreaterThanExpression))
{
if (binaryExpression.Left == node &&
binaryExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.CastExpression))
{
if (IsPreviousExpressionPotentiallyAmbiguous(binaryExpression))
{
return true;
}
}
return false;
}
}
}
else if (node.Expression.IsKind(SyntaxKind.LessThanExpression))
{
// We can't remove parentheses from a less-than expression in the following cases:
// F((x < x), x > (1 + 2))
// {(x < x), x > (1 + 2)}
var lessThanExpression = (BinaryExpressionSyntax)node.Expression;
if (IsNextExpressionPotentiallyAmbiguous(node))
{
return true;
}
return false;
}
else if (node.Expression.IsKind(SyntaxKind.GreaterThanExpression))
{
// We can't remove parentheses from a greater-than expression in the following cases:
// F(x < x, (x > (1 + 2)))
// {x < x, (x > (1 + 2))}
var greaterThanExpression = (BinaryExpressionSyntax)node.Expression;
if (IsPreviousExpressionPotentiallyAmbiguous(node))
{
return true;
}
return false;
}
return false;
}
private static bool IsPreviousExpressionPotentiallyAmbiguous(ExpressionSyntax node)
{
ExpressionSyntax previousExpression = null;
if (node.IsParentKind(SyntaxKind.Argument))
{
var argument = (ArgumentSyntax)node.Parent;
var argumentList = argument.Parent as ArgumentListSyntax;
if (argumentList != null)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex > 0)
{
previousExpression = argumentList.Arguments[argumentIndex - 1].Expression;
}
}
}
else if (node.Parent is InitializerExpressionSyntax)
{
var initializer = (InitializerExpressionSyntax)node.Parent;
var expressionIndex = initializer.Expressions.IndexOf(node);
if (expressionIndex > 0)
{
previousExpression = initializer.Expressions[expressionIndex - 1];
}
}
if (previousExpression == null ||
!previousExpression.IsKind(SyntaxKind.LessThanExpression))
{
return false;
}
var lessThanExpression = (BinaryExpressionSyntax)previousExpression;
return (IsSimpleOrDottedName(lessThanExpression.Left)
|| lessThanExpression.Left.IsKind(SyntaxKind.CastExpression))
&& IsSimpleOrDottedName(lessThanExpression.Right);
}
private static bool IsNextExpressionPotentiallyAmbiguous(ExpressionSyntax node)
{
ExpressionSyntax nextExpression = null;
if (node.IsParentKind(SyntaxKind.Argument))
{
var argument = (ArgumentSyntax)node.Parent;
var argumentList = argument.Parent as ArgumentListSyntax;
if (argumentList != null)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex >= 0 && argumentIndex < argumentList.Arguments.Count - 1)
{
nextExpression = argumentList.Arguments[argumentIndex + 1].Expression;
}
}
}
else if (node.Parent is InitializerExpressionSyntax)
{
var initializer = (InitializerExpressionSyntax)node.Parent;
var expressionIndex = initializer.Expressions.IndexOf(node);
if (expressionIndex >= 0 && expressionIndex < initializer.Expressions.Count - 1)
{
nextExpression = initializer.Expressions[expressionIndex + 1];
}
}
if (nextExpression == null ||
!nextExpression.IsKind(SyntaxKind.GreaterThanExpression))
{
return false;
}
var greaterThanExpression = (BinaryExpressionSyntax)nextExpression;
return IsSimpleOrDottedName(greaterThanExpression.Left)
&& (greaterThanExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression)
|| greaterThanExpression.Right.IsKind(SyntaxKind.CastExpression));
}
private static bool IsSimpleOrDottedName(ExpressionSyntax expression)
{
return expression.IsKind(
SyntaxKind.IdentifierName,
SyntaxKind.QualifiedName,
SyntaxKind.SimpleMemberAccessExpression);
}
}
}
| 42.506122 | 171 | 0.519781 | [
"Apache-2.0"
] | jbevain/roslyn | src/Workspaces/CSharp/Portable/Extensions/ParenthesizedExpressionSyntaxExtensions.cs | 20,830 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace LightGive
{
[CustomEditor(typeof(LocalizeText))]
[CanEditMultipleObjects]
public class LocalizeTextEditor : Editor
{
private SerializedProperty m_propTextList;
private SerializedProperty m_propFontSizeList;
private SerializedProperty m_propRectSizeList;
private SerializedProperty m_propIsChangeRectSize;
private SerializedProperty m_propIsChangeFontSize;
private void OnEnable()
{
m_propTextList = serializedObject.FindProperty("m_textList");
m_propFontSizeList = serializedObject.FindProperty("m_fontSizeList");
m_propRectSizeList = serializedObject.FindProperty("m_rectSizeList");
m_propIsChangeRectSize = serializedObject.FindProperty("m_isChangeRectSize");
m_propIsChangeFontSize = serializedObject.FindProperty("m_isChangeFontSize");
}
public override void OnInspectorGUI()
{
base.DrawDefaultInspector();
//serializedObject.Update();
//LocalizeText localizeText = target as LocalizeText;
//EditorGUILayout.Space();
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("ChangeFontSize", GUILayout.Width(100));
//m_propIsChangeFontSize.boolValue = GUILayout.Toolbar(
// (m_propIsChangeFontSize.boolValue ? 1 : 0), new string[] { "Off", "On" }) == 1;
//EditorGUILayout.EndHorizontal();
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("ChangeRectSize", GUILayout.Width(100));
//m_propIsChangeRectSize.boolValue = GUILayout.Toolbar(
// (m_propIsChangeRectSize.boolValue ? 1 : 0), new string[] { "Off", "On" }) == 1;
//EditorGUILayout.EndHorizontal();
//SerializedProperty arraySizeProp = m_propTextList.FindPropertyRelative("Array.size");
//EditorGUILayout.Space();
//List<SystemLanguage> languageList = LocalizeSystem.GetCorrespondenceLanguageList();
//for (int i = 0; i < arraySizeProp.intValue; i++)
//{
// for (int j = 0; j < languageList.Count; j++)
// {
// string labelText = ((SystemLanguage)i).ToString();
// if ((SystemLanguage)i == languageList[j])
// {
// var origFontStyle = EditorStyles.label.fontStyle;
// EditorStyles.label.fontStyle = FontStyle.Bold;
// EditorGUILayout.LabelField(labelText, GUILayout.Width(100));
// EditorStyles.label.fontStyle = origFontStyle;
// EditorGUI.indentLevel++;
// m_propTextList.GetArrayElementAtIndex(i).stringValue = EditorGUILayout.TextArea(m_propTextList.GetArrayElementAtIndex(i).stringValue);
// if (m_propIsChangeFontSize.boolValue)
// {
// EditorGUILayout.BeginHorizontal();
// EditorGUILayout.LabelField("FontSize", GUILayout.Width(65));
// m_propFontSizeList.GetArrayElementAtIndex(i).intValue = Mathf.Clamp(EditorGUILayout.IntField(m_propFontSizeList.GetArrayElementAtIndex(i).intValue), 0, 300);
// EditorGUILayout.EndHorizontal();
// }
// if (m_propIsChangeRectSize.boolValue)
// {
// EditorGUILayout.BeginHorizontal();
// EditorGUILayout.LabelField("RectSize", GUILayout.Width(65));
// m_propRectSizeList.GetArrayElementAtIndex(i).vector2Value = EditorGUILayout.Vector2Field("", m_propRectSizeList.GetArrayElementAtIndex(i).vector2Value);
// EditorGUILayout.EndHorizontal();
// }
// EditorGUI.indentLevel--;
// EditorGUILayout.Space();
// }
// }
//}
//serializedObject.ApplyModifiedProperties();
}
}
} | 39.482759 | 166 | 0.728384 | [
"MIT"
] | LightGive/LocalizeUI | LocalizeUI/Assets/LightGive/Managers/SimpleLocalizeManager/Scripts/Editor/LocalizeTextEditor.cs | 3,437 | C# |
// project namespaces
using TwitchLibrary.Enums.Helpers.Paging;
using TwitchLibrary.Interfaces.Helpers.Paging;
// imported .dll's
using RestSharp;
namespace TwitchLibrary.Helpers.Paging.Streams
{
public class PagingStreamFollows : PagingLimitOffset, ITwitchPaging
{
public StreamType stream_type;
public PagingStreamFollows() : base(25)
{
stream_type = StreamType.LIVE;
}
public PagingStreamFollows(int _limit, int _offset, StreamType _stream_type) : base(25)
{
limit = _limit;
offset = _offset;
stream_type = _stream_type;
}
/// <summary>
/// Sets how to recieve the <see cref="RestRequest"/> when getting paged results.
/// </summary>
public new RestRequest Add(RestRequest request)
{
request.AddQueryParameter("limit", limit.ToString());
request.AddQueryParameter("offset", offset.ToString());
request.AddQueryParameter("stream_type", stream_type.ToString().ToLower());
return request;
}
}
}
| 30.615385 | 99 | 0.585427 | [
"Apache-2.0"
] | RokuHodo/Twitch-Library | Helpers/Paging/Streams/PagingStreamFollows.cs | 1,196 | C# |
using LiteNetLib;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace LiteNetLibManager
{
public class LiteNetLibTransportServerEventListener : INetEventListener
{
private readonly ITransport transport;
private readonly string connectKey;
private readonly Queue<TransportEventData> eventQueue;
private readonly Dictionary<long, NetPeer> serverPeers;
public LiteNetLibTransportServerEventListener(ITransport transport, string connectKey, Queue<TransportEventData> eventQueue, Dictionary<long, NetPeer> serverPeers)
{
this.transport = transport;
this.connectKey = connectKey;
this.eventQueue = eventQueue;
this.serverPeers = serverPeers;
}
public void OnConnectionRequest(ConnectionRequest request)
{
if (transport.ServerPeersCount < transport.ServerMaxConnections)
request.AcceptIfKey(connectKey);
else
request.Reject();
}
public void OnNetworkError(IPEndPoint endPoint, SocketError socketError)
{
eventQueue.Enqueue(new TransportEventData()
{
type = ENetworkEvent.ErrorEvent,
endPoint = endPoint,
socketError = socketError,
});
}
public void OnNetworkLatencyUpdate(NetPeer peer, int latency)
{
}
public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
{
eventQueue.Enqueue(new TransportEventData()
{
type = ENetworkEvent.DataEvent,
connectionId = peer.Id,
reader = reader,
});
}
public void OnNetworkReceiveUnconnected(IPEndPoint remoteEndPoint, NetPacketReader reader, UnconnectedMessageType messageType)
{
}
public void OnPeerConnected(NetPeer peer)
{
serverPeers[peer.Id] = peer;
eventQueue.Enqueue(new TransportEventData()
{
type = ENetworkEvent.ConnectEvent,
connectionId = peer.Id,
});
}
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
serverPeers.Remove(peer.Id);
eventQueue.Enqueue(new TransportEventData()
{
type = ENetworkEvent.DisconnectEvent,
connectionId = peer.Id,
disconnectInfo = disconnectInfo,
});
}
}
}
| 32.395062 | 171 | 0.605183 | [
"MIT"
] | AldeRoberge/LiteNetLibManager | Scripts/Transports/LiteNetLib/LiteNetLibTransportServerEventListener.cs | 2,626 | C# |
namespace FarmCord.Services.Extensions.SeasonalCrop
{
public class SeasonalCrop : Crop.Crop
{
public bool isSeasonal
{
get; set;
}
}
} | 18.2 | 51 | 0.571429 | [
"Apache-2.0"
] | Aidan-is-gay/FarmCord | FarmCord/Services/Extensions/SeasonalCrop.cs | 182 | C# |
namespace MishMash.Models.BindingModels
{
public class UserRegisterBindingModel
{
public string Username { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string Email { get; set; }
}
} | 22.846154 | 52 | 0.602694 | [
"MIT"
] | stoyanov7/SoftwareUniversity | C#Development/C#Web/C#WebDevelopmentBasics/Exams/MishMash/MishMash/Models/BindingModels/UserRegisterBindingModel.cs | 299 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.PostgreSQL.FlexibleServers
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// FirewallRulesOperations operations.
/// </summary>
public partial interface IFirewallRulesOperations
{
/// <summary>
/// Creates a new firewall rule or updates an existing firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the server firewall rule.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FirewallRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, FirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a PostgreSQL server firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the server firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all the firewall rules in a given server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the server firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FirewallRule>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all the firewall rules in a given PostgreSQL server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<FirewallRule>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new firewall rule or updates an existing firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the server firewall rule.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating or updating a firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<FirewallRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, FirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a PostgreSQL server firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group. The name is case insensitive.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='firewallRuleName'>
/// The name of the server firewall rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all the firewall rules in a given PostgreSQL server.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<FirewallRule>>> ListByServerNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 47.865116 | 308 | 0.62579 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/src/postgresqlflexibleservers/Generated/IFirewallRulesOperations.cs | 10,291 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ContainsChainedSyntaxTests.cs" company="">
// Copyright 2013 Cyrille DUPUYDAUBY
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace NFluent.Tests
{
using System.Collections;
using NFluent.Helpers;
using NUnit.Framework;
[TestFixture]
public class ContainsChainedSyntaxTests
{
private readonly string[] tresAmigos = new[] { "un", "dos", "tres" };
[Test]
public void IsOnlyMadeOfSuccessTest()
{
Check.That(this.tresAmigos).Contains("dos", "un", "tres").Only();
Check.That((IEnumerable) this.tresAmigos).Contains("dos", "un", "tres").Only();
}
[Test]
public void IsOnlyMadeOfFailTest()
{
Check.ThatCode(()=>
Check.That(this.tresAmigos).Contains("dos", "un").Only()).IsAFailingCheck();
Check.ThatCode(()=>
Check.That((IEnumerable)this.tresAmigos).Contains("dos", "un").Only()).IsAFailingCheck();
}
[Test]
public void ContainsInThatOrderSuccessTest()
{
Check.That(this.tresAmigos).Contains("un", "dos", "tres").InThatOrder();
Check.That(this.tresAmigos).Contains("un", "dos").InThatOrder();
Check.That(this.tresAmigos).Contains("un", "un", "dos", "tres").InThatOrder();
Check.That(this.tresAmigos).Contains("dos", "tres").InThatOrder();
Check.That((IEnumerable)this.tresAmigos).Contains("dos", "tres").InThatOrder();
Check.ThatCode(()=> Check.That((IEnumerable) this.tresAmigos).Contains("tres", "dos").InThatOrder()).IsAFailingCheck();
}
[Test]
public void ContainsInThatOrderFails()
{
var tresAmigosAndMore = new[] { "un", "dos", "un", "tres" };
Check.ThatCode(() =>
{
Check.That(tresAmigosAndMore).Contains(this.tresAmigos).InThatOrder();
}).
IsAFailingCheckWithMessage("",
"The checked enumerable does not follow to the expected order. Item [\"un\"] appears too late in the list, at index '2'.",
"The checked enumerable:",
"\t{\"un\",\"dos\",*\"un\"*,\"tres\"} (4 items)",
"The expected value(s): in that order",
"\t{*\"un\"*,\"dos\",\"tres\"} (3 items)");
//
Check.ThatCode(() =>
{
Check.That(tresAmigosAndMore).Contains(this.tresAmigos).InThatOrder();
}).
IsAFailingCheckWithMessage("",
"The checked enumerable does not follow to the expected order. Item [\"un\"] appears too late in the list, at index '2'.",
"The checked enumerable:",
"\t{\"un\",\"dos\",*\"un\"*,\"tres\"} (4 items)",
"The expected value(s): in that order",
"\t{*\"un\"*,\"dos\",\"tres\"} (3 items)");
}
[Test]
public void ContainsInThatOrderFails2()
{
Check.ThatCode(() =>
{
Check.That(this.tresAmigos).Contains("dos", "un", "tres").InThatOrder();
})
.IsAFailingCheckWithMessage("",
"The checked enumerable does not follow to the expected order. Item [\"dos\"] appears too late in the list, at index '1'.",
"The checked enumerable:",
"\t{\"un\",*\"dos\"*,\"tres\"} (3 items)",
"The expected value(s): in that order",
"\t{*\"dos\"*,\"un\",\"tres\"} (3 items)");
}
[Test]
public void ContainsInThatOrderFails3()
{
Check.ThatCode(() =>
{
Check.That(this.tresAmigos).Contains("un", "tres", "dos").InThatOrder();
})
.IsAFailingCheckWithMessage(
"",
"The checked enumerable does not follow to the expected order. Item [\"dos\"] appears too early in the list, at index '1'.",
"The checked enumerable:",
"\t{\"un\",*\"dos\"*,\"tres\"} (3 items)",
"The expected value(s): in that order",
"\t{\"un\",\"tres\",*\"dos\"*} (3 items)");
}
[Test]
public void ContainsOnceSucceeds()
{
Check.That(this.tresAmigos).Contains(this.tresAmigos).Once();
Check.That((IEnumerable) this.tresAmigos).Contains(this.tresAmigos).Once();
Check.That((IEnumerable) this.tresAmigos).Contains("un", "dos", "tres").Once();
Check.ThatCode( ()=>
Check.That((IEnumerable) new[] { "un", "dos", "dos", "tres" }).Contains("un", "dos", "tres").Once()).IsAFailingCheck();
}
[Test]
public void ContainsOnceCantBeNegated()
{
Check.ThatCode(() => Check.That(this.tresAmigos).Not.Contains("toto").Once())
.Throws<InvalidOperationException>().WithMessage("Once can't be used when negated");
}
[Test]
public void ContainsInThatOrderCantBeNegated()
{
Check.ThatCode(() => Check.That(this.tresAmigos).Not.Contains("toto").InThatOrder())
.Throws<InvalidOperationException>().WithMessage("InThatOrder can't be used when negated");
}
[Test]
public void ContainsOnceSucceedsWithMultipleOccurrences()
{
var tresAmigosAndMore = new[] { "un", "dos", "tres", "tres" };
Check.That(tresAmigosAndMore).Contains(tresAmigosAndMore).Once();
}
[Test]
public void ContainsOnceSucceedsWithMissingEntry()
{
var tresAmigosAndMore = new[] { "un", "dos", "tres", "four" };
Check.That(tresAmigosAndMore).Contains(tresAmigos).Once();
}
[Test]
public void ContainsOnceFails()
{
var tresAmigosAndMore = new[] { "un", "dos", "tres", "tres", "dos" };
Check.ThatCode(() =>
{
Check.That(tresAmigosAndMore).Contains(this.tresAmigos).Once();
})
.IsAFailingCheckWithMessage("",
"The checked enumerable has extra occurrences of the expected items. Item [\"tres\"] at position 3 is redundant.",
"The checked enumerable:",
"\t{\"un\",\"dos\",\"tres\",*\"tres\"*,\"dos\"} (5 items)",
"The expected enumerable: once of",
"\t{\"un\",\"dos\",\"tres\"} (3 items)");
}
}
}
| 44.005747 | 145 | 0.503461 | [
"Apache-2.0"
] | NFluent/NFluent | code/tests/NFluent.Tests/ContainsChainedSyntaxTests.cs | 7,486 | C# |
namespace java.util
{
[global::MonoJavaBridge.JavaClass()]
public partial class Hashtable : java.util.Dictionary, Map, java.lang.Cloneable, java.io.Serializable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Hashtable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.Object get(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.Hashtable.staticClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.Hashtable._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::java.lang.Object put(java.lang.Object arg0, java.lang.Object arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.Hashtable.staticClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.Hashtable._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m2;
public override bool equals(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.Hashtable.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.util.Hashtable._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.util.Hashtable.staticClass, "toString", "()Ljava/lang/String;", ref global::java.util.Hashtable._m3) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::java.util.Collection values()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Collection>(this, global::java.util.Hashtable.staticClass, "values", "()Ljava/util/Collection;", ref global::java.util.Hashtable._m4) as java.util.Collection;
}
private static global::MonoJavaBridge.MethodId _m5;
public override int hashCode()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.Hashtable.staticClass, "hashCode", "()I", ref global::java.util.Hashtable._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual global::java.lang.Object clone()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.Hashtable.staticClass, "clone", "()Ljava/lang/Object;", ref global::java.util.Hashtable._m6) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual void clear()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.Hashtable.staticClass, "clear", "()V", ref global::java.util.Hashtable._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public override bool isEmpty()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.Hashtable.staticClass, "isEmpty", "()Z", ref global::java.util.Hashtable._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual bool contains(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.Hashtable.staticClass, "contains", "(Ljava/lang/Object;)Z", ref global::java.util.Hashtable._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m10;
public override int size()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.util.Hashtable.staticClass, "size", "()I", ref global::java.util.Hashtable._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::java.util.Set entrySet()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.util.Hashtable.staticClass, "entrySet", "()Ljava/util/Set;", ref global::java.util.Hashtable._m11) as java.util.Set;
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void putAll(java.util.Map arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.Hashtable.staticClass, "putAll", "(Ljava/util/Map;)V", ref global::java.util.Hashtable._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public override global::java.lang.Object remove(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.util.Hashtable.staticClass, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.util.Hashtable._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m14;
public override global::java.util.Enumeration elements()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Enumeration>(this, global::java.util.Hashtable.staticClass, "elements", "()Ljava/util/Enumeration;", ref global::java.util.Hashtable._m14) as java.util.Enumeration;
}
private static global::MonoJavaBridge.MethodId _m15;
public override global::java.util.Enumeration keys()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Enumeration>(this, global::java.util.Hashtable.staticClass, "keys", "()Ljava/util/Enumeration;", ref global::java.util.Hashtable._m15) as java.util.Enumeration;
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual global::java.util.Set keySet()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.util.Hashtable.staticClass, "keySet", "()Ljava/util/Set;", ref global::java.util.Hashtable._m16) as java.util.Set;
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual bool containsValue(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.Hashtable.staticClass, "containsValue", "(Ljava/lang/Object;)Z", ref global::java.util.Hashtable._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual bool containsKey(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.util.Hashtable.staticClass, "containsKey", "(Ljava/lang/Object;)Z", ref global::java.util.Hashtable._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
protected virtual void rehash()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.util.Hashtable.staticClass, "rehash", "()V", ref global::java.util.Hashtable._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public Hashtable(int arg0, float arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.Hashtable._m20.native == global::System.IntPtr.Zero)
global::java.util.Hashtable._m20 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(IF)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m21;
public Hashtable(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.Hashtable._m21.native == global::System.IntPtr.Zero)
global::java.util.Hashtable._m21 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m22;
public Hashtable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.Hashtable._m22.native == global::System.IntPtr.Zero)
global::java.util.Hashtable._m22 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._m22);
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m23;
public Hashtable(java.util.Map arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.util.Hashtable._m23.native == global::System.IntPtr.Zero)
global::java.util.Hashtable._m23 = @__env.GetMethodIDNoThrow(global::java.util.Hashtable.staticClass, "<init>", "(Ljava/util/Map;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Hashtable.staticClass, global::java.util.Hashtable._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static Hashtable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.util.Hashtable.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Hashtable"));
}
}
}
| 64.607843 | 344 | 0.770966 | [
"MIT"
] | JeroMiya/androidmono | MonoJavaBridge/android/generated/java/util/Hashtable.cs | 9,885 | 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("TestWebSite")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestWebSite")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fe223ae6-4e18-48c3-9826-44048b9901d6")]
// 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.638889 | 84 | 0.748339 | [
"MIT"
] | augustoproiete-forks/cake-contrib--Cake.Kudu | src/TestWebSite/Properties/AssemblyInfo.cs | 1,358 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Toolbar = Android.Support.V7.Widget.Toolbar;
using Android.Widget;
namespace MyHealth.Client.Droid.Extensions
{
static class ActivityExtensions
{
public static void SetCustomTitle(this Activity activity, string title)
{
var toolbar = activity.FindViewById<Toolbar>(Resource.Id.toolbar);
var textTitle = toolbar?.FindViewById<TextView>(Resource.Id.toolbar_title);
if (textTitle != null)
{
textTitle.Text = title;
}
}
}
} | 26.035714 | 87 | 0.672154 | [
"MIT"
] | 3miliomc/Consultorio | src/MyHealth.Client.Droid/Extensions/ActivityExtensions.cs | 729 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterBlockTests : SharedBlockTests
{
private static IEnumerable<ParameterExpression> SingleParameter
{
get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); }
}
[Theory]
[MemberData("ConstantValueData")]
public void SingleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Theory]
[MemberData("ConstantValueData")]
public void DoubleElementBlock(object value)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Fact]
public void NullExpicitType()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0)));
Assert.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>)));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[])));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>)));
}
[Theory]
[MemberData("BlockSizes")]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i < expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[MemberData("BlockSizes")]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[MemberData("ObjectAssignableConstantValuesAndSizes")]
public void BlockExplicitType(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile()());
}
[Theory]
[MemberData("BlockSizes")]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), SingleParameter, expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), SingleParameter, expressions.ToArray()));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray());
BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions);
Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile()());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile()());
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), SingleParameter));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void VariableCountCorrect(object value, int blockSize)
{
IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType()));
BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType()));
Assert.Equal(blockSize, block.Variables.Count);
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
[ActiveIssue(3883)]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
}
[Theory]
[MemberData("ConstantValuesAndSizes")]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData("ObjectAssignableConstantValuesAndSizes")]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData("BlockSizes")]
public void NullVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1);
Assert.Throws<ArgumentNullException>(() => Expression.Block(vars, expressions));
Assert.Throws<ArgumentNullException>(() => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentNullException>(() => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentNullException>(() => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData("BlockSizes")]
public void ByRefVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1);
Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData("BlockSizes")]
public void RepeatedVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
ParameterExpression variable = Expression.Variable(typeof(int));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2);
Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(vars, expressions.ToArray()));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions));
Assert.Throws<ArgumentException>(() => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
}
}
| 46.45092 | 152 | 0.644588 | [
"MIT"
] | er0dr1guez/corefx | src/System.Linq.Expressions/tests/Block/ParameterBlockTests.cs | 15,143 | 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 kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.KinesisAnalyticsV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KinesisAnalyticsV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// FlinkRunConfiguration Marshaller
/// </summary>
public class FlinkRunConfigurationMarshaller : IRequestMarshaller<FlinkRunConfiguration, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(FlinkRunConfiguration requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAllowNonRestoredState())
{
context.Writer.WritePropertyName("AllowNonRestoredState");
context.Writer.Write(requestObject.AllowNonRestoredState);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static FlinkRunConfigurationMarshaller Instance = new FlinkRunConfigurationMarshaller();
}
} | 34.387097 | 116 | 0.703096 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/KinesisAnalyticsV2/Generated/Model/Internal/MarshallTransformations/FlinkRunConfigurationMarshaller.cs | 2,132 | C# |
namespace EA.Weee.Web.Areas.Admin.Mappings.ToViewModel
{
using Areas.Admin.ViewModels.Scheme.Overview.PcsDetails;
using Core.Scheme;
using Core.Shared;
using Prsd.Core.Mapper;
public class SchemeDataToPcsDetailsOverviewViewModel : IMap<SchemeData, PcsDetailsOverviewViewModel>
{
public PcsDetailsOverviewViewModel Map(SchemeData source)
{
return new PcsDetailsOverviewViewModel
{
AppropriateAuthority = source.CompetentAuthority != null
? source.CompetentAuthority.Abbreviation
: string.Empty,
ApprovalNumber = source.ApprovalName,
BillingReference = source.IbisCustomerReference,
ObligationType = source.ObligationType.HasValue
? source.ObligationType.Value.ToString()
: string.Empty,
Status = source.SchemeStatus.ToString(),
SchemeId = source.Id,
SchemeName = source.SchemeName,
CanEditPcs = source.CanEdit,
IsRejected = source.SchemeStatus == SchemeStatus.Rejected
};
}
}
} | 39.666667 | 104 | 0.609244 | [
"Unlicense"
] | DEFRA/prsd-weee | src/EA.Weee.Web/Areas/Admin/Mappings/ToViewModel/SchemeDataToPcsDetailsOverviewViewModel.cs | 1,192 | C# |
using Serenity.ComponentModel;
using Serenity.Data;
using System;
namespace Serenity.PropertyGrid
{
public partial class BasicPropertyProcessor : PropertyProcessor
{
private void SetWidth(IPropertySource source, PropertyItem item)
{
var widthAttr = source.GetAttribute<WidthAttribute>();
var basedOnField = source.BasedOnField;
item.Width = widthAttr == null ? (!ReferenceEquals(null, basedOnField) ? AutoWidth(basedOnField) : 80) : widthAttr.Value;
if (widthAttr != null && (widthAttr.Min != 0))
item.MinWidth = widthAttr.Min;
if (widthAttr != null && (widthAttr.Max != 0))
item.MaxWidth = widthAttr.Max;
var labelWidthAttr = source.GetAttribute<LabelWidthAttribute>();
if (labelWidthAttr != null)
item.LabelWidth = labelWidthAttr.Value;
}
private static int AutoWidth(Field field)
{
var name = field.Name;
switch (field.Type)
{
case FieldType.String:
if (field.Size != 0 && field.Size <= 25)
return Math.Max(field.Size * 6, 150);
else if (field.Size == 0)
return 250;
else
return 150;
case FieldType.Boolean:
return 40;
case FieldType.DateTime:
return 85;
case FieldType.Time:
return 70;
case FieldType.Int16:
return 55;
case FieldType.Int32:
return 65;
case FieldType.Single:
case FieldType.Double:
case FieldType.Decimal:
return 85;
default:
return 80;
}
}
}
} | 34.070175 | 133 | 0.495366 | [
"MIT"
] | davidzhang9990/SimpleProject | Serenity.Data.Entity/PropertyGrid/BasicPropertyProcessor/BasicPropertyProcessor.Width.cs | 1,944 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ReportPortal.Cli.Commands.Launch;
using System;
using System.CommandLine;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
[assembly: InternalsVisibleTo("ReportPortal.Cli.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace ReportPortal.Cli
{
partial class Program
{
static IServiceProvider _serviceProvider;
public static async Task<int> Main(string[] args, IConsole console = null)
{
ConfigureServices(console);
var rpCommand = new RootCommand("Interact with Report Portal API");
AddConnectCommand(rpCommand);
AddLaunchCommand(rpCommand);
return await rpCommand.InvokeAsync(args, console);
}
static void ConfigureServices(IConsole console)
{
var serviceCollection = new ServiceCollection();
var builder = new ConfigurationBuilder()
.AddJsonFile(Settings.ConnectionRepository.HomeConfigFile, optional: true)
.AddEnvironmentVariables("ReportPortal_Cli_");
var configuration = builder.Build();
serviceCollection.AddSingleton(console);
serviceCollection.AddSingleton(configuration);
serviceCollection.AddScoped<Settings.IConnectionRepository, Settings.ConnectionRepository>();
serviceCollection.AddSingleton<Http.IApiClient, Http.ApiClient>();
serviceCollection.AddScoped<LaunchCommandExecutor>();
_serviceProvider = serviceCollection.BuildServiceProvider();
}
}
}
| 33.039216 | 105 | 0.697329 | [
"MIT"
] | nvborisenko/reportportal-cli | src/ReportPortal.Cli/Program.cs | 1,687 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using DevExpress.XtraEditors.DXErrorProvider;
namespace DevExpress.MailClient.Win.Forms {
public partial class frmFeed : XtraForm {
DialogRole role = DialogRole.New;
NavBarControl navBar;
List<string> uniqueNames;
public frmFeed() {
InitializeComponent();
}
void InitValidation() {
UniqueNameValidationRule rule = new UniqueNameValidationRule(uniqueNames);
rule.ErrorType = ErrorType.Critical;
rule.ErrorText = Properties.Resources.RuleUniqueNamesWarning;
dxValidationProvider1.SetValidationRule(teCaption, rule);
dxValidationProvider1.SetValidationRule(cbeGroup, ValidationRulesHelper.RuleIsNotBlank);
dxValidationProvider1.SetValidationRule(heLink, ValidationRulesHelper.RuleIsNotBlank);
cbeGroup.EditValueChanged += new EventHandler(edit_EditValueChanged);
teCaption.EditValueChanged += new EventHandler(edit_EditValueChanged);
heLink.EditValueChanged += new EventHandler(edit_EditValueChanged);
}
void edit_EditValueChanged(object sender, EventArgs e) {
sbOK.Enabled = !string.IsNullOrEmpty(heLink.Text);
}
public NavBarItem CurrentItem { get { return navBar.SelectedLink.Item; } }
NavBarGroup CurrentGroup { get { return navBar.SelectedLink.Group; } }
public frmFeed(DialogRole role, NavBarControl navBar) {
InitializeComponent();
this.role = role;
this.navBar = navBar;
cbeGroup.Properties.Items.AddRange(NavBarHelper.GetGroupNames(navBar));
sbOK.Text = role == DialogRole.New ? Properties.Resources.Add : Properties.Resources.OK;
Text = (role == DialogRole.New ? Properties.Resources.NewFeedDescription : Properties.Resources.EditFeedDescription).Replace(".", string.Empty);
uniqueNames = NavBarHelper.GetItemNames(navBar);
uniqueNames.Add(string.Empty);
if(role == DialogRole.New) {
teCaption.Text = NavBarHelper.GetUniqueItemName(Properties.Resources.TempFeedName, navBar);
cbeGroup.Text = Properties.Resources.TempGroupName;
sbOK.Enabled = false;
} else {
uniqueNames.Remove(CurrentItem.Caption);
teCaption.Text = CurrentItem.Caption;
cbeGroup.Text = CurrentGroup.Caption;
heLink.Text = string.Format("{0}", CurrentItem.Tag);
}
InitValidation();
}
protected override void OnClosing(CancelEventArgs e) {
base.OnClosing(e);
if(DialogResult == DialogResult.OK) {
if(role == DialogRole.New) {
navBar.BeginUpdate();
NavBarGroup group = NavBarHelper.GetGroupByName(cbeGroup.Text, navBar);
NavBarItem item = new NavBarItem(teCaption.Text);
NavBarItemLink link = group.ItemLinks.Add(item);
group.Expanded = true;
item.Tag = ObjectHelper.GetCorrectUrl(heLink.Text);
navBar.SelectedLink = link;
navBar.EndUpdate();
} else {
CurrentItem.Caption = teCaption.Text;
CurrentItem.Tag = ObjectHelper.GetCorrectUrl(heLink.Text);
if(CurrentGroup.Caption != cbeGroup.Text) {
navBar.BeginUpdate();
NavBarGroup group = NavBarHelper.GetGroupByName(cbeGroup.Text, navBar);
group.Expanded = true;
NavBarItemLink link = group.ItemLinks.Add(CurrentItem);
CurrentGroup.ItemLinks.Remove(navBar.SelectedLink);
navBar.SelectedLink = link;
NavBarHelper.DeleteEmptyGroup(navBar);
navBar.EndUpdate();
}
}
}
}
}
}
| 48.488636 | 156 | 0.612843 | [
"MIT"
] | svlcode/MailClient | sources/DevExpress.MailClient.Win/Forms/frmFeed.cs | 4,269 | C# |
using System.Runtime.InteropServices;
namespace SmashArcNet.RustTypes
{
[StructLayout(LayoutKind.Sequential)]
internal struct FileMetadata
{
public Hash40 PathHash { get; set; }
public Hash40 ExtHash { get; set; }
public Hash40 ParentHash { get; set; }
public Hash40 FileNameHash { get; set; }
public ulong Offset { get; set; }
public ulong CompSize { get; set; }
public ulong DecompSize { get; set; }
// C# bools aren't converting properly from Rust, so use byte instead.
public byte IsStream { get; set; }
public byte IsShared { get; set; }
public byte IsRedirect { get; set; }
public byte IsRegional { get; set; }
public byte IsLocalized { get; set; }
public byte IsCompressed { get; set; }
public byte UsesZstd { get; set; }
}
}
| 34.84 | 78 | 0.615385 | [
"MIT"
] | ScanMountGoat/SmashArcNet | SmashArcNet/RustTypes/FileMetadata.cs | 873 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 4.0.1
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace QuantLib {
public class SplineCubicInterpolatedSmileSection : SmileSection {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
private bool swigCMemOwnDerived;
internal SplineCubicInterpolatedSmileSection(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.SplineCubicInterpolatedSmileSection_SWIGSmartPtrUpcast(cPtr), true) {
swigCMemOwnDerived = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SplineCubicInterpolatedSmileSection obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
protected override void Dispose(bool disposing) {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwnDerived) {
swigCMemOwnDerived = false;
NQuantLibcPINVOKE.delete_SplineCubicInterpolatedSmileSection(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
base.Dispose(disposing);
}
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, SplineCubic interpolator, DayCounter dc, VolatilityType type, double shift) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_0(expiryTime, DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc), (int)type, shift), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, SplineCubic interpolator, DayCounter dc, VolatilityType type) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_1(expiryTime, DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc), (int)type), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, SplineCubic interpolator, DayCounter dc) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_2(expiryTime, DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, SplineCubic interpolator) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_3(expiryTime, DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), SplineCubic.getCPtr(interpolator)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_4(expiryTime, DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, SplineCubic interpolator, DayCounter dc, VolatilityType type, double shift) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_5(expiryTime, DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc), (int)type, shift), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, SplineCubic interpolator, DayCounter dc, VolatilityType type) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_6(expiryTime, DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc), (int)type), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, SplineCubic interpolator, DayCounter dc) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_7(expiryTime, DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, SplineCubic.getCPtr(interpolator), DayCounter.getCPtr(dc)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, SplineCubic interpolator) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_8(expiryTime, DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, SplineCubic.getCPtr(interpolator)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(double expiryTime, DoubleVector strikes, DoubleVector stdDevs, double atmLevel) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_9(expiryTime, DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate, VolatilityType type, double shift) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_10(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate), (int)type, shift), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate, VolatilityType type) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_11(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate), (int)type), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_12(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, DayCounter dc, SplineCubic interpolator) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_13(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel, DayCounter dc) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_14(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel), DayCounter.getCPtr(dc)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, QuoteHandleVector stdDevHandles, QuoteHandle atmLevel) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_15(Date.getCPtr(d), DoubleVector.getCPtr(strikes), QuoteHandleVector.getCPtr(stdDevHandles), QuoteHandle.getCPtr(atmLevel)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate, VolatilityType type, double shift) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_16(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate), (int)type, shift), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate, VolatilityType type) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_17(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate), (int)type), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, DayCounter dc, SplineCubic interpolator, Date referenceDate) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_18(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator), Date.getCPtr(referenceDate)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, DayCounter dc, SplineCubic interpolator) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_19(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, DayCounter.getCPtr(dc), SplineCubic.getCPtr(interpolator)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel, DayCounter dc) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_20(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel, DayCounter.getCPtr(dc)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public SplineCubicInterpolatedSmileSection(Date d, DoubleVector strikes, DoubleVector stdDevs, double atmLevel) : this(NQuantLibcPINVOKE.new_SplineCubicInterpolatedSmileSection__SWIG_21(Date.getCPtr(d), DoubleVector.getCPtr(strikes), DoubleVector.getCPtr(stdDevs), atmLevel), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
}
}
| 103.338462 | 536 | 0.815766 | [
"Apache-2.0"
] | andrew-stakiwicz-r3/financial_derivatives_demo | quantlib_swig_bindings/CSharp/csharp/SplineCubicInterpolatedSmileSection.cs | 13,434 | C# |
using UnityEngine;
using System.Collections.Generic;
using Unity.Mathematics;
public class LightData : MonoBehaviour
{
[HideInInspector] public int4 lastUpdatedCP;
public static int4 LastUpdatedCP
{
get
{
return instance.lastUpdatedCP;
}
}
public static void SetLastUpdatedCP(int4 cp)
{
instance.lastUpdatedCP = cp;
}
[HideInInspector] public int4? rebuildCP;
public static int4? RebuildCP
{
get
{
return instance.rebuildCP;
}
}
public static void SetRebuildCP(int4? cp)
{
instance.rebuildCP = cp;
}
[HideInInspector] public Dictionary<int4, float?[,,]> data = new Dictionary<int4, float?[,,]>();
public static Dictionary<int4, float?[,,]> Data
{
get
{
return instance.data;
}
}
static LightData instance;
void Awake()
{
if (instance != null && instance != this)
Destroy(gameObject);
else
instance = this;
}
}
| 20.901961 | 100 | 0.570356 | [
"MIT"
] | igyvigy/idle-craft | Assets/Scripts/LightData.cs | 1,066 | C# |
using SciTech.Rpc.Serialization;
using SciTech.Rpc.Serialization.Internal;
using System;
using System.Threading.Tasks;
namespace SciTech.Rpc.Lightweight.Internal
{
internal class LightweightRpcFrameWriter : ILightweightRpcFrameWriter, IDisposable
{
private BufferWriterStream writer = new BufferWriterStreamImpl();
private int maxFrameSize;
private bool isWriting;
private bool hasFrameData;
public LightweightRpcFrameWriter(int maxFrameSize)
{
this.maxFrameSize = maxFrameSize;
}
private void AbortWrite()
{
this.isWriting = this.hasFrameData = false;
}
void ILightweightRpcFrameWriter.AbortWrite(in LightweightRpcFrame.WriteState state)
=> this.AbortWrite();
internal byte[] WriteFrame<T>(in LightweightRpcFrame frameHeader, T payload, IRpcSerializer serializer)
{
var state = this.BeginWrite(frameHeader);
try
{
serializer.Serialize(state.Writer, payload, typeof(T));
this.EndWrite(state);
return this.GetFrameData()!;
}
catch
{
this.AbortWrite();
throw;
}
}
internal byte[] WriteFrame(in LightweightRpcFrame frameHeader)
{
var state = this.BeginWrite(frameHeader);
try
{
this.EndWrite(state);
return this.GetFrameData()!;
}
catch
{
this.AbortWrite();
throw;
}
}
private LightweightRpcFrame.WriteState BeginWrite(in LightweightRpcFrame responseHeader)
{
if (this.isWriting) throw new InvalidOperationException("Already writing in LightweightRpcFrameWriter.");
this.isWriting = true;
this.hasFrameData = false;
this.writer.Reset();
return responseHeader.BeginWrite(this.writer);
}
LightweightRpcFrame.WriteState ILightweightRpcFrameWriter.BeginWrite(in LightweightRpcFrame responseHeader)
=> this.BeginWrite(responseHeader);
private void EndWrite(in LightweightRpcFrame.WriteState state)
{
if (!this.isWriting) throw new InvalidOperationException("EndWriteAsync called without a BeginWriteCall.");
LightweightRpcFrame.EndWrite((int)this.writer.Length, state);
this.isWriting = false;
this.hasFrameData = true;
}
ValueTask ILightweightRpcFrameWriter.EndWriteAsync(in LightweightRpcFrame.WriteState state, bool throwOnError)
{
this.EndWrite(state);
return default;
}
internal void Reset()
{
this.isWriting = this.hasFrameData = false;
this.writer.Reset();
}
internal byte[]? GetFrameData()
{
return this.hasFrameData ? this.writer.ToArray() : null;
}
public void Dispose()
{
this.Reset();
this.writer.Dispose();
}
}
}
| 29.018182 | 119 | 0.584586 | [
"BSD-3-Clause"
] | SciTechSoftware/SciTech.Rpc | src/SciTech.Rpc.Lightweight/Lightweight/Internal/LightweightRpcFrameWriter.cs | 3,194 | C# |
//Problem 10. Find sum in array
//Write a program that finds in given array of integers a sequence of given sum S (if present).
using System;
class FindSumInArray
{
static void Main()
{
Console.Write("Enter size of the array: ");
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
Console.Write("Enter the sum of the sequence: ");
int sum = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
Console.Write("Array[{0}] = ", i);
arr[i] = int.Parse(Console.ReadLine());
}
int currentSum = 0;
int start = 0;
for (int i = 0; i < n - 1; i++)
{
currentSum += arr[i];
start = i;
for (int j = i + 1; j < n; j++)
{
currentSum += arr[j];
if (currentSum == sum)
{
for (int k = start; k <= j; k++)
{
Console.WriteLine("{0} ", arr[k]);
}
break;
}
else
{
Console.WriteLine("No sum in the array.");
break;
}
}
currentSum = 0;
}
}
}
| 25.745098 | 95 | 0.396801 | [
"MIT"
] | enchev-93/Telerik-Academy | 02.C Sharp part 2/01.Arrays/Arrays/FindSumInArray/FindSumInArray.cs | 1,315 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
namespace ModuleA
{
public class ModuleA : IModule
{
private readonly IRegionManager _regionManager;
public ModuleA(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void Initialize()
{
_regionManager.Regions["MainRegion"].Add(new DefaultViewA());
}
}
}
| 41.486486 | 85 | 0.564169 | [
"Apache-2.0"
] | andrewdbond/CompositeWPF | sourceCode/compositewpf/V2.2/trunk/Quickstarts/Modularity/ConfigurationModularity/ModuleA/ModuleA.cs | 1,535 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/* The AspectRatioTrigger class is a custom trigger for use with a VisualState. The trigger is designed to fire when the
height/width of the source FrameworkElement is greater than a specified threshold. In order to be a flexible class, it
exposes a NumeratorAspect property that can be either Height or Width. The property chosen will be the numerator when
calculating the ratio between the two properties. Additionally, users can configure whether the ratio must be strictly
greater than the threshold, or if equal should be considered acceptable for the state to trigger. */
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
namespace CalculatorApp.Views.StateTriggers
{
public enum Aspect
{
Height,
Width
}
public sealed class AspectRatioTrigger : Windows.UI.Xaml.StateTriggerBase
{
/* The source for which this class will respond to size changed events. */
public FrameworkElement Source
{
get { return (FrameworkElement)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(
name: nameof(Source),
propertyType: typeof(FrameworkElement),
ownerType: typeof(AspectRatioTrigger),
typeMetadata: new PropertyMetadata(
defaultValue: null,
propertyChangedCallback: (s, e) => (s as AspectRatioTrigger)?.OnSourcePropertyChanged(e.OldValue as FrameworkElement, e.NewValue as FrameworkElement))
);
/* Either Height or Width. The property will determine which aspect is used as the numerator when calculating
the aspect ratio. */
public Aspect NumeratorAspect
{
get { return (Aspect)GetValue(NumeratorAspectProperty); }
set { SetValue(NumeratorAspectProperty, value); }
}
// Using a DependencyProperty as the backing store for NumeratorAspect. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NumeratorAspectProperty =
DependencyProperty.Register(
name: "NumeratorAspect",
propertyType: typeof(Aspect),
ownerType: typeof(AspectRatioTrigger),
typeMetadata: new PropertyMetadata(Aspect.Height)
);
/* The threshold that will cause the trigger to fire when the aspect ratio exceeds this value. */
public double Threshold
{
get { return (double)GetValue(ThresholdProperty); }
set { SetValue(ThresholdProperty, value); }
}
// Using a DependencyProperty as the backing store for Threshold. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ThresholdProperty =
DependencyProperty.Register(
name: "Threshold",
propertyType: typeof(double),
ownerType: typeof(AspectRatioTrigger),
typeMetadata: new PropertyMetadata(0.0)
);
/* If true, the trigger will fire if the aspect ratio is greater than or equal to the threshold. */
public bool ActiveIfEqual
{
get { return (bool)GetValue(ActiveIfEqualProperty); }
set { SetValue(ActiveIfEqualProperty, value); }
}
// Using a DependencyProperty as the backing store for ActiveIfEqual. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ActiveIfEqualProperty =
DependencyProperty.Register(
name: "ActiveIfEqual",
propertyType: typeof(bool),
ownerType: typeof(AspectRatioTrigger),
typeMetadata: new PropertyMetadata(false)
);
public AspectRatioTrigger()
{
SetActive(false);
}
void OnSourcePropertyChanged(FrameworkElement oldValue, FrameworkElement newValue)
{
UnregisterSizeChanged(oldValue);
RegisterSizeChanged(newValue);
}
void RegisterSizeChanged(FrameworkElement element)
{
if (element == null)
{
return;
}
if (element != Source)
{
UnregisterSizeChanged(Source);
}
element.SizeChanged += OnSizeChanged;
}
void UnregisterSizeChanged(FrameworkElement element)
{
if (element != null)
{
element.SizeChanged -= OnSizeChanged;
}
}
void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
UpdateIsActive(e.NewSize);
}
void UpdateIsActive(Size sourceSize)
{
double numerator, denominator;
if (NumeratorAspect == Aspect.Height)
{
numerator = sourceSize.Height;
denominator = sourceSize.Width;
}
else
{
numerator = sourceSize.Width;
denominator = sourceSize.Height;
}
bool isActive = false;
if (denominator > 0)
{
double ratio = numerator / denominator;
double threshold = Math.Abs(Threshold);
isActive = ((ratio > threshold) || (ActiveIfEqual && (ratio == threshold)));
}
SetActive(isActive);
}
}
}
| 29.79375 | 155 | 0.726872 | [
"MIT"
] | AnonProgrammer007/calculator | src/Calculator.Shared/Views/StateTriggers/AspectRatioTrigger.cs | 4,767 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MatBlazor.Demo.ServerApp
{
public class Program
{
public static void Main(string[] args)
{
ThreadPool.SetMaxThreads(int.MaxValue, int.MaxValue);
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 27.129032 | 70 | 0.665874 | [
"MIT"
] | vasilemario/blazer | src/MatBlazor.Demo.ServerApp/Program.cs | 841 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.PublicApi.AuthEndpoints
{
public class UserInfo
{
public static readonly UserInfo Anonymous = new UserInfo();
public bool IsAuthenticated { get; set; }
public string NameClaimType { get; set; }
public string RoleClaimType { get; set; }
public IEnumerable<ClaimValue> Claims { get; set; }
}
}
| 27.764706 | 67 | 0.692797 | [
"MIT"
] | 1010699607/eShopOnWeb | src/PublicApi/AuthEndpoints/Authenticate.UserInfo.cs | 474 | C# |
// *
// * Copyright (C) 2005 Mats Helander : http://www.puzzleframework.com
// *
// * This library is free software; you can redistribute it and/or modify it
// * under the terms of the GNU Lesser General Public License 2.1 or later, as
// * published by the Free Software Foundation. See the included license.txt
// * or http://www.gnu.org/copyleft/lesser.html for details.
// *
// *
namespace Puzzle.NPersist.Framework.Interfaces
{
public interface IUpdatedPropertyTracker
{
bool GetUpdatedStatus(string propertyName);
void SetUpdatedStatus(string propertyName, bool value);
void ClearUpdatedStatuses();
}
} | 29.571429 | 78 | 0.73913 | [
"MIT"
] | jjvanzon/JJ.TryOut | Third Party/NPersist/Source Code/NPersist/Framework/Interfaces/IUpdatedPropertyTracker.cs | 621 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using TripGallery.DTO;
namespace TripGallery.MVCClient.Models
{
public class TripCreateViewModel
{
public HttpPostedFileBase MainImage { get; set; }
public TripForCreation Trip { get; set; }
public TripCreateViewModel()
{
}
public TripCreateViewModel(TripForCreation trip)
{
Trip = trip;
}
}
}
| 19.233333 | 57 | 0.658579 | [
"Apache-2.0"
] | patrickfly/usingOAuth | TripGallery.MVCClient/Models/TripCreateViewModel.cs | 579 | 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.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Web.Mvc.Properties;
namespace Microsoft.Web.Mvc
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class CreditCardAttribute : DataTypeAttribute, IClientValidatable
{
public CreditCardAttribute() : base("creditcard")
{
ErrorMessage = MvcResources.CreditCardAttribute_Invalid;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata,
ControllerContext context
)
{
yield return new ModelClientValidationRule
{
ValidationType = "creditcard",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
string creditCardNumber = value as string;
if (creditCardNumber == null)
{
return false;
}
creditCardNumber = creditCardNumber.Replace("-", String.Empty);
int checksum = 0;
bool evenDigit = false;
// http://www.beachnet.com/~hstiles/cardtype.html
foreach (char digit in creditCardNumber.Reverse())
{
if (!Char.IsDigit(digit))
{
return false;
}
int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
evenDigit = !evenDigit;
while (digitValue > 0)
{
checksum += digitValue % 10;
digitValue /= 10;
}
}
return (checksum % 10) == 0;
}
}
}
| 29.444444 | 111 | 0.548113 | [
"Apache-2.0"
] | belav/AspNetWebStack | src/Microsoft.Web.Mvc/CreditCardAttribute.cs | 2,122 | 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("Medical")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Medical")]
[assembly: AssemblyCopyright("Copyright © 2006")]
[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("46bb8188-2f59-438c-b807-882f9edfdc16")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 36.058824 | 84 | 0.748777 | [
"MIT"
] | gravbox/-GravityboxSchedule | PublicTests/C#_Projects/Medical/Properties/AssemblyInfo.cs | 1,229 | C# |
namespace Smart.Navigation.Mappers
{
using System;
public interface ITypeConstraint
{
bool IsValidType(Type type);
}
}
| 14.4 | 36 | 0.659722 | [
"MIT"
] | usausa/Smart-Net-Navigation | Smart.Navigation/Navigation/Mappers/ITypeConstraint.cs | 144 | C# |
//
// AmountEntryViewModel.cs
//
// Copyright (c) 2022 HODL Wallet
//
// 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.Diagnostics;
using System.Linq;
using System.Reactive.Linq;
using NBitcoin;
using ReactiveUI;
using Xamarin.Forms;
using HodlWallet.Core.Services;
using HodlWallet.Core.Utils;
namespace HodlWallet.Core.ViewModels
{
public class AmountEntryViewModel : BaseViewModel
{
string currencySymbol = "₿";
public string CurrencySymbol
{
get { return currencySymbol; }
set { SetProperty(ref currencySymbol, value); }
}
string placeholderAmount = "0.00";
public string PlaceholderAmount
{
get { return placeholderAmount; }
set { SetProperty(ref placeholderAmount, value); }
}
string amountText = "";
public string AmountText
{
get { return amountText; }
set
{
try
{
value = NormalizeAmountText(value);
SetProperty(ref amountText, value);
Observable.Start(() =>
{
UpdateAmount();
ValidateWithBalance();
}, RxApp.TaskpoolScheduler);
}
catch (Exception e)
{
Debug.WriteLine($"[AmountText_set] Error: {e}");
}
}
}
Money amount = Money.Zero;
public Money Amount
{
get { return amount; }
set { SetProperty(ref amount, value); }
}
bool trackBalance = false;
Money balance = Money.Zero;
public Money Balance
{
get { return balance; }
set { SetProperty(ref balance, value); }
}
string addressToSend;
public string AddressToSend
{
get { return addressToSend; }
set
{
SetProperty(ref addressToSend, value);
ValidateWithBalance();
}
}
decimal fee = 1;
public decimal Fee
{
get { return fee; }
set
{
SetProperty(ref fee, value);
ValidateWithBalance();
}
}
internal void TrackBalance()
{
if (WalletService.IsStarted) DoTrackBalance();
else WalletService.OnStarted += (_, _) => Device.BeginInvokeOnMainThread(() => DoTrackBalance());
}
void DoTrackBalance()
{
var acc = WalletService.Wallet.CurrentAccount;
Balance = acc.GetBalance();
trackBalance = true;
acc.Txs.CollectionChanged += (_, _) =>
{
Balance = acc.GetBalance();
};
}
void ValidateWithBalance()
{
if (!trackBalance) return;
if (Amount > Balance)
{
MessagingCenter.Send(this, "ShowBalanceError");
return;
}
var success = false;
var fees = 1m;
if (!string.IsNullOrEmpty(addressToSend))
{
try
{
(success, _, fees, _) = WalletService.CreateTransaction(
Amount.ToDecimal(MoneyUnit.BTC), AddressToSend, Fee, string.Empty
);
}
catch (Exception ex)
{
Debug.WriteLine($"[ValidateWithBalance] Error: {ex}");
fees = 144 * Fee;
success = true;
}
}
if (!success)
{
if (Amount > Balance)
MessagingCenter.Send(this, "ShowBalanceError");
else
MessagingCenter.Send(this, "ShowBalanceSuccess");
return;
}
if ((Amount + new Money(fees, MoneyUnit.Satoshi)) > Balance)
MessagingCenter.Send(this, "ShowBalanceError");
else
MessagingCenter.Send(this, "ShowBalanceSuccess");
}
public AmountEntryViewModel()
{
if (WalletService.IsStarted) Setup();
else WalletService.OnStarted += (_, _) => Device.BeginInvokeOnMainThread(() => Setup());
}
void Setup()
{
DisplayCurrencyService
.WhenAnyValue(service => service.CurrencyType)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ => UpdateCurrency(DisplayCurrencyService.FiatCurrencyCode));
DisplayCurrencyService
.WhenAnyValue(service => service.FiatCurrencyCode)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(cc => UpdateCurrency(cc));
}
void UpdateAmount()
{
if (string.IsNullOrEmpty(AmountText))
{
Amount = Money.Zero;
return;
}
var value = AmountText.Split(CurrencySymbol).Last();
if (DisplayCurrencyService.CurrencyType == DisplayCurrencyType.Bitcoin)
{
Amount = Money.Parse(value);
return;
}
var finalAmount = decimal.Parse(value) / GetRate();
Amount = new Money(finalAmount, MoneyUnit.BTC);
}
void UpdateCurrency(string cc)
{
if (string.IsNullOrEmpty(AmountText))
{
if (DisplayCurrencyService.CurrencyType == DisplayCurrencyType.Bitcoin)
{
CurrencySymbol = "₿";
PlaceholderAmount = "0.00000000";
}
else
{
CurrencySymbol = Constants.CURRENCY_SYMBOLS[cc];
PlaceholderAmount = "0.00";
}
return;
}
var rate = GetRate();
string amount;
if (DisplayCurrencyService.CurrencyType == DisplayCurrencyType.Bitcoin)
{
var symbol = Constants.CURRENCY_SYMBOLS[cc];
amount = AmountText.Replace(symbol, string.Empty);
}
else
{
amount = AmountText[1..];
}
if (decimal.TryParse(amount, out var amountDecimal))
{
if (DisplayCurrencyService.CurrencyType == DisplayCurrencyType.Bitcoin)
{
CurrencySymbol = "₿";
PlaceholderAmount = "0.00000000";
AmountText = (amountDecimal / rate).ToString("0.########");
}
else
{
CurrencySymbol = Constants.CURRENCY_SYMBOLS[cc];
PlaceholderAmount = "0.00";
AmountText = (amountDecimal * rate).ToString("0.##");
}
}
}
string NormalizeAmountText(string value)
{
if (string.IsNullOrEmpty(value) || value.Equals(CurrencySymbol))
return string.Empty;
else if (value.Equals("."))
return $"{CurrencySymbol}0.";
else if (value.EndsWith("."))
return value;
else if (!value.StartsWith(CurrencySymbol))
value = $"{CurrencySymbol}{value}";
return value;
}
decimal GetRate()
{
decimal rate;
if (DisplayCurrencyService.FiatCurrencyCode == "USD")
rate = decimal.Parse(PrecioService.Precio.CRaw);
else
rate = (decimal)PrecioService.Rates.FirstOrDefault(r => r.Code == DisplayCurrencyService.FiatCurrencyCode).Rate;
return rate;
}
}
} | 31.709898 | 129 | 0.499946 | [
"MIT"
] | hodlwallet/hodlwallet | HodlWallet/Core/ViewModels/AmountEntryViewModel.cs | 9,299 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using ODataHeroes.Contracts.Controllers;
using ODataHeroes.Contracts.Data.Repositories;
using System.Linq;
namespace ODataHeroes.API.Controllers.OData
{
public class HeroesController : ODataController, IHeroesController
{
private readonly IHeroesRepository _db;
public HeroesController(IUnitOfWork repo)
{
_db = repo.Heroes;
}
[EnableQuery]
[HttpGet("odata/Heroes")]
[HttpGet("odata/Heroes/$count")]
public IActionResult Get()
{
var x = _db.GetAll().AsQueryable();
return Ok(x);
}
[EnableQuery]
[HttpGet("odata/Heroes({id})")]
[HttpGet("odata/Heroes/{id}")]
public IActionResult Get(int id)
{
return Ok(_db.GetHeroes(id));
}
}
} | 26.305556 | 70 | 0.62302 | [
"MIT"
] | dbphoton/odataheroes | ODataHeroes.API/Controllers/OData/HeroesController.cs | 949 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadingManager : Singleton<LoadingManager>
{
public void LoadScene(string InSceneName)
{
StartCoroutine(CoroutineLoadScene(InSceneName));
}
IEnumerator CoroutineLoadScene(string InSceneName)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Loading");
while (!asyncLoad.isDone)
{
yield return null;
}
//yield return StartCoroutine(CoroutineLoadSceneComplete());
yield return new WaitForSeconds(1.0f);
AssetManager.GetManager().LoadLevelAsync("scene", InSceneName, false, null);
}
IEnumerator CoroutineLoadSceneComplete()
{
GameObject fadeBG = GameObject.Find("Canvas/BG");
CanvasRenderer cRenderer = fadeBG.GetComponent<CanvasRenderer>();
float ftime = 1f;
while(ftime > 0f)
{
ftime -= 0.05f;
if (ftime < 0)
ftime = 0;
cRenderer.SetAlpha(ftime);
yield return null;
}
}
}
| 25.955556 | 84 | 0.615582 | [
"MIT"
] | magemjmj/hide-and-seek | Assets/Code/Manager/LoadingManager.cs | 1,170 | C# |
#pragma checksum "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\Account\Manage\PersonalData.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "65755186d74c449a5d1168061a19ca135d7c8024"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_Manage_PersonalData), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/PersonalData.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\_ViewImports.cshtml"
using Auth.System.MVC.WebApp.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\_ViewImports.cshtml"
using Auth.System.MVC.WebApp.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\_ViewImports.cshtml"
using Auth.System.MVC.WebApp.Areas.Identity.Data;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using Auth.System.MVC.WebApp.Areas.Identity.Pages.Account;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml"
using Auth.System.MVC.WebApp.Areas.Identity.Pages.Account.Manage;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"65755186d74c449a5d1168061a19ca135d7c8024", @"/Areas/Identity/Pages/Account/Manage/PersonalData.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"efeaad3c27a160b50e148456cad647e14eb48ffe", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d12713204a893b1f316fe66c49bd3a1b16760c73", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c28c9f7be1ba824be948049b1a5c5fe0d2595e34", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_Manage_PersonalData : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("download-data"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "DownloadPersonalData", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-group"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("delete"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "DeletePersonalData", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-secondary"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ValidationScriptsPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 3 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\Account\Manage\PersonalData.cshtml"
ViewData["Title"] = "Personal Data";
ViewData["ActivePage"] = ManageNavPages.PersonalData;
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h4>");
#nullable restore
#line 8 "C:\Users\ramos\source\repos\Authentication.System.MVC.CSharp\Auth.System.MVC.WebApp\Areas\Identity\Pages\Account\Manage\PersonalData.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral(@"</h4>
<div class=""row"">
<div class=""col-md-6"">
<p>Your account contains personal data that you have given us. This page allows you to download or delete that data.</p>
<p>
<strong>Deleting this data will permanently remove your account, and this cannot be recovered.</strong>
</p>
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "65755186d74c449a5d1168061a19ca135d7c80248845", async() => {
WriteLiteral("\r\n <button class=\"btn btn-primary\" type=\"submit\">Download</button>\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Page = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n <p>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "65755186d74c449a5d1168061a19ca135d7c802410758", async() => {
WriteLiteral("Delete");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </p>\r\n </div>\r\n</div>\r\n\r\n");
DefineSection("Scripts", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "65755186d74c449a5d1168061a19ca135d7c802412220", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
}
);
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<PersonalDataModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<PersonalDataModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<PersonalDataModel>)PageContext?.ViewData;
public PersonalDataModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 72.285 | 355 | 0.76565 | [
"MIT"
] | proRamos/Authentication.System.MVC.CSharp | Auth.System.MVC.WebApp/obj/Debug/net5.0/Razor/Areas/Identity/Pages/Account/Manage/PersonalData.cshtml.g.cs | 14,457 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MLKitBuildAll")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Microsoft Corporation")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Copyright © Microsoft Corporation")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 36.551724 | 81 | 0.74717 | [
"MIT"
] | 4brunu/GooglePlayServicesComponents | samples/all/MLKitBuildAll/Properties/AssemblyInfo.cs | 1,063 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.WindowsAPICodePack.Dialogs;
namespace CitraV3DSManager
{
public partial class mainWin : Form
{
private firstSetup fSetup;
private setName nameSetter = new setName();
private StreamWriter sw;
private StreamReader sr;
public string CitraFolder = "";
public string cName = "";
public mainWin()
{
InitializeComponent();
toggleUIActive(false);
}
/// <summary>
/// Selects Citra Folder and initilizes Virtual System List (Button Click)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_uF_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
tb_uF.Text = dialog.FileName;
CitraFolder = dialog.FileName;
if (!Directory.Exists(Path.Combine(CitraFolder, "v3DS")))
{
MessageBox.Show("It looks like, you're using this Software for the first time. In the following Window, you can Name your current Setup");
fSetup = new firstSetup();
fSetup.ShowDialog();
Directory.CreateDirectory(Path.Combine(CitraFolder, "v3DS"));
sw = new StreamWriter(Path.Combine(CitraFolder, "v3DS", "current.txt"), false, Encoding.UTF8);
sw.WriteLine(fSetup.setName);
sw.Flush();
sw.Close();
}
cName = readFile(Path.Combine(CitraFolder, "v3DS", "current.txt"));
lb_V3DS.Items.Clear();
lb_V3DS.Items.AddRange(getAllVSystems());
lbl_currentName.Text = cName;
toggleUIActive(true);
}
}
/// <summary>
/// Switches between selected v3DS and current v3DS
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_select_Click(object sender, EventArgs e)
{
if (Directory.Exists(Path.Combine(CitraFolder, "v3DS", cName)))
{
MessageBox.Show("Can't switch v3DS because current Name is already occupied!", "Switch blocked!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (lb_V3DS.SelectedIndex < 0)
{
MessageBox.Show("Can't switch without selecting new v3DS!", "Switch blocked!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
string nName = (string)lb_V3DS.SelectedItem;
Directory.CreateDirectory(Path.Combine(CitraFolder, "v3DS", cName));
Directory.Move(Path.Combine(CitraFolder, "nand"), Path.Combine(CitraFolder, "v3DS", cName, "nand"));
Directory.Move(Path.Combine(CitraFolder, "sdmc"), Path.Combine(CitraFolder, "v3DS", cName, "sdmc"));
if (Directory.Exists(Path.Combine(CitraFolder, "v3DS", nName, "nand")))
{
Directory.Move(Path.Combine(CitraFolder, "v3DS", nName, "nand"), Path.Combine(CitraFolder, "nand"));
}
else
{
Directory.CreateDirectory(Path.Combine(CitraFolder, "nand"));
}
if (Directory.Exists(Path.Combine(CitraFolder, "v3DS", nName, "sdmc")))
{
Directory.Move(Path.Combine(CitraFolder, "v3DS", nName, "sdmc"), Path.Combine(CitraFolder, "sdmc"));
}
else
{
Directory.CreateDirectory(Path.Combine(CitraFolder, "sdmc"));
}
Directory.Delete(Path.Combine(CitraFolder, "v3DS", nName));
sw = new StreamWriter(Path.Combine(CitraFolder, "v3DS", "current.txt"), false, Encoding.UTF8);
sw.WriteLine(nName);
sw.Flush();
sw.Close();
cName = nName;
lb_V3DS.Items.Clear();
lb_V3DS.Items.AddRange(getAllVSystems());
lbl_currentName.Text = cName;
}
}
/// <summary>
/// Adds an Empty v3DS
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_addEmpty_Click(object sender, EventArgs e)
{
nameSetter.title = "Add Empty System";
nameSetter.ShowDialog();
if (nameSetter.setOutput)
{
Directory.CreateDirectory(Path.Combine(CitraFolder, "v3DS", nameSetter.output));
lb_V3DS.Items.Clear();
lb_V3DS.Items.AddRange(getAllVSystems());
}
}
/// <summary>
/// Duplicates selected v3DS
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_duplicate_Click(object sender, EventArgs e)
{
string copname = (string)lb_V3DS.SelectedItem;
if (lb_V3DS.SelectedIndex < 0)
{
MessageBox.Show("Can't do this action with a selection");
}
else
{
nameSetter.title = "Rename Current v3DS";
nameSetter.ShowDialog();
if (nameSetter.setOutput)
{
string nName = nameSetter.output;
DirectoryCopy(Path.Combine(CitraFolder, "v3DS", copname), Path.Combine(CitraFolder, "v3DS", nName));
lb_V3DS.Items.Clear();
lb_V3DS.Items.AddRange(getAllVSystems());
}
}
}
/// <summary>
/// Deletes the Selected v3DS
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_del_Click(object sender, EventArgs e)
{
string delname = (string)lb_V3DS.SelectedItem;
if (lb_V3DS.SelectedIndex < 0)
{
MessageBox.Show("Can't do this action with a selection");
}
else
{
var msgBoxRes = MessageBox.Show("This will permanently remove all Data stored within this Virtual 3DS!\nAre you sure, you want to continue?", "Irreversable Action", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (msgBoxRes == DialogResult.Yes)
{
Directory.Delete(Path.Combine(CitraFolder, "v3DS", delname), true);
lb_V3DS.Items.Clear();
lb_V3DS.Items.AddRange(getAllVSystems());
}
}
}
/// <summary>
/// Renames the current v3DS
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_rename_Click(object sender, EventArgs e)
{
nameSetter.title = "Rename Current v3DS";
nameSetter.ShowDialog();
if (nameSetter.setOutput)
{
cName = nameSetter.output;
sw = new StreamWriter(Path.Combine(CitraFolder, "v3DS", "current.txt"), false, Encoding.UTF8);
sw.WriteLine(cName);
sw.Flush();
sw.Close();
lbl_currentName.Text = cName;
}
}
/// <summary>
/// Toggles UI Button Enabled property
/// </summary>
/// <param name="enabled"></param>
private void toggleUIActive(bool enabled)
{
gb_current.Enabled = enabled;
lb_V3DS.Enabled = enabled;
btn_addEmpty.Enabled = enabled;
btn_del.Enabled = enabled;
btn_duplicate.Enabled = enabled;
btn_select.Enabled = enabled;
}
/// <summary>
/// Returns a string array of existing v3DS 8excluding current v3DS
/// </summary>
/// <returns></returns>
private string[] getAllVSystems()
{
List<string> allSystems = new List<string>();
var otherVirtuals = Directory.GetDirectories(Path.Combine(CitraFolder, "v3DS"));
for (int i = 0; i < otherVirtuals.Length; i++)
{
allSystems.Add(new DirectoryInfo(otherVirtuals[i]).Name);
}
return allSystems.ToArray();
}
/// <summary>
/// Reads contents of any File on the disk
/// </summary>
/// <param name="path">Pth to File</param>
/// <param name="ignoreNL">Wether or not New Lines should be included in output</param>
/// <returns></returns>
private string readFile(string path, bool ignoreNL=true)
{
sr = new StreamReader(path, Encoding.UTF8);
string output = "";
while (!sr.EndOfStream)
{
if (output != "" && !ignoreNL)
{
output += "\n";
}
output += sr.ReadLine();
}
sr.Close();
return output;
}
/// <summary>
/// Copys Folder with all of it's contents recursively
/// </summary>
/// <param name="sourceDirName">Source Directory</param>
/// <param name="destDirName">Destination Path</param>
private void DirectoryCopy(string sourceDirName, string destDirName)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// Copy subdirectories and their contents to new location.
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath);
}
}
}
}
| 35.647799 | 230 | 0.52717 | [
"MIT"
] | Chickenbreadlp/CitraV3DSManager | CitraV3DSManager/mainWin.cs | 11,338 | C# |
using TCC.Data;
using TCC.UI.Windows.Widgets;
namespace TCC.Settings.WindowSettings
{
public class NotificationAreaSettings : WindowSettingsBase
{
private int _defaultNotificationDuration;
public int MaxNotifications { get; set; }
public int DefaultNotificationDuration
{
get => _defaultNotificationDuration;
set
{
if (_defaultNotificationDuration == value) return;
_defaultNotificationDuration = value;
N();
}
}
public NotificationAreaSettings()
{
_visible = true;
_clickThruMode = ClickThruMode.Never;
_scale = 1;
_autoDim = false;
_dimOpacity = 1;
_showAlways = true;
_enabled = true;
_allowOffScreen = false;
PerClassPosition = false;
Positions = new ClassPositions(0, .5, ButtonsPosition.Above);
MaxNotifications = 5;
DefaultNotificationDuration = 5;
}
}
} | 28.447368 | 73 | 0.558742 | [
"MIT"
] | Foglio1024/Tera-custom-cooldowns | TCC.Core/Settings/WindowSettings/NotificationAreaSettings.cs | 1,083 | C# |
using System.Collections.Generic;
using System.Linq;
namespace fs4net.Framework.Impl
{
internal class FoldersParser
{
private readonly string _relativePath;
private readonly Validator _validator;
private readonly string _canonifiedPathWithoutBackslashes;
private bool HasDrive { get; set; }
private bool HasFilename { get; set; }
public FoldersParser(string relativePath, Validator validator, bool hasDrive, bool hasFilename)
{
_relativePath = relativePath;
_validator = validator;
HasDrive = hasDrive;
HasFilename = hasFilename;
ValidateStartAndEnd();
_canonifiedPathWithoutBackslashes = Canonify(PathWithoutStartingAndEndingBackslashes);
ValidateAscensionLevel();
}
public string Canonified
{
get
{
var appendLeadingBackslash = HasLeadingBackslash && _canonifiedPathWithoutBackslashes.Length > 0;
return string.Format("{0}{1}{2}",
appendLeadingBackslash ? "\\" : string.Empty,
_canonifiedPathWithoutBackslashes,
HasEndingBackslash ? "\\" : string.Empty);
}
}
private bool HasLeadingBackslash
{
get
{
return
_relativePath.Length > 1 && // Not to confuse it with ending backslash
_relativePath.StartsWith(@"\");
}
}
private bool HasEndingBackslash
{
get { return _relativePath.EndsWith(@"\"); }
}
protected string PathWithoutStartingAndEndingBackslashes
{
get
{
int start = HasLeadingBackslash ? 1 : 0;
int endDistance = HasEndingBackslash ? 1 : 0;
return _relativePath.Substring(start, _relativePath.Length - start - endDistance);
}
}
private void ValidateStartAndEnd()
{
_validator.Ensure<InvalidPathException>(!HasLeadingBackslash || HasDrive, "The path '{0}' starts with a '\\' which is not allowed.");
_validator.Ensure<InvalidPathException>(!HasEndingBackslash || HasFilename, "The path '{0}' ends with a '\\' which is not allowed.");
if (HasDrive && _relativePath.Length > 1 && !HasLeadingBackslash)
{
_validator.AddError<InvalidPathException>("Expected a '\\' after the drive but found a '{1}' in the path '{0}'.", _relativePath.First());
}
}
private string Canonify(string relativePath)
{
if (relativePath.Length == 0) return relativePath;
var folders = TokenizeToFolders(relativePath);
return folders.Canonify().MergeToPath();
}
private IEnumerable<string> TokenizeToFolders(string relativePath)
{
var folders = relativePath.Split(new[] { '\\' });
foreach (string folder in folders)
{
ValidateFolderName(folder);
yield return folder;
}
}
private void ValidateFolderName(string folder)
{
_validator.Ensure<InvalidPathException>(folder.Length > 0, "The path '{0}' contains an empty folder which is not allowed");
if (_validator.HasError) return; // to avoid empty string logic below
_validator.Ensure<InvalidPathException>(!char.IsWhiteSpace(folder.Last()), "The folder '{1}' in the path '{0}' ends with a whitespace which is not allowed.", folder);
_validator.Ensure<InvalidPathException>(!folder.EndsWith(".") || folder == "." || folder == "..", "The folder '{1}' in the path '{0}' ends with a dot which is not allowed.", folder);
FolderUtils.ValidatePathCharacters(folder, "folder", _validator);
}
private void ValidateAscensionLevel()
{
_validator.Ensure<InvalidPathException>(!HasDrive || !_canonifiedPathWithoutBackslashes.StartsWith(".."), "The path '{0}' ascends into a folder above the root level.");
}
public static FoldersParser WithDriveAndFilename(string relativePath, Validator validator)
{
return new FoldersParser(relativePath, validator, true, true);
}
public static FoldersParser WithDrive(string relativePath, Validator validator)
{
return new FoldersParser(relativePath, validator, true, false);
}
public static FoldersParser WithFilename(string relativePath, Validator validator)
{
return new FoldersParser(relativePath, validator, false, true);
}
public static FoldersParser WithFolderOnly(string relativePath, Validator validator)
{
return new FoldersParser(relativePath, validator, false, false);
}
}
} | 40.488189 | 195 | 0.580124 | [
"Apache-2.0"
] | toroso/fs4net | framework/fs4net.Framework/Impl/FoldersParser.cs | 5,142 | 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 Hotcakes.Modules.Core.Admin.Controls {
public partial class ProductReviewEditor {
/// <summary>
/// lblProductName 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.Label lblProductName;
/// <summary>
/// lblUserName 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.Label lblUserName;
/// <summary>
/// lblReviewDate 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.Label lblReviewDate;
/// <summary>
/// lstRating 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.DropDownList lstRating;
/// <summary>
/// KarmaField 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.TextBox KarmaField;
/// <summary>
/// chkApproved 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.CheckBox chkApproved;
/// <summary>
/// DescriptionField 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.TextBox DescriptionField;
/// <summary>
/// btnOK 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.LinkButton btnOK;
/// <summary>
/// btnCancel 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.LinkButton btnCancel;
}
}
| 34.989691 | 84 | 0.537124 | [
"MIT"
] | HotcakesCommerce/core | Website/DesktopModules/Hotcakes/Core/Admin/Controls/ProductReviewEditor.ascx.designer.cs | 3,396 | C# |
using System.Collections.Generic;
namespace DFrame.Kubernetes.Models
{
public class V1CsiVolumeSource
{
public string Driver { get; set; }
public string FsType { get; set; }
public V1LocalObjectReference NodePublishSecretRef { get; set; }
public bool? ReadOnly { get; set; }
public IDictionary<string, string> VolumeAttributes { get; set; }
}
}
| 28.5 | 73 | 0.66416 | [
"MIT"
] | Cysharp/DFrame | src/DFrame.Kubernetes/Models/V1CSIVolumeSource.cs | 401 | C# |
using PuyoTools.Modules.Compression;
using PuyoTools.Modules.Texture;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace PuyoTools.Modules.Archive
{
public class TxdStorybookArchive : ArchiveBase
{
private static readonly byte[] magicCode = { (byte)'T', (byte)'X', (byte)'A', (byte)'G' };
public override ArchiveReader Open(Stream source)
{
return new TxdStorybookArchiveReader(source);
}
public override ArchiveWriter Create(Stream destination)
{
return new TxdStorybookArchiveWriter(destination);
}
/// <summary>
/// Returns if this codec can read the data in <paramref name="source"/>.
/// </summary>
/// <param name="source">The data to read.</param>
/// <returns>True if the data can be read, false otherwise.</returns>
public static bool Identify(Stream source)
{
var startPosition = source.Position;
using (var reader = new BinaryReader(source, Encoding.UTF8, true))
{
return source.Length - startPosition > 16
&& reader.At(startPosition, x => x.ReadBytes(magicCode.Length)).SequenceEqual(magicCode);
}
}
}
#region Archive Reader
public class TxdStorybookArchiveReader : ArchiveReader
{
public TxdStorybookArchiveReader(Stream source) : base(source)
{
source.Position += 6;
var fileCount = PTStream.ReadInt16BE(source);
entries = new List<ArchiveEntry>(fileCount);
for (int i = 0; i < fileCount; i++)
{
var offset = PTStream.ReadUInt32BE(source);
var length = PTStream.ReadInt32BE(source);
var fileName = PTStream.ReadCString(source, 32);
fileName = string.IsNullOrWhiteSpace(fileName) ? fileName : Path.ChangeExtension(fileName, "GVR");
entries.Add(new ArchiveEntry(this, startOffset + offset, length, fileName));
}
}
}
#endregion
public class TxdStorybookArchiveWriter : ArchiveWriter
{
public TxdStorybookArchiveWriter(Stream destination) : base(destination) { }
/// <inheritdoc/>
public override ArchiveEntry CreateEntry(Stream source, string entryName)
{
// Only GVR textures can be added to a Sonic Storybook TXD archive. If this is not a GVR texture, throw an exception.
if (!GvrTexture.Identify(source))
{
throw new FileRejectedException("Sonic Storybook TXD archives can only contain GVR textures.");
}
return base.CreateEntry(source, entryName.ToUpper());
}
protected override void WriteFile()
{
const int blockSize = 64;
var offsetList = new int[entries.Count];
destination.WriteByte((byte)'T');
destination.WriteByte((byte)'X');
destination.WriteByte((byte)'A');
destination.WriteByte((byte)'G');
PTStream.WriteInt32BE(destination, entries.Count);
var offset = PTMethods.RoundUp(0x8 + (entries.Count * 0x28), blockSize);
for (int i = 0; i < entries.Count; i++)
{
var length = entries[i].Length;
offsetList[i] = offset;
PTStream.WriteInt32BE(destination, offset);
PTStream.WriteInt32BE(destination, length);
PTStream.WriteCString(destination, Path.GetFileNameWithoutExtension(entries[i].Name), 32);
offset += PTMethods.RoundUp(length, blockSize);
}
for (int i = 0; i < entries.Count; i++)
{
// Call the entry writing event
OnEntryWriting(new ArchiveEntryWritingEventArgs(entries[i]));
destination.Position = offsetList[i];
PTStream.CopyToPadded(entries[i].Open(), destination, blockSize, 0);
// Call the entry written event
OnEntryWritten(new ArchiveEntryWrittenEventArgs(entries[i]));
}
}
}
} | 35.366667 | 129 | 0.590245 | [
"MIT"
] | SwitchKaze/puyotools | src/PuyoTools.Modules/Archive/Formats/TxdStorybookArchive.cs | 4,246 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Voxul.Meshing;
using Voxul.Utilities;
namespace Voxul.Edit
{
[Serializable]
internal class PrimitiveTool : VoxelPainterTool
{
public override GUIContent Icon => EditorGUIUtility.IconContent("CreateAddNew");
public static Gradient DefaultGradient = new Gradient
{
colorKeys = new[]
{
new GradientColorKey
{
color = Color.white,
time = 0,
},
new GradientColorKey
{
color = Color.black,
time = 0,
},
}
};
private double m_lastAdd;
[SerializeField]
private VoxelRenderer m_cursor;
public sbyte CurrentLayer
{
get
{
return EditorPrefUtility.GetPref("VoxelPainter_CurrentLayer", default(sbyte));
}
set
{
EditorPrefUtility.SetPref("VoxelPainter_CurrentLayer", value);
}
}
public override void OnEnable()
{
if (!m_cursor)
{
m_cursor = new GameObject("AddTool_Cursor").AddComponent<VoxelRenderer>();
m_cursor.gameObject.hideFlags = HideFlags.HideAndDontSave;
m_cursor.Mesh = ScriptableObject.CreateInstance<VoxelMesh>();
m_cursor.GenerateCollider = false;
m_cursor.enabled = false;
m_cursor.SetupComponents(false);
m_cursor.gameObject.AddComponent<AutoDestroyer>();
}
base.OnEnable();
}
public override void OnDisable()
{
if (m_cursor)
{
m_cursor.gameObject.SafeDestroy();
m_cursor = null;
}
base.OnDisable();
}
protected override EPaintingTool ToolID => EPaintingTool.Add;
protected override bool GetVoxelDataFromPoint(VoxelPainter painter, VoxelRenderer renderer, MeshCollider collider, Vector3 hitPoint,
Vector3 hitNorm, int triIndex, out HashSet<VoxelCoordinate> selection, out EVoxelDirection hitDir)
{
if (Event.current.alt)
{
m_cursor?.gameObject.SetActive(false);
return base.GetVoxelDataFromPoint(painter, renderer, collider, hitPoint, hitNorm, triIndex, out selection, out hitDir);
}
hitPoint = renderer.transform.worldToLocalMatrix.MultiplyPoint3x4(hitPoint);
hitNorm = renderer.transform.worldToLocalMatrix.MultiplyVector(hitNorm);
VoxelCoordinate.VectorToDirection(hitNorm, out hitDir);
var scale = VoxelCoordinate.LayerToScale(CurrentLayer);
var singleCoord = VoxelCoordinate.FromVector3(hitPoint + hitNorm * (scale / 2f) * (collider ? 1 : 0), CurrentLayer);
selection = new HashSet<VoxelCoordinate>() { singleCoord };
DoMeshCursorPreview(renderer, selection);
return true;
}
private void DoMeshCursorPreview(VoxelRenderer renderer, IEnumerable<VoxelCoordinate> selection)
{
if (!m_cursor || !m_cursor.Mesh)
{
OnEnable();
}
m_cursor.gameObject.SetActive(true);
m_cursor.GetComponent<AutoDestroyer>().KeepAlive();
m_cursor.transform.ApplyTRSMatrix(renderer.transform.localToWorldMatrix);
if (!m_cursor.Mesh.Voxels.Keys.SequenceEqual(selection))
{
m_cursor.Mesh.Voxels.Clear();
foreach (var s in selection)
{
//var v = CurrentBrush.Copy();
//m_cursor.Mesh.Voxels.AddSafe(new Voxel { Coordinate = s, Material = v });
}
m_cursor.Mesh.Invalidate();
m_cursor.Invalidate(true, false);
}
}
protected override bool DrawSceneGUIInternal(VoxelPainter voxelPainter, VoxelRenderer renderer,
Event currentEvent, HashSet<VoxelCoordinate> selection, EVoxelDirection hitDir, Vector3 hitPos)
{
if (currentEvent.isMouse && currentEvent.type == EventType.MouseUp && currentEvent.button == 0)
{
if (EditorApplication.timeSinceStartup < m_lastAdd + .5f)
{
return false;
}
m_lastAdd = EditorApplication.timeSinceStartup;
var creationList = new HashSet<VoxelCoordinate>(selection);
if (currentEvent.control && currentEvent.shift)
{
var bounds = voxelPainter.CurrentSelection.GetBounds();
bounds.Encapsulate(selection.GetBounds());
foreach (VoxelCoordinate coord in bounds.GetVoxelCoordinates(CurrentLayer))
{
creationList.Add(coord);
}
}
voxelPainter.SetSelection(CreateVoxel(creationList, renderer).ToList());
if (m_cursor)
{
m_cursor.gameObject.SafeDestroy();
}
UseEvent(currentEvent);
}
return false;
}
protected override int GetToolWindowHeight()
{
return base.GetToolWindowHeight() + 40;
}
protected override void DrawToolLayoutGUI(Rect rect, Event currentEvent, VoxelPainter voxelPainter)
{
base.DrawToolLayoutGUI(rect, currentEvent, voxelPainter);
EditorGUILayout.BeginHorizontal();
GUILayout.Label(EditorGUIUtility.IconContent("d_ToggleUVOverlay")
.WithTooltip("Current Layer"), EditorStyles.miniLabel, GUILayout.Width(25));
if (GUILayout.Button("-", EditorStyles.miniButtonLeft))
{
CurrentLayer--;
}
CurrentLayer = (sbyte)EditorGUILayout.IntField((int)CurrentLayer, GUILayout.Width(32));
if (GUILayout.Button("+", EditorStyles.miniButtonLeft))
{
CurrentLayer++;
}
EditorGUILayout.EndHorizontal();
}
private IEnumerable<VoxelCoordinate> CreateVoxel(IEnumerable<VoxelCoordinate> coords, VoxelRenderer renderer)
{
foreach (var brushCoord in coords)
{
yield break;
}
renderer.Mesh.Invalidate();
renderer.Invalidate(true, true);
}
}
} | 28.362162 | 134 | 0.718506 | [
"Apache-2.0"
] | cowtrix/voxul | Scripts/Editor/Tools/PrimitiveTool.cs | 5,249 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Iot.Device.RadioReceiver
{
/// <summary>
/// TEA5767 FM frequency range.
/// </summary>
public enum FrequencyRange
{
/// <summary>
/// 76MHz - 90MHz
/// </summary>
Japan,
/// <summary>
/// 87MHz - 108MHz
/// </summary>
Other
}
}
| 21.181818 | 71 | 0.549356 | [
"MIT"
] | CarlosSardo/nanoFramework.IoT.Device | devices/RadioReceiver/Devices/Tea5767/FrequencyRange.cs | 466 | C# |
/*
* Copyright (C) 2011 The Libphonenumber Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace PhoneNumbers
{
/*
* Utility for international short phone numbers, such as short codes and emergency numbers. Note
* most commercial short numbers are not handled here, but by the PhoneNumberUtil.
*
* @author Shaopeng Jia
*/
public class ShortNumberUtil
{
private static PhoneNumberUtil phoneUtil;
public ShortNumberUtil()
{
phoneUtil = PhoneNumberUtil.GetInstance();
}
// @VisibleForTesting
public ShortNumberUtil(PhoneNumberUtil util)
{
phoneUtil = util;
}
/**
* Returns true if the number might be used to connect to an emergency service in the given
* region.
*
* This method takes into account cases where the number might contain formatting, or might have
* additional digits appended (when it is okay to do that in the region specified).
*
* @param number the phone number to test
* @param regionCode the region where the phone number is being dialed
* @return if the number might be used to connect to an emergency service in the given region.
*/
public bool ConnectsToEmergencyNumber(String number, String regionCode)
{
return MatchesEmergencyNumberHelper(number, regionCode, true /* allows prefix match */);
}
/**
* Returns true if the number exactly matches an emergency service number in the given region.
*
* This method takes into account cases where the number might contain formatting, but doesn't
* allow additional digits to be appended.
*
* @param number the phone number to test
* @param regionCode the region where the phone number is being dialed
* @return if the number exactly matches an emergency services number in the given region.
*/
public bool IsEmergencyNumber(String number, String regionCode)
{
return MatchesEmergencyNumberHelper(number, regionCode, false /* doesn't allow prefix match */);
}
private bool MatchesEmergencyNumberHelper(String number, String regionCode,
bool allowPrefixMatch)
{
number = PhoneNumberUtil.ExtractPossibleNumber(number);
if (PhoneNumberUtil.PlusCharsPattern.MatchBeginning(number).Success)
{
// Returns false if the number starts with a plus sign. We don't believe dialing the country
// code before emergency numbers (e.g. +1911) works, but later, if that proves to work, we can
// add additional logic here to handle it.
return false;
}
var metadata = phoneUtil.GetMetadataForRegion(regionCode);
if (metadata == null || !metadata.HasEmergency)
{
return false;
}
var emergencyNumberPattern =
new PhoneRegex(metadata.Emergency.NationalNumberPattern);
var normalizedNumber = PhoneNumberUtil.NormalizeDigitsOnly(number);
// In Brazil, it is impossible to append additional digits to an emergency number to dial the
// number.
return (!allowPrefixMatch || regionCode.Equals("BR"))
? emergencyNumberPattern.MatchAll(normalizedNumber).Success
: emergencyNumberPattern.MatchBeginning(normalizedNumber).Success;
}
}
}
| 41.514851 | 111 | 0.63606 | [
"Apache-2.0"
] | dchankhour/libphonenumber-csharp | csharp/PhoneNumbers/ShortNumberUtil.cs | 4,195 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Core.Manifest
{
/// <summary>
/// Parses the Main.js file and replaces all tokens accordingly.
/// </summary>
internal class ManifestParser
{
private readonly DirectoryInfo _pluginsDir;
//used to strip comments
private static readonly Regex CommentsSurround = new Regex(@"/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/", RegexOptions.Compiled);
private static readonly Regex CommentsLine = new Regex(@"//.*?$", RegexOptions.Compiled | RegexOptions.Multiline);
public ManifestParser(DirectoryInfo pluginsDir)
{
if (pluginsDir == null) throw new ArgumentNullException("pluginsDir");
_pluginsDir = pluginsDir;
}
/// <summary>
/// Parse the property editors from the json array
/// </summary>
/// <param name="jsonEditors"></param>
/// <returns></returns>
internal static IEnumerable<PropertyEditor> GetPropertyEditors(JArray jsonEditors)
{
return JsonConvert.DeserializeObject<IEnumerable<PropertyEditor>>(
jsonEditors.ToString(),
new PropertyEditorConverter(),
new PreValueFieldConverter());
}
/// <summary>
/// Parse the property editors from the json array
/// </summary>
/// <param name="jsonEditors"></param>
/// <returns></returns>
internal static IEnumerable<ParameterEditor> GetParameterEditors(JArray jsonEditors)
{
return JsonConvert.DeserializeObject<IEnumerable<ParameterEditor>>(
jsonEditors.ToString(),
new ParameterEditorConverter());
}
/// <summary>
/// Get all registered manifests
/// </summary>
/// <returns></returns>
public IEnumerable<PackageManifest> GetManifests()
{
//get all Manifest.js files in the appropriate folders
var manifestFileContents = GetAllManfifestFileContents(_pluginsDir);
return CreateManifests(manifestFileContents.ToArray());
}
/// <summary>
/// Get the file contents from all declared manifest files
/// </summary>
/// <param name="currDir"></param>
/// <returns></returns>
private IEnumerable<string> GetAllManfifestFileContents(DirectoryInfo currDir)
{
var depth = FolderDepth(_pluginsDir, currDir);
if (depth < 1)
{
var dirs = currDir.GetDirectories();
var result = new List<string>();
foreach (var d in dirs)
{
result.AddRange(GetAllManfifestFileContents(d));
}
return result;
}
//look for files here
return currDir.GetFiles("Package.manifest")
.Select(f => File.ReadAllText(f.FullName))
.ToList();
}
/// <summary>
/// Get the folder depth compared to the base folder
/// </summary>
/// <param name="baseDir"></param>
/// <param name="currDir"></param>
/// <returns></returns>
internal static int FolderDepth(DirectoryInfo baseDir, DirectoryInfo currDir)
{
var removed = currDir.FullName.Remove(0, baseDir.FullName.Length).TrimStart('\\').TrimEnd('\\');
return removed.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
/// <summary>
/// Creates a list of PropertyEditorManifest from the file contents of each manifest file
/// </summary>
/// <param name="manifestFileContents"></param>
/// <returns></returns>
/// <remarks>
/// This ensures that comments are removed (but they have to be /* */ style comments
/// and ensures that virtual paths are replaced with real ones
/// </remarks>
internal static IEnumerable<PackageManifest> CreateManifests(params string[] manifestFileContents)
{
var result = new List<PackageManifest>();
foreach (var m in manifestFileContents)
{
if (m.IsNullOrWhiteSpace()) continue;
//remove any comments first
var replaced = CommentsSurround.Replace(m, match => " ");
replaced = CommentsLine.Replace(replaced, match => "");
JObject deserialized;
try
{
deserialized = JsonConvert.DeserializeObject<JObject>(replaced);
}
catch (Exception ex)
{
LogHelper.Error<ManifestParser>("An error occurred parsing manifest with contents: " + m, ex);
continue;
}
//validate the javascript
var init = deserialized.Properties().Where(x => x.Name == "javascript").ToArray();
if (init.Length > 1)
{
throw new FormatException("The manifest is not formatted correctly contains more than one 'javascript' element");
}
//validate the css
var cssinit = deserialized.Properties().Where(x => x.Name == "css").ToArray();
if (cssinit.Length > 1)
{
throw new FormatException("The manifest is not formatted correctly contains more than one 'css' element");
}
//validate the property editors section
var propEditors = deserialized.Properties().Where(x => x.Name == "propertyEditors").ToArray();
if (propEditors.Length > 1)
{
throw new FormatException("The manifest is not formatted correctly contains more than one 'propertyEditors' element");
}
var jConfig = init.Any() ? (JArray)deserialized["javascript"] : new JArray();
ReplaceVirtualPaths(jConfig);
var cssConfig = cssinit.Any() ? (JArray)deserialized["css"] : new JArray();
ReplaceVirtualPaths(cssConfig);
//replace virtual paths for each property editor
if (deserialized["propertyEditors"] != null)
{
foreach (JObject p in deserialized["propertyEditors"])
{
if (p["editor"] != null)
{
ReplaceVirtualPaths((JObject) p["editor"]);
}
if (p["preValues"] != null)
{
ReplaceVirtualPaths((JObject)p["preValues"]);
}
}
}
var manifest = new PackageManifest()
{
JavaScriptInitialize = jConfig,
StylesheetInitialize = cssConfig,
PropertyEditors = propEditors.Any() ? (JArray)deserialized["propertyEditors"] : new JArray(),
ParameterEditors = propEditors.Any() ? (JArray)deserialized["parameterEditors"] : new JArray()
};
result.Add(manifest);
}
return result;
}
/// <summary>
/// Replaces any virtual paths found in properties
/// </summary>
/// <param name="jarr"></param>
private static void ReplaceVirtualPaths(JArray jarr)
{
foreach (var i in jarr)
{
ReplaceVirtualPaths(i);
}
}
/// <summary>
/// Replaces any virtual paths found in properties
/// </summary>
/// <param name="jToken"></param>
private static void ReplaceVirtualPaths(JToken jToken)
{
if (jToken.Type == JTokenType.Object)
{
//recurse
ReplaceVirtualPaths((JObject)jToken);
}
else
{
var value = jToken as JValue;
if (value != null)
{
if (value.Type == JTokenType.String)
{
if (value.Value<string>().StartsWith("~/"))
{
//replace the virtual path
value.Value = IOHelper.ResolveUrl(value.Value<string>());
}
}
}
}
}
/// <summary>
/// Replaces any virtual paths found in properties
/// </summary>
/// <param name="jObj"></param>
private static void ReplaceVirtualPaths(JObject jObj)
{
foreach (var p in jObj.Properties().Select(x => x.Value))
{
ReplaceVirtualPaths(p);
}
}
/// <summary>
/// Merges two json objects together
/// </summary>
/// <param name="receiver"></param>
/// <param name="donor"></param>
/// <param name="keepOriginal">set to true if we will keep the receiver value if the proeprty already exists</param>
/// <remarks>
/// taken from
/// http://stackoverflow.com/questions/4002508/does-c-sharp-have-a-library-for-parsing-multi-level-cascading-json/4002550#4002550
/// </remarks>
internal static void MergeJObjects(JObject receiver, JObject donor, bool keepOriginal = false)
{
foreach (var property in donor)
{
var receiverValue = receiver[property.Key] as JObject;
var donorValue = property.Value as JObject;
if (receiverValue != null && donorValue != null)
{
MergeJObjects(receiverValue, donorValue);
}
else if (receiver[property.Key] == null || !keepOriginal)
{
receiver[property.Key] = property.Value;
}
}
}
/// <summary>
/// Merges the donor array values into the receiver array
/// </summary>
/// <param name="receiver"></param>
/// <param name="donor"></param>
internal static void MergeJArrays(JArray receiver, JArray donor)
{
foreach (var item in donor)
{
if (!receiver.Any(x => x.Equals(item)))
{
receiver.Add(item);
}
}
}
}
} | 39.097222 | 139 | 0.503375 | [
"MIT"
] | AdrianJMartin/Umbraco-CMS | src/Umbraco.Core/Manifest/ManifestParser.cs | 11,262 | C# |
using System;
using System.IO;
using System.Xml;
using Xamarin;
namespace xharness
{
public class UnifiedTarget : iOSTarget
{
// special cases for the BCL applications
public override string Suffix {
get {
return MonoNativeInfo != null ? MonoNativeInfo.FlavorSuffix : "-ios";
}
}
public override string ExtraLinkerDefsSuffix {
get {
return string.Empty;
}
}
protected override string ProjectTypeGuids {
get {
return "{FEACFBD2-3405-455C-9665-78FE426C6842};" + LanguageGuid;
}
}
protected override string BindingsProjectTypeGuids {
get {
return "{8FFB629D-F513-41CE-95D2-7ECE97B6EEEC}";
}
}
protected override string TargetFrameworkIdentifier {
get {
return "Xamarin.iOS";
}
}
protected override string Imports {
get {
return IsFSharp ? "iOS\\Xamarin.iOS.FSharp.targets" : "iOS\\Xamarin.iOS.CSharp.targets";
}
}
protected override string BindingsImports {
get {
return IsFSharp ? "iOS\\Xamarin.iOS.ObjCBinding.FSharp.targets" : "iOS\\Xamarin.iOS.ObjCBinding.CSharp.targets";
}
}
public override string SimulatorArchitectures {
get {
return "i386, x86_64";
}
}
public override string DeviceArchitectures {
get {
if (SupportsBitcode)
return "ARM64";
else
return "ARMv7, ARM64";
}
}
protected override void CalculateName ()
{
if (TargetDirectory.Contains ("bcl-test")) {
if (TestProject.Name.StartsWith ("mscorlib", StringComparison.Ordinal))
Name = TestProject.Name;
else {
var bclIndex = TestProject.Name.IndexOf ("BCL", StringComparison.Ordinal);
// most of the BCL test are grouped, but there are a number that are not, in those cases remove the "{testype} Mono " prefix
Name = (bclIndex == -1) ? TestProject.Name.Substring (TestProject.Name.IndexOf ("Mono ", StringComparison.Ordinal) + "Mono ".Length) : TestProject.Name.Substring (bclIndex);
}
} else
base.CalculateName ();
if (MonoNativeInfo != null)
Name = Name + MonoNativeInfo.FlavorSuffix;
}
protected override string GetMinimumOSVersion (string templateMinimumOSVersion)
{
if (MonoNativeInfo == null)
return templateMinimumOSVersion;
return MonoNativeHelper.GetMinimumOSVersion (DevicePlatform.iOS, MonoNativeInfo.Flavor);
}
protected override int[] UIDeviceFamily {
get {
return new int [] { 1, 2 };
}
}
protected override string AdditionalDefines {
get {
return "XAMCORE_2_0";
}
}
public override bool IsMultiArchitecture {
get {
return true;
}
}
public override string Platform {
get {
return "ios";
}
}
public override string ProjectFileSuffix {
get {
if (MonoNativeInfo != null)
return MonoNativeInfo.FlavorSuffix;
return string.Empty;
}
}
protected override bool SupportsBitcode {
get {
return true;
}
}
protected override void ExecuteInternal ()
{
if (MonoNativeInfo == null)
return;
MonoNativeInfo.AddProjectDefines (inputProject);
inputProject.AddAdditionalDefines ("MONO_NATIVE_IOS");
inputProject.FixInfoPListInclude (Suffix);
inputProject.SetExtraLinkerDefs ("extra-linker-defs" + ExtraLinkerDefsSuffix + ".xml");
Harness.Save (inputProject, ProjectPath);
XmlDocument info_plist = new XmlDocument ();
var target_info_plist = Path.Combine (TargetDirectory, "Info" + Suffix + ".plist");
info_plist.LoadWithoutNetworkAccess (Path.Combine (TargetDirectory, "Info.plist"));
info_plist.SetMinimumOSVersion (GetMinimumOSVersion (info_plist.GetMinimumOSVersion ()));
Harness.Save (info_plist, target_info_plist);
}
}
}
| 23.941176 | 178 | 0.691783 | [
"BSD-3-Clause"
] | FlavioGoncalves-Cayas/xamarin-macios | tests/xharness/UnifiedTarget.cs | 3,665 | C# |
#region License
/* FNA - XNA4 Reimplementation for Desktop Platforms
* Copyright 2009-2015 Ethan Lee and the MonoGame Team
*
* Released under the Microsoft Public License.
* See LICENSE for details.
*/
#endregion
namespace Microsoft.Xna.Framework.Content
{
internal class Int32Reader : ContentTypeReader<int>
{
#region Internal Constructor
internal Int32Reader()
{
}
#endregion
#region Protected Read Method
protected internal override int Read(
ContentReader input,
int existingInstance
) {
return input.ReadInt32();
}
#endregion
}
}
| 17.970588 | 55 | 0.690671 | [
"MIT"
] | elisee/NuclearWinter | FNA/src/Content/ContentReaders/Int32Reader.cs | 611 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
var listOfCars = new List<Car>();
var listOfTrucks = new List<Truck>();
double averageCarHp = 0.00;
double averageTruckHp = 0.00;
string input = Console.ReadLine();
while (input != "End")
{
var inputParts = input
.Split(' ')
.ToArray();
string type = inputParts[0].ToLower();
string model = inputParts[1];
string colour = inputParts[2];
int horsePower = int.Parse(inputParts[3]);
if (type == "car")
{
var car = new Car
{
Model = model,
Colour = colour,
HorsePower = horsePower
};
listOfCars.Add(car);
averageCarHp += car.HorsePower;
}
else // truck
{
var truck = new Truck
{
Model = model,
Colour = colour,
HorsePower = horsePower
};
listOfTrucks.Add(truck);
averageTruckHp += truck.HorsePower;
}
input = Console.ReadLine();
}
string secondInput = Console.ReadLine();
while (secondInput != "Close the Catalogue")
{
CarOrTruck(secondInput, listOfCars, listOfTrucks);
secondInput = Console.ReadLine();
}
// have a problem with NaN if they are equal to 0.00 and I try to round them to 2;
if (averageCarHp == 0.00)
{
Console.WriteLine($"Cars have average horsepower of: {averageCarHp:f2}.");
}
else
{
averageCarHp = Math.Round(averageCarHp / listOfCars.Count, 2);
Console.WriteLine($"Cars have average horsepower of: {averageCarHp:f2}.");
}
if (averageTruckHp == 0.00)
{
Console.WriteLine($"Trucks have average horsepower of: {averageTruckHp:f2}.");
}
else
{
averageTruckHp = Math.Round(averageTruckHp / listOfTrucks.Count, 2);
Console.WriteLine($"Trucks have average horsepower of: {averageTruckHp:f2}.");
}
}
static void CarOrTruck(string secondInput, List<Car> listOfCars, List<Truck> listOfTrucks)
{
bool isACar = false;
foreach (var car in listOfCars)
{
bool matchingModel = car.Model == secondInput;
if (matchingModel == true)
{
isACar = true;
Console.WriteLine("Type: Car");
Console.WriteLine($"Model: {secondInput}");
Console.WriteLine($"Color: {car.Colour}");
Console.WriteLine($"Horsepower: {car.HorsePower}");
break;
}
}
if (isACar == false)
{
foreach (var truck in listOfTrucks)
{
bool matchingModel = truck.Model == secondInput;
if (matchingModel == true)
{
Console.WriteLine("Type: Truck");
Console.WriteLine($"Model: {secondInput}");
Console.WriteLine($"Color: {truck.Colour}");
Console.WriteLine($"Horsepower: {truck.HorsePower}");
break;
}
}
}
}
}
| 30.445378 | 94 | 0.485509 | [
"MIT"
] | Uendy/Tech-Module | L07 Classes, Objects/L07 More Exercises/Q02 Vehicle Catologue/Program.cs | 3,625 | C# |
using System.Reflection;
using System.Text;
namespace OfaSchlupfer.TextTemplate.Runtime {
/// <summary>
/// The standard rename make a camel/pascalcase name changed by `_` and lowercase. e.g `ThisIsAnExample` becomes `this_is_an_example`.
/// </summary>
public sealed class StandardMemberRenamer {
public static readonly MemberRenamerDelegate Default = Noop;
public static string Noop(MemberInfo member) => member.Name;
/// <summary>
/// Renames a camel/pascalcase member to a lowercase and `_` name. e.g `ThisIsAnExample` becomes `this_is_an_example`.
/// </summary>
/// <param name="member">The member to rename</param>
/// <returns>The member name renamed</returns>
public static string Rename(MemberInfo member) {
string name = member.Name;
var builder = new StringBuilder();
bool previousUpper = false;
for (int i = 0; i < name.Length; i++) {
var c = name[i];
if (char.IsUpper(c)) {
if (i > 0 && !previousUpper) {
builder.Append("_");
}
builder.Append(char.ToLowerInvariant(c));
previousUpper = true;
} else {
builder.Append(c);
previousUpper = false;
}
}
return builder.ToString();
}
}
} | 37.666667 | 138 | 0.543907 | [
"MIT"
] | FlorianGrimm/OfaSchlupfer | OfaSchlupfer.Elementary/TextTemplate/Runtime/StandardMemberRenamer.cs | 1,469 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MoreMountains.Feedbacks
{
/// <summary>
/// This feedback will make the bound renderer flicker for the set duration when played (and restore its initial color when stopped)
/// </summary>
[AddComponentMenu("")]
[FeedbackHelp("This feedback lets you flicker the color of a specified renderer (sprite, mesh, etc) for a certain duration, at the specified octave, and with the specified color. Useful when a character gets hit, for example (but so much more!).")]
[FeedbackPath("Renderer/Flicker")]
public class MMFeedbackFlicker : MMFeedback
{
/// sets the inspector color for this feedback
#if UNITY_EDITOR
public override Color FeedbackColor { get { return MMFeedbacksInspectorColors.RendererColor; } }
#endif
/// the possible modes
/// Color : will control material.color
/// PropertyName : will target a specific shader property by name
public enum Modes { Color, PropertyName }
[Header("Flicker")]
/// the renderer to flicker when played
[Tooltip("the renderer to flicker when played")]
public Renderer BoundRenderer;
/// the selected mode to flicker the renderer
[Tooltip("the selected mode to flicker the renderer")]
public Modes Mode = Modes.Color;
/// the name of the property to target
[MMFEnumCondition("Mode", (int)Modes.PropertyName)]
[Tooltip("the name of the property to target")]
public string PropertyName = "_Tint";
/// the duration of the flicker when getting damage
[Tooltip("the duration of the flicker when getting damage")]
public float FlickerDuration = 0.2f;
/// the frequency at which to flicker
[Tooltip("the frequency at which to flicker")]
public float FlickerOctave = 0.04f;
/// the color we should flicker the sprite to
[Tooltip("the color we should flicker the sprite to")]
[ColorUsage(true, true)]
public Color FlickerColor = new Color32(255, 20, 20, 255);
/// the list of material indexes we want to flicker on the target renderer. If left empty, will only target the material at index 0
[Tooltip("the list of material indexes we want to flicker on the target renderer. If left empty, will only target the material at index 0")]
public int[] MaterialIndexes;
/// if this is true, this component will use material property blocks instead of working on an instance of the material.
[Tooltip("if this is true, this component will use material property blocks instead of working on an instance of the material.")]
public bool UseMaterialPropertyBlocks = false;
/// the duration of this feedback is the duration of the flicker
public override float FeedbackDuration { get { return ApplyTimeMultiplier(FlickerDuration); } set { FlickerDuration = value; } }
protected const string _colorPropertyName = "_Color";
protected Color[] _initialFlickerColors;
protected int[] _propertyIDs;
protected bool[] _propertiesFound;
protected Coroutine[] _coroutines;
protected MaterialPropertyBlock _propertyBlock;
/// <summary>
/// On init we grab our initial color and components
/// </summary>
/// <param name="owner"></param>
protected override void CustomInitialization(GameObject owner)
{
if (MaterialIndexes.Length == 0)
{
MaterialIndexes = new int[1];
MaterialIndexes[0] = 0;
}
_coroutines = new Coroutine[MaterialIndexes.Length];
_initialFlickerColors = new Color[MaterialIndexes.Length];
_propertyIDs = new int[MaterialIndexes.Length];
_propertiesFound = new bool[MaterialIndexes.Length];
_propertyBlock = new MaterialPropertyBlock();
BoundRenderer.GetPropertyBlock(_propertyBlock);
for (int i = 0; i < MaterialIndexes.Length; i++)
{
_propertiesFound[i] = false;
if (Active && (BoundRenderer == null) && (owner != null))
{
if (owner.MMFGetComponentNoAlloc<Renderer>() != null)
{
BoundRenderer = owner.GetComponent<Renderer>();
}
if (BoundRenderer == null)
{
BoundRenderer = owner.GetComponentInChildren<Renderer>();
}
}
if (Active && (BoundRenderer != null))
{
if (Mode == Modes.Color)
{
_propertiesFound[i] = UseMaterialPropertyBlocks ? BoundRenderer.sharedMaterials[i].HasProperty(_colorPropertyName) : BoundRenderer.materials[i].HasProperty(_colorPropertyName);
if (_propertiesFound[i])
{
_initialFlickerColors[i] = UseMaterialPropertyBlocks ? BoundRenderer.sharedMaterials[i].color : BoundRenderer.materials[i].color;
}
}
else
{
_propertiesFound[i] = UseMaterialPropertyBlocks ? BoundRenderer.sharedMaterials[i].HasProperty(PropertyName) : BoundRenderer.materials[i].HasProperty(PropertyName);
if (_propertiesFound[i])
{
_propertyIDs[i] = Shader.PropertyToID(PropertyName);
_initialFlickerColors[i] = UseMaterialPropertyBlocks ? BoundRenderer.sharedMaterials[i].GetColor(_propertyIDs[i]) : BoundRenderer.materials[i].GetColor(_propertyIDs[i]);
}
}
}
}
}
/// <summary>
/// On play we make our renderer flicker
/// </summary>
/// <param name="position"></param>
/// <param name="feedbacksIntensity"></param>
protected override void CustomPlayFeedback(Vector3 position, float feedbacksIntensity = 1.0f)
{
if (Active && (BoundRenderer != null))
{
for (int i = 0; i < MaterialIndexes.Length; i++)
{
_coroutines[i] = StartCoroutine(Flicker(BoundRenderer, i, _initialFlickerColors[i], FlickerColor, FlickerOctave, FeedbackDuration));
}
}
}
/// <summary>
/// On reset we make our renderer stop flickering
/// </summary>
protected override void CustomReset()
{
base.CustomReset();
if (InCooldown)
{
return;
}
if (Active && (BoundRenderer != null))
{
for (int i = 0; i < MaterialIndexes.Length; i++)
{
SetColor(i, _initialFlickerColors[i]);
}
}
}
public virtual IEnumerator Flicker(Renderer renderer, int materialIndex, Color initialColor, Color flickerColor, float flickerSpeed, float flickerDuration)
{
if (renderer == null)
{
yield break;
}
if (!_propertiesFound[materialIndex])
{
yield break;
}
if (initialColor == flickerColor)
{
yield break;
}
float flickerStop = FeedbackTime + flickerDuration;
while (FeedbackTime < flickerStop)
{
SetColor(materialIndex, flickerColor);
if (Timing.TimescaleMode == TimescaleModes.Scaled)
{
yield return MMFeedbacksCoroutine.WaitFor(flickerSpeed);
}
else
{
yield return MMFeedbacksCoroutine.WaitForUnscaled(flickerSpeed);
}
SetColor(materialIndex, initialColor);
if (Timing.TimescaleMode == TimescaleModes.Scaled)
{
yield return MMFeedbacksCoroutine.WaitFor(flickerSpeed);
}
else
{
yield return MMFeedbacksCoroutine.WaitForUnscaled(flickerSpeed);
}
}
SetColor(materialIndex, initialColor);
}
protected virtual void SetColor(int materialIndex, Color color)
{
if (!_propertiesFound[materialIndex])
{
return;
}
if (Mode == Modes.Color)
{
if (UseMaterialPropertyBlocks)
{
BoundRenderer.GetPropertyBlock(_propertyBlock);
_propertyBlock.SetColor(_colorPropertyName, color);
BoundRenderer.SetPropertyBlock(_propertyBlock, materialIndex);
}
else
{
BoundRenderer.materials[materialIndex].color = color;
}
}
else
{
if (UseMaterialPropertyBlocks)
{
BoundRenderer.GetPropertyBlock(_propertyBlock);
_propertyBlock.SetColor(_propertyIDs[materialIndex], color);
BoundRenderer.SetPropertyBlock(_propertyBlock, materialIndex);
}
else
{
BoundRenderer.materials[materialIndex].SetColor(_propertyIDs[materialIndex], color);
}
}
}
/// <summary>
/// Stops this feedback
/// </summary>
/// <param name="position"></param>
/// <param name="feedbacksIntensity"></param>
protected override void CustomStopFeedback(Vector3 position, float feedbacksIntensity = 1)
{
base.CustomStopFeedback(position, feedbacksIntensity);
if (Active)
{
for (int i = 0; i < _coroutines.Length; i++)
{
if (_coroutines[i] != null)
{
StopCoroutine(_coroutines[i]);
}
_coroutines[i] = null;
}
}
}
}
}
| 40.429119 | 252 | 0.546531 | [
"MIT"
] | DuLovell/Rhythm-Game | Assets/Plugins/Feel/MMFeedbacks/MMFeedbacks/Feedbacks/MMFeedbackFlicker.cs | 10,554 | C# |
//-----------------------------------------------------------------------------
// Runtime: 168ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _037_SudokuSolver
{
bool[,] colUsed = new bool[9, 9];
bool[,] rowUsed = new bool[9, 9];
bool[,] squareUsed = new bool[9, 9];
public void SolveSudoku(char[,] board)
{
int row, column, squareId, value;
for (row = 0; row < 9; row++)
{
for (column = 0; column < 9; column++)
{
value = board[row, column] - '0' - 1;
if (value > 8 || value < 0) { continue; }
squareId = (row / 3) * 3 + column / 3;
if (colUsed[column, value] || rowUsed[row, value] || squareUsed[squareId, value]) { return; }
colUsed[column, value] = rowUsed[row, value] = squareUsed[squareId, value] = true;
}
}
RecursiveSolver(board, 0, 0);
}
bool RecursiveSolver(char[,] boarder, int row, int col)
{
if (row == 9) { return true; }
if (col == 9) { return RecursiveSolver(boarder, row + 1, 0); }
if (boarder[row, col] != '.') { return RecursiveSolver(boarder, row, col + 1); }
int squareId;
for (int i = 0; i < 9; i++)
{
squareId = (row / 3) * 3 + col / 3;
if (colUsed[col, i] || rowUsed[row, i] || squareUsed[squareId, i]) { continue; }
boarder[row, col] = (char)('1' + i);
colUsed[col, i] = rowUsed[row, i] = squareUsed[squareId, i] = true;
if (RecursiveSolver(boarder, row, col + 1))
{
return true;
}
boarder[row, col] = '.';
colUsed[col, i] = rowUsed[row, i] = squareUsed[squareId, i] = false;
}
return false;
}
}
}
| 34.131148 | 113 | 0.407301 | [
"MIT"
] | BigEggStudy/LeetCode-CS | LeetCode/0001-0050/037-SudokuSolver.cs | 2,082 | C# |
// ***********************************************************************
// Assembly : OptimizationToolbox
// Author : campmatt
// Created : 01-28-2021
//
// Last Modified By : campmatt
// Last Modified On : 01-28-2021
// ***********************************************************************
// <copyright file="linearExteriorPenalty.cs" company="OptimizationToolbox">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
/*************************************************************************
* This file & class is part of the Object-Oriented Optimization
* Toolbox (or OOOT) Project
* Copyright 2010 Matthew Ira Campbell, PhD.
*
* OOOT is free software: you can redistribute it and/or modify
* it under the terms of the MIT X11 License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OOOT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MIT X11 License for more details.
*
*
* Please find further details and contact information on OOOT
* at http://designengrlab.github.io/OOOT/.
*************************************************************************/
using System;
namespace OptimizationToolbox
{
/// <summary>
/// Class linearExteriorPenalty.
/// Implements the <see cref="OptimizationToolbox.abstractMeritFunction" />
/// </summary>
/// <seealso cref="OptimizationToolbox.abstractMeritFunction" />
public class linearExteriorPenalty : abstractMeritFunction
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="linearExteriorPenalty"/> class.
/// </summary>
/// <param name="optMethod">The opt method.</param>
/// <param name="penaltyWeight">The penalty weight.</param>
public linearExteriorPenalty(abstractOptMethod optMethod, double penaltyWeight)
: base(optMethod, penaltyWeight)
{
}
#endregion
/// <summary>
/// Calcs the penalty.
/// </summary>
/// <param name="point">The point.</param>
/// <returns>System.Double.</returns>
public override double calcPenalty(double[] point)
{
var sum = 0.0;
double temp;
foreach (var c in optMethod.h)
{
temp = optMethod.calculate(c, point);
sum += Math.Abs(temp);
}
foreach (var c in optMethod.g)
{
temp = optMethod.calculate(c, point);
if (temp > 0) sum += temp;
}
sum *= penaltyWeight;
return sum;
}
/// <summary>
/// Calculates the gradient of penalty.
/// </summary>
/// <param name="point">The point.</param>
/// <returns>System.Double[].</returns>
public override double[] calcGradientOfPenalty(double[] point)
{
var n = point.GetLength(0);
var grad = new double[n];
for (var i = 0; i != n; i++)
{
var sum = 0.0;
double temp;
foreach (var c in optMethod.h)
{
temp = optMethod.calculate(c, point);
if (temp < 0.0)
sum -= optMethod.deriv_wrt_xi(c,point, i);
if (temp > 0.0)
sum += optMethod.deriv_wrt_xi(c,point, i);
}
foreach (var c in optMethod.g)
{
temp = optMethod.calculate(c, point);
if (temp > 0.0)
sum += optMethod.deriv_wrt_xi(c,point, i);
}
grad[i] = penaltyWeight * sum;
}
return grad;
}
}
} | 35.784483 | 88 | 0.488557 | [
"MIT"
] | DesignEngrLab/OOOT | OptimizationToolbox/Merit Functions/linearExteriorPenalty.cs | 4,153 | C# |
namespace Mapbox.Examples.Scripts
{
using Mapbox.Unity.Location;
using Mapbox.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class LogLocationProviderData : MonoBehaviour
{
[SerializeField]
private Text _logText;
private CultureInfo _invariantCulture = CultureInfo.InvariantCulture;
// Use this for initialization
void Start()
{
LocationProviderFactory.Instance.DefaultLocationProvider.OnLocationUpdated += LocationProvider_OnLocationUpdated;
}
void OnDestroy()
{
LocationProviderFactory.Instance.DefaultLocationProvider.OnLocationUpdated -= LocationProvider_OnLocationUpdated;
}
void LocationProvider_OnLocationUpdated(Location location)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("IsLocationServiceEnabled: {0}", location.IsLocationServiceEnabled));
sb.AppendLine(string.Format("IsLocationServiceInitializing: {0}", location.IsLocationServiceInitializing));
sb.AppendLine(string.Format("IsLocationUpdated: {0}", location.IsLocationUpdated));
sb.AppendLine(string.Format("IsHeadingUpdated: {0}", location.IsUserHeadingUpdated));
string locationProviderClass = LocationProviderFactory.Instance.DefaultLocationProvider.GetType().Name;
sb.AppendLine(string.Format("location provider: {0} ({1})", location.Provider, locationProviderClass));
sb.AppendLine(string.Format("UTC time:{0} - device: {1}{0} - location:{2}", Environment.NewLine, DateTime.UtcNow.ToString("yyyyMMdd HHmmss"), UnixTimestampUtils.From(location.Timestamp).ToString("yyyyMMdd HHmmss")));
sb.AppendLine(string.Format(_invariantCulture, "position: {0:0.00000000} / {1:0.00000000}", location.LatitudeLongitude.x, location.LatitudeLongitude.y));
sb.AppendLine(string.Format(_invariantCulture, "accuracy: {0:0.0}m", location.Accuracy));
sb.AppendLine(string.Format(_invariantCulture, "user heading: {0:0.0}°", location.UserHeading));
sb.AppendLine(string.Format(_invariantCulture, "device orientation: {0:0.0}°", location.DeviceOrientation));
sb.AppendLine(nullableAsStr<float>(location.SpeedKmPerHour, "speed: {0:0.0}km/h"));
sb.AppendLine(nullableAsStr<bool>(location.HasGpsFix, "HasGpsFix: {0}"));
sb.AppendLine(nullableAsStr<int>(location.SatellitesUsed, "SatellitesUsed:{0} ") + nullableAsStr<int>(location.SatellitesInView, "SatellitesInView:{0}"));
_logText.text = sb.ToString();
}
private string nullableAsStr<T>(T? val, string formatString = null) where T : struct
{
if (null == val && null == formatString) { return "[not supported by provider]"; }
if (null == val && null != formatString) { return string.Format(_invariantCulture, formatString, "[not supported by provider]"); }
if (null != val && null == formatString) { return val.Value.ToString(); }
return string.Format(_invariantCulture, formatString, val);
}
// Update is called once per frame
void Update()
{
}
}
}
| 39 | 222 | 0.752465 | [
"MIT"
] | HypnosisXStar/infiltrate-source | Source/Infiltrate/Assets/Mapbox/Mapbox/Examples/5_Playground/Scripts/LogLocationProviderData.cs | 3,044 | C# |
namespace Frapid.Account.Models
{
public class GoogleUserInfo : IUserInfo
{
public string Name { get; set; }
public string Email { get; set; }
}
} | 21.75 | 43 | 0.614943 | [
"MIT"
] | 2ia/frapid | src/Frapid.Web/Areas/Frapid.Account/Models/GoogleUserInfo.cs | 174 | C# |
using System;
using System.Reflection.Emit;
///<summary>
///System.Reflection.Emit.OpCodes.Stloc_0 [v-zuolan]
///</summary>
public class OpCodesStloc_0
{
public static int Main()
{
OpCodesStloc_0 testObj = new OpCodesStloc_0();
TestLibrary.TestFramework.BeginTestCase("for field of System.Reflection.Emit.OpCodes.Stloc_0");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
#region Test Logic
public bool PosTest1()
{
bool retVal = true;
CompareResult expectedValue = CompareResult.Equal;
CompareResult actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest1:get the property and verify its fields");
try
{
OpCode opcode = OpCodes.Stloc_0;
actualValue = CompareOpCode(opcode, "stloc.0", StackBehaviour.Pop1, StackBehaviour.Push0, OperandType.InlineNone, OpCodeType.Macro, 1, (byte)0xff, (byte)0xa, FlowControl.Next);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("001", "Errors accured in fields:" + GetResult(actualValue));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region helper method
//verify the opcode fields
//if not equal,retun the field name which contains error.
private CompareResult CompareOpCode(
OpCode opcode,
String stringname,
StackBehaviour pop,
StackBehaviour push,
OperandType operand,
OpCodeType type,
int size,
byte s1,
byte s2,
FlowControl ctrl)
{
CompareResult returnValue = CompareResult.Equal;
if (opcode.Name != stringname) returnValue = returnValue | CompareResult.Name;
if (opcode.StackBehaviourPop != pop) returnValue = returnValue | CompareResult.Pop;
if (opcode.StackBehaviourPush != push) returnValue = returnValue | CompareResult.Push;
if (opcode.OperandType != operand) returnValue = returnValue | CompareResult.OpenrandType;
if (opcode.OpCodeType != type) returnValue = returnValue | CompareResult.OpCodeType;
if (opcode.Size != size) returnValue = returnValue | CompareResult.Size;
if (size == 2)
{
if (opcode.Value != ((short)(s1 << 8 | s2)))
{
returnValue = returnValue | CompareResult.Value;
}
}
else
{
if (opcode.Value != ((short)s2))
{
returnValue = returnValue | CompareResult.Value;
}
}
if (opcode.FlowControl != ctrl)
{
returnValue = returnValue | CompareResult.FlowControl;
}
return returnValue;
}
//Transform numeric result into string description
public String GetResult(CompareResult result)
{
String retVal = null;
for (int i = 0; i < 8; i++)
{
if (((int)result & (0x01 << i)) == (0x01 << i))
{
if (retVal == null)
{
retVal = "{" + ((CompareResult)(0x01 << i)).ToString();
}
else
{
retVal = retVal + "," + ((CompareResult)(0x01 << i)).ToString();
}
}
}
if (retVal == null)
{
retVal = "{Equal}";
}
else
{
retVal = retVal + "}";
}
return retVal;
}
#endregion
}
#region Enum CompareResult
public enum CompareResult
{
Equal = 0x00,
Name = 0x01,
Pop = 0x02,
Push = 0x04,
OpenrandType = 0x08,
OpCodeType = 0x10,
Size = 0x20,
Value = 0x40,
FlowControl = 0x80
}
#endregion | 27.407407 | 188 | 0.553153 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/CoreMangLib/cti/system/reflection/emit/opcodes/opcodesstloc_0.cs | 4,440 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FlubuCore.Context;
using FlubuCore.Tasks;
using FlubuCore.Tasks.Process;
namespace FlubuCore.Azure.Tasks.Network
{
public partial class AzureNetworkDnsZoneTask : ExternalProcessTaskBase<AzureNetworkDnsZoneTask>
{
/// <summary>
/// Manage DNS zones.
/// </summary>
public AzureNetworkDnsZoneTask()
{
WithArguments("az network dns zone");
}
protected override string Description { get; set; }
}
}
| 22 | 100 | 0.645105 | [
"MIT"
] | flubu-core/FlubuCore.Azure | FlubuCore.Azure/Tasks/Network/AzureNetworkDnsZoneTask.cs | 572 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Search.VisualSearch.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A JSON object containing information about the request, such as filters
/// for the resulting actions.
/// </summary>
public partial class KnowledgeRequest
{
/// <summary>
/// Initializes a new instance of the KnowledgeRequest class.
/// </summary>
public KnowledgeRequest()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the KnowledgeRequest class.
/// </summary>
/// <param name="filters">A key-value object consisting of filters that
/// may be specified to limit the results returned by the API.</param>
public KnowledgeRequest(Filters filters = default(Filters))
{
Filters = filters;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a key-value object consisting of filters that may be
/// specified to limit the results returned by the API.
/// </summary>
[JsonProperty(PropertyName = "filters")]
public Filters Filters { get; set; }
}
}
| 31.215686 | 90 | 0.612437 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/cognitiveservices/Search.BingVisualSearch/src/Generated/Models/KnowledgeRequest.cs | 1,592 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Health.Fhir.CosmosDb {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Health.Fhir.CosmosDb.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Failed to get or access the Azure AD token to access the customer-managed key..
/// </summary>
internal static string AadClientCredentialsGrantFailure {
get {
return ResourceManager.GetString("AadClientCredentialsGrantFailure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Azure AD service is unavailable to get access to the customer-managed key..
/// </summary>
internal static string AadServiceUnavailable {
get {
return ResourceManager.GetString("AadServiceUnavailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sub-queries in a chained expression cannot return more than {0} results, please use a more selective criteria..
/// </summary>
internal static string ChainedExpressionSubqueryLimit {
get {
return ResourceManager.GetString("ChainedExpressionSubqueryLimit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was an error using the customer-managed key..
/// </summary>
internal static string CmkDefaultError {
get {
return ResourceManager.GetString("CmkDefaultError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to _include:iterate and _revinclude:iterate are not supported..
/// </summary>
internal static string IncludeIterateNotSupported {
get {
return ResourceManager.GetString("IncludeIterateNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Consistency level '{0}' specified in the request is invalid when service is configured with consistency level '{1}'. Ensure the request consistency level is not stronger than the service consistency level..
/// </summary>
internal static string InvalidConsistencyLevel {
get {
return ResourceManager.GetString("InvalidConsistencyLevel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Internal server error: the input bytes are not in base64 format..
/// </summary>
internal static string InvalidInputBytes {
get {
return ResourceManager.GetString("InvalidInputBytes", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The customer-managed key URI is invalid..
/// </summary>
internal static string InvalidKeyVaultKeyUri {
get {
return ResourceManager.GetString("InvalidKeyVaultKeyUri", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Key Vault does not grant permission to the Azure AD, or the customer-managed key is disabled..
/// </summary>
internal static string KeyVaultAuthenticationFailure {
get {
return ResourceManager.GetString("KeyVaultAuthenticationFailure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not resolve the DNS name of the Key Vault of the customer-managed key..
/// </summary>
internal static string KeyVaultDnsNotResolved {
get {
return ResourceManager.GetString("KeyVaultDnsNotResolved", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Key Vault internal service errors accessing the customer-managed key..
/// </summary>
internal static string KeyVaultInternalServerError {
get {
return ResourceManager.GetString("KeyVaultInternalServerError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The customer-managed key is not found..
/// </summary>
internal static string KeyVaultKeyNotFound {
get {
return ResourceManager.GetString("KeyVaultKeyNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The Key Vault Service is unavailable to access the customer-managed key..
/// </summary>
internal static string KeyVaultServiceUnavailable {
get {
return ResourceManager.GetString("KeyVaultServiceUnavailable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failure to Wrap or Unwrap the customer-managed key..
/// </summary>
internal static string KeyVaultWrapUnwrapFailure {
get {
return ResourceManager.GetString("KeyVaultWrapUnwrapFailure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unhandled {0} '{1}'..
/// </summary>
internal static string UnhandledEnumValue {
get {
return ResourceManager.GetString("UnhandledEnumValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid consistency level '{0}'. Valid values are: {1}..
/// </summary>
internal static string UnrecognizedConsistencyLevel {
get {
return ResourceManager.GetString("UnrecognizedConsistencyLevel", resourceCulture);
}
}
}
}
| 42.543269 | 279 | 0.595322 | [
"MIT"
] | BearerPipelineTest/fhir-server | src/Microsoft.Health.Fhir.CosmosDb/Resources.Designer.cs | 8,851 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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.Collections.Generic;
namespace behaviac
{
public abstract class CompositeStochastic : BehaviorNode
{
public CompositeStochastic()
{
}
~CompositeStochastic()
{
m_method = null;
}
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
foreach(property_t p in properties)
{
if (p.name == "RandomGenerator")
{
if (p.value[0] != '\0')
{
this.m_method = Action.LoadMethod(p.value);
}//if (p.value[0] != '\0')
}
else
{
//Debug.Check(0, "unrecognised property %s", p.name);
}
}
}
public bool CheckIfInterrupted(Agent pAgent)
{
bool bInterrupted = this.EvaluteCustomCondition(pAgent);
return bInterrupted;
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is CompositeStochastic))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
protected CMethodBase m_method;
public class CompositeStochasticTask : CompositeTask
{
public CompositeStochasticTask()
{
}
~CompositeStochasticTask()
{
}
//generate a random float value between 0 and 1.
public static float GetRandomValue(CMethodBase method, Agent pAgent)
{
float value = 0;
if (method != null)
{
value = (float)method.Invoke(pAgent);
}
else
{
value = RandomGenerator.GetInstance().GetRandom();
}
Debug.Check(value >= 0.0f && value < 1.0f);
return value;
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
Debug.Check(target is CompositeStochasticTask);
CompositeStochasticTask ttask = (CompositeStochasticTask)target;
ttask.m_set = this.m_set;
}
public override void save(ISerializableNode node)
{
base.save(node);
CSerializationID setId = new CSerializationID("set");
node.setAttr(setId, this.m_set);
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override bool onenter(Agent pAgent)
{
Debug.Check(this.m_children.Count > 0);
this.random_child(pAgent);
this.m_activeChildIndex = 0;
return true;
}
protected override void onexit(Agent pAgent, EBTStatus s)
{
base.onexit(pAgent, s);
}
private void random_child(Agent pAgent)
{
Debug.Check(this.GetNode() == null || this.GetNode() is CompositeStochastic);
CompositeStochastic pNode = (CompositeStochastic)(this.GetNode());
int n = this.m_children.Count;
if (this.m_set.Count != n)
{
this.m_set.Clear();
for (int i = 0; i < n; ++i)
{
this.m_set.Add(i);
}
}
for (int i = 0; i < n; ++i)
{
int index1 = (int)(n * GetRandomValue(pNode != null ? pNode.m_method : null, pAgent));
Debug.Check(index1 < n);
int index2 = (int)(n * GetRandomValue(pNode != null ? pNode.m_method : null, pAgent));
Debug.Check(index2 < n);
//swap
if (index1 != index2)
{
int old = this.m_set[index1];
this.m_set[index1] = this.m_set[index2];
this.m_set[index2] = old;
}
}
}
protected List<int> m_set = new List<int>();
}
}
}
| 31.653179 | 113 | 0.471877 | [
"BSD-3-Clause"
] | 675492062/behaviac | integration/BattleCityDemo/Assets/Scripts/behaviac/BehaviorTree/Nodes/Composites/Compositestochastic.cs | 5,476 | C# |
namespace UglyToad.PdfPig.Fonts.Encodings
{
using System.Collections.Generic;
using UglyToad.PdfPig.Tokens;
/// <summary>
/// Maps character codes to glyph names from a PostScript encoding.
/// </summary>
public abstract class Encoding
{
/// <summary>
/// Mutable code to name map.
/// </summary>
protected readonly Dictionary<int, string> CodeToName = new Dictionary<int, string>(250);
/// <summary>
/// Maps from character codes to names.
/// </summary>
public IReadOnlyDictionary<int, string> CodeToNameMap => CodeToName;
/// <summary>
/// Mutable name to code map.
/// </summary>
protected readonly Dictionary<string, int> NameToCode = new Dictionary<string, int>(250);
/// <summary>
/// Maps from names to character cocdes.
/// </summary>
public IReadOnlyDictionary<string, int> NameToCodeMap => NameToCode;
/// <summary>
/// The name of this encoding.
/// </summary>
public abstract string EncodingName { get; }
/// <summary>
/// Whether this encoding contains a code for the name.
/// </summary>
public bool ContainsName(string name)
{
return NameToCode.ContainsKey(name);
}
/// <summary>
/// Whether this encoding contains a name for the code.
/// </summary>
public bool ContainsCode(int code)
{
return CodeToName.ContainsKey(code);
}
/// <summary>
/// Get the character name corresponding to the given code.
/// </summary>
public virtual string GetName(int code)
{
if (!CodeToName.TryGetValue(code, out var name))
{
return ".notdef";
}
return name;
}
/// <summary>
/// Add a character code and name pair.
/// </summary>
protected void Add(int code, string name)
{
CodeToName[code] = name;
if (!NameToCode.ContainsKey(name))
{
NameToCode[name] = code;
}
}
/// <summary>
/// Get a known encoding instance with the given name.
/// </summary>
public static bool TryGetNamedEncoding(NameToken name, out Encoding encoding)
{
encoding = null;
if (name == null)
{
return false;
}
if (name.Equals(NameToken.StandardEncoding))
{
encoding = StandardEncoding.Instance;
return true;
}
if (name.Equals(NameToken.WinAnsiEncoding))
{
encoding = WinAnsiEncoding.Instance;
return true;
}
if (name.Equals(NameToken.MacExpertEncoding))
{
encoding = MacExpertEncoding.Instance;
return true;
}
if (name.Equals(NameToken.MacRomanEncoding))
{
encoding = MacRomanEncoding.Instance;
return true;
}
return false;
}
}
}
| 27.694915 | 97 | 0.511934 | [
"Apache-2.0"
] | Lordtagoh/PdfPig | src/UglyToad.PdfPig.Fonts/Encodings/Encoding.cs | 3,270 | C# |
namespace ClientLogic.Models
{
public class Configuration
{
public string Host { get; set; }
}
}
| 14.75 | 40 | 0.610169 | [
"Apache-2.0"
] | projectcloudlife/CloudLife | ClientLogic/Models/Configuration.cs | 120 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.