content stringlengths 23 1.05M |
|---|
namespace BankManagementSystem.Services
{
using System;
public interface IClientService
{
void Create(string name, string email, DateTime dateTime, decimal balance);
}
}
|
/*
类:MainForm
描述:模板填充规则文件生成工具UI
编 码 人:韩兆新 日期:2015年01月17日
修改记录:
*/
using System;
using System.IO;
using System.Windows.Forms;
using ExcelReport;
namespace XmlGenerator
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void btnSelecttxtExcelTemplate_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.Filter = "Excel 2003文件|*.xls|Excel 2007文件|*.xlsx|所有文件|*";
if (DialogResult.OK.Equals(openFileDlg.ShowDialog()))
{
txtExcelTemplatePath.Text = openFileDlg.FileName;
}
}
private void txtExcelTemplatePath_DragDrop(object sender, DragEventArgs e)
{
string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
txtExcelTemplatePath.Text = path;
}
private void txtExcelTemplatePath_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Link;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void btnFillTemplate_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtExcelTemplatePath.Text.Trim()))
{
MessageBox.Show("请选择Excel模板文件!", "提示");
return;
}
WorkbookParameterContainer workbookParameter = ParseTemplate.Parse(txtExcelTemplatePath.Text);
workbookParameter.Save(Path.ChangeExtension(txtExcelTemplatePath.Text, ".xml"));
}
}
} |
using System;
using System.Threading;
using System.Threading.Tasks;
using GroupDocs.Viewer.UI.Api.InMemory.Cache.Configuration;
using GroupDocs.Viewer.UI.Core;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace GroupDocs.Viewer.UI.Api.InMemory.Cache
{
public class InMemoryFileCache : IFileCache
{
private readonly IMemoryCache _cache;
private readonly Config _config;
public InMemoryFileCache(IMemoryCache cache, IOptions<Config> config)
{
_cache = cache;
_config = config.Value;
}
public TEntry TryGetValue<TEntry>(string cacheKey, string filePath)
{
string key = $"{filePath}_{cacheKey}";
if (_cache.TryGetValue(key, out object obj))
return (TEntry) obj;
return default;
}
public Task<TEntry> TryGetValueAsync<TEntry>(string cacheKey, string filePath)
{
TEntry entry = TryGetValue<TEntry>(cacheKey, filePath);
return Task.FromResult(entry);
}
public void Set<TEntry>(string cacheKey, string filePath, TEntry entry)
{
MemoryCacheEntryOptions entryOptions;
if (_config.CacheEntryExpirationTimeoutMinutes > 0)
{
var cts = GetOrCreateCancellationTokenSource(cacheKey, filePath);
entryOptions = CreateCacheEntryOptions(cts);
}
else
{
entryOptions = CreateCacheEntryOptions();
}
string key = $"{filePath}_{cacheKey}";
_cache.Set(key, entry, entryOptions);
}
public Task SetAsync<TEntry>(string cacheKey, string filePath, TEntry entry)
{
Set(cacheKey, filePath, entry);
return Task.CompletedTask;
}
private CancellationTokenSource GetOrCreateCancellationTokenSource(string cacheKey, string filePath)
{
var ctsCacheKey = _config.GroupCacheEntriesByFile
? $"{filePath}__CTS"
: $"{filePath}_{cacheKey}__CTS";
var cts = _cache.Get<CancellationTokenSource>(ctsCacheKey);
if (cts == null || cts.IsCancellationRequested)
{
using (var ctsEntry = _cache.CreateEntry(ctsCacheKey))
{
cts = CreateCancellationTokenSource();
ctsEntry.Value = cts;
ctsEntry.AddExpirationToken(CreateCancellationChangeToken(cts));
}
}
return cts;
}
private MemoryCacheEntryOptions CreateCacheEntryOptions(CancellationTokenSource cts)
{
var entryOptions = new MemoryCacheEntryOptions();
entryOptions.AddExpirationToken(CreateCancellationChangeToken(cts));
return entryOptions;
}
private MemoryCacheEntryOptions CreateCacheEntryOptions()
{
var entryOptions = new MemoryCacheEntryOptions();
return entryOptions;
}
private CancellationChangeToken CreateCancellationChangeToken(CancellationTokenSource cancellationTokenSource)
=> new CancellationChangeToken(cancellationTokenSource.Token);
private CancellationTokenSource CreateCancellationTokenSource() =>
new CancellationTokenSource(TimeSpan.FromMinutes(_config.CacheEntryExpirationTimeoutMinutes));
}
} |
@page "/"
@page "/tag/{CurrentTag}"
@page "/tag/"
@inject IHttpApiClientRequestBuilderFactory ClientFactory
@inject IAccountService AccountService
<div class="row">
<div class="col-2"> <NewToss OnNewTossCreated="@RefreshTossList"></NewToss></div>
<div class="col-10">
<HashTagBar CurrentTag="@CurrentTag"></HashTagBar>
</div>
</div>
<div class="row">
@if (string.IsNullOrEmpty(CurrentTag))
{
<div class="col-md-3 col-sm-6 my-2">
<div class="card text-white bg-warning h-100">
<div class="card-body">
<h5 class="card-title">Select a hashtag</h5>
<p class="card-text">Use the textbox below for searching content based on a hashtag.</p>
</div>
</div>
</div>
}
@foreach (var toss in Tosses.OrderByDescending(t => t.CreatedOn))
{
<div class="col-md-3 col-sm-6 my-2 toss">
<OneToss toss="@toss" />
</div>
}
</div>
@functions{
List<TossLastQueryItem> Tosses = new List<TossLastQueryItem>();
[Parameter]
private string CurrentTag { get; set; } = "";
protected override async Task OnParametersSetAsync()
{
await RefreshTossList();
}
public override void SetParameters(ParameterCollection parameters)
{
if (string.IsNullOrEmpty(parameters.GetValueOrDefault<string>("CurrentTag")))
{
CurrentTag = null;
}
base.SetParameters(parameters);
}
protected async Task RefreshTossList()
{
Tosses = new List<TossLastQueryItem>();
if (string.IsNullOrWhiteSpace(CurrentTag))
return;
await ClientFactory.Create("/api/toss/last?hashtag=" + CurrentTag)
.OnOK<List<TossLastQueryItem>>(l =>
{
Tosses = l;
StateHasChanged();
})
.Get();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BassUtils.Runtime
{
/// <summary>
/// Information about the server and environment.
/// </summary>
public class ServerRuntimeInformation
{
/// <summary>
/// Machine name.
/// </summary>
public string MachineName { get; set; }
/// <summary>
/// Current UTC server time.
/// </summary>
public DateTime CurrentServerTimeUtc { get; private set; }
/// <summary>
/// Current server local time.
/// </summary>
public DateTime CurrentServerTimeLocal { get; private set; }
/// <summary>
/// Gets the name of the user associated with the current thread.
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Gets the CLR version.
/// </summary>
public string ClrVersion { get; private set; }
/// <summary>
/// Gets the number of processors.
/// </summary>
public int ProcessorCount { get; private set; }
/// <summary>
/// Gets the command line for this process.
/// </summary>
public string CommandLine { get; private set; }
/// <summary>
/// Returns the OS platform (Windows, Linux etc).
/// </summary>
public string OsPlatform { get; private set; }
/// <summary>
/// Returns a string describing the OS version.
/// </summary>
public string OsVersionString { get; private set; }
/// <summary>
/// Create a new instance of the <seealso cref="ServerRuntimeInformation"/>.
/// </summary>
public ServerRuntimeInformation()
{
MachineName = Environment.MachineName;
CurrentServerTimeUtc = DateTime.UtcNow;
CurrentServerTimeLocal = DateTime.Now;
UserName = Environment.UserName;
ClrVersion = Environment.Version.ToString();
ProcessorCount = Environment.ProcessorCount;
CommandLine = Environment.CommandLine;
OsPlatform = Environment.OSVersion.Platform.ToString();
OsVersionString = Environment.OSVersion.VersionString;
}
}
}
|
using AcceptanceTests.Common.PageObject.Helpers;
using OpenQA.Selenium;
namespace VideoWeb.AcceptanceTests.Pages
{
public static class RulesPage
{
public static By HmctsLogo = CommonLocators.ImageWithAltTags("HM Courts & Tribunals Service crest");
}
}
|
#if !WP7 && !WP8
using System.Collections.Generic;
using DigitalRune.Graphics.Effects;
using DigitalRune;
using DigitalRune.Geometry;
using DigitalRune.Graphics;
using DigitalRune.Graphics.Rendering;
using DigitalRune.Graphics.SceneGraph;
using DigitalRune.Mathematics.Algebra;
using DigitalRune.Physics.ForceEffects;
using Microsoft.Xna.Framework;
using System.Linq;
namespace Samples.Graphics
{
[Sample(SampleCategory.Graphics,
@"This sample shows how to use the MeshInstancingNode and custom effects to render many plant
instances which are swaying in the wind.",
@"A custom game object 'WindObject' is used to generate a wind vector.
A custom game object class 'VegetationObject' is used to place plant mesh instances in the scene.
The instances are managed in several VegetationObjects. Each VegetationObject plants instances of
one mesh type in a grid. One MeshInstancingNode is created per grid cell. Only MeshInstancingNodes
within a certain max distance are added to the scene.
Three different plants are displayed. The meshes and effects can be found in the folder
<DIGITALRUNE_FOLDER/Samples/Content/Vegetation>.
The palm tree mesh and the smaller bird's nest plant use the *Vegetation.fx effects.
The bird's nest plant is a mesh with two levels of detail.
The grass mesh uses the *Grass.fx effects.
The effects uses a vertex shader which animates the vertices to create a swaying animation. This
method is described in Vegetation Procedural Animation and Shading in Crysis, GPU Gems 3, pp. 373
(http://http.developer.nvidia.com/GPUGems3/gpugems3_ch16.html).
The swaying animation consists of 3 parts:
1. The trunk animation bends the whole plant left and right.
2. The branch animation moves the branches and big leaves up and down.
3. The leaf animation adds a vertical flutter to the vertical edges of the big leaves.
The palm tree mesh and the bird's nest plant mesh use vertex colors to control the animation as
described in the article. However, the vertex colors are used a bit differently: The red color
defines the intensity of the up-down branch swaying. The green color is used to create a random
oscillation phase per branch/leave. The blue color defines the intensity of the horizontal leaf-edge
flutter.
The effects use screen door transparency (= alpha test with a dither pattern) to fade objects out.
The effects also add a simple translucency effect.
Important notes:
For swaying you need to increase bounding box of plant models. In this sample the bounding box
is manually set in the *.drmdl files of the models.
The MeshInstancingNode is not yet supported in MonoGame! Support for hardware instancing in MonoGame
will be added in the future.
The sample adds some GUI controls to the 'Game Object' and the 'Vegetation' tab of the Options
window.",
132)]
public class VegetationSample : Sample
{
private enum VertexColorChannel { None, Red, Green, Blue, };
private VertexColorChannel _vertexColorChannel;
private readonly DeferredGraphicsScreen _graphicsScreen;
// Dictionary used to store the default values of effect parameters.
private readonly Dictionary<EffectParameterBinding, Vector3> _defaultEffectParameterValues = new Dictionary<EffectParameterBinding, Vector3>();
private bool _enableTranslucency = true;
private float _windWaveFrequency = 0.2f;
private float _windWaveRandomness = 0.3f;
private float _trunkFrequencyMultiplier = 1;
private float _branchFrequencyMultiplier = 1;
private float _trunkScaleMultiplier = 1;
private float _branchScaleMultiplier = 1;
private float _leafScaleMultiplier = 1;
private bool _drawDebugInfo;
// A list of all used plant meshes.
private readonly List<Mesh> _meshes = new List<Mesh>();
public VegetationSample(Microsoft.Xna.Framework.Game game)
: base(game)
{
SampleFramework.IsMouseVisible = false;
_graphicsScreen = new DeferredGraphicsScreen(Services);
_graphicsScreen.DrawReticle = true;
GraphicsService.Screens.Insert(0, _graphicsScreen);
GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));
Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
var scene = _graphicsScreen.Scene;
Services.Register(typeof(IScene), null, scene);
// Add gravity and damping to the physics simulation.
Simulation.ForceEffects.Add(new Gravity());
Simulation.ForceEffects.Add(new Damping());
// Add a custom game object which controls the camera.
var cameraGameObject = new CameraObject(Services);
GameObjectService.Objects.Add(cameraGameObject);
_graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;
// Add standard game objects.
GameObjectService.Objects.Add(new GrabObject(Services));
GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
GameObjectService.Objects.Add(new GroundObject(Services));
GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
GameObjectService.Objects.Add(new LavaBallsObject(Services));
// Add a new game object which controls the wind velocity and "Wind" parameters in effects.
GameObjectService.Objects.Add(new WindObject(Services));
#if MONOGAME // TODO: Test if MonoGame supports effect annotations.
// The vegetation effects use an effect parameter named "LodDistances". By default all
// effect parameters are shared per "Material". However, we want to change the parameter
// per instance. Therefore, the effect declares the parameter like this:
// float3 LodDistances < string Hint = "PerInstance"; >;
// However, MonoGame does not yet support effect annotations. Therefore, we tell the
// graphics service that the "LodDistances" parameter should be stored per instance by
// adding a new entry to the default effect interpreter.
var defaultEffectInterpreter = GraphicsService.EffectInterpreters.OfType<DefaultEffectInterpreter>().First();
if (!defaultEffectInterpreter.ParameterDescriptions.ContainsKey("LodDistances"))
defaultEffectInterpreter.ParameterDescriptions.Add(
"LodDistances",
(parameter, i) => new EffectParameterDescription(parameter, "LodDistances", i, EffectParameterHint.PerInstance));
#endif
// Load three different plant models.
// The palm tree consists of a single mesh. It uses the *Vegetation.fx effects.
ModelNode palmModelNode = ContentManager.Load<ModelNode>("Vegetation/PalmTree/palm_tree");
Mesh palmMesh = ((MeshNode)palmModelNode.Children[0]).Mesh;
// The bird's nest plant consists of 2 LODs. It uses the *Vegetation.fx effects.
ModelNode plantModelNode = ContentManager.Load<ModelNode>("Vegetation/BirdnestPlant/BirdnestPlant");
LodGroupNode plantLodGroupNode = plantModelNode.GetDescendants().OfType<LodGroupNode>().First().Clone();
// The grass model consists of one mesh. It uses the *Grass.fx effects.
ModelNode grassModelNode = ContentManager.Load<ModelNode>("Vegetation/Grass/grass");
Mesh grassMesh = ((MeshNode)grassModelNode.Children[0]).Mesh;
// Store all used meshes in a list for use in UpdateMaterialEffectParameters.
_meshes.Add(palmMesh);
foreach (var meshNode in plantLodGroupNode.Levels.Select(lodEntry => lodEntry.Node).OfType<MeshNode>())
_meshes.Add(meshNode.Mesh);
_meshes.Add(grassMesh);
// We can add individual plant instances to the scene like this:
// (However, this is inefficient for large amounts of plants.)
_graphicsScreen.Scene.Children.Add(new MeshNode(palmMesh)
{
PoseLocal = new Pose(new Vector3F(-2, 0, 0))
});
plantLodGroupNode.PoseLocal = Pose.Identity;
_graphicsScreen.Scene.Children.Add(plantLodGroupNode);
_graphicsScreen.Scene.Children.Add(new MeshNode(grassMesh)
{
PoseLocal = new Pose(new Vector3F(2, 0, 0))
});
#if WINDOWS
int numberOfInstancesPerCell = 100;
#else
int numberOfInstancesPerCell = 10;
#endif
// It is more efficient to group instances in batches and render them using mesh instancing.
// This is handled by the VegetationObject class.
GameObjectService.Objects.Add(new VegetationObject(Services, palmMesh, numberOfInstancesPerCell, 20, 10, 10, 1)
{
Name = "PalmTrees"
});
// The bird's nest plant has 2 LODs. We create two VegetationObjects. One displays the
// detailed meshes near the camera. The second displays the low-poly meshes in the distance.
var plantMeshLod0 = ((MeshNode)plantLodGroupNode.Levels[0].Node).Mesh;
_meshes.Add(plantMeshLod0);
GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod0, numberOfInstancesPerCell, 20, 10, 10, 2)
{
Name = "PlantLOD0",
MaxDistance = plantLodGroupNode.Levels[1].Distance,
});
var plantMeshLod1 = ((MeshNode)plantLodGroupNode.Levels[1].Node).Mesh;
_meshes.Add(plantMeshLod1);
GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod1, numberOfInstancesPerCell, 20, 10, 10, 2)
{
Name = "PlantLOD1",
MinDistance = plantLodGroupNode.Levels[1].Distance,
MaxDistance = plantLodGroupNode.MaxDistance,
CastsShadows = false, // No shadows in the distance.
});
// Grass, lots of it...
GameObjectService.Objects.Add(new VegetationObject(Services, grassMesh, numberOfInstancesPerCell * 10, 10, 20, 20, 3)
{
Name = "Grass",
MaxDistance = 30,
CastsShadows = false,
});
CreateGuiControls();
}
private void CreateGuiControls()
{
var panel = SampleFramework.AddOptions("Vegetation");
var swayPanel = SampleHelper.AddGroupBox(panel, "Swaying");
SampleHelper.AddSlider(
swayPanel,
"Wind wave frequency",
"F2",
0,
0.5f,
_windWaveFrequency,
value =>
{
_windWaveFrequency = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Wind wave randomness",
"F2",
0,
1,
_windWaveRandomness,
value =>
{
_windWaveRandomness = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Trunk frequency multiplier",
"F2",
0,
10,
_trunkFrequencyMultiplier,
value =>
{
_trunkFrequencyMultiplier = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Branch frequency multiplier",
"F2",
0,
10,
_branchFrequencyMultiplier,
value =>
{
_branchFrequencyMultiplier = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Trunk scale multiplier",
"F2",
0,
10,
_trunkScaleMultiplier,
value =>
{
_trunkScaleMultiplier = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Branch scale multiplier",
"F2",
0,
10,
_branchScaleMultiplier,
value =>
{
_branchScaleMultiplier = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddSlider(
swayPanel,
"Leaf scale multiplier",
"F2",
0,
10,
_leafScaleMultiplier,
value =>
{
_leafScaleMultiplier = value;
UpdateMaterialEffectParameters();
});
SampleHelper.AddDropDown(
swayPanel,
"Render vertex color",
EnumHelper.GetValues(typeof(VertexColorChannel)),
0,
item =>
{
_vertexColorChannel = (VertexColorChannel)item;
UpdateMaterialEffectParameters();
});
SampleHelper.AddCheckBox(
panel,
"Enable translucency",
true,
isChecked =>
{
_enableTranslucency = isChecked;
UpdateMaterialEffectParameters();
});
SampleHelper.AddCheckBox(
panel,
"Draw debug info",
_drawDebugInfo,
isChecked => _drawDebugInfo = isChecked);
SampleFramework.ShowOptionsWindow("Vegetation");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Unload content.
// (We have changed the properties of some loaded materials. Other samples
// should use the default values. When we unload them now, the next sample
// will reload them with default values.)
ContentManager.Unload();
}
base.Dispose(disposing);
}
public override void Update(GameTime gameTime)
{
_graphicsScreen.DebugRenderer.Clear();
if (_drawDebugInfo)
{
// Yellow bounding boxes.
_graphicsScreen.DebugRenderer.DrawObjects(
_graphicsScreen.Scene
.GetDescendants()
.Where(node => node is MeshNode || node is LodGroupNode)
.Cast<IGeometricObject>(), // This cast is only required to compile on Xbox.
Color.Yellow,
true,
false);
}
}
/// <summary>
/// Updates the material effect parameters for the vegetation and grass effects.
/// </summary>
private void UpdateMaterialEffectParameters()
{
// The parameters which are changed here are "Material" parameters (see enumeration
// EffectParameterHint). That means, the effect parameters are shared per material. We
// only need to update the effect parameter bindings of each mesh to update all mesh
// instances. - On the downside, this means that two instances cannot use different
// parameter values.
// When this method is called the first time, the default values of certain effect
// parameters are stored in a dictionary.
foreach (var mesh in _meshes)
{
foreach (var material in mesh.Materials)
{
foreach (var entry in material)
{
var name = entry.Key;
var effectBinding = entry.Value;
// The DeferredGraphicsScreen uses following render passes:
if (name == "GBuffer" || name == "ShadowMap" || name == "Material")
{
if (name == "Material")
{
// Update "TranslucencyColor".
var translucencyColorBinding = (ConstParameterBinding<Vector3>)effectBinding.ParameterBindings["TranslucencyColor"];
Vector3 defaultTranslucency;
if (!_defaultEffectParameterValues.TryGetValue(translucencyColorBinding, out defaultTranslucency))
{
defaultTranslucency = translucencyColorBinding.Value;
_defaultEffectParameterValues[translucencyColorBinding] = defaultTranslucency;
}
if (_enableTranslucency)
translucencyColorBinding.Value = defaultTranslucency;
else
translucencyColorBinding.Value = new Vector3(0, 0, 0);
// Update "VertexColorMask" (only used for debugging).
if (effectBinding.ParameterBindings.Contains("VertexColorMask"))
{
var vertexColorMaskBinding = (ConstParameterBinding<Vector3>)effectBinding.ParameterBindings["VertexColorMask"];
switch (_vertexColorChannel)
{
case VertexColorChannel.None:
vertexColorMaskBinding.Value = new Vector3(0, 0, 0);
break;
case VertexColorChannel.Red:
vertexColorMaskBinding.Value = new Vector3(1, 0, 0);
break;
case VertexColorChannel.Green:
vertexColorMaskBinding.Value = new Vector3(0, 1, 0);
break;
case VertexColorChannel.Blue:
vertexColorMaskBinding.Value = new Vector3(0, 0, 1);
break;
}
}
}
// Update "WindWaveParameters".
var windWaveParametersBinding = (ConstParameterBinding<Vector2>)effectBinding.ParameterBindings["WindWaveParameters"];
windWaveParametersBinding.Value = new Vector2(_windWaveFrequency, _windWaveRandomness);
// Update "SwayFrequencies".
var swayFrequenciesBinding = (ConstParameterBinding<Vector3>)effectBinding.ParameterBindings["SwayFrequencies"];
Vector3 defaultFrequencies;
if (!_defaultEffectParameterValues.TryGetValue(swayFrequenciesBinding, out defaultFrequencies))
{
defaultFrequencies = swayFrequenciesBinding.Value;
_defaultEffectParameterValues[swayFrequenciesBinding] = defaultFrequencies;
}
swayFrequenciesBinding.Value = new Vector3(
defaultFrequencies.X * _trunkFrequencyMultiplier,
defaultFrequencies.Y * _branchFrequencyMultiplier,
0); // not yet used in the effects.
// Update "SwayScales".
var swayScalesBinding = (ConstParameterBinding<Vector3>)effectBinding.ParameterBindings["SwayScales"];
Vector3 defaultScales;
if (!_defaultEffectParameterValues.TryGetValue(swayScalesBinding, out defaultScales))
{
defaultScales = swayScalesBinding.Value;
_defaultEffectParameterValues[swayScalesBinding] = defaultScales;
}
swayScalesBinding.Value = new Vector3(
defaultScales.X * _trunkScaleMultiplier,
defaultScales.Y * _branchScaleMultiplier,
defaultScales.Z * _leafScaleMultiplier);
}
}
}
}
}
}
}
#endif
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.CdmFolders.SampleLibraries
{
using System;
using System.IO;
using Microsoft.CdmFolders.SampleLibraries.SerializationHelpers;
using Newtonsoft.Json;
/// <summary>
/// Partition
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class Partition : DataObject
{
/// <summary>
/// Gets or sets the Refresh Time
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset? RefreshTime { get; set; }
/// <summary>
/// Gets or sets location
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Uri Location { get; set; }
/// <summary>
/// Gets or sets file format settings
/// </summary>
/// <remarks>The usage of <see cref="TypeNameHandling.Auto"/> was approved in this by Azure security team since the TypeNameSerializationBinder limits the scope only to this assembly</remarks>
[JsonProperty(TypeNameHandling = TypeNameHandling.Auto, NullValueHandling = NullValueHandling.Ignore, Order = SerializationOrderConstants.ObjectSerializationOrder)]
public FileFormatSettings FileFormatSettings { get; set; }
/// <summary>
/// Clones the partition
/// </summary>
/// <returns>A clone of the partition</returns>
public Partition Clone()
{
var clone = new Partition();
clone.CopyFrom(this);
clone.Parent = null;
return clone;
}
/// <summary>
/// Copy from other data object
/// </summary>
/// <param name="other">The other data object</param>
protected void CopyFrom(Partition other)
{
base.CopyFrom(other);
this.RefreshTime = other.RefreshTime;
this.Location = (other.Location == null) ? null : new UriBuilder(other.Location).Uri;
this.FileFormatSettings = other.FileFormatSettings?.Clone();
}
}
}
|
#region Using
using System;
#endregion
namespace NMock.Syntax
{
/// <summary>
/// Contains the methods that define the expectation for either a property, method, or event.
/// </summary>
/// <typeparam name="TInterface">The interface or class being mocked.</typeparam>
/// <remarks>
/// This interface defines generic methods that take lambda expressions.
/// </remarks>
public interface IMethodSyntax<TInterface> : IStubSyntax<TInterface>, IMethodSyntax
{
#region SetProperty
/// <summary>
/// Creates an expectation that this property will be set to a value specified in the
/// <see cref="IAutoValueSyntax{TProperty}"/> result of this method. The value used in the expression
/// is ignored.
/// </summary>
/// <typeparam name="TProperty"></typeparam>
/// <param name="expression">A set property expression that specifies the property to be set.</param>
/// <remarks>
/// If the property specified in the expression has a getter, a value isn't required in the expression.
/// <code>
/// mock.Expects.One.SetProperty(p => p.Prop)
/// </code>
/// instead of
/// <code>
/// mock.Expects.One.SetProperty(p => p.Prop = "Ignored Value")
/// </code>
/// The code above only needs to be used in cases where the property is write-only.
/// </remarks>
/// <returns></returns>
IAutoValueSyntax<TProperty> SetProperty<TProperty>(Func<TInterface, TProperty> expression);
/// <summary>
/// Creates an expectation that this property will be set to the specified value.
/// </summary>
/// <param name="action">z => z.prop = 0</param>
/// <returns>An <see cref="ICommentSyntax"/> object to specify the comment for the expectation. </returns>
IActionSyntax SetPropertyTo(Action<TInterface> action);
#endregion
}
} |
using Forge.Entities.Implementation.Content;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Forge.Entities.Tests {
internal class TestSnapshotBuilder {
public IGameSnapshot Snapshot = LevelManager.CreateSnapshot();
public TestEntityBuilder NewEntity() {
return new TestEntityBuilder(Snapshot.CreateEntity());
}
public TestEntityBuilder NewEntity(GameSnapshot.EntityAddTarget addTarget) {
return new TestEntityBuilder(((GameSnapshot)Snapshot).CreateEntity(addTarget));
}
}
internal class TestEntityBuilder {
public IEntity Entity;
public TestEntityBuilder(IEntity entity) {
Entity = entity;
}
public TestEntityBuilder AddData<TData>(TData data) where TData : Data.IVersioned {
((TData)Entity.AddData(new DataAccessor(data))).CopyFrom(data);
return this;
}
public TestEntityBuilder AddData<TData>(Action<TData> initializer) where TData : Data.IData {
TData allocated = Entity.AddData<TData>();
initializer(allocated);
return this;
}
}
internal class TestTemplateGroupBuilder {
public ITemplateGroup TemplateGroup = LevelManager.CreateTemplateGroup();
public TestTemplateBuilder NewTemplate {
get {
return new TestTemplateBuilder(TemplateGroup.CreateTemplate());
}
}
}
internal class TestTemplateBuilder {
public ITemplate Template;
public TestTemplateBuilder(ITemplate template) {
Template = template;
}
public TestTemplateBuilder AddData<TData>(TData data) where TData : Data.IData {
Template.AddDefaultData(data);
return this;
}
}
internal class SnapshotTemplateData : IEnumerable<object[]> {
private static void AddData(List<object[]> data,
Func<ITemplateGroup, IGameSnapshot> snapshot, ITemplateGroup templateGroup) {
data.Add(new object[] { snapshot(templateGroup), templateGroup });
}
public IEnumerator<object[]> GetEnumerator() {
var data = new List<object[]>();
foreach (ITemplateGroup templateGroup in new[] {
// list all template group providers here
TemplateGroup1(),
TemplateGroup2()
}) {
// list all snapshot providers here
AddData(data, Snapshot1, templateGroup);
AddData(data, Snapshot2, templateGroup);
AddData(data, Snapshot3, templateGroup);
}
return data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public static DataReference<TData> CreateDataReference<TData>(IQueryableEntity entity)
where TData : Data.IData {
var dataReference = new DataReference<TData>();
((IDataReference)dataReference).Provider = entity;
return dataReference;
}
public static ITemplateGroup TemplateGroup1() {
return LevelManager.CreateTemplateGroup();
}
public static ITemplateGroup TemplateGroup2() {
var builder = new TestTemplateGroupBuilder();
builder.NewTemplate
.AddData(new DataEmpty());
ITemplate template1 = builder.NewTemplate
.AddData(new DataEmpty())
.AddData(new DataInt() { A = 90 })
.Template;
builder.NewTemplate
.AddData(new DataEmpty())
.AddData(new DataInt() { A = 100 });
builder.NewTemplate
.AddData(new DataNonVersionedInt() { A = 110 });
builder.NewTemplate
.AddData(new DataEmpty())
.AddData(new DataNonVersionedInt() { A = 110 });
builder.NewTemplate
.AddData(new DataTemplate() { Template = template1 });
builder.NewTemplate
.AddData(new DataDataReference() {
DataReference = CreateDataReference<DataEmpty>(template1)
});
return builder.TemplateGroup;
}
public static IGameSnapshot Snapshot1(ITemplateGroup templates) {
return LevelManager.CreateSnapshot();
}
public static IGameSnapshot Snapshot2(ITemplateGroup templates) {
TestSnapshotBuilder builder = new TestSnapshotBuilder();
{
builder.NewEntity();
builder.NewEntity()
.AddData(new DataEmpty());
IEntity entity1 = builder.NewEntity()
.AddData(new DataInt() { A = 10 })
.Entity;
builder.NewEntity()
.AddData(new DataEmpty())
.AddData(new DataInt() { A = 20 });
builder.NewEntity()
.AddData(new DataDataReference() { DataReference = CreateDataReference<DataEmpty>(entity1) });
builder.NewEntity()
.AddData<DataNonVersionedInt>(data => data.A = 500);
builder.NewEntity()
.AddData(new DataEmpty())
.AddData<DataNonVersionedInt>(data => data.A = 510);
}
{
builder.NewEntity(GameSnapshot.EntityAddTarget.Active);
for (int i = 0; i < 5; ++i) {
builder.NewEntity(GameSnapshot.EntityAddTarget.Active)
.AddData(new DataEmpty());
builder.NewEntity(GameSnapshot.EntityAddTarget.Active)
.AddData(new DataInt { A = 30 });
builder.NewEntity(GameSnapshot.EntityAddTarget.Active)
.AddData(new DataEmpty())
.AddData(new DataInt { A = 40 });
}
}
{
builder.NewEntity(GameSnapshot.EntityAddTarget.Removed)
.AddData(new DataEmpty());
builder.NewEntity(GameSnapshot.EntityAddTarget.Removed)
.AddData(new DataInt { A = 70 });
builder.NewEntity(GameSnapshot.EntityAddTarget.Removed)
.AddData(new DataEmpty())
.AddData(new DataInt() { A = 80 });
}
return builder.Snapshot;
}
public static IGameSnapshot Snapshot3(ITemplateGroup templates) {
var builder = new TestSnapshotBuilder();
{
builder.NewEntity()
.AddData(new DataEmpty());
IEntity entity1 = builder.NewEntity()
.AddData(new DataInt() { A = 10 })
.Entity;
builder.NewEntity()
.AddData(new DataEmpty())
.AddData(new DataInt() { A = 20 });
IEntity entity3 = builder.NewEntity()
.AddData(new DataDataReference() { DataReference = CreateDataReference<DataEmpty>(entity1) })
.Entity;
builder.NewEntity()
.AddData(new DataEntity() { Entity = entity3 });
IEntity entity5 = builder.Snapshot.CreateEntity();
entity5.AddData<DataEntity>().Entity = entity5;
builder.NewEntity()
.AddData(new DataQueryableEntity() { QueryableEntity = entity5 });
IEntity entity7 = builder.Snapshot.CreateEntity();
entity7.AddData<DataQueryableEntity>().QueryableEntity = entity7;
}
if (templates.Templates.Count() > 0) {
ITemplate template = templates.Templates.First();
builder.NewEntity()
.AddData(new DataDataReference() { DataReference = CreateDataReference<DataEmpty>(template) });
builder.NewEntity()
.AddData(new DataQueryableEntity() { QueryableEntity = template });
}
return builder.Snapshot;
}
}
} |
using FilterPattern.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FilterPattern.Criteria
{
public class CriteriaSingle : IPersonCriteria
{
public IList<Person> MeetCriteria(IList<Person> persons)
{
return persons.Where(person => person.MaritalStatus == MaritalStatus.Single).ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PassboltSharp.Models
{
public class Permission : BaseResource
{
public string Aco;
public string Aro;
public int Type;
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class HighScore : MonoBehaviour
{
#region Awake
private void Awake()
{
}
#endregion
public Text _txtScoreUI;
#region Public Properties
public int _highScore {
get { return _scr; }
set { _scr = value;
_txtScoreUI.text = _highScore.ToString();
PlayerPrefs.SetInt("HighScore", _highScore);
}
}
#endregion
#region Init
private void Start()
{
_scr = 0;
}
#endregion
private int _scr;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace SpeckleUnityConverter
{
class SpecklePrefabs : MonoBehaviour
{
public static SpecklePrefabs Instance { get; private set; }
public GameObject MeshPrefab;
public GameObject LinePrefab;
public GameObject PointPrefab;
void Awake()
{
if (Instance != null)
{
Destroy(this);
throw new InvalidOperationException("A Converter component has already been instantiated");
}
Instance = this;
}
void OnDestroy()
{
if (Instance == this)
{
Instance = null;
}
}
public static GameObject InstantiateMesh()
{
return Instantiate(Instance.MeshPrefab);
}
public static GameObject InstantiateLine()
{
return Instantiate(Instance.LinePrefab);
}
public static GameObject InstantiatePoint()
{
return Instantiate(Instance.PointPrefab);
}
}
}
|
using GraphQL.EntityFramework;
public class ChildGraph : EfObjectGraphType<ChildEntity>
{
public ChildGraph(IEfGraphQLService graphQlService) : base(graphQlService)
{
Field(x => x.Id);
Field(x => x.Property);
Field(x => x.Nullable, true);
AddNavigationField<ParentGraph, ParentEntity>(
name: "parent",
resolve: context => context.Source.Parent);
AddNavigationField<ParentGraph, ParentEntity>(
name: "parentAlias",
resolve: context => context.Source.Parent,
includeNames: new []{"Parent"});
}
} |
using DataAccess.Model;
using DataAccess.Repositories;
using System;
using System.Linq;
namespace BusinessLogic
{
public class SubjectManager : IDisposable
{
private SubjectRepository subjectRepository;
public SubjectManager()
{
subjectRepository = new SubjectRepository();
}
public IQueryable<Subject> GetAllSubjects()
{
return subjectRepository.GetAll();
}
public void Dispose()
{
if (subjectRepository != null)
subjectRepository.Dispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace SEDC.Quiz.Data.Models
{
public class Question
{
public string QuestionText { get; set; }
public string AnswerA { get; set; }
public string AnswerB { get; set; }
public string AnswerC { get; set; }
public string AnswerD { get; set; }
public string CorectAnswer { get; set; }
public Question()
{
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace MPS.Data.EF.Configuration
{
public interface IBaseEntityTypeConfiguration<T> : IEntityTypeConfiguration<T> where T : class
{
}
} |
using System.Collections.Generic;
using System.Linq;
using SharpX.Compiler.Composition.Abstractions;
using SharpX.Compiler.Composition.Interfaces;
namespace SharpX.Compiler.ShaderLab.Models.HLSL.Statements
{
internal class Constructor : INestableStatement
{
private readonly List<IStatement> _arguments;
private readonly string _ctor;
public Constructor(string ctor)
{
_ctor = ctor;
_arguments = new List<IStatement>();
}
public void WriteTo(SourceBuilder sb)
{
sb.WriteSpan($"{_ctor}(");
foreach (var (argument, i) in _arguments.Select((w, i) => (w, i)))
{
if (i > 0)
sb.WriteSpan(", ");
argument.WriteTo(sb);
}
sb.WriteSpan(")");
}
public void AddSourcePart(INestableStatement statement)
{
_arguments.Add(statement);
}
public void AddSourcePart(IStatement statement)
{
_arguments.Add(statement);
}
}
} |
using System;
using System.Reactive;
using System.Reactive.Linq;
using Microsoft.Reactive.Testing;
using Xunit;
using RxLibrary;
using Xunit.Abstractions;
namespace RxLibrary.Tests
{
public class CreatColdObservableTests : ReactiveTest
{
[Fact]
public void CreatColdObservable_ShortWay()
{
var testScheduler = new TestScheduler();
ITestableObservable<int> coldObservable =
testScheduler.CreateColdObservable<int>(
// Inheritting your test class from ReactiveTest opens the following
// factory methods that make your code much more fluent
OnNext(20, 1),
OnNext(40, 2),
OnNext(60, 2),
OnCompleted<int>(900)
);
// Creating an observer that captures the emission it recieves
var testableObserver = testScheduler.CreateObserver<int>();
// Subscribing the observer, but until TestSchduler is started, emissions
// are not be emitted
coldObservable
.Subscribe(testableObserver);
// Starting the TestScheduler means that only now emissions that were configured
// will be emitted
testScheduler.Start();
// Asserting that every emitted value was recieved by the observer at the
// same time it was emitted
coldObservable.Messages
.AssertEqual(testableObserver.Messages);
// Asserting that the observer was subscribed at Scheduler inital time
coldObservable.Subscriptions.AssertEqual(
Subscribe(0));
}
[Fact]
public void CreatColdObservable_LongWay()
{
var testScheduler = new TestScheduler();
ITestableObservable<int> coldObservable = testScheduler.CreateColdObservable<int>(
// This is the long way to configure emissions. see below for a shorter one
new Recorded<Notification<int>>(20, Notification.CreateOnNext<int>(1)),
new Recorded<Notification<int>>(40, Notification.CreateOnNext<int>(2)),
new Recorded<Notification<int>>(60, Notification.CreateOnCompleted<int>())
);
// Creating an observer that captures the emission it recieves
var testableObserver = testScheduler.CreateObserver<int>();
// Subscribing the observer, but until TestSchduler is started, emissions
// are not be emitted
coldObservable
.Subscribe(testableObserver);
// Starting the TestScheduler means that only now emissions that were configured
// will be emitted
testScheduler.Start();
// Asserting that every emitted value was recieved by the observer at the
// same time it was emitted
coldObservable.Messages
.AssertEqual(testableObserver.Messages);
// Asserting that the observer was subscribed at Scheduler inital time
coldObservable.Subscriptions.AssertEqual(
Subscribe(0));
}
}
} |
using System;
using System.Net;
namespace LumiSoft.Net.Mail
{
// Token: 0x02000186 RID: 390
public class Mail_t_TcpInfo
{
// Token: 0x06001017 RID: 4119 RVA: 0x000646C8 File Offset: 0x000636C8
public Mail_t_TcpInfo(IPAddress ip, string hostName)
{
bool flag = ip == null;
if (flag)
{
throw new ArgumentNullException("ip");
}
this.m_pIP = ip;
this.m_HostName = hostName;
}
// Token: 0x06001018 RID: 4120 RVA: 0x00064710 File Offset: 0x00063710
public override string ToString()
{
bool flag = string.IsNullOrEmpty(this.m_HostName);
string result;
if (flag)
{
result = "[" + this.m_pIP.ToString() + "]";
}
else
{
result = this.m_HostName + " [" + this.m_pIP.ToString() + "]";
}
return result;
}
// Token: 0x1700056B RID: 1387
// (get) Token: 0x06001019 RID: 4121 RVA: 0x00064770 File Offset: 0x00063770
public IPAddress IP
{
get
{
return this.m_pIP;
}
}
// Token: 0x1700056C RID: 1388
// (get) Token: 0x0600101A RID: 4122 RVA: 0x00064788 File Offset: 0x00063788
public string HostName
{
get
{
return this.m_HostName;
}
}
// Token: 0x04000680 RID: 1664
private IPAddress m_pIP = null;
// Token: 0x04000681 RID: 1665
private string m_HostName = null;
}
}
|
@model EstateSocialSystem.Web.Areas.Administration.ViewModels.AdministerApplianceViewModel
<h2>AdministerApplianceViewModel</h2>
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(e => e.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.EditorFor(e => e.Name, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(e => e.Type, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.EditorFor(e => e.Type, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(e => e.Power, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.EditorFor(e => e.Power, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(e => e.Input, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.EditorFor(e => e.Input, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(e => e.Output, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.EditorFor(e => e.Output, new { @class = "form-control" })
</div>
</div>
|
using System;
namespace Standard
{
[Flags]
internal enum WTNCA : uint
{
NODRAWCAPTION = 1u,
NODRAWICON = 2u,
NOSYSMENU = 4u,
NOMIRRORHELP = 8u,
VALIDBITS = 15u
}
}
|
using Pizza.Contracts.Security.ViewModels;
namespace KebabManager.Contracts.ViewModels
{
public class KebabUserViewModel : PizzaUserViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
} |
using Newtonsoft.Json;
using System;
namespace HelperFunctions.Business
{
public class FantasyFootballParser
{
public FantasyFootball Parse(string fantasyFootballJson)
{
var fantasyFootball = JsonConvert.DeserializeObject<FantasyFootball>(fantasyFootballJson);
return fantasyFootball;
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Totem.Runtime.Hosting;
using Totem.Timeline.Area;
namespace Totem.Timeline.Hosting
{
/// <summary>
/// Extends <see cref="IServiceCollection"/> to declare the timeline area
/// </summary>
public static class TimelineAreaServiceExtensions
{
public static IServiceCollection AddAreaMap(this IServiceCollection services) =>
services.AddSingleton(p =>
{
var options = p.GetOptions<TimelineAreaOptions>();
return AreaMap.From(options.Types);
});
public static IServiceCollection ConfigureArea(this IServiceCollection services, IEnumerable<Type> types) =>
services.Configure<TimelineAreaOptions>(options => options.Types.AddRange(types));
public static IServiceCollection ConfigureArea<TArea>(this IServiceCollection services) where TArea : TimelineArea, new() =>
services.ConfigureArea(new TArea().GetTypes());
}
} |
//<Snippet1>
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
namespace SecurityRulesLibrary
{
[SuppressUnmanagedCodeSecurityAttribute()]
public class BadTypeWithPublicPInvokeAndSuppress
{
[DllImport("native.dll")]
public static extern void DoDangerousThing();
public void DoWork()
{
// Note that because DoDangerousThing is public, this
// security check does not resolve the violation.
// This only checks callers that go through DoWork().
SecurityPermission secPerm = new SecurityPermission(
SecurityPermissionFlag.ControlPolicy |
SecurityPermissionFlag.ControlEvidence
);
secPerm.Demand();
DoDangerousThing();
}
}
}
//</Snippet1>
|
// Copyright 2020 by PeopleWare n.v..
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;
using PPWCode.Util.Validation.III.European.Belgium;
namespace PPWCode.Util.Validation.III.UnitTests.European.Belgium
{
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Test")]
[SuppressMessage("ReSharper", "UnusedMember.Local", Justification = "Test")]
public class INSSTests : BaseTests
{
public static IEnumerable InvalidIdentifications
{
get
{
yield return null;
yield return string.Empty;
yield return "1";
yield return "12341234";
}
}
public static IEnumerable StrictValidIdentifications
{
get
{
yield return "55250200801";
yield return "01410191175";
yield return "00030610329";
}
}
public static IEnumerable ValidIdentifications
{
get
{
foreach (object inss in StrictValidIdentifications)
{
yield return inss;
}
yield return "1410191175";
yield return "30610329";
yield return "BE 55250200801";
yield return "BE 55.25.02 008-01";
}
}
public static IEnumerable PaperVersions
{
get
{
yield return new TestCaseData("55250200801").Returns("55.25.02-008.01");
yield return new TestCaseData("BE 55250200801").Returns("55.25.02-008.01");
}
}
private static IEnumerable BisNumbers
{
get
{
foreach (object inss in InvalidIdentifications)
{
yield return new TestCaseData(inss).Returns(null);
}
yield return new TestCaseData("08082207107").Returns(false);
yield return new TestCaseData("56252201101").Returns(true);
yield return new TestCaseData("01410191175").Returns(true);
}
}
private static IEnumerable BirthDates
{
get
{
yield return new TestCaseData("06102614576").Returns(new DateTime(2006, 10, 26));
yield return new TestCaseData("08290801251").Returns(new DateTime(2008, 09, 08));
yield return new TestCaseData("08511500896").Returns(new DateTime(2008, 11, 15));
yield return new TestCaseData("09051132455").Returns(new DateTime(1909, 05, 11));
yield return new TestCaseData("24210700548").Returns(new DateTime(1924, 01, 07));
yield return new TestCaseData("09501001134").Returns(new DateTime(1909, 10, 10));
yield return new TestCaseData("00081503486").Returns(new DateTime(2000, 8, 15));
}
}
private static IEnumerable Sexes
{
get
{
yield return new TestCaseData("06102614576").Returns(Sexe.MALE);
yield return new TestCaseData("08290801251").Returns(null);
yield return new TestCaseData("09051132455").Returns(Sexe.FEMALE);
}
}
[Test]
[TestCaseSource(nameof(ValidIdentifications))]
public void check_binairy_serializable(string identification)
{
// Arrange
INSS expected = new INSS(identification);
// Act
INSS actual = DeepCloneUsingBinaryFormatter(expected);
// Assert
Assert.That(actual, Is.Not.Null);
Assert.That(actual.RawVersion, Is.EquivalentTo(expected.RawVersion));
}
[Test]
[TestCaseSource(nameof(BirthDates))]
public DateTime? check_birthdate(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
return inss.BirthDate;
}
[Test]
[TestCaseSource(nameof(BisNumbers))]
public bool? check_bis_numbers(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
return inss.IsBisNumber;
}
[Test]
[TestCaseSource(nameof(PaperVersions))]
public string check_paperversion(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
Assert.That(inss.IsValid, Is.True);
Assert.That(inss.ElectronicVersion, Is.Not.Null);
return inss.PaperVersion;
}
[Test]
[TestCaseSource(nameof(InvalidIdentifications))]
public void inss_is_not_valid(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
Assert.That(inss.IsValid, Is.False);
Assert.That(inss.IsStrictValid, Is.False);
Assert.That(inss.ElectronicVersion, Is.Null);
Assert.That(inss.PaperVersion, Is.Null);
}
[Test]
[TestCaseSource(nameof(StrictValidIdentifications))]
public void inss_is_strict_valid(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
Assert.That(inss.IsValid, Is.True);
Assert.That(inss.IsStrictValid, Is.True);
Assert.That(inss.ElectronicVersion, Is.EqualTo(inss.CleanedVersion));
Assert.That(inss.ElectronicVersion, Is.EqualTo(inss.RawVersion));
Assert.That(inss.PaperVersion, Is.Not.Null);
}
[Test]
[TestCaseSource(nameof(ValidIdentifications))]
public void inss_is_valid(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
Assert.That(inss.IsValid, Is.True);
Assert.That(inss.ElectronicVersion, Is.Not.Null);
Assert.That(inss.PaperVersion, Is.Not.Null);
}
[Test]
[TestCaseSource(nameof(Sexes))]
public Sexe? inss_sexe(string identification)
{
// Arrange
INSS inss = new INSS(identification);
// Act
// Assert
return inss.Sexe;
}
}
}
|
// 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.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace NuGet.Services.Metadata.Catalog.Monitoring
{
public class SearchHasVersionValidator : Validator<SearchEndpoint>
{
public SearchHasVersionValidator(
SearchEndpoint endpoint,
ValidatorConfiguration config,
ILogger<Validator> logger)
: base(endpoint, config, logger)
{
}
protected override async Task RunInternalAsync(ValidationContext context)
{
var searchVisible = await IsVisibleInSearchAsync(context);
var databaseState = await GetDatabaseStateAsync(context);
var databaseVisible = databaseState == DatabaseState.Listed;
if (databaseVisible != searchVisible)
{
const string listedString = "listed";
const string unlistedString = "unlisted";
throw new MetadataInconsistencyException(
$"Database shows {databaseState.ToString().ToLowerInvariant()}" +
$" but search shows {(searchVisible ? listedString : unlistedString)}.");
}
}
private async Task<bool> IsVisibleInSearchAsync(ValidationContext context)
{
var searchPage = await context.GetSearchPageForIdAsync(Endpoint.BaseUri);
var searchItem = searchPage.SingleOrDefault();
bool searchListed;
if (searchItem != null)
{
var searchVersions = await searchItem.GetVersionsAsync();
searchListed = searchVersions.Any(x => x.Version == context.Package.Version);
}
else
{
searchListed = false;
}
return searchListed;
}
private static async Task<DatabaseState> GetDatabaseStateAsync(ValidationContext context)
{
var databaseResult = await context.GetIndexDatabaseAsync();
if (databaseResult == null)
{
return DatabaseState.Unavailable;
}
return databaseResult.Listed ? DatabaseState.Listed : DatabaseState.Unlisted;
}
private enum DatabaseState
{
Unavailable,
Unlisted,
Listed,
}
}
}
|
namespace bsn_sdk_csharp
{
public class FileConfig
{
public string NodeApi { get; set; }
public string UserCode { get; set; }
public string AppCode { get; set; }
public string UserPrivateKey { get; set; }
public string BsnPublicKey { get; set; }
public string MspPath { get; set; }
}
} |
using UnityEngine;
namespace HT.Framework
{
/// <summary>
/// 异常信息
/// </summary>
public sealed class ExceptionInfo : IReference
{
/// <summary>
/// 异常类型
/// </summary>
public LogType Type;
/// <summary>
/// 异常日志
/// </summary>
public string LogString;
/// <summary>
/// 异常堆栈信息
/// </summary>
public string StackTrace;
public ExceptionInfo Fill(string logString, string stackTrace, LogType type)
{
Type = type;
LogString = logString;
StackTrace = stackTrace;
return this;
}
public void Reset()
{
Type = LogType.Error;
LogString = "";
StackTrace = "";
}
}
} |
namespace JG.FinTechTest.GiftAid
{
public class TaxRateStorage : IStoreTaxRate
{
public TaxRateStorage()
{
CurrentRate = 20M;
}
public decimal CurrentRate { get; }
}
} |
namespace Vorlesung_11.Windows
{
using System;
using System.Windows;
using Vorlesung_11.Model;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private static void ShowWindow(Func<IUser> createUser)
{
var window = new DataBindingWindow(createUser);
window.Show();
}
private void POCO_OnClick(object sender, RoutedEventArgs e) => ShowWindow(() => new User());
private void INPC_OnClick(object sender, RoutedEventArgs e) => ShowWindow(() => new UserWithINPC());
private void BindableBase_OnClick(object sender, RoutedEventArgs e) => ShowWindow(() => new UserWithBase());
}
}
|
using PrefixTree;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace PrefixTreeTests
{
public class PrefixTreeTests_Emoji
{
[Theory]
// Format: <prefix to find>, <match that MUST be returned from tree>, [Words to add to Tree]
//
// This is an odd tests, as it's treating complex Emoji's as words. In reality, most emoji's
// are grapheme's that combine many "letters" into a single word, by treating each letter as
// an attribute. This mechanism allows us leveraget the prefix list. As the first "letter" of
// an emoji is typed, the subset of possible emoji's is returned. For example, the first flag
// below is made from 7 UTF-32 Codepoints that "look" like a single character on the screen.
// The Unicode list of Emoji's is here: http://unicode.org/emoji/charts/full-emoji-list.html
// The ones selected below are in the #1555 (Skull + Crossbones), #1814 (flag of England),
// #1815 (flag of Scotland), #1816 (flag of Wales)
//
// Note: The first codepoint in each of the 4 Emoji's below is U+1F3F4.
// The Full "Word" for the first flag (Note UTF-32 Codepoints) is:
// U+1F3F4 U+E0067 U+E0062 U+E0065 U+E006E U+E0067 U+E007F
// The full "Word" of the Skull and Crossbones 🏴☠️ is: (Note that different fonts render this differently).
// U+1F3F4 U+200D U+2620 U+FE0F
// The UTF-16 encoding of this first "letter" (U+1F3F4) is: U+D83C U+DFF4
[InlineData("\uD83C\uDFF4", new string[] { "🏴", "🏴", "🏴", "🏴☠️" })]
public void EmojiMultiMatchesTheory(string prefixToFind, string[] exactMatches)
{
// Arrange
ImmutablePrefixTree tree = CreateFromEmojiWordList();
// The strings that come in for exact match may be non-normalized. As the
// prefix tree returns only normlaized strings, make sure these are properly
// stringprepped for comparison. See here for a refresher if needed:
// https://docs.microsoft.com/en-us/dotnet/api/system.string.normalize?view=net-5.0
List<string> normalizedMatches = new List<string>();
foreach (string s in exactMatches)
{
normalizedMatches.Add(PrefixTree.PrefixTree.NormalizeString(s));
}
// Act
var matchResults = tree.FindMatches(prefixToFind);
// Assert
Assert.True(matchResults.Count == exactMatches.Length);
foreach (var requiredMatch in normalizedMatches)
{
Assert.Contains(requiredMatch, matchResults);
}
}
private static ImmutablePrefixTree CreateFromEmojiWordList()
{
const string fileName = "Emoji.txt";
if (!File.Exists(fileName))
{
throw new FileNotFoundException("Emoji file is missing");
}
var allWords = File.ReadAllLines(fileName);
return PrefixTreeBuilder.CreatePrefixTree(allWords);
}
}
}
|
// FINISHED
// thx to http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited
using System.Data.Entity;
using Orc.EntityFramework.Repositories;
using Catel.Data;
using Catel.IoC;
using Orc.LicenseManager.Server.Repositories;
using Orc.LicenseManager.Server;
// REPOSITORIES
// REPOSITORIES INTERFACES
// REPOSITORIES Initializer
// AddReposToUoW
// UOW
|
using Mamesaver.Configuration;
using NUnit.Framework;
using SimpleInjector;
namespace Mamesaver.Test.Unit
{
public abstract class MamesaverTests
{
public Container Container { get; private set; }
[OneTimeSetUp]
public void SetupContainer() => Container = ContainerFactory.NewContainer();
/// <summary>
/// Retrieves an instance from the container
/// </summary>
public T GetInstance<T>() where T : class => Container.GetInstance<T>();
}
/// <summary>
/// Copy from main application due to ILMerge's internalisation resulting in the <see cref="NewContainer"/>
/// method being made internal.
/// </summary>
public static class ContainerFactory
{
public static Container NewContainer()
{
var container = new Container();
container.Register(() => container.GetInstance<GeneralSettingsStore>().Get());
container.Register(() => container.GetInstance<GameListStore>().GetGameList);
return container;
}
}
} |
using Microsoft.EntityFrameworkCore;
namespace QueryNinja.Targets.EntityFrameworkCore.Filters
{
/// <summary>
/// Represent operations defined by <see cref="EF.Functions"/> class.
/// </summary>
public enum DatabaseFunction
{
/// <summary>
/// Corresponds to SQL Like operation.
/// </summary>
Like = 1
}
} |
using HL7Data.Models.Types;
namespace HL7Data.Contracts.Packages
{
public interface IPackageValidationSetting
{
bool IgnoreAllValidations { get; set; }
ValidationSetting MaximumLength { get; set; }
ValidationSetting MinimumLength { get; set; }
ValidationSetting RequiredField { get; set; }
ValidationSetting TableValueLookup { get; set; }
}
} |
namespace DACbyEatMe
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.getProxies = new System.Windows.Forms.Button();
this.Start = new System.Windows.Forms.Button();
this.username = new System.Windows.Forms.TextBox();
this.inviteBox = new System.Windows.Forms.TextBox();
this.randomChecked = new System.Windows.Forms.CheckBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.closeButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// getProxies
//
this.getProxies.Location = new System.Drawing.Point(307, 114);
this.getProxies.Name = "getProxies";
this.getProxies.Size = new System.Drawing.Size(75, 23);
this.getProxies.TabIndex = 0;
this.getProxies.Text = "Get Proxies";
this.getProxies.UseVisualStyleBackColor = true;
this.getProxies.Click += new System.EventHandler(this.getProxies_Click);
//
// Start
//
this.Start.Location = new System.Drawing.Point(307, 85);
this.Start.Name = "Start";
this.Start.Size = new System.Drawing.Size(75, 23);
this.Start.TabIndex = 1;
this.Start.Text = "Start";
this.Start.UseVisualStyleBackColor = true;
this.Start.Click += new System.EventHandler(this.Start_Click);
//
// username
//
this.username.Location = new System.Drawing.Point(12, 12);
this.username.Name = "username";
this.username.Size = new System.Drawing.Size(129, 20);
this.username.TabIndex = 2;
this.username.Text = "Username";
this.username.TextChanged += new System.EventHandler(this.username_TextChanged);
//
// inviteBox
//
this.inviteBox.Location = new System.Drawing.Point(12, 66);
this.inviteBox.Name = "inviteBox";
this.inviteBox.Size = new System.Drawing.Size(129, 20);
this.inviteBox.TabIndex = 3;
this.inviteBox.Text = "Invite Links";
this.inviteBox.TextChanged += new System.EventHandler(this.inviteBox_TextChanged);
//
// randomChecked
//
this.randomChecked.AutoSize = true;
this.randomChecked.Location = new System.Drawing.Point(147, 14);
this.randomChecked.Name = "randomChecked";
this.randomChecked.Size = new System.Drawing.Size(117, 17);
this.randomChecked.TabIndex = 4;
this.randomChecked.Text = "Random Username";
this.randomChecked.UseVisualStyleBackColor = true;
this.randomChecked.CheckedChanged += new System.EventHandler(this.randomChecked_CheckedChanged);
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(12, 126);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(129, 20);
this.textBox3.TabIndex = 5;
this.textBox3.Text = "Another Stupid Textbox";
this.textBox3.TextChanged += new System.EventHandler(this.textBox3_TextChanged);
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Location = new System.Drawing.Point(147, 66);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(147, 17);
this.checkBox2.TabIndex = 6;
this.checkBox2.Text = "Another Stupid Checkbox";
this.checkBox2.UseVisualStyleBackColor = true;
this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged);
//
// closeButton
//
this.closeButton.Location = new System.Drawing.Point(307, 143);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(75, 23);
this.closeButton.TabIndex = 7;
this.closeButton.Text = "Close";
this.closeButton.UseVisualStyleBackColor = true;
this.closeButton.Click += new System.EventHandler(this.closeButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(394, 178);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.checkBox2);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.randomChecked);
this.Controls.Add(this.inviteBox);
this.Controls.Add(this.username);
this.Controls.Add(this.Start);
this.Controls.Add(this.getProxies);
this.Name = "Form1";
this.ShowIcon = false;
this.Text = "DAC by Eat Me";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button getProxies;
private System.Windows.Forms.Button Start;
private System.Windows.Forms.TextBox username;
private System.Windows.Forms.TextBox inviteBox;
private System.Windows.Forms.CheckBox randomChecked;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.Button closeButton;
}
}
|
namespace ArrayVisualizerControls
{
public enum ArrayRenderSection
{
Front,
Top,
Side
}
} |
namespace Furlong
{
/// <summary>
/// Represents a link in a Chain (of Responsibility).
/// </summary>
/// <typeparam name="TRequest">The type of the object that contains the data to be handled.</typeparam>
public interface IAsyncChainLink<TRequest> : IAsyncLink<TRequest>
{
/// <summary>
/// Set the next link in the chain.
/// </summary>
/// <param name="link"></param>
void SetNext(IAsyncChainLink<TRequest> link);
}
/// <summary>
/// Represents a link in a Chain (of Responsibility).
/// </summary>
/// <typeparam name="TRequest">The type of the object that contains the data to be handled.</typeparam>
/// <typeparam name="TResponse">The type of the object returned.</typeparam>
public interface IAsyncChainLink<TRequest, TResponse> : IAsyncLink<TRequest, TResponse>
{
/// <summary>
/// Set the next link in the chain.
/// </summary>
/// <param name="link"></param>
void SetNext(IAsyncChainLink<TRequest, TResponse> link);
}
} |
namespace GameDesigner
{
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 音效管理
/// </summary>
public class AudioManager : MonoBehaviour
{
[SerializeField]
private List<AudioSource> sources = new List<AudioSource>();
[SerializeField]
private List<AudioSource> destroyPlayingSources = new List<AudioSource>();
private static AudioManager _instance = null;
/// <summary>
/// 音效实例
/// </summary>
public static AudioManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<AudioManager>();
if (_instance == null)
{
_instance = new GameObject("AudioManager").AddComponent<AudioManager>();
DontDestroyOnLoad(_instance);
}
}
return _instance;
}
}
public static AudioManager I => Instance;
void Update()
{
for (int i = 0; i < destroyPlayingSources.Count; ++i)
{
if (!destroyPlayingSources[i].isPlaying)
{
Destroy(destroyPlayingSources[i]);
destroyPlayingSources.RemoveAt(i);
}
}
}
/// <summary>
/// 播放音效剪辑
/// 参数clip : 放入你要播放的音源
/// </summary>
public static void Play(AudioClip clip)
{
Play(clip, 1f);
}
/// <summary>
/// 播放音效剪辑
/// 参数clip : 放入你要播放的音源
/// 参数volume : 声音大小调节
/// </summary>
public static AudioSource Play(AudioClip clip, float volume)
{
return Play(clip, volume, false);
}
/// <summary>
/// 播放音效剪辑
/// 参数clip : 放入你要播放的音源
/// 参数volume : 声音大小调节
/// </summary>
public static AudioSource Play(AudioClip clip, float volume, bool loop)
{
if (clip == null)
return null;
for (int i = 0; i < I.sources.Count; ++i)
{
if (!I.sources[i].isPlaying)//如果音效剪辑存在 并且 音效没有被播放 则可以执行播放音效
{
I.sources[i].clip = clip;
I.sources[i].volume = volume;
I.sources[i].loop = loop;
if (loop)
I.sources[i].Play();
else
I.sources[i].PlayOneShot(clip, volume);
return I.sources[i];
}
}
AudioSource source = I.gameObject.AddComponent<AudioSource>();
I.sources.Add(source);
source.clip = clip;
source.volume = volume;
source.loop = loop;
if (loop)
source.Play();
else
source.PlayOneShot(clip, volume);
return source;
}
/// <summary>
/// 当音效播放完成销毁AudioSource组件
/// 参数clip : 放入你要播放的音源
/// </summary>
public static AudioSource OnPlayingDestroy(AudioClip clip)
{
return OnPlayingDestroy(clip, 1f); ;
}
/// <summary>
/// 当音效播放完成销毁AudioSource组件
/// 参数clip : 放入你要播放的音源
/// 参数volume : 声音大小调节
/// </summary>
public static AudioSource OnPlayingDestroy(AudioClip clip, float volume)
{
AudioSource source = Instance.gameObject.AddComponent<AudioSource>();
Instance.destroyPlayingSources.Add(source);
source.volume = volume;
source.clip = clip;
source.PlayOneShot(clip);
return source;
}
/// <summary>
/// 当音效播放完成销毁AudioSource组件
/// 参数clip : 放入你要播放的音源
/// 参数source : 音频源组件
/// </summary>
public static void OnPlayingDestroy(AudioSource source, AudioClip clip)
{
Instance.destroyPlayingSources.Add(source);
source.clip = clip;
source.PlayOneShot(clip);
}
public static AudioSource Stop(AudioClip clip)
{
if (clip == null)
return null;
for (int i = 0; i < I.sources.Count; ++i)
{
if (I.sources[i].clip == clip)
{
I.sources[i].Stop();
return I.sources[i];
}
}
return null;
}
public static AudioSource GetAudioSource(AudioClip clip)
{
if (clip == null)
return null;
for (int i = 0; i < I.sources.Count; ++i)
{
if (I.sources[i].clip == clip)
return I.sources[i];
}
return null;
}
}
} |
using UnityEngine;
public partial class Game {
public Canvas canvas;
void InitUI() {
canvas.worldCamera = Camera.main;
canvas.planeDistance = 1;
}
}
|
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ByteDev.Hibp.Http
{
internal static class HttpResponseMessageExtensions
{
public static async Task<T> DeserializeAsync<T>(this HttpResponseMessage source)
{
var json = await source.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
public static bool IsRateLimitedExceeded(this HttpResponseMessage source)
{
return (int)source.StatusCode == 429;
}
}
} |
using Desafio.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Desafio.Data.Mappings
{
public class MovimentacaoMap : IEntityTypeConfiguration<Movimentacao>
{
public void Configure(EntityTypeBuilder<Movimentacao> builder)
{
builder.ToTable("CAD_MOVIMENTACAO", "dbo");
builder.Property(x => x.Id)
.HasColumnName("IDT_MOVIMENTACAO")
.HasColumnType("uniqueidentifier")
.ValueGeneratedOnAdd();
builder.Property(e => e.ValorInvestido)
.HasColumnName("VLR_MOVIMENTACAO")
.HasColumnType("decimal(18,2)")
.IsRequired();
builder.Property(e => e.DataMovimento)
.HasColumnName("DTA_MOVIMENTACAO")
.IsRequired();
builder.HasOne(x => x.Pessoa)
.WithMany(x => x.Movimentacoes)
.HasForeignKey("IDT_PESSOA");
builder.HasOne(x => x.Fundo)
.WithMany(x => x.Movimentacoes)
.HasForeignKey("IDT_FUNDO");
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Sas.Model.V20181203;
namespace Aliyun.Acs.Sas.Transform.V20181203
{
public class DescribeVulDetailsResponseUnmarshaller
{
public static DescribeVulDetailsResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeVulDetailsResponse describeVulDetailsResponse = new DescribeVulDetailsResponse();
describeVulDetailsResponse.HttpResponse = _ctx.HttpResponse;
describeVulDetailsResponse.RequestId = _ctx.StringValue("DescribeVulDetails.RequestId");
List<DescribeVulDetailsResponse.DescribeVulDetails_Cve> describeVulDetailsResponse_cves = new List<DescribeVulDetailsResponse.DescribeVulDetails_Cve>();
for (int i = 0; i < _ctx.Length("DescribeVulDetails.Cves.Length"); i++) {
DescribeVulDetailsResponse.DescribeVulDetails_Cve cve = new DescribeVulDetailsResponse.DescribeVulDetails_Cve();
cve.CveId = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].CveId");
cve.CnvdId = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].CnvdId");
cve.Title = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Title");
cve.CvssScore = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].CvssScore");
cve.CvssVector = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].CvssVector");
cve.ReleaseTime = _ctx.LongValue("DescribeVulDetails.Cves["+ i +"].ReleaseTime");
cve.Complexity = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Complexity");
cve.Poc = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Poc");
cve.PocCreateTime = _ctx.LongValue("DescribeVulDetails.Cves["+ i +"].PocCreateTime");
cve.PocDisclosureTime = _ctx.LongValue("DescribeVulDetails.Cves["+ i +"].PocDisclosureTime");
cve.Summary = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Summary");
cve.Solution = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Solution");
cve.Content = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Content");
cve.Vendor = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Vendor");
cve.Product = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Product");
cve.VulLevel = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].VulLevel");
cve.Reference = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Reference");
cve.Classify = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Classify");
List<DescribeVulDetailsResponse.DescribeVulDetails_Cve.DescribeVulDetails_Classify> cve_classifys = new List<DescribeVulDetailsResponse.DescribeVulDetails_Cve.DescribeVulDetails_Classify>();
for (int j = 0; j < _ctx.Length("DescribeVulDetails.Cves["+ i +"].Classifys.Length"); j++) {
DescribeVulDetailsResponse.DescribeVulDetails_Cve.DescribeVulDetails_Classify classify = new DescribeVulDetailsResponse.DescribeVulDetails_Cve.DescribeVulDetails_Classify();
classify.Classify = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Classifys["+ j +"].Classify");
classify.Description = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Classifys["+ j +"].Description");
classify.DemoVideoUrl = _ctx.StringValue("DescribeVulDetails.Cves["+ i +"].Classifys["+ j +"].DemoVideoUrl");
cve_classifys.Add(classify);
}
cve.Classifys = cve_classifys;
describeVulDetailsResponse_cves.Add(cve);
}
describeVulDetailsResponse.Cves = describeVulDetailsResponse_cves;
return describeVulDetailsResponse;
}
}
}
|
using System;
namespace Dfc.CourseDirectory.Services.Models.Onspd
{
public class Onspd
{
public string pcd { get; set; }
public string pcd2 { get; set; }
public string pcds { get; set; }
public string dointr { get; set; }
public string doterm { get; set; }
public string oscty { get; set; }
public string oslaua { get; set; }
public string osward { get; set; }
public string prsh { get; set; }
public string ctry { get; set; }
public string rgn { get; set; }
public decimal lat { get; set; }
public decimal @long { get; set; }
public string Parish { get; set; }
public string LocalAuthority { get; set; }
public string Region { get; set; }
public string County { get; set; }
public string Country { get; set; }
public DateTime updated { get; set; }
}
}
|
namespace Backend.Response
{
public class Empty
{ }
}
|
using System;
namespace Yargon.Terms
{
/// <summary>
/// Descriptor for a term child.
/// </summary>
public struct ChildDescriptor
{
/// <summary>
/// Gets the name of the child.
/// </summary>
/// <value>The name of the child.</value>
public string Name { get; }
/// <summary>
/// Gets whether the child is abstract.
/// </summary>
/// <value><see langword="true"/> when the child is abstract;
/// otherwise, <see langword="false"/>.</value>
public bool IsAbstract { get; }
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ChildDescriptor"/> class.
/// </summary>
/// <param name="name">The name of the child.</param>
/// <param name="isAbstract">Whether the child is abstract.</param>
public ChildDescriptor(string name, bool isAbstract)
{
#region Contract
if (name == null)
throw new ArgumentNullException(nameof(name));
#endregion
this.Name = name;
this.IsAbstract = isAbstract;
}
#endregion
#region Equality
/// <inheritdoc />
public bool Equals(ChildDescriptor other)
{
return this.Name == other.Name
&& this.IsAbstract == other.IsAbstract;
}
/// <inheritdoc />
public override int GetHashCode()
{
int hash = 17;
unchecked
{
hash = hash * 29 + this.Name.GetHashCode();
hash = hash * 29 + this.IsAbstract.GetHashCode();
}
return hash;
}
/// <inheritdoc />
public override bool Equals(object obj) => obj is ChildDescriptor && Equals((ChildDescriptor)obj);
/// <summary>
/// Returns a value that indicates whether two specified <see cref="ChildDescriptor"/> objects are equal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns><see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are equal;
/// otherwise, <see langword="false"/>.</returns>
public static bool operator ==(ChildDescriptor left, ChildDescriptor right) => Object.Equals(left, right);
/// <summary>
/// Returns a value that indicates whether two specified <see cref="ChildDescriptor"/> objects are not equal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns><see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are not equal;
/// otherwise, <see langword="false"/>.</returns>
public static bool operator !=(ChildDescriptor left, ChildDescriptor right) => !(left == right);
#endregion
/// <inheritdoc />
public override string ToString()
{
return (this.IsAbstract ? "abstract " : "") + this.Name;
}
}
}
|
using System;
using System.Collections.Generic;
using DomainDrivenDesign.CoreEcommerce.Ef;
namespace Core.FrontEnd.Models
{
public class FeShoppingCartCheckoutPage
{
public Guid Id;
public List<FeIdAndDescription> PaymentMethods;
public List<FeIdAndDescription> ShippingMethods;
public int CartItemCount;
public FeOrderPromotion OrderPromotion;
public long CartTotal;
public class FeIdAndDescription
{
public Guid Id;
public string Name;
public string Description;
}
public long CartDiscount { get; set; }
}
} |
using System;
using System.Drawing;
namespace Snake_Game_CSharp
{
public class Ball
{
private readonly Random _random;
private Size _size;
public Brush Color { get; set; }
public Point Position { get; private set; }
public Ball(Size size)
{
_size = size;
Color = Brushes.Red;
_random = new Random();
}
public Point GenerateBallWithinBounds(Size gridBounds)
{
return Position = new Point(x: _random.Next(1, gridBounds.Width),
y: _random.Next(1, gridBounds.Height));
}
public void Repaint(Graphics graphics)
{
graphics.FillEllipse(brush: Color,
x: Position.X * _size.Width,
y: Position.Y * _size.Height,
width: _size.Width,
height: _size.Height);
}
}
}
|
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.Assets;
namespace OpenMetaverse.TestClient
{
public class ViewNotecardCommand : Command
{
/// <summary>
/// TestClient command to download and display a notecard asset
/// </summary>
/// <param name="testClient"></param>
public ViewNotecardCommand(TestClient testClient)
{
Name = "viewnote";
Description = "Downloads and displays a notecard asset";
Category = CommandCategory.Inventory;
}
/// <summary>
/// Exectute the command
/// </summary>
/// <param name="args"></param>
/// <param name="fromAgentID"></param>
/// <returns></returns>
public override string Execute(string[] args, UUID fromAgentID)
{
if (args.Length < 1)
{
return "Usage: viewnote [notecard asset uuid]";
}
UUID note;
if (!UUID.TryParse(args[0], out note))
{
return "First argument expected agent UUID.";
}
System.Threading.AutoResetEvent waitEvent = new System.Threading.AutoResetEvent(false);
System.Text.StringBuilder result = new System.Text.StringBuilder();
// verify asset is loaded in store
if (Client.Inventory.Store.Contains(note))
{
// retrieve asset from store
InventoryItem ii = (InventoryItem)Client.Inventory.Store[note];
// make request for asset
Client.Assets.RequestInventoryAsset(ii, true,
delegate(AssetDownload transfer, Asset asset)
{
if (transfer.Success)
{
result.AppendFormat("Raw Notecard Data: " + System.Environment.NewLine + " {0}", Utils.BytesToString(asset.AssetData));
waitEvent.Set();
}
}
);
// wait for reply or timeout
if (!waitEvent.WaitOne(10000, false))
{
result.Append("Timeout waiting for notecard to download.");
}
}
else
{
result.Append("Cannot find asset in inventory store, use 'i' to populate store");
}
// return results
return result.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LDY.UIP.EarthCalculator.BLL.Services;
using LDY.UIP.EarthCalculator.Shared.Interfaces;
namespace LDY.UIP.EarthCalculator.UIConsole {
public class UIConsoleApp {
private ILandAreaCalculator landAreaCalculator;
public UIConsoleApp(ILandAreaCalculator landAreaCalculator) {
this.landAreaCalculator = landAreaCalculator;
}
public void Start() {
List<Point> points = GetPoints();
int res = landAreaCalculator.CalculateLandArea(points);
Console.WriteLine(res);
}
private List<Point> GetPoints() {
return null;
}
}
}
|
using System.Collections.Generic;
namespace CardGames.Core.Contracts
{
/// <summary>
/// Represents the game interface.
/// </summary>
/// <typeparam name="TPlayer">The <see cref="IPlayer{TDeck,TCard}" /> subtype.</typeparam>
/// <typeparam name="TDeck">The <see cref="IDeck{TCard}" /> subtype.</typeparam>
/// <typeparam name="TCard">The <see cref="ICard" /> subtype.</typeparam>
public interface IGame<TPlayer, TDeck, TCard>
where TCard : class, ICard
where TDeck : class, IDeck<TCard>
where TPlayer : class, IPlayer<TDeck, TCard>
{
/// <summary>
/// Represents the winning player.
/// </summary>
TPlayer Winner { get; }
/// <summary>
/// Represents the players that are enrolled in the game.
/// </summary>
IEnumerable<TPlayer> Players { get; }
/// <summary>
/// Represents the list of rounds that were created during the game.
/// </summary>
IEnumerable<IRound<TPlayer, TDeck, TCard>> Rounds { get; }
/// <summary>
/// Represents the initial deck of cards.
/// </summary>
TDeck InitialDeck { get; set; }
/// <summary>
/// Executes the game play logic.
/// </summary>
void Play();
/// <summary>
/// Creates a game round.
/// </summary>
/// <typeparam name="TRound">The custom round type.</typeparam>
/// <param name="players">The players that are eligible to play in the next round.</param>
/// <param name="roundNumber">The index of the round.</param>
/// <returns>The created game round.</returns>
TRound CreateRound<TRound>(IEnumerable<TPlayer> players, int roundNumber)
where TRound : class, IRound<TPlayer, TDeck, TCard>, new();
/// <summary>
/// Distributes the initial deck of cards to the competing players.
/// </summary>
void DistributeCards();
}
} |
using System;
using System.IO;
using System.Numerics;
namespace GameSpec.Cry.Formats.Core.Chunks
{
public class ChunkNode_824 : ChunkNode
{
public override void Read(BinaryReader r)
{
base.Read(r);
Name = r.ReadFString(64);
if (string.IsNullOrEmpty(Name)) Name = "unknown";
ObjectNodeID = r.ReadInt32(); // Object reference ID
ParentNodeID = r.ReadInt32();
__NumChildren = r.ReadInt32();
MatID = r.ReadInt32(); // Material ID?
SkipBytes(r, 4);
// Read the 4x4 transform matrix.
var transform = new Matrix4x4
{
M11 = r.ReadSingle(),
M12 = r.ReadSingle(),
M13 = r.ReadSingle(),
M14 = r.ReadSingle(),
M21 = r.ReadSingle(),
M22 = r.ReadSingle(),
M23 = r.ReadSingle(),
M24 = r.ReadSingle(),
M31 = r.ReadSingle(),
M32 = r.ReadSingle(),
M33 = r.ReadSingle(),
M34 = r.ReadSingle(),
M41 = r.ReadSingle() * VERTEX_SCALE,
M42 = r.ReadSingle() * VERTEX_SCALE,
M43 = r.ReadSingle() * VERTEX_SCALE,
M44 = r.ReadSingle(),
};
// original transform matrix is 3x4 stored as 4x4.
transform.M14 = transform.M24 = transform.M34 = 0f;
transform.M44 = 1f;
Transform = transform;
Pos = r.ReadVector3() * VERTEX_SCALE;
Rot = r.ReadQuaternion();
Scale = r.ReadVector3();
// read the controller pos/rot/scale
PosCtrlID = r.ReadInt32();
RotCtrlID = r.ReadInt32();
SclCtrlID = r.ReadInt32();
Properties = r.ReadPString();
}
}
} |
using System;
using System.Linq;
using FluentAssertions;
using Xunit;
namespace Okanshi.Test
{
public class DoubleCounterTest
{
private readonly DoubleCounter counter;
public DoubleCounterTest()
{
counter = new DoubleCounter(MonitorConfig.Build("Test"));
}
[Fact]
public void Initial_value_is_zero()
{
var value = counter.GetValues();
value.First().Value.Should().Be(0);
}
[Fact]
public void Value_is_reset_when_get_and_reset_is_called()
{
counter.Increment();
counter.GetValuesAndReset().ToList();
counter.GetValues().First().Value.Should().Be(0);
}
[Theory]
[InlineData(1.0)]
[InlineData(2.2)]
[InlineData(605.18)]
public void Value_returns_the_value(double expectedValue)
{
counter.Increment(expectedValue);
var value = counter.GetValues();
value.First().Value.Should().Be(expectedValue);
}
[Fact]
public void Incrementing_multiple_time_increments_the_value()
{
counter.Increment(1);
counter.Increment(1);
var value = counter.GetValues();
value.First().Value.Should().Be(2);
}
[Fact]
public void Get_and_reset_returns_the_value()
{
counter.Increment(1);
var value = counter.GetValuesAndReset();
value.First().Value.Should().Be(1);
}
[Fact]
public void Value_is_called_value()
{
counter.GetValues().Single().Name.Should().Be("value");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Simple2DLight
{
public class FadeLight : MonoBehaviour
{
//컴포넌트
private LightManager light_manager;
//조명
public float light_size = 3f;
public float light_grow_up_time = 2.5f;
public float light_grow_down_time = 2f;
public float light_bright = 1f;
//초기화
void Start()
{
light_manager = LightManager.instance;
}
//조명 On
public void Lighting()
{
//쉐이더 On
light_manager.CreateFadeLight(
transform.position,
light_size,
light_grow_up_time,
light_grow_down_time,
light_bright
);
}
}
}
|
using System;
using System.Threading.Tasks;
using Impostor.Api.Events;
namespace Impostor.Server.Events.Register
{
internal class WrappedRegisteredEventListener : IRegisteredEventListener
{
private readonly IRegisteredEventListener _innerObject;
private readonly object _object;
public WrappedRegisteredEventListener(IRegisteredEventListener innerObject, object o)
{
_innerObject = innerObject;
_object = o;
}
public Type EventType => _innerObject.EventType;
public EventPriority Priority => _innerObject.Priority;
public ValueTask InvokeAsync(object eventHandler, object @event, IServiceProvider provider)
{
return _innerObject.InvokeAsync(_object, @event, provider);
}
}
} |
namespace Cosmos.Data.Common
{
/// <summary>
/// DbContext Meta Interface<br />
/// DnContext 元接口
/// </summary>
public interface IDbContext { }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZedGraph;
using MathLib;
using static System.Math;
using System.IO;
using System.Drawing;
namespace OrbModUI
{
//Plot residuals on ZedGraphControl by observatory
//
public abstract class PlotResbyObs : Plot
{
//intermnal class for storage statistic by observatory
//
protected class statbyObs
{
public string ID;
public double Mean;
public double sigma;
public uint counter;
//
public statbyObs()
{
counter = 0;
Mean = sigma = 0;
}
//
public statbyObs(uint i)
{
counter = i;
Mean = sigma = 0;
}
//
public string ToString(string format, string delim)
{
return (ID + delim + counter + delim + Mean.ToString(format) + delim + (sigma).ToString(format));
}
}
public PlotResbyObs() { }
public PlotResbyObs(ZedGraphControl zg, string fname) : base(zg, fname) { }
protected abstract bool AddPoint(DateTime dt, double et, string[] Data, ref PointPairList Points);
//
public override void PlotData()
{
Random rand = new Random();
GraphPane pane = zg.GraphPane;
Dictionary<string, PointPairList> pLists = new Dictionary<string, PointPairList>();
Dictionary<string, statbyObs> Stat = new Dictionary<string, statbyObs>();
using (StreamReader sr = new StreamReader(fileName))
{
while (sr.Peek() != -1)
{
string line = sr.ReadLine();
if (!ParseString(line, out DateTime dt, out double et, out string[] data)) continue;
if (data.Length != 3) continue;
PointPairList pList;
if (!pLists.TryGetValue(data[0], out pList))
{
//create and add new points list by Obseravatory
pList = new PointPairList();
pLists.Add(data[0], pList);
}
else
{
pList = pLists[data[0]];
}
//
AddPoint(dt, et, data, ref pList);
}
//
int N_obsy = pLists.Count;
statbyObs[] stats = new statbyObs[N_obsy];
//Calculate mean by observatory
int i_ = 0;
foreach (var it in pLists)
{
stats[i_] = new statbyObs(0);
stats[i_].ID = it.Key;
foreach (var it2 in it.Value)
{
stats[i_].Mean += it2.Y;
stats[i_].counter++;
}
//
stats[i_].Mean /= stats[i_].counter;
i_++;
}
//
i_ = 0;
foreach (var it in pLists)
{
// Calculate standard deviation by observatory
#region stdev
foreach (var it2 in it.Value)
{
stats[i_].sigma += Misc.SQR((it2.Y - stats[i_].Mean));
}
// standard deviation
stats[i_].sigma = Sqrt(stats[i_].sigma / (stats[i_].counter - 1));
#endregion
// random color
Color col = Color.FromArgb(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255));
//add line
var list_ = it.Value;
LineItem myCurve = pane.AddCurve("", list_, col, (SymbolType)Config.Instance.SymbolType);
//Symbol formatting
myCurve.Symbol.Size = Config.Instance.SymbolSize;
myCurve.Symbol.Fill.Type = FillType.Solid;
//line formatting
myCurve.Line.IsVisible = Config.Instance.IsShowLines;
myCurve.Line.Width = Config.Instance.LineWidth;
//label
string LabelText = stats[i_].ToString("F2", " ");
TextObj Label = new TextObj(LabelText, list_[0].X, list_[0].Y);
Label.FontSpec.Fill.Type = FillType.None;
Label.FontSpec.FontColor = col;
Label.FontSpec.IsBold = true;
Label.FontSpec.Border.IsVisible = false;
// add label to graph pane
pane.GraphObjList.Add(Label);
i_++;
}
}
EndDraw();
}
}
//
public class PlotResbyObsRA : PlotResbyObs
{
public PlotResbyObsRA() { }
public PlotResbyObsRA(ZedGraphControl zg, string fname) : base(zg, fname) { }
protected override bool AddPoint(DateTime dt, double et, string[] data, ref PointPairList list)
{
if (data.Length < 3) return false;
double.TryParse(data[1], out double Val);
AddPoint(list, dt, et, Val);
return true;
}
public override void EndDraw_()
{
string yT = "Δα*cos(δ), asec";
zg.GraphPane.YAxis.Title.Text = yT;
}
}
//
public class PlotResbyObsDec : PlotResbyObs
{
//
public PlotResbyObsDec() { }
//
public PlotResbyObsDec(ZedGraphControl zg, string fname) : base(zg, fname) { }
//
protected override bool AddPoint(DateTime dt, double et, string[] data, ref PointPairList list)
{
//
if (data.Length < 3) return false;
double.TryParse(data[2], out double Val);
AddPoint(list, dt, et, Val);
return true;
}
public override void EndDraw_()
{
string yT = "Δδ, asec";
zg.GraphPane.YAxis.Title.Text = yT;
}
}
}
|
namespace TemplateProcessor.Helpers.SmartString.Models
{
public class Word
{
public string Value { get; set; }
public bool AllowMultipleUpperCase { get; set; }
}
}
|
namespace TraktNet.Objects.Get.Tests.Movies.Json.Reader
{
using FluentAssertions;
using System;
using System.Threading.Tasks;
using Trakt.NET.Tests.Utility.Traits;
using TraktNet.Enums;
using TraktNet.Objects.Get.Movies;
using TraktNet.Objects.Get.Movies.Json.Reader;
using Xunit;
[Category("Objects.Get.Movies.JsonReader")]
public partial class MovieReleaseObjectJsonReader_Tests
{
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Complete()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_COMPLETE);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_1()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_1);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_2()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_2);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_3()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_3);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_4()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_4);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_5()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_5);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_6()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_6);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_7()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_7);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_8()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_8);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_9()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_9);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Incomplete_10()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_10);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_1()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_1);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_2()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_2);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_3()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_3);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_4()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_4);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().Be("Los Angeles, California");
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_5()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_5);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().Be("us");
traktMovieRelease.Certification.Should().Be("PG-13");
traktMovieRelease.ReleaseDate.Should().Be(DateTime.Parse("2015-12-14"));
traktMovieRelease.ReleaseType.Should().Be(TraktReleaseType.Premiere);
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Not_Valid_6()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_6);
traktMovieRelease.Should().NotBeNull();
traktMovieRelease.CountryCode.Should().BeNull();
traktMovieRelease.Certification.Should().BeNull();
traktMovieRelease.ReleaseDate.Should().BeNull();
traktMovieRelease.ReleaseType.Should().BeNull();
traktMovieRelease.Note.Should().BeNull();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Null()
{
var jsonReader = new MovieReleaseObjectJsonReader();
Func<Task<ITraktMovieRelease>> traktMovieRelease = () => jsonReader.ReadObjectAsync(default(string));
await traktMovieRelease.Should().ThrowAsync<ArgumentNullException>();
}
[Fact]
public async Task Test_MovieReleaseObjectJsonReader_ReadObject_From_Json_String_Empty()
{
var jsonReader = new MovieReleaseObjectJsonReader();
var traktMovieRelease = await jsonReader.ReadObjectAsync(string.Empty);
traktMovieRelease.Should().BeNull();
}
}
}
|
using System.Drawing;
using System.Windows.Forms;
namespace BizHawk.Client.EmuHawk
{
public sealed class NameTableViewer : Control
{
public Bitmap Nametables;
public NameTableViewer()
{
var pSize = new Size(512, 480);
Nametables = new Bitmap(pSize.Width, pSize.Height);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, true);
Size = new Size(256, 224);
BackColor = Color.Transparent;
Paint += NameTableViewer_Paint;
}
public enum WhichNametable
{
NT_2000, NT_2400, NT_2800, NT_2C00, NT_ALL, TOPS, BOTTOMS
}
public WhichNametable Which = WhichNametable.NT_ALL;
private void NameTableViewer_Paint(object sender, PaintEventArgs e)
{
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
switch (Which)
{
case WhichNametable.NT_ALL:
e.Graphics.DrawImageUnscaled(Nametables, 0, 0);
break;
case WhichNametable.NT_2000:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 0, 512, 480), 0, 0, 256, 240, GraphicsUnit.Pixel);
break;
case WhichNametable.NT_2400:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 0, 512, 480), 256, 0, 256, 240, GraphicsUnit.Pixel);
break;
case WhichNametable.NT_2800:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 0, 512, 480), 0, 240, 256, 240, GraphicsUnit.Pixel);
break;
case WhichNametable.NT_2C00:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 0, 512, 480), 256, 240, 256, 240, GraphicsUnit.Pixel);
break;
//adelikat: Meh, just in case we might want these, someone requested it but I can't remember the justification so I didn't do the UI part
case WhichNametable.TOPS:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 0, 512, 240), 0, 0, 512, 240, GraphicsUnit.Pixel);
break;
case WhichNametable.BOTTOMS:
e.Graphics.DrawImage(Nametables, new Rectangle(0, 240, 512, 240), 0, 240, 512, 240, GraphicsUnit.Pixel);
break;
}
}
public void ScreenshotToClipboard()
{
using var b = new Bitmap(Width, Height);
var rect = new Rectangle(new Point(0, 0), Size);
DrawToBitmap(b, rect);
Clipboard.SetImage(b);
}
}
}
|
using System;
namespace AppTokiota.Users.Services
{
public interface INetworkConnectionService
{
bool IsAvailable();
}
}
|
using OrchardCore.Data.Documents;
namespace OrchardCore.Documents.Options
{
public class DocumentOptions<TDocument> where TDocument : IDocument, new()
{
public DocumentOptions(IDocumentOptionsFactory factory)
{
Value = factory.Create(typeof(TDocument));
}
public DocumentOptions Value { get; }
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using Microsoft.MachineLearning;
using Microsoft.MachineLearning.Api;
using Microsoft.MachineLearning.Data;
using Microsoft.MachineLearning.Recommend;
namespace Recommendations.Core.Sar
{
internal class SarScorer : IDisposable
{
/// <summary>
/// Creates a new instance of <see cref="SarScorer"/> class.
/// </summary>
/// <param name="recommender">A trained SAR recommender</param>
/// <param name="tracer">A message tracer to use for logging</param>
public SarScorer(IUserHistoryToItemsRecommender recommender, ITracer tracer = null)
{
if (recommender == null)
{
throw new ArgumentNullException(nameof(recommender));
}
_recommender = recommender;
_tracer = tracer ?? new DefaultTracer();
// create the input schema
_usageDataSchema = SchemaDefinition.Create(typeof(SarUsageEvent));
_usageDataSchema["user"].ColumnType = _recommender.UserIdType;
_usageDataSchema["Item"].ColumnType = _recommender.ItemIdType;
// create an environment and register a message listener
_environment = new TlcEnvironment(verbose: true);
_environment.AddListener<ChannelMessage>(_tracer.TraceChannelMessage);
}
/// <summary>
/// Scores the input usage items.
/// </summary>
/// <param name="usageItems">The items to score</param>
/// <param name="scoringArguments">The scoring arguments</param>
/// <returns></returns>
public IEnumerable<SarScoreResult> ScoreUsageItems(IList<SarUsageEvent> usageItems, SarScoringArguments scoringArguments)
{
if (_disposed)
{
throw new ObjectDisposedException(typeof(SarScorer).FullName);
}
if (usageItems == null)
{
throw new ArgumentNullException(nameof(usageItems));
}
if (scoringArguments == null)
{
throw new ArgumentNullException(nameof(scoringArguments));
}
_tracer.TraceVerbose("Getting or creating the prediction engine");
BatchPredictionEngine<SarUsageEvent, SarScoreResult> engine =
GetOrCreateBatchPredictionEngine(usageItems, scoringArguments);
_tracer.TraceInformation($"Getting recommendation for {usageItems.Count} input items");
lock (engine)
{
return engine.Predict(usageItems, false)
.OrderByDescending(x => x.Score)
.Take(scoringArguments.RecommendationCount)
.ToArray();
}
}
/// <summary>
/// Gets a cached prediction engine or creates a new one if not cached
/// </summary>
private BatchPredictionEngine<SarUsageEvent, SarScoreResult> GetOrCreateBatchPredictionEngine(
IList<SarUsageEvent> usageItems, SarScoringArguments sarScoringArguments)
{
var arguments = new RecommenderScorerTransform.Arguments
{
// round the recommendations count to optimize engine cache
recommendationCount = GetRoundedNumberOfResults(sarScoringArguments.RecommendationCount),
includeHistory = sarScoringArguments.IncludeHistory
};
// create a data column mapping
var dataColumnMapping = new Dictionary<RoleMappedSchema.ColumnRole, string>
{
{new RoleMappedSchema.ColumnRole("Item"), "Item"},
{new RoleMappedSchema.ColumnRole("User"), "user"}
};
string weightColumn = null;
if (sarScoringArguments.ReferenceDate.HasValue)
{
// rounding the reference date to the beginning of next day to optimize engine cache
DateTime referenceDate = sarScoringArguments.ReferenceDate.Value.Date + TimeSpan.FromDays(1);
arguments.referenceDate = referenceDate.ToString("s");
if (sarScoringArguments.Decay.HasValue)
{
arguments.decay = sarScoringArguments.Decay.Value.TotalDays;
}
dataColumnMapping.Add(new RoleMappedSchema.ColumnRole("Date"), "date");
weightColumn = "weight";
}
// create an engine cache key
string cacheKey = $"{arguments.recommendationCount}|{arguments.includeHistory}|{arguments.referenceDate}|{arguments.decay}";
_tracer.TraceVerbose("Trying to find the engine in the cache");
var engine = _enginesCache.Get(cacheKey) as BatchPredictionEngine<SarUsageEvent, SarScoreResult>;
if (engine == null)
{
_tracer.TraceInformation("Engine is not cached - creating a new engine");
IDataView pipeline = _environment.CreateDataView(usageItems, _usageDataSchema);
RoleMappedData usageDataMappedData = _environment.CreateExamples(pipeline, null, weight: weightColumn, custom: dataColumnMapping);
ISchemaBindableMapper mapper = RecommenderScorerTransform.Create(_environment, arguments, _recommender);
ISchemaBoundMapper boundMapper = mapper.Bind(_environment, usageDataMappedData.Schema);
IDataScorerTransform scorer = RecommenderScorerTransform.Create(
_environment, arguments, pipeline, boundMapper, null);
engine = _environment.CreateBatchPredictionEngine<SarUsageEvent, SarScoreResult>(scorer, false, _usageDataSchema);
bool result = _enginesCache.Add(cacheKey, engine, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromDays(1) });
_tracer.TraceVerbose($"Addition of engine to the cache resulted with '{result}'");
}
return engine;
}
private static int GetRoundedNumberOfResults(int numberOfResults)
{
// if less than 5, round the requested number of results to 5,
// otherwise round up to the closest multiplication of 10
if (numberOfResults <= 5)
{
return 5;
}
// round up to the closest multiplication of 10
// Examples:
// 7 -> 10
// 10 -> 10
// 11 -> 20
// 19 -> 20
// 21 -> 30
return (int) Math.Ceiling((double) numberOfResults/10)*10;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_disposed)
{
_environment.Dispose();
_enginesCache.Dispose();
_disposed = true;
}
}
}
private bool _disposed;
private readonly TlcEnvironment _environment;
private readonly SchemaDefinition _usageDataSchema;
private readonly MemoryCache _enginesCache = new MemoryCache(nameof(_enginesCache));
private readonly IUserHistoryToItemsRecommender _recommender;
private readonly ITracer _tracer;
}
} |
using System;
namespace Bolt.Client
{
public class ConnectionDescriptor
{
public ConnectionDescriptor(Uri server)
{
Server = server ?? throw new ArgumentNullException(nameof(server));
}
public Uri Server { get; set; }
public bool KeepAlive { get; set; }
}
} |
namespace LTPTranslations.Web.ViewModels.ViewModels.WordOfTheDay
{
public class SynonymsInputModel
{
public string SynonymName { get; set; }
}
}
|
using System;
using System.Diagnostics;
using System.Management.Automation;
namespace PSAsync
{
public readonly struct ShouldProcessResult :
IEquatable<ShouldProcessResult>
{
public ShouldProcessResult(
bool result,
ShouldProcessReason reason)
{
this.Result = result;
this.Reason = reason;
}
// https://github.com/dotnet/roslyn-analyzers/issues/2834
#pragma warning disable CA1822
public bool Result
{
[DebuggerStepThrough]
get;
}
public ShouldProcessReason Reason
{
[DebuggerStepThrough]
get;
}
#pragma warning restore CA1822
public void Deconstruct(
out bool result,
out ShouldProcessReason reason)
{
result = this.Result;
reason = this.Reason;
}
public bool Equals(
ShouldProcessResult other)
{
return
this.Result == other.Result &&
this.Reason == other.Reason;
}
/// <inheritdoc />
public override bool Equals(
object? obj)
{
return (obj is ShouldProcessResult other) && Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return HashCode.Combine(this.Result, (int) this.Reason);
}
public static bool operator ==(
ShouldProcessResult left,
ShouldProcessResult right)
{
return left.Equals(right);
}
public static bool operator !=(
ShouldProcessResult left,
ShouldProcessResult right)
{
return !(left == right);
}
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjaxControlToolkit;
using System.Web.UI;
using System.IO;
using Moq;
using System.Xml;
namespace AjaxControlToolkit.Tests {
[TestFixture]
public class TabPanelTests {
[Test]
public void ParseHeaderInfo() {
var wrapper = new TabPanelWrapper();
var mockWrapper = new Mock<TabPanelWrapper>();
var layout = wrapper.RenderElement();
using(var reader = XmlReader.Create(new StringReader(layout))) {
reader.Read();
}
}
}
class TabPanelWrapper : TabPanel {
public TabPanelWrapper() {
ID = "abc";
}
protected override void RegisterScriptDescriptors() {
}
public string RenderElement() {
StringBuilder sb = new StringBuilder();
TextWriter textWriter = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(textWriter);
Render(writer);
return sb.ToString();
}
}
} |
using AutoMapper;
using Fox.Common.Extensions;
using IdentityServer.Models;
namespace IdentityServer.Configurations.AutoMapper
{
public class AccountMapping : BaseMapping
{
public AccountMapping()
{
CreateMap<RegistrationRequest, User>(MemberList.None)
.ForMember(dest => dest.PasswordHash, src => src.Ignore())
.ForMember(dest => dest.Email, src => src.MapFrom(s => s.Email))
.ForMember(dest => dest.UserName, src => src.MapFrom(s => s.Email))
.ForMember(dest => dest.Firstname, src => src.MapFrom(s => s.Firstname))
.ForMember(dest => dest.Lastname, src => src.MapFrom(s => s.Lastname))
.ReverseMap()
.IgnoreAll();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Raylib_cs;
using static RayWrapper.GameBox;
namespace RayWrapper.CollisionSystem
{
public class ScreenGrid
{
public Dictionary<(int x, int y), List<int>> collisionGrid = new();
private IList<Collider> subCol = new List<Collider>();
private long lastTick = -1;
private const float screenPercent = .1f;
private IList<Collider> removeQueue = new List<Collider>();
private IList<Collider> addQueue = new List<Collider>();
private IDictionary<(int x, int y), Rectangle> rects = new Dictionary<(int x, int y), Rectangle>();
private List<(int x, int y)> keys = new();
public ScreenGrid()
{
var incrX = (int) Math.Ceiling(WindowSize.X * screenPercent);
var incrY = (int) Math.Ceiling(WindowSize.Y * screenPercent);
for (var x = 0; x < WindowSize.X; x += incrX)
for (var y = 0; y < WindowSize.Y; y += incrY)
rects.Add((x, y), new Rectangle(x, y, incrX, incrY));
foreach (var k in rects.Keys) collisionGrid.Add(k, new List<int>());
keys.AddRange(rects.Keys);
}
public async Task Update()
{
var thisTick = GetTimeMs();
if (lastTick == -1) lastTick = thisTick;
var deltaTime = thisTick - lastTick;
foreach (var k in collisionGrid.Keys) collisionGrid[k].Clear();
await Task.Run(() => Sort(deltaTime));
await Task.Run(CollDetect);
if (addQueue.Any())
{
foreach (var c in addQueue) subCol.Add(c);
addQueue.Clear();
}
if (removeQueue.Any())
{
foreach (var c in removeQueue) subCol.Remove(c);
removeQueue.Clear();
}
lastTick = thisTick;
}
public void Draw(bool debug)
{
foreach (var t in subCol) t.Render();
if (!debug || !isCollisionSystem) return;
foreach (var rect in rects.Values) rect.DrawHallowRect(Color.GREEN);
}
public void SubscribeCollider(Collider c) => addQueue.Add(c);
public void UnSubscribeCollider(Collider c) => removeQueue.Add(c);
public void Sort(float deltaTime)
{
for (var i = 0; i < subCol.Count; i++)
{
foreach (var t in keys.Where(t => subCol[i].SampleCollision(rects[t])))
collisionGrid[t].Add(i);
if (subCol[i].velocity != Vector2.Zero) subCol[i].Position += subCol[i].velocity * deltaTime;
subCol[i].Update();
}
}
public void CollDetect()
{
var lists = collisionGrid.Values.Where(l => l.Count > 1).ToList();
if (!lists.Any()) return;
foreach (var list in lists.Where(list => list.Any()))
{
for (var i = 0; i < list.Count - 1; i++)
for (var j = i + 1; j < list.Count; j++)
subCol[list[i]].DoCollision(subCol[list[j]]);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeTrialRing : MonoBehaviour
{
[HideInInspector]
public Challenge_TimeTrial trial; // set by the Challenge_TimeTrial
public bool Passed { get; private set; }
private Renderer rend;
private Collider col;
private void Awake() {
rend = GetComponent<Renderer>();
col = GetComponent<Collider>();
}
public void Clear() {
Passed = false;
rend.enabled = true;
}
public void Hide() {
Color color = rend.material.color;
color.a = 0;
rend.material.color = color;
col.enabled = false;
}
public void Show() {
Color color = rend.material.color;
color.a = 1;
rend.material.color = color;
}
private void OnTriggerEnter(Collider other) {
if(Player.IsPlayerTrigger(other)) {
Passed = true;
rend.enabled = false;
col.enabled = false;
GetComponent<AudioSource>().Play();
}
}
}
|
using FrannHammer.WebScraping;
using FrannHammer.WebScraping.Attributes;
using FrannHammer.WebScraping.Character;
using FrannHammer.WebScraping.Contracts;
using FrannHammer.WebScraping.Contracts.Attributes;
using FrannHammer.WebScraping.Contracts.Character;
using FrannHammer.WebScraping.Contracts.HtmlParsing;
using FrannHammer.WebScraping.Contracts.Images;
using FrannHammer.WebScraping.Contracts.Movements;
using FrannHammer.WebScraping.Contracts.Moves;
using FrannHammer.WebScraping.Contracts.PageDownloading;
using FrannHammer.WebScraping.Contracts.UniqueData;
using FrannHammer.WebScraping.Contracts.WebClients;
using FrannHammer.WebScraping.HtmlParsing;
using FrannHammer.WebScraping.Images;
using FrannHammer.WebScraping.Movements;
using FrannHammer.WebScraping.Moves;
using FrannHammer.WebScraping.PageDownloading;
using FrannHammer.WebScraping.Unique;
using FrannHammer.WebScraping.WebClients;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
namespace FrannHammer.NetCore.WebApi.ServiceCollectionExtensions
{
public static class ScrapingServiceCollectionExtensions
{
public static IServiceCollection AddScrapingSupport(this IServiceCollection services)
{
services.AddTransient<IInstanceIdGenerator, InstanceIdGenerator>();
services.AddTransient<IHtmlParserProvider, DefaultHtmlParserProvider>();
services.AddTransient<IMovementProvider, DefaultMovementProvider>();
services.AddTransient<IMoveProvider, DefaultMoveProvider>();
services.AddTransient<IPageDownloader, DefaultPageDownloader>();
services.AddTransient<IWebClientProvider, DefaultWebClientProvider>();
services.AddTransient<IAttributeProvider, DefaultAttributeProvider>();
services.AddSingleton<IColorScrapingService, DefaultColorScrapingService>(sp =>
{
string css = sp.GetService<IPageDownloader>()
.DownloadPageSource(new Uri("http://kuroganehammer.com/css/character.css"),
sp.GetService<IWebClientProvider>());
return new DefaultColorScrapingService(css);
});
services.AddTransient<IAttributeScrapingServices, DefaultAttributeScrapingServices>();
services.AddTransient<IMoveScrapingServices, DefaultMoveScrapingServices>();
services.AddTransient<IMovementScrapingServices, DefaultMovementScrapingServices>();
services.AddTransient<IUniqueDataProvider, DefaultUniqueDataProvider>();
services.AddTransient<GroundMoveScraper>();
services.AddTransient<AerialMoveScraper>();
services.AddTransient<SpecialMoveScraper>();
services.AddTransient<ThrowMoveScraper>();
services.AddTransient<ICharacterMoveScraper, DefaultCharacterMoveScraper>(sp =>
{
var scrapers = new List<IMoveScraper>
{
sp.GetService<GroundMoveScraper>(),
sp.GetService<AerialMoveScraper>(),
sp.GetService<SpecialMoveScraper>(),
sp.GetService<ThrowMoveScraper>()
};
return new DefaultCharacterMoveScraper(scrapers);
});
services.AddTransient<IMovementScraper, DefaultMovementScraper>();
services.AddTransient<ICharacterDataScrapingServices, DefaultCharacterDataScrapingServices>(sp =>
{
var scrapers = AttributeScrapers.AllWithScrapingServices(sp.GetService<IAttributeScrapingServices>());
return new DefaultCharacterDataScrapingServices(
sp.GetService<IColorScrapingService>(),
sp.GetService<IMovementScraper>(),
scrapers,
sp.GetService<ICharacterMoveScraper>(),
sp.GetService<IUniqueDataScrapingServices>(),
sp.GetService<IWebServices>(),
sp.GetService<IInstanceIdGenerator>());
});
services.AddTransient<ICharacterDataScraper, DefaultCharacterDataScraper>();
services.AddTransient<IUniqueDataScrapingServices, DefaultUniqueDataScrapingServices>();
services.AddSingleton<IWebServices, DefaultWebServices>();
return services;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using CodeTherapy.HttpSecurityChecks.Data;
namespace CodeTherapy.HttpSecurityChecks
{
public abstract class HttpSecurityCheckBase : ISecurityCheck, IEquatable<HttpSecurityCheckBase>
{
public abstract string Name { get; }
public abstract string Description { get; }
public abstract string Category { get; }
public abstract string Recommendation { get; }
public virtual bool HttpsOnly => false;
public SecurityCheckResult Check(HttpResponseMessage httpResponseMessage)
{
if (httpResponseMessage is null)
{
throw new ArgumentNullException(nameof(httpResponseMessage));
}
if (HttpsOnly && httpResponseMessage.RequestMessage.RequestUri.Scheme != Uri.UriSchemeHttps)
{
return SecurityCheckResult.Create(SecurityCheckState.Skipped, $"{Name} is HTTPS only.");
}
return CheckCore(httpResponseMessage);
}
protected abstract SecurityCheckResult CheckCore(HttpResponseMessage httpResponseMessage);
public bool Equals(HttpSecurityCheckBase other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
public sealed override bool Equals(object obj)
{
return Equals(obj as HttpSecurityCheckBase);
}
public override int GetHashCode()
{
unchecked
{
return 539060726 + EqualityComparer<string>.Default.GetHashCode(Name);
}
}
public static bool operator ==(HttpSecurityCheckBase obj1, HttpSecurityCheckBase obj2)
{
return EqualityComparer<HttpSecurityCheckBase>.Default.Equals(obj1, obj2);
}
public static bool operator !=(HttpSecurityCheckBase obj1, HttpSecurityCheckBase obj2)
{
return !(obj1 == obj2);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Lex.Db
{
using Indexing;
using Serialization;
interface IIndex<T> where T : class
{
DbTable<T> Table { get; }
MemberInfo[] Keys { get; }
void Read(DataReader reader, DbFormat format);
void Write(DataWriter writer);
void Purge();
string Name { get; }
int Count { get; }
}
interface IIndex<T, K> : IIndex<T> where T : class
{
int ExecuteCount(IndexQueryArgs<K> args);
List<T> ExecuteToList(IndexQueryArgs<K> args);
List<L> ExecuteToList<L>(IndexQueryArgs<K> args, Func<K, IKeyNode, L> selector);
}
class IndexQueryArgs<K>
{
public int? Skip, Take;
public bool? MinInclusive, MaxInclusive;
public K Min, Max;
public Func<K, bool> Filter;
public IndexQueryArgs() { }
public IndexQueryArgs(IndexQueryArgs<K> source)
{
Filter = source.Filter;
Skip = source.Skip;
Take = source.Take;
MinInclusive = source.MinInclusive;
MaxInclusive = source.MaxInclusive;
Min = source.Min;
Max = source.Max;
}
}
/// <summary>
/// Query via index interface
/// </summary>
public interface IIndexQuery
{
/// <summary>
/// Counts the number of the indexed entities identitified by the query
/// </summary>
/// <returns>Number of entities identitified by the query</returns>
int Count();
/// <summary>
/// Returns the list of PK values for entities identitified by the query
/// </summary>
/// <typeparam name="K">Type of the primary key</typeparam>
/// <returns>List of PK values for entities identitified by the query</returns>
List<K> ToIdList<K>();
}
/// <summary>
/// Typed query via index interface
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public interface IIndexQuery<T> : IIndexQuery where T : class
{
/// <summary>
/// Loads entities returned by the query
/// </summary>
/// <returns>List of entities identitified by the query</returns>
List<T> ToList();
}
/// <summary>
/// Typed query via index interface
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <typeparam name="I1">Type of the indexed member</typeparam>
public interface IIndexQuery<T, I1> : IIndexQuery<T>
where T : class
{
/// <summary>
/// Lazy loads entities returned by the query
/// </summary>
/// <returns>List of lazy-loaded entities identitified by the query</returns>
List<Lazy<T, I1>> ToLazyList();
/// <summary>
/// Returns a specified number of contiguous entities from the start of a query.
/// </summary>
/// <param name="count">The number of elements to return.</param>
/// <returns>A new query that returns the specified number of entities.</returns>
IIndexQuery<T, I1> Take(int count);
/// <summary>
/// Bypasses a specified number of entities in a query and then returns the remaining entities.
/// </summary>
/// <param name="count">The number of entities to skip before returning the remaining entities.</param>
/// <returns>A new query that bypasses the specified number of entities.</returns>
IIndexQuery<T, I1> Skip(int count);
/// <summary>
/// Returns entities with specified lower bound
/// </summary>
IIndexQuery<T, I1> GreaterThan(I1 key, bool orEqual = false);
/// <summary>
/// Returns entities with specified upper bound
/// </summary>
IIndexQuery<T, I1> LessThan(I1 key, bool orEqual = false);
/// <summary>
/// Returns entities with specified key value
/// </summary>
/// <param name="key">Key value</param>
/// <returns>A new query that returns entities with specified key value.</returns>
IIndexQuery<T, I1> Key(I1 key);
/// <summary>
/// Returns entities with filtered key values
/// </summary>
/// <param name="predicate">Predicate function to filter entities</param>
/// <returns>A new query that returns entities with filtered key values.</returns>
IIndexQuery<T, I1> Where(Func<I1, bool> predicate);
}
/// <summary>
/// Typed query via 2-component index interface
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <typeparam name="I1">Type of the first component indexed member</typeparam>
/// <typeparam name="I2">Type of the second component indexed member</typeparam>
public interface IIndexQuery<T, I1, I2> : IIndexQuery<T>
where T : class
{
/// <summary>
/// Lazy loads entities returned by the query
/// </summary>
/// <returns>List of lazy-loaded entities identitified by the query</returns>
List<Lazy<T, I1, I2>> ToLazyList();
/// <summary>
/// Returns a specified number of contiguous entities from the start of a query.
/// </summary>
/// <param name="count">The number of elements to return.</param>
/// <returns>A new query that returns the specified number of entities.</returns>
IIndexQuery<T, I1, I2> Take(int count);
/// <summary>
/// Bypasses a specified number of entities in a query and then returns the remaining entities.
/// </summary>
/// <param name="count">The number of entities to skip before returning the remaining entities.</param>
/// <returns>A new query that bypasses the specified number of entities.</returns>
IIndexQuery<T, I1, I2> Skip(int count);
/// <summary>
/// Returns entities with specified 2-component lower bound
/// </summary>
IIndexQuery<T, I1, I2> GreaterThan(I1 key1, I2 key2 = default(I2), bool inclusive = false);
/// <summary>
/// Returns entities with specified 2-component upper bound
/// </summary>
IIndexQuery<T, I1, I2> LessThan(I1 key1, I2 key2 = default(I2), bool inclusive = false);
/// <summary>
/// Returns entities with specified 2-component key value
/// </summary>
/// <param name="key1">First component key value</param>
/// <param name="key2">Second component key value</param>
/// <returns>A new query that returns entities with specified key value.</returns>
IIndexQuery<T, I1, I2> Key(I1 key1, I2 key2);
/// <summary>
/// Returns entities with filtered key values
/// </summary>
/// <param name="predicate">Predicate function to filter entities</param>
/// <returns>A new query that returns entities with filtered key values.</returns>
IIndexQuery<T, I1, I2> Where(Func<I1, I2, bool> predicate);
}
/// <summary>
/// Typed query via 3-component index interface
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <typeparam name="I1">Type of the first component indexed member</typeparam>
/// <typeparam name="I2">Type of the second component indexed member</typeparam>
/// <typeparam name="I3">Type of the third component indexed member</typeparam>
public interface IIndexQuery<T, I1, I2, I3> : IIndexQuery<T>
where T : class
{
/// <summary>
/// Lazy loads entities returned by the query
/// </summary>
/// <returns>List of lazy-loaded entities identitified by the query</returns>
List<Lazy<T, I1, I2, I3>> ToLazyList();
/// <summary>
/// Returns a specified number of contiguous entities from the start of a query.
/// </summary>
/// <param name="count">The number of elements to return.</param>
/// <returns>A new query that returns the specified number of entities.</returns>
IIndexQuery<T, I1, I2, I3> Take(int count);
/// <summary>
/// Bypasses a specified number of entities in a query and then returns the remaining entities.
/// </summary>
/// <param name="count">The number of entities to skip before returning the remaining entities.</param>
/// <returns>A new query that bypasses the specified number of entities.</returns>
IIndexQuery<T, I1, I2, I3> Skip(int count);
/// <summary>
/// Returns entities with specified 3-component lower bound
/// </summary>
IIndexQuery<T, I1, I2, I3> GreaterThan(I1 key1, I2 key2 = default(I2), I3 key3 = default(I3), bool inclusive = false);
/// <summary>
/// Returns entities with specified 3-component upper bound
/// </summary>
IIndexQuery<T, I1, I2, I3> LessThan(I1 key1, I2 key2 = default(I2), I3 key3 = default(I3), bool inclusive = false);
/// <summary>
/// Returns entities with specified 3-component key value
/// </summary>
/// <param name="key1">First component key value</param>
/// <param name="key2">Second component key value</param>
/// <param name="key3">Third component key value</param>
/// <returns>A new query that returns entities with specified key value.</returns>
IIndexQuery<T, I1, I2, I3> Key(I1 key1, I2 key2, I3 key3);
/// <summary>
/// Returns entities with filtered key values
/// </summary>
/// <param name="predicate">Predicate function to filter entities</param>
/// <returns>A new query that returns entities with filtered key values.</returns>
IIndexQuery<T, I1, I2, I3> Where(Func<I1, I2, I3, bool> predicate);
}
abstract class IndexQueryBase<T, K, R>
where T : class
where R : class
{
protected readonly IIndex<T, K> _index;
protected readonly IndexQueryArgs<K> _args;
public IndexQueryBase(IIndex<T, K> index)
{
_index = index;
_args = new IndexQueryArgs<K>();
}
protected IndexQueryBase(IndexQueryBase<T, K, R> source)
{
_index = source._index;
_args = new IndexQueryArgs<K>(source._args);
}
public int Count()
{
return _index.ExecuteCount(_args);
}
public List<PK> ToIdList<PK>()
{
_index.Table.GetPrimaryIndex<PK>();
return _index.ExecuteToList<PK>(_args, (k, pk) => (PK)pk.Key);
}
public List<T> ToList()
{
return _index.ExecuteToList(_args);
}
public R Take(int count)
{
return CloneAndUpdate(i => i._args.Take = count);
}
public R Skip(int count)
{
return CloneAndUpdate(i => i._args.Skip = count);
}
public R GreaterThan(K min, bool orEqual = false)
{
return CloneAndUpdate(i => { i._args.Min = min; i._args.MinInclusive = orEqual; });
}
public R LessThan(K max, bool orEqual = false)
{
return CloneAndUpdate(i => { i._args.Max = max; i._args.MaxInclusive = orEqual; });
}
public R Key(K key)
{
return CloneAndUpdate(i => { i._args.Max = key; i._args.Min = key; i._args.MaxInclusive = true; i._args.MinInclusive = true; });
}
public R Where(Func<K, bool> predicate)
{
return CloneAndUpdate(i => i._args.Filter = predicate);
}
protected abstract R Clone();
protected R CloneAndUpdate(Action<IndexQueryBase<T, K, R>> updater)
{
var result = Clone();
updater(result as IndexQueryBase<T, K, R>);
return result;
}
}
class IndexQuery<T, I1> : IndexQueryBase<T, I1, IIndexQuery<T, I1>>, IIndexQuery<T, I1> where T : class
{
IndexQuery(IndexQuery<T, I1> source) : base(source) { }
public IndexQuery(IIndex<T, I1> index) : base(index) { }
public List<Lazy<T, I1>> ToLazyList()
{
return _index.ExecuteToList(_args, _index.Table.LazyCtor<I1>);
}
protected override IIndexQuery<T, I1> Clone()
{
return new IndexQuery<T, I1>(this);
}
}
class IndexQuery<T, I1, I2> : IndexQueryBase<T, Indexer<I1, I2>, IIndexQuery<T, I1, I2>>, IIndexQuery<T, I1, I2> where T : class
{
IndexQuery(IndexQuery<T, I1, I2> source) : base(source) { }
public IndexQuery(IIndex<T, Indexer<I1, I2>> index) : base(index) { }
public List<Lazy<T, I1, I2>> ToLazyList()
{
return _index.ExecuteToList(_args, _index.Table.LazyCtor<I1, I2>);
}
public IIndexQuery<T, I1, I2> GreaterThan(I1 key1, I2 key2 = default(I2), bool inclusive = false)
{
return GreaterThan(new Indexer<I1, I2>(key1, key2), inclusive);
}
public IIndexQuery<T, I1, I2> LessThan(I1 key1, I2 key2 = default(I2), bool inclusive = false)
{
return LessThan(new Indexer<I1, I2>(key1, key2), inclusive);
}
public IIndexQuery<T, I1, I2> Key(I1 key1, I2 key2)
{
return Key(new Indexer<I1, I2>(key1, key2));
}
protected override IIndexQuery<T, I1, I2> Clone()
{
return new IndexQuery<T, I1, I2>(this);
}
public IIndexQuery<T, I1, I2> Where(Func<I1, I2, bool> predicate)
{
return base.Where(k => predicate(k.Key1, k.Key2));
}
}
class IndexQuery<T, I1, I2, I3> : IndexQueryBase<T, Indexer<I1, I2, I3>, IIndexQuery<T, I1, I2, I3>>, IIndexQuery<T, I1, I2, I3> where T : class
{
IndexQuery(IndexQuery<T, I1, I2, I3> source) : base(source) { }
public IndexQuery(IIndex<T, Indexer<I1, I2, I3>> index) : base(index) { }
public List<Lazy<T, I1, I2, I3>> ToLazyList()
{
return _index.ExecuteToList(_args, _index.Table.LazyCtor<I1, I2, I3>);
}
public IIndexQuery<T, I1, I2, I3> GreaterThan(I1 key1, I2 key2 = default(I2), I3 key3 = default(I3), bool inclusive = false)
{
return GreaterThan(new Indexer<I1, I2, I3>(key1, key2, key3), inclusive);
}
public IIndexQuery<T, I1, I2, I3> LessThan(I1 key1, I2 key2 = default(I2), I3 key3 = default(I3), bool inclusive = false)
{
return LessThan(new Indexer<I1, I2, I3>(key1, key2, key3), inclusive);
}
public IIndexQuery<T, I1, I2, I3> Key(I1 key1, I2 key2, I3 key3)
{
return Key(new Indexer<I1, I2, I3>(key1, key2, key3));
}
protected override IIndexQuery<T, I1, I2, I3> Clone()
{
return new IndexQuery<T, I1, I2, I3>(this);
}
public IIndexQuery<T, I1, I2, I3> Where(Func<I1, I2, I3, bool> predicate)
{
return base.Where(k => predicate(k.Key1, k.Key2, k.Key3));
}
}
}
|
using System;
using NUnit.Framework;
using Foundation;
using CloudKit;
using ObjCRuntime;
using Xamarin.Utils;
namespace MonoTouchFixtures.CloudKit
{
[TestFixture]
[Preserve (AllMembers = true)]
public class CKFetchRecordsOperationTest
{
CKRecordID [] recordIDs = new CKRecordID [0];
CKFetchRecordsOperation op = null;
[SetUp]
public void SetUp ()
{
TestRuntime.AssertXcodeVersion (6, 0);
TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false);
op = new CKFetchRecordsOperation (recordIDs);
}
[TearDown]
public void TearDown ()
{
op?.Dispose ();
}
[Test]
public void PerRecordProgressSetter ()
{
op.PerRecordProgress = (id, p) => { Console.WriteLine ("Notification");};
Assert.NotNull (op.PerRecordProgress);
}
[Test]
public void PerRecordCompletionSetter ()
{
op.PerRecordCompletion = (record, id, e) => { Console.WriteLine ("Notification");};
Assert.NotNull (op.PerRecordCompletion);
}
[Test]
public void TestCompletedSetter ()
{
op.Completed = (idDict, e) => { Console.WriteLine ("Completed");};
Assert.NotNull (op.Completed);
}
}
}
|
namespace TopDownProteomics.ProForma
{
/// <summary>
/// Anything that describes a modification.
/// </summary>
public interface IProFormaDescriptor
{
/// <summary>The key.</summary>
ProFormaKey Key { get; }
/// <summary>The type of the evidence.</summary>
ProFormaEvidenceType EvidenceType { get; }
/// <summary>The value.</summary>
string Value { get; }
}
} |
using Client.Repository.Interface;
using Common.DTO;
using Common.Extension;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Client.Controllers
{
[Authorize(Roles = Constant.Role_Customer)]
public class RequestController : Controller
{
private readonly IRequestRepository _rp;
public RequestController(IRequestRepository rp)
{
_rp = rp;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> SendRequest(string message)
{
ClaimsIdentity claimsIdentity = (ClaimsIdentity)User.Identity;
Claim claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
UserRequest ur = new UserRequest
{
UserId = Convert.ToInt32(claim.Value),
Message = message
};
if (!await _rp.SendRequest(ur))
{
return Json(new { success = false, message = "Gửi thất bại" });
}
return Json(new { success = true, message = "Gửi thành công" });
}
}
}
|
namespace MercadoPago.Resource.Payment
{
/// <summary>
/// Payment's transaction data.
/// </summary>
public class PaymentTransactionData
{
/// <summary>
/// QR code.
/// </summary>
public string QrCode { get; set; }
/// <summary>
/// QR code image in Base 64.
/// </summary>
public string QrCodeBase64 { get; set; }
/// <summary>
/// Transaction ID.
/// </summary>
public string TransactionId { get; set; }
/// <summary>
/// Bank transfer ID.
/// </summary>
public long? BankTransferId { get; set; }
/// <summary>
/// Financial institution.
/// </summary>
public long? FinancialInstitution { get; set; }
/// <summary>
/// Bank info.
/// </summary>
public PaymentBankInfo BankInfo { get; set; }
}
}
|
using RoslynMetrics.Contracts;
using System;
using System.Runtime.CompilerServices;
using RoslynMetrics.Contracts.Metrics;
namespace RoslynMetrics.CSharp
{
internal sealed class HalsteadMetrics : IHalsteadMetrics
{
public readonly static IHalsteadMetrics GenericInstanceSetPropertyMetrics;
public readonly static IHalsteadMetrics GenericStaticSetPropertyMetrics;
public readonly static IHalsteadMetrics GenericInstanceGetPropertyMetrics;
public readonly static IHalsteadMetrics GenericStaticGetPropertyMetrics;
public int NumOperands
{
get
{
return JustDecompileGenerated_get_NumOperands();
}
set
{
JustDecompileGenerated_set_NumOperands(value);
}
}
private int JustDecompileGenerated_NumOperands_k__BackingField;
public int JustDecompileGenerated_get_NumOperands()
{
return this.JustDecompileGenerated_NumOperands_k__BackingField;
}
internal void JustDecompileGenerated_set_NumOperands(int value)
{
this.JustDecompileGenerated_NumOperands_k__BackingField = value;
}
public int NumOperators
{
get
{
return JustDecompileGenerated_get_NumOperators();
}
set
{
JustDecompileGenerated_set_NumOperators(value);
}
}
private int JustDecompileGenerated_NumOperators_k__BackingField;
public int JustDecompileGenerated_get_NumOperators()
{
return this.JustDecompileGenerated_NumOperators_k__BackingField;
}
internal void JustDecompileGenerated_set_NumOperators(int value)
{
this.JustDecompileGenerated_NumOperators_k__BackingField = value;
}
public int NumUniqueOperands
{
get
{
return JustDecompileGenerated_get_NumUniqueOperands();
}
set
{
JustDecompileGenerated_set_NumUniqueOperands(value);
}
}
private int JustDecompileGenerated_NumUniqueOperands_k__BackingField;
public int JustDecompileGenerated_get_NumUniqueOperands()
{
return this.JustDecompileGenerated_NumUniqueOperands_k__BackingField;
}
internal void JustDecompileGenerated_set_NumUniqueOperands(int value)
{
this.JustDecompileGenerated_NumUniqueOperands_k__BackingField = value;
}
public int NumUniqueOperators
{
get
{
return JustDecompileGenerated_get_NumUniqueOperators();
}
set
{
JustDecompileGenerated_set_NumUniqueOperators(value);
}
}
private int JustDecompileGenerated_NumUniqueOperators_k__BackingField;
public int JustDecompileGenerated_get_NumUniqueOperators()
{
return this.JustDecompileGenerated_NumUniqueOperators_k__BackingField;
}
internal void JustDecompileGenerated_set_NumUniqueOperators(int value)
{
this.JustDecompileGenerated_NumUniqueOperators_k__BackingField = value;
}
static HalsteadMetrics()
{
HalsteadMetrics halsteadMetric = new HalsteadMetrics()
{
NumOperands = 5,
NumOperators = 3,
NumUniqueOperands = 4,
NumUniqueOperators = 3
};
HalsteadMetrics.GenericInstanceSetPropertyMetrics = halsteadMetric;
HalsteadMetrics halsteadMetric1 = new HalsteadMetrics()
{
NumOperands = 4,
NumOperators = 3,
NumUniqueOperands = 3,
NumUniqueOperators = 3
};
HalsteadMetrics.GenericStaticSetPropertyMetrics = halsteadMetric1;
HalsteadMetrics halsteadMetric2 = new HalsteadMetrics()
{
NumOperands = 3,
NumOperators = 2,
NumUniqueOperands = 3,
NumUniqueOperators = 2
};
HalsteadMetrics.GenericInstanceGetPropertyMetrics = halsteadMetric2;
HalsteadMetrics halsteadMetric3 = new HalsteadMetrics()
{
NumOperands = 2,
NumOperators = 1,
NumUniqueOperands = 2,
NumUniqueOperators = 1
};
HalsteadMetrics.GenericStaticGetPropertyMetrics = halsteadMetric3;
}
public HalsteadMetrics()
{
}
public double? GetBugs()
{
double? effort = this.GetEffort();
if (!effort.HasValue)
{
return null;
}
return new double?((double)effort.GetValueOrDefault() / 3000);
}
public double GetDifficulty()
{
return (double)this.NumUniqueOperators / 2 * ((double)this.NumOperands / (double)this.NumUniqueOperands);
}
public double? GetEffort()
{
double difficulty = this.GetDifficulty();
double? volume = this.GetVolume();
if (!volume.HasValue)
{
return null;
}
double num = difficulty;
double? nullable = volume;
if (!nullable.HasValue)
{
return null;
}
return new double?(num * (double)nullable.GetValueOrDefault());
}
public int GetLength()
{
return checked(this.NumOperators + this.NumOperands);
}
public int GetVocabulary()
{
return checked(this.NumUniqueOperators + this.NumUniqueOperands);
}
public double? GetVolume()
{
double num = 2;
double vocabulary = (double)this.GetVocabulary();
double length = (double)this.GetLength();
if (vocabulary == 0)
{
return null;
}
return new double?(length * Math.Log(vocabulary, num));
}
}
} |
using Microsoft.Maui.Controls.Internals;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Hosting;
using Microsoft.Maui.HotReload;
namespace Microsoft.Maui.Controls
{
public partial class ContentPage : IPage, HotReload.IHotReloadableView
{
// TODO ezhart That there's a layout alignment here tells us this hierarchy needs work :)
public Primitives.LayoutAlignment HorizontalLayoutAlignment => Primitives.LayoutAlignment.Fill;
// TODO ezhart super sus
public Thickness Margin => Thickness.Zero;
IView IPage.Content => Content;
protected override Size MeasureOverride(double widthConstraint, double heightConstraint)
{
if (Content is IFrameworkElement frameworkElement)
{
frameworkElement.Measure(widthConstraint, heightConstraint);
}
return new Size(widthConstraint, heightConstraint);
}
protected override Size ArrangeOverride(Rectangle bounds)
{
// Update the Bounds (Frame) for this page
Layout(bounds);
if (Content is IFrameworkElement element)
{
element.Arrange(bounds);
element.Handler?.SetFrame(element.Frame);
}
return Frame.Size;
}
protected override void InvalidateMeasureOverride()
{
base.InvalidateMeasureOverride();
if (Content is IFrameworkElement frameworkElement)
{
frameworkElement.InvalidateMeasure();
}
}
#region HotReload
IView IReplaceableView.ReplacedView => HotReload.MauiHotReloadHelper.GetReplacedView(this) ?? this;
HotReload.IReloadHandler HotReload.IHotReloadableView.ReloadHandler { get; set; }
void HotReload.IHotReloadableView.TransferState(IView newView)
{
//TODO: Let you hot reload the the ViewModel
//TODO: Lets do a real state transfer
if (newView is View v)
v.BindingContext = BindingContext;
}
void HotReload.IHotReloadableView.Reload()
{
Device.BeginInvokeOnMainThread(() =>
{
this.CheckHandlers();
var reloadHandler = ((IHotReloadableView)this).ReloadHandler;
reloadHandler?.Reload();
//TODO: if reload handler is null, Do a manual reload?
});
}
#endregion
}
}
|
namespace P08.Threeuple
{
public class Threeuple<Tfirst, Tsecond, Tthird>
{
public Threeuple(Tfirst first, Tsecond second, Tthird third)
{
this.FirstItem = first;
this.SecondItem = second;
this.ThirdItem = third;
}
public Tfirst FirstItem { get; set; }
public Tsecond SecondItem { get; set; }
public Tthird ThirdItem { get; set; }
public override string ToString()
{
return $"{FirstItem} -> {SecondItem} -> {ThirdItem}";
}
}
}
|
using UnityEngine;
using System.Collections;
public class basicShooting : MonoBehaviour {
protected Vector2 direction;
public GameObject mainBullet;
protected float width;
protected GameObject bullet;
protected SpriteRenderer sr;
protected SpriteRenderer gruSr;
protected AudioSource sound;
protected gunStats stats;
// Use this for initialization
virtual protected void Start () {
sound = GetComponent<AudioSource>();
width = GetComponent<SpriteRenderer>().sprite.rect.width;
sr = GetComponent<SpriteRenderer>();
gruSr = transform.parent.gameObject.GetComponent<SpriteRenderer>();
stats = GetComponent<gunStats>();
}
// Update is called once per frame
virtual protected void Update () {
GetDirection();
UpdateGunLayer();
}
virtual protected void GetDirection () {
Vector3 mousePos = Input.mousePosition;
direction = (mousePos - Camera.main.WorldToScreenPoint(transform.position)).normalized;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
virtual protected void SpawnBullet() {
Vector2 currentPosition = new Vector2(transform.position.x, transform.position.y);
Vector2 bulletStartPoint = currentPosition + direction * (width + 2) / 100;
bullet = Instantiate(mainBullet, bulletStartPoint, Quaternion.identity) as GameObject;
bullet.transform.rotation = transform.rotation;
bullet.GetComponent<friendlyBulletCollisions>().combo = GetComponent<gunStats>().combo;
}
virtual protected void UpdateGunLayer() {
if (Mathf.Atan2(direction.y, direction.x) > 0){
sr.sortingOrder = gruSr.sortingOrder - 1;
}
else {
sr.sortingOrder = gruSr.sortingOrder + 1;
}
if (direction.x >= 0) {
sr.sprite = stats.right;
}
else {
sr.sprite = stats.left;
}
}
}
|
using System;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp;
using Sf = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using Sk = Microsoft.CodeAnalysis.CSharp.SyntaxKind;
using St = Microsoft.CodeAnalysis.SyntaxToken;
namespace GirLoader.Helper
{
public class String
{
private readonly string _text;
public String(string text)
{
_text = text;
}
public String ToCamelCase()
{
var pascalCase = ToPascal(_text);
return _text switch
{
{ Length: 0 } => new String(""),
{ Length: 1 } => new String(pascalCase.ToLower()),
_ => new String(char.ToLower(pascalCase[0]) + pascalCase[1..])
};
}
public String ToPascalCase()
{
return _text switch
{
{ Length: 0 } => new String(""),
{ Length: 1 } => new String(_text.ToUpper()),
_ => new String(ToPascal(_text))
};
}
private static string ToPascal(string str)
{
var words = str.Replace("_", "-").Split("-");
var builder = new StringBuilder();
foreach (var word in words.Where(x => !string.IsNullOrWhiteSpace(x)))
{
builder
.Append(char.ToUpper(word[0]))
.Append(word[1..]);
}
return builder.ToString();
}
public String EscapeIdentifier()
{
var escaped = FixFirstCharIfNumber(_text);
escaped = FixIfIdentifierIsKeyword(escaped);
return new String(escaped);
}
private static string FixIfIdentifierIsKeyword(string identifier)
{
St token = Sf.ParseToken(identifier);
if (token.Kind() != Sk.IdentifierToken)
identifier = "@" + identifier;
return identifier;
}
private static string FixFirstCharIfNumber(string identifier)
{
var firstChar = identifier[0];
if (char.IsNumber(firstChar))
{
// Capitalise Second Char
if (identifier.Length > 1)
identifier = CapitaliseSecondChar(identifier);
var number = (int) char.GetNumericValue(firstChar);
return number switch
{
0 => ReplaceFirstChar("Zero", identifier),
1 => ReplaceFirstChar("One", identifier),
2 => ReplaceFirstChar("Two", identifier),
3 => ReplaceFirstChar("Three", identifier),
4 => ReplaceFirstChar("Four", identifier),
5 => ReplaceFirstChar("Five", identifier),
6 => ReplaceFirstChar("Six", identifier),
7 => ReplaceFirstChar("Seven", identifier),
8 => ReplaceFirstChar("Eight", identifier),
9 => ReplaceFirstChar("Nine", identifier),
_ => throw new Exception("Can't fix identifier " + identifier)
};
}
return identifier;
}
private static string ReplaceFirstChar(string prefix, string str)
=> prefix + str[1..];
private static string CapitaliseSecondChar(string identifier)
=> $"{identifier[0]}{char.ToUpper(identifier[1])}{identifier?[2..]}";
public string Get()
=> _text;
public override string ToString()
{
return _text;
}
}
}
|
namespace BikeShop.Services
{
public interface IConfigService
{
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace DomainCQRS
{
/// <summary>
/// Is thrown when an event is saved for a version of an Aggregate Root that already exists.
/// </summary>
[Serializable]
public class ConcurrencyException : EventToStoreException, ISerializable
{
public ConcurrencyException() : base() { }
public ConcurrencyException(string message) : base(message) { }
public ConcurrencyException(string message, Exception innerException) : base(message, innerException) { }
public ConcurrencyException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public Guid AggregateRootId { get; set; }
public int Version { get; set; }
}
}
|
// Copyright 2019 Light Conversion, UAB
// Licensed under the Apache 2.0, see LICENSE.md for more details.
namespace LightConversion.Protocols.Yadp {
/// <summary>
/// The result of the YADP command.
/// </summary>
/// <remarks>Used only in GetRegisterResponse and SetRegisterResponse packets.</remarks>
public enum ResponseResult : byte {
/// <summary>
/// Never use this!
/// </summary>
/// <remarks></remarks>
NotDefined = 0,
/// <summary>
/// Operation completed successfully.
/// </summary>
/// <remarks></remarks>
Ok = 0x10,
/// <summary>
/// Register is not readable (write-only).
/// </summary>
/// <remarks></remarks>
NotReadable = 0x20,
/// <summary>
/// Register is not writeable (read-only).
/// </summary>
/// <remarks></remarks>
NotWriteable = 0x30,
/// <summary>
/// The provided index is wrong.
/// </summary>
/// <remarks></remarks>
WrongIndex = 0x40,
/// <summary>
/// Wrong, non-existent, register address.
/// </summary>
/// <remarks></remarks>
DoesNotExist = 0x50,
/// <summary>
/// User needs elevated privileges to execute that command.
/// </summary>
/// <remarks></remarks>
InsufficientRights = 0x60,
/// <summary>
/// Queried device failed to execute the command in time.
/// </summary>
/// <remarks></remarks>
Timeout = 0x70,
/// <summary>
/// Device address is incorrect.
/// </summary>
/// <remarks></remarks>
WrongDeviceAddress = 0x80,
/// <summary>
/// The value provided is incorrect.
/// </summary>
IncorrectValue = 0x90,
/// <summary>
/// Register operation is not permitted by current state of the device.
/// </summary>
WrongState = 0xA0
}
} |
using Arbor.App.Extensions.Messaging;
namespace Milou.Deployer.Web.Core.Deployment.Environments
{
public class CreateEnvironment : ICommand<CreateEnvironmentResult>
{
public string EnvironmentTypeId { get; init; }
public string EnvironmentTypeName { get; init; }
public string PreReleaseBehavior { get; init; }
}
} |
using HexBoardGame.Runtime.GameBoard;
using TMPro;
using UnityEngine;
namespace Game.Ui
{
[RequireComponent(typeof(TMP_Text))]
public class UiOrientationText : UiTmpText
{
private const string Vertical = "Vertical";
private const string Horizontal = "Horizontal";
[SerializeField] private BoardController controller;
private void OnEnable()
{
CheckOrientation();
}
private void CheckOrientation()
{
var board = controller.Board;
if (board == null)
return;
var txt = board.Orientation == Orientation.FlatTop ? Vertical : Horizontal;
SetText(txt);
}
}
} |
using MiniEngine.Pipeline.Models.Components;
using MiniEngine.Primitives.Cameras;
using MiniEngine.Systems;
using MiniEngine.Systems.Containers;
using MiniEngine.Units;
namespace MiniEngine.Pipeline.Models.Systems
{
public sealed class UVAnimationSystem : IUpdatableSystem
{
private readonly IComponentContainer<UVAnimation> Animations;
private readonly IComponentContainer<OpaqueModel> Models;
public UVAnimationSystem(IComponentContainer<UVAnimation> animations, IComponentContainer<OpaqueModel> models)
{
this.Animations = animations;
this.Models = models;
}
public void Update(PerspectiveCamera perspectiveCamera, Seconds elapsed)
{
for (var i = 0; i < this.Animations.Count; i++)
{
var animation = this.Animations[i];
var model = this.Models.Get(animation.Entity);
for (var offsetIndex = 0; offsetIndex < animation.MeshUVOffsets.Length; offsetIndex++)
{
var offset = animation.MeshUVOffsets[offsetIndex];
model.UVOffsets[offset.MeshIndex] = offset.UVOffset;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Interop;
using Win32;
namespace WinD.Common
{
public class EmbeddedApp : HwndHost, IKeyboardInputSink
{
private IntPtr TargetHWND;
public EmbeddedApp(IntPtr intPtr)
{
TargetHWND = intPtr;
}
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
//改变样式
//User.ShowWindow(TargetHWND, User.SW_SHOW);
//User.EnableWindow(TargetHWND, 1);
int style = User.GetWindowLong(TargetHWND, User.GWL_STYLE);
//style = style & ~((int)User.WS_CAPTION) & ~((int)User.WS_THICKFRAME);
style |= ((int)User.WS_CHILD);
style |= ((int)User.WS_CLIPCHILDREN);
User.SetWindowLong(TargetHWND, User.GWL_STYLE, User.WS_CHILD);
//嵌入进去
User.SetParent(TargetHWND, hwndParent.Handle);
return new HandleRef(this, TargetHWND);
}
protected override void DestroyWindowCore(HandleRef hwnd)
{
Console.WriteLine("释放了");
}
}
}
|
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Edison.Core.Common;
using Edison.Core.Common.Models;
using Edison.Api.Helpers;
namespace Edison.Api.Controllers
{
/// <summary>
/// Controller to handle operations on Iot Hub devices
/// </summary>
[ApiController]
[Route("api/IoTHub")]
public class IoTHubController : ControllerBase
{
private readonly IoTHubControllerDataManager _iotHubControllerDataManager;
/// <summary>
/// DI Constructor
/// </summary>
public IoTHubController(IoTHubControllerDataManager iotHubControllerDataManager)
{
_iotHubControllerDataManager = iotHubControllerDataManager;
}
/// <summary>
/// Create a device
/// Call for debug only. Device Creation should be done through DPS only
/// </summary>
/// <param name="device">DeviceCreationModel</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.SuperAdmin)]
[HttpPost]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> CreationDevice(DeviceCreationModel device)
{
var result = await _iotHubControllerDataManager.CreationDevice(device);
return Ok(result);
}
/// <summary>
/// Update a device
/// </summary>
/// <param name="device">DeviceUpdateModel</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPut]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> UpdateDevice(DeviceUpdateModel device)
{
var result = await _iotHubControllerDataManager.UpdateDevice(device);
return Ok(result);
}
/// <summary>
/// Update a set of devices tags
/// </summary>
/// <param name="devices">List of device ids</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPut("Tags")]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> UpdateDevicesTags(DevicesUpdateTagsModel devices)
{
var result = await _iotHubControllerDataManager.UpdateDevicesTags(devices);
return Ok(result);
}
/// <summary>
/// Update a set of devices desired properties
/// </summary>
/// <param name="devices">List of device ids</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPut("Desired")]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> UpdateDevicesDesired(DevicesUpdateDesiredModel devices)
{
var result = await _iotHubControllerDataManager.UpdateDevicesDesired(devices);
return Ok(result);
}
/// <summary>
/// Launch a direct method on a set of devices
/// </summary>
//// <param name="devices">List of device ids</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPut("DirectMethods")]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> LaunchDevicesDirectMethod(DevicesLaunchDirectMethodModel devices)
{
var result = await _iotHubControllerDataManager.LaunchDevicesDirectMethods(devices);
return Ok(result);
}
/// <summary>
/// Delete a device
/// </summary>
/// <param name="deviceId">Device Id</param>
/// <returns>True if the masstransit publish command has succeeded</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpDelete]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> DeleteDevice(Guid deviceId)
{
var result = await _iotHubControllerDataManager.DeleteDevice(deviceId);
return Ok(result);
}
}
}
|
using Ntrada.Configuration;
namespace Ntrada
{
internal interface IUpstreamBuilder
{
string Build(Module module, Route route);
}
} |
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using NUnit.Framework;
using Octopus.RoslynAnalyzers;
using Octopus.RoslynAnalyzers.Testing.Integration;
using Verify = Tests.CSharpVerifier<Octopus.RoslynAnalyzers.Testing.Integration.IntegrationTestClassAnalyzer>;
namespace Tests.Testing.Integration
{
public class IntegrationTestClassAnalyzerFixture
{
[TestCase]
public async Task IgnoresClassesThatHaveNothingToDoWithThisAnalyser()
{
var container = @"
public class JustAClassSittingAroundDoingItsThing
{
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task IgnoresClassesThatDirectlyInheritFromIntegrationTestAndAreEmpty()
{
var container = @"
public class TestClass : IntegrationTest
{
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task DetectsClassesThatInheritFromSomeOtherClassThatInheritsFromIntegrationTest()
{
var container = @"
public class BaseClass : IntegrationTest
{
}
public class {|#0:TestClass|} : BaseClass
{
}
";
var result = new DiagnosticResult(Descriptors.Oct2001NoIntegrationTestBaseClasses).WithLocation(0);
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes(), result);
}
[TestCase]
public async Task IgnoresIntegrationTestClassesWithASingleFact()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Fact]
public void Test() {}
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task IgnoresIntegrationTestClassesWithASingleTheory()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Theory]
[Xunit.InlineData(""1"")]
public void Test(string data) {}
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task IgnoresIntegrationTestClassesWithASingleTheoryWithMultipleLinesOfData()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Theory]
[Xunit.InlineData(""1"")]
[Xunit.InlineData(""2"")]
[Xunit.InlineData(""3"")]
public void Test(string data) {}
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task IgnoresClassesThatDoNotInheritFromIntegrationTest()
{
var container = @"
public class TestClass
{
public string CanHaveThis { get; set; }
string thisToo;
public void SureWhyNotLetsHaveSomeMethods() { }
}
";
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes());
}
[TestCase]
public async Task DetectsIntegrationTestWithMoreThanOneFact()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Fact]
public void {|#0:TheFirstFact|}()
{
}
[Xunit.Fact]
public void {|#1:TheSecondFact|}()
{
}
}
";
var firstTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(0);
var secondTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(1);
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes(), firstTest, secondTest);
}
[TestCase]
public async Task DetectsIntegrationTestWithMoreThanOneTheory()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Theory]
[Xunit.InlineData(""1"")]
public void {|#0:TheFirstTheory|}(string data)
{
}
[Xunit.Theory]
[Xunit.InlineData(""1"")]
public void {|#1:TheSecondTheory|}(string data)
{
}
}
";
var firstTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(0);
var secondTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(1);
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes(), firstTest, secondTest);
}
[TestCase]
public async Task DetectsIntegrationTestWithFactsAndTheories()
{
var container = @"
public class TestClass : IntegrationTest
{
[Xunit.Fact]
public void {|#0:TheFact|}()
{
}
[Xunit.Theory]
[Xunit.InlineData(""1"")]
public void {|#1:TheTheory|}(string data)
{
}
}
";
var firstTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(0);
var secondTest = new DiagnosticResult(Descriptors.Oct2003SingleIntegrationTestInEachClass).WithLocation(1);
await Verify.VerifyAnalyzerAsync(container.WithTestingTypes(), firstTest, secondTest);
}
}
} |
using System;
using System.Threading;
using Autofac.Extras.DynamicProxy2;
using log4net;
namespace IoCSample09_Interception
{
[Intercept("LoggingInterceptor")]
public interface ICustomerService
{
void AddCustomer();
}
public class CustomerService : ICustomerService
{
private readonly ILog _logger;
private readonly Random _random;
public CustomerService(ILog logger)
{
_logger = logger;
_random = new Random();
}
public void AddCustomer()
{
Thread.Sleep(_random.Next(1000));
_logger.Info("Adding customer...");
}
}
} |
using System;
using System.Collections.Generic;
public class RoleShowWidget
{
public void setAgent(BaseEntity agent)
{
}
/// <summary>
/// 接口 播放动画
/// </summary>
/// <param name="anim"></param>
/// <param name="loop"></param>
/// <param name="add"></param>
public float playAnim(string anim, bool loop = false, string add = null)
{
return 0;
}
/// <summary>
/// 修改动画完成订阅
/// </summary>
/// <param name="isAdd"></param>
public void modifyCompleteEvent(bool isAdd)
{
}
//设置渲染层
private int maxOrder = 1000;
private int magnifyOrder = 100;//放大倍率
public void updateRenderOrder()
{
}
/// <summary>
/// 加载模型资源
/// @"AssetBundle\Prefabs\model\role_superman\model\role_superman"
/// </summary>
public void loadModel()
{
}
public void changeLookFlag(LookFlag flag)
{
}
/// <summary>
/// 实体表现刷新
/// 1 model
/// </summary>
public virtual void refresh()
{
}
public void doMove()
{
}
public void onDispose()
{
}
public void drawAttack(AttackData atkData)
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace Perlang.Tests.Integration
{
public class TestCultures : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
// A culture which uses 123.45 number format. Resembles the C locale in POSIX systems, which is the default
// unless a locale is explicitly specified. (See https://man7.org/linux/man-pages/man7/locale.7.html for
// more details)
yield return new object[] { CultureInfo.GetCultureInfo("en-US") };
// A culture which uses 123,45 number format.
yield return new object[] { CultureInfo.GetCultureInfo("sv-SE") };
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
using System;
namespace Rubik.Toolkit.Utils
{
public static class DateTimeUtil
{
/// <summary>
/// 时间戳转时间
/// </summary>
/// <param name="timestamp">时间戳</param>
/// <returns>时间</returns>
public static DateTime TimestampToDateTime(long timestamp)
{
var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 8, 0, 0), TimeZoneInfo.Local);
return startTime.Add(new TimeSpan(long.Parse($"{timestamp}0000")));
}
/// <summary>
/// 时间转时间戳
/// </summary>
/// <param name="time">时间</param>
/// <returns>时间戳</returns>
public static long DateTimeToTimestamp(this DateTime time)
{
var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 8, 0, 0), TimeZoneInfo.Local);
return (long)(time - startTime).TotalMilliseconds;
}
}
}
|
using System;
using Xunit;
using Buffer = AwesomeSockets.Buffers.Buffer;
namespace AwesomeSockets.UnitTests.Buffers
{
public class BufferTests
{
[Fact]
public void GetBuffer_ReturnsAppropriatelySizedBuffer()
{
var testBuffer = CreateValidBuffer();
const int expected = sizeof (int) + sizeof (double) + sizeof (char);
var actual = Buffer.GetBuffer(testBuffer).Length;
Assert.Equal(expected, actual);
}
[Fact]
public void GetBuffer_ThrowsBufferFinalizedException_WhenBufferIsntFinalized()
{
var invalidBuffer = CreateInvalidBuffer();
Assert.Throws<InvalidOperationException>(() => Buffer.GetBuffer(invalidBuffer));
}
[Fact]
public void GetBuffer_ThrowsArgumentNullException_WhenBufferIsNull()
{
Assert.Throws<ArgumentNullException>(() => Buffer.GetBuffer(null));
}
[Fact]
public void Add_ThrowsArgumentNullException_WhenBufferIsNull()
{
Assert.Throws<ArgumentNullException>(() => Buffer.Add(null, 4));
}
[Fact]
public void Add_ThrowsBufferFinalizedException_WhenBufferIsFinalized()
{
var testBuffer = CreateValidBuffer();
Assert.Throws<InvalidOperationException>(() => Buffer.Add(testBuffer, 1));
}
[Fact]
public void ClearBuffer_ThrowsArgumentNullException_WhenBufferIsNull()
{
Assert.Throws<ArgumentNullException>(() => Buffer.ClearBuffer(null));
}
[Fact]
public void FinalizeBuffer_DoesntThrowBufferFinalizedException_IfBufferIsAlreadyFinalized()
{
var testBuffer = CreateValidBuffer();
Buffer.FinalizeBuffer(testBuffer);
}
[Fact]
public void Duplicate_ReturnsADifferentButCorrectlyDuplicatedBuffer()
{
var testBuffer = CreateValidBuffer();
var duplicateBuffer = Buffer.Duplicate(testBuffer);
Assert.NotSame(testBuffer, duplicateBuffer); //This checks to see that there isn't any REFERENCE equality
Assert.True(testBuffer.Equals(duplicateBuffer)); //This check to see if there is VALUE equality
}
private Buffer CreateValidBuffer()
{
var buff = CreateBuffer();
Buffer.FinalizeBuffer(buff);
return buff;
}
private Buffer CreateInvalidBuffer()
{
return CreateBuffer();
}
private Buffer CreateBuffer()
{
var tempBuffer = Buffer.New(14);
Buffer.Add(tempBuffer, 12);
Buffer.Add(tempBuffer, 32.0);
Buffer.Add(tempBuffer, 'c');
return tempBuffer;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.