content stringlengths 23 1.05M |
|---|
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using LibHac.Common;
using LibHac.Diag;
using LibHac.FsSystem;
using LibHac.Util;
using static LibHac.Fs.StringTraits;
// ReSharper disable once CheckNamespace
namespace LibHac.Fs
{
/// <summary>
/// Contains functions for working with path formatting and normalization.
/// </summary>
/// <remarks>Based on FS 12.0.3 (nnSdk 12.3.1)</remarks>
public static class PathFormatter
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Result CheckHostName(ReadOnlySpan<byte> name)
{
if (name.Length == 2 && name[0] == Dot && name[1] == Dot)
return ResultFs.InvalidPathFormat.Log();
for (int i = 0; i < name.Length; i++)
{
if (name[i] == ':' || name[i] == '$')
return ResultFs.InvalidPathFormat.Log();
}
return Result.Success;
}
private static Result CheckSharedName(ReadOnlySpan<byte> name)
{
if (name.Length == 1 && name[0] == Dot)
return ResultFs.InvalidPathFormat.Log();
if (name.Length == 2 && name[0] == Dot && name[1] == Dot)
return ResultFs.InvalidPathFormat.Log();
for (int i = 0; i < name.Length; i++)
{
if (name[i] == ':')
return ResultFs.InvalidPathFormat.Log();
}
return Result.Success;
}
public static Result ParseMountName(out ReadOnlySpan<byte> newPath, out int mountNameLength,
Span<byte> outMountNameBuffer, ReadOnlySpan<byte> path)
{
Assert.SdkRequiresNotNull(path);
UnsafeHelpers.SkipParamInit(out mountNameLength);
newPath = default;
int maxMountLength = outMountNameBuffer.Length == 0
? PathTools.MountNameLengthMax + 1
: Math.Min(outMountNameBuffer.Length, PathTools.MountNameLengthMax + 1);
int mountLength;
for (mountLength = 0; mountLength < maxMountLength && path.At(mountLength) != 0; mountLength++)
{
byte c = path[mountLength];
if (c == DriveSeparator)
{
mountLength++;
break;
}
if (c == DirectorySeparator || c == AltDirectorySeparator)
{
newPath = path;
mountNameLength = 0;
return Result.Success;
}
}
if (mountLength <= 2 || path[mountLength - 1] != DriveSeparator)
{
newPath = path;
mountNameLength = 0;
return Result.Success;
}
for (int i = 0; i < mountLength; i++)
{
if (path.At(i) is (byte)'*' or (byte)'?' or (byte)'<' or (byte)'>' or (byte)'|')
return ResultFs.InvalidCharacter.Log();
}
if (!outMountNameBuffer.IsEmpty)
{
if (mountLength >= outMountNameBuffer.Length)
return ResultFs.TooLongPath.Log();
path.Slice(0, mountLength).CopyTo(outMountNameBuffer);
outMountNameBuffer[mountLength] = NullTerminator;
}
newPath = path.Slice(mountLength);
mountNameLength = mountLength;
return Result.Success;
}
public static Result SkipMountName(out ReadOnlySpan<byte> newPath, out int mountNameLength,
ReadOnlySpan<byte> path)
{
return ParseMountName(out newPath, out mountNameLength, Span<byte>.Empty, path);
}
private static Result ParseWindowsPathImpl(out ReadOnlySpan<byte> newPath, out int windowsPathLength,
Span<byte> normalizeBuffer, ReadOnlySpan<byte> path, bool hasMountName)
{
Assert.SdkRequiresNotNull(path);
UnsafeHelpers.SkipParamInit(out windowsPathLength);
newPath = default;
if (normalizeBuffer.Length != 0)
normalizeBuffer[0] = NullTerminator;
ReadOnlySpan<byte> currentPath = path;
if (hasMountName && path.At(0) == DirectorySeparator)
{
if (path.At(1) == AltDirectorySeparator && path.At(2) == AltDirectorySeparator)
{
if (normalizeBuffer.Length == 0)
return ResultFs.NotNormalized.Log();
currentPath = path.Slice(1);
}
else if (path.Length != 0 && WindowsPath.IsWindowsDrive(path.Slice(1)))
{
if (normalizeBuffer.Length == 0)
return ResultFs.NotNormalized.Log();
currentPath = path.Slice(1);
}
}
if (WindowsPath.IsWindowsDrive(currentPath))
{
int winPathLength;
for (winPathLength = 2; currentPath.At(winPathLength) != NullTerminator; winPathLength++)
{
if (currentPath[winPathLength] == DirectorySeparator ||
currentPath[winPathLength] == AltDirectorySeparator)
{
break;
}
}
if (normalizeBuffer.IsEmpty)
{
for (int i = 0; i < winPathLength; i++)
{
if (currentPath[i] == '\\')
return ResultFs.NotNormalized.Log();
}
}
if (!normalizeBuffer.IsEmpty)
{
if (winPathLength >= normalizeBuffer.Length)
return ResultFs.TooLongPath.Log();
currentPath.Slice(0, winPathLength).CopyTo(normalizeBuffer);
normalizeBuffer[winPathLength] = NullTerminator;
PathUtility.Replace(normalizeBuffer.Slice(0, winPathLength), AltDirectorySeparator,
DirectorySeparator);
}
newPath = currentPath.Slice(winPathLength);
windowsPathLength = winPathLength;
return Result.Success;
}
if (WindowsPath.IsDosDevicePath(currentPath))
{
int dosPathLength = WindowsPath.GetDosDevicePathPrefixLength();
if (WindowsPath.IsWindowsDrive(currentPath.Slice(dosPathLength)))
{
dosPathLength += 2;
}
else
{
dosPathLength--;
}
if (!normalizeBuffer.IsEmpty)
{
if (dosPathLength >= normalizeBuffer.Length)
return ResultFs.TooLongPath.Log();
currentPath.Slice(0, dosPathLength).CopyTo(normalizeBuffer);
normalizeBuffer[dosPathLength] = NullTerminator;
PathUtility.Replace(normalizeBuffer.Slice(0, dosPathLength), DirectorySeparator,
AltDirectorySeparator);
}
newPath = currentPath.Slice(dosPathLength);
windowsPathLength = dosPathLength;
return Result.Success;
}
if (WindowsPath.IsUncPath(currentPath, false, true))
{
Result rc;
ReadOnlySpan<byte> finalPath = currentPath;
if (currentPath.At(2) == DirectorySeparator || currentPath.At(2) == AltDirectorySeparator)
return ResultFs.InvalidPathFormat.Log();
int currentComponentOffset = 0;
int pos;
for (pos = 2; currentPath.At(pos) != NullTerminator; pos++)
{
if (currentPath.At(pos) == DirectorySeparator || currentPath.At(pos) == AltDirectorySeparator)
{
if (currentComponentOffset != 0)
{
rc = CheckSharedName(
currentPath.Slice(currentComponentOffset, pos - currentComponentOffset));
if (rc.IsFailure()) return rc;
finalPath = currentPath.Slice(pos);
break;
}
if (currentPath.At(pos + 1) == DirectorySeparator || currentPath.At(pos + 1) == AltDirectorySeparator)
return ResultFs.InvalidPathFormat.Log();
rc = CheckHostName(currentPath.Slice(2, pos - 2));
if (rc.IsFailure()) return rc;
currentComponentOffset = pos + 1;
}
}
if (currentComponentOffset == pos)
return ResultFs.InvalidPathFormat.Log();
if (currentComponentOffset != 0 && finalPath == currentPath)
{
rc = CheckSharedName(currentPath.Slice(currentComponentOffset, pos - currentComponentOffset));
if (rc.IsFailure()) return rc;
finalPath = currentPath.Slice(pos);
}
ref byte currentPathStart = ref MemoryMarshal.GetReference(currentPath);
ref byte finalPathStart = ref MemoryMarshal.GetReference(finalPath);
int uncPrefixLength = (int)Unsafe.ByteOffset(ref currentPathStart, ref finalPathStart);
if (normalizeBuffer.IsEmpty)
{
for (int i = 0; i < uncPrefixLength; i++)
{
if (currentPath[i] == DirectorySeparator)
return ResultFs.NotNormalized.Log();
}
}
if (!normalizeBuffer.IsEmpty)
{
if (uncPrefixLength >= normalizeBuffer.Length)
return ResultFs.TooLongPath.Log();
currentPath.Slice(0, uncPrefixLength).CopyTo(normalizeBuffer);
normalizeBuffer[uncPrefixLength] = NullTerminator;
PathUtility.Replace(normalizeBuffer.Slice(0, uncPrefixLength), DirectorySeparator, AltDirectorySeparator);
}
newPath = finalPath;
windowsPathLength = uncPrefixLength;
return Result.Success;
}
newPath = path;
windowsPathLength = 0;
return Result.Success;
}
public static Result ParseWindowsPath(out ReadOnlySpan<byte> newPath, out int windowsPathLength,
Span<byte> normalizeBuffer, ReadOnlySpan<byte> path, bool hasMountName)
{
return ParseWindowsPathImpl(out newPath, out windowsPathLength, normalizeBuffer, path, hasMountName);
}
public static Result SkipWindowsPath(out ReadOnlySpan<byte> newPath, out int windowsPathLength,
out bool isNormalized, ReadOnlySpan<byte> path, bool hasMountName)
{
isNormalized = true;
Result rc = ParseWindowsPathImpl(out newPath, out windowsPathLength, Span<byte>.Empty, path, hasMountName);
if (!rc.IsSuccess())
{
if (ResultFs.NotNormalized.Includes(rc))
{
isNormalized = false;
}
else
{
return rc;
}
}
return Result.Success;
}
private static Result ParseRelativeDotPathImpl(out ReadOnlySpan<byte> newPath, out int length,
Span<byte> relativePathBuffer, ReadOnlySpan<byte> path)
{
Assert.SdkRequiresNotNull(path);
UnsafeHelpers.SkipParamInit(out length);
newPath = default;
if (relativePathBuffer.Length != 0)
relativePathBuffer[0] = NullTerminator;
if (path.At(0) == Dot && (path.At(1) == NullTerminator || path.At(1) == DirectorySeparator ||
path.At(1) == AltDirectorySeparator))
{
if (relativePathBuffer.Length >= 2)
{
relativePathBuffer[0] = Dot;
relativePathBuffer[1] = NullTerminator;
}
newPath = path.Slice(1);
length = 1;
return Result.Success;
}
if (path.At(0) == Dot && path.At(1) == Dot)
return ResultFs.DirectoryUnobtainable.Log();
newPath = path;
length = 0;
return Result.Success;
}
public static Result ParseRelativeDotPath(out ReadOnlySpan<byte> newPath, out int length,
Span<byte> relativePathBuffer, ReadOnlySpan<byte> path)
{
return ParseRelativeDotPathImpl(out newPath, out length, relativePathBuffer, path);
}
public static Result SkipRelativeDotPath(out ReadOnlySpan<byte> newPath, out int length,
ReadOnlySpan<byte> path)
{
return ParseRelativeDotPathImpl(out newPath, out length, Span<byte>.Empty, path);
}
public static Result IsNormalized(out bool isNormalized, out int normalizedLength, ReadOnlySpan<byte> path,
PathFlags flags)
{
UnsafeHelpers.SkipParamInit(out isNormalized, out normalizedLength);
Result rc = PathUtility.CheckUtf8(path);
if (rc.IsFailure()) return rc;
ReadOnlySpan<byte> buffer = path;
int totalLength = 0;
if (path.At(0) == NullTerminator)
{
if (!flags.IsEmptyPathAllowed())
return ResultFs.InvalidPathFormat.Log();
isNormalized = true;
normalizedLength = 0;
return Result.Success;
}
if (path.At(0) != DirectorySeparator &&
!flags.IsWindowsPathAllowed() &&
!flags.IsRelativePathAllowed() &&
!flags.IsMountNameAllowed())
{
return ResultFs.InvalidPathFormat.Log();
}
if (WindowsPath.IsWindowsPath(path, false) && !flags.IsWindowsPathAllowed())
return ResultFs.InvalidPathFormat.Log();
bool hasMountName = false;
rc = SkipMountName(out buffer, out int mountNameLength, buffer);
if (rc.IsFailure()) return rc;
if (mountNameLength != 0)
{
if (!flags.IsMountNameAllowed())
return ResultFs.InvalidPathFormat.Log();
totalLength += mountNameLength;
hasMountName = true;
}
if (buffer.At(0) != DirectorySeparator && !PathUtility.IsPathStartWithCurrentDirectory(buffer) &&
!WindowsPath.IsWindowsPath(buffer, false))
{
if (!flags.IsRelativePathAllowed() || !PathUtility.CheckInvalidCharacter(buffer.At(0)).IsSuccess())
return ResultFs.InvalidPathFormat.Log();
isNormalized = false;
return Result.Success;
}
bool isRelativePath = false;
rc = SkipRelativeDotPath(out buffer, out int relativePathLength, buffer);
if (rc.IsFailure()) return rc;
if (relativePathLength != 0)
{
if (!flags.IsRelativePathAllowed())
return ResultFs.InvalidPathFormat.Log();
totalLength += relativePathLength;
if (buffer.At(0) == NullTerminator)
{
isNormalized = true;
normalizedLength = totalLength;
return Result.Success;
}
isRelativePath = true;
}
rc = SkipWindowsPath(out buffer, out int windowsPathLength, out bool isNormalizedWin, buffer, hasMountName);
if (rc.IsFailure()) return rc;
if (!isNormalizedWin)
{
if (!flags.IsWindowsPathAllowed())
return ResultFs.InvalidPathFormat.Log();
isNormalized = false;
return Result.Success;
}
if (windowsPathLength != 0)
{
if (!flags.IsWindowsPathAllowed())
return ResultFs.InvalidPathFormat.Log();
totalLength += windowsPathLength;
if (isRelativePath)
return ResultFs.InvalidPathFormat.Log();
if (buffer.At(0) == NullTerminator)
{
isNormalized = false;
return Result.Success;
}
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] == AltDirectorySeparator)
{
isNormalized = false;
return Result.Success;
}
}
}
if (PathNormalizer.IsParentDirectoryPathReplacementNeeded(buffer))
return ResultFs.DirectoryUnobtainable.Log();
rc = PathUtility.CheckInvalidBackslash(out bool isBackslashContained, buffer,
flags.IsWindowsPathAllowed() || flags.IsBackslashAllowed());
if (rc.IsFailure()) return rc;
if (isBackslashContained && !flags.IsBackslashAllowed())
{
isNormalized = false;
return Result.Success;
}
rc = PathNormalizer.IsNormalized(out isNormalized, out int length, buffer);
if (rc.IsFailure()) return rc;
totalLength += length;
normalizedLength = totalLength;
return Result.Success;
}
public static Result Normalize(Span<byte> outputBuffer, ReadOnlySpan<byte> path, PathFlags flags)
{
Result rc;
ReadOnlySpan<byte> src = path;
int currentPos = 0;
bool isWindowsPath = false;
if (path.At(0) == NullTerminator)
{
if (!flags.IsEmptyPathAllowed())
return ResultFs.InvalidPathFormat.Log();
if (outputBuffer.Length != 0)
outputBuffer[0] = NullTerminator;
return Result.Success;
}
bool hasMountName = false;
if (flags.IsMountNameAllowed())
{
rc = ParseMountName(out src, out int mountNameLength, outputBuffer.Slice(currentPos), src);
if (rc.IsFailure()) return rc;
currentPos += mountNameLength;
hasMountName = mountNameLength != 0;
}
bool isDriveRelative = false;
if (src.At(0) != DirectorySeparator && !PathUtility.IsPathStartWithCurrentDirectory(src) &&
!WindowsPath.IsWindowsPath(src, false))
{
if (!flags.IsRelativePathAllowed() || !PathUtility.CheckInvalidCharacter(src.At(0)).IsSuccess())
return ResultFs.InvalidPathFormat.Log();
outputBuffer[currentPos++] = Dot;
isDriveRelative = true;
}
if (flags.IsRelativePathAllowed())
{
if (currentPos >= outputBuffer.Length)
return ResultFs.TooLongPath.Log();
rc = ParseRelativeDotPath(out src, out int relativePathLength, outputBuffer.Slice(currentPos), src);
if (rc.IsFailure()) return rc;
currentPos += relativePathLength;
if (src.At(0) == NullTerminator)
{
if (currentPos >= outputBuffer.Length)
return ResultFs.TooLongPath.Log();
outputBuffer[currentPos] = NullTerminator;
return Result.Success;
}
}
if (flags.IsWindowsPathAllowed())
{
ReadOnlySpan<byte> originalPath = src;
if (currentPos >= outputBuffer.Length)
return ResultFs.TooLongPath.Log();
rc = ParseWindowsPath(out src, out int windowsPathLength, outputBuffer.Slice(currentPos), src,
hasMountName);
if (rc.IsFailure()) return rc;
currentPos += windowsPathLength;
if (src.At(0) == NullTerminator)
{
// Note: Bug is in the original code. Should be "currentPos + 2"
if (currentPos + 1 >= outputBuffer.Length)
return ResultFs.TooLongPath.Log();
outputBuffer[currentPos] = DirectorySeparator;
outputBuffer[currentPos + 1] = NullTerminator;
return Result.Success;
}
int skippedLength = (int)Unsafe.ByteOffset(ref MemoryMarshal.GetReference(originalPath),
ref MemoryMarshal.GetReference(src));
if (skippedLength > 0)
isWindowsPath = true;
}
rc = PathUtility.CheckInvalidBackslash(out bool isBackslashContained, src,
flags.IsWindowsPathAllowed() || flags.IsBackslashAllowed());
if (rc.IsFailure()) return rc;
byte[] srcBufferSlashReplaced = null;
try
{
if (isBackslashContained && flags.IsWindowsPathAllowed())
{
srcBufferSlashReplaced = ArrayPool<byte>.Shared.Rent(path.Length);
StringUtils.Copy(srcBufferSlashReplaced, path);
PathUtility.Replace(srcBufferSlashReplaced, AltDirectorySeparator, DirectorySeparator);
int srcOffset = (int)Unsafe.ByteOffset(ref MemoryMarshal.GetReference(path),
ref MemoryMarshal.GetReference(src));
src = srcBufferSlashReplaced.AsSpan(srcOffset);
}
rc = PathNormalizer.Normalize(outputBuffer.Slice(currentPos), out _, src, isWindowsPath, isDriveRelative);
if (rc.IsFailure()) return rc;
return Result.Success;
}
finally
{
if (srcBufferSlashReplaced is not null)
{
ArrayPool<byte>.Shared.Return(srcBufferSlashReplaced);
}
}
}
public static Result CheckPathFormat(ReadOnlySpan<byte> path, PathFlags flags)
{
return Result.Success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace mdryden.cflapi.v1.Models.Games
{
public class PlayerFieldGoalReturns : FieldGoalReturns
{
[JsonIgnore]
public int GameId { get; set; }
[JsonIgnore]
public int PlayerId
{
get { return Player.CflCentralId; }
set { Player.CflCentralId = value; }
}
[JsonProperty("player")]
public PlayerSummary Player { get; set; }
}
}
|
using System;
namespace _01._Biscuits_Factory
{
class Program
{
static void Main(string[] args)
{
int bisciutsWorkerDay = int.Parse(Console.ReadLine());
int workers = int.Parse(Console.ReadLine());
int competitorBiscuits = int.Parse(Console.ReadLine());
double production = 0;
for (int i = 1; i <= 30; i++)
{
if (i % 3 != 0)
{
production += bisciutsWorkerDay * workers;
}
else if (i % 3 == 0)
{
production += Math.Floor(bisciutsWorkerDay * workers * 0.75);
}
}
double percentage = 0;
Console.WriteLine($"You have produced {production} biscuits for the past month.");
if (production > competitorBiscuits)
{
percentage = (production - competitorBiscuits) / competitorBiscuits * 100;
Console.WriteLine($"You produce {percentage:f2} percent more biscuits.");
}
else
{
percentage = (competitorBiscuits - production) / competitorBiscuits * 100;
Console.WriteLine($"You produce {percentage:f2} percent less biscuits.");
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
namespace Contoso.FraudProtection.ApplicationCore.Entities.FraudProtectionApiModels
{
public abstract class BaseAssessmentResponse
{
public string MerchantRuleDecision { get; set; }
public int RiskScore { get; set; }
public string ReasonCodes { get; set; }
}
}
|
using System;
using FarsiLibrary.Win.BaseClasses;
using FarsiLibrary.Win.Enums;
namespace FarsiLibrary.Win.Drawing
{
public class FAPainterFactory
{
private static readonly FAPainterOffice2000 PainterOffice2000;
private static readonly FAPainterOffice2003 PainterOffice2003;
private static readonly FAPainterOffice2007 PainterOffice2007;
private static readonly FAPainterWindowsXP PainterWinXP;
/// <summary>
/// Ctor. Creates know painter types.
/// </summary>
static FAPainterFactory()
{
PainterOffice2000 = new FAPainterOffice2000();
PainterOffice2003 = new FAPainterOffice2003();
PainterOffice2007 = new FAPainterOffice2007();
PainterWinXP = new FAPainterWindowsXP();
}
/// <summary>
/// Returns a IFAPainter implementation based on state
/// of the control.
/// </summary>
/// <param name="control"></param>
/// <returns></returns>
public static IFAPainter GetPainter(BaseStyledControl control)
{
if(control == null)
throw new InvalidOperationException("Control can not be null");
if (!control.UseThemes || control.Theme == ThemeTypes.Office2000)
return PainterOffice2000;
if (control.UseThemes && control.Theme == ThemeTypes.Office2007)
return PainterOffice2007;
if (control.UseThemes && control.Theme == ThemeTypes.Office2003)
return PainterOffice2003;
if (control.UseThemes && control.Theme == ThemeTypes.WindowsXP)
return PainterWinXP;
return PainterOffice2000;
}
}
} |
using Microsoft.Extensions.Logging;
using Open.ChannelExtensions;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace PlateManager
{
internal class UploadProcessor : ICommand
{
private readonly UploadProcessorOptions _options;
private readonly IEnumerable<IWorkItemGenerator> _generators;
private readonly ILogger<UploadProcessor> _logger;
public UploadProcessor(UploadProcessorOptions options, IEnumerable<IWorkItemGenerator> generators, ILogger<UploadProcessor> logger)
{
_options = options;
_generators = generators;
_logger = logger;
}
public Task RunAsync(CancellationToken token)
{
int _count = 0;
int _total = 0;
return Channel.CreateBounded<string>(capacity: 100)
.Source(_options.Files, token)
.TransformMany(ProcessFile, capacity: 10000, token: token)
.ReadAllConcurrentlyAsync(_options.UploaderCount, async action =>
{
try
{
var count = Interlocked.Increment(ref _count);
await action(count, _total, token);
}
catch (Exception e)
{
_logger.LogError(e, "Unexpected error running task");
}
});
IEnumerable<Func<int, int, CancellationToken, Task>> ProcessFile(string file)
{
_logger.LogInformation("Adding {File}", file);
foreach (var generator in _generators)
{
foreach (var task in generator.GenerateWorkItems(file, _options.BaseUrl, _options.AzureContainer))
{
yield return task;
Interlocked.Increment(ref _total);
}
}
}
}
}
}
|
using Bonsai;
using Bonsai.Design.Visualizers;
[assembly: TypeVisualizer(typeof(BooleanTimeSeriesVisualizer), Target = typeof(bool))]
namespace Bonsai.Design.Visualizers
{
public class BooleanTimeSeriesVisualizer : TimeSeriesVisualizerBase
{
public BooleanTimeSeriesVisualizer()
{
Capacity = 640;
}
public int Capacity { get; set; }
internal override RollingGraphView CreateView()
{
var view = new BooleanTimeSeriesView();
view.Capacity = Capacity;
view.HandleDestroyed += delegate
{
Capacity = view.Capacity;
};
return view;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GetSuspicion : MonoBehaviour
{
[SerializeField]PlayerController playerController;
RectTransform rectTf;
// Start is called before the first frame update
void Start()
{
rectTf = GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
RectTransform r = rectTf;
r.localScale = new Vector3(playerController.GetSuspicion() / 100, 1f, 1f);
rectTf = r;
}
}
|
using System.Windows;
namespace VVMConnection
{
//TODO methodはstaticなのと結び付けたい
//TODO Fileダイアログとか
public class MessageBox
{
public string MessageBoxText { get; set; } = string.Empty;
public string Caption { get; set; } = string.Empty;
public MessageBoxButton Button { get; set; } = MessageBoxButton.OK;
public MessageBoxImage Icon { get; set; } = MessageBoxImage.None;
public MessageBoxResult DefaultResult { get; set; } = MessageBoxResult.None;
public MessageBoxOptions Options { get; set; } = MessageBoxOptions.None;
public bool? Show()
{
return Show(MessageBoxText);
}
public bool? Show(string messageBoxText)
{
switch (System.Windows.MessageBox.Show(messageBoxText, Caption, Button, Icon, DefaultResult, Options))
{
case MessageBoxResult.OK:
case MessageBoxResult.Yes:
return true;
case MessageBoxResult.No:
case MessageBoxResult.Cancel:
return false;
default:
return null;
}
}
}
}
|
namespace OrchardCore.Environment.Extensions.Features
{
public class InternalFeatureInfo : IFeatureInfo
{
public InternalFeatureInfo(
string id,
IExtensionInfo extensionInfo)
{
Id = id;
Name = id;
Priority = 0;
Category = null;
Description = null;
DefaultTenantOnly = false;
Extension = extensionInfo;
Dependencies = new string[0];
}
public string Id { get; }
public string Name { get; }
public int Priority { get; }
public string Category { get; }
public string Description { get; }
public bool DefaultTenantOnly { get; }
public IExtensionInfo Extension { get; }
public string[] Dependencies { get; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
internal partial class Interop
{
internal static partial class Oleaut32
{
[Flags]
public enum FADF : ushort
{
AUTO = 0x0001,
STATIC = 0x0002,
EMBEDDED = 0x0004,
FIXEDSIZE = 0x0010,
RECORD = 0x0020,
HAVEIID = 0x0040,
HAVEVARTYPE = 0x0080,
BSTR = 0x0100,
UNKNOWN = 0x0200,
DISPATCH = 0x0400,
VARIANT = 0x0800
}
}
}
|
using System.Collections.Generic;
using System.Data.Common;
namespace football.history.api.Repositories.PointDeduction
{
public interface IPointDeductionRepository
{
List<PointDeductionModel> GetPointDeductions(long competitionId);
}
public class PointDeductionRepository : IPointDeductionRepository
{
private readonly IDatabaseConnection _connection;
private readonly IPointDeductionCommandBuilder _queryBuilder;
public PointDeductionRepository(IDatabaseConnection connection, IPointDeductionCommandBuilder queryBuilder)
{
_connection = connection;
_queryBuilder = queryBuilder;
}
public List<PointDeductionModel> GetPointDeductions(long competitionId)
{
_connection.Open();
var cmd = _queryBuilder.Build(_connection, competitionId);
var pointsDeductions = GetPointDeductionModels(cmd);
_connection.Close();
return pointsDeductions;
}
private static List<PointDeductionModel> GetPointDeductionModels(DbCommand cmd)
{
var pointDeductions = new List<PointDeductionModel>();
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
var pointDeductionModel = GetPointDeductionModel(reader);
pointDeductions.Add(pointDeductionModel);
}
return pointDeductions;
}
private static PointDeductionModel GetPointDeductionModel(DbDataReader reader)
{
return new(
Id: reader.GetInt64(0),
CompetitionId: reader.GetInt64(1),
PointsDeducted: reader.GetInt16(2),
TeamId: reader.GetInt64(3),
TeamName: reader.GetString(4),
Reason: reader.GetString(5));
}
}
}
|
namespace OJS.Web.Infrastructure.Filters
{
using System;
using System.Collections;
using System.Web.Mvc;
using OJS.Web.Common.Extensions;
using OJS.Web.Infrastructure.Filters.Contracts;
public sealed class ActionFilterDispatcher : IActionFilter
{
private readonly Func<Type, IEnumerable> container;
public ActionFilterDispatcher(Func<Type, IEnumerable> container) => this.container = container;
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var attributes = filterContext.ActionDescriptor.GetAppliedCustomAttributes();
foreach (var attribute in attributes)
{
var filters = this.GetActionFilters(attribute);
foreach (dynamic actionFilter in filters)
{
actionFilter.OnActionExecuting((dynamic)attribute, filterContext);
}
}
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
var attributes = filterContext.ActionDescriptor.GetAppliedCustomAttributes();
foreach (var attribute in attributes)
{
var filters = this.GetActionFilters(attribute);
foreach (dynamic actionFilter in filters)
{
actionFilter.OnActionExecuted((dynamic)attribute, filterContext);
}
}
}
private IEnumerable GetActionFilters(Attribute attribute)
{
var filterType = typeof(IActionFilter<>).MakeGenericType(attribute.GetType());
var filters = this.container.Invoke(filterType);
return filters;
}
}
} |
using RestaurantReviews.Models.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace RestaurantReviews.Models
{
public class Restaurant:IReviewable
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<Review> Reviews { get; set; }
public string PhoneNumber { get; set; }
public string City { get; set; }
public string State { get; set; }
[JsonIgnore]
public double AvgRating { get; set; }
public double CalculateAverageRating()
{
AvgRating = 0;
foreach (var i in Reviews)
{
AvgRating += i.Rating;
}
return (double)(AvgRating /= Reviews.Count);
}
public void AddReview(Review review)
{
Reviews.Add(review);
}
}
}
|
using System;
using CafeLib.Core.Data;
namespace CafeLib.Data
{
/// <summary>
/// Data access layer storage interface.
/// </summary>
public interface IStorage : IDisposable
{
IRepository<T> CreateRepository<T>() where T : class, IEntity;
IRepository<T> GetRepository<T>() where T : class, IEntity;
void Close();
}
}
|
using RestSharp.Deserializers;
namespace NemSharp.Request.Responses.Account
{
public class AccountInfo
{
[DeserializeAs(Name = "address")]
public string Address { get; set; }
[DeserializeAs(Name = "balance")]
public int Balance { get; set; }
[DeserializeAs(Name = "vestedBalance")]
public int VestedBalance { get; set; }
[DeserializeAs(Name = "importance")]
public float Importance { get; set; }
[DeserializeAs(Name = "publicKey")]
public string PublicKey { get; set; }
[DeserializeAs(Name = "label")]
public string Label { get; set; }
}
}
|
/**
Copyright 2014 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System.Xml;
using ccl.ShaderNodes.Sockets;
using ccl.Attributes;
namespace ccl.ShaderNodes
{
public class NoiseInputs : Inputs
{
public VectorSocket Vector { get; set; }
public FloatSocket Scale { get; set; }
public FloatSocket Detail { get; set; }
public FloatSocket Distortion { get; set; }
public NoiseInputs(ShaderNode parentNode)
{
Vector = new VectorSocket(parentNode, "Vector");
AddSocket(Vector);
Scale = new FloatSocket(parentNode, "Scale");
AddSocket(Scale);
Detail = new FloatSocket(parentNode, "Detail");
AddSocket(Detail);
Distortion = new FloatSocket(parentNode, "Distortion");
AddSocket(Distortion);
}
}
public class NoiseOutputs : Outputs
{
public ColorSocket Color { get; set; }
public FloatSocket Fac { get; set; }
public NoiseOutputs(ShaderNode parentNode)
{
Color = new ColorSocket(parentNode, "Color");
AddSocket(Color);
Fac = new FloatSocket(parentNode, "Fac");
AddSocket(Fac);
}
}
[ShaderNode("noise_texture")]
public class NoiseTexture : TextureNode
{
public NoiseInputs ins => (NoiseInputs)inputs;
public NoiseOutputs outs => (NoiseOutputs)outputs;
public NoiseTexture() : this("a noise texture") { }
public NoiseTexture(string name)
: base(ShaderNodeType.NoiseTexture, name)
{
inputs = new NoiseInputs(this);
outputs = new NoiseOutputs(this);
ins.Scale.Value = 1.0f;
ins.Detail.Value = 2.0f;
ins.Distortion.Value = 0.0f;
}
internal override void ParseXml(XmlReader xmlNode)
{
Utilities.Instance.get_float4(ins.Vector, xmlNode.GetAttribute("vector"));
Utilities.Instance.get_float(ins.Detail, xmlNode.GetAttribute("detail"));
Utilities.Instance.get_float(ins.Distortion, xmlNode.GetAttribute("distortion"));
Utilities.Instance.get_float(ins.Scale, xmlNode.GetAttribute("scale"));
}
}
}
|
using System.Collections.Generic;
namespace FluentNHibernate.AspNet.Identity.Entities
{
public class AspNetRole
{
internal AspNetRole()
{
AspNetUserRoles = new List<AspNetUserRole>();
}
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<AspNetUserRole> AspNetUserRoles { get; set; }
}
} |
using AirCC.Portal.AppService.ApplicationDtos;
using AirCC.Portal.Domain;
using AutoMapper;
namespace AirCC.Portal.AppService
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
#region Input
CreateMap<ApplicationInput, Application>();
CreateMap<CreateConfigurationInput, ApplicationConfiguration>();
CreateMap<ApplicationConfiguration, ConfigurationListOutput>();
#endregion
#region Output
CreateMap<Application, ApplicationListOutput>();
CreateMap<Application, ApplicationInput>();
#endregion
}
}
}
|
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
//Copyright © 2014 Vincent Simonetti
using System.Drawing;
namespace Sce.Atf.Drawing
{
/// <summary>
/// Brush that paints an area with a solid color
/// </summary>
public interface IAtfSolidColorBrush : IAtfBrush
{
/// <summary>
/// Gets and sets the color of the solid color brush
/// </summary>
Color Color
{
get;
set;
}
}
}
|
using Com.Game.Data;
using Com.Game.Manager;
using System;
namespace Com.Game.Module
{
public class Reward_coupon : RewardItemBase
{
public Reward_coupon() : base(ERewardType.Reward_coupon)
{
}
public override void Init(string[] param)
{
base.Init(param);
if (base.Valid)
{
base.Num = 1;
SysCouponVo dataById = BaseDataMgr.instance.GetDataById<SysCouponVo>(param[2]);
if (dataById != null)
{
if (dataById.mother_type == 1)
{
SysHeroMainVo dataById2 = BaseDataMgr.instance.GetDataById<SysHeroMainVo>(dataById.mother_id);
if (dataById2 != null)
{
base.SIcon = dataById2.avatar_icon;
base.BIcon = dataById2.Loading_icon;
}
}
else if (dataById.mother_type == 2)
{
SysHeroSkinVo dataById3 = BaseDataMgr.instance.GetDataById<SysHeroSkinVo>(dataById.mother_id);
if (dataById3 != null)
{
base.SIcon = dataById3.avatar_icon;
base.BIcon = dataById3.Loading_icon;
}
}
base.ExtraData = dataById;
base.TypeDes = LanguageManager.Instance.GetStringById("Currency_Coupon");
base.Quality = dataById.quality;
base.Valid = true;
}
}
}
}
}
|
namespace Zaabee.Utf8Json;
public static partial class Utf8JsonExtensions
{
public static Task<TValue?> FromStreamAsync<TValue>(this Stream? stream,
IJsonFormatterResolver? resolver = null) =>
Utf8JsonHelper.FromStreamAsync<TValue>(stream, resolver);
public static Task<object?> FromStreamAsync(this Stream? stream, Type type,
IJsonFormatterResolver? resolver = null) =>
Utf8JsonHelper.FromStreamAsync(type, stream, resolver);
} |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace StockExchange.Web.Models.DataTables
{
/// <summary>
/// Response model send to a DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class DataTableResponse<T>
{
/// <summary>
/// Draw
/// </summary>
[JsonProperty(PropertyName = "draw")]
public int Draw { get; set; }
/// <summary>
/// Total number of items
/// </summary>
[JsonProperty(PropertyName = "recordsTotal")]
public int RecordsTotal { get; set; }
/// <summary>
/// Number of records after filtering
/// </summary>
[JsonProperty(PropertyName = "recordsFiltered")]
public int RecordsFiltered { get; set; }
/// <summary>
/// Filtered data
/// </summary>
[JsonProperty(PropertyName = "data")]
public IEnumerable<T> Data { get; set; }
/// <summary>
/// Error if any occurred
/// </summary>
[JsonProperty(PropertyName = "error")]
public string Error { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Vim.UnitTest
{
public static class Extensions
{
#region Semaphore
internal static SemaphoreDisposer DisposableWait(this Semaphore semaphore, CancellationToken cancellationToken)
{
if (cancellationToken.CanBeCanceled)
{
var signalledIndex = WaitHandle.WaitAny(new[] { semaphore, cancellationToken.WaitHandle });
if (signalledIndex != 0)
{
cancellationToken.ThrowIfCancellationRequested();
throw new Exception("Unreacheable");
}
}
else
{
semaphore.WaitOne();
}
return new SemaphoreDisposer(semaphore);
}
internal static Task<SemaphoreDisposer> DisposableWaitAsync(this Semaphore semaphore, CancellationToken cancellationToken)
{
return Task.Factory.StartNew(
() => DisposableWait(semaphore, cancellationToken),
cancellationToken,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
internal readonly struct SemaphoreDisposer : IDisposable
{
private readonly Semaphore _semaphore;
public SemaphoreDisposer(Semaphore semaphore)
{
_semaphore = semaphore;
}
public void Dispose()
{
_semaphore.Release();
}
}
#endregion
}
}
|
@{
ViewBag.Title = "显示分页信息";
ViewBag.Description = "本示例演示如何显示分页相关信息,如总页数、总记录数及当前页数等。";
}
@model PagedList<Article>
@Html.Partial("_ArticleTable", Model)
<div><div style="float:left;width:50%">共 @Model.TotalPageCount 页 @Model.TotalItemCount 条记录,当前为第 @Model.CurrentPageIndex 页</div>
@Html.Pager(Model).Options(o=>o.SetPageIndexParameterName("id").SetPagerItemTemplate(" {0}").AddHtmlAttribute("style","float:right"))</div>
@section Scripts{@{Html.RegisterMvcPagerScriptResource();}}
|
using MimeKit;
using System.Linq;
using System.Collections.Generic;
/*
* Name: Message.cs
* Author: Namchok Singhachai
* Description: Message for sending an email.
*/
namespace EmailService
{
public class Message
{
public List<MailboxAddress> To { set; get; } // An email for sending
public string Subject { set; get; } // The subject of an email
public string Content { set; get; } // The conten of an email
public string HtmlText { set; get; } // The html in an email (Optional)
/*
* Name: Message
* Parametor: to(IEnumerable<string>), subject(string), content(String)
* Author: Namchok Singhachai
* Description: Setting a messages.
*/
public Message(IEnumerable<string> to, string subject, string content)
{
To = new List<MailboxAddress>();
To.AddRange(to.Select(x => new MailboxAddress(x)));
Subject = subject;
Content = content;
} // End Message
} // End Message Class
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CryptoNews.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SinglePost : ContentPage
{
public SinglePost(string blogPostUrl)
{
InitializeComponent();
webView.Source = blogPostUrl;
}
protected async override void OnAppearing()
{
base.OnAppearing();
await progressBar.ProgressTo(0.9, 900, Easing.SpringIn);
}
private void webView_Navigating(object sender, WebNavigatingEventArgs e)
{
progressBar.IsVisible = true;
}
private void webView_Navigated(object sender, WebNavigatedEventArgs e)
{
progressBar.IsVisible = false;
}
}
} |
using System.Collections.Generic;
namespace WebRtcNet
{
/// <summary>
/// <seealso href="http://www.w3.org/TR/webrtc/#rtcicetransportpolicy-enum"/>
/// </summary>
public enum RtcIceTransportPolicy
{
/// <summary>
/// The ICE engine must not send or receive any packets at this point.
/// </summary>
None,
/// <summary>
/// The ICE engine must only use media relay candidates such as candidates
/// passing through a TURN server. This can be used to reduce leakage of
/// IP addresses in certain use cases.
/// </summary>
Relay,
/// <summary>
/// The ICE engine may use any type of candidates when this value is specified.
/// </summary>
All,
};
/// <summary>
/// <seealso href="http://www.w3.org/TR/webrtc/#rtcbundlepolicy-enum"/>
/// </summary>
public enum RtcBundlePolicy
{
/// <summary>
/// Gather ICE candidates for each media type in use (audio, video, and data).
/// If the remote endpoint is not BUNDLE-aware, negotiate only one audio and video
/// track on separate transports.
/// </summary>
Balanced,
/// <summary>
/// Gather ICE candidates for each track.If the remote endpoint is
/// not BUNDLE - aware, negotiate all media tracks on separate transports.
/// </summary>
MaxCompat,
/// <summary>
/// Gather ICE candidates for only one track. If the remote endpoint is
/// not BUNDLE-aware, negotiate only one media track.
/// </summary>
MaxBundle
};
/// <summary>
/// <seealso href="http://www.w3.org/TR/webrtc/#rtcconfiguration-type"/>
/// </summary>
public class RtcConfiguration
{
public RtcConfiguration()
:this(null)
{
}
public RtcConfiguration(IEnumerable<RtcIceServer> servers)
{
IceServers = servers == null ? new List<RtcIceServer>() : new List<RtcIceServer>(servers);
IceTransportPolicy = RtcIceTransportPolicy.All;
BundlePolicy = RtcBundlePolicy.Balanced;
PeerIdentity = null;
}
/// A list containing URIs of servers available to be used by ICE, such as STUN and TURN server.
public List<RtcIceServer> IceServers;
/// Indicates which candidates the ICE engine is allowed to use.
public RtcIceTransportPolicy IceTransportPolicy;
/// Indicates which BundlePolicy to use. Defaults to "Balanced"
public RtcBundlePolicy BundlePolicy;
/// Sets the target peer identity for the RTCPeerConnection. The RTCPeerConnection will establish
/// a connection to a remote peer unless it can be successfully authenticated with the provided name.
public string PeerIdentity;
};
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using SqlFu.Builders;
using SqlFu.Builders.Expressions;
using SqlFu.Mapping;
using SqlFu.Providers;
namespace SqlFu.Configuration.Internals
{
public class TableInfo
{
protected TableInfo()
{
}
public TableInfo(Type t, IManageConverters converter, TableName name = null)
{
Type = t;
Converter = converter;
TableName = name ?? new TableName(t.Name);
Columns =
t.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.IsProperty())
.Cast<PropertyInfo>()
.Select((m, idx) => new ColumnInfo(this, m)
{
PocoIdx = idx,
HasConverter = converter.HasConverter(m.PropertyType)
}).ToArray();
}
public ColumnInfo this[string propertyName] => Columns.FirstOrDefault(d => d.PropertyInfo.Name == propertyName);
public string GetIdentityColumnName() => Columns.FirstOrDefault(d => d.IsIdentity)?.Name??null;
public string[] GetColumnNames(IEnumerable<string> properties=null)
=> (properties??Columns.Select(d=>d.PropertyInfo.Name)).Select(p => this[p]).Where(d => !d.IgnoreRead).Select(d => d.Name).ToArray();
public object ConvertWriteValue(string propertyName, object value)
{
var p=this[propertyName];
return p.ConvertWritableValue(value);
}
public ColumnInfo[] Columns { get; }
Dictionary<string, TableSqlCache> _cache = new Dictionary<string, TableSqlCache>();
object _sync = new object();
public TableSqlCache GetSqlCache(string providerId)
{
lock (_sync)
{
return _cache.GetValueOrCreate(providerId, () => new TableSqlCache());
}
}
public PagedBuilderResult PagedSql { get; set; }
public string EscapeName(IEscapeIdentifier provider, TableName name = null)
{
name = name ?? TableName;
return provider.EscapeTableName(name);
}
public Type Type { get; internal set; }
public IManageConverters Converter { get; set; }
/// <summary>
/// Gets table name and schema
/// </summary>
public TableName TableName { get; set; }
public override string ToString()
{
return $"[Tableinfo]{Type} as {TableName}";
}
}
public interface ITableInfo
{
TableName TableName { get; set; }
}
public interface IIgnoreColumns<T>
{
/// <summary>
/// Properties will be always ignored read/write
/// </summary>
/// <param name="properties"></param>
void IgnoreProperties(params Expression<Func<T, object>>[] properties);
}
public interface ITableInfo<T> : IIgnoreColumns<T>,ITableInfo
{
IConfigurePropertyInfo<R> Property<R>(Expression<Func<T, R>> property);
}
public class TableInfo<T>:ITableInfo<T>
{
private readonly TableInfo _info;
private TableName _tableName;
public TableInfo(TableInfo info)
{
_info = info;
}
public void IgnoreProperties(params Expression<Func<T, object>>[] properties)
{
foreach (var prop in properties)
{
var info = _info[prop.GetPropertyName()];
info.IgnoreWrite= info.IgnoreRead = true;
}
}
public IConfigurePropertyInfo<R> Property<R>(Expression<Func<T, R>> property)
=>new ColumnInfo<R>(_info[property.GetPropertyName()]);
public TableName TableName
{
get { return _info.TableName; }
set { _info.TableName = value; }
}
}
} |
using System;
using System.Reflection;
namespace GraphExt
{
public static class ReflectionExtensions
{
public static object GetValue(this MemberInfo memberInfo, object target)
{
return memberInfo switch
{
FieldInfo fi => fi.GetValue(target),
PropertyInfo pi => pi.GetValue(target),
_ => throw new NotImplementedException()
};
}
public static T GetValue<T>(this MemberInfo memberInfo, object target)
{
return (T)GetValue(memberInfo, target);
}
}
} |
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the Apache License. See LICENSE.txt in the project root for license information.
namespace Masa.Auth.Contracts.Admin.Infrastructure.Enums;
public enum ClientTypes
{
Web = 1,
Spa = 2,
Native = 3,
Machine = 4,
Device = 5
}
|
using L2ScriptMaker.Models.Npc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using L2ScriptMaker.Core.Files;
using L2ScriptMaker.Core.Parser;
using L2ScriptMaker.Models.Dto;
using L2ScriptMaker.Core.Mapper;
namespace L2ScriptMaker.Services.Npc
{
public class NpcDataService : INpcDataService
{
private readonly ModelMapper<NpcDataDto> _mapper = new ModelMapper<NpcDataDto>();
private const string StartPrefix = "npc_begin";
private const string EndPrefix = "npc_end";
public IEnumerable<string> Collect(IEnumerable<string> lines)
{
return ScriptLoader.Collect(lines, StartPrefix, EndPrefix);
}
public NpcDataDto Parse(string record)
{
ParsedData data = ParseService.Parse(record);
NpcDataDto npcDataDto = _mapper.Map(data);
return npcDataDto;
// return InlineParser.Parse(data);
}
public IEnumerable<NpcDataDto> Parse(IEnumerable<string> data)
{
IEnumerable<NpcDataDto> result = data.Select(Parse);
return result;
}
public ServiceResult Generate(string NpcDataDir, string NpcDataFile, IProgress<int> progress)
{
throw new NotImplementedException();
}
// npc_begin warrior 20001 [gremlin] category={} level=1 exp=0
public static string Print(NpcData model)
{
throw new NotImplementedException();
//return $"npc_begin" +
// $"\t{model.Type}" +
// $"\t{model.Id}" +
// $"\t[{model.Name}]";
}
}
}
|
/*
* [The BSD 3-Clause License]
* Copyright (c) 2015, Samuel Suffos
* 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.
*
* 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 Antlr.Runtime;
using Antlr.Runtime.Tree;
using Matlab.Nodes;
using Matlab.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Matlab.Recognizer
{
internal static class TreeToNodeBuilder
{
#region STATIC METHODS:
#region MAIN METHODS:
public static FileNode Build(string path, ITree tree)
{
Checker.CheckNotNull(path);
Checker.CheckNotNull(tree);
FileNode node = (FileNode)TreeToNodeBuilder.BuildNode(tree);
node.Path = path;
return node;
}
#endregion
#region BUILDER METHODS:
private static MNode BuildNode(ITree tree)
{
MNode node = TreeToNodeBuilder.BuildNode(tree.Type);
if (node is InternalNode)
{
InternalNode internalNode = (InternalNode)node;
internalNode.Line = tree.Line;
internalNode.Column = tree.CharPositionInLine + 1;
internalNode.Text = tree.Text;
}
for (int i = 0; i < tree.ChildCount; i++)
{
MNode childNode = TreeToNodeBuilder.BuildNode(tree.GetChild(i));
node.Children.Add(childNode);
}
return node;
}
private static MNode BuildNode(int type)
{
switch (type)
{
case MatlabParser.CLASSFILE:
return new ClassFileNode();
case MatlabParser.FUNCTIONFILE:
return new FunctionFileNode();
case MatlabParser.SCRIPTFILE:
return new ScriptFileNode();
case MatlabParser.FUNCTION:
return new FunctionNode();
case MatlabParser.CLASSDEF:
return new ClassNode();
case MatlabParser.EVENTSECTION:
return new EventSectionNode();
case MatlabParser.PROPERTYSECTION:
return new PropertySectionNode();
case MatlabParser.METHODSECTION:
return new MethodSectionNode();
case MatlabParser.ENUMERATIONSECTION:
return new EnumerationSectionNode();
case MatlabParser.EVENT:
return new EventNode();
case MatlabParser.PROPERTY:
return new PropertyNode();
case MatlabParser.REGULARMETHOD:
return new RegularMethodNode();
case MatlabParser.EXTERNALMETHOD:
return new ExternalMethodNode();
case MatlabParser.ENUMERATION:
return new EnumerationNode();
case MatlabParser.ATTRIBUTE:
return new AttributeNode();
case MatlabParser.ACTION:
return new ActionNode();
case MatlabParser.ASSIGN:
return new AssignmentNode();
case MatlabParser.EXCLAMATION:
return new BangNode();
case MatlabParser.BREAK:
return new BreakNode();
case MatlabParser.CONTINUE:
return new ContinueNode();
case MatlabParser.FOR:
return new ForNode();
case MatlabParser.GLOBAL:
return new GlobalNode();
case MatlabParser.IFELSE:
return new IfNode();
case MatlabParser.NESTEDFUNCTION:
return new NestedFunctionNode();
case MatlabParser.PARFOR:
return new ParforNode();
case MatlabParser.PERSISTENT:
return new PersistentNode();
case MatlabParser.RETURN:
return new ReturnNode();
case MatlabParser.SPMD:
return new SpmdNode();
case MatlabParser.SWITCHCASE:
return new SwitchNode();
case MatlabParser.TRYCATCH:
return new TryNode();
case MatlabParser.WHILE:
return new WhileNode();
case MatlabParser.IF:
return new IfPartNode();
case MatlabParser.ELSEIF:
return new ElseIfPartNode();
case MatlabParser.ELSE:
return new ElsePartNode();
case MatlabParser.SWITCH:
return new SwitchPartNode();
case MatlabParser.CASE:
return new CasePartNode();
case MatlabParser.OTHERWISE:
return new OtherwisePartNode();
case MatlabParser.TRY:
return new TryPartNode();
case MatlabParser.CATCH:
return new CatchPartNode();
case MatlabParser.COLON:
return new ColonNode();
case MatlabParser.HCAT:
return new HCatNode();
case MatlabParser.VCAT:
return new VCatNode();
case MatlabParser.PLUS:
return new PlusNode();
case MatlabParser.MINUS:
return new MinusNode();
case MatlabParser.TIMES:
return new TimesNode();
case MatlabParser.MTIMES:
return new MTimesNode();
case MatlabParser.LDIV:
return new LDivNode();
case MatlabParser.MLDIV:
return new MLDivNode();
case MatlabParser.RDIV:
return new RDivNode();
case MatlabParser.MRDIV:
return new MRDivNode();
case MatlabParser.POW:
return new PowNode();
case MatlabParser.MPOW:
return new MPowNode();
case MatlabParser.TRANS:
return new TransNode();
case MatlabParser.CTRANS:
return new CTransNode();
case MatlabParser.EQ:
return new EqNode();
case MatlabParser.NOTEQ:
return new NotEqNode();
case MatlabParser.LT:
return new LtNode();
case MatlabParser.LTEQ:
return new LtEqNode();
case MatlabParser.GT:
return new GtNode();
case MatlabParser.GTEQ:
return new GtEqNode();
case MatlabParser.AND:
return new AndNode();
case MatlabParser.SHORTAND:
return new ShortAndNode();
case MatlabParser.OR:
return new OrNode();
case MatlabParser.SHORTOR:
return new ShortOrNode();
case MatlabParser.POSITIVE:
return new PositiveNode();
case MatlabParser.NEGATIVE:
return new NegativeNode();
case MatlabParser.NOT:
return new NotNode();
case MatlabParser.ALL:
return new AllNode();
case MatlabParser.END:
return new EndNode();
case MatlabParser.IMAGINARY:
return new ImaginaryNode();
case MatlabParser.REAL:
return new RealNode();
case MatlabParser.STRING:
return new StringNode();
case MatlabParser.CELLARRAY:
return new CellArrayNode();
case MatlabParser.REGULARARRAY:
return new RegularArrayNode();
case MatlabParser.VAR:
return new VarNode();
case MatlabParser.DOTEXPRESSION:
return new DotExpressionNode();
case MatlabParser.DOTNAME:
return new DotNameNode();
case MatlabParser.PARENTHESIS:
return new ParenthesisNode();
case MatlabParser.CURLYBRACE:
return new CurlyBraceNode();
case MatlabParser.ATBASE:
return new AtBaseNode();
case MatlabParser.ANONYMOUSFUNCTION:
return new AnonymousFunctionNode();
case MatlabParser.FUNCTIONHANDLE:
return new FunctionHandleNode();
case MatlabParser.QUESTION:
return new MetaclassNode();
case MatlabParser.STORAGE:
return new StorageNode();
case MatlabParser.INPUT:
return new InputNode();
case MatlabParser.OUTPUT:
return new OutputNode();
case MatlabParser.PRINT:
return new PrintNode();
case MatlabParser.NOPRINT:
return new NoPrintNode();
case MatlabParser.CLASSREF:
return new ClassRefNode();
case MatlabParser.FUNCTIONREF:
return new FunctionRefNode();
case MatlabParser.ID:
return new IdNode();
case MatlabParser.NAME:
return new NameNode();
default:
throw new InternalException();
}
}
#endregion
#endregion
}
}
|
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public partial class HomeController : MyController
{
[Route("")]
public IActionResult Index()
{
//Sets the variable so the includes of css and js will pull through
ViewData["homePage"] = true;
return this.ModuleView("Examples", "MVC", "Index.cshtml");
}
//This demonstrates how to use a different layout than default for a page in ModFrame
[ModFrameLayouts.AnotherLayout]
[Route("another_layout")]
public IActionResult AnotherLayout()
{
//Sets the variable so the includes of css and js will pull through
ViewData["homePage"] = true;
return this.ModuleView("Examples", "MVC", "Index.cshtml");
}
//This demonstrates how to use a basic Async method
[Route("async_demo")]
public async Task<IActionResult> AsyncDemo()
{
//Sets the variable so the includes of css and js will pull through
ViewData["homePage"] = true;
//Awaits for a task to be completed async
await Task.Delay(1000);
//Returns the view
return this.ModuleView("Examples", "MVC", "Index.cshtml");
}
} |
namespace MvcMarket.FrontEnd.Models
{
using System;
using System.Net.Mail;
using System.Text;
public class EmailOrderSubmitter
{
private const string MailSubject = "New order submitted!";
private readonly string _mailFrom;
private readonly string _mailTo;
private readonly string _smtpServer;
public EmailOrderSubmitter(string smtpServer, string mailFrom, string mailTo)
{
_smtpServer = smtpServer;
_mailFrom = mailFrom;
_mailTo = mailTo;
}
public bool SubmitOrder(Cart cart,Guid userId)
{
var body = new StringBuilder();
body.AppendLine("A new order has been submitted");
body.AppendLine("---");
body.AppendLine("Items:");
foreach (var line in cart.Lines)
{
var subtotal = line.Product.Price * line.Quantity;
body.AppendFormat("{0} x {1} (subtotal: {2:c}", line.Quantity,
line.Product.Name,
subtotal);
}
body.AppendFormat("Total order value: {0:c}", cart.ComputeTotalValue());
body.AppendLine("---");
body.AppendLine("Ship to:");
var sd = cart.ShippingDetails(userId);
body.AppendLine(sd.Name);
body.AppendLine(sd.Address);
body.AppendLine(sd.City);
body.AppendLine(sd.State);
body.AppendLine(sd.Country);
body.AppendLine(sd.Zip);
var smtpClient = new SmtpClient(_smtpServer);
try
{
smtpClient.Send(new MailMessage(_mailFrom, _mailTo, MailSubject,
body.ToString()));
return true;
}
catch
{
return false;
}
}
}
} |
using JetBrains.Annotations;
namespace BuildNotifications.PluginInterfaces.SourceControl
{
/// <summary>
/// Contains information about a PullRequest
/// </summary>
[PublicAPI]
public interface IPullRequest : IBranch
{
/// <summary>
/// User entered description of the PR.
/// </summary>
string Description { get; }
/// <summary>
/// Number of this PR. Should identify it uniquely in its connection.
/// </summary>
string Id { get; }
/// <summary>
/// Branch this request originates from.
/// </summary>
string SourceBranch { get; }
/// <summary>
/// Branch this request should merge into.
/// </summary>
string TargetBranch { get; }
}
} |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Robotify.AspNetCore
{
public class RobotifyMiddleware : IMiddleware
{
private readonly IRobotifyContentWriter writer;
public RobotifyMiddleware(IRobotifyContentWriter writer)
{
this.writer = writer;
}
//public async Task Invoke(HttpContext httpContext, IRobotifyContentWriter writer)
//{
// var content = writer.Write();
// httpContext.Response.ContentType = "text/plain";
// await httpContext.Response.WriteAsync(content);
//}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var content = writer.Write();
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(content);
}
}
} |
using System;
using static BulletSharp.UnsafeNativeMethods;
namespace BulletSharp
{
public class ConstraintSolverPoolMultiThreaded : ConstraintSolver
{
public ConstraintSolverPoolMultiThreaded(int numSolvers)
{
IntPtr native = btConstraintSolverPoolMt_new(numSolvers);
InitializeUserOwned(native);
}
}
public class DiscreteDynamicsWorldMultiThreaded : DiscreteDynamicsWorld
{
public DiscreteDynamicsWorldMultiThreaded(Dispatcher dispatcher, BroadphaseInterface pairCache,
ConstraintSolverPoolMultiThreaded constraintSolver, ConstraintSolver constraintSolverMultiThreaded,
CollisionConfiguration collisionConfiguration)
{
IntPtr native = btDiscreteDynamicsWorldMt_new(
dispatcher != null ? dispatcher.Native : IntPtr.Zero,
pairCache != null ? pairCache.Native : IntPtr.Zero,
constraintSolver != null ? constraintSolver.Native : IntPtr.Zero,
constraintSolverMultiThreaded != null ? constraintSolverMultiThreaded.Native : IntPtr.Zero,
collisionConfiguration != null ? collisionConfiguration.Native : IntPtr.Zero);
InitializeUserOwned(native);
InitializeMembers(dispatcher, pairCache, constraintSolver);
}
}
}
|
// <copyright file="ListExtensions.cs" company="federrot Software">
// Copyright (c) federrot Software. All rights reserved.
// </copyright>
// <summary>Defines the Atom.Collections.ListExtensions class.</summary>
// <author>Paul Ennemoser</author>
namespace Atom.Collections
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Atom.Diagnostics.Contracts;
/// <summary>
/// Defines extension methods for the IList{T} interface.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Swaps the items at the given zero-based indices of this IList{T}.
/// </summary>
/// <typeparam name="T">
/// The type of elements in the list.
/// </typeparam>
/// <param name="list">
/// The list to modify.
/// </param>
/// <param name="indexA">
/// The zero-based index of the first element to swap.
/// </param>
/// <param name="indexB">
/// The zero-based index of the second element to swap.
/// </param>
public static void SwapItems<T>( this IList<T> list, int indexA, int indexB )
{
Contract.Requires<ArgumentNullException>( list != null );
Contract.Requires<ArgumentOutOfRangeException>( indexA >= 0 );
Contract.Requires<ArgumentOutOfRangeException>( indexB >= 0 );
Contract.Requires<ArgumentOutOfRangeException>( indexA < list.Count );
Contract.Requires<ArgumentOutOfRangeException>( indexB < list.Count );
T itemA = list[indexA];
T itemB = list[indexB];
list[indexA] = itemB;
list[indexB] = itemA;
}
/// <summary>
/// Returns a read-only instance of this <see cref="IList{T}"/>.
/// </summary>
/// <typeparam name="T">
/// The type of elements in the list.
/// </typeparam>
/// <param name="list">
/// The list to wrap.
/// </param>
/// <returns>
/// A new read-only instance of this <see cref="IList{T}"/>.
/// </returns>
public static IList<T> AsReadOnly<T>( this IList<T> list )
{
Contract.Requires<ArgumentNullException>( list != null );
// Contract.Ensures( Contract.Result<IList<T>>() != null );
// Contract.Ensures( Contract.Result<IList<T>>().IsReadOnly );
return new ReadOnlyCollection<T>( list );
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Text;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.Messaging
{
public class Common
{
public const string TestEventString = @"{""type"":""event"",""event"":""testEvent"",""body"":null}";
public const string TestEventFormatString = @"{{""event"":""testEvent"",""body"":{{""someString"":""{0}""}},""seq"":0,""type"":""event""}}";
public static readonly int ExpectedMessageByteCount = Encoding.UTF8.GetByteCount(TestEventString);
}
}
|
namespace IntraSoft.Data.Dtos.IsoCategory
{
using IntraSoft.Services.Mapping;
using IntraSoft.Data.Models;
public class IsoFileCategoryReadDto : IMapFrom<IsoFileCategory>
{
public int Id { get; set; }
public string Name { get; set; }
}
}
|
using System.Threading;
using System.Threading.Tasks;
using ProjectName.DomainName.Application.Commands.AddressCommands;
using ProjectName.DomainName.Application.ViewModels;
using ProjectName.DomainName.Domain.Interfaces.Repository;
using ProjectName.Shared.Bus.Abstractions;
namespace ProjectName.DomainName.Handlers.Addresses
{
public class SearchAddressCommandHandler : ICommandHandler<SearchAddressCommand, AddressViewModel>
{
private readonly IAddressReadRepository _addressReadRepository;
public SearchAddressCommandHandler(IAddressReadRepository addressReadRepository)
{
this._addressReadRepository = addressReadRepository;
}
public async Task<AddressViewModel> Handle(SearchAddressCommand request, CancellationToken cancellationToken)
{
var address = await this._addressReadRepository.SearchByIdAsync(request.AggregateId);
return address.ToViewModel();
}
}
}
|
using FlasherWeb.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FlasherWeb.Pages.Models
{
public class IndexPage
{
public FlashCard FlashCard { get; set; } = new FlashCard();
public List<FlashCard> FlashCards { get; set; } = new List<FlashCard>();
public int CardIndex { get; set; } = 0;
public bool Front { get; set; } = true;
public string Side { get; set; } = "Front";
public string Title { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public string SupersetTitle { get; set; } = string.Empty;
public List<Superset> Supersets { get; set; } = new List<Superset>();
public string SetTitle { get; set; } = string.Empty;
public List<Set> Sets { get; set; } = new List<Set>();
public string ShowButton { get; set; } = "Back";
public bool AnsweredCorrectly { get; set; } = false;
public List<Set> SuperSetSelectElements { get; set; } = new List<Set>();
public List<Set> SelectedSets { get; set; } = new List<Set>();
public int SelectedSupersetId { get; set; } = 0;
public int SelectedSetId { get; set; } = 0;
}
}
|
using Google.Maps.Examples.Shared;
using UnityEngine;
namespace Google.Maps.Examples {
/// <summary>
/// Example demonstrating the use of Nine-Sliced <see cref="Material"/>s for better building
/// texturing.
/// </summary>
/// <remarks>
/// Uses <see cref="DynamicMapsService"/> component to allow navigation around the world, with the
/// <see cref="MapsService"/> component keeping only the viewed part of the world loaded at all
/// times.
/// <para>
/// Also uses <see cref="BuildingTexturer"/> component to apply Nine-Sliced <see
/// cref="Material"/>s.
/// </para>
/// Also uses <see cref="ErrorHandling"/> component to display an errors encountered by the
/// <see cref="MapsService"/> component when loading geometry.
/// </remarks>
[RequireComponent(typeof(DynamicMapsService), typeof(BuildingTexturer), typeof(ErrorHandling))]
public sealed class NineSlicing : MonoBehaviour {
/// <summary>
/// Use events to connect <see cref="DynamicMapsService"/> to <see cref="BuildingTexturer"/> so
/// that all extruded buildings can receive a Nine-Sliced <see cref="Material"/>.
/// </summary>
private void Awake() {
// Get required Building Texturer component on this GameObject.
BuildingTexturer buildingTexturer = GetComponent<BuildingTexturer>();
// Get the required Dynamic Maps Service on this GameObject.
DynamicMapsService dynamicMapsService = GetComponent<DynamicMapsService>();
// Sign up to event called after each new building is loaded, so can assign Materials to this
// new building. Note that:
// - DynamicMapsService.MapsService is auto-found on first access (so will not be null).
// - This event must be set now during Awake, so that when Dynamic Maps Service starts loading
// the map during Start, this event will be triggered for all Extruded Structures.
dynamicMapsService.MapsService.Events.ExtrudedStructureEvents.DidCreate.AddListener(
args => buildingTexturer.AssignNineSlicedMaterials(args.GameObject));
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
namespace AuthService.Model
{
public class Account
{
private Account()
{
}
public Account(string login, string password, UserRole role)
{
ValidateLogin(login);
ValidatePassword(password);
Login = login;
Role = role;
Created = DateTime.UtcNow;
HashPassword(password);
}
public string Login { get; private set; } = default!;
public UserRole Role { get; private set; } = default!;
public DateTime Created { get; private set; } = default!;
public byte[] PasswordHash { get; private set; } = default!;
public byte[] PasswordSalt { get; private set; } = default!;
public bool VerifyPassword(string password)
{
using var hmac = new HMACSHA512(PasswordSalt);
byte[] computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
return computedHash.SequenceEqual(PasswordHash);
}
private void HashPassword(string password)
{
using var hmac = new HMACSHA512();
PasswordSalt = hmac.Key;
PasswordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
private void ValidateLogin(string login)
{
if (login.Length < 3)
{
throw new ServiceException("Invalid login.", HttpStatusCode.BadRequest);
}
}
private void ValidatePassword(string password)
{
if (password.Length < 6)
{
throw new ServiceException("Invalid password.", HttpStatusCode.BadRequest);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RobofestWTE.Models
{
public class TeamDetailsModel
{
public string TeamName;
public int TeamNumberBranch;
public int TeamNumberSpecific;
public string Location;
public string Coach;
public int CompID;
public int TeamID;
public float RoundAverage;
public int Rank;
public RobofestWTE.Models.RoundEntry Round1;
public RobofestWTE.Models.RoundEntry Round2;
public int Rerun1;
public int Rerun2;
public List<RobofestWTE.Models.RoundEntry> Round = new List<RoundEntry>();
}
} |
using UnityEngine;
namespace Player
{
public static class InputController
{
public static Vector2 GetPlayerMovement()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var movement = new Vector2(horizontal, vertical);
if (movement.sqrMagnitude > 1)
{
movement.Normalize();
}
return movement;
}
public static Vector2 GetMouseDelta()
{
return new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
}
public static float GetMouseScrollValue()
{
return Input.mouseScrollDelta.y;
}
public static bool IsCrouchHeld()
{
return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl);
}
public static bool IsSprintHeld()
{
return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
}
public static bool IsJumpPressed()
{
return Input.GetKeyDown(KeyCode.Space);
}
public static bool IsShootHeld()
{
return Input.GetKey(KeyCode.Mouse0);
}
public static bool IsShootPressed()
{
return Input.GetKeyDown(KeyCode.Mouse0);
}
public static bool IsReloadPressed()
{
return Input.GetKeyDown(KeyCode.R);
}
}
} |
@{ Register Src="../UI/FunctionTitleBar.ascx" TagName="FunctionTitleBar" TagPrefix="uc6" }
@{ @ Register Src="../Common/DataModelContainer.ascx" TagName="DataModelContainer"
TagPrefix="uc8"}
<asp:Button ID="btnAdd" runat="server" Text="新增料品" class="btn" OnClick="btnAdd_Click" />
<asp:Button ID="btnQuery" runat="server" Text="查詢" class="btn" OnClick="btnQuery_Click" />
<uc6:FunctionTitleBar ID="resultTitle" runat="server" ItemName="查詢結果" Visible="false" />
<uc8:DataModelContainer ID="modelItem" runat="server" />
|
using System;
using UnityEditor;
using UnityEngine;
using InternalRealtimeCSG;
using RealtimeCSG.Legacy;
namespace RealtimeCSG
{
internal static class ShapeUtility
{
#region CheckMaterials
public static bool CheckMaterials(Shape shape)
{
return shape.CheckMaterials();
}
#endregion
#region EnsureInitialized
public static bool EnsureInitialized(Shape shape)
{
bool dirty = CheckMaterials(shape);
for (int i = 0; i < shape.TexGens.Length; i++)
{
if ((shape.TexGens[i].Scale.x >= -MathConstants.MinimumScale && shape.TexGens[i].Scale.x <= MathConstants.MinimumScale) ||
(shape.TexGens[i].Scale.y >= -MathConstants.MinimumScale && shape.TexGens[i].Scale.y <= MathConstants.MinimumScale))
{
dirty = true;
if (shape.TexGens[i].Scale.x == 0 &&
shape.TexGens[i].Scale.y == 0)
{
shape.TexGens[i].Scale.x = 1.0f;
shape.TexGens[i].Scale.y = 1.0f;
}
if (shape.TexGens[i].Scale.x < 0)
shape.TexGens[i].Scale.x = -Mathf.Max(MathConstants.MinimumScale, Mathf.Abs(shape.TexGens[i].Scale.x));
else
shape.TexGens[i].Scale.x = Mathf.Max(MathConstants.MinimumScale, Mathf.Abs(shape.TexGens[i].Scale.x));
if (shape.TexGens[i].Scale.y < 0)
shape.TexGens[i].Scale.y = -Mathf.Max(MathConstants.MinimumScale, Mathf.Abs(shape.TexGens[i].Scale.y));
else
shape.TexGens[i].Scale.y = Mathf.Max(MathConstants.MinimumScale, Mathf.Abs(shape.TexGens[i].Scale.y));
}
}
Vector3 tangent = MathConstants.zeroVector3, binormal = MathConstants.zeroVector3;
for (int i = 0; i < shape.Surfaces.Length; i++)
{
if (shape.Surfaces[i].Tangent == MathConstants.zeroVector3 ||
shape.Surfaces[i].BiNormal == MathConstants.zeroVector3)
{
dirty = true;
var normal = shape.Surfaces[i].Plane.normal;
GeometryUtility.CalculateTangents(normal, out tangent, out binormal);
shape.Surfaces[i].Tangent = tangent;
shape.Surfaces[i].BiNormal = binormal;
}
// if (Surfaces[i].Stretch == MathConstants.zeroVector2)
// {
// Surfaces[i].Stretch = MathConstants.oneVector2;
// dirty = true;
// }
}
return dirty;
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class Armor : Item {
public Armor(){
addHealth = 10;
name = "Angel Angst My";
descript = "op";
}
public Armor(string givenName, string givenDescript, int givenHealth, string givenImagePath){
name = givenName;
addHealth = givenHealth;
descript = givenDescript;
imageRepresentation = Resources.Load<Sprite>(givenImagePath) as Sprite;
}
//we havemultiple types of armor:
/*
* kigurumis
* rings
* /
//kigurumi types:
/*red panda
* panda
* dinosaur
* fox
* tabby cat
* hedgehog
* blue unicorn
* zingore
* gold hedgehog
* rathain
* rainbow panda
* chicken
* gore magala
* dreamin panda
* abyss watchers
* royalnt
* cow
* cat
* reindeer
* dog
* doggo
* doggy
* dogiest
* doeer?
* suschi cat
* the entire population of iceland
* hen wearing tie
* bear
* computer part bear
* furyhorn
* chimera
* rathalos
* styngian zynogre
* beholder (dnd)
* beholder (ff)
* gandalf
* mimichu
* bahamut
* lgith metatron
* isis (dragon quest/dog)
* a katana
*/
/*
* AND BUILDY OUR OWN KIGURUMI
*
*/
}
|
using UnityEngine;
public class CurvePointControl : MonoBehaviour {
public int objectNumber;
public GameObject controlObject;
public GameObject controlObject2;
void OnMouseDrag () {
transform.position = DrawCurve.cam.ScreenToViewportPoint (Input.mousePosition);
DrawCurve.use.UpdateLine (objectNumber, Input.mousePosition, gameObject);
}
} |
////////////////////////////////////////////////////////////////////////////
// <copyright file="UserManager.cs" company="Intel Corporation">
//
// Copyright (c) 2013-2015 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using ACAT.Lib.Core.Utility;
#region SupressStyleCopWarnings
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1126:PrefixCallsCorrectly",
Scope = "namespace",
Justification = "Not needed. ACAT naming conventions takes care of this")]
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1101:PrefixLocalCallsWithThis",
Scope = "namespace",
Justification = "Not needed. ACAT naming conventions takes care of this")]
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1121:UseBuiltInTypeAlias",
Scope = "namespace",
Justification = "Since they are just aliases, it doesn't really matter")]
[module: SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1200:UsingDirectivesMustBePlacedWithinNamespace",
Scope = "namespace",
Justification = "ACAT guidelines")]
[module: SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1309:FieldNamesMustNotBeginWithUnderscore",
Scope = "namespace",
Justification = "ACAT guidelines. Private fields begin with an underscore")]
[module: SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1300:ElementMustBeginWithUpperCaseLetter",
Scope = "namespace",
Justification = "ACAT guidelines. Private/Protected methods begin with lowercase")]
#endregion SupressStyleCopWarnings
namespace ACAT.Lib.Core.UserManagement
{
/// <summary>
/// Manages users. The purpose for having "users" is to support apps
/// that require multi-user support. Assets such as word prediction models,
/// abbreviations etc are user specific and the application can store
/// them in the user directory
/// </summary>
public class UserManager
{
/// <summary>
/// Name of the default user
/// </summary>
public const String DefaultUserName = "Default";
/// <summary>
/// The name of the current user
/// </summary>
private static String _currentUserName = DefaultUserName;
#if SUPPORT_ASSETS
private static String _sourceDir = "Install";
private static Tuples<Assets, String, String> _assetList = new Tuples<Assets, string, string>
{
{Assets.Abbreviations, "AbbreviationsEmpty.xml", "Abbreviations.xml"},
{Assets.Spellings, "SpellCheck.xml", "*"},
{Assets.WordPrediction, "WordPrediction", "*"}
};
#endif
/// <summary>
/// Initializes the user manager
/// </summary>
static UserManager()
{
_currentUserName = DefaultUserName;
}
/// <summary>
/// Gets or set the current user
/// </summary>
public static String CurrentUser
{
get
{
return _currentUserName;
}
set
{
_currentUserName = value;
}
}
/// <summary>
/// Gets the root path to the "Users" directory
/// </summary>
public static String UsersDirBasePath
{
get
{
return FileUtils.GetUsersDir();
}
}
/// <summary>
/// Returns the root path to the directory of the current user
/// </summary>
public static String CurrentUserDir
{
get
{
return Path.Combine(FileUtils.GetUsersDir(), _currentUserName);
}
}
/// <summary>
/// Returns the user dir for the specified user name
/// </summary>
/// <param name="userName">name of the user</param>
/// <returns>user directory</returns>
public static String GetUserDir(String userName)
{
return Path.Combine(FileUtils.GetUsersDir(), userName);
}
/// <summary>
/// Gets the full path relative to the user dir of the specified
/// relative path / filename
/// </summary>
/// <param name="path">relative path</param>
/// <returns>full path</returns>
public static String GetFullPath(String path)
{
return Path.Combine(CurrentUserDir, path);
}
/// <summary>
/// Checks if the current user's directory exists
/// </summary>
/// <returns>true on success</returns>
public static bool CurrentUserExists()
{
return UserExists(_currentUserName);
}
/// <summary>
/// Checks if the specified user name exists (checks if the
/// directory exists)
/// </summary>
/// <param name="userName">name of the user</param>
/// <returns>true on success</returns>
public static bool UserExists(String userName)
{
return Directory.Exists(GetUserDir(userName));
}
/// <summary>
/// Checks if the default user exists
/// </summary>
/// <returns>true if it does</returns>
public static bool DefaultUserExists()
{
return UserExists(DefaultUserName);
}
/// <summary>
/// Creates default user directory
/// </summary>
/// <returns>true on success</returns>
public static bool CreateDefaultUser()
{
return CreateUser(DefaultUserName);
}
/// <summary>
/// Creates user specified by the username
/// </summary>
/// <param name="userName">name of the user</param>
/// <returns>true on success</returns>
public static bool CreateUser(String userName)
{
bool retVal = true;
if (UserExists(userName))
{
return false;
}
try
{
var dir = GetUserDir(userName);
if (!UserExists(userName))
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
catch (Exception ex)
{
Log.Debug(ex.ToString());
retVal = false;
}
return retVal;
}
/// <summary>
/// Deletes the specified user. (not supported yet)
/// </summary>
/// <param name="userName">name of the user</param>
/// <returns>true on success</returns>
public static bool DeleteUser(String userName)
{
return false;
}
}
} |
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace Moq.Microsoft.Configuration.Tests.Utils.ConfigurationSectionTests;
public sealed class ConfigurationSectionShould : ConfigurationSectionTestsBase
{
[Fact]
public void HaveNoChildren()
{
var result = CreateClass()
.GetChildren();
result
.Should()
.BeEmpty();
}
[Fact]
public void NotExist()
{
var result = CreateClass()
.Exists();
result
.Should()
.BeFalse();
}
} |
@{
Layout = "_Layout";
}
<!DOCTYPE html>
<html>
<body>
<script>
//add call to microsoftTeams here.gi
</script>
@{
<section style="width: 100%; display: table">
<div style="display:table-row">
<div style="width: auto; display:table-cell;">
<div id="gray" style="display:none;"><h3 style="color:#6364a5">@ViewBag.Gray</h3></div>
</div>
<div style="display: table-cell">
<div id="red" style="display:none;"><h3 style="color:#6364a5">@ViewBag.Red</h3></div>
</div>
</div>
</section>
}
<script>
let gr = document.getElementById("gray").style;
let rd = document.getElementById("red").style;
const colorClickGray = () => {
gr.display = "block";
rd.display = "none";
}
const colorClickRed = () => {
rd.display = "block";
gr.display = "none";
}
</script>
<button onclick="(document.getElementById('icon').src='/images/iconGray.png'); colorClickGray()">Select Gray</button>
<img id="icon" src="~/images/teamsIcon.png" alt="icon" style="width:100px" />
<button onclick="(document.getElementById('icon').src='/images/iconRed.png'); colorClickRed()">Select Red</button>
<p>
<h2 style="color:#6364a5">This is your personal tab</h2>
<br />
<br />
</p>
</body>
</html>
|
using UnityEngine;
using System.Collections.Generic;
public class HTTP : MonoBehaviour
{
public delegate void HTTPCallback(WWW a_Request);
struct RequestWithCB
{
public RequestWithCB(WWW a_Request, HTTPCallback a_Callback, bool a_Important)
{
Request = a_Request;
Callbacks = new List<HTTPCallback>();
Callbacks.Add(a_Callback);
Important = a_Important;
}
public void Add(HTTPCallback a_RequestCallback)
{
Callbacks.Add(a_RequestCallback);
}
public WWW Request { get; private set; }
public List<HTTPCallback> Callbacks;
public bool Important;
}
static List<RequestWithCB> m_Requests = new List<RequestWithCB>();
public static void Request(string a_URL, HTTPCallback a_Callback, bool a_Important)
{
for(int i = 0; i< m_Requests.Count; i++)
{
if (m_Requests[i].Request.url == a_URL)
{
m_Requests[i].Add(a_Callback);
return;
}
}
m_Requests.Add(new RequestWithCB(new WWW(a_URL), a_Callback, a_Important));
}
bool HasImportantTask()
{
for (int i = m_Requests.Count - 1; i >= 0; i--)
if (m_Requests[i].Important)
return true;
return false;
}
void Update ()
{
for(int i = m_Requests.Count - 1; i >= 0; i--)
{
var t_Request = m_Requests[i];
if (t_Request.Request.isDone)
{
foreach(HTTPCallback t_Callback in t_Request.Callbacks)
t_Callback.Invoke(t_Request.Request);
m_Requests.Remove(t_Request);
}
}
if (HasImportantTask())
LoadingWindow.Show();
else
LoadingWindow.Hide();
}
}
|
using UnityEditor;
using UnityEngine;
using ProceduralWorlds.Node;
using ProceduralWorlds.Editor;
namespace ProceduralWorlds.Editor
{
[CustomEditor(typeof(NodeCurve))]
public class NodeCurveEditor : BaseNodeEditor
{
NodeCurve node;
const string notifyKey = "curveModify";
public override void OnNodeEnable()
{
node = target as NodeCurve;
delayedChanges.BindCallback(notifyKey, (unused) => {
NotifyReload();
node.CurveTerrain();
node.sCurve.SetAnimationCurve(node.curve);
});
}
public override void OnNodeGUI()
{
PWGUI.SpaceSkipAnchors();
EditorGUI.BeginChangeCheck();
{
Rect pos = EditorGUILayout.GetControlRect(false, 100);
node.curve = EditorGUI.CurveField(pos, node.curve);
}
if (EditorGUI.EndChangeCheck())
delayedChanges.UpdateValue(notifyKey);
PWGUI.SamplerPreview(node.outputTerrain);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AvataItem : MonoBehaviour
{
public Text m_AvataPriceText;
public int m_AvataIdx;
public int m_AvataPrice;
private void Start()
{
if (m_AvataPriceText)
m_AvataPriceText.text = m_AvataPrice.ToString();
}
public void OnClickToggle()
{
//if (m_AvataPriceText)
// m_AvataPriceText.text = m_AvataPrice.ToString();
}
}
|
using System;
using System.Threading;
using System.Windows.Forms;
namespace Terraria.ModLoader.Setup
{
public interface ITaskInterface : IWin32Window
{
void SetMaxProgress(int max);
void SetStatus(string status);
void SetProgress(int progress);
CancellationToken CancellationToken();
object Invoke(Delegate action);
IAsyncResult BeginInvoke(Delegate action);
}
}
|
using Microsoft.AspNetCore.Mvc;
using PlakDukkani.BLL.Abstract;
using PlakDukkani.BLL.Concrete.ResultServiceBLL;
using PlakDukkani.ViewModel.AlbumViewModels;
using PlakDukkani.ViewModel.Constrains;
using System.Collections.Generic;
namespace PlakDukkani.UI.MVC.Controllers
{
public class HomeController : Controller
{
//SOLID D => Dependency Inversion
//Dependency Injection Pattern
//Ctor Dep Injection
IAlbumBLL albumService;
public HomeController(IAlbumBLL albumService)
{
this.albumService = albumService;
}
//IAlbumBLL albumservice = new AlbumService();
public IActionResult Index()
{
ResultService<List<SingleAlbumVM>> albumResult = albumService.GetSingleAlbums();
if (!albumResult.HasError)
{
return View(albumResult.Data);
}
else
{
ViewBag.Message = albumResult.Errors[0].ErrorMessage;
return View();
}
}
public IActionResult AlbumStore()
{
return View();
}
public IActionResult AlbumDetail(int id)
{
ResultService<AlbumDetailVM> albumDetail= albumService.GetAlbumById(id);
if (albumDetail.HasError)
{
ViewBag.Message = AlbumMessage.idHatasi;
return View();
}
return View(albumDetail.Data);
}
public IActionResult Contact()
{
return View();
}
}
}
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Rebus.Pipeline;
using SafeRebus.Abstractions;
using SafeRebus.Config;
namespace SafeRebus.RebusSteps.IncomingSteps
{
public class HandleDatabaseTransactionIncomingStep : IIncomingStep
{
public async Task Process(IncomingStepContext context, Func<Task> next)
{
var scope = context.Load<IServiceScope>(SafeRebusContextTags.ScopeContextTag);
var dbProvider = scope.ServiceProvider.GetService<IDbProvider>();
try
{
await next();
}
catch (Exception e)
{
dbProvider.GetDbTransaction().Rollback();
throw;
}
dbProvider.GetDbTransaction().Commit();
}
}
} |
using System;
using System.Windows.Forms;
using System.Data;
public class Form1: Form
{
protected TextBox textBox1;
// <Snippet1>
private void PrintListItems() {
// Get the CurrencyManager of a TextBox control.
CurrencyManager myCurrencyManager = (CurrencyManager)textBox1.BindingContext[0];
// Presuming the list is a DataView, create a DataRowView variable.
DataRowView drv;
for(int i = 0; i < myCurrencyManager.Count; i++) {
myCurrencyManager.Position = i;
drv = (DataRowView)myCurrencyManager.Current;
// Presuming a column named CompanyName exists.
Console.WriteLine(drv["CompanyName"]);
}
}
// </Snippet1>
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionDemo
{
class MyCustomException : ApplicationException
{
public MyCustomException()
{
}
public MyCustomException(string message) : base(message)
{
Console.WriteLine(message);
}
public MyCustomException(string message, Exception innerException) : base(message, innerException)
{
Console.WriteLine($"Message : {message} and InnerException : {innerException}");
}
protected MyCustomException(SerializationInfo info, StreamingContext context) : base(info, context)
{
Console.WriteLine($"SerializationInfo : {info} and StreamingContext : {context}");
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace DFC.App.JobProfile.CurrentOpportunities.ViewModels
{
[ExcludeFromCodeCoverage]
public class BodyApprenticeshipsViewModel
{
[Display(Name = "Apprenticeships")]
public IEnumerable<BodyVacancyViewModel> Vacancies { get; set; }
}
}
|
using System;
namespace SpectabisUI.Controls.AnimatedImage.Decoding
{
public class GifFrame
{
public bool HasTransparency, IsInterlaced, IsLocalColorTableUsed;
public byte TransparentColorIndex;
public int LZWMinCodeSize, LocalColorTableSize;
public long LZWStreamPosition;
public TimeSpan FrameDelay;
public FrameDisposal FrameDisposalMethod;
public ulong LocalColorTableCacheID;
public bool ShouldBackup;
public GifRect Dimensions;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using 自定义Uppercomputer_20200727.Nlog;
using static 自定义Uppercomputer_20200727.AutoSizeFormClass;
namespace 自定义Uppercomputer_20200727
{
/// <summary>
/// 窗口大小改变 控件自动改变
/// </summary>
class AutoSizeFormClass
{
/// <summary>
/// 声明结构 记录控件位置和大小
/// </summary>
public struct ControlRect
{
public string name;
public float Left;
public float Top;
public float Width;
public float Height;
public float Size;
}
public List<ControlRect> _oldCtrl = new List<ControlRect>();
private int _ctrlNo = 0;
ControlRect decimals;
public static float X, Y, Width, Height;//静态字段保存数据
public void RenewControlRect(Control mForm)
{
//如果控件集合对象_oldCtrl不存在则将其添加,如果不添加首先无法找到主窗口
//也就无法开始遍历
//LogUtils日志
//LogUtils.debugWrite( $"{mForm.TopLevelControl.ToString()??mForm.Name} 窗口大小改变 控件自动改变");
_oldCtrl.Clear();
ControlRect cR;
cR.name = mForm.Name;
cR.Left = mForm.Left;
cR.Top = mForm.Top;
cR.Width = mForm.Width;
cR.Height = mForm.Height;
cR.Size = mForm.Font.Size;
_oldCtrl.Add(cR);
AddControl(mForm);
_ctrlNo = 1;
_oldCtrl.Clear();
}
private void AddControl(Control ctrl)
{
foreach (Control c in ctrl.Controls)
{
ControlRect cR;
cR.name = c.Name;
cR.Left = c.Left;
cR.Top = c.Top;
cR.Width = c.Width;
cR.Height = c.Height;
cR.Size = c.Font.Size;
_oldCtrl.Add(cR);
// 控件可能嵌套子控件
if (c.Controls.Count > 0)
AddControl(c);
}
}
public void ControlAutoSize(Control mForm)
{
_ctrlNo = 1;
/*计算宽度比率*/
float wScale = (float)mForm.Width / _oldCtrl[0].Width;
/*计算高度比率*/
float hScale = (float)mForm.Height / _oldCtrl[0].Height;
AutoScaleControl(mForm, wScale, hScale);
}
private void AutoScaleControl(Control mForm, float wScale, float hScale)
{
float ctrlLeft, ctrlTop, ctrlWidth, ctrlHeight;
float ctrlFontSize, hSize, wSize;
List<ControlRect> Ctrl = new List<ControlRect>();
X = wScale;
Width = wScale;
Y = hScale;
Height= hScale;
foreach (Control c in mForm.Controls)
{
//在_oldCtrl 中查询出控件名称相同的控件,并返回对象
ControlRect shortDigits = _oldCtrl.Where((p) => p.name == c.Name).ToList().FirstOrDefault();
//获取左边框的长度
ctrlLeft = shortDigits.Left;
//获取上边框的长度
ctrlTop = shortDigits.Top;
//获取宽度
ctrlWidth = shortDigits.Width;
//获取高度
ctrlHeight = shortDigits.Height;
//获取字体大小
ctrlFontSize = shortDigits.Size;
//通过获取的比率相乘计算出要显示的x,y轴
c.Left = (int)Math.Round((ctrlLeft * wScale));
if (c.Left < 0)
{
c.Left = 0;
}
c.Top = (int)Math.Round((ctrlTop * hScale));
if (c.Top < 0)
{
c.Top = 0;
}
//保存计算结果后的坐标和大小,当下次进行计算是使用该浮点型进行计算
//确保控件不会错乱
//设置高度和宽度
c.Width = (int)Math.Round((ctrlWidth * wScale));
c.Height = (int)Math.Round((ctrlHeight * hScale));
//通过比率获取放大或缩小后的字体大小并进行设置
wSize = ctrlFontSize * wScale;
hSize = ctrlFontSize * hScale;
if (hSize < 7)
{
hSize = 7;
}
if (wSize < 7)
{
wSize = 7;
}
// c.Font = new Font(c.Font.Name, Math.Min(hSize, wSize), c.Font.Style, c.Font.Unit);
c.Font = new Font(c.Font.Name, c.Font.SizeInPoints* hScale, c.Font.Style, c.Font.Unit);
_ctrlNo++;
// 先缩放控件本身 再缩放子控件
if (c.Controls.Count > 0)
{
AutoScaleControl(c, wScale, hScale);
}
shortDigits.Top = ctrlTop * hScale;
shortDigits.Left = ctrlTop * wScale;
shortDigits.Width = ctrlTop * wScale;
shortDigits.Height = ctrlTop * hScale;
//Ctrl.Add(shortDigits);
}
}
}
}
|
using Prism.Events;
namespace ioList.Module.Import
{
public class ImportCompleteEvent : PubSubEvent
{
}
} |
namespace Associativy.Services
{
/// <summary>
/// Contains services that are specific to a graph.
/// </summary>
public interface IGraphServices
{
/// <summary>
/// Service for generating associations
/// </summary>
IMind Mind { get; }
/// <summary>
/// Service for dealing with connections between nodes
/// </summary>
IConnectionManager ConnectionManager { get; }
/// <summary>
/// Deals with node-to-node path calculations
/// </summary>
IPathFinder PathFinder { get; }
/// <summary>
/// Service for handling nodes
/// </summary>
INodeManager NodeManager { get; }
}
} |
using System.Data.Common;
namespace NWrath.Logging
{
public interface IDbLogSchema
{
string ConnectionString { get; set; }
string InitScript { get; }
string TableName { get; }
IDbLogColumnSchema[] Columns { get; }
string BuildInsertQuery(LogRecord record);
string BuildInsertBatchQuery(LogRecord[] batch);
DbConnection CreateConnection();
}
} |
using UnityEngine;
using UnityEditor;
namespace InkFungus
{
class MenuItemsCreator
{
private static GameObject SpawnPrefab(string prefabName)
{
GameObject prefab = Resources.Load<GameObject>("Prefabs/" + prefabName);
if (prefab == null)
{
Debug.LogError("Prefab " + prefabName + " not found");
}
GameObject go = GameObject.Instantiate(prefab) as GameObject;
go.name = prefab.name;
go.transform.position = Vector3.zero;
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Object");
return go;
}
[MenuItem("Tools/Fungus/Create/Ink-Fungus Gateway", false, 100000)]
static void CreateInkFungusGateway()
{
SpawnPrefab("Ink-Fungus Gateway");
}
[MenuItem("Tools/Fungus/Create/Variable Processor", false, 100000)]
static void CreateVariableProcessor()
{
SpawnPrefab("Variable Processor");
}
}
}
|
namespace AspNetCoreWeb
{
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PutJsonAsync(
this HttpClient client,
string requestUrl,
object model)
{
StringContent content = new StringContent(
JsonConvert.SerializeObject(model),
Encoding.UTF8,
"application/json"
);
return await client.PutAsync(requestUrl, content);
}
}
}
|
/*
*
* Mikrotron camera support
*
* Make sure to use NI Camera File Generator to put the Serial termination string to \n
* Tested with EoSens CL MC1362
*
*
* Default baud rate: 9600
* Termination char: \r (0x0D) Carriage Return
*
* Responses: ACK (0x6) on success. NAK (0x15) for unrecognized commands or errors.
*/
using NationalInstruments.Vision;
using NationalInstruments.Vision.Acquisition.Imaq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RTTracker
{
class MikrotronCamera : IMAQCamera
{
public MikrotronCamera(CameraSettings settings)
{
Initialize(settings);
}
void Initialize(CameraSettings settings)
{
session = new ImaqSession(settings.deviceName);
Framerate = settings.framerate;
Trace.WriteLine("Framerate: " + Framerate);
// Create a buffer collection for the acquisition with the requested
// number of images, and configure the buffers to loop continuously.
bufList = session.CreateBufferCollection(settings.numBuffers);
for (int i = 0; i < bufList.Count; ++i)
{
bufList[i].Command = (i == bufList.Count - 1) ? ImaqBufferCommand.Loop : ImaqBufferCommand.Next;
}
// Configure and start the acquisition.
session.Acquisition.Configure(bufList);
session.Acquisition.AcquireAsync();
}
public override void Close()
{
base.Close();
}
public void UpdateAcquisition(VisionImage image )
{
uint bufferNumber = 0;
// Try to get the next image. If it has been overwritten then get
// the newest image.
bufferNumber = session.Acquisition.Copy(bufferNumber, ImaqOverwriteMode.GetNewest, image);
bufferNumber++;
// Update the UI by calling ReportProgress on the background worker.
}
public override void SetROI(QTrkDotNet.Int2 size, QTrkDotNet.Int2[] roiPositions)
{
throw new NotImplementedException();
}
internal void Start()
{
session.Start();
}
internal void Stop()
{
session.Stop();
}
public override int Framerate
{
get
{
// frame min max
//%06x %02x-%06x
string resp = SerialCmd(":q?");
string[] values=resp.Split(' ');
return Convert.ToInt32(values[0], 16);
}
set
{
SerialCmd(string.Format(":q{0:X06}", value));
}
}
string SerialCmd(string p)
{
var cmd=ASCIIEncoding.ASCII.GetBytes(p+"\r");
session.SerialConnection.Write(cmd,1000);
session.SerialConnection.Flush();
string resp = "";
bool err = false;
while (true)
{
byte r = session.SerialConnection.ReadBytes(1, 1000)[0];
if (r == '\r') break;
if (r == 0x06)
{
resp = "ACK.";
return "";
}
if (r == 0x15)
{
resp = "NAK.";
err = true;
break;
}
resp += ASCIIEncoding.ASCII.GetString(new byte[] { r });
}
Trace.WriteLine("IMAQ Camera Resp: " + resp);
if (err)
throw new ApplicationException("IMAQ Camera error: " + resp);
return resp;
}
}
}
|
using TekConf.Core.ViewModels;
namespace TekConf.Pages
{
public class LoginPageBase : ViewPage<LoginViewModel> { }
public partial class LoginPage : LoginPageBase
{
public LoginPage()
{
InitializeComponent();
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace Sortingtime.Infrastructure
{
public static class CalenderExtensions
{
public static DateTime FirstDayOfWeek(this DateTime from)
{
var startDate = from.Date;
while (startDate.DayOfWeek != DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek)
{
startDate = startDate.AddDays(-1);
}
return startDate;
}
public static DateTime FirstDayOfNextWeek(this DateTime from)
{
var startDate = from.Date.FirstDayOfWeek();
return startDate.AddDays(7);
}
public static DateTime FirstDayOfMonth(this DateTime from)
{
return new DateTime(from.Date.Year, from.Date.Month, 1);
}
public static DateTime FirstDayOfNextMonth(this DateTime from)
{
return new DateTime(from.Date.Year, from.Date.Month, 1).AddMonths(1);
}
public static int DaysInMonth(this DateTime date)
{
return DateTime.DaysInMonth(date.Year, date.Month);
}
}
}
|
// Copyright (c) Amer Koleci and contributors.
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
namespace Vortice.Direct2D1.Effects
{
public sealed class Posterize : ID2D1Effect
{
public Posterize(ID2D1DeviceContext context)
: base(context.CreateEffect(EffectGuids.Posterize))
{
}
public Posterize(ID2D1EffectContext context)
: base(context.CreateEffect(EffectGuids.Posterize))
{
}
public int RedValueCount
{
set => SetValue((int)PosterizeProperties.RedValueCount, value);
get => GetIntValue((int)PosterizeProperties.RedValueCount);
}
public int GreenValueCount
{
set => SetValue((int)PosterizeProperties.GreenValueCount, value);
get => GetIntValue((int)PosterizeProperties.GreenValueCount);
}
public int BlueValueCount
{
set => SetValue((int)PosterizeProperties.BlueValueCount, value);
get => GetIntValue((int)PosterizeProperties.BlueValueCount);
}
}
}
|
//-----------------------------------------------------------------------------
// <copyright file="ODataHttpContentExtensions.cs" company=".NET Foundation">
// Copyright (c) .NET Foundation and Contributors. All rights reserved.
// See License.txt in the project root for license information.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.OData.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OData;
namespace Microsoft.AspNet.OData.Batch
{
/// <summary>
/// Provides extension methods for the <see cref="HttpContent"/> class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ODataHttpContentExtensions
{
/// <summary>
/// Gets the <see cref="ODataMessageReader"/> for the <see cref="HttpContent"/> stream.
/// </summary>
/// <param name="requestContainer">The dependency injection container for the request.</param>
/// <param name="content">The <see cref="HttpContent"/>.</param>
/// <returns>A task object that produces an <see cref="ODataMessageReader"/> when completed.</returns>
public static Task<ODataMessageReader> GetODataMessageReaderAsync(this HttpContent content,
IServiceProvider requestContainer)
{
return GetODataMessageReaderAsync(content, requestContainer, CancellationToken.None);
}
/// <summary>
/// Gets the <see cref="ODataMessageReader"/> for the <see cref="HttpContent"/> stream.
/// </summary>
/// <param name="requestContainer">The dependency injection container for the request.</param>
/// <param name="content">The <see cref="HttpContent"/>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task object that produces an <see cref="ODataMessageReader"/> when completed.</returns>
public static async Task<ODataMessageReader> GetODataMessageReaderAsync(this HttpContent content,
IServiceProvider requestContainer, CancellationToken cancellationToken)
{
if (content == null)
{
throw Error.ArgumentNull("content");
}
cancellationToken.ThrowIfCancellationRequested();
Stream contentStream = await content.ReadAsStreamAsync();
IODataRequestMessage oDataRequestMessage = ODataMessageWrapperHelper.Create(contentStream, content.Headers,
requestContainer);
ODataMessageReaderSettings settings = requestContainer.GetRequiredService<ODataMessageReaderSettings>();
ODataMessageReader oDataMessageReader = new ODataMessageReader(oDataRequestMessage, settings);
return oDataMessageReader;
}
}
}
|
// Copyright 2020 - 2021 Vignette Project
// Licensed under MIT. See LICENSE for details.
// This software implements Live2D. Copyright (c) Live2D Inc. All Rights Reserved.
// License for Live2D can be found here: http://live2d.com/eula/live2d-open-software-license-agreement_en.html
using NUnit.Framework;
using System.Linq;
using Vignette.Live2D.Model;
namespace Vignette.Live2D.Tests.Visual.Model
{
public class TestSceneCubismModel : CubismModelTestScene
{
[Test]
public void TestModelInitialization()
{
AddAssert("has drawables", () => Model.Drawables.Any());
AddAssert("has parts", () => Model.Drawables.Any());
AddAssert("has parameters", () => Model.Parameters.Any());
AddAssert("check version", () => Model.Version != CubismMocVersion.csmMocVersion_Unknown);
}
[Test]
public void TestModelParameterUpdate()
{
var target = Model.Parameters.FirstOrDefault(p => p.Name == "ParamMouthOpenY");
AddAssert("check if default", () => target.Value == target.Default);
AddStep("set to maximum", () => Schedule(() => target.Value = target.Maximum));
AddWaitStep("wait", 5);
AddAssert("check if maximum", () => target.Value == target.Maximum);
}
}
}
|
namespace Ninject.Extensions.Interception.Fakes
{
public class ImplicitDerived : Base, IDerived
{
void IDerived.DoDerived()
{
}
}
}
|
using NgxLib;
using Prototype.Components;
namespace Prototype.Systems
{
public class AnimationSystem : TableSystem<Animator>
{
protected NgxTable<Sprite> SpriteTable { get; private set; }
public override void Initialize()
{
SpriteTable = Database.Table<Sprite>();
}
protected override void Update(Animator animator)
{
if(animator.Changed)
{
UpdateSprite(animator);
}
if(animator.NextFrame())
{
UpdateSprite(animator);
}
}
private void UpdateSprite(Animator animator)
{
var sprite = SpriteTable[animator.Entity];
var tileset = Context.Tilesets[sprite.TilesetName];
var animation = tileset.GetAnimation(animator.Animation);
if (animation == null) return;
var frame = animation.Frames[animator.FrameIndex];
animator.FrameCount = animation.Frames.Count;
animator.FrameTime = frame.FrameTime;
animator.Texels = tileset[frame.TileId].Texels;
sprite.Texels = animator.Texels;
}
}
} |
// Copyright (c) 2018 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Specialized;
using System.IO;
//from Paul Welter: http://weblogs.asp.net/pwelter34/archive/2006/02/08/create-a-relative-path-code-snippet.aspx
namespace SIL.BuildTasks.MakeWixForDirTree
{
public static class PathUtil
{
/// <summary>
/// Creates a relative path from one file
/// or folder to another.
/// </summary>
/// <param name="fromDirectory">
/// Contains the directory that defines the
/// start of the relative path.
/// </param>
/// <param name="toPath">
/// Contains the path that defines the
/// endpoint of the relative path.
/// </param>
/// <returns>
/// The relative path from the start
/// directory to the end path.
/// </returns>
/// <exception cref="ArgumentNullException"></exception>
public static string RelativePathTo(string fromDirectory, string toPath)
{
if (fromDirectory == null)
throw new ArgumentNullException(nameof(fromDirectory));
if (toPath == null)
throw new ArgumentNullException(nameof(toPath));
var isRooted = Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath);
if (isRooted)
{
if (string.Compare(Path.GetPathRoot(fromDirectory),
Path.GetPathRoot(toPath), StringComparison.OrdinalIgnoreCase) != 0)
return toPath;
}
var relativePath = new StringCollection();
var fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);
var toDirectories = toPath.Split(Path.DirectorySeparatorChar);
var length = Math.Min(fromDirectories.Length, toDirectories.Length);
var lastCommonRoot = -1;
// find common root
for (var x = 0; x < length; x++)
{
if (string.Compare(fromDirectories[x], toDirectories[x], StringComparison.OrdinalIgnoreCase) != 0)
break;
lastCommonRoot = x;
}
if (lastCommonRoot == -1)
return toPath;
// add relative folders in from path
for (var x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
if (fromDirectories[x].Length > 0)
relativePath.Add("..");
// add to folders to path
for (var x = lastCommonRoot + 1; x < toDirectories.Length; x++)
relativePath.Add(toDirectories[x]);
// create relative path
var relativeParts = new string[relativePath.Count];
relativePath.CopyTo(relativeParts, 0);
return string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);
}
}
}
|
namespace Bari.Core.Build.MergingTag
{
public interface IMergingBuilderTag
{
}
} |
using System;
using System.Collections.Generic;
#nullable disable
namespace ToHDL.Entities
{
public partial class Hero
{
public int Id { get; set; }
public string HeroName { get; set; }
public int Hp { get; set; }
/// <summary>
/// This property is a fk reference to the element table
/// </summary>
/// <value></value>
public int? ElementType { get; set; }
public virtual ElementType ElementTypeNavigation { get; set; }
public virtual Superpower Superpower { get; set; }
}
}
|
using System.Runtime.Serialization;
namespace LM.Responses
{
[DataContract]
public class Maybe<TValue>
{
Maybe() { }
Maybe(TValue value) => Value = value;
public static Maybe<TValue> Create(TValue value) => new Maybe<TValue>(value);
public static Maybe<TValue> Create() => new Maybe<TValue>();
[DataMember]
public bool HasValue => Value != null;
[DataMember]
public TValue Value { get; set; }
public static implicit operator Maybe<TValue>(TValue value) => Create(value);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class One_Way_Platforms : MonoBehaviour
{
PlatformEffector2D effector;
void Start(){
effector = GetComponent<PlatformEffector2D>();
}
// When holding down, the player can fall through the one way platforms
void Update()
{
// When down is being held, the surface arc of the platforms becomes 0 (intangible)
if (Input.GetKey(KeyCode.DownArrow)){
effector.surfaceArc = 0f;
}
// Once released, it's set back to 90 degrees (collider only active from above)
else{
effector.surfaceArc = 90f;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Common.Core;
using Microsoft.Common.Core.IO;
using Microsoft.Common.Core.Logging;
using Microsoft.R.Common.Core.Output;
using Microsoft.R.Host.Client.Session;
namespace Microsoft.R.Host.Client.BrokerServices {
internal class RemoteStaticFileServer: StaticFileServerBase {
private readonly IRSessionProvider _sessionProvider;
private const string remoteFileSession = "FileFetcher";
private IRSession _session;
public RemoteStaticFileServer(IRSessionProvider sessionProvider, IFileSystem fs, IActionLog log, IConsole console) : base(fs, log, console) {
_sessionProvider = sessionProvider;
}
public async Task<string> HandleUrlAsync(string urlStr, CancellationToken ct = default(CancellationToken)) {
await InitializeAsync(ct);
var session = _sessionProvider.GetOrCreate(remoteFileSession);
await session.EnsureHostStartedAsync(new RHostStartupInfo(), null, 3000, ct);
_session = session;
Log.WriteLine(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_StaticFileServerStarted.FormatInvariant(Listener.Prefixes.FirstOrDefault()));
Console.WriteLine(Resources.Info_StaticFileServerStarted.FormatInvariant(Listener.Prefixes.FirstOrDefault()));
string path = urlStr;
if (urlStr.StartsWithIgnoreCase("file://")) {
Uri ub = new Uri(urlStr);
path = ub.LocalPath;
}
return GetFileServerPath(path);
}
public override async Task HandleRequestAsync(HttpListenerContext context, CancellationToken ct) {
if (!_session.IsHostRunning) {
await _session.EnsureHostStartedAsync(new RHostStartupInfo(), null, 3000, ct);
}
var ub = new UriBuilder() {
Scheme = "file",
Host = "",
Path = context.Request.Url.AbsolutePath
};
var uri = ub.Uri.LocalPath;
if (await _session.FileExistsAsync(uri, ct)) {
await CopyFileAsync(uri, context, ct);
return;
}
}
private async Task CopyFileAsync(string path, HttpListenerContext context, CancellationToken ct) {
using (DataTransferSession dts = new DataTransferSession(_session, FileSystem)) {
await dts.CopyToFileStreamAsync(path, context.Response.OutputStream, true, null, ct);
}
context.Response.OutputStream.Close();
}
}
}
|
using Borg.Platform.Azure.Cosmos;
using System;
namespace Borg.Platform.Azure.Tests
{
public class Emulator
{
static Emulator()
{
CosmosConnection = new DocDbConfig()
{
Endpoint = "https://localhost:8081/",
AuthKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
Database = $"test{DateTimeOffset.UtcNow.Ticks}"
};
}
public const string AzureStorageConnection = "UseDevelopmentStorage=true";
public static DocDbConfig CosmosConnection { get; }
}
} |
using Reactive.Bindings;
namespace SandBeige.MediaBox.Composition.Interfaces.Models.TaskQueue.Objects {
/// <summary>
/// タスク状態オブジェクト
/// </summary>
public class StateObject {
/// <summary>
/// タスク名
/// </summary>
public IReactiveProperty<string> Name {
get;
} = new ReactiveProperty<string>();
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
namespace Divergent.ITOps.ViewModelComposition
{
public class CamelCaseToPascalSettings
{
static JsonSerializerSettings settings;
static CamelCaseToPascalSettings()
{
settings = new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new CamelCaseToPascalCaseExpandoObjectConverter() }
};
}
public static JsonSerializerSettings GetSerializerSettings()
{
return settings;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Amazon.Core.DataStructures
{
public class LinkedListTest
{
public static void Run()
{
var list = new LinkedList<string>();
list.AddLast("last item");
list.AddFirst("first item");
var item = list.First;
DisplayList(list);
list.AddAfter(item, "second item");
DisplayList(list);
item = list.Last;
list.AddBefore(item, "item before last");
DisplayList(list);
Console.ReadKey();
}
static void DisplayList(LinkedList<string> list)
{
foreach (var item in list)
Console.WriteLine(item);
Console.WriteLine("- - - ");
}
}
}
|
// Copyright (c) Drew Noakes and contributors. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using static MetadataExtractor.Formats.Wav.WavFormatDirectory;
namespace MetadataExtractor.Formats.Wav
{
/// <author>Dmitry Shechtman</author>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public sealed class WavFormatDescriptor : TagDescriptor<WavFormatDirectory>
{
#if NET35 || NET45
private static readonly byte[] _emptyByteArray = new byte[0];
#else
private static readonly byte[] _emptyByteArray = Array.Empty<byte>();
#endif
public WavFormatDescriptor(WavFormatDirectory directory)
: base(directory)
{
}
public override string? GetDescription(int tag)
{
return tag switch
{
TagFormat => GetFormatDescription(),
TagSamplesPerSec => Directory.GetUInt32(tag).ToString("0 bps"),
TagBytesPerSec => Directory.GetUInt32(tag).ToString("0 bps"),
TagSubformat => BitConverter.ToString(Directory.GetByteArray(tag) ?? _emptyByteArray).Replace("-", ""),
_ => base.GetDescription(tag),
};
}
private string? GetFormatDescription()
{
var value = Directory.GetUInt16(TagFormat);
return value switch
{
1 => "PCM",
3 => "IEEE float",
6 => "8-bit ITU-T G.711 A-law",
7 => "8-bit ITU-T G.711 µ-law",
0xFFFE => "Determined by Subformat",
_ => $"Unknown ({value})"
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Inheritance.Lab01.Sample.Solution
{
class Rectangle : FourSidedFigure
{
public int Height;
public int Width;
public override int Area()
{
return base.CalculateAreaOfRectangularFourSidedFigure(Width, Height);
}
}
}
|
using AltV.Net.Shared.Elements.Entities;
namespace AltV.Net.Client.Elements.Interfaces
{
public interface IBaseObject : ISharedBaseObject
{
new ICore Core { get; }
public void Remove();
}
} |
using Mediator.Colleague;
namespace Mediator.Mediator
{
public interface IFacebookGroupMediator
{
void SendMessage(string msg, User user);
void RegisterUser(User user);
}
}
|
namespace SnipInsight.Forms
{
public partial class Styles
{
public Styles()
{
this.InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magic.Data;
using Magic.IO;
using Magic.Net.Security;
namespace Magic.Net.Packets.Server
{
[PacketIdentifier(0x02, PacketType.ServerPacket)]
public class SMKeyS02 : GamePacket<ConnectionInfo>
{
public byte[] SMKey;
public bool Force;
public override DataStream Deserialize(DataStream ds, VersionControl vc)
{
SMKey = ds.ReadBytes();
Force = ds.ReadBoolean();
return ds;
}
protected internal override void HandleData(ConnectionInfo data)
{
var CMKey = new byte[16];
var rnd = new Random();
rnd.NextBytes(CMKey);
data.SMKey = SMKey;
data.CMKey = CMKey;
MD5Hash md5Hash = data.MD5;
byte[] encKey = md5Hash.GetKey(SMKey);
byte[] decKey = md5Hash.GetKey(CMKey);
data.RC4Enc = new Rc4Encryption(encKey);
data.RC4Dec = new Rc4Encryption(decKey);
data.MPPC = new MppcUnpacker();
}
}
}
|
using System;
using System.Linq;
using Foundation;
using Toggl.Daneel.Cells.Calendar;
using Toggl.Foundation.MvvmCross.Collections;
using Toggl.Foundation.MvvmCross.ViewModels.Selectable;
using UIKit;
namespace Toggl.Daneel.ViewSources
{
public sealed class SelectUserCalendarsTableViewSource
: ReactiveSectionedListTableViewSource<SelectableUserCalendarViewModel, SelectableUserCalendarViewCell>
{
private const int rowHeight = 48;
private const int headerHeight = 48;
private const string cellIdentifier = nameof(SelectableUserCalendarViewCell);
private const string headerIdentifier = nameof(UserCalendarListHeaderViewCell);
public UIColor SectionHeaderBackgroundColor { get; set; } = UIColor.White;
public SelectUserCalendarsTableViewSource(
UITableView tableView,
ObservableGroupedOrderedCollection<SelectableUserCalendarViewModel> items
)
: base(items, cellIdentifier)
{
tableView.RegisterNibForCellReuse(SelectableUserCalendarViewCell.Nib, cellIdentifier);
tableView.RegisterNibForHeaderFooterViewReuse(UserCalendarListHeaderViewCell.Nib, headerIdentifier);
}
public override nfloat GetHeightForHeader(UITableView tableView, nint section)
=> headerHeight;
public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath)
=> rowHeight;
public override UIView GetViewForHeader(UITableView tableView, nint section)
{
var header = (UserCalendarListHeaderViewCell)tableView.DequeueReusableHeaderFooterView(headerIdentifier);
header.Item = DisplayedItems[(int)section].First().SourceName;
header.ContentView.BackgroundColor = SectionHeaderBackgroundColor;
return header;
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
base.RowSelected(tableView, indexPath);
var cell = (SelectableUserCalendarViewCell)tableView.CellAt(indexPath);
cell.UpdateView(true);
tableView.DeselectRow(indexPath, true);
}
public override void RefreshHeader(UITableView tableView, int section)
{
}
}
}
|
using System;
using UnityEngine;
[CreateAssetMenu(fileName = "New BoolVariable", menuName = "Blackboard/Variables/Bool", order = 0)]
public class BoolVariable : BlackboardVariable
{
public bool value;
private bool valueSnapshot;
public override BVarSave CreateSave()
{
return new BVSBoolVariable(value);
}
public override void LoadFrom(BVarSave source)
{
value = ((BVSBoolVariable) source).value;
}
public override Type GetSaveType()
{
return typeof(BVSBoolVariable);
}
public override void SnapshotState()
{
valueSnapshot = value;
}
public override void UndoChanges()
{
value = valueSnapshot;
}
} |
using System;
namespace Wxl.Extensions.StringExtensions
{
public static class StringLengthExtensions
{
/// <summary>
/// Determine if length of a given string is shorter than a given length
/// </summary>
/// <exception cref="ArgumentException">Thrown when <paramref name="length"/> is positive</exception>
public static bool ShorterLengthThan(this string value, int length)
{
return ShorterLengthThanImpl(value, length);
}
/// <summary>
/// Ensure length of <paramref name="value"/> is longer than given <paramref name="length"/>
/// </summary>
/// <exception cref="ArgumentException">Thrown when <paramref name="length"/> is positive</exception>
public static bool LongerLengthThan(this string value, int length)
{
return LongerLengthThanImpl(value, length);
}
#region Implementations
private static bool ShorterLengthThanImpl(string value, int length)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), "Argument cannot be null");
}
if (length <= 0)
{
throw new ArgumentOutOfRangeException(nameof(length), $"Argument must be a positive integer");
}
// Max length of a string is equal to max value of int
if (length == int.MaxValue)
{
return true;
}
return value.Length < length;
}
private static bool LongerLengthThanImpl(string value, int length)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), "Argument cannot be null");
}
if (length <= 0)
{
throw new ArgumentOutOfRangeException(nameof(length), $"Argument must be a positive integer");
}
// Max length of a string is equal to max value of int
if (length == int.MaxValue)
{
return true;
}
return value.Length > length;
}
#endregion
}
}
|
#region License
// Copyright 2017 Tua Rua Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Additional Terms
// No part, or derivative of this Air Native Extension's code is permitted
// to be sold as the basis of a commercially packaged Air Native Extension which
// undertakes the same purpose as this software. That is, a WebView for Windows,
// OSX and/or iOS and/or Android.
// All Rights Reserved. Tua Rua Ltd.
#endregion
using System;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT;
using Microsoft.Toolkit.Wpf.UI.Controls;
using Newtonsoft.Json.Linq;
using TuaRua.FreSharp;
using WebViewANELib.Edge;
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace WebViewANELib {
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")]
public partial class EdgeView : IWebView {
public int CurrentTab { get; private set; }
public ArrayList TabDetails { get; } = new ArrayList();
private readonly ArrayList _tabs = new ArrayList();
private WebView _currentBrowser;
public int X { get; set; }
public int Y { get; set; }
public int ViewWidth { get; set; }
public int ViewHeight { get; set; }
public string InjectCode { get; set; }
public string InjectScriptUrl { get; set; }
public int InjectStartLine { get; set; }
public UrlRequest InitialUrl { private get; set; }
public ArrayList WhiteList { private get; set; }
public ArrayList BlackList { private get; set; }
public static FreContextSharp Context;
public void Init() {
InitializeComponent();
IsManipulationEnabled = true;
var browser = CreateNewBrowser();
_currentBrowser = browser;
MainGrid.Children.Add(_currentBrowser);
}
private WebView CreateNewBrowser() {
// ReSharper disable once UseObjectOrCollectionInitializer
var browser = new WebView {
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch,
IsJavaScriptEnabled = true,
IsIndexedDBEnabled = true,
IsPrivateNetworkClientServerCapabilityEnabled = true,
IsScriptNotifyAllowed = true,
};
browser.NavigationStarting += OnNavigationStarting;
browser.ContentLoading += OnBrowserLoadingStateChanged;
browser.DOMContentLoaded += OnBrowserTitleChanged;
browser.NavigationCompleted += OnNavigationCompleted;
browser.NewWindowRequested += OnNewWindowRequested;
browser.ScriptNotify += OnScriptNotify;
browser.Loaded += OnLoaded;
_tabs.Add(browser);
TabDetails.Add(new TabDetails());
return browser;
}
private void OnLoaded(object sender, RoutedEventArgs e) {
if (InitialUrl != null && !string.IsNullOrEmpty(InitialUrl.Url)) {
_currentBrowser.Navigate(new Uri(InitialUrl.Url));
}
}
private static void OnScriptNotify(object sender, WebViewControlScriptNotifyEventArgs e) {
Context.DispatchEvent(WebViewEvent.JsCallbackEvent, e.Value);
}
private void OnNavigationStarting(object sender, WebViewControlNavigationStartingEventArgs e) {
for (var index = 0; index < _tabs.Count; index++) {
if (!_tabs[index].Equals(sender)) continue;
var tabDetails = GetTabDetails(index);
var url = e.Uri.AbsoluteUri;
if (!IsWhiteListBlocked(url) && !IsBlackListBlocked(url)) {
if (tabDetails.Address == url) {
return;
}
tabDetails.Address = url;
SendPropertyChange(@"url", url, index);
}
else {
e.Cancel = true;
const int tab = 0;
var json = JObject.FromObject(new {url, tab});
Context.DispatchEvent(WebViewEvent.OnUrlBlocked, json.ToString());
}
}
}
private void OnBrowserLoadingStateChanged(object sender, WebViewControlContentLoadingEventArgs e) {
var browser = (WebView) sender;
for (var index = 0; index < _tabs.Count; index++) {
if (!_tabs[index].Equals(browser)) continue;
var tabDetails = GetTabDetails(index);
if (tabDetails.IsLoading) {
return;
}
tabDetails.IsLoading = true;
SendPropertyChange(@"isLoading", true, index);
if (tabDetails.CanGoForward != browser.CanGoForward) {
tabDetails.CanGoForward = browser.CanGoForward;
SendPropertyChange(@"canGoForward", browser.CanGoForward, index);
}
if (tabDetails.CanGoBack == browser.CanGoBack) return;
tabDetails.CanGoBack = browser.CanGoBack;
SendPropertyChange(@"canGoBack", browser.CanGoBack, index);
}
}
private void OnBrowserTitleChanged(object sender, WebViewControlDOMContentLoadedEventArgs e) {
for (var index = 0; index < _tabs.Count; index++) {
if (!_tabs[index].Equals(sender)) continue;
var tabDetails = GetTabDetails(index);
if (tabDetails.Title == _currentBrowser.DocumentTitle) {
return;
}
tabDetails.Title = _currentBrowser.DocumentTitle;
SendPropertyChange(@"title", _currentBrowser.DocumentTitle, index);
}
}
private void OnNavigationCompleted(object sender, WebViewControlNavigationCompletedEventArgs e) {
if (!e.IsSuccess) {
var json = JObject.FromObject(new {
url = e.Uri,
errorCode = e.WebErrorStatus,
errorText = e.WebErrorStatus.ToString(),
tab = 0
});
Context.DispatchEvent(WebViewEvent.OnFail, json.ToString());
return;
}
var browser = (WebView) sender;
for (var index = 0; index < _tabs.Count; index++) {
if (!_tabs[index].Equals(browser)) continue;
var tabDetails = GetTabDetails(index);
if (!tabDetails.IsLoading) return;
tabDetails.IsLoading = false;
SendPropertyChange(@"isLoading", false, index);
}
}
private void OnNewWindowRequested(object sender, WebViewControlNewWindowRequestedEventArgs e) {
Load(e.Uri.ToString());
}
private TabDetails GetTabDetails(int tab) {
return (TabDetails) TabDetails[tab];
}
public void AddTab() {
Context.DispatchEvent("TRACE", "AddTab Unavailable in Edge");
}
public void SetCurrentTab(int index) {
Context.DispatchEvent("TRACE", "SetCurrentTab Unavailable in Edge");
}
public void CloseTab(int index) {
Context.DispatchEvent("TRACE", "CloseTab Unavailable in Edge");
}
private static void SendPropertyChange(string propName, bool value, int tab) {
var json = JObject.FromObject(new {propName, value, tab});
Context.DispatchEvent(WebViewEvent.OnPropertyChange, json.ToString());
}
private static void SendPropertyChange(string propName, string value, int tab) {
var json = JObject.FromObject(new {propName, value, tab});
Context.DispatchEvent(WebViewEvent.OnPropertyChange, json.ToString());
}
private void Load(string url) {
try {
_currentBrowser.Navigate(new Uri(url));
}
catch (Exception e) {
Context.DispatchEvent("TRACE", e.Message);
}
}
private void LoadFile(string url, string allowingReadAccessTo) {
var fName = Path.GetFileName(url);
if (fName == null) return;
var relativeUrl = new Uri(fName, UriKind.Relative);
var resolver = new StreamResolver(allowingReadAccessTo);
try {
_currentBrowser.NavigateToLocalStreamUri(relativeUrl, resolver);
}
catch (Exception e) {
Context.DispatchEvent("TRACE", e.Message);
}
}
public void Load(UrlRequest url, string allowingReadAccessTo = null) {
if (allowingReadAccessTo != null) {
LoadFile(url.Url, allowingReadAccessTo);
}
else {
try {
var headers = url.RequestHeaders;
_currentBrowser.Navigate(new Uri(url.Url), HttpMethod.Get, null,
headers.Count > 0 ? headers : null);
}
catch (Exception e) {
Context.DispatchEvent("TRACE", e.Message);
}
}
}
public void LoadHtmlString(string html, UrlRequest url) {
_currentBrowser.NavigateToString(html);
}
public void ZoomIn() {
Context.DispatchEvent("TRACE", "ZoomIn Unavailable in Edge");
}
public void ZoomOut() {
Context.DispatchEvent("TRACE", "ZoomOut Unavailable in Edge");
}
public void ForceFocus() {
_currentBrowser.Focus();
}
public void Reload(bool ignoreCache = false) {
_currentBrowser.Refresh();
}
public void Stop() {
_currentBrowser.Stop();
}
public void Back() {
if (_currentBrowser.CanGoBack) {
_currentBrowser.GoBack();
}
}
public void Forward() {
if (_currentBrowser.CanGoForward) {
_currentBrowser.GoForward();
}
}
public void Print() {
Context.DispatchEvent("TRACE", "Print Unavailable in Edge");
}
public void PrintToPdfAsync(string path) {
Context.DispatchEvent("TRACE", "PrintToPdfAsync Unavailable in Edge");
}
public void AddEventListener(string type) {
Context.DispatchEvent("TRACE", "AddEventListener Unavailable in Edge");
}
public void RemoveEventListener(string type) {
Context.DispatchEvent("TRACE", "RemoveEventListener Unavailable in Edge");
}
public void ShowDevTools() {
Context.DispatchEvent("TRACE", "ShowDevTools Unavailable in Edge");
}
public void CloseDevTools() {
Context.DispatchEvent("TRACE", "CloseDevTools Unavailable in Edge");
}
public async void EvaluateJavaScript(string javascript, string callback) {
var task = _currentBrowser.InvokeScriptAsync("eval", javascript);
await task.ContinueWith(previous => {
JObject json;
if (previous.Status == TaskStatus.RanToCompletion) {
json = JObject.FromObject(new {
message = (string) null,
error = (string) null,
result = (object) previous.Result,
success = true,
callbackName = callback
});
Context.DispatchEvent(WebViewEvent.AsCallbackEvent, json.ToString());
}
else {
json = JObject.FromObject(new {
message = (string) null,
error = previous.Exception?.Message,
result = (object) null,
success = false,
callbackName = callback
});
Context.DispatchEvent(WebViewEvent.AsCallbackEvent, json.ToString());
}
}, TaskContinuationOptions.ExecuteSynchronously);
}
public void EvaluateJavaScript(string javascript) {
_currentBrowser.InvokeScript("eval", javascript);
}
public void DeleteCookies() {
Context.DispatchEvent("TRACE", "DeleteCookies Unavailable in Edge");
}
private bool IsWhiteListBlocked(string url) {
return WhiteList != null && WhiteList.Count != 0 &&
!WhiteList.Cast<string>().Any(s => url.ToLower().Contains(s.ToLower()));
}
private bool IsBlackListBlocked(string url) {
return BlackList != null && BlackList.Count != 0 &&
BlackList.Cast<string>().Any(s => url.ToLower().Contains(s.ToLower()));
}
}
} |
using System;
using AeroSharp.DataAccess;
using AeroSharp.DataAccess.Policies;
using FluentAssertions;
using NUnit.Framework;
namespace AeroSharp.UnitTests.DataAccess.Policies
{
[TestFixture]
[Category("Aerospike")]
public class InfoConfigurationToInfoPolicyMapperTests
{
[Test]
public void InfoConfig_Maps_Correctly_to_InfoPolicy()
{
var config = new InfoConfiguration { RequestTimeout = TimeSpan.FromMilliseconds(5000) };
var result = InfoConfigurationToInfoPolicyMapper.MapToPolicy(config);
result.timeout.Should().Be((int)config.RequestTimeout.TotalMilliseconds);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BusinessLayer.DataTransferObjects;
using BusinessLayer.DataTransferObjects.Filters;
using BusinessLayer.QueryObjects;
using BusinessLayerTesting.QueryObjectsTests.Common;
using EntityDatabase;
using NUnit.Framework;
using WCIWT.Infrastructure.Query.Predicates;
using WCIWT.Infrastructure.Query.Predicates.Operators;
namespace BusinessLayerTesting.QueryObjectsTests
{
[TestFixture]
public class HashtagQueryObjectTest
{
[Test]
public async Task ApplyWhereClause_FilterByPostId_ReturnsCorrectPredicate()
{
Guid filteredPostId = Guid.NewGuid();
var mockManager = new QueryMockManager();
var expectedPredicate = new CompositePredicate(new List<IPredicate>
{
new SimplePredicate(nameof(Hashtag.PostId), ValueComparingOperator.Equal, filteredPostId)
}, LogicalOperator.AND);
var mapperMock = mockManager.ConfigureMapperMock<Hashtag, HashtagDto, HashtagFilterDto>();
var queryMock = mockManager.ConfigureQueryMock<Hashtag>();
var hashtagQueryObject = new HashtagQueryObject(mapperMock.Object, queryMock.Object);
var filter = new HashtagFilterDto { PostId = filteredPostId };
var temp = await hashtagQueryObject.ExecuteQuery(filter);
Assert.AreEqual(expectedPredicate, mockManager.CapturedPredicate);
}
[Test]
public async Task ApplyWhereClause_FilterByTagString_ReturnsCorrectPredicate()
{
const string filteredTag = "Hashtag";
var mockManager = new QueryMockManager();
var expectedPredicate = new CompositePredicate(new List<IPredicate>
{
new SimplePredicate(nameof(Hashtag.Tag), ValueComparingOperator.Equal, filteredTag)
}, LogicalOperator.AND);
var mapperMock = mockManager.ConfigureMapperMock<Hashtag, HashtagDto, HashtagFilterDto>();
var queryMock = mockManager.ConfigureQueryMock<Hashtag>();
var hashtagQueryObject = new HashtagQueryObject(mapperMock.Object, queryMock.Object);
var filter = new HashtagFilterDto { Tag = filteredTag };
var temp = await hashtagQueryObject.ExecuteQuery(filter);
Assert.AreEqual(expectedPredicate, mockManager.CapturedPredicate);
}
[Test]
public async Task ApplyWhereClause_ComplexFilterByPostIdAndTagString_ReturnsCorrectPredicate()
{
Guid filteredPostId = Guid.NewGuid();
const string filteredTag = "Hashtag";
var mockManager = new QueryMockManager();
var expectedPredicate = new CompositePredicate(new List<IPredicate>
{
new SimplePredicate(nameof(Hashtag.Tag), ValueComparingOperator.Equal, filteredTag),
new SimplePredicate(nameof(Hashtag.PostId), ValueComparingOperator.Equal, filteredPostId)
}, LogicalOperator.AND);
var mapperMock = mockManager.ConfigureMapperMock<Hashtag, HashtagDto, HashtagFilterDto>();
var queryMock = mockManager.ConfigureQueryMock<Hashtag>();
var hashtagQueryObject = new HashtagQueryObject(mapperMock.Object, queryMock.Object);
var filter = new HashtagFilterDto { PostId = filteredPostId, Tag = filteredTag };
var temp = await hashtagQueryObject.ExecuteQuery(filter);
Assert.AreEqual(expectedPredicate, mockManager.CapturedPredicate);
}
[Test]
public async Task ApplyWhereClause_EmptyFilter_ReturnsNull()
{
var mockManager = new QueryMockManager();
var mapperMock = mockManager.ConfigureMapperMock<Hashtag, HashtagDto, HashtagFilterDto>();
var queryMock = mockManager.ConfigureQueryMock<Hashtag>();
var hashtagQueryObject = new HashtagQueryObject(mapperMock.Object, queryMock.Object);
var filter = new HashtagFilterDto();
var temp = await hashtagQueryObject.ExecuteQuery(filter);
Assert.AreEqual(null, mockManager.CapturedPredicate);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.