content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Umbraco.Core.Models.PublishedContent;
namespace YuzuDelivery.Umbraco.Grid
{
public static class GridExtensions
{
public static IGridItem GridPartial(this HtmlHelper helper, IPublishedElement publishedElement)
{
var overrideGridItems = DependencyResolver.Current.GetServices<IGridItem>();
var gridItem = overrideGridItems
.Where(x => x.ElementType == publishedElement.GetType())
.Cast<IGridItem>()
.FirstOrDefault();
if (gridItem == null)
{
var gridItems = DependencyResolver.Current.GetService<IGridItemInternal[]>();
return gridItems
.Where(x => x.ElementType == publishedElement.GetType())
.Cast<IGridItem>()
.FirstOrDefault();
}
else
return gridItem;
}
public static R GridPartial<R>(this HtmlHelper helper)
where R : IGridItem
{
var overrideGridItems = DependencyResolver.Current.GetServices<IGridItem>();
var gridItem = overrideGridItems
.Where(x => x.ElementType == typeof(R))
.Cast<IGridItem>()
.FirstOrDefault();
if (gridItem == null)
{
var gridItems = DependencyResolver.Current.GetServices<IGridItemInternal[]>();
return gridItems
.Cast<IGridItem>()
.Where(x => x.ElementType == typeof(R))
.Cast<R>()
.FirstOrDefault();
}
else
return ((R)gridItem);
}
}
}
|
namespace TableQueryParser.Core.Values
{
internal class StringValue : IValue
{
private readonly string _value;
public StringValue(string value)
{
_value = value;
}
public bool LessThan(object value)
{
if (value is string)
return _value.CompareTo(value) > 0;
return false;
}
public bool GreaterThan(object value)
{
if(value is string)
return _value.CompareTo(value) < 0;
return false;
}
public bool EqualTo(object value)
{
if (value is string)
return _value.Equals(value);
return false;
}
public override string ToString()
{
return $"\"{_value}\"";
}
}
} |
using System;
using System.IO;
#if CONTRACTS_FULL_SHIM
using Contract = System.Diagnostics.ContractsShim.Contract;
#else
using Contract = System.Diagnostics.Contracts.Contract; // SHIM'D
#endif
using FA = System.IO.FileAccess;
namespace KSoft.Phoenix.Resource.ECF
{
public enum EcfFileBuilderOptions
{
[Obsolete(EnumBitEncoderBase.kObsoleteMsg, true)] kNumberOf,
};
public sealed class EcfFileBuilder
: EcfFileUtil
{
/// <see cref="EcfFileBuilderOptions"/>
public Collections.BitVector32 BuilderOptions;
public EcfFileBuilder(string listingPath)
{
if (Path.GetExtension(listingPath) != EcfFileDefinition.kFileExtension)
listingPath += EcfFileDefinition.kFileExtension;
mSourceFile = listingPath;
}
#region Reading
bool ReadInternal()
{
bool result = true;
if (ProgressOutput != null)
ProgressOutput.WriteLine("Trying to read source listing {0}...", mSourceFile);
if (!File.Exists(mSourceFile))
result = false;
else
{
using (var xml = new IO.XmlElementStream(mSourceFile, FA.Read, this))
{
xml.InitializeAtRootElement();
EcfDefinition.Serialize(xml);
}
EcfDefinition.CullChunksPossiblyWithoutFileData((chunkIndex, chunk) =>
{
if (VerboseOutput != null)
VerboseOutput.WriteLine("\t\tCulling chunk #{0} since it has no associated file data",
chunkIndex);
});
}
if (result == false)
{
if (ProgressOutput != null)
ProgressOutput.WriteLine("\tFailed!");
}
return result;
}
public bool Read() // read the listing definition
{
bool result = true;
try { result &= ReadInternal(); }
catch (Exception ex)
{
if (VerboseOutput != null)
VerboseOutput.WriteLine("\tEncountered an error while trying to read listing: {0}", ex);
result = false;
}
return result;
}
#endregion
#region Building
public bool Build(string workPath, string outputPath = null)
{
if (string.IsNullOrWhiteSpace(outputPath))
outputPath = workPath;
bool result = true;
try
{
result = BuildInternal(workPath, outputPath);
} catch (Exception ex)
{
if (VerboseOutput != null)
VerboseOutput.WriteLine("\tEncountered an error while building the ECF: {0}", ex);
result = false;
}
return result;
}
bool BuildInternal(string workPath, string outputPath)
{
EcfDefinition.WorkingDirectory = workPath;
string ecf_name = EcfDefinition.EcfName;
if (ecf_name.IsNotNullOrEmpty())
{
ecf_name = Path.GetFileNameWithoutExtension(mSourceFile);
}
string ecf_filename = Path.Combine(outputPath, ecf_name);
#if false // I'm no longer doing this since we don't strip the file ext off listing when expanding
// #TODO I bet a user could forget to include the preceding dot
if (EcfDefinition.EcfFileExtension.IsNotNullOrEmpty())
ecf_filename += EcfDefinition.EcfFileExtension;
#endif
if (File.Exists(ecf_filename))
{
var attrs = File.GetAttributes(ecf_filename);
if (attrs.HasFlag(FileAttributes.ReadOnly))
throw new IOException("ECF file is readonly, can't build: " + ecf_filename);
}
mEcfFile = new EcfFile();
mEcfFile.SetupHeaderAndChunks(EcfDefinition);
const FA k_mode = FA.Write;
const int k_initial_buffer_size = 8 * IntegerMath.kMega; // 8MB
if (ProgressOutput != null)
ProgressOutput.WriteLine("Building {0} to {1}...", ecf_name, outputPath);
if (ProgressOutput != null)
ProgressOutput.WriteLine("\tAllocating memory...");
bool result = true;
using (var ms = new MemoryStream(k_initial_buffer_size))
using (var ecf_memory = new IO.EndianStream(ms, Shell.EndianFormat.Big, this, permissions: k_mode))
{
ecf_memory.StreamMode = k_mode;
ecf_memory.VirtualAddressTranslationInitialize(Shell.ProcessorSize.x32);
long preamble_size = mEcfFile.CalculateHeaderAndChunkEntriesSize();
ms.SetLength(preamble_size);
ms.Seek(preamble_size, SeekOrigin.Begin);
// now we can start embedding the files
if (ProgressOutput != null)
ProgressOutput.WriteLine("\tPacking chunks...");
result = result && PackChunks(ecf_memory);
if (result)
{
if (ProgressOutput != null)
ProgressOutput.WriteLine("\tFinializing...");
// seek back to the start of the ECF and write out the finalized header and chunk descriptors
ms.Seek(0, SeekOrigin.Begin);
mEcfFile.Serialize(ecf_memory);
Contract.Assert(ecf_memory.BaseStream.Position == preamble_size,
"Written ECF header size is NOT EQUAL what we calculated");
// Update sizes and checksums
ms.Seek(0, SeekOrigin.Begin);
mEcfFile.SerializeBegin(ecf_memory, isFinalizing: true);
mEcfFile.SerializeEnd(ecf_memory);
// finally, bake the ECF memory stream into a file
using (var fs = new FileStream(ecf_filename, FileMode.Create, FA.Write))
ms.WriteTo(fs);
}
}
return result;
}
bool PackChunks(IO.EndianStream ecfStream)
{
bool success = true;
foreach (var chunk in EcfDefinition.Chunks)
{
if (ProgressOutput != null)
ProgressOutput.Write("\r\t\t{0} ", chunk.Id.ToString("X16"));
success = success && BuildChunkToStream(ecfStream, chunk);
if (!success)
break;
}
if (success && ProgressOutput != null)
ProgressOutput.Write("\r\t\t{0} \r", new string(' ', 16));
return success;
}
bool BuildChunkToStream(IO.EndianStream ecfStream, EcfFileChunkDefinition chunk)
{
bool success = true;
var raw_chunk = mEcfFile.GetChunk(chunk.RawChunkIndex);
using (var chunk_ms = EcfDefinition.GetChunkFileDataStream(chunk))
{
raw_chunk.BuildBuffer(ecfStream, chunk_ms);
}
return success;
}
#endregion
};
} |
using Microsoft.Azure.OpenApiExtensions.Attributes;
//using System.Text.Json.Serialization;
namespace ArmResourceProviderDemo.WebModels.Traffic
{
//[JsonConverter(typeof(TrafficJsonConverter))]
[SwaggerVirtualInheritances(typeof(TrafficKindsVirtualInheritanceProvider), nameof(TrafficResource))]
public class TrafficResource : ResourceProxy<TrafficBaseProperties>, IPropertiesHolder<TrafficBaseProperties>
{
[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
public new TrafficKind Kind { get; set; }
}
public enum TrafficKind
{
India,
Israel
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BattleNetLibrary.Models
{
public class GamesAndSubs
{
public class GameAccount
{
public class AccountUniqueId
{
public long gameAccountId;
public int gameServiceRegionId;
public long programId;
}
public long titleId;
public string localizedGameName;
public string gameAccountName;
public AccountUniqueId gameAccountUniqueId;
public string gameAccountRegion;
public string regionalGameFranchiseIconFilename;
public string gameAccountStatus;
public bool titleHasSubscriptions;
public bool titleHasGameTime;
}
public List<GameAccount> gameAccounts;
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using IO = System.IO;
namespace Content_Pipeline.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
var files = IO.Directory.GetFiles(@"..\data\original");
Files = files;
}
public async Task OnPost(string name, IFormFile file)
{
if (string.IsNullOrEmpty(name) == false && IO.Path.GetExtension(file.FileName).Substring(1) == "txt")
{
using (var stream = file.OpenReadStream())
using (var reader = new StreamReader(stream))
{
IO.File.WriteAllText($@"..\data\original\{name}.txt", await reader.ReadToEndAsync());
}
}
OnGet();
Process(Files);
}
private void Process(string[] files)
{
foreach (var input in files)
{
var output = input.Replace(@"\original\", @"\processed\");
var contents = IO.File.ReadAllText(input);
IO.File.WriteAllText(output, contents.ToUpper());
}
}
public string[] Files { get; private set; }
}
} |
namespace AcmeCorp.EventSourcingExampleApp.Orders.Contracts.Dto
{
public class OrderItem
{
public OrderItem(int productId, string productDescription, decimal productPrice, int quantity)
{
this.ProductId = productId;
this.ProductDescription = productDescription;
this.ProductPrice = productPrice;
this.Quantity = quantity;
}
public int ProductId { get; }
public string ProductDescription { get; }
public decimal ProductPrice { get; }
public int Quantity { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedditSharp.Utils
{
internal static class DateTimeExtensions
{
public static double DateTimeToUnixTimestamp(this DateTime dateTime)
{
double time = (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
return Convert.ToInt32(time);
}
}
} |
using System;
namespace IDE
{
[Serializable]
public class WireProject
{
public PointProject From;
public int FromComponent;
public int FromIndex;
public int RootComponent;
public PointProject To;
public int ToComponent;
public int ToIndex;
public WireProject(Wire wire, FileProject project)
{
From = wire.From;
RootComponent = UiStatics.Circuito.Components.IndexOf(wire.RootComponent);
if (wire.FromComponent != null)
{
FromComponent = UiStatics.Circuito.Components.IndexOf(wire.FromComponent);
FromIndex = wire.FromIndex;
}
else
{
FromIndex = -1;
FromComponent = -1;
}
To = wire.To;
if (wire.ToComponent != null)
{
ToComponent = UiStatics.Circuito.Components.IndexOf(wire.ToComponent);
ToIndex = wire.ToIndex;
}
else
{
ToIndex = -1;
ToComponent = -1;
}
}
public Wire ToWire(FileProject project)
{
var wire = new Wire(From, To);
if (RootComponent != -1)
wire.RootComponent = UiStatics.Circuito.Components[RootComponent];
if (FromComponent != -1)
{
wire.FromComponent = UiStatics.Circuito.Components[FromComponent];
wire.FromIndex = FromIndex;
}
else
{
FromIndex = -1;
}
if (ToComponent != -1)
{
wire.ToComponent = UiStatics.Circuito.Components[ToComponent];
wire.ToIndex = ToIndex;
}
else
{
FromIndex = -1;
}
return wire;
}
}
} |
using Autofac;
using IFPS.Factory.Domain.Serializers.Implementations;
using IFPS.Factory.Domain.Serializers.Interfaces;
using IFPS.Factory.Domain.Services.Implementations;
using IFPS.Factory.Domain.Services.Interfaces;
namespace IFPS.Factory.API.Bootstrap.AutofacModules
{
public class DomainAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<JsonByteSerializer>().As<IByteSerializer>();
builder.RegisterAssemblyTypes(typeof(FileHandlerService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
builder.RegisterType<IdentityService>().As<IIdentityService>()
.InstancePerLifetimeScope();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Microsoft.Deployment.DotNet.Releases
{
/// <summary>
/// Describes a single runtime release.
/// </summary>
public class RuntimeReleaseComponent : ReleaseComponent
{
/// <summary>
/// The friendly display name for the component.
/// </summary>
public override string Name => ReleasesResources.RuntimeReleaseName;
/// <summary>
/// The versions of Visual Studio for Mac that includes this runtime.
/// </summary>
[JsonProperty(PropertyName = "vs-mac-version")]
public string VisualStudioMacVersion
{
get;
private set;
}
/// <summary>
/// The versions of Visual Studio that includes this runtime. Multiple versions may be listed, e.g.
/// "15.9.25, 16.0.16, 16.4.11, 16.6.4"
/// </summary>
[JsonProperty(PropertyName = "vs-version")]
public string VisualStudioVersion
{
get;
private set;
}
internal RuntimeReleaseComponent(JToken token, ProductRelease release) : base(token, release)
{
}
}
}
|
//[?] 1부터 1,000까지의 정수 중 13의 배수의 개수(건수, 횟수)
using System;
using System.Linq;
/// <summary>
/// 개수 알고리즘(Count Algorithm): 주어진 범위에 주어진 조건에 해당하는 자료들의 개수
/// </summary>
class CountAlgorithm
{
static void Main()
{
//[1] Input: 1부터 1,000까지의 데이터
var numbers = Enumerable.Range(1, 1_000).ToArray();
int count = default; // 개수를 저장할 변수는 0으로 초기화
//[2] Process: 개수 알고리즘 영역: 주어진 범위에 주어진 조건(필터링)
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] % 13 == 0) // 13의 배수면 개수 증가
{
//count = count + 1;
//count += 1;
count++; // COUNT
}
}
//[3] Output
Console.WriteLine($"1부터 1,000까지의 정수 중 13의 배수의 개수: {count}");
}
}
//Enumerable.Range(1, 1_000).ToArray().Where(n => n % 13 == 0).Count()
//76
//Enumerable.Range(1, 1_000).ToArray().Count(n => n % 13 == 0)
//76
|
using System.Reflection;
namespace FasmCode.ViewModels
{
/// <summary>
/// Represents an about information
/// </summary>
class AboutViewModel
{
/// <summary>
/// Creates a new instance of AboutViewModel
/// </summary>
public AboutViewModel()
{
Assembly assembly = Assembly.GetExecutingAssembly();
Title = assembly.GetCustomAttribute<AssemblyTitleAttribute>().Title;
Description = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
Copyright = assembly.GetCustomAttribute<AssemblyCopyrightAttribute>().Copyright;
Version = "Version " + assembly.GetName().Version.ToString();
}
/// <summary>
/// The title of the application
/// </summary>
public string Title { get; set; }
/// <summary>
/// The brief description of the application
/// </summary>
public string Description { get; set; }
/// <summary>
/// The information about the copyright
/// </summary>
public string Copyright { get; set; }
/// <summary>
/// The information about the version
/// </summary>
public string Version { get; set; }
}
} |
using System.ComponentModel.Composition;
using System.IO;
using CuttingEdge.Conditions;
namespace PhoenixVB6.ProjectModel.Exports
{
[Export(typeof(IProjectItemProvider))]
public class ProjectItemProvider : IProjectItemProvider
{
#region IProjectItemProvider Members
public virtual bool TryRead(IProjectContext context, LineInfo line, out IProjectItem item)
{
item = new ProjectItem
{
Line = line,
};
return true;
}
public virtual void Write(IProjectContext context, StreamWriter writer, IProjectItem item)
{
Condition.Requires(writer, "writer").IsNotNull();
Condition.Requires(item, "item").IsNotNull();
var projectItem = (ProjectItem)item;
writer.WriteLine(projectItem.Line.Full);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Helpers
{
public static class UrlExtensions
{
/// <summary>
/// Strips the querystring from a url and returns the result as a string
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static string StripQueryString(this Uri uri)
{
return Regex.Replace(uri.ToString(), @"\?.*$", string.Empty);
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using SmartPos.Ui;
using SmartPos.Ui.Theming;
using SmartPos.Ui.Controls;
using SmartPos.Ui.Security;
using SmartPos.Ui.Components;
using SmartPos.Desktop.Security;
using SmartPos.Desktop.Interfaces;
namespace SmartPos.Desktop.Controls
{
[PosAuthorisation]
public partial class CtrlToolBar : BaseControl
{
#region Fields
private ITheme _theme;
#endregion
#region Events
public event EventHandler OptionPressed;
#endregion
#region Constructors
public CtrlToolBar()
{
InitializeComponent();
}
#endregion
#region Overrides of BaseControl
public override void ApplyTheme(ITheme theme)
{
base.ApplyTheme(theme);
_theme = theme;
if (theme != null)
BackColor = theme.ToolBarBackground;
}
#endregion
#region Public methods
public void ResetCustomize()
{
Customize(null);
}
public void Customize(IToolBarCustomizer customizer)
{
try
{
SuspendLayout();
customizer = customizer ?? new DefaultToolBarCustomizer();
pnlLogout.Visible = customizer.ShowLogout;
pnlOptions.Visible = customizer.ShowOptions;
ClearButtons();
if (customizer.Buttons == null)
return;
foreach (var toolBarButton in customizer.Buttons)
{
var button = CreateButton(toolBarButton);
if (toolBarButton.Location == ToolBarButtonLocation.Left)
flowLeft.Controls.Add(button);
else
flowRight.Controls.Add(button);
}
}
finally
{
ResumeLayout();
}
}
#endregion
#region Private methods
private SpButton CreateButton(IToolBarButton toolBarButton)
{
var button = new SpButton
{
Text = toolBarButton.Text,
Size = btnLogout.Size
};
button.ApplyTheme(_theme);
button.Click += async (s, e) => await ToolBarCustomButtonClick(toolBarButton.Action);
return button;
}
private static Task ToolBarCustomButtonClick(Func<Task> action)
{
return action == null
? Task.CompletedTask
: action();
}
private void ClearButtons()
{
foreach (var button in flowLeft.Controls.OfType<SpButton>())
button.Dispose();
foreach (var button in flowRight.Controls.OfType<SpButton>())
button.Dispose();
flowLeft.Controls.Clear();
flowRight.Controls.Clear();
}
#endregion
#region Event handlers
private void btnLogout_Click(object sender, EventArgs e)
{
AuthenticationManager.Logout();
ParentForm.PresentMessage("Logout successful", MessageType.Info, 1000);
}
private void btnOptions_Click(object sender, EventArgs e)
{
OptionPressed?.Invoke(sender, e);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace ScottPlot.Statistics
{
public static class Common
{
private readonly static RNGCryptoServiceProvider Rand = new();
/// <summary>
/// Return the minimum, and maximum, and sum of a given array.
/// </summary>
public static (double min, double max, double sum) MinMaxSum(double[] values)
{
if (values is null)
throw new ArgumentNullException(nameof(values));
if (values.Length == 0)
throw new ArgumentException("input cannot be empty");
double min = double.MaxValue;
double max = double.MinValue;
double sum = 0;
for (int i = 0; i < values.Length; i++)
{
min = Math.Min(min, values[i]);
max = Math.Max(max, values[i]);
sum += values[i];
}
return (min, max, sum);
}
/// <summary>
/// Return the standard deviation of the given values.
/// </summary>
public static double StDev(double[] values) => StDev(values, Mean(values));
/// <summary>
/// Return the standard deviation of the given values.
/// This overload is faster because the mean of the values is provided.
/// </summary>
public static double StDev(double[] values, double mean)
{
double sumVariancesSquared = 0;
for (int i = 0; i < values.Length; i++)
{
double pointVariance = Math.Abs(mean - values[i]);
double pointVarianceSquared = Math.Pow(pointVariance, 2);
sumVariancesSquared += pointVarianceSquared;
}
double meanVarianceSquared = sumVariancesSquared / values.Length;
double stDev = Math.Sqrt(meanVarianceSquared);
return stDev;
}
/// <summary>
/// Return the standard error of the given values
/// </summary>
public static double StdErr(double[] values) => StDev(values) / Math.Sqrt(values.Length);
/// <summary>
/// Return the mean of the given values
/// </summary>
public static double Mean(double[] values)
{
double sum = 0;
for (int i = 0; i < values.Length; i++)
sum += values[i];
double mean = sum / values.Length;
return mean;
}
/// <summary>
/// Return the Nth smallest value in the given array.
/// </summary>
public static double NthOrderStatistic(double[] values, int n)
{
if (n < 1 || n > values.Length)
throw new ArgumentException("n must be a number from 1 to the length of the array");
double[] valuesCopy = new double[values.Length];
Array.Copy(values, valuesCopy, values.Length);
return QuickSelect(valuesCopy, 0, values.Length - 1, n - 1);
}
/// <summary>
/// Return the value of the Nth quantile.
/// </summary>
public static double Quantile(double[] values, int n, int quantileCount)
{
if (n == 0)
return values.Min();
else if (n == quantileCount)
return values.Max();
else
return NthOrderStatistic(values, n * values.Length / quantileCount);
}
/// <summary>
/// Return the value of the Nth quartile
/// </summary>
/// <param name="values"></param>
/// <param name="quartile">quartile 1, 2, or 3</param>
public static double Quartile(double[] values, int quartile) => Quantile(values, quartile, 4);
/// <summary>
/// Return the percentile of the given array
/// </summary>
/// <param name="values"></param>
/// <param name="percentile">number from 0 to 100</param>
/// <returns></returns>
public static double Percentile(double[] values, int percentile) => Quantile(values, percentile, 100);
/// <summary>
/// Return the percentile of the given array
/// </summary>
/// <param name="values"></param>
/// <param name="percentile">number from 0 to 100</param>
public static double Percentile(double[] values, double percentile)
{
if (percentile == 0)
return values.Min();
else if (percentile == 100)
return values.Max();
int percentileIndex = (int)(percentile / 100.0 * (values.Length - 1));
double[] copiedValues = new double[values.Length];
Array.Copy(values, copiedValues, values.Length);
return NthOrderStatistic(values, percentileIndex + 1);
}
/// <summary>
/// Return the median of the given array.
/// If the length of the array is even, this value is the mean of the upper and lower medians.
/// </summary>
public static double Median(double[] values)
{
if (values.Length % 2 == 1)
{
return NthOrderStatistic(values, values.Length / 2 + 1);
}
else
{
double lowerMedian = NthOrderStatistic(values, values.Length / 2);
double upperMedian = NthOrderStatistic(values, values.Length / 2 + 1);
return (lowerMedian + upperMedian) / 2;
}
}
/// <summary>
/// Return the kth smallest value from a range of the given array.
/// WARNING: values will be mutated.
/// </summary>
/// <param name="values"></param>
/// <param name="leftIndex">inclusive lower bound</param>
/// <param name="rightIndex">inclusive upper bound</param>
/// <param name="k">number starting at 0</param>
/// <returns></returns>
private static double QuickSelect(double[] values, int leftIndex, int rightIndex, int k)
{
/*
* QuickSelect (aka Hoare's Algorithm) is a selection algorithm
* - Given an integer k it returns the kth smallest element in a sequence) with O(n) expected time.
* - In the worst case it is O(n^2), i.e. when the chosen pivot is always the max or min at each call.
* - The use of a random pivot virtually assures linear time performance.
* - https://en.wikipedia.org/wiki/Quickselect
*/
if (leftIndex == rightIndex)
return values[leftIndex];
if (k == 0)
{
double min = values[leftIndex];
for (int j = leftIndex; j <= rightIndex; j++)
{
if (values[j] < min)
{
min = values[j];
}
}
return min;
}
if (k == rightIndex - leftIndex)
{
double max = values[leftIndex];
for (int j = leftIndex; j <= rightIndex; j++)
{
if (values[j] > max)
{
max = values[j];
}
}
return max;
}
int partitionIndex = Partition(values, leftIndex, rightIndex);
int pivotIndex = partitionIndex - leftIndex;
if (k == pivotIndex)
return values[partitionIndex];
else if (k < pivotIndex)
return QuickSelect(values, leftIndex, partitionIndex - 1, k);
else
return QuickSelect(values, partitionIndex + 1, rightIndex, k - pivotIndex - 1);
}
/// <summary>
/// Return a random integer from within the given range
/// </summary>
/// <param name="min">inclusive lower bound</param>
/// <param name="max">exclusive upper bound</param>
/// <returns></returns>
public static int GetRandomInt(int min, int max)
{
byte[] randomBytes = new byte[sizeof(int)];
Rand.GetBytes(randomBytes);
int randomInt = BitConverter.ToInt32(randomBytes, 0);
return Math.Abs(randomInt % (max - min + 1)) + min;
}
/// <summary>
/// Partition the array between the defined bounds according to elements above and below a randomly chosen pivot value
/// </summary>
/// <param name="values"></param>
/// <param name="leftIndex"></param>
/// <param name="rightIndex"></param>
/// <returns>index of the pivot used</returns>
private static int Partition(double[] values, int leftIndex, int rightIndex)
{
// Moving the pivot to the end is far easier than handling it where it is
// This also allows you to turn this into the non-randomized Partition
int initialPivotIndex = GetRandomInt(leftIndex, rightIndex);
double swap = values[initialPivotIndex];
values[initialPivotIndex] = values[rightIndex];
values[rightIndex] = swap;
double pivotValue = values[rightIndex];
int pivotIndex = leftIndex - 1;
for (int j = leftIndex; j < rightIndex; j++)
{
if (values[j] <= pivotValue)
{
pivotIndex++;
double tmp1 = values[j];
values[j] = values[pivotIndex];
values[pivotIndex] = tmp1;
}
}
pivotIndex++;
double tmp2 = values[rightIndex];
values[rightIndex] = values[pivotIndex];
values[pivotIndex] = tmp2;
return pivotIndex;
}
/// <summary>
/// Given a dataset of values return the probability density function.
/// The returned function is a Gaussian curve from 0 to 1 (not normalized)
/// </summary>
/// <param name="values">original dataset</param>
/// <returns>Function to return Y for a given X</returns>
public static Func<double, double?> ProbabilityDensityFunction(double[] values)
{
var stats = new ScottPlot.Statistics.BasicStats(values);
return x => Math.Exp(-.5 * Math.Pow((x - stats.Mean) / stats.StDev, 2));
}
/// <summary>
/// Given a dataset of values return the probability density function at specific X positions.
/// Returned values will be normalized such that their integral is 1.
/// </summary>
/// <param name="values">original dataset</param>
/// <param name="xs">Positions (Xs) for which probabilities (Ys) will be returned</param>
/// <param name="percent">if True, output will be multiplied by 100</param>
/// <returns>Densities (Ys) for each of the given Xs</returns>
public static double[] ProbabilityDensity(double[] values, double[] xs, bool percent = false)
{
var f = ProbabilityDensityFunction(values);
double[] ys = xs.Select(x => (double)f(x)).ToArray();
double sum = ys.Sum();
if (percent)
sum /= 100;
for (int i = 0; i < ys.Length; i++)
ys[i] /= sum;
return ys;
}
/// <summary>
/// Return the cumulative sum of the given data
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static double[] CumulativeSum(double[] values)
{
double[] sum = new double[values.Length];
sum[0] = values[0];
for (int i = 1; i < values.Length; i++)
{
sum[i] = sum[i - 1] + values[i];
}
return sum;
}
/// <summary>
/// Compute the histogram of a dataset.
/// </summary>
/// <param name="values">Input data</param>
/// <param name="min">Lower edge of the first bin (inclusive). If NaN, minimum of input values will be used.</param>
/// <param name="max">High edge of the largest bin (inclusive). If NaN, maximum of input values will be used.</param>
/// <param name="binSize">Width of each bin.</param>
/// <param name="density">If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin (the sum of all values will be 1 if the bin size is 1).</param>
public static (double[] hist, double[] binEdges) Histogram(double[] values, double min, double max, double binSize, bool density = false)
{
int binCount = (int)((max - min) / binSize);
return Histogram(values, binCount, density, min, max);
}
/// <summary>
/// Compute the histogram of a dataset.
/// </summary>
/// <param name="values">Input data</param>
/// <param name="binCount">Number of equal-width bins</param>
/// <param name="density">If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin (the sum of all values will be 1 if the bin size is 1).</param>
/// <param name="min">Lower edge of the first bin (inclusive). If NaN, minimum of input values will be used.</param>
/// <param name="max">High edge of the largest bin (inclusive). If NaN, maximum of input values will be used.</param>
/// <returns></returns>
public static (double[] hist, double[] binEdges) Histogram(double[] values, int binCount, bool density = false, double min = double.NaN, double max = double.NaN)
{
/* note: function signature loosely matches numpy:
* https://numpy.org/doc/stable/reference/generated/numpy.histogram.html
*/
// determine min/max based on the data (if not provided)
if (double.IsNaN(min) || double.IsNaN(max))
{
var stats = new BasicStats(values);
if (double.IsNaN(min))
min = stats.Min;
if (double.IsNaN(max))
max = stats.Max;
}
// create evenly sized bins
double binWidth = (max - min) / binCount;
double[] binEdges = new double[binCount + 1];
for (int i = 0; i < binEdges.Length; i++)
binEdges[i] = min + binWidth * i;
// place values in histogram
double[] hist = new double[binCount];
for (int i = 0; i < values.Length; i++)
{
if (values[i] < min || values[i] > max)
{
continue;
}
if (values[i] == max)
{
hist[hist.Length - 1] += 1;
continue;
}
double distanceFromMin = values[i] - min;
int binsFromMin = (int)(distanceFromMin / binWidth);
hist[binsFromMin] += 1;
}
// optionally normalize the data
if (density)
{
double binScale = hist.Sum() * binWidth;
for (int i = 0; i < hist.Length; i++)
hist[i] /= binScale;
}
return (hist, binEdges);
}
}
}
|
@using Microsoft.AspNetCore.Identity
@using MyFBPage
@using MyFBPage.Models
@using MyFBPage.Models.AccountViewModels
@using MyFBPage.Models.ManageViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Bvx
{
public class Document
{
public Document(string application, params Part[] parts)
{
this.Application = application;
this.parts.AddRange(parts);
}
private List<Part> parts = new List<Part>();
public List<Part> Parts
{
get
{
return parts;
}
}
public DateTime? DeliveryDate { get; set; }
public string Application { get; set; }
public XDocument ToXDocument()
{
var id = 1;
var parts = Parts.Select(o => o.ToXElement(id++)).ToList();
return new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Job",
new XAttribute("BvxVersion", "2.0"),
new XAttribute("ProgVersion", Application),
new XElement("Parts", parts)));
}
}
}
|
// <copyright file="IServiceLocator.cs" company="Huy Tran">
// Copyright (c) Huy Tran. All rights reserved.
// </copyright>
namespace SpeakerAutoVolume.Presentation.Interfaces
{
/// <summary>
/// Interface for ServiceLocator.
/// </summary>
public interface IServiceLocator
{
/// <summary>
/// Interface for ServiceLocator.
/// </summary>
/// <typeparam name="T">The generic type parameter.</typeparam>
/// <returns>Type T.</returns>
T GetInstance<T>()
where T : class;
}
} |
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Quark.Localization;
namespace Quark.AppService.Dtos;
[Serializable]
public record QueryRequestDto : IValidatableObject
{
public static int DefaultMaxResultCount { get; set; } = 10;
public static int MaxMaxResultCount { get; set; } = 1000;
[Range(1, int.MaxValue)]
public int MaxResultCount { get; set; } = DefaultMaxResultCount;
[Range(0, int.MaxValue)]
public int SkipCount { get; set; } = 0;
public string? Sort { get; set; }
public string? Filter { get; set; }
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (MaxResultCount > MaxMaxResultCount)
{
var localizer = validationContext.GetRequiredService<IStringLocalizer<QuarkSharedResource>>();
yield return new ValidationResult(
localizer[
"{0} can not be more than {1}! Increase {2}.{3} on the server side to allow more results.",
nameof(MaxResultCount),
MaxMaxResultCount,
typeof(QueryRequestDto).FullName!,
nameof(MaxMaxResultCount)
],
new[] { nameof(MaxResultCount) });
}
}
}
|
@model ProjetoCursoAspNetMVC.Models.Cliente
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
<p>@Model.Nome</p>
<p>@Model.SobreNome</p>
<p>@Model.DataCadastro</p>
</div>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace XSmartNote.ThemeManager.Themes.Splash
{
class LoadMessage
{
public static void Load()
{
Thread.Sleep(5000);
SplashScreen.ChangeTitle("正在加载UI组件 ... ...");
Thread.Sleep(1000);
SplashScreen.ChangeTitle("正在加载Data组件 ... ...");
Thread.Sleep(5000);
SplashScreen.ChangeTitle("正在加载主题插件 ... ...");
Thread.Sleep(1000);
SplashScreen.ChangeTitle("正在加载主界面 ... ...");
SplashScreen.Close();
}
}
}
|
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
//
// Email: gustavo_franco@hotmail.com
//
// Copyright (C) 2005 Franco, Gustavo
//
using System;
using System.Collections;
namespace WaveLib.AudioMixer
{
[Author("Gustavo Franco")]
public class MixerDetails : System.Collections.CollectionBase
{
#region Constructors & Destructors
public MixerDetails()
{
}
~MixerDetails()
{
this.InnerList.Clear();
}
#endregion
#region Methods
public bool Contains(MixerDetail detail)
{
foreach(MixerDetail mixerDetail in this.InnerList)
if (mixerDetail == detail)
return true;
return false;
}
public MixerDetail GetMixerByDeviceId(int deviceId)
{
foreach(MixerDetail mixerDetail in this.InnerList)
if (mixerDetail.DeviceId == deviceId)
return mixerDetail;
return null;
}
public MixerDetail GetMixerByIndex(int index)
{
return this[index];
}
public MixerDetail GetMixerByName(string name)
{
foreach(MixerDetail mixerDetail in this.InnerList)
if (mixerDetail.MixerName == name)
return mixerDetail;
return null;
}
public void Add(MixerDetail mixer)
{
this.InnerList.Add(mixer);
}
public void Remove(MixerDetail mixer)
{
if (this.InnerList.Contains(mixer))
{
this.InnerList.Remove(mixer);
return;
}
MixerDetail mixerDetailToRemove = null;
foreach(MixerDetail mixerDetail in this.InnerList)
{
if (mixerDetail.DeviceId == mixer.DeviceId &&
mixerDetail.MixerName == mixer.MixerName)
{
mixerDetailToRemove = mixerDetail;
break;
}
}
if (mixerDetailToRemove != null)
this.InnerList.Remove(mixerDetailToRemove);
}
#endregion
#region Indexers
public MixerDetail this[int index]
{
get
{
if (index >= this.InnerList.Count || index < 0)
return null;
return (MixerDetail) this.InnerList[index];
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.DataTransferObjects
{
public abstract class CompanyForManipulationDto
{
[Required(ErrorMessage = "Company name is a required field.")]
[MaxLength(30, ErrorMessage = "Maximum length for the Name is 30 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Company Address is a required field.")]
[MaxLength(100, ErrorMessage = "Maximum length for the Address is 100 characters.")]
public string Address { get; set; }
[Required(ErrorMessage = "Company Country is a required field.")]
[MaxLength(20, ErrorMessage = "Maximum length for the Country is 20 characters.")]
public string Country { get; set; }
public IEnumerable<EmployeeForCreationDto> Employees { get; set; }
}
}
|
using System;
namespace PSTParse.NDB
{
public class BlockTrailer
{
public uint DataSize { get; set; }
public uint WSig { get; set; }
public uint CRC { get; set; }
public ulong BID_raw { get; set; }
public BlockTrailer(byte[] bytes, int offset)
{
this.DataSize = BitConverter.ToUInt16(bytes, offset);
this.WSig = BitConverter.ToUInt16(bytes, 2 + offset);
this.CRC = BitConverter.ToUInt32(bytes, 4 + offset);
this.BID_raw = BitConverter.ToUInt64(bytes, 8 + offset);
}
}
}
|
namespace Smart.IO.ByteMapper.Builders
{
using System.Reflection;
using Smart.IO.ByteMapper.Mappers;
public interface IMemberMapperBuilder
{
int Offset { get; set; }
PropertyInfo Property { get; set; }
int CalcSize();
IMapper CreateMapper(IBuilderContext context);
}
}
|
namespace AccessModifiers
{
internal class RateCalculator
{
public int Calculate(CustomerAccess customerAccess)
{
return 0;
}
}
} |
using System.Linq;
namespace Unity.MLAgents.Sensors
{
/// <summary>
/// The compression setting for visual/camera observations.
/// </summary>
public enum SensorCompressionType
{
/// <summary>
/// No compression. Data is preserved as float arrays.
/// </summary>
None,
/// <summary>
/// PNG format. Data will be stored in binary format.
/// </summary>
PNG
}
/// <summary>
/// A description of the compression used for observations.
/// </summary>
/// <remarks>
/// Most ISensor implementations can't take advantage of compression,
/// and should return CompressionSpec.Default() from their ISensor.GetCompressionSpec() methods.
/// Visual observations, or mulitdimensional categorical observations (for example, image segmentation
/// or the piece types in a match-3 game board) can use PNG compression reduce the amount of
/// data transferred between Unity and the trainer.
/// </remarks>
public struct CompressionSpec
{
internal SensorCompressionType m_SensorCompressionType;
/// <summary>
/// The compression type that the sensor will use for its observations.
/// </summary>
public SensorCompressionType SensorCompressionType
{
get => m_SensorCompressionType;
}
internal int[] m_CompressedChannelMapping;
/// <summary>
/// The mapping of the channels in compressed data to the actual channel after decompression.
/// </summary>
/// <remarks>
/// The mapping is a list of integer index with the same length as
/// the number of output observation layers (channels), including padding if there's any.
/// Each index indicates the actual channel the layer will go into.
/// Layers with the same index will be averaged, and layers with negative index will be dropped.
/// For example, mapping for CameraSensor using grayscale and stacking of two: [0, 0, 0, 1, 1, 1]
/// Mapping for GridSensor of 4 channels and stacking of two: [0, 1, 2, 3, -1, -1, 4, 5, 6, 7, -1, -1]
/// </remarks>
public int[] CompressedChannelMapping
{
get => m_CompressedChannelMapping;
}
/// <summary>
/// Return a CompressionSpec indicating possible compression.
/// </summary>
/// <param name="sensorCompressionType">The compression type to use.</param>
/// <param name="compressedChannelMapping">Optional mapping mapping of the channels in compressed data to the
/// actual channel after decompression.</param>
public CompressionSpec(SensorCompressionType sensorCompressionType, int[] compressedChannelMapping = null)
{
m_SensorCompressionType = sensorCompressionType;
m_CompressedChannelMapping = compressedChannelMapping;
}
/// <summary>
/// Return a CompressionSpec indicating no compression. This is recommended for most sensors.
/// </summary>
/// <returns></returns>
public static CompressionSpec Default()
{
return new CompressionSpec
{
m_SensorCompressionType = SensorCompressionType.None,
m_CompressedChannelMapping = null
};
}
/// <summary>
/// Return whether the compressed channel mapping is "trivial"; if so it doesn't need to be sent to the
/// trainer.
/// </summary>
/// <returns></returns>
internal bool IsTrivialMapping()
{
var mapping = CompressedChannelMapping;
if (mapping == null)
{
return true;
}
// check if mapping equals zero mapping
if (mapping.Length == 3 && mapping.All(m => m == 0))
{
return true;
}
// check if mapping equals identity mapping
for (var i = 0; i < mapping.Length; i++)
{
if (mapping[i] != i)
{
return false;
}
}
return true;
}
}
}
|
using System;
namespace lp73.designPatterns.Builder
{
public class LiasseXml : Liasse
{
public override void AjouteDocument(string document)
{
if (document.StartsWith("<XML>"))
Contenu.Add(document);
}
public override void Imprime()
{
Console.WriteLine("Liasse XML");
foreach (string s in Contenu)
Console.WriteLine(s);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YGOPRODraft
{
public class Constants
{
public String LOTD_DAT_FILENAME = "YGO_DATA.dat";
public String LOTD_TOC_FILENAME = "YGO_DATA.toc";
public String LOTD_SAVE_FILENAME = "savegame.dat";
public String CSV_MAP_FILENAME = "card_map.csv";
public String CARD_DB_FILENAME = "cards.cdb";
public String BATTLEPACK_1_FILENAME = "bpack_BattlePack1.bin";
public String YGODATA_PACKS = "packs.zib";
public String YGODATA_DECKS = "decks.zib";
public String ADD_PACKS_FOLDER = "PUT_DRAFT_DECKS_PACKS_HERE";
public String YGO_DATA_WORKING_FOLDER = "YGO_DATA";
public String UNPACKED_SUFFIX = "_UNPACKED";
public String PATCHED_YGODATA_OUT_FOLDER = "PATCHED_YGODATA_OUT";
public String CARDS_NOT_AVAILABLE = "list_of_not_available_cards.txt";
public String DECK_DATABASE = "DECK_DATABASE";
public String AI_DECK_DRAFT_FILE_EU = "bp1_draft_eu";
public String AI_SEALED_DECK_FILE = "bp1_sealed_us";
public int MAX_AI_DRAFT_INDEX = 10;
public int MIN_AI_DRAFT_INDEX = 1;
public long BATTLEPACK_NUM_CATEGORIES = 5;
public String AI_DECK_DRAFT_FILE_US = "bp1_draft_us";
public String YDK_EXTENSION = ".ydk";
public String YDC_EXTENSION = ".ydc";
public String JSON_EXTENSION = ".json";
public String EXTRACT_DECK_PREFIX = "extracted_deck_";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using ForgottenSchism.control;
using ForgottenSchism.engine;
using ForgottenSchism.world;
namespace ForgottenSchism.screen
{
public class MainMenu: Screen
{
Label lbl_title;
SpriteFont font;
Link lnk_newGame;
Link lnk_loadGame;
Link lnk_option;
Link lnk_exit;
public MainMenu()
{
MainWindow.BackgroundImage = Content.Graphics.Instance.Images.background.bg_titleMenu;
lbl_title = new Label("Main menu");
lbl_title.center(350);
lbl_title.LabelFun = ColorTheme.LabelColorTheme.LabelFunction.TITLE;
lnk_newGame = new Link("New Game");
lnk_newGame.center(405);
lnk_newGame.selected = newGame;
lnk_loadGame = new Link("Load Game");
lnk_loadGame.center(440);
lnk_loadGame.selected = loadGame;
lnk_option = new Link("Option");
lnk_option.center(475);
lnk_option.selected = options;
lnk_exit = new Link("Exit");
lnk_exit.center(510);
lnk_exit.selected = exit;
MainWindow.add(lbl_title);
MainWindow.add(lnk_newGame);
MainWindow.add(lnk_loadGame);
MainWindow.add(lnk_option);
MainWindow.add(lnk_exit);
}
public override void start()
{
base.start();
MediaPlayer.Play(Content.Instance.audio.songs.test);
MediaPlayer.IsRepeating = true;
}
private void options(object o, EventArgs e)
{
StateManager.Instance.goForward(new Options());
}
public void loadGame(object o, EventArgs e)
{
StateManager.Instance.goForward(new Load());
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (InputHandler.keyReleased(Keys.Escape))
Game.Exit();
}
private void exit(object sender, EventArgs e)
{
Game.Exit();
}
private void newGame(object sender, EventArgs e)
{
StateManager.Instance.goForward(new CharCre());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pattern10.State
{
class Program
{
static void Main()
{
Player forrest = new Player("Forrest Gump");
forrest.Show();
forrest.Run();
forrest.DrinkAlcohol(10);
forrest.Run();
forrest.EatSpinach(40);
forrest.Run();
forrest.EatSpinach(40);
forrest.EatSpinach(100);
forrest.Run();
}
}
}
|
namespace LinkedList
{
public class SinglyLinkedList<T> : ISinglyLinkedList<T>
{
private SinglyLinkedListNode<T> _head = null;
private SinglyLinkedListNode<T> _tail = null;
private int _size = 0;
private SinglyLinkedListNode<T> _nodes;
public void AddAfter(SinglyLinkedListNode<T> existingNode, SinglyLinkedListNode<T> newNode)
{
throw new System.NotImplementedException();
}
public void AddAfter(T existingValue, T newValue)
{
throw new System.NotImplementedException();
}
public void AddBefore(SinglyLinkedListNode<T> existingNode, SinglyLinkedListNode<T> newNode)
{
throw new System.NotImplementedException();
}
public void AddBefore(T existingValue, T newValue)
{
throw new System.NotImplementedException();
}
public void Add(T newValue)
{
SinglyLinkedListNode<T> newNode = new SinglyLinkedListNode<T>(newValue);
Add(newNode);
}
public void Add(SinglyLinkedListNode<T> newValueNode)
{
if (_nodes == null)
{
_nodes = newValueNode;
_head = newValueNode;
newValueNode.IsHead(true);
_tail = newValueNode;
newValueNode.IsTail(true);
_size++;
}
else
{
_nodes.AddTail(newValueNode);
_tail = newValueNode;
newValueNode.IsTail(true);
_size++;
}
}
public void AddLast(SinglyLinkedListNode<T> node)
{
throw new System.NotImplementedException();
}
public void AddLast(T value)
{
throw new System.NotImplementedException();
}
public void Clear()
{
throw new System.NotImplementedException();
}
public void Contains(T value)
{
throw new System.NotImplementedException();
}
public T GetHead()
{
throw new System.NotImplementedException();
}
public T GetTail()
{
return _tail.GetValue();
}
public void CopyTo(T[] array, int startPosition)
{
throw new System.NotImplementedException();
}
public SinglyLinkedList<T>? Find(T value)
{
throw new System.NotImplementedException();
}
public SinglyLinkedList<T>? FindLast(T value)
{
throw new System.NotImplementedException();
}
}
} |
/*
* Copyright (C) 2016-2017 Ansuria Solutions LLC & Tommy Baggett:
* http://github.com/tbaggett
* http://twitter.com/tbaggett
* http://tommyb.com
* http://ansuria.com
*
* The MIT License (MIT) see GitHub For more information
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.ComponentModel;
using System.IO;
using CoreGraphics;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using XFGloss.iOS.Extensions;
using XFGloss.iOS.Views;
[assembly: ExportCell(typeof(EntryCell), typeof(XFGloss.iOS.Renderers.XFGlossEntryCellRenderer))]
[assembly: ExportCell(typeof(SwitchCell), typeof(XFGloss.iOS.Renderers.XFGlossSwitchCellRenderer))]
[assembly: ExportCell(typeof(TextCell), typeof(XFGloss.iOS.Renderers.XFGlossTextCellRenderer))]
[assembly: ExportCell(typeof(ImageCell), typeof(XFGloss.iOS.Renderers.XFGlossImageCellRenderer))]
[assembly: ExportCell(typeof(ViewCell), typeof(XFGloss.iOS.Renderers.XFGlossViewCellRenderer))]
namespace XFGloss.iOS.Renderers
{
#region iOSXFGlossCellRenderer
/// <summary>
/// The iOS platform-specific XFGlossRenderer base class used for all <see cref="T:Xamarin.Forms.Cell"/> types.
/// </summary>
[Preserve(AllMembers = true)]
internal class iOSXFGlossCellRenderer : XFGlossCellRenderer<UITableViewCell>, IGradientRenderer
{
#region IGradientRenderer implementation
/// <summary>
/// Implementation of method required by the <see cref="T:XFGloss.IXFGlossRenderer"/> interface that the
/// <see cref="T:XFGloss.IGradientRenderer"/> interface extends. Applies the passed
/// <see cref="T:XFGloss.XFGlossElement"/> properties to the iOS UITableViewCell controls.
/// </summary>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
/// <param name="element">The <see cref="T:XFGloss.XFGlossElement"/> instance that changed</param>
/// <typeparam name="TElement">The type <see cref="T:XFGloss.XFGlossElement"/> that changed</typeparam>
public virtual void CreateNativeElement<TElement>(string propertyName, TElement element) where TElement : XFGlossElement
{
// No need to check property name yet. BackgroundGradient is the only property currently supported.
//if (propertyName == CellGloss.BackgroundGradientProperty.PropertyName && element is Gradient)
//{
if (element is Gradient)
{
CreateBackgroundGradientView(GetNativeCell(), element as Gradient);
}
//}
}
/// <summary>
/// Implementation of method required by the <see cref="T:XFGloss.IXFGlossRenderer"/> interface that the
/// <see cref="T:XFGloss.IGradientRenderer"/> interface extends. Indicates if there is an existing
/// implementation of the property specified by the propertyName parameter.
/// </summary>
/// <returns><c>true</c>, if an existing implementation is found, <c>false</c> otherwise.</returns>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
public virtual bool CanUpdate(string propertyName)
{
// No need to check property name yet. BackgroundGradient is the only property currently supported.
var nativeCell = GetNativeCell();
if (nativeCell != null)
{
return GetBackgroundGradientView(nativeCell) != null;
}
return false;
}
/// <summary>
/// Implementation of method required by the <see cref="T:XFGloss.IXFGlossRenderer"/> interface that the
/// <see cref="T:XFGloss.IGradientRenderer"/> interface extends. Removes any existing implementation of
/// the property specified by the propertyName parameter.
/// </summary>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
public virtual void RemoveNativeElement(string propertyName)
{
// No need to check property name yet. BackgroundGradient is the only property currently supported.
var nativeCell = GetNativeCell();
if (nativeCell != null)
{
RemoveBackgroundGradientView(nativeCell);
}
}
/// <summary>
/// Implementation of method required by the <see cref="T:XFGloss.IGradientRenderer"/> interface. Updates
/// the rotation angle being used by any existing implementation of the property specified by the propertyName
/// parameter.
/// </summary>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
/// <param name="rotation">The new rotation value, an integer number between 0 and 359</param>
public void UpdateRotation(string propertyName, int rotation)
{
// No need to check property name yet, BackgroundGradient is the only one being handled here.
var nativeCell = GetNativeCell();
if (nativeCell != null)
{
GetBackgroundGradientView(nativeCell)?.UpdateRotation(rotation);
}
}
/// <summary>
/// Implementation of method required by the <see cref="T:XFGloss.IGradientRenderer"/> interface. Updates
/// the gradient fill steps being used by any existing implementation of the property specified by the
/// propertyName parameter.
/// </summary>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
/// <param name="steps">The new collection of <see cref="T:XFGloss.GradientStep"/> instances that specify the
/// colors and positions of each step of the gradient fill</param>
public void UpdateSteps(string propertyName, GradientStepCollection steps)
{
// No need to check property name yet, BackgroundGradient is the only one being handled here.
var nativeCell = GetNativeCell();
if (nativeCell != null)
{
GetBackgroundGradientView(nativeCell)?.UpdateSteps(steps);
}
}
/// <summary>
/// Creates a new <see cref="T:XFGloss.iOS.Views.UIBackgroundGradientView"/> instance and assigns it as the
/// background view to the passed UITableViewCell instance.
/// </summary>
/// <returns>The new <see cref="T:XFGloss.iOS.Views.UIBackgroundGradientView"/> instance</returns>
/// <param name="nativeCell">The native UITableViewCell instance to attach the gradient view to</param>
/// <param name="gradient">The <see cref="T:XFGloss.Gradient"/> instance to copy properties from</param>
UIBackgroundGradientView CreateBackgroundGradientView(UITableViewCell nativeCell, Gradient gradient)
{
RemoveBackgroundGradientView(nativeCell);
if (nativeCell != null)
{
nativeCell.BackgroundView = new UIBackgroundGradientView(CGRect.Empty, gradient);
}
return nativeCell?.BackgroundView as UIBackgroundGradientView;
}
/// <summary>
/// Private helper method used to find and return a previously-created
/// <see cref="T:XFGloss.iOS.Views.UIBackgroundGradientView"/> instance if found, null if not found.
/// </summary>
/// <returns>The background gradient view if found, null if not.</returns>
/// <param name="nativeCell">The native UITableViewCell view used to display the cell contents</param>
UIBackgroundGradientView GetBackgroundGradientView(UITableViewCell nativeCell)
{
if (nativeCell != null && nativeCell.BackgroundView is UIBackgroundGradientView)
{
return nativeCell.BackgroundView as UIBackgroundGradientView;
}
return null;
}
/// <summary>
/// Private helper method used to remove any previously-created
/// <see cref="T:XFGloss.iOS.Views.UIBackgroundGradientView"/> instance if found.
/// </summary>
/// <param name="nativeCell">The native iOS UITableViewCell used to display the cell contents</param>
void RemoveBackgroundGradientView(UITableViewCell nativeCell)
{
if (nativeCell != null)
{
nativeCell.BackgroundView?.Dispose();
nativeCell.BackgroundView = null;
}
}
#endregion
#region UpdateProperties
/// <summary>
/// Static method called by custom Xamarin.Forms renderers, used to direct the call to the cross-platform base
/// class and provide the required <see cref="T:XFGloss.XFGlossCellRenderer"/> factory method.
/// </summary>
/// <param name="cell">The associated <see cref="T:Xamarin.Forms.Cell"/> instance</param>
/// <param name="nativeCell">The native UITableViewCell used to display the cell contents</param>
public static void UpdateProperties(Cell cell, UITableViewCell nativeCell)
{
UpdateProperties(cell, nativeCell, () => new iOSXFGlossCellRenderer());
}
/// <summary>
/// Implementation of the cross-platform base class's abstract UpdateProperties method. Used to apply the
/// XFGloss attached BindableProperty values for the property specified by the propertyName parameter.
/// </summary>
/// <param name="cell">The associated <see cref="T:Xamarin.Forms.Cell"/> instance</param>
/// <param name="nativeCell">The native UITableViewCell used to display the cell contents</param>
/// <param name="propertyName">The name of the XFGloss attached BindableProperty that changed</param>
protected override void UpdateProperties(Cell cell, UITableViewCell nativeCell, string propertyName)
{
// TintColor property - to be passed to CreateEditIndicatorAccessoryView and possibly others in the future
if (propertyName == null || propertyName == CellGloss.TintColorProperty.PropertyName)
{
var tintColor = (Color)cell.GetValue(CellGloss.TintColorProperty);
if (tintColor != Color.Default)
{
nativeCell.TintColor = tintColor.ToUIColor();
if (nativeCell.AccessoryView != null)
{
UIColor uiColor = tintColor.ToUIColor();
nativeCell.AccessoryView.TintColor = uiColor;
}
}
}
// BackgroundColor and BackgroundGradient properties
// We shouldn't apply BOTH a background gradient and solid color. The gradient takes preference.
Gradient bkgrndGradient = (Gradient)cell.GetValue(CellGloss.BackgroundGradientProperty);
if (bkgrndGradient != null && bkgrndGradient.UpdateProperties(CellGloss.BackgroundGradientProperty.PropertyName,
this, propertyName))
{
// We don't need to handle BackgroundColor if a BackgroundGradient is assigned/updated
return ;
}
if (propertyName == null || propertyName == CellGloss.BackgroundColorProperty.PropertyName)
{
Color bkgrndColor = (Color)cell.GetValue(CellGloss.BackgroundColorProperty);
if (bkgrndColor != Color.Default)
{
UIColor uiColor = bkgrndColor.ToUIColor();
// First check for a background color view being already assigned. Update it if found
if (nativeCell.BackgroundView is UIBackgroundColorView &&
nativeCell.BackgroundView.BackgroundColor != uiColor)
{
nativeCell.BackgroundView.BackgroundColor = uiColor;
}
else
{
// Dispose of any previously assigned background gradient view before replacing it with a background color view
if (nativeCell.BackgroundView is UIBackgroundGradientView)
{
nativeCell.BackgroundView.Dispose();
nativeCell.BackgroundView = null;
}
UIBackgroundColorView bkgrndView = new UIBackgroundColorView(CGRect.Empty);
bkgrndView.BackgroundColor = uiColor;
nativeCell.BackgroundView = bkgrndView;
}
}
else
{
// Dispose of any previously assigned background color view as a color is no longer assigned
if (nativeCell.BackgroundView is UIBackgroundColorView)
{
nativeCell.BackgroundView.Dispose();
nativeCell.BackgroundView = null;
}
}
}
}
/// <summary>
/// A marker class used to confirm if an instance is assigned to the UINativeCell.BackgroundView property
/// </summary>
class UIBackgroundColorView : UIView
{
public UIBackgroundColorView(CGRect rect) : base(rect) { }
}
#endregion
}
#endregion
#region iOSXFGlossAccessoryCellRenderer
/// <summary>
/// The iOS platform-specific XFGloss cell renderer class used for the <see cref="T:Xamarin.Forms.Cell"/> based
/// classes that support customizing the accessory view on the iOS platform.
/// </summary>
[Preserve(AllMembers = true)]
internal class iOSXFGlossAccessoryCellRenderer : iOSXFGlossCellRenderer
{
WeakReference<UIView> _accessoryView;
/// <summary>
/// Static method called by the custom <see cref="T:Xamarin.Forms.Cell"/> renderer, used to direct the
/// call to the cross-platform base class and provide the required
/// <see cref="T:XFGloss.XFGlossCellRenderer"/> factory method. Hides the
/// <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation of this method.
/// </summary>
/// <param name="cell">The associated <see cref="T:Xamarin.Forms.Cell"/> instance</param>
/// <param name="nativeCell">The native UITableViewCell used to display the cell contents</param>
new public static void UpdateProperties(Cell cell, UITableViewCell nativeCell)
{
UpdateProperties(cell, nativeCell, () => new iOSXFGlossAccessoryCellRenderer());
}
/// <summary>
/// Override of the <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation
/// of the ElementPropertyChanged method, checks the <see cref="T:XFGloss.CellGloss.AccessoryType"/> property
/// </summary>
/// <param name="sender">The object instance the notification was received from</param>
/// <param name="args">The PropertyChanged event arguments</param>
protected override void ElementPropertyChanged(object sender, PropertyChangedEventArgs args)
{
// Check all the properties that this implementation supports for changes
if (args.PropertyName == CellGloss.AccessoryTypeProperty.PropertyName)
{
UpdateProperties(args.PropertyName);
}
base.ElementPropertyChanged(sender, args);
}
/// <summary>
/// Override of the <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation
/// of the UpdateProperties method, applies any <see cref="T:XFGloss.CellGloss.AccessoryType"/> property changes
/// to the native UITableViewCell.
/// </summary>
/// <param name="cell">Cell.</param>
/// <param name="nativeCell">Native cell.</param>
/// <param name="propertyName">Property name.</param>
protected override void UpdateProperties(Cell cell, UITableViewCell nativeCell, string propertyName)
{
// AccessoryType property
if (propertyName == null ||
propertyName == CellGloss.AccessoryTypeProperty.PropertyName)
{
var accessoryType = (CellGlossAccessoryType)cell.GetValue(CellGloss.AccessoryTypeProperty);
UIView accView;
if (_accessoryView != null && _accessoryView.TryGetTarget(out accView))
{
if (accessoryType != CellGlossAccessoryType.EditIndicator)
{
accView.Dispose();
_accessoryView = null;
nativeCell.AccessoryView = null;
}
}
switch (accessoryType)
{
case CellGlossAccessoryType.None:
nativeCell.Accessory = UITableViewCellAccessory.None;
//nativeCell.AccessoryView = new UIView(new CGRect(0, 0, 20, 40));
//_accessoryView = new WeakReference<UIView>(nativeCell.AccessoryView);
break;
case CellGlossAccessoryType.Checkmark:
nativeCell.Accessory = UITableViewCellAccessory.Checkmark;
break;
// Disabled until we can access the detail button tapped method in the table view source
// for both the ListView (currently not possible) and TableView (currently possible) classes.
/*
case CellAccessoryType.DetailButton:
nativeCell.Accessory = UITableViewCellAccessory.DetailButton;
break;
case CellAccessoryType.DetailDisclosureButton:
nativeCell.Accessory = UITableViewCellAccessory.DetailDisclosureButton;
break;
*/
case CellGlossAccessoryType.DisclosureIndicator:
nativeCell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
break;
case CellGlossAccessoryType.EditIndicator:
var tintColor = (Color)cell.GetValue(CellGloss.TintColorProperty);
if (!(nativeCell.AccessoryView is EditIndicatorView))
{
nativeCell.Accessory = UITableViewCellAccessory.None;
accView = new EditIndicatorView(tintColor);
if (accView != null)
{
nativeCell.AccessoryView = accView;
_accessoryView = new WeakReference<UIView>(accView);
}
}
else
{
(nativeCell.AccessoryView as EditIndicatorView).ApplyTintColor(tintColor);
}
break;
}
}
base.UpdateProperties(cell, nativeCell, propertyName);
}
/// <summary>
/// Class used to render our custom "EditingIndicator" accessory view type
/// </summary>
class EditIndicatorView : UIView
{
WeakReference<UIColor> _defaultTintColor = null;
public EditIndicatorView(Color tintColor)
{
UserInteractionEnabled = false;
BackgroundColor = UIColor.Clear;
ApplyTintColor(tintColor);
Frame = new CGRect(0, 0, 6, 32);
}
public void ApplyTintColor(Color tintColor)
{
// Assign the user's custom tint color if one is specified.
if (tintColor != Color.Default)
{
// Store whatever tint color is assigned before we overwrite it so it can be restored if needed.
if (_defaultTintColor == null)
{
_defaultTintColor = new WeakReference<UIColor>(TintColor);
}
TintColor = tintColor.ToUIColor();
} // Handle users clearing their custom tint color by reassigning Color.Default
else if (_defaultTintColor != null)
{
UIColor defaultColor = null;
if (_defaultTintColor.TryGetTarget(out defaultColor))
{
TintColor = defaultColor;
}
}
}
public override void Draw(CGRect rect)
{
//get graphics context
using (CGContext g = UIGraphics.GetCurrentContext())
{
//set up drawing attributes
g.SetLineWidth(1);
if (TintColor != null)
{
TintColor.SetFill();
TintColor.SetStroke();
}
else
{
UIColor.Black.SetFill();
UIColor.Black.SetStroke();
}
//create geometry
var path = new CGPath();
path.AddLines(new CGPoint[]{
new CGPoint (1, 30),
new CGPoint (5, 30),
new CGPoint (5, 26)});
path.CloseSubpath();
//add geometry to graphics context and draw it
g.AddPath(path);
g.DrawPath(CGPathDrawingMode.FillStroke);
}
base.Draw(rect);
}
}
}
#endregion
#region iOSXFGlossSwitchCellRenderer
/// <summary>
/// The iOS platform-specific XFGloss cell renderer class used for the <see cref="T:Xamarin.Forms.SwitchCell"/>
/// class.
/// </summary>
[Preserve(AllMembers = true)]
internal class iOSXFGlossSwitchCellRenderer : iOSXFGlossCellRenderer
{
SwitchCellGloss _properties;
/// <summary>
/// Initializes a new instance of the <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossSwitchCellRenderer"/> class.
/// </summary>
/// <param name="bindable">Bindable.</param>
public iOSXFGlossSwitchCellRenderer(BindableObject bindable)
{
_properties = new SwitchCellGloss(bindable);
}
/// <summary>
/// Static method called by the custom <see cref="T:Xamarin.Forms.SwitchCell"/> renderer, used to direct the
/// call to the cross-platform base class and provide the required
/// <see cref="T:XFGloss.XFGlossCellRenderer"/> factory method. Hides the
/// <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation of this method.
/// </summary>
/// <param name="cell">The associated <see cref="T:Xamarin.Forms.Cell"/> instance</param>
/// <param name="nativeCell">The native iOS UITableViewCell used to display the cell contents</param>
new public static void UpdateProperties(Cell cell, UITableViewCell nativeCell)
{
UpdateProperties(cell, nativeCell, () => new iOSXFGlossSwitchCellRenderer(cell));
}
/// <summary>
/// Override of the <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation
/// of the ElementPropertyChanged method, checks the XFGloss properties that are unique to the
/// <see cref="T:Xamarin.Forms.SwitchCell"/> class.
/// </summary>
/// <param name="sender">The object instance the notification was received from</param>
/// <param name="args">The PropertyChanged event arguments</param>
protected override void ElementPropertyChanged(object sender, PropertyChangedEventArgs args)
{
// Check all the properties that this implementation supports for changes
if (args.PropertyName == SwitchCellGloss.OnTintColorProperty.PropertyName ||
args.PropertyName == SwitchCellGloss.ThumbTintColorProperty.PropertyName ||
args.PropertyName == SwitchCellGloss.ThumbOnTintColorProperty.PropertyName)
{
UpdateProperties(args.PropertyName);
}
// Special handling of state change to make XF Switch and Switch property names consistent
if (args.PropertyName == SwitchCell.OnProperty.PropertyName)
{
base.UpdateProperties(Switch.IsToggledProperty.PropertyName);
}
base.ElementPropertyChanged(sender, args);
}
/// <summary>
/// Override of the <see cref="T:XFGloss.iOS.Renderers.iOSXFGlossCellRenderer"/> base class's implementation
/// of the UpdateProperties method, applies XFGloss property changes that are unique to the
/// <see cref="T:Xamarin.Forms.SwitchCell"/> class.
/// </summary>
/// <param name="cell">Cell.</param>
/// <param name="nativeCell">Native cell.</param>
/// <param name="propertyName">Property name.</param>
protected override void UpdateProperties(Cell cell, UITableViewCell nativeCell, string propertyName)
{
if (nativeCell.AccessoryView is UISwitch)
{
var uiSwitch = nativeCell.AccessoryView as UISwitch;
uiSwitch.UpdateColorProperty(_properties, propertyName);
}
base.UpdateProperties(cell, nativeCell, propertyName);
}
}
#endregion
#region Xamarin.Forms renderers
/// <summary>
/// Custom <see cref="T:Xamarin.Forms.EntryCellRenderer"/>-based renderer class used to apply the custom XFGloss
/// properties to the iOS platform-specific implementation
/// </summary>
[Preserve(AllMembers = true)]
public class XFGlossEntryCellRenderer : EntryCellRenderer
{
/// <summary>
/// Override of the <see cref="EntryCellRenderer"/> GetCell method, used to apply any custom
/// settings to the iOS platform-specific cell display element.
/// </summary>
/// <returns>The iOS platform-specific cell display element after applying any custom settings to it</returns>
/// <param name="item">The <see cref="T:Xamarin.Forms.Cell"/> instance whose properties need to be transferred
/// from</param>
/// <param name="reusableCell">A previously-created iOS UITableViewCell if this cell has been rendered before
/// </param>
/// <param name="tv">The parent iOS UITableView</param>
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
iOSXFGlossAccessoryCellRenderer.UpdateProperties(item, nativeCell);
return nativeCell;
}
}
/// <summary>
/// Custom <see cref="T:Xamarin.Forms.SwitchCellRenderer"/>-based renderer class used to apply the custom XFGloss
/// properties to the iOS platform-specific implementation
/// </summary>
[Preserve(AllMembers = true)]
public class XFGlossSwitchCellRenderer : SwitchCellRenderer
{
/// <summary>
/// Override of the <see cref="SwitchCellRenderer"/> GetCell method, used to apply any custom
/// settings to the iOS platform-specific cell display element.
/// </summary>
/// <returns>The iOS platform-specific cell display element after applying any custom settings to it</returns>
/// <param name="item">The <see cref="T:Xamarin.Forms.Cell"/> instance whose properties need to be transferred
/// from</param>
/// <param name="reusableCell">A previously-created iOS UITableViewCell if this cell has been rendered before
/// </param>
/// <param name="tv">The parent iOS UITableView</param>
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
iOSXFGlossSwitchCellRenderer.UpdateProperties(item, nativeCell);
return nativeCell;
}
}
/// <summary>
/// Custom <see cref="T:Xamarin.Forms.TextCellRenderer"/>-based renderer class used to apply the custom XFGloss
/// properties to the iOS platform-specific implementation
/// </summary>
[Preserve(AllMembers = true)]
public class XFGlossTextCellRenderer : TextCellRenderer
{
/// <summary>
/// Override of the <see cref="TextCellRenderer"/> GetCell method, used to apply any custom
/// settings to the iOS platform-specific cell display element.
/// </summary>
/// <returns>The iOS platform-specific cell display element after applying any custom settings to it</returns>
/// <param name="item">The <see cref="T:Xamarin.Forms.Cell"/> instance whose properties need to be transferred
/// from</param>
/// <param name="reusableCell">A previously-created iOS UITableViewCell if this cell has been rendered before
/// </param>
/// <param name="tv">The parent iOS UITableView</param>
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
iOSXFGlossAccessoryCellRenderer.UpdateProperties(item, nativeCell);
return nativeCell;
}
}
/// <summary>
/// Custom <see cref="T:Xamarin.Forms.ImageCellRenderer"/>-based renderer class used to apply the custom XFGloss
/// properties to the iOS platform-specific implementation
/// </summary>
[Preserve(AllMembers = true)]
public class XFGlossImageCellRenderer : ImageCellRenderer
{
/// <summary>
/// Override of the <see cref="ImageCellRenderer"/> GetCell method, used to apply any custom
/// settings to the iOS platform-specific cell display element.
/// </summary>
/// <returns>The iOS platform-specific cell display element after applying any custom settings to it</returns>
/// <param name="item">The <see cref="T:Xamarin.Forms.Cell"/> instance whose properties need to be transferred
/// from</param>
/// <param name="reusableCell">A previously-created iOS UITableViewCell if this cell has been rendered before
/// </param>
/// <param name="tv">The parent iOS UITableView</param>
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
iOSXFGlossAccessoryCellRenderer.UpdateProperties(item, nativeCell);
return nativeCell;
}
}
/// <summary>
/// Custom <see cref="T:Xamarin.Forms.ViewCellRenderer"/>-based renderer class used to apply the custom XFGloss
/// properties to the iOS platform-specific implementation
/// </summary>
[Preserve(AllMembers = true)]
public class XFGlossViewCellRenderer : ViewCellRenderer
{
/// <summary>
/// Override of the <see cref="ViewCellRenderer"/> GetCell method, used to apply any custom
/// settings to the iOS platform-specific cell display element.
/// </summary>
/// <returns>The iOS platform-specific cell display element after applying any custom settings to it</returns>
/// <param name="item">The <see cref="T:Xamarin.Forms.Cell"/> instance whose properties need to be transferred
/// from</param>
/// <param name="reusableCell">A previously-created iOS UITableViewCell if this cell has been rendered before
/// </param>
/// <param name="tv">The parent iOS UITableView</param>
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
var nativeCell = base.GetCell(item, reusableCell, tv);
iOSXFGlossAccessoryCellRenderer.UpdateProperties(item, nativeCell);
return nativeCell;
}
}
#endregion
} |
using System;
using System.IO.Abstractions;
using RegionOrebroLan.Localization.Reflection;
using RegionOrebroLan.Localization.Resourcing;
namespace RegionOrebroLan.Localization.Json.Resourcing
{
public class ResourceValidator : BasicResourceValidator
{
#region Fields
private const string _validExtension = ".json";
#endregion
#region Constructors
public ResourceValidator(IFileSystem fileSystem) : base(fileSystem) { }
#endregion
#region Properties
protected internal virtual string ValidExtension => _validExtension;
#endregion
#region Methods
protected internal override bool IsValidEmbeddedResourceInternal(IAssembly assembly, string name)
{
return this.IsValidExtension(this.FileSystem.Path.GetExtension(name));
}
protected internal virtual bool IsValidExtension(string extension)
{
return string.Equals(extension, this.ValidExtension, StringComparison.OrdinalIgnoreCase);
}
protected internal override bool IsValidFileResourceInternal(IFileInfo file)
{
return this.IsValidExtension(file?.Extension);
}
#endregion
}
} |
using NUnit.Framework;
using UnityEngine;
namespace VRM
{
public class EnumUtilTest
{
[Test]
public void EnumUtilTestSimplePasses()
{
Assert.AreEqual(default(HumanBodyBones), EnumUtil.TryParseOrDefault<HumanBodyBones>("xxx"));
#if UNITY_5_6_OR_NEWER
Assert.AreEqual(HumanBodyBones.UpperChest, EnumUtil.TryParseOrDefault<HumanBodyBones>("upperchest"));
#else
Assert.AreEqual(default(HumanBodyBones), EnumUtil.TryParseOrDefault<HumanBodyBones>("upperchest"));
#endif
}
}
}
|
using Kaia.Common.DataAccess;
using System.Collections.Generic;
using System.Linq;
namespace Kaia.MultiSelect.Domain
{
/// <summary>
/// Represents the changes to one ore more suppliers
/// </summary>
public static class SupplierExtensions
{
public static SupplierModifier GetModifier(this Supplier supplier)
{
return new SupplierModifier(new List<long> { supplier.SupplierId })
{
SupplierName = new UpdatableField<string>(supplier.SupplierName),
Status = new UpdatableField<long>(supplier.Status),
City = new UpdatableField<string>(supplier.City)
};
}
public static SupplierModifier GetModifier(this IEnumerable<Supplier> suppliers)
{
Indeterminate<string> supplierName = null;
Indeterminate<long> status = null;
Indeterminate<string> city = null;
var ids = new List<long>();
foreach (var supplier in suppliers)
{
ids.Add(supplier.SupplierId);
if (supplierName == null)
{
supplierName =
new Indeterminate<string>(supplier.SupplierName);
}
else
{
supplierName.Value = supplier.SupplierName;
}
if (status == null)
{
status = new Indeterminate<long>(supplier.Status);
}
else
{
status.Value = supplier.Status;
}
if (city == null)
{
city = new Indeterminate<string>(supplier.City);
}
else
{
city.Value = supplier.City;
}
}
var result = new SupplierModifier(ids)
{
SupplierName = new UpdatableField<string>(supplierName,
ids.Count == 1), // Can only update if modifying a single entity
Status = new UpdatableField<long>(status),
City = new UpdatableField<string>(city)
};
return result;
}
}
}
|
namespace MusicXml
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.7.2046.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "midi-instrument")]
public partial class midiinstrument : object, System.ComponentModel.INotifyPropertyChanged
{
private string midichannelField;
private string midinameField;
private string midibankField;
private string midiprogramField;
private string midiunpitchedField;
private decimal volumeField;
private bool volumeFieldSpecified;
private decimal panField;
private bool panFieldSpecified;
private decimal elevationField;
private bool elevationFieldSpecified;
private string idField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("midi-channel", DataType = "positiveInteger")]
public string midichannel
{
get
{
return this.midichannelField;
}
set
{
this.midichannelField = value;
this.RaisePropertyChanged("midichannel");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("midi-name")]
public string midiname
{
get
{
return this.midinameField;
}
set
{
this.midinameField = value;
this.RaisePropertyChanged("midiname");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("midi-bank", DataType = "positiveInteger")]
public string midibank
{
get
{
return this.midibankField;
}
set
{
this.midibankField = value;
this.RaisePropertyChanged("midibank");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("midi-program", DataType = "positiveInteger")]
public string midiprogram
{
get
{
return this.midiprogramField;
}
set
{
this.midiprogramField = value;
this.RaisePropertyChanged("midiprogram");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("midi-unpitched", DataType = "positiveInteger")]
public string midiunpitched
{
get
{
return this.midiunpitchedField;
}
set
{
this.midiunpitchedField = value;
this.RaisePropertyChanged("midiunpitched");
}
}
/// <remarks/>
public decimal volume
{
get
{
return this.volumeField;
}
set
{
this.volumeField = value;
this.RaisePropertyChanged("volume");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool volumeSpecified
{
get
{
return this.volumeFieldSpecified;
}
set
{
this.volumeFieldSpecified = value;
this.RaisePropertyChanged("volumeSpecified");
}
}
/// <remarks/>
public decimal pan
{
get
{
return this.panField;
}
set
{
this.panField = value;
this.RaisePropertyChanged("pan");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool panSpecified
{
get
{
return this.panFieldSpecified;
}
set
{
this.panFieldSpecified = value;
this.RaisePropertyChanged("panSpecified");
}
}
/// <remarks/>
public decimal elevation
{
get
{
return this.elevationField;
}
set
{
this.elevationField = value;
this.RaisePropertyChanged("elevation");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool elevationSpecified
{
get
{
return this.elevationFieldSpecified;
}
set
{
this.elevationFieldSpecified = value;
this.RaisePropertyChanged("elevationSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(DataType = "IDREF")]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("id");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null))
{
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ExampleSignalTest.cs" company="Supyrb">
// Copyright (c) Supyrb. All rights reserved.
// </copyright>
// <author>
// Johannes Deml
// send@johannesdeml.com
// </author>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Supyrb
{
public class BasicExampleSignalTest : MonoBehaviour
{
private Signal exampleSignal;
private void Awake()
{
exampleSignal = Signals.Get<BasicExampleSignal>();
SubscribeListeners();
}
private void Start()
{
DispatchSignal();
}
private void SubscribeListeners()
{
exampleSignal.AddListener(FirstListener, -100);
exampleSignal.AddListener(PauseTwoSecondsListener, -10);
exampleSignal.AddListener(DefaultListener);
exampleSignal.AddListener(ConsumeEventListener, 10);
exampleSignal.AddListener(LastListener, 100);
}
private void OnDestroy()
{
exampleSignal.RemoveListener(FirstListener);
exampleSignal.RemoveListener(PauseTwoSecondsListener);
exampleSignal.RemoveListener(DefaultListener);
exampleSignal.RemoveListener(ConsumeEventListener);
exampleSignal.RemoveListener(LastListener);
}
[ContextMenu("DispatchSignal")]
public void DispatchSignal()
{
exampleSignal.Dispatch();
}
private void FirstListener()
{
Debug.Log("First Listener (Order -100)");
}
private void PauseTwoSecondsListener()
{
Debug.Log("Pausing for 2 seconds (Order -10)");
exampleSignal.Pause();
StartCoroutine(ContinueAfterDelay(exampleSignal, 2f));
}
private void DefaultListener()
{
Debug.Log("Default order Listener (Order 0)");
}
private void ConsumeEventListener()
{
Debug.Log("Consume Signal (Order 10)");
exampleSignal.Consume();
}
private void LastListener()
{
Debug.Log("Won't be called, since the signal was consumed. (Order 100)");
}
private IEnumerator ContinueAfterDelay(Signal signal, float delay)
{
yield return new WaitForSeconds(delay);
signal.Continue();
}
}
} |
namespace WebMoney.Services.Contracts.BusinessObjects
{
public interface IPaymentConfirmation
{
string TargetPurse { get; }
long InvoiceId { get; }
string ConfirmationCode { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrugLibAPI.RESTModels.RxNorm
{
public class GetNdcProperties
{
#region Inner Class Models
public class Rootobject
{
public Ndcpropertylist ndcPropertyList { get; set; }
}
public class Ndcpropertylist
{
public Ndcproperty[] ndcProperty { get; set; }
}
public class Ndcproperty
{
public string ndcItem { get; set; }
public string ndc9 { get; set; }
public string ndc10 { get; set; }
public string rxcui { get; set; }
public string splSetIdItem { get; set; }
public Packaginglist packagingList { get; set; }
public Propertyconceptlist propertyConceptList { get; set; }
}
public class Packaginglist
{
public string[] packaging { get; set; }
}
public class Propertyconceptlist
{
public Propertyconcept[] propertyConcept { get; set; }
}
public class Propertyconcept
{
public string propName { get; set; }
public string propValue { get; set; }
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LZ78
{
class Encoded
{
int index;
char character;
public Encoded(int index, char character)
{
this.Index = index;
this.Character = character;
}
public int Index { get => index; set => index = value; }
public char Character { get => character; set => character = value; }
}
}
|
using UnityEngine;
[System.Serializable]
class BeamParamters
{
public float countPerMeter = 1f;
public float speed = 1f;
public float curvatureRadius = 1f;
public float damping = 0.1f;
public float impact = 1f;
}
class Beam
{
public Beam()
{
time = -float.MaxValue;
}
public void Emit(
Vector3 position,
Vector3 velocity,
float speed,
float curvatureRadius,
float damping)
{
this.position = position;
this.velocity = velocity;
// 速さv、半径rで円を描く時、その向心力はv^2/r。これを計算しておく。
this.maxCentripetalAccel = speed * speed / curvatureRadius;
this.damping = damping;
// 終端速度がspeedになるaccelを求める
// v = a / kだからa=v*k
this.propulsion = speed * damping;
time = 0f;
}
public void Update(float deltaTime, Vector3 target)
{
var toTarget = target - position;
var vn = velocity.normalized;
var dot = Vector3.Dot(toTarget, vn);
var centripetalAccel = toTarget - (vn * dot);
var centripetalAccelMagnitude = centripetalAccel.magnitude;
if (centripetalAccelMagnitude > 1f)
{
centripetalAccel /= centripetalAccelMagnitude;
}
var force = centripetalAccel * maxCentripetalAccel;
force += vn * propulsion;
force -= velocity * damping;
velocity += force * deltaTime;
position += velocity * deltaTime;
time += deltaTime;
}
public Vector3 position;
public Vector3 velocity;
public float time;
float maxCentripetalAccel;
float damping;
float propulsion; // 推進力
}
|
using System.Collections.Generic;
namespace MvcContrib.FluentHtml.Behaviors
{
/// <summary>
/// Contract for any class implementing a list of custom behaviors.
/// </summary>
public interface IBehaviorsContainer
{
/// <summary>
/// The collection of <see cref="IBehaviorMarker"/> objects.
/// </summary>
IEnumerable<IBehaviorMarker> Behaviors { get; }
}
} |
using System.Diagnostics.CodeAnalysis;
namespace TaskIt.NexusUploader.Types
{
/// <summary>
/// possible exit codes / errors
/// </summary>
[SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "<Pending>")]
public enum EExitCode
{
/// <summary>
/// ok
/// </summary>
SUCCESS = 0,
/// <summary>
/// Param Parsing error
/// </summary>
PARAM_PARSING_ERROR = 1,
/// <summary>
/// illegal parameters
/// </summary>
INVALID_PARAMS = 2,
/// <summary>
/// illegal folder
/// </summary>
INVALID_FOLDER = 3,
/// <summary>
/// Error during upload
/// </summary>
UPLOAD_ERROR = 4
}
}
|
using System;
using MonoTouch.Foundation;
using MonoTouch.Security;
namespace BeeblexSDK
{
public partial class BBXBeeblex : NSObject
{
//TODO: Verify if this is Possible
// public SecKey PublicKey
// {
// get
// {
// IntPtr ptr = this.PublicKey_;
// return new SecKey(ptr);
// }
// }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MicroBluer.TimeTask
{
public class TimeSetting
{
public int Hour { get; }
public int Minute { get; }
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using PSDocs.Definitions.Selectors;
namespace PSDocs.Definitions
{
public abstract class Spec
{
private const string FullNameSeparator = "/";
public static string GetFullName(string apiVersion, string name)
{
return string.Concat(apiVersion, FullNameSeparator, name);
}
}
internal static class Specs
{
internal const string V1 = "github.com/microsoft/PSDocs/v1";
internal const string Selector = "Selector";
public readonly static ISpecDescriptor[] BuiltinTypes = new ISpecDescriptor[]
{
new SpecDescriptor<SelectorV1, SelectorV1Spec>(V1, Selector),
};
}
}
|
using UnityEngine;
namespace DevLocker.StatesManagement.SampleTanks.Garage
{
// Expose for uGUI Unity events.
public class TanksGarageStateExpose : MonoBehaviour {
public void SetState(TanksGarageStates state) {
TanksGarageLevelManager.Instance.States.SetState(state);
}
public void SetStateLobby() {
SetState(TanksGarageStates.Lobby);
}
public void SetStateShop() {
SetState(TanksGarageStates.Shop);
}
public void SetStateInventory() {
SetState(TanksGarageStates.Inventory);
}
public void SetStateStats() {
SetState(TanksGarageStates.Stats);
}
public void SetStateChat() {
SetState(TanksGarageStates.Chat);
}
public void PushStateOptions() {
TanksGarageLevelManager.Instance.States.PushState(TanksGarageStates.Options);
}
}
} |
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="~/">ASP.NET Web API</a>
</p>
</div>
</div>
</header>
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome to ASP.NET Web API!</h1><br />
<h2>Please enter number and click the button:</h2>
</hgroup>
<p>
<input type="text" id="txt" /><br />
<input type="button" id="btnGet" value="Click to get the value" />
</p>
</div>
</section>
</div>
|
// 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.Data.Common;
using System.Transactions;
namespace System.Data.ProviderBase
{
internal abstract partial class DbConnectionClosed : DbConnectionInternal
{
protected override void Activate(Transaction transaction) => throw ADP.ClosedConnectionError();
public override void EnlistTransaction(Transaction transaction) => throw ADP.ClosedConnectionError();
}
}
|
using HarmonyLib;
using VoxelTycoon.Tracks;
namespace Sandbox
{
[HarmonyPatch(typeof(VehicleUnitSharedData), nameof(VehicleUnitSharedData.BasePrice), MethodType.Getter)]
internal class VehicleBasePricePatch
{
internal static bool Prefix(ref double __result)
{
return SandboxSettings.FreeIf(SandboxSettings.FreeVehicle, ref __result);
}
}
}
|
//------------------------------------------------------------------------------
// Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
// NOTICE: You are permitted to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------
using Robotlegs.Bender.Framework.Impl;
using NUnit.Framework;
using Robotlegs.Bender.Framework.API;
using System.Collections.Generic;
using System;
namespace Robotlegs.Bender.Extensions.ViewProcessor.Utils
{
[TestFixture]
public class FastPropertyInjectorTest
{
/*============================================================================*/
/* Private Properties */
/*============================================================================*/
private FastPropertyInjector instance;
private IInjector injector;
private int INT_VALUE = 3;
private string STRING_VALUE = "someValue";
/*============================================================================*/
/* Test Setup and Teardown */
/*============================================================================*/
[SetUp]
public void Setup()
{
Dictionary<string,Type> config = new Dictionary<string, Type> ();
config.Add ("intValue", typeof(int));
config.Add ("stringValue", typeof(string));
instance = new FastPropertyInjector(config);
injector = new RobotlegsInjector();
}
[TearDown]
public void tearDown()
{
instance = null;
injector = null;
}
/*============================================================================*/
/* Tests */
/*============================================================================*/
[Test]
public void Can_Be_Instantiated()
{
Assert.That(instance, Is.InstanceOf(typeof(FastPropertyInjector)), "instance is FastPropertyInjector");
}
[Test]
public void Process_Properties_Are_Injected()
{
injector.Map(typeof(int)).ToValue(INT_VALUE);
injector.Map(typeof(string)).ToValue(STRING_VALUE);
ViewToBeInjected view = new ViewToBeInjected();
instance.Process(view, typeof(ViewToBeInjected), injector);
Assert.That (view.intValue, Is.EqualTo (INT_VALUE));
Assert.That (view.stringValue, Is.EqualTo (STRING_VALUE));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using SQLite;
namespace Hookshot.Client
{
using Orm;
class Db
{
static readonly string TAG = "Db";
static readonly string Path = System.IO.Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"hookshot.db3");
static Db()
{
// Ensure all required tables exist on first reference.
Execute(db =>
{
CreateTable<Orm.Server>(db);
CreateTable<Orm.BrowsedFilepath>(db);
});
}
static void CreateTable<T>(SQLiteConnection db, CreateFlags createFlags = CreateFlags.None)
{
try
{
db.CreateTable<T>(createFlags);
Log.Info(TAG, $"Created db table {typeof(T).Name}.");
}
catch (Exception e)
{
Log.Error(TAG, $"Failed to create table {typeof(T).Name} with error {e}.");
}
}
static T Execute<T>(Func<SQLiteConnection, T> method)
{
try
{
using (var db = new SQLiteConnection(Path))
{
return method(db);
}
}
catch (Exception e)
{
Log.Error(TAG, $"Db operation failed with error {e}.");
throw;
}
}
static void Execute(Action<SQLiteConnection> method)
{
Execute<int>(db => {
method(db);
return 0;
});
}
public int InsertServer(Server server)
{
return Execute(db =>
{
return server.Id = db.Insert(server);
});
}
public void UpdateServer(Server server)
{
Execute(db =>
{
db.Update(server);
});
}
public Server[] GetServers()
{
return Execute(db =>
{
return db.Table<Server>().ToArray();
});
}
public void DeleteServer(Server server)
{
Execute(db =>
{
db.Delete(server);
});
}
public void UpdateBrowsedFilepath(int serverId, string filepath)
{
Execute(db =>
{
var table = db.Table<BrowsedFilepath>();
var f = table.FirstOrDefault(r => r.ServerId == serverId);
if (f == null)
{
// Then we need to create the element and add it.
db.Insert(new BrowsedFilepath
{
ServerId = serverId,
Filepath = filepath,
});
}
else
{
f.Filepath = filepath;
db.Update(f);
}
});
}
public BrowsedFilepath GetBrowsedFilepath(int serverId)
{
return Execute(db =>
{
return db.Table<BrowsedFilepath>().FirstOrDefault(f => f.ServerId == serverId);
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using NBass.Declarations;
namespace NBass
{
//TODO implement plugin info
public class Plugin : IPlugin, IDisposable
{
bool _isDisposed = false;
internal IntPtr Handle { get; private set; }
public string Name { get; private set; }
public string Path { get; private set; }
public Plugin(string path)
{
Path = path;
Handle = IntPtr.Zero;
}
internal void Init()
{
int flags = 0;
Handle = _Load(Path, flags);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
_isDisposed = true;
}
if (Handle == IntPtr.Zero)
throw new InvalidOperationException("Plugin don`t initialized");
_Unload(Handle);
}
~Plugin()
{
Dispose(false);
}
#endregion
[DllImport("bass.dll", CharSet = CharSet.Auto, EntryPoint = "BASS_PluginLoad")]
private static extern IntPtr _Load([MarshalAs(UnmanagedType.LPWStr)] [In] string path, int flags);
[DllImport("bass.dll", CharSet = CharSet.Auto, EntryPoint = "BASS_PluginFree")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool _Unload(IntPtr handle);
}
}
|
using System;
using System.Runtime.InteropServices;
namespace x360ce.Engine.Win32
{
/// <summary>
/// The structure represents a security identifier (SID) and its
/// attributes. SIDs are used to uniquely identify users or groups.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SID_AND_ATTRIBUTES
{
public readonly IntPtr Sid;
public Int32 Attributes;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SomaSim.AI
{
[TestClass]
public class ActionsTest
{
public class TestAction : Action
{
public string name;
public bool stopOnStart = false;
public int countActivate;
public int countDeactivate;
public int countUpdate;
public TestAction (string name, bool stopOnStart = false) {
this.name = name;
this.stopOnStart = stopOnStart;
}
public override void OnActivated () {
base.OnActivated();
this.countActivate++;
}
public override void OnDeactivated (bool pushedback) {
this.countDeactivate++;
base.OnDeactivated(pushedback);
}
internal override void OnStarted () {
base.OnStarted();
if (stopOnStart) {
Stop(true);
}
}
internal override void OnUpdate () {
base.OnUpdate();
this.countUpdate++;
}
public override string ToString () {
return "TestAction " + name;
}
}
public class TestScript : Script
{
public int countActivate;
public int countDeactivate;
public TestScript (string name, params Action[] actions) : base(name, actions.ToList()) { }
public override void OnActivated () {
base.OnActivated();
this.countActivate++;
}
public override void OnDeactivated (bool pushedback) {
this.countDeactivate++;
base.OnDeactivated(pushedback);
}
}
[TestMethod]
public void TestActionsInScript () {
// make some actions
var a = new TestAction("a");
var b = new TestAction("b");
var c = new TestAction("c");
var d = new TestAction("d");
var e = new TestAction("e");
var f = new TestAction("f");
var seq = new TestScript("test");
seq.Enqueue(new List<Action>() { a, b, c });
// make sure they're all enqueued but only A is activated
Assert.IsTrue(!seq.IsEmpty && seq.Head == a);
Assert.IsTrue(a.IsEnqueued && a.IsActive);
Assert.IsTrue(b.IsEnqueued && !b.IsActive);
Assert.IsTrue(c.IsEnqueued && !c.IsActive);
// stop A, this should dequeue it and activate B
a.Stop(true);
Assert.IsTrue(!seq.IsEmpty && seq.Head == b);
Assert.IsTrue(!a.IsEnqueued && !a.IsActive);
Assert.IsTrue( b.IsEnqueued && b.IsActive);
Assert.IsTrue( c.IsEnqueued && !c.IsActive);
// stop the script, this should pop B and C without activating the latter
seq.Clear();
Assert.IsTrue(seq.IsEmpty && seq.Head == null);
Assert.IsTrue(!a.IsEnqueued && !a.IsActive && a.countActivate == 1 && a.countDeactivate == 1);
Assert.IsTrue(!b.IsEnqueued && !b.IsActive && b.countActivate == 1 && b.countDeactivate == 1);
Assert.IsTrue(!c.IsEnqueued && !c.IsActive && c.countActivate == 0 && c.countDeactivate == 0);
// push two more
seq.Enqueue(new List<Action>() { d, e });
Assert.IsTrue(d.IsEnqueued && d.IsActive && d.countActivate == 1 && d.countDeactivate == 0);
Assert.IsTrue(e.IsEnqueued && !e.IsActive && e.countActivate == 0 && e.countDeactivate == 0);
// pop E from the end, this should not affect D, or activate/deactivate E
seq.PopTail();
Assert.IsTrue( d.IsEnqueued && d.IsActive && d.countActivate == 1 && d.countDeactivate == 0);
Assert.IsTrue(!e.IsEnqueued && !e.IsActive && e.countActivate == 0 && e.countDeactivate == 0);
// push F to the front, this should deactivate D but keep it in the queue
seq.PushHead(f);
Assert.IsTrue(f.IsEnqueued && f.IsActive && f.countActivate == 1 && f.countDeactivate == 0);
Assert.IsTrue(d.IsEnqueued && !d.IsActive && d.countActivate == 1 && d.countDeactivate == 1);
// now dequeue F from the front, this should pop it, and re-activate D
seq.StopCurrentAction(true, null);
Assert.IsTrue(!f.IsEnqueued && !f.IsActive && f.countActivate == 1 && f.countDeactivate == 1);
Assert.IsTrue( d.IsEnqueued && d.IsActive && d.countActivate == 2 && d.countDeactivate == 1);
}
[TestMethod]
public void TestActionStartupAndUpdate () {
// make some actions
var a = new TestAction("a");
var b = new TestAction("b");
var c = new TestAction("c", true); // this one stops before first update
var seq = new TestScript("test", a, b, c);
Assert.IsTrue(a.IsEnqueued && a.IsActive && !a.IsStarted);
Assert.IsTrue(a.countUpdate == 0);
// fake an update cycle
seq.OnUpdate();
Assert.IsTrue(a.IsEnqueued && a.IsActive && a.IsStarted);
Assert.IsTrue(a.countUpdate == 1);
// stop. this will remove and deactivate A, and activate B,
// but not start it yet until an update
a.Stop(true);
Assert.IsTrue(!a.IsEnqueued && !a.IsActive && !a.IsStarted);
Assert.IsTrue( b.IsEnqueued && b.IsActive && !b.IsStarted);
Assert.IsTrue(a.countUpdate == 1);
Assert.IsTrue(b.countUpdate == 0);
seq.OnUpdate();
Assert.IsTrue(b.IsEnqueued && b.IsActive && b.IsStarted);
Assert.IsTrue(b.countUpdate == 1);
// stop b. this will activate c, which will stop itself before first update
b.Stop(true);
Assert.IsTrue(c.IsEnqueued && c.IsActive && !c.IsStarted);
Assert.IsTrue(c.countUpdate == 0);
seq.OnUpdate();
Assert.IsTrue(!c.IsEnqueued && !c.IsActive && !c.IsStarted);
Assert.IsTrue(c.countUpdate == 0); // this update never got a chance to run
}
[TestMethod]
public void TestScriptsInQueue () {
// make some scripts
var a = new TestAction("a");
var b = new TestAction("b");
var c = new TestAction("c");
var abc = new TestScript("abc", a, b, c);
var empty = new TestScript("empty");
var d = new TestAction("d");
var e = new TestAction("e");
var f = new TestAction("f");
var def = new TestScript("def", d, e, f );
var q = new ScriptQueue();
q.Enqueue(new List<Script>() { abc, empty, def });
// verify the first script and action are active
Assert.IsTrue(!q.IsEmpty && q.Head == abc && q.Head.Head == a);
Assert.IsTrue( abc.IsEnqueued && abc.IsActive);
Assert.IsTrue(empty.IsEnqueued && !empty.IsActive);
Assert.IsTrue( def.IsEnqueued && !def.IsActive);
// stop the first action, keeps the same script active
a.Stop(true);
Assert.IsTrue(!q.IsEmpty && q.Head == abc && q.Head.Head == b);
// finish off actions. this will remove ABC from the queue
b.Stop(true);
c.Stop(true);
Assert.IsTrue(!q.IsEmpty && q.Head != abc);
Assert.IsTrue(abc.countActivate == 1 && abc.countDeactivate == 1);
// the Empty script was activated but then immediately removed, because it's empty
Assert.IsTrue(!empty.IsEnqueued && !empty.IsActive);
Assert.IsTrue(empty.countActivate == 1 && empty.countDeactivate == 1);
// and let's make sure that DEF is the active one now
Assert.IsTrue(!q.IsEmpty && q.Head == def && q.Head.Head == d);
Assert.IsTrue( !abc.IsEnqueued && !abc.IsActive);
Assert.IsTrue(!empty.IsEnqueued && !empty.IsActive);
Assert.IsTrue( def.IsEnqueued && def.IsActive);
Assert.IsTrue(def.countActivate == 1 && def.countDeactivate == 0);
// then if we force-stop DEF, it should clean out of the queue completely
def.StopScript(true, null);
Assert.IsTrue(q.IsEmpty && q.Head == null);
Assert.IsTrue(!def.IsEnqueued && !def.IsActive);
Assert.IsTrue(def.countActivate == 1 && def.countDeactivate == 1);
}
[TestMethod]
public void TestStopOnFailure () {
// make some scripts
var a = new TestAction("a");
var b = new TestAction("b");
var c = new TestAction("c");
var abc = new TestScript("abc", a, b, c);
var d = new TestAction("d");
var e = new TestAction("e");
var f = new TestAction("f");
var def = new TestScript("def", d, e, f);
var q = new ScriptQueue();
q.Enqueue(new List<Script>() { abc, def });
q.OnUpdate();
Assert.IsTrue(a.IsEnqueued && a.IsActive && a.IsStarted);
// if we stop just action a with the failure flag set, it should stop the entire script
// and advance to the next one
abc.StopCurrentAction(false, null);
Assert.IsTrue(!a.IsEnqueued && !a.IsActive);
Assert.IsTrue(!abc.IsEnqueued && !abc.IsActive);
Assert.IsTrue(def.IsActive && d.IsActive);
// similary stopping the script will just remove it
def.StopScript(false, null);
Assert.IsTrue(!def.IsActive && !d.IsActive);
}
[TestMethod]
public void TestQueueUpdate () {
// make some scripts
var a = new TestAction("a");
var b = new TestAction("b");
var c = new TestAction("c");
var abc = new TestScript("abc", a, b, c);
var d = new TestAction("d");
var e = new TestAction("e");
var f = new TestAction("f");
var def = new TestScript("def", d, e, f);
var q = new ScriptQueue();
q.Enqueue(new List<Script>() { abc, def });
Assert.IsTrue(a.IsEnqueued && a.IsActive && !a.IsStarted);
// fake a queue update
q.OnUpdate();
Assert.IsTrue(a.IsEnqueued && a.IsActive && a.IsStarted);
// stop the script. the first action in the next script
// will be activated, but won't be started until another update
q.StopCurrentScript(true, null);
Assert.IsTrue(!abc.IsEnqueued && !abc.IsActive && !a.IsActive && !a.IsStarted);
Assert.IsTrue(def.IsEnqueued && def.IsActive && d.IsActive && !d.IsStarted);
q.OnUpdate();
Assert.IsTrue(def.IsEnqueued && def.IsActive && d.IsActive && d.IsStarted);
// clear everything. no more updates
q.StopAllScripts(true, null);
Assert.IsTrue(!def.IsEnqueued && !def.IsActive && !d.IsActive && !d.IsStarted);
Assert.IsTrue(q.IsEmpty);
}
}
}
|
using System.Collections.Generic;
namespace PEG.Builder
{
public class ConsumeExpressionCache
{
private static Dictionary<string, ConsumeExpression> cache = new Dictionary<string, ConsumeExpression>();
private static object lockObject = new object();
public static ConsumeExpression Get(string expression)
{
ConsumeExpression result;
bool found;
lock (lockObject)
{
found = cache.TryGetValue(expression, out result);
}
if (!found)
{
result = ConsumeExpressionParsing.Parse(expression);
lock (lockObject)
{
cache[expression] = result;
}
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using TweetinviCore.Enum;
using TweetinviCore.Interfaces.DTO;
using TweetinviCore.Interfaces.Parameters;
namespace TweetinviCore.Interfaces
{
public interface ITweetList
{
ITweetListDTO TweetListDTO { get; set; }
long Id { get; }
string IdStr { get; }
string Slug { get; }
string Name { get; }
string FullName { get; }
IUser Creator { get; }
DateTime CreatedAt { get; }
string Uri { get; }
string Description { get; }
bool Following { get; }
PrivacyMode PrivacyMode { get; }
int MemberCount { get; }
int SubscriberCount { get; }
bool Update(IListUpdateParameters parameters);
bool Destroy();
IEnumerable<ITweet> GetTweets();
IEnumerable<IUser> GetMembers(int maxNumberOfUsersToRetrieve = 100);
}
} |
namespace LcaDataModel
{
using Repository.Pattern.Ef6;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("FragmentNodeProcess")]
public partial class FragmentNodeProcess : Entity
{
public FragmentNodeProcess() {
ProcessSubstitutions = new HashSet<ProcessSubstitution>();
}
//[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int FragmentNodeProcessID { get; set; }
public int FragmentFlowID { get; set; }
public int ProcessID { get; set; }
public int FlowID { get; set; }
public int? ConservationFragmentFlowID { get; set; } // not a foreign key, just an annotation
public virtual Flow Flow { get; set; }
public virtual FragmentFlow FragmentFlow { get; set; }
public virtual Process Process { get; set; }
public virtual ICollection<ProcessSubstitution> ProcessSubstitutions { get; set; }
}
}
|
/*
Write a simple program that lets the user manage a list of elements.
It can be a grocery list, "to do" list, etc.
Refer to Looping Based on a Logical Expression if necessary to see how to implement
an infinite loop.
Each time through the loop, ask the user to perform an operation,
and then show the current contents of their list.
The operations available should be Add, Remove, and Clear.
The syntax should be as follows:
+ some item
- some item
--
Your program should read in the user's input and determine
if it begins with a "+" or "-", or if it is simply "--".
In the first two cases, your program should add or remove the string
given ("some item" in the example).
If the user enters just "--" then the program should clear the current list.
Your program can start each iteration through its loop with the following
instruction: Console.WriteLine("Enter command (+ item, - item, or -- to clear)):");
*/
using System;
using System.Collections.Generic;
namespace list_ex_1
{
class Program
{
public static List<string> addItem(List<string> toDoList, string item) {
toDoList.Add(item);
return toDoList;
}
public static List<string> removeItem(List<string> toDoList, string item) {
toDoList.Remove(item);
return toDoList;
}
public static List<string> clearAll(List<string> toDoList) {
toDoList.Clear();
return toDoList;
}
public static void manageList() {
List<string> toDoList = new List<string>();
while(true) {
Console.WriteLine("Enter command: + item, - item or -- to clear all");
var userInput = Console.ReadLine();
var split = userInput.Split();
var item = split[1];
switch (split[0]) {
case "+":
toDoList = addItem(toDoList, item);
break;
case "-":
toDoList = removeItem(toDoList, item);
break;
case "--":
toDoList = clearAll(toDoList);
break;
default:
Console.WriteLine("Invalid input provided, terminating program!!");
break;
}
Console.WriteLine("Current items in list: ");
toDoList.ForEach(Console.WriteLine);
}
}
static void Main(string[] args)
{
manageList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace state
{
internal class CloseState : State
{
Filee f;
public CloseState(Filee f)
{
this.f = f;
}
public void close()
{
Console.WriteLine("File is already closed");
}
public void delete()
{
Console.WriteLine("File Deleted");
f.changeState(new DeleteSate(f));
}
public void open()
{
Console.WriteLine("Open File");
f.changeState(new OpenState(f));
}
public string getState()
{
return ("Close State");
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
class Solution
{
// Complete the pangrams function below.
static string pangrams(string s)
{
string result = string.Empty;
Queue<char> queue = new Queue<char>();
for (char x = 'a'; x <= 'z'; x++)
{
queue.Enqueue(x);
}
bool isFailed = false;
while (queue.Any())
{
if (s.Contains(queue.Peek()))
{
queue.Dequeue();
}
else
{
isFailed = true;
break;
}
}
if (isFailed)
{
result = "not pangram";
}
else
{
result = "pangram";
}
return result;
}
static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string s = Console.ReadLine();
string result = pangrams(s);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DtoGenerator.TestSolution.DAL.Dto.Infrastructure;
using DtoGenerator.TestSolution.Model.Entity;
namespace DtoGenerator.TestSolution.DAL.Dto
{
public class ComputerDTO
{
////BCC/ BEGIN CUSTOM CODE SECTION
private int _customField;
public void SomeMethod()
{
}
public ComputerDTO()
{
}
public int Xy { get; set; }
public void Something()
{
}
public string Xy2 { get; set; }
public void EndMethod()
{
}
////ECC/ END CUSTOM CODE SECTION
public string Name { get; set; }
public int Cpus { get; set; }
}
public class ComputerMapper : MapperBase<Computer, ComputerDTO>
{
////BCC/ BEGIN CUSTOM CODE SECTION
public Expression<Func<City, ComputerDTO>> SelectorExpressionFromCity
{
get
{
return ((Expression<Func<City, ComputerDTO>>)(p => new ComputerDTO()
{
Name = "None"
}));
}
}
public void Test()
{
}
////ECC/ END CUSTOM CODE SECTION
public override Expression<Func<Computer, ComputerDTO>> SelectorExpression
{
get
{
return ((Expression<Func<Computer, ComputerDTO>>)(p => new ComputerDTO()
{
////BCC/ BEGIN CUSTOM CODE SECTION
Xy = 77,
// this is my extra custom comment
Xy2 = null,
// another comment
////ECC/ END CUSTOM CODE SECTION
Name = p.Name,
}));
}
}
public override void MapToModel(ComputerDTO dto, Computer model)
{
////BCC/ BEGIN CUSTOM CODE SECTION
var x = 0;
x++;
model.Cpus = x;
////ECC/ END CUSTOM CODE SECTION
model.Name = dto.Name;
model.Cpus = dto.Cpus;
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace Fork.View.Xaml2.Controls
{
public class StretchyWrapPanel : Panel
{
public static readonly DependencyProperty ItemWidthProperty = DependencyProperty.Register(nameof(ItemWidth),
typeof(double), typeof(StretchyWrapPanel),
new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure));
[TypeConverter(typeof(LengthConverter))]
public double ItemWidth
{
get { return (double) GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
public static readonly DependencyProperty ItemHeightProperty = DependencyProperty.Register(nameof(ItemHeight),
typeof(double), typeof(StretchyWrapPanel),
new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure));
[TypeConverter(typeof(LengthConverter))]
public double ItemHeight
{
get { return (double) GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
public static readonly DependencyProperty OrientationProperty = StackPanel.OrientationProperty.AddOwner(
typeof(StretchyWrapPanel),
new FrameworkPropertyMetadata(Orientation.Horizontal, FrameworkPropertyMetadataOptions.AffectsMeasure,
OnOrientationChanged));
public Orientation Orientation
{
get { return _orientation; }
set { SetValue(OrientationProperty, value); }
}
private static void OnOrientationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((StretchyWrapPanel) d)._orientation = (Orientation) e.NewValue;
}
private Orientation _orientation = Orientation.Horizontal;
public static readonly DependencyProperty StretchProportionallyProperty = DependencyProperty.Register(
nameof(StretchProportionally), typeof(bool),
typeof(StretchyWrapPanel), new PropertyMetadata(true, OnStretchProportionallyChanged));
public bool StretchProportionally
{
get { return _stretchProportionally; }
set { SetValue(StretchProportionallyProperty, value); }
}
private static void OnStretchProportionallyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((StretchyWrapPanel) o)._stretchProportionally = (bool) e.NewValue;
}
private bool _stretchProportionally = true;
private struct UVSize
{
internal UVSize(Orientation orientation, double width, double height)
{
U = V = 0d;
_orientation = orientation;
Width = width;
Height = height;
}
internal UVSize(Orientation orientation)
{
U = V = 0d;
_orientation = orientation;
}
internal double U;
internal double V;
private readonly Orientation _orientation;
internal double Width
{
get { return _orientation == Orientation.Horizontal ? U : V; }
set
{
if (_orientation == Orientation.Horizontal)
{
U = value;
}
else
{
V = value;
}
}
}
internal double Height
{
get { return _orientation == Orientation.Horizontal ? V : U; }
set
{
if (_orientation == Orientation.Horizontal)
{
V = value;
}
else
{
U = value;
}
}
}
}
protected override Size MeasureOverride(Size constraint)
{
var curLineSize = new UVSize(Orientation);
var panelSize = new UVSize(Orientation);
var uvConstraint = new UVSize(Orientation, constraint.Width, constraint.Height);
var itemWidth = ItemWidth;
var itemHeight = ItemHeight;
var itemWidthSet = !double.IsNaN(itemWidth);
var itemHeightSet = !double.IsNaN(itemHeight);
var childConstraint = new Size(
itemWidthSet ? itemWidth : constraint.Width,
itemHeightSet ? itemHeight : constraint.Height);
var children = InternalChildren;
for (int i = 0, count = children.Count; i < count; i++)
{
var child = children[i];
if (child == null) continue;
// Flow passes its own constrint to children
child.Measure(childConstraint);
// This is the size of the child in UV space
var sz = new UVSize(Orientation,
itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (curLineSize.U + sz.U > uvConstraint.U)
{
// Need to switch to another line
panelSize.U = Math.Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V;
curLineSize = sz;
if (sz.U > uvConstraint.U)
{
// The element is wider then the constrint - give it a separate line
panelSize.U = Math.Max(sz.U, panelSize.U);
panelSize.V += sz.V;
curLineSize = new UVSize(Orientation);
}
}
else
{
// Continue to accumulate a line
curLineSize.U += sz.U;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
}
}
// The last line size, if any should be added
panelSize.U = Math.Max(curLineSize.U, panelSize.U);
panelSize.V += curLineSize.V;
// Go from UV space to W/H space
return new Size(panelSize.Width, panelSize.Height);
}
protected override Size ArrangeOverride(Size finalSize)
{
var firstInLine = 0;
var itemWidth = ItemWidth;
var itemHeight = ItemHeight;
double accumulatedV = 0;
var itemU = Orientation == Orientation.Horizontal ? itemWidth : itemHeight;
var curLineSize = new UVSize(Orientation);
var uvFinalSize = new UVSize(Orientation, finalSize.Width, finalSize.Height);
var itemWidthSet = !double.IsNaN(itemWidth);
var itemHeightSet = !double.IsNaN(itemHeight);
var useItemU = Orientation == Orientation.Horizontal ? itemWidthSet : itemHeightSet;
var children = InternalChildren;
for (int i = 0, count = children.Count; i < count; i++)
{
var child = children[i];
if (child == null) continue;
var sz = new UVSize(Orientation, itemWidthSet ? itemWidth : child.DesiredSize.Width,
itemHeightSet ? itemHeight : child.DesiredSize.Height);
if (curLineSize.U + sz.U > uvFinalSize.U)
{
// Need to switch to another line
if (!useItemU && StretchProportionally)
{
ArrangeLineProportionally(accumulatedV, curLineSize.V, firstInLine, i, uvFinalSize.Width);
}
else
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, i, true,
useItemU ? itemU : uvFinalSize.Width / Math.Max(1, i - firstInLine - 1));
}
accumulatedV += curLineSize.V;
curLineSize = sz;
if (sz.U > uvFinalSize.U)
{
// The element is wider then the constraint - give it a separate line
// Switch to next line which only contain one element
if (!useItemU && StretchProportionally)
{
ArrangeLineProportionally(accumulatedV, sz.V, i, ++i, uvFinalSize.Width);
}
else
{
ArrangeLine(accumulatedV, sz.V, i, ++i, true, useItemU ? itemU : uvFinalSize.Width);
}
accumulatedV += sz.V;
curLineSize = new UVSize(Orientation);
}
firstInLine = i;
}
else
{
// Continue to accumulate a line
curLineSize.U += sz.U;
curLineSize.V = Math.Max(sz.V, curLineSize.V);
}
}
// Arrange the last line, if any
if (firstInLine < children.Count)
{
if (!useItemU && StretchProportionally)
{
ArrangeLineProportionally(accumulatedV, curLineSize.V, firstInLine, children.Count,
uvFinalSize.Width);
}
else
{
ArrangeLine(accumulatedV, curLineSize.V, firstInLine, children.Count, true,
useItemU ? itemU : uvFinalSize.Width / Math.Max(1, children.Count - firstInLine - 1));
}
}
return finalSize;
}
private void ArrangeLineProportionally(double v, double lineV, int start, int end, double limitU)
{
var u = 0d;
var horizontal = Orientation == Orientation.Horizontal;
var children = InternalChildren;
var total = 0d;
for (var i = start; i < end; i++)
{
total += horizontal ? children[i].DesiredSize.Width : children[i].DesiredSize.Height;
}
var uMultipler = limitU / total;
for (var i = start; i < end; i++)
{
var child = children[i];
if (child != null)
{
var childSize = new UVSize(Orientation, child.DesiredSize.Width, child.DesiredSize.Height);
var layoutSlotU = childSize.U * uMultipler;
child.Arrange(new Rect(horizontal ? u : v, horizontal ? v : u,
horizontal ? layoutSlotU : lineV, horizontal ? lineV : layoutSlotU));
u += layoutSlotU;
}
}
}
private void ArrangeLine(double v, double lineV, int start, int end, bool useItemU, double itemU)
{
var u = 0d;
var horizontal = Orientation == Orientation.Horizontal;
var children = InternalChildren;
for (var i = start; i < end; i++)
{
var child = children[i];
if (child != null)
{
var childSize = new UVSize(Orientation, child.DesiredSize.Width, child.DesiredSize.Height);
var layoutSlotU = useItemU ? itemU : childSize.U;
child.Arrange(new Rect(horizontal ? u : v, horizontal ? v : u,
horizontal ? layoutSlotU : lineV, horizontal ? lineV : layoutSlotU));
u += layoutSlotU;
}
}
}
}
} |
using System;
using UnityEngine;
namespace JCMG.Curves
{
/// <summary>
/// A serializable version of a nullable-Quaternion.
/// </summary>
[Serializable]
public struct NullableQuaternion
{
/// <summary>
/// Returns the <see cref="Quaternion"/> value.
/// </summary>
public Quaternion Value
{
get { return rotation; }
}
/// <summary>
/// Returns the <see cref="Quaternion"/> value if present, otherwise null.
/// </summary>
public Quaternion? NullableValue
{
get { return hasValue ? (Quaternion?)rotation : null; }
}
/// <summary>
/// Returns true if a <see cref="Quaternion"/> value is present, otherwise false.
/// </summary>
public bool HasValue
{
get { return hasValue; }
}
[SerializeField]
private Quaternion rotation;
[SerializeField]
private bool hasValue;
public NullableQuaternion(Quaternion? rot)
{
rotation = rot.HasValue ? rot.Value : Quaternion.identity;
hasValue = rot.HasValue;
}
/// <summary>
/// User-defined conversion from nullable type to NullableQuaternion
/// </summary>
/// <param name="r"></param>
public static implicit operator NullableQuaternion(Quaternion? r)
{
return new NullableQuaternion(r);
}
}
}
|
using ExtendedXmlSerializer.Core.Sources;
namespace ExtendedXmlSerializer.ExtensionModel.References
{
interface IReferenceMap : ITableSource<ReferenceIdentity, object> {}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Assignment4.Models;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
namespace Assignment4.Controllers
{
public class HomeController : Controller
{
[Route("")]
public IActionResult Index()
{
string url = "http://localhost:63224/api/Product/FindLastThree";
WebRequest request = WebRequest.Create(url);
request.Method = "get";
string res = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
res = ex.ToString();
}
var products = JsonConvert.DeserializeObject<List<Product>>(res);
ViewBag.Products = products;
if (HttpContext.Session.GetString("username") == null)
{
HttpContext.Session.SetString("username", "");
}
ViewBag.Username = HttpContext.Session.GetString("username");
return View();
}
}
}
|
using System;
namespace Griddly.Mvc
{
public class GriddlyHtmlButton : GriddlyButton
{
public Func<object, object> HtmlTemplate { get; set; }
}
} |
namespace CDR.DataHolder.API.Infrastructure.Models
{
public class Health
{
public string Status { get; set; }
}
}
|
using System;
namespace IdGen
{
/// <summary>
/// Holds information about a decoded id.
/// </summary>
public struct ID
{
/// <summary>
/// Gets the sequence number of the id.
/// </summary>
public int SequenceNumber { get; private set; }
/// <summary>
/// Gets the generator id of the generator that generated the id.
/// </summary>
public int GeneratorId { get; private set; }
/// <summary>
/// Gets the date/time when the id was generated.
/// </summary>
public DateTimeOffset DateTimeOffset { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ID"/> struct.
/// </summary>
/// <param name="sequenceNumber">The sequence number of the id.</param>
/// <param name="generatorId">The generator id of the generator that generated the id.</param>
/// <param name="dateTimeOffset">The date/time when the id was generated.</param>
/// <returns></returns>
internal static ID Create(int sequenceNumber, int generatorId, DateTimeOffset dateTimeOffset)
{
return new ID
{
SequenceNumber = sequenceNumber,
GeneratorId = generatorId,
DateTimeOffset = dateTimeOffset
};
}
}
}
|
using System.Collections.Generic;
using System.IO;
using Cottle.Documents.Compiled;
namespace Cottle.Documents.Evaluated.StatementExecutors
{
internal class CompositeStatementExecutor : IStatementExecutor
{
private readonly IReadOnlyList<IStatementExecutor> _nodes;
public CompositeStatementExecutor(IReadOnlyList<IStatementExecutor> nodes)
{
_nodes = nodes;
}
public Value? Execute(Frame frame, TextWriter output)
{
foreach (var node in _nodes)
{
var result = node.Execute(frame, output);
if (result.HasValue)
return result.Value;
}
return null;
}
}
} |
using AutoMapper;
using ZKWeb.MVVMPlugins.MVVM.Common.MultiTenant.src.Application.Dtos;
using ZKWeb.MVVMPlugins.MVVM.Common.MultiTenant.src.Domain.Entities;
using ZKWebStandard.Ioc;
namespace ZKWeb.MVVMPlugins.MVVM.Common.MultiTenant.src.Application.Mappings
{
/// <summary>
/// AutoMapper的配置
/// </summary>
[ExportMany]
public class MultiTenantMapperProfile : Profile
{
public MultiTenantMapperProfile()
{
// 租户
CreateMap<TenantInputDto, Tenant>();
CreateMap<Tenant, TenantOutputDto>();
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.SelfHost;
using Xunit;
using Xunit.Extensions;
namespace System.Web.Http.ModelBinding
{
/// <summary>
/// Tests actions that directly use HttpRequestMessage parameters
/// </summary>
public class HttpContentBindingTests : IDisposable
{
public HttpContentBindingTests()
{
this.SetupHost();
}
public void Dispose()
{
this.CleanupHost();
}
[Theory]
[InlineData("application/xml")]
[InlineData("text/xml")]
[InlineData("application/json")]
[InlineData("text/json")]
public void Action_Directly_Reads_HttpRequestMessage(string mediaType)
{
Order order = new Order() { OrderId = "99", OrderValue = 100.0 };
var formatter = new MediaTypeFormatterCollection().FindWriter(typeof(Order), new MediaTypeHeaderValue(mediaType));
HttpRequestMessage request = new HttpRequestMessage()
{
Content = new ObjectContent<Order>(order, formatter, mediaType),
RequestUri = new Uri(baseAddress + "/HttpContentBinding/HandleMessage"),
Method = HttpMethod.Post
};
HttpResponseMessage response = httpClient.SendAsync(request).Result;
Order receivedOrder = response.Content.ReadAsAsync<Order>().Result;
Assert.Equal(order.OrderId, receivedOrder.OrderId);
Assert.Equal(order.OrderValue, receivedOrder.OrderValue);
}
private HttpSelfHostServer server = null;
private string baseAddress = null;
private HttpClient httpClient = null;
private void SetupHost()
{
httpClient = new HttpClient();
baseAddress = String.Format("http://{0}", Environment.MachineName);
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute("Default", "{controller}/{action}", new { controller = "HttpContentBinding", action = "HandleMessage" });
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
}
private void CleanupHost()
{
if (server != null)
{
server.CloseAsync().Wait();
}
}
}
public class Order
{
public string OrderId { get; set; }
public double OrderValue { get; set; }
}
public class HttpContentBindingController : ApiController
{
[HttpPost]
public HttpResponseMessage HandleMessage()
{
Order order = Request.Content.ReadAsAsync<Order>().Result;
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<Order>(order, new JsonMediaTypeFormatter())
};
}
}
} |
using Newtonsoft.Json;
using System;
namespace Kentico.Kontent.Management.Models.Subscription;
/// <summary>
/// Represents project's environemnt.
/// </summary>
public sealed class SubscriptionProjectEnvironmentModel
{
/// <summary>
/// Gets or sets the environment's internal ID.
/// Use this as the projectId path parameter in project-specific endpoints.
/// </summary>
[JsonProperty("id")]
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the environment's name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
|
using System.Collections.Generic;
using Android.Content;
using Android.Support.V4.View;
using Android.Util;
using Android.Views;
using Android.Widget;
using Java.Lang;
using XCarousel.Droid.Interfaces;
using XCarousel.Droid.Models;
namespace XCarousel.Droid.Adapters
{
public class XCarouselViewAdapter : PagerAdapter
{
private List<PickerItem> items;
public List<PickerItem> Items
{
get
{
return items;
}
set
{
items = value;
NotifyDataSetChanged();
}
}
public Context Context { get; set; }
public int Drawable { get; set; }
public int TextColor { get; set; } = 0;
public override int Count => Items.Count;
public XCarouselViewAdapter(Context context, List<PickerItem> items, int drawable)
{
Context = context;
Drawable = drawable;
if (items != null)
Items = items;
else
Items = new List<PickerItem>();
if (Drawable == 0)
Drawable = Resource.Layout.Page;
}
public override Object InstantiateItem(ViewGroup container, int position)
{
var view = LayoutInflater.From(container.Context).Inflate(Drawable, null);
var imageView = view.FindViewById<ImageView>(Resource.Id.imageView);
var textView = view.FindViewById<TextView>(Resource.Id.textView);
var pickerItem = Items[position];
imageView.Visibility = ViewStates.Visible;
if(pickerItem.HasDrawable)
{
imageView.Visibility = ViewStates.Visible;
textView.Visibility = ViewStates.Gone;
imageView.SetImageResource(pickerItem.Drawable);
}
else
{
if(pickerItem.Text != null)
{
imageView.Visibility = ViewStates.Gone;
textView.Visibility = ViewStates.Visible;
textView.Text = pickerItem.Text;
var textSize = (pickerItem as TextItem).TextSize;
if (textSize != 0)
textView.TextSize = DpToPx((pickerItem as TextItem).TextSize);
}
}
view.Tag = position;
container.AddView(view);
return view;
}
public override void DestroyItem(ViewGroup container, int position, Object @object)
{
container.RemoveView(@object as View);
}
public override bool IsViewFromObject(View view, Object @object)
{
return view == @object;
}
private int DpToPx(int dp)
{
var displayMetrics = Context.Resources.DisplayMetrics;
return Math.Round(dp * (displayMetrics.Xdpi / (float) DisplayMetricsDensity.Default));
}
}
}
|
using UnityEngine;
public class PassEndCubeScript : MonoBehaviour
{
public GameFlowManagerScript gameManager;
// ensure player not win by fly to end cube
public PlayerMoveScript playerMove;
// music
public AudioSource backgroundAudioSource;
AudioSource winAudioSource;
void Start()
{
winAudioSource = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider other)
{
if (other.name == "Player" && playerMove.isActiveAndEnabled)
{
// stop background music
backgroundAudioSource.Stop();
// play win music
winAudioSource.Play();
gameManager.CompleteLevel();
}
}
}
|
using LASI.Core;
using System;
using System.Linq;
using System.Collections.Generic;
using Xunit;
using NFluent;
namespace LASI.Core.Tests
{
/// <summary>
///This is a test class for IDirectObjectTakerTest and is intended
///to contain all IDirectObjectTakerTest Unit Tests
/// </summary>
public class IDirectObjectTakerTest
{
/// <summary>
///A test for BindDirectObject
/// </summary>
[Fact]
public void BindDirectObjectTest()
{
var target = new BaseVerb("slay");
IEntity directObject = new PersonalPronoun("them");
target.BindDirectObject(directObject);
Check.That(target.DirectObjects).Contains(directObject);
}
/// <summary>
///A test for AggregateDirectObject
/// </summary>
[Fact]
public void AggregateDirectObjectTest()
{
var target = new BaseVerb("slay");
IAggregateEntity aggregateObject = new AggregateEntity(
new NounPhrase(new ProperSingularNoun("John"), new ProperSingularNoun("Smith")),
new NounPhrase(new PossessivePronoun("his"), new CommonPluralNoun("cats"))
);
target.BindDirectObject(aggregateObject);
var actual = target.AggregateDirectObject;
Check.That(actual).ContainsExactly(aggregateObject).And.Not.IsNull().And.Not.IsEmpty();
}
/// <summary>
///A test for DirectObjects
/// </summary>
[Fact]
public void DirectObjectsTest()
{
var target = new BaseVerb("slay");
IEnumerable<IEntity> actual = target.DirectObjects;
Check.That(target.DirectObjects).IsEqualTo(actual);
}
}
}
|
using System.Threading.Tasks;
namespace Oxagile.Demos.Api.Services
{
public interface IBlobStorage
{
Task<string> SaveAsync(byte[] stream);
Task<byte[]> LoadAsync(string blobPath);
bool Exists(string blobPath);
}
} |
using System;
using System.Collections.Generic;
namespace Insql.Resolvers
{
public class InsqlDescriptor
{
public Type Type { get; }
public Dictionary<string, IInsqlSection> Sections { get; }
public Dictionary<Type, IInsqlMapSection> Maps { get; }
public InsqlDescriptor(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
this.Type = type;
this.Sections = new Dictionary<string, IInsqlSection>();
this.Maps = new Dictionary<Type, IInsqlMapSection>();
}
public InsqlDescriptor(string typeName)
{
var type = Type.GetType(typeName);
if (type == null)
{
throw new Exception($"insql type : {typeName} not found !");
}
this.Type = type;
this.Sections = new Dictionary<string, IInsqlSection>();
this.Maps = new Dictionary<Type, IInsqlMapSection>();
}
}
}
|
using MyProject01.Test;
using MyProject01.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyProject01
{
abstract class BasicTestParameterSet
{
protected NetworkTestParameter[] _parmArr;
protected LogWriter _logger;
public NetworkTestParameter[] GetParameterSet(string testCaseName)
{
int num = 1;
foreach (NetworkTestParameter parm in _parmArr)
{
parm.name = testCaseName + num++.ToString("D2");
}
return _parmArr;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PowerCode.CodeGeneration.Core
{
// ----------------------- -------------------------- ------------------- -----------------
public sealed class ClassDeclarationBuilder : DeclarationBuilderBase
{
const string CTR_INDICATOR = ".";
public ClassDeclarationBuilder(string template) : base(template)
{
}
public override string Build()
{
var result = new StringBuilder();
var classTemplate = GetClassTemplate(_template);
var props = BuildProperties();
classTemplate = classTemplate.Replace("$Properties$", props);
var methods = BuildMethods();
classTemplate = classTemplate.Replace("$Methods$", methods);
result.Append(classTemplate);
return result.ToString();
}
private string GetClassTemplate(string template)
{
var classTemplate = @"
public class $ClassName$ $BaseClass$ $Interfaces$
{
public $ClassName$($ClassArgs$)
{
}
$Properties$
$Methods$
}
";
var parts = template.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
//parts.Dump();
var name = parts[0];
var baseClass = string.Empty;
if (name.Contains(":"))
{
var nameParts = name.Split(new string[] { ":" }, StringSplitOptions.None);
name = nameParts[0];
baseClass = nameParts[1];
if (baseClass.Trim() == ",")
{ baseClass = string.Empty; }
if (string.IsNullOrEmpty(baseClass) == false)
{
baseClass = ":" + baseClass;
}
}
var interfaces = parts.Skip(1).Where(f => f.Trim().StartsWith(CTR_INDICATOR) == false);
var classArgs = parts.Skip(1).Where(f => f.Trim().StartsWith(CTR_INDICATOR) == true);
classTemplate = classTemplate.Replace("$ClassName$", name.Trim());
classTemplate = classTemplate.Replace("$BaseClass$", baseClass.Trim());
var interfaceString = string.Join(",", interfaces).Trim();
if (string.IsNullOrEmpty(interfaceString) == false)
{
interfaceString = ", " + interfaceString;
}
classTemplate = classTemplate.Replace("$Interfaces$", interfaceString);
var ctorArgs = GetConstructorArgs(classArgs);
classTemplate = classTemplate.Replace("$ClassArgs$", ctorArgs);
return classTemplate;
}
private string GetConstructorArgs(IEnumerable<string> args)
{
var result = new List<string>();
foreach (var arg in args)
{
var argParts = (arg.Contains(":") ?
arg.Split(new string[] { ":" }, StringSplitOptions.None) :
new string[] { arg, "string" });
result.Add($"{argParts[1]} {argParts[0].Replace(CTR_INDICATOR, "")}");
}
return (result.Count > 0 ? string.Join(", ", result) : string.Empty);
}
private string BuildProperties()
{
var propBuilders = _builders.Where(f => f.GetType().Equals(typeof(PropertyDeclarationBuilder)));
var result = new StringBuilder();
foreach (var item in propBuilders)
{
result.Append(item.Build());
}
return result.ToString();
}
private string BuildMethods()
{
var methodBuilders = _builders.Where(f => f.GetType().Equals(typeof(MethodDeclarationBuilder)));
var result = new StringBuilder();
foreach (var item in methodBuilders)
{
result.Append(item.Build());
}
return result.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApplication1.Controllers
{
using Repositories;
using WebApplication1.新文件夹2;
[Route("api/[controller]")]
public class ClassController : Controller
{
private ClassRepository repository = new ClassRepository();
// GET: api/<controller>
[HttpGet]
public IEnumerable<Class> Get()
{
return this.repository.GetAll();
}
// GET api/<controller>/5
[HttpGet("{id}")]
public Class Get(string id)
{
return this.repository.Get(id);
}
// POST api/<controller>
[HttpPost]
public void Post(Class value)
{
this.repository.Add(value);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public void Put(Class value)
{
repository.Update(value);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public void Delete(string id)
{
repository.Delete(id);
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace NLightning.Utils.Extensions
{
public static class DbSetExtensions
{
public static void InsertOrUpdate<T>(this DbSet<T> dbSet, T entity, DbContext db) where T : class
{
if (db.Entry(entity).State == EntityState.Detached)
{
dbSet.Add(entity);
}
}
}
} |
//
// BinaryExpression.cs
//
// Author:
// Aaron Bockover <abock@xamarin.com>
//
// Copyright 2015 Xamarin Inc. All rights reserved.
namespace Xamarin.Pmcs.CSharp.Ast
{
public class BinaryExpression : Expression
{
public static readonly Role LeftOperandRole = new Role (nameof (LeftOperandRole));
public static readonly Role RightOperandRole = new Role (nameof (RightOperandRole));
public TokenType Operator { get; set; }
public Expression LeftOperand {
get { return GetChild<Expression> (LeftOperandRole); }
set { SetChild (value, RightOperandRole); }
}
public Expression RightOperand {
get { return GetChild<Expression> (RightOperandRole); }
set { SetChild (value, LeftOperandRole); }
}
public BinaryExpression ()
{
}
public BinaryExpression (Expression leftOperand, TokenType op, Expression rightOperand)
{
if (leftOperand != null)
AddChild (leftOperand, LeftOperandRole);
if (rightOperand != null)
AddChild (rightOperand, RightOperandRole);
Operator = op;
}
public override void AcceptVisitor (IAstVisitor visitor)
{
visitor.VisitBinaryExpression (this);
}
}
} |
namespace Common.Hosting.Configuration
{
/// <summary>
/// Kafka configuration.
/// </summary>
public class KafkaConfiguration
{
public const string Key = "Kafka";
public string ClientId { get; set; }
public string Host { get; set; }
}
} |
using System;
using System.Text;
class HelloGender
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine("Вашият пол е мъжки(M) или женски(F):");
string gender = Console.ReadLine();
bool isFemale = (gender == "F" || gender == "f");
bool isMale = (gender == "M" || gender == "m");
if (isFemale)
{
Console.WriteLine("Добър ден г-жа..");
}
else if(isMale)
{
Console.WriteLine("Добър ден г-н...");
}
else
{
Console.WriteLine("Моля, Въведете един от символите(M/F)");
}
}
}
|
using ClArc.Async.Core;
namespace ClArc.Tests.Async
{
public class InputData : IInputData
{
}
} |
using System;
using System.Threading;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DotLiquid.Util
{
/// <summary>
/// Utility to avoid repetitive reflection calls that are found to be slow.
/// </summary>
internal class ReflectionCacheValue
{
private const TypeAttributes AnonymousTypeAttributes = TypeAttributes.NotPublic;
private readonly Type _type;
private readonly Lazy<bool> _isAnonymous;
public ReflectionCacheValue(Type type)
{
_type = type;
_isAnonymous = new Lazy<bool>(() => IsAnonymousInternal(), LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool IsAnonymous => _isAnonymous.Value;
private bool IsAnonymousInternal()
{
#if NETSTANDARD1_3
var typeInfo = _type.GetTypeInfo();
#endif
return (_type.Name.StartsWith("<>") || _type.Name.StartsWith("VB$"))
&& (_type.Name.Contains("AnonymousType") || _type.Name.Contains("AnonType"))
#if NETSTANDARD1_3
&& typeInfo.GetCustomAttribute<CompilerGeneratedAttribute>() != null
&& typeInfo.IsGenericType
&& (typeInfo.Attributes & AnonymousTypeAttributes) == AnonymousTypeAttributes;
#else
&& _type.GetCustomAttribute<CompilerGeneratedAttribute>() != null
&& _type.IsGenericType
&& (_type.Attributes & AnonymousTypeAttributes) == AnonymousTypeAttributes;
#endif
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;
using System.Drawing;
#pragma warning disable 1591
namespace OSGeo.MapGuide.Viewer
{
[ToolboxItem(true)]
public class MgViewerOptionsComponent : MgViewerComponent
{
public MgViewerOptionsComponent()
{
this.Label = this.ToolTipText = Strings.TextViewerOptions;
this.Icon = Properties.Resources.options;
this.PreferencesDirectory = string.Empty;
}
[Description("The directory where the preferences are saved to and loaded from")] //NOXLATE
[MgComponentProperty]
public string PreferencesDirectory
{
get;
set;
}
protected override void SubscribeViewerEvents(IMapViewer viewer)
{
base.SubscribeViewerEvents(viewer);
//This is a new viewer instance. So load our prefs and apply settings to this viewer
var ser = new XmlSerializer(typeof(MgViewerOptions));
var path = Path.Combine(this.PreferencesDirectory, MgViewerOptions.FILENAME);
if (File.Exists(path))
{
using (var stream = File.OpenRead(path))
{
try
{
var options = (MgViewerOptions)ser.Deserialize(stream);
//Apply settings
viewer.ShowVertexCoordinatesWhenDigitizing = options.ShowVertexCoordinates;
viewer.SelectionColor = Util.FromHtmlColor(options.SelectionColor);
viewer.ZoomInFactor = options.ZoomInFactor;
viewer.ZoomOutFactor = options.ZoomOutFactor;
viewer.ConvertTiledGroupsToNonTiled = options.ConvertTiledLayersToNonTiled;
Trace.TraceInformation("Applied viewer settings from: " + path); //NOXLATE
}
catch { }
}
}
else
{
Trace.TraceInformation("No viewer settings found in " + path + ". Doing nothing"); //NOXLATE
}
}
protected override MgControlView CreateControlView()
{
return new MgViewerOptionsControlImpl(this.Viewer, this.PreferencesDirectory);
}
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using RTSEngine.Data.Parsers;
namespace RTS.Input {
public class UICRTS {
public string Font;
public int FontSize;
public UICMinimap UICMinimap;
public UICAlertQueue UICAlertQueue;
public UICCombatStats UICCombatStats;
public UICUnitData UICUnitData;
public UICBuildingData UICBuildingData;
public int BBRows;
public int BBColumns;
public int BBIconSize;
public int BBIconBuffer;
public string BBTexture;
public int SelectionRows;
public int SelectionColumns;
public int SelectionIconSize;
public int SelectionIconBuffer;
public string SelectionTexture;
}
}
|
#region Using
using System.Runtime.InteropServices;
#endregion
namespace Emotion.Web.Models
{
/// <summary>
/// Used for VertexAttribPointer
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VertexAttribData
{
public uint Index;
public int Size;
public int Type;
public bool Normalized;
public int Stride;
public int Offset;
}
} |
using MongoDbGenericRepository.Models;
namespace Service.Models.Data
{
public interface IGroup : IDocument
{
IQuote Quote { get; set; }
IOption Option { get; set; }
}
public class CGroup : Document, IGroup
{
public IQuote Quote { get; set; }
public IOption Option { get; set; }
}
}
|
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace Linguist.XML
{
internal static class XDoc
{
public static XDocument Load ( Stream stream, LoadOptions options = LoadOptions.None )
{
#if ! NET35
return XDocument.Load ( stream, options );
#else
var settings = new XmlReaderSettings ( );
if ( ( options & LoadOptions.PreserveWhitespace ) == LoadOptions.None )
settings.IgnoreWhitespace = true;
settings.ProhibitDtd = false;
settings.MaxCharactersFromEntities = 10000000L;
settings.XmlResolver = null;
using ( var reader = XmlReader.Create ( stream, settings ) )
return XDocument.Load ( reader, options );
#endif
}
}
} |
// Copyright (c) 2016 Nicholas Rogoff
//
// Author: Nicholas Rogoff
// Created: 2016 - 12 - 26
//
// Project: hms.ConsoleProcessorTemplate
// Filename: ConsoleProcessorTemplate.cs
using System;
using System.IO;
using CommandLine;
namespace hms.ConsoleProcessorTemplate
{
public abstract class ConsoleProcessorTemplateBase<TOptions> where TOptions : new ()
{
protected TextWriter Error;
protected TextReader Input;
protected TextWriter Output;
protected TOptions Options;
protected ConsoleBusyIndicator BusyIndicator;
/// <summary>
/// The Template Method.
///
/// Defines the series of steps, some of which
/// may be overridden in derived classes.
/// </summary>
/// <param name="args">The command line arguments</param>
/// <param name="input">The input stream that will be iterated over</param>
/// <param name="output">The output stream</param>
/// <param name="error">The error stream</param>
public void Process(string[] args, TextReader input, TextWriter output, TextWriter error)
{
Error = error;
Output = output;
Input = input;
BusyIndicator = new ConsoleBusyIndicator();
ParseOptions(args);
var isValidArguments = ValidateArguments();
if (isValidArguments)
{
PreProcess();
ProcessLines();
PostProcess();
}
}
private void ParseOptions(string[] args)
{
Options = new TOptions();
Parser.Default.ParseArgumentsStrict(args, Options, OnFail);
}
/// <summary>
/// Runs when argument validation fails
/// </summary>
private void OnFail()
{
#if DEBUG
Console.WriteLine("!! command arguements failed validation !!");
Console.ReadKey();
#endif
Console.CursorVisible = true;
Environment.Exit(-1);
}
private void ProcessLines()
{
var currentLine = Input.ReadLine();
while (currentLine != null)
{
ProcessLine(currentLine);
currentLine = Input.ReadLine();
}
}
/// <summary>
/// Override to perform additional argument validation
/// and write validation error output to user.
/// Defaults to true.
/// </summary>
/// <returns>t</returns>
protected virtual bool ValidateArguments()
{
return true;
}
/// <summary>
/// Override to perform one-time pre-processing
/// that executes before the main processing loop.
/// </summary>
protected virtual void PreProcess()
{
}
/// <summary>
/// Override to perform processing on each line of input.
/// </summary>
protected virtual void ProcessLine(string line)
{
}
/// <summary>
/// Override to perform one-time post-processing
/// that executes after the main processing loop.
/// </summary>
protected virtual void PostProcess()
{
}
}
} |
using System;
using System.Windows.Media;
using Prism.Mvvm;
namespace Arsync.Prismatic.MinimalWindowDemo.ViewModels
{
public abstract class TabViewModelBase : BindableBase, IDisposable
{
private ImageSource _tabIcon;
private string _tabHeader;
private bool _isPinned;
protected TabViewModelBase()
{
}
public ImageSource TabIcon
{
get => _tabIcon;
set => SetProperty(ref _tabIcon, value);
}
public string TabHeader
{
get => _tabHeader;
set => SetProperty(ref _tabHeader, value);
}
public bool IsPinned
{
get => _isPinned;
set => SetProperty(ref _isPinned, value);
}
public abstract void PrepareToWindowTransfer();
protected virtual void Dispose(bool disposing)
{
}
public void Dispose()
{
Dispose(true);
// GC.SuppressFinalize(this);
}
}
}
|
using System;
using System.Xml;
using System.Xml.Serialization;
namespace EMS.EDXL.CIQ
{
/// <summary>
/// A container of different types of electronic addresses of party (e.g. email, chat, skype, etc)
/// </summary>
[Serializable]
public class ElectronicAddressIdentifier
{
#region Private Member Variables
/// <summary>
/// Type of the electronic Address
/// </summary>
private ElectronicAddressIdentifierTypeList? electronicAddressKind;
/// <summary>
/// Usage of electronic address identifier. e.g. business, personal
/// </summary>
private string usage;
/// <summary>
/// The Free-Text Address
/// </summary>
private string electronicAddressValue;
#endregion
#region XML Attributes
/// <summary>
/// Gets or sets
/// Usage of electronic address identifier. e.g. business, personal
/// </summary>
[XmlAttribute("Usage")]
public string Usage
{
get { return this.usage; }
set { this.usage = value; }
}
/// <summary>
/// Set flag to determine if Usage attribute is serialized or not
/// </summary>
[XmlIgnore]
public bool UsageSpecified
{
get { return !string.IsNullOrWhiteSpace(this.usage); }
}
/// <summary>
/// Gets or sets
/// Kind of the contact number
/// </summary>
[XmlAttribute("Kind")]
public ElectronicAddressIdentifierTypeList Kind
{
get { return this.electronicAddressKind.Value; }
set { this.electronicAddressKind = value; }
}
/// <summary>
/// Set flag to determine if Kind attribute is serialized or not
/// </summary>
[XmlIgnore]
public bool KindSpecified
{
get { return this.electronicAddressKind.HasValue; }
}
#endregion XML Attributes
#region XML Elements
/// <summary>
/// Gets or sets
/// Electronic address of party
/// </summary>
[XmlText]
public string Value
{
get { return this.electronicAddressValue; }
set { this.electronicAddressValue = value; }
}
#endregion XML Elements
}
} |
public class Wizard : Hero
{
public Wizard(string Name, int Level, string HeroType)
{
this.Name = Name;
this.Level = Level;
this.HeroType = HeroType;
}
public override string Attack()
{
return this.Name + " Lançou magia";
}
public string Attack(int Bonus)
{
if (Bonus > 6)
{
return this.Name + " Lançou magia super efetiva com bonus de " + Bonus;
}
else
{
return this.Name + " Lançou uma magia com força fraca com bonus de " + Bonus;
}
}
} |
using System.Net;
namespace ApiHelper2.Models
{
/// <summary>
/// API 回傳的結果資訊
/// </summary>
public class APIResult<T>
{
/// <summary>
/// 回傳的Response 標頭
/// </summary>
public WebHeaderCollection ResponseHeaders;
/// <summary>
/// 回傳的 Response 字串
/// </summary>
public T Response { get; internal set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.