content stringlengths 23 1.05M |
|---|
using System.Text.Json.Serialization;
namespace TweetScraping.Models
{
public class GuestTokenAuth
{
[JsonPropertyName("guest_token")]
public string GuestToken { get; set; }
}
}
|
using OpenQA.Selenium.Firefox;
namespace Selenium.Contrib.Examples
{
public static class WebDriverFactory
{
public static FirefoxDriver GetWebDriver()
{
var profile = new FirefoxProfile();
var driver = new FirefoxDriver(profile);
driver.Manage().Window.Maximize();
return driver;
}
}
} |
using Newtonsoft.Json;
namespace Umbraco.Forms.Integrations.Crm.Hubspot.Services
{
internal abstract class BaseTokenRequest
{
public abstract string GrantType { get; }
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("redirect_uri")]
public string RedirectUrl { get; set; }
}
}
|
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using MonoGame.Framework;
using MonoGame.Framework.Memory;
using MonoGame.Framework.Vectors;
using MonoGame.Imaging.Attributes.Coder;
using MonoGame.Imaging.Coders.Detection;
using MonoGame.Imaging.Utilities;
using StbSharp.ImageRead;
namespace MonoGame.Imaging.Coders.Decoding
{
public abstract partial class StbImageDecoderBase<TOptions> : IImageDecoder, IProgressReportingCoder<IImageDecoder>
where TOptions : DecoderOptions, new()
{
private readonly object _progressMutex = new object();
private ImagingProgressCallback<IImageDecoder>? _progress;
private ReadProgressCallback? _readProgress;
private Image.ConvertPixelDataDelegate? _convertPixels;
public event ImagingProgressCallback<IImageDecoder>? Progress
{
add
{
if (value == null)
return;
lock (_progressMutex)
{
_progress += value;
if (_readProgress == null)
{
_readProgress = (p, r) => _progress?.Invoke(this, p, r?.ToMGRect());
ReadState.Progress += _readProgress;
}
}
}
remove
{
if (value == null)
return;
lock (_progressMutex)
{
_progress -= value;
if (_progress == null && _readProgress != null)
{
ReadState.Progress -= _readProgress;
_readProgress = null;
}
}
}
}
public IImagingConfig ImagingConfig { get; }
public TOptions DecoderOptions { get; }
public ImageBinReader Reader { get; }
public ReadState ReadState { get; }
public bool IsDisposed { get; private set; }
public Image? CurrentImage { get; private set; }
public VectorType? SourcePixelType { get; private set; } // TODO: move into CurrentImage metadata
public VectorType? TargetPixelType { get; set; }
public int FrameIndex { get; protected set; }
DecoderOptions IImageDecoder.DecoderOptions => DecoderOptions;
CoderOptions IImageCoder.CoderOptions => DecoderOptions;
public virtual bool CanReportProgressRectangle => false;
public abstract ImageFormat Format { get; }
public StbImageDecoderBase(
IImagingConfig config, Stream stream, TOptions? decoderOptions)
{
ImagingConfig = config ?? throw new ArgumentNullException(nameof(config));
DecoderOptions = decoderOptions ?? new();
byte[] buffer = RecyclableMemoryManager.Default.GetBlock();
Reader = new ImageBinReader(stream, buffer);
ReadState = new ReadState()
{
StateReadyCallback = OnStateReady,
OutputPixelLineCallback = OnOutputPixelLine,
OutputPixelCallback = OnOutputPixel
};
}
public void Decode(CancellationToken cancellationToken = default)
{
Reader.CancellationToken = cancellationToken;
ReadState.CancellationToken = cancellationToken;
Read();
FrameIndex++;
}
protected abstract void Read();
private void OnStateReady(ReadState state)
{
SourcePixelType = GetVectorType(state);
var dstType = TargetPixelType ?? SourcePixelType;
var size = new Size(state.Width, state.Height);
if (DecoderOptions.ClearImageMemory)
{
CurrentImage = Image.Create(dstType, size);
}
else
{
CurrentImage = Image.CreateUninitialized(dstType, size);
}
_convertPixels = Image.GetConvertPixelsDelegate(SourcePixelType, dstType);
_progress?.Invoke(this, 0, null);
}
private void AssertValidStateForOutput()
{
if (SourcePixelType == null)
throw new InvalidOperationException("Missing source pixel type.");
if (CurrentImage == null)
throw new InvalidOperationException("Missing image buffer.");
}
private void OnOutputPixelLineContiguous(
AddressingMajor addressing, int line, int start, ReadOnlySpan<byte> pixels)
{
if (SourcePixelType == CurrentImage!.PixelType)
{
if (addressing == AddressingMajor.Row)
CurrentImage.SetPixelByteRow(start, line, pixels);
else if (addressing == AddressingMajor.Column)
CurrentImage.SetPixelByteColumn(start, line, pixels);
else
throw new ArgumentOutOfRangeException(nameof(addressing));
}
else
{
int dstElementSize = CurrentImage!.PixelType.ElementSize;
if (addressing == AddressingMajor.Row)
{
var dstSpan = CurrentImage.GetPixelByteRowSpan(line)[(start * dstElementSize)..];
_convertPixels!.Invoke(pixels, dstSpan);
}
else if (addressing == AddressingMajor.Column)
{
throw new NotImplementedException();
//CurrentImage.SetPixelByteColumn(start, line, pixels);
}
else
{
throw new ArgumentOutOfRangeException(nameof(addressing));
}
}
}
[SkipLocalsInit]
private void OnOutputPixelLine(
ReadState state, AddressingMajor addressing,
int line, int start, int spacing, ReadOnlySpan<byte> pixelData)
{
if (spacing == 0)
throw new ArgumentOutOfRangeException(nameof(spacing));
AssertValidStateForOutput();
if (_progress != null)
{
int pline = state.Orientation.HasFlag(ImageOrientation.BottomToTop) ? (state.Height - line) : line;
_progress.Invoke(
this,
pline / (float)state.Height,
new Rectangle(start, line, state.Width - start, 1));
}
if (spacing == 1)
{
OnOutputPixelLineContiguous(addressing, line, start, pixelData);
return;
}
int dstElementSize = CurrentImage!.PixelType.ElementSize;
if (SourcePixelType == CurrentImage.PixelType)
{
if (addressing == AddressingMajor.Row)
{
var imageRow = CurrentImage.GetPixelByteRowSpan(line)[(start * dstElementSize)..];
for (int x = 0; x < pixelData.Length; x += dstElementSize)
{
var src = pixelData.Slice(x, dstElementSize);
var dst = imageRow.Slice(x * spacing, dstElementSize);
src.CopyTo(dst);
}
}
else if (addressing == AddressingMajor.Column)
{
throw new NotImplementedException();
}
else
{
throw new ArgumentOutOfRangeException(nameof(addressing));
}
}
else
{
if (addressing == AddressingMajor.Row)
{
Span<byte> imageRow = CurrentImage.GetPixelByteRowSpan(line)[(start * dstElementSize)..];
Span<byte> buffer = stackalloc byte[4096];
int srcElementSize = SourcePixelType!.ElementSize;
int bufferCapacity = buffer.Length / dstElementSize;
int pixelCount = pixelData.Length / srcElementSize;
int dstOffset = 0;
do
{
int count = pixelCount > bufferCapacity ? bufferCapacity : pixelCount;
var slice = pixelData.Slice(0, count * srcElementSize);
_convertPixels!.Invoke(slice, buffer);
int bufOffset = 0;
for (int x = 0; x < slice.Length; x += srcElementSize)
{
var src = buffer.Slice(bufOffset, dstElementSize);
var dst = imageRow.Slice(dstOffset, dstElementSize);
src.CopyTo(dst);
bufOffset += dstElementSize;
dstOffset += dstElementSize * spacing;
}
pixelData = pixelData[slice.Length..];
pixelCount -= count;
} while (!pixelData.IsEmpty);
}
else if (addressing == AddressingMajor.Column)
{
throw new NotImplementedException();
}
else
{
throw new ArgumentOutOfRangeException(nameof(addressing));
}
}
}
private void OnOutputPixel(ReadState state, int x, int y, ReadOnlySpan<byte> pixel)
{
AssertValidStateForOutput();
if (SourcePixelType == CurrentImage!.PixelType)
{
CurrentImage.SetPixelByteRow(x, y, pixel);
}
else
{
throw new NotImplementedException();
}
}
public static VectorType GetVectorType(ReadState state)
{
if (state == null)
throw new ArgumentNullException(nameof(state));
return StbImageInfoDetectorBase.GetVectorType(state.OutComponents, state.OutDepth);
}
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
if (!Reader.IsDisposed)
{
RecyclableMemoryManager.Default.ReturnBlock(Reader.Buffer);
Reader.Dispose();
}
IsDisposed = true;
}
}
~StbImageDecoderBase()
{
Dispose(disposing: false);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
|
using UnityEngine;
[RequireComponent(typeof(GamePiece))]
public class TimeBonus : MonoBehaviour
{
[Range(0, 5)]
public int bonusValue = 5;
[Range(0f, 1f)]
public float chanceForBonus = 0.1f;
public GameObject bonusGlow;
public GameObject ringGlow;
public Material[] bonusMaterials;
private void Start()
{
float random = Random.Range(0f, 1f);
if (random > chanceForBonus)
{
bonusValue = 0;
}
if (GameManager.Instance != null)
{
if (GameManager.Instance.LevelGoal.levelCounter == LevelCounter.Moves)
{
bonusValue = 0;
}
}
SetActive(bonusValue != 0);
if (bonusValue != 0)
{
SetupMaterial(bonusValue - 1, bonusGlow);
}
}
private void SetActive(bool state)
{
if (bonusGlow != null)
{
bonusGlow.SetActive(state);
}
if (ringGlow != null)
{
ringGlow.SetActive(state);
}
}
private void SetupMaterial(int value, GameObject bonusGlow)
{
int clampedValue = Mathf.Clamp(value, 0, bonusMaterials.Length - 1);
if (bonusMaterials[clampedValue] != null)
{
if (bonusGlow != null)
{
ParticleSystemRenderer bonusGlowRenderer =
bonusGlow.GetComponent<ParticleSystemRenderer>();
bonusGlowRenderer.material = bonusMaterials[clampedValue];
}
}
}
}
|
namespace MiddlewareUtility.Tools
{
public static class DayIntervalFactoryMessages
{
public static string TIME_IN_UNSPECIFIED { get; } = "Time doesn't be unspecified.";
public static string OFFSET_MORE_THEN_MAXVALUE { get; } = "Offset more than maxvalue";
public static string OFFSET_LESS_THEN_MINVALUE { get; } = "Offset less than minvalue";
}
} |
namespace RedBlackTree.Tests.TimeTests
{
using NUnit.Framework;
[TestFixture]
class InsertFourth
{
[Test]
[Timeout(500)]
public void Insert_MultipleElements_ShouldBeFast()
{
RedBlackTree<int> rbt = new RedBlackTree<int>();
for (int i = 0; i < 100000; i++)
{
rbt.Insert(i);
}
}
}
} |
//------------------------------------------------------------------------------
// <copyright file="IListSource.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.ComponentModel {
using System;
using Microsoft.Win32;
using System.Collections;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
TypeConverterAttribute("System.Windows.Forms.Design.DataSourceConverter, " + AssemblyRef.SystemDesign),
Editor("System.Windows.Forms.Design.DataSourceListEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
MergableProperty(false)
]
public interface IListSource {
bool ContainsListCollection { get; }
IList GetList();
}
}
|
using NUnit.Framework;
using VkNet.Enums.SafetyEnums;
using VkNet.Model;
using VkNet.Tests.Infrastructure;
namespace VkNet.Tests.Categories.Messages
{
[TestFixture]
public class MessagesSendMessageEventAnswerTests : MessagesBaseTests
{
[Test]
public void SendMessageEventAnswer()
{
Url = "https://api.vk.com/method/messages.sendMessageEventAnswer";
ReadJsonFile(JsonPaths.True);
var data = new EventData
{
Type = MessageEventType.SnowSnackbar,
Text = "text"
};
var result = Api.Messages.SendMessageEventAnswer("testEventId", 1, 1, data);
Assert.IsTrue(result);
}
}
} |
using System.Net;
using TimCodes.ApiAbstractions.Http.Sample.Models;
using TimCodes.ApiAbstractions.Http.Sample.Models.Responses;
using TimCodes.ApiAbstractions.Http.Server;
namespace TimCodes.ApiAbstractions.Http.Sample.Business;
public class RecipeService : IRecipeService
{
private readonly Dictionary<int, Recipe> _recipes = new Dictionary<int, Recipe>()
{
{
1,
new Recipe
{
Id = 1,
Title = "Spaghetti Meatballs",
Ingredients = new[] { "Pasta", "Meat" },
Method = "Put some balls of meat on your pasta"
}
},
{
2,
new Recipe
{
Id = 2,
Title = "Beef Pie",
Ingredients = new[] { "Pastry", "Beef", "Gravy" },
Method = "Put some cow in your gravy and then put your newly gravied cow in your pastry"
}
}
};
public Task<RecipeListResponse> GetAllAsync()
=> Task.FromResult(HttpApiMessageBuilder.CreateSuccess<RecipeListResponse>(m =>
{
m.Recipes = _recipes.Values.ToList();
}));
public Task<RecipeResponse> GetAsync(int id)
=> Task.FromResult(
_recipes.ContainsKey(id) ?
HttpApiMessageBuilder.CreateSuccess<RecipeResponse>(m =>
{
m.Recipe = _recipes[id];
}) :
HttpApiMessageBuilder.CreateFailure<RecipeResponse>(
HttpStatusCode.NotFound,
"Recipe not found",
RecipeError.NotYetCreated));
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Xunit;
using JasonSoft.Net;
namespace JasonSoft.Tests.Net
{
public class IPAddressTest
{
[Fact]
public void GetIP()
{
UInt32 ipNumber = 3232235521;
System.Net.IPAddress aa = new System.Net.IPAddress(ipNumber);
Console.WriteLine(aa.ToNumber());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
enum DecoupledInputMode
{
Keyboard = 0,
TouchDPad = 1,
Joystick_fixed = 2,
Joystick_floating = 4,
Joystick_dynamic = 8,
Joystick_default = 16,
}
public class DecoupledControllerInputTest : MonoBehaviour
{
[SerializeField] DecoupledInputMode mode = DecoupledInputMode.Keyboard;
[SerializeField] GameObject AssetJoystick;
[SerializeField] VariableJoystick joystick
{
get
{
return AssetJoystick.GetComponent<VariableJoystick>();
}
}
[SerializeField] Dropdown dropdown;
[SerializeField] GameObject JoystickDefault_GO;
[SerializeField] SegmentedJoystick joystick_default
{
get
{
return JoystickDefault_GO.GetComponent<SegmentedJoystick>();
}
}
[SerializeField] GameObject DPad_GO;
IDPad dpad
{
get
{
return DPad_GO.GetComponent<IDPad>();
}
}
public Vector2 touchInputVector = new Vector2(0, 0);
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// TODO nachforschen wo/wann am besten refresh stattfinden sollte. erst bei update() oder schon früher?
refreshInputVector();
}
public void ModeChanged(int index)
{
// HACK nur für demo
int dropdownMode = index;// dropdown.value;
switch (dropdownMode)
{
case 0:
mode = DecoupledInputMode.Keyboard;
AssetJoystick.SetActive(false);
DPad_GO.SetActive(false);
JoystickDefault_GO.SetActive(false);
break;
case 1:
mode = DecoupledInputMode.TouchDPad;
AssetJoystick.SetActive(false);
DPad_GO.SetActive(true);
JoystickDefault_GO.SetActive(false);
break;
case 2:
mode = DecoupledInputMode.Joystick_fixed;
AssetJoystick.SetActive(true);
DPad_GO.SetActive(false);
joystick.SetMode(JoystickType.Fixed);
JoystickDefault_GO.SetActive(false);
break;
case 3:
mode = DecoupledInputMode.Joystick_floating;
AssetJoystick.SetActive(true);
DPad_GO.SetActive(false);
joystick.SetMode(JoystickType.Floating);
JoystickDefault_GO.SetActive(false);
break;
case 4:
mode = DecoupledInputMode.Joystick_dynamic;
AssetJoystick.SetActive(true);
DPad_GO.SetActive(false);
joystick.SetMode(JoystickType.Dynamic);
JoystickDefault_GO.SetActive(false);
break;
case 5:
mode = DecoupledInputMode.Joystick_default;
AssetJoystick.SetActive(false);
DPad_GO.SetActive(false);
JoystickDefault_GO.SetActive(true);
joystick_default.mode = SegmentedJoystickMode.Joystick_ForwardHelp;
break;
case 6:
mode = DecoupledInputMode.Joystick_default;
AssetJoystick.SetActive(false);
DPad_GO.SetActive(false);
JoystickDefault_GO.SetActive(true);
joystick_default.mode = SegmentedJoystickMode.DPad4;
break;
case 7:
mode = DecoupledInputMode.Joystick_default;
AssetJoystick.SetActive(false);
DPad_GO.SetActive(false);
JoystickDefault_GO.SetActive(true);
joystick_default.mode = SegmentedJoystickMode.DPad8;
break;
default:
break;
}
}
private void refreshInputVector()
{
touchInputVector = new Vector2(0, 0);
switch (mode)
{
case DecoupledInputMode.Keyboard:
touchInputVector.x = Input.GetAxis("Horizontal");
touchInputVector.y = Input.GetAxis("Vertical");
break;
case DecoupledInputMode.TouchDPad:
touchInputVector = dpad.Direction;
break;
case DecoupledInputMode.Joystick_fixed:
case DecoupledInputMode.Joystick_floating:
case DecoupledInputMode.Joystick_dynamic:
touchInputVector = joystick.Direction;
break;
case DecoupledInputMode.Joystick_default:
touchInputVector = joystick_default.Direction;
break;
default:
break;
}
//if (L.buttonPressed && R.buttonPressed)
//{
// touchInputVector.x = 0;
//}
//else
//{
// if (L.buttonPressed)
// {
// touchInputVector.x = -1;
// }
// if (R.buttonPressed)
// {
// touchInputVector.x = 1;
// }
//}
//if (V.buttonPressed && B.buttonPressed)
//{
// touchInputVector.y = 0;
//}
//else
//{
// if (V.buttonPressed)
// {
// touchInputVector.y = 1;
// }
// if (B.buttonPressed)
// {
// touchInputVector.y = -1;
// }
//}
}
public Vector2 GetInputVector()
{
//refreshInputVector();
return touchInputVector;
}
public float GetAxis(string a_axis)
{
//refreshInputVector(); // TODO woanders aufrufen - eigentlich schlecht wenn immer bei Get refresht wird
switch (a_axis)
{
case "Horizontal":
return touchInputVector.x;
case "Vertical":
return touchInputVector.y;
default:
break;
}
return 0f;
}
}
|
using System;
using Avalonia.Media;
namespace Avalonia.Controls
{
/// <summary>
/// Viewbox is used to scale single child.
/// </summary>
/// <seealso cref="Avalonia.Controls.Decorator" />
public class Viewbox : Decorator
{
/// <summary>
/// The stretch property
/// </summary>
public static readonly AvaloniaProperty<Stretch> StretchProperty =
AvaloniaProperty.RegisterDirect<Viewbox, Stretch>(nameof(Stretch),
v => v.Stretch, (c, v) => c.Stretch = v, Stretch.Uniform);
private Stretch _stretch = Stretch.Uniform;
/// <summary>
/// Gets or sets the stretch mode,
/// which determines how child fits into the available space.
/// </summary>
/// <value>
/// The stretch.
/// </value>
public Stretch Stretch
{
get => _stretch;
set => SetAndRaise(StretchProperty, ref _stretch, value);
}
static Viewbox()
{
ClipToBoundsProperty.OverrideDefaultValue<Viewbox>(true);
AffectsMeasure<Viewbox>(StretchProperty);
}
protected override Size MeasureOverride(Size availableSize)
{
var child = Child;
if (child != null)
{
child.Measure(Size.Infinity);
var childSize = child.DesiredSize;
var scale = GetScale(availableSize, childSize, Stretch);
return (childSize * scale).Constrain(availableSize);
}
return new Size();
}
protected override Size ArrangeOverride(Size finalSize)
{
var child = Child;
if (child != null)
{
var childSize = child.DesiredSize;
var scale = GetScale(finalSize, childSize, Stretch);
var scaleTransform = child.RenderTransform as ScaleTransform;
if (scaleTransform == null)
{
child.RenderTransform = scaleTransform = new ScaleTransform(scale.X, scale.Y);
child.RenderTransformOrigin = RelativePoint.TopLeft;
}
scaleTransform.ScaleX = scale.X;
scaleTransform.ScaleY = scale.Y;
child.Arrange(new Rect(childSize));
return childSize * scale;
}
return new Size();
}
private static Vector GetScale(Size availableSize, Size childSize, Stretch stretch)
{
double scaleX = 1.0;
double scaleY = 1.0;
bool validWidth = !double.IsPositiveInfinity(availableSize.Width);
bool validHeight = !double.IsPositiveInfinity(availableSize.Height);
if (stretch != Stretch.None && (validWidth || validHeight))
{
scaleX = childSize.Width <= 0.0 ? 0.0 : availableSize.Width / childSize.Width;
scaleY = childSize.Height <= 0.0 ? 0.0 : availableSize.Height / childSize.Height;
if (!validWidth)
{
scaleX = scaleY;
}
else if (!validHeight)
{
scaleY = scaleX;
}
else
{
switch (stretch)
{
case Stretch.Uniform:
scaleX = scaleY = Math.Min(scaleX, scaleY);
break;
case Stretch.UniformToFill:
scaleX = scaleY = Math.Max(scaleX, scaleY);
break;
}
}
}
return new Vector(scaleX, scaleY);
}
}
}
|
using NUnit.Framework;
namespace ValveKeyValue.Test
{
class InvalidSyntaxTestCase
{
[TestCase("empty")]
[TestCase("quoteonly")]
[TestCase("partialname")]
[TestCase("nameonly")]
[TestCase("partial_nodata")]
[TestCase("partial_opening_key")]
[TestCase("partial_partialkey")]
[TestCase("partial_novalue")]
[TestCase("partial_opening_value")]
[TestCase("partial_partialvalue")]
[TestCase("partial_noclose")]
[TestCase("invalid_zerobracerepeated")]
public void InvalidTextSyntaxThrowsKeyValueException(string resourceName)
{
using var stream = TestDataHelper.OpenResource("Text." + resourceName + ".vdf");
Assert.That(
() => KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize(stream),
Throws.Exception.TypeOf<KeyValueException>());
}
}
}
|
using System.Linq;
using System.Text.RegularExpressions;
namespace Octopus.CoreParsers.Hcl
{
/// <summary>
/// Represents a list
/// </summary>
public class HclListElement : HclElement
{
public override string Type => ListType;
public override string Value => ToString(-1);
public override string ToString(bool naked, int indent)
{
var indentString = GetIndent(indent);
return indentString + PrintArray(indent);
}
protected string PrintArray(int indent)
{
var indentString = GetIndent(indent);
var nextIndentString = GetIndent(indent + 1);
var lineBreak = indent == -1 ? string.Empty : "\n";
var startArray = "[" + lineBreak +
Children?.Aggregate("", (total, child) =>
{
// Comments appear without a comma at the end
var suffix = child.Type != CommentType ? ", " : "";
return total + nextIndentString + child + suffix + lineBreak;
});
// Retain the comma at the end (if one exists) if the last element is a comment
if (Children?.LastOrDefault()?.Type != CommentType)
startArray = new Regex(",$").Replace(startArray.TrimEnd(), "");
return startArray + lineBreak + indentString + "]";
}
}
} |
namespace DllImportX.Tests
{
public interface DllImportXNotImplementedMembersInterface
{
void NotImplementedVoid();
int NotImplementedPropertyInt { get; set; }
}
}
|
using System;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Instances = R5T.T0045.X001.Instances;
namespace System
{
public static class ClassDeclarationSyntaxExtensions
{
public static ClassDeclarationSyntax AddOmittedPrivateStaticVoidMethod(this ClassDeclarationSyntax @class,
string methodName,
ModifierSynchronous<MethodDeclarationSyntax> modifier = default)
{
var method = Instances.MethodGenerator.GetOmittedPrivateStaticVoidMethod(methodName);
var output = @class.AddMethod(method, modifier);
return output;
}
}
}
|
/*
* Copyright 2002-2020 Raphael Mudge
* Copyright 2020 Sebastian Ritter
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using java = biz.ritter.javapi;
namespace sleep.parser{
public class ParserUtilities
{
public static Token combineTokens(Token a, Token b)
{
return new Token(a.toString() + b.toString(), a.getHint());
}
public static Token makeToken(String token, Token a)
{
return new Token(token, a.getHint());
}
public static Token[] get(Token[] t, int a, int b)
{
Token[] rv = new Token[b - a];
for (int x = 0; x < rv.Length; x++)
{
rv[x] = t[a + x];
}
return rv;
}
public static Token join(Token [] temp)
{
return join(temp, " ");
}
public static Token join(Token [] temp, String with)
{
java.lang.StringBuffer rv = new java.lang.StringBuffer();
for (int x = 0; x < temp.Length; x++)
{
if ((x > 0 && temp[x].getHint() == temp[x-1].getTopHint()) || x == 0)
{
rv.append(with);
}
else
{
int difference = temp[x].getHint() - temp[x-1].getTopHint();
for (int z = 0; z < difference; z++)
{
rv.append("\n");
}
}
rv.append(temp[x].toString());
}
return new Token(rv.toString(), temp[0].getHint());
}
public static Token extract (Token temp)
{
return new Token(extract(temp.toString()), temp.getHint());
}
public static String extract (String temp)
{
return temp.substring(1, temp.length() - 1);
}
/** breaks down the token into sub tokens that are one "term" wide, in the case of blocks separated by ; */
public static TokenList groupByBlockTerm(Parser parser, Token smokin)
{
StringIterator iterator = new StringIterator(smokin.toString(), smokin.getHint());
TokenList tokens = LexicalAnalyzer.GroupBlockTokens(parser, iterator);
return groupByTerm(tokens);
}
/** breaks down the token into sub tokens that are one "term" wide, in the case of messages separated by : */
public static TokenList groupByMessageTerm(Parser parser, Token smokin)
{
StringIterator iterator = new StringIterator(smokin.toString(), smokin.getHint());
TokenList tokens = LexicalAnalyzer.GroupExpressionIndexTokens(parser, iterator);
return groupByTerm(tokens);
}
/** breaks down the token into sub tokens that are one "term" wide, a termi in the case of parameters it uses , */
public static TokenList groupByParameterTerm(Parser parser, Token smokin)
{
StringIterator iterator = new StringIterator(smokin.toString(), smokin.getHint());
TokenList tokens = LexicalAnalyzer.GroupParameterTokens(parser, iterator);
return groupByTerm(tokens);
}
private static TokenList groupByTerm(TokenList n)
{
TokenList rv = new TokenList();
if (n.getList().size() == 0)
{
return rv;
}
java.lang.StringBuffer current = new java.lang.StringBuffer();
int hint = -1;
java.util.Iterator<Object> i = n.getList().iterator();
while (i.hasNext())
{
Token temp = (Token)i.next();
hint = hint == -1 ? temp.getHint() : hint;
if (temp.toString().equals("EOT"))
{
rv.add(new Token(current.toString(), hint));
current = new java.lang.StringBuffer();
hint = -1; /* reset hint to prevent line # skew */
}
else
{
if (current.length() > 0)
current.append(" ");
current.append(temp.toString());
}
}
if (current.length() > 0)
rv.add(new Token(current.toString(), hint));
return rv;
}
}
} |
using System;
namespace CoreEscuela.Entidades
{
public class ObjetoEscuela
{
public string Id { get; set; }
public string Nombre { get; set; }
public ObjetoEscuela()
{
Id = Guid.NewGuid().ToString();
}
public ObjetoEscuela(string nombre)
{
Id = Guid.NewGuid().ToString();
Nombre = nombre;
}
}
}
|
using Autofac;
using PVScan.Core;
using PVScan.Core.Services.Interfaces;
using PVScan.Mobile.Services;
using PVScan.Core.Services.Interfaces;
using PVScan.Mobile.Views;
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using Xamarin.Forms.Svg;
using Xamarin.Forms.Xaml;
using PVScan.Mobile.Services.Interfaces;
namespace PVScan.Mobile
{
public partial class App : Xamarin.Forms.Application
{
public App()
{
DataAccess.Init(System.IO.Path.Combine(FileSystem.AppDataDirectory, "PVScan.db3"));
InitializeTheme();
InitializeComponent();
SvgImageSource.RegisterAssembly();
var mainPage = Resolver.Resolve<MainPage>();
InitializePopupService(mainPage);
var navigationPage = new Xamarin.Forms.NavigationPage(mainPage);
navigationPage.On<iOS>().SetHideNavigationBarSeparator(false);
navigationPage.SetOnAppTheme(Xamarin.Forms.NavigationPage.BarTextColorProperty, Color.Black, Color.White);
MainPage = navigationPage;
}
private async void InitializeTheme()
{
using var scope = Resolver.Container.BeginLifetimeScope();
var kvp = scope.Resolve<IPersistentKVP>();
string themeSelected = await kvp.Get(StorageKeys.Theme, null);
if (themeSelected == null)
{
// User hasn't changed the app theme yet, use system theme.
UserAppTheme = RequestedTheme;
}
else
{
UserAppTheme = themeSelected == "Light" ? OSAppTheme.Light : OSAppTheme.Dark;
}
RequestedThemeChanged += (s, e) =>
{
// Respond to user device theme change if option is set?
};
}
private void InitializePopupService(MainPage mainPage)
{
var popupService = (Resolver.Resolve<IPopupMessageService>() as PopupMessageService);
popupService.Initialize(mainPage.PopupMessageBox, mainPage.PopupMessageLabel);
}
protected override async void OnStart()
{
using var scope = Resolver.Container.BeginLifetimeScope();
var identity = scope.Resolve<IIdentityService>();
var barcodeHub = scope.Resolve<IAPIBarcodeHub>();
var userInfoHub = scope.Resolve<IAPIUserInfoHub>();
await identity.Initialize();
if (identity.AccessToken != null)
{
await barcodeHub.Connect();
await userInfoHub.Connect();
}
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
|
using Autofac;
using DDit.Core.Data.IRepositories;
using DDit.Core.Data.Repositories;
using DDitApplicationFrame.Service;
using DDitApplicationFrame.Service.Imp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DDitApplicationFrame.Common
{
public class RegisterModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<LoginService>().As<ILoginService>().PropertiesAutowired();
builder.RegisterType<UserService>().As<IUserService>().PropertiesAutowired();
}
}
} |
// Copyright (c) Tocsoft and contributors.
// Licensed under the Apache License, Version 2.0.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using TestHelper;
using Xunit;
namespace Tocsoft.DateTimeAbstractions.Analyzer.Test
{
public class DateTimeAnalyzer : CodeFixVerifier
{
[Fact]
public void TestMethod1()
{
string test = string.Empty;
this.VerifyCSharpDiagnostic(test);
}
[Fact]
public void TestMethodAnalyzerExpected()
{
string test = @"
using System;
namespace Tocsoft.DateTimeAbstractions
{
class TypeName
{
public TypeName(){
DateTime time = DateTime.Now;
}
}
public static class Clock { public static DateTime Now { get; set; } }
}";
DiagnosticResult expected = new DiagnosticResult
{
Id = DateTimeUsageAnalyzer.DiagnosticId,
Message = "Do not call DateTime.Now as they are not testable, use an abstraction instead.",
Severity = DiagnosticSeverity.Warning,
Locations =
new[]
{
new DiagnosticResultLocation("Test0.cs", 8, 33)
}
};
this.VerifyCSharpDiagnostic(test, expected);
}
[Fact]
public void TestMethodAnalyzerExpectedForSystemDatetime()
{
string test = @"
namespace Tocsoft.DateTimeAbstractions
{
class TypeName
{
public TypeName(){
System.DateTime time = System.DateTime.Now;
}
}
public static class Clock { public static DateTime Now { get; set; } }
}";
DiagnosticResult expected = new DiagnosticResult
{
Id = DateTimeUsageAnalyzer.DiagnosticId,
Message = "Do not call DateTime.Now as they are not testable, use an abstraction instead.",
Severity = DiagnosticSeverity.Warning,
Locations =
new[]
{
new DiagnosticResultLocation("Test0.cs", 7, 40, 19)
}
};
this.VerifyCSharpDiagnostic(test, expected);
}
[Fact]
public void CodeFixReducesProperly()
{
string test = @"
using System;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = DateTime.Now;
}
}
}";
this.AdditionalCodeFiles = new[]
{
@"
using System;
namespace Tocsoft.DateTimeAbstractions
{
public static class Clock { public static DateTime Now { get; set; } }
}"
};
string fixtest = @"
using System;
using Tocsoft.DateTimeAbstractions;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = Clock.Now;
}
}
}";
this.VerifyCSharpFix(test, fixtest);
}
[Fact]
public void IncompleteCodeCanBeFixed()
{
string test = @"
using System;
namespace TestApplication
{
class TypeName
{
DateTime prop;
public TypeName()
{
var r = DateTime.Now
}
}
}";
this.AdditionalCodeFiles = new[]
{
@"
using System;
namespace Tocsoft.DateTimeAbstractions
{
public static class Clock { public static DateTime Now { get; set; } }
}"
};
string fixtest = @"
using System;
using Tocsoft.DateTimeAbstractions;
namespace TestApplication
{
class TypeName
{
DateTime prop;
public TypeName()
{
var r = Clock.Now
}
}
}";
this.VerifyCSharpFix(test, fixtest);
}
[Fact]
public void DateTimeUtcNowMappsToClockUtcNow()
{
string test = @"
using Tocsoft.DateTimeAbstractions;
using System;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = DateTime.UtcNow;
}
}
}";
this.AdditionalCodeFiles = new[]
{
@"
using System;
namespace Tocsoft.DateTimeAbstractions
{
public static class Clock { public static DateTime UtcNow { get; set; } }
}"
};
string fixtest = @"
using Tocsoft.DateTimeAbstractions;
using System;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = Clock.UtcNow;
}
}
}";
this.VerifyCSharpFix(test, fixtest);
}
[Fact]
public void DateTimeUtcNowMappsToClockUtcNowDotHour()
{
string test = @"
using System;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = DateTime.UtcNow.Hour;
}
}
}";
this.AdditionalCodeFiles = new[]
{
@"
using System;
namespace Tocsoft.DateTimeAbstractions
{
public static class Clock { public static DateTime UtcNow { get; set; } }
}"
};
string fixtest = @"
using System;
using Tocsoft.DateTimeAbstractions;
namespace TestApplication
{
class TypeName
{
public TypeName(){
DateTime time = Clock.UtcNow.Hour;
}
}
}";
this.VerifyCSharpFix(test, fixtest);
}
[Fact]
public void SystemDateTimeUtcNowMappsToClockUtcNow()
{
string test = @"
namespace TestApplication
{
class TypeName
{
public TypeName(){
System.DateTime time = System.DateTime.UtcNow;
}
}
}";
this.AdditionalCodeFiles = new[]
{
@"
using System;
namespace Tocsoft.DateTimeAbstractions
{
public static class Clock { public static DateTime UtcNow { get; set; } }
}"
};
string fixtest = @"using Tocsoft.DateTimeAbstractions;
namespace TestApplication
{
class TypeName
{
public TypeName(){
System.DateTime time = Clock.UtcNow;
}
}
}";
this.VerifyCSharpFix(test, fixtest);
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new DateTimeUsageCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DateTimeUsageAnalyzer();
}
}
}
|
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum)]
public class TypeAttribute : Attribute
{
private string type;
private string category;
private string description;
public TypeAttribute(string type, string category, string description)
{
this.Type = type;
this.Category = category;
this.Description = description;
}
public string Type
{
get { return this.type; }
private set { this.type = value; }
}
public string Category
{
get { return this.category; }
private set { this.category = value; }
}
public string Description
{
get { return this.description; }
private set { this.description = value; }
}
public override string ToString()
{
return $"Type = {this.Type}, Description = {this.Description}";
}
} |
using System;
using System.Collections.Generic;
namespace CupsPuzzleSolver
{
public class NaiveSolver
{
// Store collection, foreach state: moves to reach, and the previous state
private readonly Dictionary<Cups, (int moves, Cups? prev)> _explored;
// List of states yet to be explored, the steps to get there, and the state we reached them from
private readonly List<(Cups state, int moves, Cups? prev)> _toExplore;
private (int, Cups?) _bestSolution;
public NaiveSolver(Cups start)
{
start.CheckValid();
_toExplore = new List<(Cups, int, Cups?)> {(start, 0, null)};
_explored = new Dictionary<Cups, (int, Cups?)>();
}
private bool Explore(Cups to, Cups? from)
{
if (from == null)
{
_explored.Add(to, (0, null));
return true;
}
var (fromCost, _) = _explored[from];
if (_explored.ContainsKey(to))
{
var (currCost, _) = _explored[to];
if (fromCost + 1 < currCost)
{
_explored[to] = (fromCost + 1, from);
return true;
}
}
else
{
_explored.Add(to, (fromCost + 1, from));
return true;
}
return false;
}
public bool Step()
{
// Take the next state to be explored
if (_toExplore.Count == 0)
{
Console.WriteLine("Fully explored tree");
return false;
}
var (currState, currMoves, prevState) = _toExplore[0];
_toExplore.RemoveAt(0);
// Console.WriteLine("==============================================");
// Console.WriteLine("Checking state:");
// currState.PrintState();
if (_explored.TryGetValue(currState, out (int, Cups?) foundEntry))
{
var (foundMoves, _) = foundEntry;
if (currMoves >= foundMoves)
// Console.WriteLine("State already encountered");
return true;
_explored[currState] = (currMoves, prevState);
}
else
{
_explored.Add(currState, (currMoves, prevState));
Console.WriteLine(_explored.Count + " states have been explored");
}
if (currState.Solved())
{
var (bestMoveCount, bestSolution) = _bestSolution;
if (bestSolution == null || currMoves < bestMoveCount)
{
Console.WriteLine("Found a solution with " + currMoves + " moves.");
_bestSolution = (currMoves, currState);
}
}
else
{
// Enumerate possible moves from this state, and add them all to the to-explore list
var moveList = currState.GetPossibleMoves();
// Console.WriteLine(moveList.Count + " possible moves");
foreach (var move in moveList)
{
// Console.WriteLine("Pouring cup " + from + " into cup " + to + ", resulting in:");
var nextState = (Cups) currState.Clone();
nextState.Move(move);
nextState.CheckValid();
// nextState.PrintState();
_toExplore.Add((nextState, currMoves + 1, currState));
}
}
return true;
}
public void PrintBestSolution()
{
var (_, solvedState) = _bestSolution;
if (solvedState == null)
{
Console.WriteLine("No solution found.");
return;
}
var currState = solvedState;
List<Cups> solution = new();
while (true)
{
solution.Insert(0, currState);
var (moves, prevState) = _explored[currState];
if (prevState == null) break;
currState = prevState;
}
Console.WriteLine(solution.Count - 1 + " moves in solution");
foreach (var state in solution) state.PrintState();
}
}
} |
using A19.Messaging.Common;
namespace Mrh.Messaging.Json
{
/// <summary>
/// The json body encoder.
/// </summary>
public class JsonBodyEncoder : IBodyEncoder<string>
{
public T Decode<T>(string body)
{
return JsonHelper.Decode<T>(body);
}
public string Encode<T>(T value)
{
return JsonHelper.Encode(value);
}
}
} |
namespace Firebase.Sample {
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using Firebase.TestLab;
public class AutomatedTestRunner {
// Function used to log the results of the tests. Defaults to UnityEngine.Debug.Log().
public Action<string> LogFunc { get; set; }
// The list of tests to run through.
private Func<Task>[] tests = null;
// The index of the currently running test.
private int currentTestIndex = -1;
// Name and index of the current running test function.
public string CurrentTestDescription { get; private set; }
// The Task that represents the currently running test.
public Task CurrentTestResult { get; private set; }
// Have all the tests been run and finished.
public bool Finished { get; private set; }
private bool startedExecution = false;
// Custom names to use for the tests, instead of the function names.
private string[] customTestNames = null;
private TestLabManager testLabManager;
// Used to output summary of the test run.
private int passedTestsCount = 0;
private int failedTestsCount = 0;
// Descriptions of failing tests.
private List<string> failingTestDescriptions = new List<string>();
// Used to measure the time currently elapsed by the test, to see if the test timed out.
private float startTime = 0.0f;
// If a test takes longer to run than the timeout, it will be skipped and considered failed.
// The unit is seconds, used by Unity.
public float TestTimeoutSeconds { get; set; }
// The time in seconds since the testapp started when all tests were finished. Used to delay
// notifying the test lab manager to shut down the app, to provide time for results to appear
// in the testapp. Otherwise, video recording cuts off early.
private float endTime;
private AutomatedTestRunner(Func<Task>[] testsToRun, TestLabManager testLabManager,
Action<string> logFunc = null, string[] testNames = null) {
LogFunc = logFunc != null ? logFunc : UnityEngine.Debug.Log;
tests = testsToRun;
customTestNames = testNames;
Finished = false;
TestTimeoutSeconds = 60.0f;
this.testLabManager = testLabManager;
}
// Static factory method for the test runner. Creates an instance and sets up
// the environment for testing.
public static AutomatedTestRunner CreateTestRunner(
Func<Task>[] testsToRun, Action<string> logFunc = null, string[] testNames = null) {
TestLabManager testLabManager = InitializeTestLabManager();
return new AutomatedTestRunner(testsToRun, testLabManager, logFunc, testNames);
}
/// <summary>
/// Configures a TestLabManager object to be used with Firebase Test Lab. Required even
/// if not using Firebase Test Lab.
/// </summary>
private static TestLabManager InitializeTestLabManager() {
TestLabManager testLabManager = TestLabManager.Instantiate();
Application.logMessageReceived += (string condition, string stackTrace, LogType type) => {
testLabManager.LogToResults(FormatLog(condition, stackTrace, type));
};
return testLabManager;
}
private static string FormatLog(string condition, string stackTrace, LogType type) {
return string.Format("[{0}]({1}): {2}\n{3}\n", DateTime.Now, type, condition, stackTrace);
}
// Is the current test still running.
public bool IsRunningTest {
get {
return !(CurrentTestResult == null ||
CurrentTestResult.IsCompleted ||
CurrentTestResult.IsCanceled ||
CurrentTestResult.IsFaulted);
}
}
// Runs through the tests, checking if the current one is done.
// If so, logs the relevant information, and proceeds to the next test.
public void Update() {
if (tests == null) {
return;
}
if (!startedExecution) {
LogFunc("Starting executing tests.");
startedExecution = true;
}
if (currentTestIndex >= tests.Length) {
if (Finished) {
// No tests left to run.
// Wait 5 seconds before notifying test lab manager so video can capture end of test.
if (Time.time > endTime + 5f) {
testLabManager.NotifyHarnessTestIsComplete();
}
return;
} else {
// All tests are finished!
LogFunc("All tests finished");
LogFunc(String.Format("PASS: {0}, FAIL: {1}\n\n" +
"{2}{3}", passedTestsCount, failedTestsCount,
failedTestsCount > 0 ? "Failing Tests:\n" : "",
String.Join("\n", failingTestDescriptions.ToArray())));
failingTestDescriptions = new List<string>();
Finished = true;
endTime = Time.time;
}
}
// If the current test is done, start up the next one.
if (!IsRunningTest) {
// Log the results of the test that has finished.
if (CurrentTestResult != null) {
if (CurrentTestResult.IsFaulted) {
LogFunc(String.Format("Test {0} failed!\n\n" +
"Exception message: {1}",
CurrentTestDescription,
CurrentTestResult.Exception.Flatten().ToString()));
++failedTestsCount;
failingTestDescriptions.Add(CurrentTestDescription);
} else {
// If the task was not faulted, assume it succeeded.
LogFunc("Test " + CurrentTestDescription + " passed.");
++passedTestsCount;
}
} else if (currentTestIndex >= 0 && currentTestIndex < tests.Length &&
tests[currentTestIndex] != null) {
LogFunc(String.Format("Test {0} failed.\n\n" +
"No task was returned by the test.",
CurrentTestDescription));
++failedTestsCount;
failingTestDescriptions.Add(CurrentTestDescription);
}
StartNextTest();
} else {
// Watch out for timeout
float elapsedTime = Time.time - startTime;
if (elapsedTime > TestTimeoutSeconds) {
LogFunc("Test " + CurrentTestDescription + " timed out, elapsed time: " + elapsedTime);
++failedTestsCount;
failingTestDescriptions.Add(CurrentTestDescription);
StartNextTest();
}
}
}
void StartNextTest() {
CurrentTestResult = null;
++currentTestIndex;
if (currentTestIndex < tests.Length && tests[currentTestIndex] != null) {
// Start running the next test.
var testFunc = tests[currentTestIndex];
string testName = testFunc.Method.Name;
if (customTestNames != null && currentTestIndex < customTestNames.Length) {
testName = customTestNames[currentTestIndex];
}
CurrentTestDescription = String.Format("{0} ({1}/{2})", testName,
currentTestIndex + 1, tests.Length);
try {
LogFunc("Test " + CurrentTestDescription + " started...");
CurrentTestResult = testFunc();
} catch (Exception e) {
var tcs = new TaskCompletionSource<bool>();
tcs.SetException(e);
CurrentTestResult = tcs.Task;
}
startTime = Time.time;
}
}
}
// This is a class for forcing code to run on the main thread.
// You can give it arbitrary code via the RunOnMainThread method,
// and it will execute that code during the Update() function. (Which
// Unity always runs on the main thread.)
// The returned Task object also contains a helpful function
// to block execution until the job is completed. (WaitUntilComplete)
public class MainThreadDispatcher : MonoBehaviour {
// Queue of all the pending jobs that will be executed.
System.Collections.Queue jobQueue =
System.Collections.Queue.Synchronized(new System.Collections.Queue());
// Update is called once per frame. Every frame we grab any available
// jobs that are pending and execute them. Since unity always calls
// update on the main thread, this guarantees that our jobs will also
// execute on the main thread as well.
void Update() {
while (jobQueue.Count > 0) {
(jobQueue.Dequeue() as Action)();
}
}
// Specify code to execute on the main thread. Returns a Task object
// that can be used to track the progress of the job.
public Task RunOnMainThread(System.Action jobFunction) {
TaskCompletionSource<bool> completionSource = new TaskCompletionSource<bool>();
jobQueue.Enqueue(new Action(() => {
try {
jobFunction();
} catch (Exception e) {
completionSource.SetException(e);
}
completionSource.SetResult(true);
}));
return completionSource.Task;
}
}
}
|
using Drp.Data.Definitions;
using System;
using System.Collections.Generic;
namespace Drp.Data.Entities
{
public partial class SystemRole : IHaveIdentifier
{
public SystemRole()
{
#region Generated Constructor
#endregion
}
#region Generated Properties
public long Id { get; set; }
public DateTime DataChangeLastTime { get; set; }
public bool IsActive { get; set; }
public string MenuRights { get; set; }
public string ActionList { get; set; }
public string CreateUser { get; set; }
public long CreateRoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
#endregion
#region Generated Relationships
#endregion
}
}
|
using MFlow.Core.Validation.Validators.Generic;
namespace MFlow.Core.Internal.Validators.Generic
{
/// <summary>
/// Required Validator
/// </summary>
class RequiredValidator<T> : IRequiredValidator<T>
{
public bool Validate (T input)
{
return input != null && !string.IsNullOrEmpty (input.ToString ()) && !input.Equals (default(T));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Barembo.Models
{
/// <summary>
/// An EntryReference holds information about an Entry, where it belongs to and where it can be found
/// </summary>
public struct EntryReference : IEquatable<EntryReference>
{
/// <summary>
/// Too BookReference to the Book this Entry belongs to
/// </summary>
public BookReference BookReference { get; set; }
/// <summary>
/// The Key of the Entry in the store
/// </summary>
public string EntryKey { get; set; }
/// <summary>
/// The Id of the Entry referenced
/// </summary>
public string EntryId { get; set; }
/// <summary>
/// The creation date of that entry - to be used to sort entries
/// </summary>
public DateTime CreationDate { get; set; }
public bool Equals(EntryReference other)
{
return BookReference.BookId == other.BookReference.BookId && EntryId == other.EntryId;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using BuildItEasy.Validation;
namespace BuildItEasy
{
public abstract partial class Builder<TResult, TSelf> : IBuilder<TResult>
where TSelf : Builder<TResult, TSelf>
{
public static implicit operator ValueProvider<TResult>(Builder<TResult, TSelf> builder)
=> new BuilderValueProvider<TResult>(builder);
private readonly ICollection<IValidator<TResult>> _validators;
private readonly ICollection<IResettable> _resettables;
protected Builder()
{
_validators = new List<IValidator<TResult>>();
_resettables = new List<IResettable>();
}
public TResult Build()
{
foreach (var resettable in _resettables)
resettable.Reset();
var result = BuildInternal();
var validationResult = ValidationResult.Merge(_validators.Select(v => v.Validate(result)));
validationResult.AssertValid();
return result;
}
protected abstract TResult BuildInternal();
public TSelf Customize(Customizer<TSelf> customizer = null)
{
customizer?.Invoke((TSelf) this);
return (TSelf) this;
}
}
}
|
// <copyright file="TransformationContextTest.cs" company="Oleg Sych">
// Copyright © Oleg Sych. All Rights Reserved.
// </copyright>
namespace T4Toolbox.Tests
{
using System;
using System.CodeDom.Compiler;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TextTemplating;
/// <summary>
/// This is a test class for <see cref="TransformationContext"/> and is intended
/// to contain all of its unit tests.
/// </summary>
[TestClass]
public class TransformationContextTest
{
private const string TestText = "Test Text";
private const string TestFile = "Test.txt";
#region Cleanup
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "value", Justification = "C# can't invoke property getter without a variable.")]
[TestMethod, ExpectedException(typeof(TransformationException))]
public void CleanupRemovesCurrent()
{
using (var transformation = new FakeTransformation())
{
TransformationContext.Initialize(transformation, transformation.GenerationEnvironment);
TransformationContext.Cleanup();
var value = TransformationContext.Current;
}
}
[TestMethod]
public void CleanupDisposesCurrent()
{
using (var transformation = new FakeTransformation())
{
bool disposed = false;
TransformationContext.Initialize(transformation, transformation.GenerationEnvironment);
try
{
TransformationContext.Current.Disposed += delegate { disposed = true; };
}
finally
{
TransformationContext.Cleanup();
}
Assert.IsTrue(disposed);
}
}
[TestMethod]
public void CleanupDoesNotThrowExceptionsWhenContextIsNullBecauseTheyWouldObscureInitializationExceptions()
{
TransformationContext.Cleanup();
}
#endregion
#region Constructor
/// <summary>
/// Mimics code generated by T4 based on <#@ parameter type="System.String" name="StringParameter" #> directive.
/// </summary>
private class FakeTransformationWithStringParameter : FakeTransformation
{
private readonly string stringParameter = string.Empty;
private string StringParameter
{
get { return this.stringParameter; }
}
}
[TestMethod]
public void ConstructorAddsMetadataValuesForMatchingParametersToTransformationSession()
{
using (var transformation = new FakeTransformationWithStringParameter())
{
const string ExpectedValue = "TestValue";
const string ParameterName = "StringParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? ExpectedValue : null;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.AreEqual(ExpectedValue, transformation.Session[ParameterName]);
}
}
}
[TestMethod]
public void ConstructorDoesNotOverrideParameterValuesSuppliedViaTransformationSession()
{
using (var transformation = new FakeTransformationWithStringParameter())
{
const string ExpectedValue = "SessionValue";
const string ParameterName = "StringParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? "MetadataValue" : null;
transformation.Session[ParameterName] = ExpectedValue;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.AreEqual(ExpectedValue, transformation.Session[ParameterName]);
}
}
}
[TestMethod]
public void ConstructorDoesNotOverrideParameterValuesSuppliedViaCallContext()
{
using (var transformation = new FakeTransformationWithStringParameter())
{
const string ParameterName = "StringParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? "MetadataValue" : null;
CallContext.LogicalSetData(ParameterName, "CallContextValue");
try
{
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsFalse(transformation.Session.ContainsKey(ParameterName));
}
}
finally
{
CallContext.FreeNamedDataSlot(ParameterName);
}
}
}
[TestMethod]
public void ConstructorDoesNotModifyTransformationSessionWhenMetadataValueIsNotSpecified()
{
using (var transformation = new FakeTransformationWithStringParameter())
{
const string ParameterName = "StringParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => string.Empty;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsFalse(transformation.Session.ContainsKey(ParameterName));
}
}
}
[TestMethod]
public void ConstructorReportsErrorWhenParameterCannotBeInitializedBecauseSessionIsNull()
{
using (var transformation = new FakeTransformationWithStringParameter())
{
const string ExpectedValue = "TestValue";
const string ParameterName = "StringParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? ExpectedValue : null;
CompilerErrorCollection loggedErrors = null;
transformation.Host.LoggedErrors = errors => loggedErrors = errors;
transformation.Session = null;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsNotNull(loggedErrors);
StringAssert.Contains(loggedErrors.Cast<CompilerError>().Single().ErrorText, ParameterName);
}
}
}
/// <summary>
/// Mimics code generated by T4 based on <#@ parameter type="System.Int32" name="IntParameter" #> directive.
/// </summary>
private class FakeTransformationWithIntParameter : FakeTransformation
{
private readonly int intParameter = 0;
private int IntParameter
{
get { return this.intParameter; }
}
}
[TestMethod]
public void ConstructorConvertsMetadataValuesToParameterTypes()
{
using (var transformation = new FakeTransformationWithIntParameter())
{
const int ExpectedValue = 42;
const string ParameterName = "IntParameter";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? ExpectedValue.ToString(CultureInfo.InvariantCulture) : null;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.AreEqual(ExpectedValue, transformation.Session[ParameterName]);
}
}
}
[TestMethod]
public void ConstructorReportsErrorWhenMetadataValueCannotBeConvertedToParameterType()
{
using (var transformation = new FakeTransformation())
{
CompilerErrorCollection actualErrors = null;
const string ParameterName = "Host";
const string MetadataValue = "InvalidValue";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => metadataName == ParameterName ? MetadataValue : null;
transformation.Host.LoggedErrors = errors => actualErrors = errors;
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsNotNull(actualErrors);
Assert.AreEqual(1, actualErrors.Count);
CompilerError error = actualErrors[0];
Assert.IsFalse(error.IsWarning);
StringAssert.Contains(error.ErrorText, ParameterName);
StringAssert.Contains(error.ErrorText, MetadataValue);
StringAssert.Contains(error.ErrorText, transformation.Host.GetType().Name);
}
}
}
#endregion
#region Current
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "value", Justification = "C# can't invoke property getter without a variable.")]
[TestMethod, ExpectedException(typeof(TransformationException))]
public void CurrentThrowsTransformationExceptionWhenContextWasNotInitialized()
{
var value = TransformationContext.Current;
}
#endregion
#region Dispose
[TestMethod]
public void DisposeRaisesDisposedEvent()
{
bool disposed = false;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Disposed += delegate { disposed = true; };
}
Assert.IsTrue(disposed);
}
[TestMethod]
public void DisposeInvokesOutputFileManagerWhenThereAreAdditionalOutputs()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile }, TestText);
}
Assert.IsNotNull(outputFiles);
}
[TestMethod]
public void DisposeInvokesOutputFileManagerWhenThereAreNoAdditionalOutputsSoThatPreviouslyGeneratedFilesCanBeDeleted()
{
bool outputFileManagerInvoked = false;
using (var transformation = new FakeTransformation())
using (new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFileManagerInvoked = true;
}
Assert.IsTrue(outputFileManagerInvoked);
}
[TestMethod]
public void DisposeUpdatesTemplateFileWhenSessionDoesNotHaveInputFile()
{
const string TemplateFile = "TestTemplate.tt";
string actualInput = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.TemplateFile = TemplateFile;
transformation.Host.UpdatedOutputFiles = (input, outputs) => actualInput = input;
context.Write(new OutputItem { File = TestFile }, TestText);
}
Assert.AreEqual(TemplateFile, actualInput);
}
[TestMethod]
public void DisposeUpdatesInputFileWhenSessionHasInputFile()
{
const string ExpectedInput = "TestInput.cs";
string actualInput = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Session[TransformationContext.InputFileNameKey] = ExpectedInput;
transformation.Host.TemplateFile = "TestTemplate.tt";
transformation.Host.UpdatedOutputFiles = (input, outputs) => actualInput = input;
context.Write(new OutputItem { File = TestFile }, TestText);
}
Assert.AreEqual(ExpectedInput, actualInput);
}
[TestMethod]
public void DisposeLogsTransformationExceptionsThrownByOutputFileManager()
{
CompilerErrorCollection actualErrors = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => { throw new TransformationException(TestText); };
transformation.Host.LoggedErrors = errors => actualErrors = errors;
context.Write(new OutputItem { File = TestFile }, TestText);
}
var error = actualErrors.Cast<CompilerError>().Single();
Assert.AreEqual(TestText, error.ErrorText);
}
[TestMethod]
public void DisposeLogsTransformationExceptionsThrownByTransformationEndedEventHandlers()
{
CompilerErrorCollection actualErrors = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.LoggedErrors = errors => actualErrors = errors;
context.Disposed += delegate { throw new TransformationException(); };
}
Assert.AreEqual(1, actualErrors.Count);
}
[TestMethod]
public void DisposeReportsTemplateFileInErrorsWhenSessionDoesNotHaveInputFile()
{
const string TemplateFile = "TestTemplate.tt";
CompilerErrorCollection actualErrors = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.TemplateFile = TemplateFile;
transformation.Host.LoggedErrors = errors => actualErrors = errors;
context.Disposed += delegate { throw new TransformationException(); };
}
Assert.AreEqual(TemplateFile, actualErrors.Cast<CompilerError>().Single().FileName);
}
[TestMethod]
public void DisposeReportsInputFileInErrorsWhenSessionHasInputFile()
{
const string InputFile = "TestInput.cs";
CompilerErrorCollection actualErrors = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Session[TransformationContext.InputFileNameKey] = InputFile;
transformation.Host.LoggedErrors = errors => actualErrors = errors;
context.Disposed += delegate { throw new TransformationException(); };
}
Assert.AreEqual(InputFile, actualErrors.Cast<CompilerError>().Single().FileName);
}
#endregion
#region GetMetadataValue
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void GetMetadataValueThrowsArgumentNullExceptionWhenNameIsNull()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.GetMetadataValue(null);
}
}
[TestMethod, ExpectedException(typeof(ArgumentException))]
public void GetMetadataValueThrowsArgumentExceptionWhenNameIsEmpty()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.GetMetadataValue(" \t\r\n");
}
}
[TestMethod]
public void GetMetadataValueReturnsValueSuppliedByProvider()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
const string ExpectedValue = "TestValue";
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) => ExpectedValue;
Assert.AreEqual(ExpectedValue, context.GetMetadataValue("TestProperty"));
}
}
[TestMethod]
public void GetMetadataValuePassesHostHierarchyToProvider()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.Hierarchy = new object();
object actualHierarchy = null;
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) =>
{
actualHierarchy = hierarchy;
return string.Empty;
};
context.GetMetadataValue("Irrelevant");
Assert.AreSame(transformation.Host.Hierarchy, actualHierarchy);
}
}
[TestMethod]
public void GetMetadataValuePassesInputFileToProvider()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.TemplateFile = Path.GetRandomFileName();
string actualFileName = null;
transformation.Host.GetMetadataValue = (hierarchy, fileName, metadataName) =>
{
actualFileName = fileName;
return string.Empty;
};
context.GetMetadataValue("Irrelevant");
Assert.AreSame(transformation.Host.TemplateFile, actualFileName);
}
}
#endregion
#region GetPropertyValue
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void GetPropertyValueThrowsArgumentNullExceptionWhenNameIsNull()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.GetPropertyValue(null);
}
}
[TestMethod, ExpectedException(typeof(ArgumentException))]
public void GetPropertyValueThrowsArgumentExceptionWhenNameIsEmpty()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.GetPropertyValue(" \t\r\n");
}
}
[TestMethod]
public void GetPropertyValueReturnsValueSuppliedByProvider()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
const string ExpectedValue = "TestValue";
transformation.Host.GetPropertyValue = (hierarchy, propertyName) => ExpectedValue;
Assert.AreEqual(ExpectedValue, context.GetPropertyValue("TestProperty"));
}
}
[TestMethod]
public void GetPropertyValuePassesHostHierarchyToProvider()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.Hierarchy = new object();
object actualHierarchy = null;
transformation.Host.GetPropertyValue = (hierarchy, propertyName) =>
{
actualHierarchy = hierarchy;
return string.Empty;
};
context.GetPropertyValue("Irrelevant");
Assert.AreSame(transformation.Host.Hierarchy, actualHierarchy);
}
}
#endregion
#region GetService
[TestMethod]
public void GetServiceDelegatesToHost()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
var expected = ((IServiceProvider)transformation.Host).GetService(typeof(ITransformationContextProvider));
var actual = context.GetService(typeof(ITransformationContextProvider));
Assert.AreSame(expected, actual);
}
}
[TestMethod]
public void GetServiceReturnsNullWhenServiceIsNotAvailable()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsNull(context.GetService(typeof(ICloneable))); // Bogus service
}
}
#endregion
#region Host
[TestMethod]
public void HostReturnsHostOfTransformation()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.IsNotNull(context.Host);
Assert.AreSame(transformation.Host, context.Host);
}
}
#endregion
#region Initialize
[TestMethod]
public void InitializeSetsCurrent()
{
using (var transformation = new FakeTransformation())
{
TransformationContext.Initialize(transformation, transformation.GenerationEnvironment);
try
{
Assert.IsNotNull(TransformationContext.Current);
}
finally
{
TransformationContext.Cleanup();
}
}
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void InitializeThrowsArgumentNullExceptionWhenTransformationIsNull()
{
TransformationContext.Initialize(null, new StringBuilder());
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void InitializeThrowsArgumentNullExceptionWhenGenerationEnvironmentIsNull()
{
using (var transformation = new FakeTransformation())
{
TransformationContext.Initialize(transformation, null);
}
}
[TestMethod, ExpectedException(typeof(ArgumentException))]
public void InitializeThrowsArgumentExceptionWhenTransformationIsNotHostSpecific()
{
using (var transformation = new HostNeutralTransformation())
{
TransformationContext.Initialize(transformation, transformation.GenerationEnvironment);
}
}
[TestMethod, ExpectedException(typeof(ArgumentException))]
public void InitializeThrowsArgumentExceptionWhenTransformationHostIsNull()
{
using (var transformation = new FakeTransformation())
{
transformation.Host = null;
TransformationContext.Initialize(transformation, transformation.GenerationEnvironment);
}
}
#endregion
#region Transformation
[TestMethod]
public void TransformationReturnsTransformationPassedToConstructor()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
Assert.AreSame(transformation, context.Transformation);
}
}
#endregion
#region Write
[TestMethod]
public void WriteAppendsToPreviousTemplateOutput()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Write(new OutputItem(), "TemplateOutput");
transformation.Write("TransformationOutput");
Assert.AreEqual("TemplateOutput" + "TransformationOutput", transformation.TransformText());
}
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void WriteThrowsArgumentNullExceptionWhenOutputIsNull()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Write(null, string.Empty);
}
}
[TestMethod]
public void WriteAppendsToTransformationWhenOutputFileIsNotSpecified()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Write("TransformationOutput");
context.Write(new OutputItem(), "TemplateOutput");
Assert.AreEqual("TransformationOutput" + "TemplateOutput", transformation.TransformText());
}
}
[TestMethod]
public void WriteRespectsTransformationIndentationForSingleLineText()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.PushIndent("\t");
context.Write(new OutputItem(), TestText);
Assert.AreEqual("\t" + TestText, transformation.TransformText());
}
}
[TestMethod]
public void WriteRespectsTransformationIndentationForMultilineText()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.PushIndent("\t");
string text = TestText + Environment.NewLine + TestText;
context.Write(new OutputItem(), text);
string expectedOutput = "\t" + TestText + Environment.NewLine + "\t" + TestText;
Assert.AreEqual(expectedOutput, transformation.TransformText());
}
}
[TestMethod]
public void WriteCombinesTextWrittenToTheSameOutputMultipleTimes()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
var outputInfo = new OutputItem { File = TestFile };
context.Write(outputInfo, TestText);
context.Write(outputInfo, TestText);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(TestText + TestText, outputFile.Content.ToString());
}
[TestMethod]
public void WriteCombinesTextOfDifferentOutputsWithTheSameFileName()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile }, TestText);
context.Write(new OutputItem { File = TestFile }, TestText);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(TestText + TestText, outputFile.Content.ToString());
}
[TestMethod]
public void WriteCombinesFileMetadata()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
var outputInfo = new OutputItem { File = TestFile };
outputInfo.Metadata["Generator"] = "TextTemplatingFileGenerator";
context.Write(outputInfo, string.Empty);
outputInfo.Metadata.Clear();
outputInfo.Metadata["LastGenOutput"] = "Test.txt";
context.Write(outputInfo, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual("TextTemplatingFileGenerator", outputFile.Metadata["Generator"]);
Assert.AreEqual("Test.txt", outputFile.Metadata["LastGenOutput"]);
}
[TestMethod]
public void WriteCombinesFileReferences()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
var outputInfo = new OutputItem { File = TestFile };
outputInfo.References.Add("System");
context.Write(outputInfo, string.Empty);
outputInfo.Metadata.Clear();
outputInfo.References.Add("System.Xml");
context.Write(outputInfo, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.IsTrue(outputFile.References.Contains("System"));
Assert.IsTrue(outputFile.References.Contains("System.Xml"));
}
[TestMethod]
public void WriteSetsFileItemType()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, ItemType = ItemType.Compile }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(ItemType.Compile, outputFile.ItemType);
}
[TestMethod]
public void WriteSetsFileItemTypeForDefaultOutput()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { ItemType = ItemType.Compile }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => string.IsNullOrEmpty(output.File));
Assert.AreEqual(ItemType.Compile, outputFile.ItemType);
}
[TestMethod]
public void WriteSetsFileCopyToOutputDirectory()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, CopyToOutputDirectory = CopyToOutputDirectory.CopyAlways }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(CopyToOutputDirectory.CopyAlways, outputFile.CopyToOutputDirectory);
}
[TestMethod]
public void WriteSetsFileCustomTool()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, CustomTool = "TextTemplatingFileGenerator" }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual("TextTemplatingFileGenerator", outputFile.CustomTool);
}
[TestMethod]
public void WriteSetsFileCustomToolNamespace()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, CustomToolNamespace = "Microsoft" }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual("Microsoft", outputFile.CustomToolNamespace);
}
[TestMethod]
public void WriteSetsFileDirectory()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, Directory = "SubFolder" }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual("SubFolder", outputFile.Directory);
}
[TestMethod]
public void WriteSetsFileEncoding()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, Encoding = Encoding.UTF7 }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(Encoding.UTF7, outputFile.Encoding);
}
[TestMethod]
public void WriteSetsFileEncodingForDefaultOutput()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { Encoding = Encoding.UTF7 }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => string.IsNullOrEmpty(output.File));
Assert.AreEqual(Encoding.UTF7, outputFile.Encoding);
}
[TestMethod]
public void WriteSetsFilePreserveExistingFile()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, PreserveExistingFile = true }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual(true, outputFile.PreserveExistingFile);
}
[TestMethod]
public void WriteSetsFileProject()
{
OutputFile[] outputFiles = null;
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
transformation.Host.UpdatedOutputFiles = (input, outputs) => outputFiles = outputs;
context.Write(new OutputItem { File = TestFile, Project = "Test.proj" }, string.Empty);
}
OutputFile outputFile = outputFiles.Single(output => output.File == TestFile);
Assert.AreEqual("Test.proj", outputFile.Project);
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void WriteThrowsInvalidOperationExceptionWhenDirectoryIsSpecifiedWithoutFile()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Write(new OutputItem { Directory = "SubFolder" }, string.Empty);
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void WriteThrowsInvalidOperationExceptionWhenProjectIsSpecifiedWithoutFile()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Write(new OutputItem { Project = "Test.proj" }, string.Empty);
}
}
[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void WriteThrowsInvalidOperationExceptionWhenPreserveExistingFileIsSpecifiedWithoutFile()
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
context.Write(new OutputItem { PreserveExistingFile = true }, string.Empty);
}
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenEncodingIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { Encoding = Encoding.ASCII },
new OutputItem { Encoding = Encoding.UTF8 },
new[] { "Encoding", Encoding.ASCII.EncodingName, Encoding.UTF8.EncodingName });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenBuildActionIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { ItemType = ItemType.Compile },
new OutputItem { ItemType = ItemType.Content },
new[] { "ItemType", ItemType.Compile, ItemType.Content });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenCopyToOutputDirectoryIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { CopyToOutputDirectory = CopyToOutputDirectory.CopyIfNewer },
new OutputItem { CopyToOutputDirectory = CopyToOutputDirectory.CopyAlways },
new[] { "CopyToOutputDirectory", "PreserveNewest", "Always" });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenCustomToolIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { CustomTool = "TextTemplatingFileGenerator" },
new OutputItem { CustomTool = "TextTemplatingFilePreprocessor" },
new[] { "TextTemplatingFileGenerator", "TextTemplatingFilePreprocessor" });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenCustomToolNamespaceIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { CustomToolNamespace = "T4Toolbox" },
new OutputItem { CustomToolNamespace = "Microsoft" },
new[] { "CustomToolNamespace", "T4Toolbox", "Microsoft" });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenMetadataIsInconsistent()
{
var first = new OutputItem();
first.Metadata["Generator"] = "TextTemplatingFileGenerator";
var second = new OutputItem();
second.Metadata["Generator"] = "TextTemplatingFilePreprocessor";
WriteThrowsInvalidOperationException(first, second, new[] { "Metadata", "Generator", "TextTemplatingFileGenerator", "TextTemplatingFilePreprocessor" });
}
[TestMethod]
public void WriteThrowsInvalidOperationExceptionWhenPreserveExistingFileIsInconsistent()
{
WriteThrowsInvalidOperationException(
new OutputItem { PreserveExistingFile = false },
new OutputItem { PreserveExistingFile = true },
new[] { "PreserveExistingFile", false.ToString(), true.ToString() });
}
#endregion
private static void WriteThrowsInvalidOperationException(OutputItem first, OutputItem second, params string[] keywords)
{
using (var transformation = new FakeTransformation())
using (var context = new TransformationContext(transformation, transformation.GenerationEnvironment))
{
first.File = TestFile;
context.Write(first, string.Empty);
try
{
second.File = TestFile;
context.Write(second, string.Empty);
}
catch (InvalidOperationException e)
{
Assert.AreNotEqual(typeof(TransformationException), e.GetType());
foreach (string keyword in keywords)
{
StringAssert.Contains(e.Message, keyword);
}
}
}
}
private class HostNeutralTransformation : TextTransformation
{
public new StringBuilder GenerationEnvironment
{
get { return base.GenerationEnvironment; }
}
public override string TransformText()
{
throw new NotImplementedException();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IslandConverter
{
public class ClipProperties
{
public float[] OffsetPivot { get; set; }
public int OffsetDirection { get; set; }
}
}
|
namespace Altairis.ShirtShop.Web {
public class ShopConfig {
public PaymentConfig Payment { get; set; }
public MailingConfig Mailing { get; set; }
public class PaymentConfig {
public string AccountNumber { get; set; }
public string VarSymbolFormat { get; set; }
}
public class MailingConfig {
public string PickupFolder { get; set; }
public string SenderAddress { get; set; }
public string OrderRecipientAddress { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Duality
{
/// <summary>
/// A log entry.
/// </summary>
public struct LogEntry
{
private Log source;
private LogMessageType type;
private string message;
private object context;
private DateTime timeStamp;
private int frameStamp;
private int indent;
/// <summary>
/// [GET] The <see cref="Log"/> from which this entry originates.
/// </summary>
public Log Source
{
get { return this.source; }
}
/// <summary>
/// [GET] The messages type.
/// </summary>
public LogMessageType Type
{
get { return this.type; }
}
/// <summary>
/// [GET] The log entry's message.
/// </summary>
public string Message
{
get { return this.message; }
}
/// <summary>
/// [GET] The context in which this log was written. Usually the primary object the log entry is associated with.
/// </summary>
public object Context
{
get { return this.context; }
}
/// <summary>
/// [GET] The messages timestamp.
/// </summary>
public DateTime TimeStamp
{
get { return this.timeStamp; }
}
/// <summary>
/// [GET] The value of <see cref="Time.FrameCount"/> when the message was logged.
/// </summary>
public int FrameStamp
{
get { return this.frameStamp; }
}
/// <summary>
/// [GET] The desired indentation level for this log message when displaying it.
/// </summary>
public int Indent
{
get { return this.indent; }
}
public LogEntry(Log source, LogMessageType type, string msg, object context)
{
this.source = source;
this.type = type;
this.message = msg;
this.context = context;
this.indent = source.Indent;
this.timeStamp = DateTime.Now;
this.frameStamp = Time.FrameCount;
}
public override string ToString()
{
return string.Format("{0}: {1}", this.type, this.message);
}
}
}
|
using System;
using System.Collections.Generic;
namespace AIStudio.Wpf.Entity.Models
{
public partial class Subscription
{
public long PersistenceId { get; set; }
public string EventKey { get; set; }
public string EventName { get; set; }
public int StepId { get; set; }
public Guid SubscriptionId { get; set; }
public string WorkflowId { get; set; }
public DateTime SubscribeAsOf { get; set; }
public string SubscriptionData { get; set; }
public string ExecutionPointerId { get; set; }
public string ExternalToken { get; set; }
public DateTime? ExternalTokenExpiry { get; set; }
public string ExternalWorkerId { get; set; }
}
}
|
using Discord.Commands;
using System;
using System.Threading.Tasks;
namespace Mitternacht.Common.TypeReaders {
public class ModerationPointsTypeReader : TypeReader {
public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services){
try {
return Task.FromResult(TypeReaderResult.FromSuccess(ModerationPoints.FromString(input)));
} catch(ArgumentException e) {
return Task.FromResult(TypeReaderResult.FromError(e));
}
}
}
}
|
//
// Copyright (c) Antmicro
//
// This file is part of the Emul8 project.
// Full license details are defined in the 'LICENSE' file.
//
using System;
namespace Emul8.Exceptions
{
public class ConfigurationException : System.Exception
{
public ConfigurationException(String message) : base(message)
{
}
}
}
|
using System;
using System.Threading.Tasks;
using Serilog;
using Araumi.Server.Services;
using Araumi.Server.Services.Servers.Game;
using Araumi.Server.Services.Servers.Static;
namespace Araumi.Server.Cli {
public static class Program {
public static async Task Main(string[] args) {
try {
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
ServiceManager.Instance.Init();
ServiceManager.Instance.Container.Resolve<ILoggerService>().Init();
await ServiceManager.Instance.Container.Resolve<IConfigService>().Init();
await ServiceManager.Instance.Container.Resolve<IDatabaseService>().Init();
await ServiceManager.Instance.Container.Resolve<IClientConfigService>().Init();
await ServiceManager.Instance.Container.Resolve<IStaticServer>().Start();
await ServiceManager.Instance.Container.Resolve<IGameServer>().Start();
await ServiceManager.Instance.Container.Resolve<IExitWaitService>().WaitAsync();
Log.Information("Stopping...");
await ServiceManager.Instance.Container.Resolve<IDatabaseService>().DisposeAsync();
ServiceManager.Instance.Dispose();
} catch(Exception exception) {
Log.Fatal(exception, "A fatal exception occurred");
} finally {
Log.Information("Server stopped, exiting...");
Console.ReadLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
namespace storeme.Code
{
public static class AppSettings
{
public static int DaysToKeep
{
get
{
return Setting<int>("DaysToKeep");
}
}
private static T Setting<T>(string name)
{
string value = ConfigurationManager.AppSettings[name];
if (value == null)
{
throw new Exception(String.Format("Could not find setting '{0}',", name));
}
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
}
} |
using System.Collections.Generic;
using AspNetCoreSpa.Core.Entities;
namespace AspNetCoreSpa.Infrastructure
{
public interface ITourCategoryRepository : IRepository<TourCategory>,IEnumerable<TourCategory>
{
}
} |
using System;
using API.BLL.Base;
using API.BLL.UseCases.Memberships.Entities;
using API.BLL.UseCases.Memberships.Transformer;
namespace API.BLL.UseCases.Memberships.Daos
{
public interface IUserDao : IDao<User, UserIdent, UserTransformer>
{
User GetUserByUserName(string userName);
bool IsLoginUnique(string userName, Guid? userIdent);
User FindByIdentForContext(UserIdent userIdent);
DataTableSearchResult<User> FindBySearchValue(UserSearchOptions searchOptions);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PoshSec.Framework.Interface
{
public class ProxyPreferenceGroupBox : GroupBox
{
public event EventHandler SelectedChanged = delegate { };
ProxyPreference _selected;
public ProxyPreference Selected
{
get
{
return _selected;
}
set
{
ProxyPreference val = ProxyPreference.System;
var radioButton = Controls.OfType<RadioButton>()
.FirstOrDefault(radio =>
radio.Tag != null
&& Enum.TryParse(radio.Tag.ToString(), out val) && val == value);
if (radioButton != null)
{
radioButton.Checked = true;
_selected = val;
}
}
}
protected override void OnControlAdded(ControlEventArgs e)
{
base.OnControlAdded(e);
if (e.Control is RadioButton radioButton)
radioButton.CheckedChanged += RadioButton_CheckedChanged;
}
void RadioButton_CheckedChanged(object sender, EventArgs e)
{
var radio = (RadioButton)sender;
if (radio.Checked && radio.Tag != null
&& Enum.TryParse(radio.Tag.ToString(), out ProxyPreference val))
{
_selected = val;
SelectedChanged(this, new EventArgs());
}
}
}
}
|
using System.Collections.Generic;
using Loon.Core;
using System;
using Loon.Utils;
namespace Loon.Media
{
public abstract class SoundImpl : Sound {
protected IList<Callback<object>> callbacks;
protected Exception error;
protected bool playing, looping;
protected float volume = 1;
protected object impl;
public virtual void OnLoaded(object impl)
{
this.impl = impl;
callbacks = CallbackList<object>.DispatchSuccessClear(callbacks, this);
SetVolumeImpl(volume);
SetLoopingImpl(looping);
if (playing) {
PlayImpl();
}
}
public virtual void OnLoadError(Exception error)
{
this.error = error;
callbacks = CallbackList<object>.DispatchSuccessClear(callbacks, error);
}
public virtual bool Prepare()
{
return (impl != null) ? PrepareImpl() : false;
}
public virtual bool IsPlaying()
{
return (impl != null) ? PlayingImpl() : playing;
}
public virtual bool Play()
{
this.playing = true;
if (impl != null) {
return PlayImpl();
} else {
return false;
}
}
public virtual void Stop()
{
this.playing = false;
if (impl != null) {
StopImpl();
}
}
public virtual void SetLooping(bool looping)
{
this.looping = looping;
if (impl != null) {
SetLoopingImpl(looping);
}
}
public virtual float Volume()
{
return volume;
}
public virtual void SetVolume(float volume)
{
this.volume = MathUtils.Clamp(volume, 0, 1);
if (impl != null) {
SetVolumeImpl(this.volume);
}
}
public virtual void Release()
{
if (impl != null) {
ReleaseImpl();
impl = null;
}
}
public virtual void AddCallback(Callback<object> callback)
{
if (impl != null) {
callback.OnSuccess(this);
} else if (error != null) {
callback.OnFailure(error);
} else {
callbacks = CallbackList<object>.CreateAdd(callbacks, callback);
}
}
protected virtual bool PrepareImpl() {
return false;
}
protected virtual bool PlayingImpl()
{
return playing;
}
protected abstract bool PlayImpl();
protected abstract void StopImpl();
protected abstract void SetLoopingImpl(bool looping);
protected abstract void SetVolumeImpl(float volume);
protected abstract void ReleaseImpl();
}
}
|
using JudgeSystem.Workers.Common;
namespace JudgeSystem.Compilers
{
public interface ICompilerFactory
{
ICompiler CreateCompiler(ProgrammingLanguage programmingLanguage);
}
}
|
using System;
using System.Reflection;
namespace LOLCode.Compiler.Symbols
{
internal abstract class FunctionRef
: SymbolRef
{
// TODO: All of these should be readonly.
public int Arity;
public bool IsVariadic;
public Type ReturnType;
public Type[] ArgumentTypes;
public abstract MethodInfo Method { get; }
}
}
|
using System.Collections.Generic;
namespace AntDesign.Docs
{
public class DemoComponent
{
public string Title { get; set; }
public string SubTitle { get; set; }
public string Type { get; set; }
public string Desc { get; set; }
public string ApiDoc { get; set; }
public int? Cols { get; set; }
public string Cover { get; set; }
public List<DemoItem> DemoList { get; set; }
}
public class DemoItem
{
public decimal Order { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public string Type { get; set; }
public string Style { get; set; }
public int? Iframe { get; set; }
public bool? Docs { get; set; }
public bool Debug { get; set; }
}
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Dolittle. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using Dolittle.Booting;
using Dolittle.DependencyInversion;
using Dolittle.DependencyInversion.Booting;
using Dolittle.Types;
namespace Dolittle.Configuration.Files.Booting.Stages
{
/// <summary>
/// Represents bindings for booting
/// </summary>
public class PreConfiguration : ICanRunBeforeBootStage<NoSettings>
{
/// <inheritdoc/>
public BootStage BootStage => BootStage.Configuration;
/// <inheritdoc/>
public void Perform(NoSettings settings, IBootStageBuilder builder)
{
var typeFinder = builder.GetAssociation(WellKnownAssociations.TypeFinder) as ITypeFinder;
var parsers = new ConfigurationFileParsers(typeFinder, builder.Container);
builder.Bindings.Bind<IConfigurationFileParsers>().To(parsers);
}
}
}
|
namespace GB.Unity.Editor {
using UnityEngine;
using UnityEditor;
public class GBMenuEditor {
[MenuItem ("GeBros/Documents/Start Guide...", false, 200)]
public static void ShowDocumentsStartGuide() {
Application.OpenURL("127.0.0.1");
}
[MenuItem ("GeBros/Documents/API Guide...", false, 201)]
public static void ShowDocumentsAPIGuide() {
}
[MenuItem ("GeBros/Download", false, 300)]
public static void goDownloadSite() {
}
[MenuItem ("GeBros/About", false, 400)]
public static void About() {
// string msg = GPGSStrings.AboutText + PluginVersion.VersionString + " (" +
// string.Format("0x{0:X8}", GooglePlayGames.PluginVersion.VersionInt) + ")";
// EditorUtility.DisplayDialog(GPGSStrings.AboutTitle, msg,
// GPGSStrings.Ok);
GBUtils.Alert(GBConstantStrings.Version.Title, GBSettingsImpl.SDK_VERSION);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
using UnityEngine;
namespace SceneJect.Common
{
/// <summary>
/// MonoBehaviour that can be inherited from to register dependencies
/// that aren't MonoBehaviour and thus don't exist in the scene or can't
/// exist in the scene.
/// </summary>
public abstract class NonBehaviourDependency : MonoBehaviour
{
/// <summary>
/// Called when registeration is happening by Sceneject.
/// </summary>
/// <param name="register">A non-null registeration object.</param>
public abstract void Register(ContainerBuilder register);
}
}
|
using System.Windows;
using System.Windows.Input;
namespace Cobalt.Views.Util
{
public class TextBoxUtil
{
public static readonly RoutedEvent EnterUpEvent = EventManager.RegisterRoutedEvent("EnterUp",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(TextBoxUtil));
public static void AddEnterUpHandler(DependencyObject d, RoutedEventHandler h)
{
if (!(d is UIElement elem)) return;
elem.KeyUp += HandleKeyUp;
elem.AddHandler(EnterUpEvent, h);
}
private static void HandleKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
((UIElement) sender).RaiseEvent(new RoutedEventArgs(EnterUpEvent));
}
public static void RemoveEnterUpHandler(DependencyObject d, RoutedEventHandler h)
{
if (!(d is UIElement elem)) return;
elem.KeyUp -= HandleKeyUp;
elem.RemoveHandler(EnterUpEvent, h);
}
}
} |
namespace Common.Lab
{
using System;
using System.Collections.Generic;
using System.Linq;
public class JournalLog
{
public List<EntryLog> EntryLogList { get; internal set; }
public int Count { get; internal set; }
public JournalLog()
{
this.EntryLogList = new List<EntryLog>();
}
protected EntryLog GetCopy(int index) => new EntryLog(this.EntryLogList.ElementAt(index));
public void Publish(string message)
{
this.EntryLogList.Add(new EntryLog(DateTime.Now, message));
this.Count = this.EntryLogList.Count;
}
}
}
|
namespace PunchGame.Server.Room.Core.Output
{
public class GameStartedEvent : RoomBroadcastEvent
{
}
}
|
using WG.Entities;
using Common;
using System;
using System.Linq;
using System.Collections.Generic;
namespace WG.Controllers.stock.stock_master
{
public class StockMaster_ItemDTO : DataDTO
{
public long Id { get; set; }
public long ProductId { get; set; }
public long FirstVariationId { get; set; }
public long? SecondVariationId { get; set; }
public string SKU { get; set; }
public long Price { get; set; }
public long MinPrice { get; set; }
public StockMaster_ItemDTO() {}
public StockMaster_ItemDTO(Item Item)
{
this.Id = Item.Id;
this.ProductId = Item.ProductId;
this.FirstVariationId = Item.FirstVariationId;
this.SecondVariationId = Item.SecondVariationId;
this.SKU = Item.SKU;
this.Price = Item.Price;
this.MinPrice = Item.MinPrice;
}
}
public class StockMaster_ItemFilterDTO : FilterDTO
{
public long? Id { get; set; }
public long? ProductId { get; set; }
public long? FirstVariationId { get; set; }
public long? SecondVariationId { get; set; }
public string SKU { get; set; }
public long? Price { get; set; }
public long? MinPrice { get; set; }
public ItemOrder OrderBy { get; set; }
}
}
|
using Core.Model;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace OnlineStore.Api.Extensions
{
public static class CommandResponseExtensions
{
public static void AddToModelState(
this CommandResponse commandResponse,
ModelStateDictionary modelStateDictionary)
{
foreach (CommandError error in commandResponse.Errors)
{
modelStateDictionary.AddModelError(error.Key ?? "", error.Message);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System.Linq;
namespace IndiePixel
{
public class IP_Track : MonoBehaviour
{
#region Variables
[Header("Track Properties")]
public IP_Track_Data trackData;
public List<IP_Gate> gates = new List<IP_Gate>();
[Header("Track Events")]
public UnityEvent OnCompletedTrack = new UnityEvent();
private float startTime;
private int currentTime;
#endregion
#region Properties
private int currentGateID = 0;
public int CurrentGateID
{
get { return currentGateID; }
}
private int totalGates;
public int TotalGates
{
get { return totalGates; }
}
private int currentMinutes;
public int CurrentMinutes
{
get { return currentMinutes; }
}
private int currentSeconds;
public int CurrentSecond
{
get { return currentSeconds; }
}
private int currentScore;
public int CurrentScore
{
get { return currentScore; }
}
private bool isComplete = false;
public bool IsComplete
{
set { isComplete = value; }
}
#endregion
#region Builtin Methods
// Use this for initialization
void Start()
{
FindGates();
InitializeGates();
currentGateID = 0;
StartTrack();
}
// Update is called once per frame
void Update()
{
if(!isComplete)
{
UpdateStats();
}
}
private void OnDrawGizmos()
{
FindGates();
if(gates.Count > 0)
{
for(int i = 0; i < gates.Count; i++)
{
if((i+1) == gates.Count)
{
break;
}
Gizmos.color = new Color(1f, 1f, 0, 0.5f);
Gizmos.DrawLine(gates[i].transform.position, gates[i + 1].transform.position);
}
}
}
#endregion
#region Custom Methods
public void StartTrack()
{
if(gates.Count > 0)
{
startTime = Time.time;
currentScore = 0;
isComplete = false;
gates[currentGateID].ActivateGate();
}
}
void SelectNextGate(float distPercentage)
{
int score = Mathf.RoundToInt(100f * (1f-distPercentage));
score = Mathf.Clamp(score, 0, 100);
currentScore += score;
currentGateID++;
if(currentGateID == gates.Count)
{
//Debug.Log("Completed Track!");
if(OnCompletedTrack != null)
{
OnCompletedTrack.Invoke();
}
return;
}
gates[currentGateID].ActivateGate();
}
void FindGates()
{
gates.Clear();
gates = GetComponentsInChildren<IP_Gate>().ToList<IP_Gate>();
totalGates = gates.Count;
}
void InitializeGates()
{
if(gates.Count > 0)
{
foreach(IP_Gate gate in gates)
{
gate.DeactivateGate();
gate.OnClearedGate.AddListener(SelectNextGate);
}
}
}
void UpdateStats()
{
currentTime = (int)(Time.time - startTime);
currentMinutes = (int)(currentTime / 60f);
currentSeconds = currentTime - (currentMinutes * 60);
}
public void SaveTrackData()
{
if(trackData)
{
trackData.SetTimes(currentTime);
trackData.SetScores(currentScore);
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rocket : Bullet {
public float _explosionRadius;
public float _explosionTime;
public UnityEngine.Events.UnityEvent OnExplode;
void Start() {
Invoke("Explode", _explosionTime);
}
protected override void OnTriggerEnter(Collider other) {
Explode();
}
void Explode() {
OnExplode.Invoke();
var colliders = Physics.OverlapSphere(transform.position, _explosionRadius);
foreach (var collider in colliders) {
var damageable = collider.GetComponentInParent<Damageable>();
if (damageable) {
damageable.Damage(_damage);
}
}
Destroy(gameObject);
}
} |
using System;
namespace Logzio.NLog.Extensions
{
public class Options
{
public string Name { get; set; }
public string Token { get; set; }
public string LogzioType { get; set; }
public string ListenerUrl { get; set; }
public int BufferSize { get; set; }
public TimeSpan BufferTimeOut { get; set; }
public int RetriesMaxAttempts { get; set; }
public TimeSpan RetriesInterval { get; set; }
public bool IsDebug { get; set; }
}
} |
using System;
using System.Reflection;
using Castle.DynamicProxy;
namespace SharpAspect
{
/// <summary>
/// Encapsulates an invocation of a proxied method.
/// </summary>
public interface IInvocation
{
object[] Arguments { get; }
Type[] GenericArguments { get; }
object InvocationTarget { get; }
MethodInfo Method { get; }
MethodInfo MethodInvocationTarget { get; }
object Proxy { get; }
object ReturnValue { get; set; }
Type TargetType { get; }
IInvocationProceedInfo CaptureProceedInfo();
object GetArgumentValue(int index);
MethodInfo GetConcreteMethod();
MethodInfo GetConcreteMethodInvocationTarget();
void SetArgumentValue(int index, object value);
Exception Exception { get; }
}
}
|
namespace NewRelicSharp.Items
{
using System.Text;
/// <summary>
/// Represents base, not mandatory parameters for deployments.
/// Could not be used to record deployment
/// Do not use this base class directly
/// </summary>
public abstract class DeploymentsBase
{
internal const string DeploymentInformationFormat = "deployment[{0}]={1}&";
/// <summary>
/// A list of changes for this deployment
/// </summary>
public string Changelog { get; set; }
/// <summary>
/// Text annotation for the deployment; notes for you
/// </summary>
public string Description { get; set; }
/// <summary>
/// A revision number (e.g., git commit SHA)
/// </summary>
public string Revision { get; set; }
/// <summary>
/// The name of the user/process that triggered this deployment
/// </summary>
public string User { get; set; }
/// <summary>
/// Name of the application
/// </summary>
public string AppName { get; set; }
/// <summary>
/// The environment for this deployment
/// </summary>
public string Environment { get; set; }
/// <summary>
/// Returns string representation for current deployment
/// </summary>
/// <returns></returns>
public override string ToString()
{
var data = new StringBuilder();
if (!string.IsNullOrWhiteSpace(this.Changelog))
{
data.AppendFormat(DeploymentInformationFormat, "changelog", this.Changelog);
}
if (!string.IsNullOrWhiteSpace(this.Description))
{
data.AppendFormat(DeploymentInformationFormat, "description", this.Description);
}
if (!string.IsNullOrWhiteSpace(this.Revision))
{
data.AppendFormat(DeploymentInformationFormat, "revision", this.Revision);
}
if (!string.IsNullOrWhiteSpace(this.User))
{
data.AppendFormat(DeploymentInformationFormat, "user", this.User);
}
if (!string.IsNullOrWhiteSpace(this.AppName))
{
data.AppendFormat(DeploymentInformationFormat, "appname", this.AppName);
}
if (!string.IsNullOrWhiteSpace(this.AppName))
{
data.AppendFormat(DeploymentInformationFormat, "appname", this.AppName);
}
if (!string.IsNullOrWhiteSpace(this.Environment))
{
data.AppendFormat(DeploymentInformationFormat, "environment", this.Environment);
}
return data.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Poke_Edit
{
public struct Time
{
public ushort hours;
public byte minutes, seconds;
};
public enum Gender {
Male = 0, Female = 1
};
public struct TrainerID {
public ushort Public, Secret;
};
public static class TrainerInfo
{
public static string playerName;
public static Gender playerGender;
public static TrainerID playerId;
public static Time playTime;
public static uint money;
public static uint securityKey;
}
}
|
namespace Evelyn.Client
{
public interface IEvelynClient
{
bool GetToggleState(string toggleKey);
}
}
|
/*
* File: AgentDriver.cs
* Project: Unity 2018 AI Programming Cookbook
* Created Date: 2018-05-27 15:41:40
* Author: Jorge Palacios
* -----
* Last Modified: 2018-05-27 16:19:11
* Modified By: Jorge Palacios
* -----
* Copyright (c) 2018 Packt Publishing Ltd
*/
using UnityEngine;
public class AgentDriver : MonoBehaviour
{
public DriverProfile profile;
public CarController car;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ES5.Script.EcmaScript.Internal
{
public class ArrayLiteralExpression : ExpressionElement
{
List<ExpressionElement> fItems;
public ArrayLiteralExpression(PositionPair aPositionPair, params ExpressionElement[] aItems)
: base(aPositionPair)
{
fItems = new List<ExpressionElement>(aItems);
}
public ArrayLiteralExpression(PositionPair aPositionPair, IEnumerable<ExpressionElement> aItems)
: base(aPositionPair)
{
fItems = new List<ExpressionElement>(aItems);
}
public ArrayLiteralExpression(PositionPair aPositionPair, List<ExpressionElement> aItems)
: base(aPositionPair)
{
fItems = aItems;
}
public List<ExpressionElement> Items { get { return fItems; } }
public override ElementType Type { get { return ElementType.ArrayLiteralExpression; } }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.DataTransferObjects
{
public class MeasurementDto
{
public double Value { get; set; }
public DateTime Time { get; set; }
public int SensorId { get; set; }
public string SensorName { get; set; }
public double Trend { get; set; }
public override string ToString()
{
return $"{SensorName} {Time.ToShortTimeString()}: {Value}";
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json.Serialization;
using CommandLine;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Rinkudesu.Services.Links;
using Rinkudesu.Services.Links.Data;
using Rinkudesu.Services.Links.DataTransferObjects;
using Rinkudesu.Services.Links.HealthChecks;
using Rinkudesu.Services.Links.Repositories;
using Rinkudesu.Services.Links.Utilities;
using Serilog;
using Serilog.Exceptions;
using Serilog.Formatting.Compact;
#pragma warning disable 1591
#pragma warning disable CA1812
// Migrations adding is behaving in a rather bizarre way.
// This line is required to fix some arguments being passed to this program
// and also theres a fatal exception somewhere during it
// However, the migration is generated correctly
#if DEBUG
args = args.Where(a => a != "--applicationName").ToArray();
#endif
var result = Parser.Default.ParseArguments<InputArguments>(args)
.WithParsed(o => {
o.SaveAsCurrent();
});
if (result.Tag == ParserResultType.NotParsed)
{
return 1;
}
var logConfig = new LoggerConfiguration();
if (!InputArguments.Current.MuteConsoleLog)
{
logConfig.WriteTo.Console();
}
Log.Logger = logConfig.CreateBootstrapLogger();
try
{
var builder = WebApplication.CreateBuilder(args);
ConfigureServices(builder.Services);
builder.Host.UseSerilog((context, services, configuration) => {
if (!InputArguments.Current.MuteConsoleLog)
{
configuration.WriteTo.Console();
}
if (InputArguments.Current.FileLogPath != null)
{
configuration.WriteTo.File(new RenderedCompactJsonFormatter(),
InputArguments.Current.FileLogPath);
}
InputArguments.Current.GetMinimumLogLevel(configuration);
configuration.ReadFrom.Services(services);
configuration.Enrich.FromLogContext()
.Enrich.WithProperty("ApplicationName", context.HostingEnvironment.ApplicationName)
.Enrich.WithExceptionDetails();
});
builder.WebHost
.UseKestrel((context, serverOptions) => {
serverOptions.ConfigureHttpsDefaults(https => {
https.ServerCertificate = new X509Certificate2("cert.pfx");
});
});
var app = builder.Build();
Configure(app, app.Environment);
await app.RunAsync();
}
#pragma warning disable CA1031
catch (Exception e)
#pragma warning restore CA1031
{
Log.Fatal(e, "Application failed to start");
return 2;
}
finally
{
Log.CloseAndFlush();
}
return 0;
void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILinkRepository, LinkRepository>();
services.AddAutoMapper(typeof(LinkMappingProfile));
services.AddScoped<ISharedLinkRepository, SharedLinkRepository>();
services.AddDbContext<LinkDbContext>(options => {
options.UseNpgsql(
EnvironmentalVariablesReader.GetRequiredVariable(EnvironmentalVariablesReader
.DbContextVariableName), providerOptions => {
providerOptions.EnableRetryOnFailure();
providerOptions.MigrationsAssembly("Rinkudesu.Services.Links");
});
#if DEBUG
options.EnableSensitiveDataLogging();
#endif
});
var requireAuthenticated = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
services.AddControllers(o =>
{
o.Filters.Add(new AuthorizeFilter(requireAuthenticated));
})
.AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
options.Authority = Environment.GetEnvironmentVariable("RINKUDESU_AUTHORITY");
#if DEBUG
options.RequireHttpsMetadata = false;
#endif
options.Audience = "rinkudesu";
});
services.AddApiVersioning(o => {
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
o.ApiVersionReader = new UrlSegmentApiVersionReader();
});
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Link management API",
Description = "API to manage link objects"
});
var xmlName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = AppContext.BaseDirectory;
c.IncludeXmlComments(Path.Combine(xmlPath, xmlName));
});
services.AddHealthChecks().AddCheck<DatabaseHealthCheck>("Database health check");
}
void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSerilogRequestLogging();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Links API V1");
});
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
if (InputArguments.Current.ApplyMigrations)
{
ApplyMigrations(app);
}
}
static void ApplyMigrations(IApplicationBuilder app)
{
using var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<LinkDbContext>();
context.Database.Migrate();
}
|
namespace Test.BridgeIssues.N447
{
using Bridge;
public class N447
{
public const int Five = 5;
public const string Another = "Another";
public const decimal Ten = 10m;
[InlineConst]
public const int InlineFifteen = 15;
[InlineConst]
public const string InlineSome = "Some";
[InlineConst]
public const decimal InlineHalf = 0.5m;
public static void CheckInlineExpression()
{
var s = Another + InlineSome;
var i = Five + InlineFifteen;
var d = Ten + InlineHalf;
}
public static void CheckInlineCalls()
{
var s = Math447.GetSum(Another, InlineSome);
var i = Math447.GetSum(Five, InlineFifteen);
var d = Math447.GetSum(Ten, InlineHalf);
}
}
public class Math447
{
public static int GetSum(int a, int b)
{
return a + b;
}
public static string GetSum(string a, string b)
{
return a + b;
}
public static decimal GetSum(decimal a, decimal b)
{
return a + b;
}
}
}
|
using System.IO;
using UnityEditor.AssetImporters;
using UnityEngine;
namespace ANovel.Engine.Tools
{
[ScriptedImporter(1, "anovel")]
public class ANovelAssetImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
var texts = File.ReadAllText(ctx.assetPath);
var asset = new TextAsset(texts);
ctx.AddObjectToAsset("main", asset);
ctx.SetMainObject(asset);
}
}
} |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace IGeekFan.FreeKit.Modularity;
public class ModuleRoutingMvcOptionsPostConfigure : IPostConfigureOptions<MvcOptions>
{
private readonly IEnumerable<ModuleInfo> _modules;
public ModuleRoutingMvcOptionsPostConfigure(IEnumerable<ModuleInfo> modules)
{
_modules = modules;
}
public void PostConfigure(string name, MvcOptions options)
{
options.Conventions.Add(new ModuleRoutingConvention(_modules));
}
}
|
using UnityEngine;
using System.Collections;
public interface IInteract
{
/// <summary>
/// Called when the player wants to interact with the object implementing this interface
/// </summary>
void Interact();
/// <summary>
/// What is displayed on screen when the player is close enough
/// </summary>
string Description { get; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpBasic.Basic.BasicKnowledge
{
public class Demo
{
public static void TestDemo() {
/*
//属性和索引器
Person p1 = new Person();
Person p2 = new Person();
p1.Name = "zhangsan";
p1.Address = "suzhou";
p1.Age = 16;
p2.Name = "lisi";
p2.Address = "shanghai";
p2.Age = 20;
Console.WriteLine(p1.Age.ToString() + "...." + p2.Age.ToString());
Console.WriteLine("p1的年龄是{0}....p2的年龄是{1}", p1.Age.ToString(), p2.Age.ToString());//占位符方式
Console.WriteLine(p1[0] + "...." + p1[1] + "...." + p1[2] + "...." + p1[3]);
Console.ReadKey();
* */
/*
//里氏替换原则,父类对象赋值子类对象
Person[] p = { new Employee(), new Student() };
for (int i = 0; i < p.Length; i++)
{
p[i].DoAction(); //利用虚方法实现重写(实现多态的一种方法)
}
*/
Dog dog1 = new Dog();
dog1.Eat();
dog1.Sleep();
IAnimal ani = new Dog();
ani.Eat();//同样可以打印出DOG Eat
}
}
}
|
using System;
using System.Windows.Media;
using System.Windows.Threading;
using TETCSharpClient;
using TETCSharpClient.Data;
using TETWinControls;
namespace NetworkController.Plugin.EyeTribe
{
public partial class GazeDot : IGazeUpdateListener
{
public bool EnableCorrection;
public GazeDot(Color fillColor)
{
InitializeComponent();
GazeManager.Instance.AddGazeListener(this);
Circle.Fill = new SolidColorBrush(fillColor);
}
public void OnScreenIndexChanged(int number)
{
}
public void OnCalibrationStateChanged(bool val)
{
}
public void ToggleVisibilitySafely(bool value)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(
new Action(() => ToggleVisibilitySafely(value)));
return;
}
if (value) Show();
else Hide();
}
public void OnGazeUpdate(GazeData gazeData)
{
if (Dispatcher.CheckAccess() == false)
{
Dispatcher.BeginInvoke(new Action(() => OnGazeUpdate(gazeData)));
return;
}
// Start or stop tracking lost animation
if ((gazeData.State & GazeData.STATE_TRACKING_GAZE) == 0 &&
(gazeData.State & GazeData.STATE_TRACKING_PRESENCE) == 0) return;
//Tracking coordinates
var d = Utility.Instance.ScaleDpi;
var x = Utility.Instance.RecordingPosition.X;
var y = Utility.Instance.RecordingPosition.Y;
//var gX = gazeData.RawCoordinates.X;
//var gY = gazeData.RawCoordinates.Y;
var smoothedCoordinates = gazeData.SmoothedCoordinates;
var gX = smoothedCoordinates.X;
var gY = smoothedCoordinates.Y;
if (EnableCorrection)
{
var diff = Correction.Instance.CorrectPoint(smoothedCoordinates);
gX = diff.X;
gY = diff.Y;
}
Left = d*x + d*gX - Width/2;
Top = d*y + d*gY - Height/2;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace YaR.Clouds.SpecialCommands
{
public class RemoveBadLinksCommand : SpecialCommand
{
public RemoveBadLinksCommand(Cloud cloud, string path, IList<string> parames): base(cloud, path, parames)
{
}
protected override MinMax<int> MinMaxParamsCount { get; } = new MinMax<int>(0);
public override Task<SpecialCommandResult> Execute()
{
Cloud.RemoveDeadLinks();
return Task.FromResult(SpecialCommandResult.Success);
}
}
} |
using GL.Events.Home;
using HK.Framework.EventSystems;
using UniRx;
using UnityEngine;
using UnityEngine.Assertions;
using DG.Tweening;
namespace GL.Home.UI
{
/// <summary>
/// フッターを制御するクラス
/// </summary>
public sealed class FooterController : MonoBehaviour
{
public enum Mode
{
/// <summary>
/// 通常モード
/// </summary>
Default,
/// <summary>
/// キャンセルモード
/// </summary>
Cancel,
}
[SerializeField]
private Transform DefaultRoot;
[SerializeField]
private Transform CancelRoot;
[SerializeField]
private Mode initialMode;
[SerializeField]
private float duration;
[SerializeField]
private Ease ease;
private RectTransform cachedTransform;
private Mode currentMode;
void Start()
{
Broker.Global.Receive<ChangeFooter>()
.SubscribeWithState(this, (x, _this) => _this.Change(x.Mode))
.AddTo(this);
this.cachedTransform = (RectTransform)this.transform;
this.ChangeImmediate(this.initialMode);
}
private void Change(FooterController.Mode mode)
{
if(this.currentMode == mode)
{
return;
}
this.CurrentRoot.DOLocalMoveY(-this.cachedTransform.rect.height, this.duration, true).SetEase(this.ease);
this.currentMode = mode;
this.CurrentRoot.DOLocalMoveY(0.0f, this.duration, true).SetEase(this.ease);
}
private void ChangeImmediate(FooterController.Mode mode)
{
this.currentMode = mode;
this.ChangeImmediate(this.DefaultRoot, mode == Mode.Default);
this.ChangeImmediate(this.CancelRoot, mode == Mode.Cancel);
}
private void ChangeImmediate(Transform root, bool isEnable)
{
var pos = root.localPosition;
pos.y = isEnable ? 0.0f : -this.cachedTransform.rect.height;
root.localPosition = pos;
}
private Transform CurrentRoot
{
get
{
switch(this.currentMode)
{
case Mode.Default:
return this.DefaultRoot;
case Mode.Cancel:
return this.CancelRoot;
default:
Assert.IsTrue(false, $"{this.currentMode}は未対応の値です");
return null;
}
}
}
}
}
|
using SetBoxTV.VideoPlayer.Interface;
using Xamarin.Forms;
[assembly: Dependency(typeof(SetBoxTV.VideoPlayer.Droid.Controls.CloseApplication))]
namespace SetBoxTV.VideoPlayer.Droid.Controls
{
class CloseApplication : ICloseApplication
{
public void closeApplication()
{
MainActivity.Instance.FinishAffinity();
}
}
} |
using UnityEngine;
namespace Entia.Experimental.Unity
{
public abstract class NodeReference : ScriptableObject
{
public abstract Node Node { get; }
}
} |
using System;
using Xunit;
namespace SharpAdbClient.Tests
{
public class AdbServerStatusTests
{
[Fact]
public void ToStringTest()
{
AdbServerStatus s = new AdbServerStatus()
{
IsRunning = true,
Version = new Version(1, 0, 32)
};
Assert.Equal("Version 1.0.32 of the adb daemon is running.", s.ToString());
s.IsRunning = false;
Assert.Equal("The adb daemon is not running.", s.ToString());
}
}
}
|
using NUnit.Framework;
using UnityAuxiliaryTools.Trigger;
using UnityAuxiliaryTools.Trigger.Factory;
namespace UnityAuxiliartyTools.Tests.Triggers
{
public class TriggerFactoryTests
{
[Test]
public void CreateRegularTrigger_RegularTriggerCreated()
{
// Arrange
var factory = new TriggerFactory();
// Act
var regularTrigger = factory.CreateRegularTrigger();
// Assert
Assert.IsTrue(regularTrigger is RegularTrigger);
}
}
} |
using Xunit;
namespace DFC.ServiceTaxonomy.IntegrationTests.Helpers
{
[CollectionDefinition("GraphCluster Integration")]
public class GraphClusterIntegrationCollection : ICollectionFixture<GraphClusterCollectionFixture>
{
}
}
|
using System.Collections.Generic;
namespace SJP.Schematic.Core
{
/// <summary>
/// Defines a database index.
/// </summary>
/// <seealso cref="IDatabaseOptional" />
public interface IDatabaseIndex : IDatabaseOptional
{
/// <summary>
/// The index name.
/// </summary>
/// <value>The name of the index.</value>
Identifier Name { get; }
/// <summary>
/// The index columns that form the primary basis of the index.
/// </summary>
/// <value>A collection of index columns.</value>
IReadOnlyCollection<IDatabaseIndexColumn> Columns { get; }
/// <summary>
/// The included or leaf columns that are also available once the key columns have been searched.
/// </summary>
/// <value>A collection of database columns.</value>
IReadOnlyCollection<IDatabaseColumn> IncludedColumns { get; }
/// <summary>
/// Indicates whether covered index columns must be unique across the index column set.
/// </summary>
/// <value><c>true</c> if the index column set must have unique values; otherwise, <c>false</c>.</value>
bool IsUnique { get; }
}
}
|
using LmpClient.Base;
namespace LmpClient.Systems.VesselPositionSys
{
public class PositionEvents : SubSystem<VesselPositionSystem>
{
/// <summary>
/// When stop warping adjust the interpolation times of long running packets
/// </summary>
public void WarpStopped()
{
System.AdjustExtraInterpolationTimes();
}
}
}
|
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mimetick.WinApp.ViewModels;
namespace Mimetick.WinApp.Tests.ViewModels
{
[TestClass]
public class ShellViewModelTests
{
[TestMethod]
public void Should_CreateVM_When_ConstructorValid()
{
var vm = new ShellViewModel();
vm.Should().NotBeNull();
}
}
}
|
namespace Roton.Emulation.Conditions
{
public interface IConditionList
{
ICondition Get(string name);
}
} |
//
// TextureX.cs
//
// Copyright (c) 2014-2015, Candlelight Interactive, LLC
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
using UnityEngine;
namespace Candlelight
{
/// <summary>
/// Extension methods for <see cref="UnityEngine.Texture"/> and subclasses.
/// </summary>
public static class TextureX
{
/// <summary>
/// A temporary render texture allocation.
/// </summary>
private static RenderTexture s_TempRenderTex;
/// <summary>
/// Gets a readable copy of the source <see cref="UnityEngine.Texture2D"/>.
/// </summary>
/// <returns>A readable copy of the source <see cref="UnityEngine.Texture2D"/>.</returns>
/// <param name="source">Source.</param>
public static Texture2D GetReadableCopy(this Texture2D source)
{
if (source == null)
{
return null;
}
Texture2D result = new Texture2D(source.width, source.height, source.format, false);
result.hideFlags = HideFlags.DontSave;
#if !UNITY_4_6 || UNITY_PRO_LICENSE
s_TempRenderTex = RenderTexture.GetTemporary(source.width, source.height);
RenderTexture.active = s_TempRenderTex;
Graphics.Blit(source, s_TempRenderTex);
result.ReadPixels(new Rect(0f, 0f, result.width, result.height), 0 , 0);
RenderTexture.ReleaseTemporary(s_TempRenderTex);
RenderTexture.active = null;
#else
try
{
result.SetPixels32(source.GetPixels32());
}
catch (UnityException)
{
result = null;
}
#endif
return result;
}
/// <summary>
/// Flood fill the specified block on the specified <see cref="UnityEngine.Texture2D"/> using the specified
/// color.
/// </summary>
/// <param name="texture">The <see cref="UnityEngine.Texture2D"/> to flood fill.</param>
/// <param name="x">The x coordinate of the block.</param>
/// <param name="y">The y coordinate of the block.</param>
/// <param name="width">Width of the block.</param>
/// <param name="height">Height of the block.</param>
/// <param name="color">Color to apply to pixels in the block.</param>
/// <param name="apply">If set to <see langword="true"/> apply results.</param>
public static void FloodFill(
this Texture2D texture, int x, int y, int width, int height, Color color, bool apply = true
)
{
int size = width*height;
Color[] colors = new Color[size];
for (int i=0; i<size; ++i)
{
colors[i] = color;
}
try
{
texture.SetPixels(x, y, width, height, colors);
if (apply)
{
texture.Apply();
}
}
catch (System.Exception e)
{
Debug.LogException(e);
}
}
}
} |
using System;
namespace PiRhoSoft.MonsterMaker
{
public class ExponentOperator : InfixOperatorExpression
{
public override ExpressionResult Evaluate(InstructionContext context)
{
var number = Left.Evaluate(context);
var exponent = Right.Evaluate(context);
if (number.Type == ExpressionResultType.Number || exponent.Type == ExpressionResultType.Number)
return new ExpressionResult((float)Math.Pow(number.Number, exponent.Number));
return new ExpressionResult(MathHelper.IntExponent(number.Integer, exponent.Integer));
}
}
}
|
using System;
using System.Runtime.Caching;
using System.Threading.Tasks;
using DryIoc;
using VaraniumSharp.Attributes;
using VaraniumSharp.Interfaces.Caching;
namespace VaraniumSharp.Initiator.Caching
{
/// <summary>
/// Factory for creating <see cref="IMemoryCacheWrapper{T}"/> instances
/// </summary>
[AutomaticContainerRegistration(typeof(IMemoryCacheWrapperFactory))]
public class MemoryCacheWrapperFactory : IMemoryCacheWrapperFactory
{
#region Constructor
/// <summary>
/// DI Constructor
/// </summary>
/// <param name="container">DryIoC intance</param>
public MemoryCacheWrapperFactory(IContainer container)
{
_container = container;
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new instance of the MemoryCacheWrapper and initialize it
/// </summary>
/// <typeparam name="T">Type of items that will be stored in the cache</typeparam>
/// <param name="policy">Cache eviction policy</param>
/// <param name="dataRetrievalFunc">Function used to retrieve items if they are not in the cache</param>
/// <returns>Initialized instance of MemoryCacheWrapper</returns>
public IMemoryCacheWrapper<T> Create<T>(CacheItemPolicy policy, Func<string, Task<T>> dataRetrievalFunc)
{
var instance = _container.Resolve<IMemoryCacheWrapper<T>>();
instance.CachePolicy = policy;
instance.DataRetrievalFunc = dataRetrievalFunc;
return instance;
}
/// <summary>
/// Creates a new instance of the MemoryCacheWrapper and initialize it with a default cache policy.
/// The default policy uses SlidingExpiration with a duration 5 minute
/// </summary>
/// <typeparam name="T">Type of items that will be stored in the cache</typeparam>
/// <param name="dataRetrievalFunc">Function used to retrieve items if they are not in the cache</param>
/// <returns>Initialized instance of MemoryCacheWrapper</returns>
public IMemoryCacheWrapper<T> CreateWithDefaultSlidingPolicy<T>(Func<string, Task<T>> dataRetrievalFunc)
{
var defaultPolicy = new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(DefaultTimeoutInMinutes)
};
return Create(defaultPolicy, dataRetrievalFunc);
}
#endregion
#region Variables
private const int DefaultTimeoutInMinutes = 5;
private readonly IContainer _container;
#endregion
}
} |
namespace Windows.UI.Xaml.Controls.Maps;
public enum MapAnimationKind
{
Default,
None,
Linear,
Bow
}
|
using System;
using NUnit.Framework;
using WodiLib.Cmn;
using WodiLib.Sys.Cmn;
using WodiLib.Test.Tools;
namespace WodiLib.Test.Cmn
{
[TestFixture]
public class VariableAddressFactoryTest
{
private static WodiLibLogger logger;
[SetUp]
public static void Setup()
{
LoggerInitializer.SetupWodiLibLoggerForDebug();
logger = WodiLibLogger.GetInstance();
}
private static readonly object[] CreateTestCaseSource =
{
new object[] {int.MinValue, true, null},
new object[] {-2000000000, true, null},
new object[] {999999, true, null},
new object[] {1000000, false, typeof(MapEventVariableAddress)},
new object[] {1099999, false, typeof(MapEventVariableAddress)},
new object[] {1100000, false, typeof(ThisMapEventVariableAddress)},
new object[] {1100009, false, typeof(ThisMapEventVariableAddress)},
new object[] {1100010, true, null},
new object[] {1599999, true, null},
new object[] {1600000, false, typeof(ThisCommonEventVariableAddress)},
new object[] {1600099, false, typeof(ThisCommonEventVariableAddress)},
new object[] {1600100, true, null},
new object[] {1999999, true, null},
new object[] {2000000, false, typeof(NormalNumberVariableAddress)},
new object[] {2099999, false, typeof(NormalNumberVariableAddress)},
new object[] {2100000, false, typeof(SpareNumberVariableAddress)},
new object[] {2999999, false, typeof(SpareNumberVariableAddress)},
new object[] {3000000, false, typeof(StringVariableAddress)},
new object[] {3999999, false, typeof(StringVariableAddress)},
new object[] {4000000, true, null},
new object[] {7999999, true, null},
new object[] {8000000, false, typeof(RandomVariableAddress)},
new object[] {8999999, false, typeof(RandomVariableAddress)},
new object[] {9000000, false, typeof(SystemVariableAddress)},
new object[] {9099999, false, typeof(SystemVariableAddress)},
new object[] {9100000, false, typeof(EventInfoAddress)},
new object[] {9179999, false, typeof(EventInfoAddress)},
new object[] {9180000, false, typeof(HeroInfoAddress)},
new object[] {9180009, false, typeof(HeroInfoAddress)},
new object[] {9180010, false, typeof(MemberInfoAddress)},
new object[] {9180059, false, typeof(MemberInfoAddress)},
new object[] {9180060, true, null},
new object[] {9189999, true, null},
new object[] {9190000, false, typeof(ThisMapEventInfoAddress)},
new object[] {9199999, false, typeof(ThisMapEventInfoAddress)},
new object[] {9200000, true, null},
new object[] {9899999, true, null},
new object[] {9900000, false, typeof(SystemStringVariableAddress)},
new object[] {9999999, false, typeof(SystemStringVariableAddress)},
new object[] {10000000, true, null},
new object[] {14899999, true, null},
new object[] {15000000, false, typeof(CommonEventVariableAddress)},
new object[] {15999999, false, typeof(CommonEventVariableAddress)},
new object[] {16000000, true, null},
new object[] {999999999, true, null},
new object[] {1000000000, false, typeof(UserDatabaseAddress)},
new object[] {1099999999, false, typeof(UserDatabaseAddress)},
new object[] {1100000000, false, typeof(ChangeableDatabaseAddress)},
new object[] {1199999999, false, typeof(ChangeableDatabaseAddress)},
new object[] {1300000000, false, typeof(SystemDatabaseAddress)},
new object[] {1399999920, false, typeof(SystemDatabaseAddress)},
new object[] {1399999921, false, typeof(SystemDatabaseAddress)},
new object[] {1399999999, false, typeof(SystemDatabaseAddress)},
new object[] {1400000000, true, null},
new object[] {2000000000, true, null},
new object[] {int.MaxValue, true, null},
};
[TestCaseSource(nameof(CreateTestCaseSource))]
public static void CreateTest(int value, bool isError, Type createdInstanceType)
{
VariableAddress instance = null;
var errorOccured = false;
try
{
instance = VariableAddressFactory.Create(value);
}
catch (Exception ex)
{
logger.Exception(ex);
errorOccured = true;
}
// エラーフラグが一致すること
Assert.AreEqual(errorOccured, isError);
if (errorOccured) return;
// 意図した型にキャストできること
Assert.AreEqual(instance.GetType(), createdInstanceType);
// セットした値が正しく取得できること
Assert.AreEqual(instance.ToInt(), value);
}
}
} |
namespace Monorepo2020.Tests.Solutions;
public class Day6Tests : SolutionTestBase<Day6, string[][]>
{
protected override long? Part1Solution => 6596;
protected override long? Part2Solution => 3219;
[Fact]
void Solve1() => TestSolve1ForInput("test1.txt", 11);
[Fact]
void Solve2() => TestSolve2ForInput("test1.txt", 6);
} |
//using System.Drawing;
//using System.Drawing.Imaging;
using ImageProcessorCore;
using ImageProcessorCore.Formats;
using Microservice.Library.Extension;
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace Microservice.Library.File
{
/// <summary>
/// 图片操作帮助类
/// </summary>
public static class ImgHelper
{
/// <summary>
/// 从文件获取图片
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static Image GetImgFromFile(string fileName)
{
return new Image(new FileStream(fileName, FileMode.Open, FileAccess.Read));
//return Image.FromFile(fileName);
}
/// <summary>
/// 从base64字符串读入图片
/// </summary>
/// <param name="base64">base64字符串</param>
/// <returns></returns>
public static Image GetImgFromBase64(string base64)
{
byte[] bytes = Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
Image img = new Image(memStream);
//Image img = Image.FromStream(memStream);
return img;
}
/// <summary>
/// 从URL格式的Base64图片获取真正的图片
/// 即去掉data:image/jpg;base64,这样的格式
/// </summary>
/// <param name="base64Url">图片Base64的URL形式</param>
/// <returns></returns>
public static Image GetImgFromBase64Url(string base64Url)
{
string base64 = GetBase64String(base64Url);
return GetImgFromBase64(base64);
}
/// <summary>
/// 压缩图片
/// 注:等比压缩
/// </summary>
/// <param name="img">原图片</param>
/// <param name="width">压缩后宽度</param>
/// <returns></returns>
public static Image CompressImg(Image img, int width)
{
return CompressImg(img, width, (int)(((double)width) / img.Width * img.Height));
}
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="img">原图片</param>
/// <param name="width">压缩后宽度</param>
/// <param name="height">压缩后高度</param>
/// <returns></returns>
public static Image CompressImg(Image img, int width, int height)
{
using (var ms = new MemoryStream())
{
img.Resize(width, height)
.Save(ms);
return new Image(ms);
}
//Bitmap bitmap = new Bitmap(img, width, height);
//return bitmap;
}
/// <summary>
/// 将图片转为base64字符串
/// </summary>
/// <param name="img">图片对象</param>
/// <returns></returns>
public static string ToBase64String(Image img)
{
return img.ToBase64String();
}
/// <summary>
/// 将图片转为base64字符串
/// 使用指定格式
/// </summary>
/// <param name="img">图片对象</param>
/// <param name="imageFormat">指定格式</param>
/// <returns></returns>
public static string ToBase64String(Image img, IImageFormat imageFormat)
{
MemoryStream memStream = new MemoryStream();
img.Save(memStream, imageFormat);
return new Image(memStream).ToBase64String();
//byte[] bytes = memStream.ToArray();
//string base64 = Convert.ToBase64String(bytes);
//return base64;
}
/// <summary>
/// 将图片转为base64字符串
/// 默认使用jpg格式,并添加data:image/jpg;base64,前缀
/// </summary>
/// <param name="img">图片对象</param>
/// <returns></returns>
public static string ToBase64StringUrl(Image img)
{
return "data:image/jpg;base64," + ToBase64String(img);
}
/// <summary>
/// 将图片转为base64字符串
/// 使用指定格式,并添加data:image/jpg;base64,前缀
/// </summary>
/// <param name="img">图片对象</param>
/// <param name="imageFormat">指定格式</param>
/// <returns></returns>
public static string ToBase64StringUrl(Image img, IImageFormat imageFormat)
{
string base64 = ToBase64String(img, imageFormat);
var type = imageFormat.GetType();
var formatName = "jpg";
if (type == typeof(JpegFormat))
{
}
else if (type == typeof(BmpFormat))
formatName = "bmp";
else if (type == typeof(PngFormat))
formatName = "png";
else if (type == typeof(GifFormat))
formatName = "gif";
return $"data:image/{formatName};base64,{base64}";
}
/// <summary>
/// 获取真正的图片base64数据
/// 即去掉data:image/jpg;base64,这样的格式
/// </summary>
/// <param name="base64UrlStr">带前缀的base64图片字符串</param>
/// <returns></returns>
public static string GetBase64String(string base64UrlStr)
{
string parttern = "^(data:image/.*?;base64,).*?$";
var match = Regex.Match(base64UrlStr, parttern);
if (match.Groups.Count > 1)
base64UrlStr = base64UrlStr.Replace(match.Groups[1].ToString(), "");
return base64UrlStr;
}
/// <summary>
/// 将图片的URL或者Base64字符串转为图片并上传到服务器,返回上传后的完整图片URL
/// </summary>
/// <param name="imgBase64OrUrl">URL地址或者Base64字符串</param>
/// <param name="dir">存储目录</param>
/// <param name="key">标识(为空时默认使用GUID)</param>
/// <returns></returns>
public static string GetImgUrl(string imgBase64OrUrl, string dir, string key = null)
{
if (imgBase64OrUrl.Contains("data:image"))
{
Image img = GetImgFromBase64Url(imgBase64OrUrl);
string fileName = $"{(key.IsNullOrEmpty() ? Guid.NewGuid().ToString() : key)}.jpg";
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (var fs = new FileStream(Path.Combine(dir, fileName), FileMode.Create, FileAccess.Write))
img.Save(fs);
return $"{dir}/{fileName}";
}
else
return imgBase64OrUrl;
}
}
}
|
using Openfox.Foxnet.Client;
using Openfox.Foxnet.Common.Protocol;
using System;
using System.Threading;
namespace Openfox.Foxnet.ConsoleClient
{
class Program
{
static void Main(string[] args)
{
const string ip = "127.0.0.1";
const int port = 7800;
Console.Title = "Foxnet Console Client";
Thread.Sleep(2500);
var conManager = new FoxnetConnectionManager(ip, port);
conManager.OnServerConnected += OnServerConnected;
conManager.Connect();
while (true)
{
Thread.Sleep(2000);
}
}
private static void OnServerConnected()
{
Console.WriteLine("Server connected.");
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace SourceGenerator.MediatR.Proxy.Internal
{
internal static class ResourceReader
{
public static string GetResource(string endWith, Type assemblyType = null)
{
var assembly = GetAssembly(assemblyType);
var resources = assembly.GetManifestResourceNames()
.Where(r => r.EndsWith(endWith))
.ToList();
if (resources.Count == 0)
{
throw new InvalidOperationException($"There is no resources that ends with '{endWith}'");
}
if (resources.Count > 1)
{
throw new InvalidOperationException($"There is more then one resource that ends with '{endWith}'");
}
var resourceName = resources.Single();
return ReadEmbeddedResource(assembly, resourceName);
}
private static Assembly GetAssembly(Type assemblyType) =>
assemblyType == null
? Assembly.GetExecutingAssembly()
: Assembly.GetAssembly(assemblyType);
private static string ReadEmbeddedResource(Assembly assembly, string name)
{
using var resourceStream = assembly.GetManifestResourceStream(name);
if (resourceStream == null)
{
return null;
}
using var streamReader = new StreamReader(resourceStream);
return streamReader.ReadToEnd();
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using IntoTheCode.Buffer;
namespace Buffer
{
[TestClass]
public class BufferTest
{
[TestMethod]
public void ITC01GetLineAndColumn()
{
string str = @"Firstline
SecondlineX
Thirdline
Z";
int line, column;
var buffer = new FlatBuffer(str);
int pos = str.IndexOf("F");
buffer.GetLineAndColumn(out line, out column, pos);
Assert.AreEqual(1, line, "find F line");
Assert.AreEqual(1, column, "find F col");
pos = str.IndexOf("X");
buffer.GetLineAndColumn(out line, out column, pos);
Assert.AreEqual(2, line, "find X line");
Assert.AreEqual(11, column, "find X col");
//Assert.AreEqual("Line 2, colomn 11", buffer.GetLineAndColumn(pos), "find X");
pos = str.IndexOf("Z");
buffer.GetLineAndColumn(out line, out column, pos);
Assert.AreEqual(4, line, "find Z line");
Assert.AreEqual(2, column, "find Z col");
// Assert.AreEqual("Line 4, colomn 2", buffer.GetLineAndColumn(pos), "find Z");
}
}
}
|
using System.IO;
using System.Linq;
using TankLib;
using TankLib.ExportFormats;
namespace DataTool.SaveLogic {
public static class Entity {
public class OverwatchEntity : IExportFormat {
public string Extension => "owentity";
protected readonly FindLogic.Combo.ComboInfo Info;
protected readonly FindLogic.Combo.EntityAsset Entity;
public const ushort VersionMajor = 1;
public const ushort VersionMinor = 1;
public OverwatchEntity(FindLogic.Combo.EntityAsset entity, FindLogic.Combo.ComboInfo info) {
Info = info;
Entity = entity;
}
public void Write(Stream stream) {
using (BinaryWriter writer = new BinaryWriter(stream)) {
writer.Write(Extension); // type identifier
writer.Write(VersionMajor);
writer.Write(VersionMinor);
writer.Write(Entity.GetNameIndex());
if (Entity.m_modelGUID != 0) {
FindLogic.Combo.ModelAsset modelInfo = Info.m_models[Entity.m_modelGUID];
writer.Write(modelInfo.GetName());
} else {
writer.Write("null");
}
if (Entity.m_effectGUID != 0) {
FindLogic.Combo.EffectInfoCombo effectInfo = Info.m_effects[Entity.m_effectGUID];
writer.Write(effectInfo.GetName());
} else {
writer.Write("null");
}
writer.Write(teResourceGUID.Index(Entity.m_GUID));
writer.Write(teResourceGUID.Index(Entity.m_modelGUID));
writer.Write(teResourceGUID.Index(Entity.m_effectGUID));
if (Entity.Children == null) {
writer.Write(0);
return;
}
writer.Write(Entity.Children.Count(x => x.m_defGUID != 0));
foreach (FindLogic.Combo.ChildEntityReference childEntityReference in Entity.Children.Where(x => x.m_defGUID != 0)) {
FindLogic.Combo.EntityAsset childEntityInfo = Info.m_entities[childEntityReference.m_defGUID];
writer.Write(childEntityInfo.GetName());
writer.Write(childEntityReference.m_hardpointGUID);
writer.Write(childEntityReference.m_identifier);
writer.Write(teResourceGUID.Index(childEntityReference.m_hardpointGUID));
writer.Write(teResourceGUID.Index(childEntityReference.m_identifier));
if (childEntityReference.m_hardpointGUID != 0) {
writer.Write(OverwatchModel.IdToString("hardpoint", teResourceGUID.Index(childEntityReference.m_hardpointGUID)));
} else {
writer.Write("null"); // erm, k
}
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ConsTemperature : ConsObj
{
// Setup relevant properties
private enum Mode { On, Off }
private string[] modeNames = { "På", "Av" };
private enum Type { TwentyFour, TwentyTwo, Twenty, Eighteen }
private string[] typeNames = { "24°", "22°", "20°", "18°" };
private Mode currentMode = Mode.On;
private Type currentType = Type.TwentyFour;
int[,] powerConsArray = new int[2, 4] {
{ 2500, 2225, 1950, 1675 }, //On
{ 0, 0, 0, 0 } //Off
};
int[,] waterConsArray = new int[2, 4] {
{ 0, 0, 0, 0 }, //On
{ 0, 0, 0, 0 } //Off
};
int[] yearlyPowerCons = new int[] { 2500*52*84, 2225 * 52 * 84, 1950 * 52 * 84, 1675 * 52 * 84 };
public bool IsOn()
{
return currentMode == Mode.On;
}
House house;
// Change of state
public override void SetType(int typeIndex)
{
base.SetType(typeIndex);
currentType = (Type)typeIndex;
SetCurrentPowerCons(powerConsArray[(int)currentMode, (int)currentType]);
}
public override void SetMode(int modeIndex)
{
base.SetType(modeIndex);
currentMode = (Mode)modeIndex;
SetCurrentPowerCons(powerConsArray[(int)currentMode, (int)currentType]);
if ((Mode)modeIndex == Mode.On) { TurnOn(); }
else if ((Mode)modeIndex == Mode.Off) { TurnOff(); }
}
public override int GetMaxCons()
{
return MaxValue(powerConsArray);
}
// Setting up ConsPanel
public override void MoveConsPanel()
{
base.MoveConsPanel();
GameObject UIButtonsFour = consPanel.GetComponent<ConsPanel>().UIButtonsFour;
UIButtonsFour.SetActive(true);
UIButton[] buttons = UIButtonsFour.GetComponentsInChildren<UIButton>();
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].GetComponentInChildren<Text>().text = typeNames[(int)((Type)i)];
if (i == (int)currentType)
{
buttons[i].SetSelected();
}
else
{
buttons[i].SetUnselected();
}
}
GameObject UIButtonsTwo = consPanel.GetComponent<ConsPanel>().UIButtonsTwo;
UIButtonsTwo.SetActive(true);
buttons = UIButtonsTwo.GetComponentsInChildren<UIButton>();
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].GetComponentInChildren<Text>().text = modeNames[(int)((Mode)i)];
if (i == (int)currentMode)
{
buttons[i].SetSelected();
}
else
{
buttons[i].SetUnselected();
}
}
SetupConsPanelCollider();
}
// Event handlers
public override void HandleOver()
{
base.HandleOver();
}
public override void HandleOut()
{
base.HandleOut();
}
public override void HandleClick()
{
base.HandleClick();
}
private void TurnOff()
{
currentMode = Mode.Off;
SetCurrentPowerCons(powerConsArray[(int)currentMode, (int)currentType]);
}
private void TurnOn()
{
currentMode = Mode.On;
SetCurrentPowerCons(powerConsArray[(int)currentMode, (int)currentType]);
}
// Used for initialization
public override void Awake()
{
base.Awake();
house = GameObject.FindObjectOfType<House>();
}
// Used for initialization
public void Start()
{
SetCurrentPowerCons(powerConsArray[(int)currentMode, (int)currentType]);
}
// Utility functions
public override void SetModeOff()
{
TurnOff();
}
public override void SetModeOn()
{
TurnOn();
}
public override void SetRandomMode()
{
if (Random.value > 0.5f)
{
TurnOn();
}
else
{
TurnOff();
}
}
public override void SetRandomType()
{
SetType((int)Mathf.Floor(Random.value * 4));
}
public override void UpdateUICons()
{
base.UpdateUICons();
Text text = consPanel.transform.Find("UICons").transform.Find("Text").GetComponent<Text>();
if (yearlyPowerCons[(int)currentType] > 1000)
{
text.text += "\n(Gj.snittlig årsforbruk: " + yearlyPowerCons[(int)currentType]/1000 + " MWh)";
}
else
{
text.text += "\n(Gj.snittlig årsforbruk: " + yearlyPowerCons[(int)currentType] + " kWh)";
}
}
}
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AliCloud.Hbr.Outputs
{
[OutputType]
public sealed class GetBackupJobsJobResult
{
/// <summary>
/// The actual size of backup job.
/// </summary>
public readonly string ActualBytes;
/// <summary>
/// The actual number of files.
/// </summary>
public readonly string ActualItems;
/// <summary>
/// The name of backup job.
/// </summary>
public readonly string BackJobName;
/// <summary>
/// The ID of backup job.
/// </summary>
public readonly string BackupJobId;
/// <summary>
/// Backup type. Valid values: `COMPLETE`(full backup).
/// </summary>
public readonly string BackupType;
/// <summary>
/// The name of target ofo OSS bucket.
/// </summary>
public readonly string Bucket;
/// <summary>
/// The size of backup job recovered.
/// </summary>
public readonly string BytesDone;
/// <summary>
/// The total size of backup job recovered.
/// </summary>
public readonly string BytesTotal;
/// <summary>
/// The completion time of backup job. UNIX time seconds.
/// </summary>
public readonly string CompleteTime;
/// <summary>
/// The creation time of backup job. UNIX time seconds.
/// </summary>
public readonly string CreateTime;
/// <summary>
/// Exclude path. String of Json list. Up to 255 characters. e.g. `"[\"/home/work\"]"`
/// </summary>
public readonly string Exclude;
/// <summary>
/// The ID of destination file system.
/// </summary>
public readonly string FileSystemId;
/// <summary>
/// The ID of the backup job.
/// </summary>
public readonly string Id;
/// <summary>
/// Include path. String of Json list. Up to 255 characters. e.g. `"[\"/var\"]"`
/// </summary>
public readonly string Include;
/// <summary>
/// The ID of target ECS instance.
/// </summary>
public readonly string InstanceId;
/// <summary>
/// The number of items restore job recovered.
/// </summary>
public readonly string ItemsDone;
/// <summary>
/// The total number of items restore job recovered.
/// </summary>
public readonly string ItemsTotal;
/// <summary>
/// File system creation time. UNIX time in seconds.
/// </summary>
public readonly string NasCreateTime;
/// <summary>
/// Backup path. e.g. `["/home", "/var"]`
/// </summary>
public readonly ImmutableArray<string> Paths;
/// <summary>
/// The IF of a backup plan.
/// </summary>
public readonly string PlanId;
/// <summary>
/// The prefix of Oss bucket files.
/// </summary>
public readonly string Prefix;
/// <summary>
/// The type of data source. Valid Values: `ECS_FILE`, `OSS`, `NAS`.
/// </summary>
public readonly string SourceType;
/// <summary>
/// The scheduled backup start time. UNIX time seconds.
/// </summary>
public readonly string StartTime;
/// <summary>
/// The status of restore job. Valid values: `COMPLETE` , `PARTIAL_COMPLETE`, `FAILED`.
/// </summary>
public readonly string Status;
/// <summary>
/// The update time of backup job. UNIX time seconds.
/// </summary>
public readonly string UpdatedTime;
/// <summary>
/// The ID of backup vault.
/// </summary>
public readonly string VaultId;
[OutputConstructor]
private GetBackupJobsJobResult(
string actualBytes,
string actualItems,
string backJobName,
string backupJobId,
string backupType,
string bucket,
string bytesDone,
string bytesTotal,
string completeTime,
string createTime,
string exclude,
string fileSystemId,
string id,
string include,
string instanceId,
string itemsDone,
string itemsTotal,
string nasCreateTime,
ImmutableArray<string> paths,
string planId,
string prefix,
string sourceType,
string startTime,
string status,
string updatedTime,
string vaultId)
{
ActualBytes = actualBytes;
ActualItems = actualItems;
BackJobName = backJobName;
BackupJobId = backupJobId;
BackupType = backupType;
Bucket = bucket;
BytesDone = bytesDone;
BytesTotal = bytesTotal;
CompleteTime = completeTime;
CreateTime = createTime;
Exclude = exclude;
FileSystemId = fileSystemId;
Id = id;
Include = include;
InstanceId = instanceId;
ItemsDone = itemsDone;
ItemsTotal = itemsTotal;
NasCreateTime = nasCreateTime;
Paths = paths;
PlanId = planId;
Prefix = prefix;
SourceType = sourceType;
StartTime = startTime;
Status = status;
UpdatedTime = updatedTime;
VaultId = vaultId;
}
}
}
|
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace Leap.Unity.Recording {
[CanEditMultipleObjects]
[CustomEditor(typeof(TransitionBehaviour), editorForChildClasses: true, isFallback = true)]
public class TransitionBehaviourEditor : CustomEditorBase<TransitionBehaviour> {
protected override void OnEnable() {
base.OnEnable();
specifyCustomDrawer("transitionState", drawIndentedTransitionState);
}
private void drawIndentedTransitionState(SerializedProperty prop) {
EditorGUI.indentLevel++;
if (prop.objectReferenceValue == null) {
GUI.contentColor = new Color(0.7f, 0.7f, 0.7f, 1);
}
EditorGUILayout.PropertyField(prop);
EditorGUI.indentLevel--;
GUI.contentColor = Color.white;
EditorGUILayout.Space();
}
public override void OnInspectorGUI() {
base.OnInspectorGUI();
if (targets.Length == 1 && Application.isPlaying) {
if (GUILayout.Button("Execute Transition")) {
target.Transition();
}
}
}
}
}
|
using System.Runtime.Serialization;
namespace MailChimp.Lists
{
[DataContract]
public class ListActivity
{
[DataMember(Name = "user_id")]
public string UserId
{
get;
set;
}
[DataMember(Name = "day")]
public string Date
{
get;
set;
}
[DataMember(Name = "emails_sent")]
public int EmailSent
{
get;
set;
}
[DataMember(Name = "unique_opens")]
public int UniqueOpens
{
get;
set;
}
[DataMember(Name = "recipient_clicks")]
public int RecipientClicks
{
get;
set;
}
[DataMember(Name = "hard_bounce")]
public int HardBounce
{
get;
set;
}
[DataMember(Name = "soft_bounce")]
public int SoftBounce
{
get;
set;
}
[DataMember(Name = "abuse_reports")]
public int AbuseReports
{
get;
set;
}
[DataMember(Name = "subs")]
public int Subscriptions
{
get;
set;
}
[DataMember(Name = "unsubs")]
public int Unsubscriptions
{
get;
set;
}
[DataMember(Name = "other_adds")]
public int OtherAdds
{
get;
set;
}
[DataMember(Name = "other_removes")]
public int OtherRemoves
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Datalayer.Gremlin
{
public class CosmosDBConfig
{
public string HostName { get; set; }
public int Port { get; set; }
public string AuthorityKey { get; set; }
public string DatabaseName { get; set; }
public string CollectionName { get; set; }
public string GenerateUserName()
{
return String.Format("/dbs/{0}/colls/{1}", DatabaseName, CollectionName);
}
}
}
|
namespace NVIDIA.PhysX.Unity
{
public class PxPlaneShape : PxSolidShape
{
#region Protected
protected override PxGeometry CreateGeometry()
{
return new PxPlaneGeometry();
}
protected override void ApplyProperties()
{
base.ApplyProperties();
if (valid)
{
}
}
#endregion
}
}
|
using UnityEngine;
namespace PoolDesignPattern
{
public class Spawner : MonoBehaviour
{
public Pool pool;
public float frequency = 0.3f;
public float radius = 1f;
private float _lastTimeSpawned;
private void OnEnable()
{
_lastTimeSpawned = Time.time;
}
private void Update()
{
if(Time.time - _lastTimeSpawned > frequency)
{
Spawn();
}
}
private void Spawn()
{
var poolItem = pool.GetAvailable();
var pos = transform.position;
pos.x += Random.Range(-radius, radius);
pos.y += Random.Range(-radius, radius);
poolItem.transform.position = pos;
poolItem.gameObject.SetActive(true);
_lastTimeSpawned = Time.time;
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, radius);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.