content stringlengths 23 1.05M |
|---|
using System;
#if ALTCOINS
namespace BTCPayServer.Services.Altcoins.Stripe.UI
{
public class StripePaymentViewModel
{
public string Crypto { get; set; }
public string Amount { get; set; }
public string TransactionId { get; set; }
public DateTimeOffset ReceivedTime { get; set; }
public object TransactionLink { get; set; }
}
}
#endif
|
namespace ReadyPlayerMe
{
public enum ColorMode
{
SystemSetting = 0,
DarkModeOff = 1,
DarkModeOn = 2
}
public enum WebkitContentMode
{
Recommended = 0,
Mobile = 1,
Desktop = 2
}
public class WebViewOptions
{
public bool Transparent = false;
public bool Zoom = false;
public string UA = "";
public ColorMode AndroidForceDarkMode = ColorMode.DarkModeOff;
public bool EnableWKWebView = true;
public WebkitContentMode WKContentMode = WebkitContentMode.Recommended;
}
} |
using CruiseManager.Core.App;
using System;
using System.Windows.Forms;
namespace CruiseManager.WinForms
{
public partial class SettingsView : UserControl
{
public SettingsView()
{
InitializeComponent();
}
private void _BTN_browseDefaultCruiseFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.ShowDialog(this);
}
}
private void _BTN_browseTemplateFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.ShowDialog(this);
}
}
public void SaveSettings()
{
}
public void RevertSettings()
{
}
#region IView Members
protected void InitializeView(WindowPresenter windowPresenter)
{
this.WindowPresenter = windowPresenter;
}
public WindowPresenter WindowPresenter { get; set; }
//public NavOption[] NavOptions
//{
// get { throw new NotImplementedException(); }
//}
//public NavOption[] ViewActions
//{
// get { throw new NotImplementedException(); }
//}
#endregion IView Members
}
} |
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour {
private RythmCheck check;
public GameObject blastPrefab;
public Collider2D ground;
public SoundMaster sm;
private Rigidbody2D thisRigid;
public HealthBarController healthBart;
private List<float> timeStamp = new List<float>();
private GroundWaveRenderer groundWave;
public List<Color> colors;
public float period = 2;
// Use this for initialization
void Start () {
thisRigid = GetComponent<Rigidbody2D>();
check = GetComponent<RythmCheck> ();
groundWave = GameObject.FindWithTag ("ground_foreground").GetComponent<GroundWaveRenderer>();
SoundMaster sm = GameObject.FindWithTag ("SoundMaster").GetComponent<SoundMaster>();
sm.beatListeners += delegate(float beatDuration) {
doEndOfMaat ();
};
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire1"))
{
//add a new timeStamp
timeStamp.Add(Time.time);
// only keep the last 20 taps
if (timeStamp.Count > 20) {
timeStamp.RemoveAt (0);
}
}
}
public List<float> getTimeStamp()
{
return timeStamp;
}
public void doEndOfMaat()
{
// Do finale rythmCheck
int lastRythm = check.rythmCheck ();
if (lastRythm > 0) {
groundWave.stampBig ();
blast (lastRythm);
} else {
groundWave.stampSmall ();
}
}
private void blast(int frq)
{
GameObject go = Instantiate (blastPrefab);
go.GetComponent<BlastController>().setFrequency(frq);
Color color;
if (frq == 2) {
color = colors[0];
} else if (frq == 4) {
color = colors[1];
} else if (frq == 8) {
color = colors[2];
} else {
color = Color.cyan;
}
go.GetComponent<SpriteRenderer> ().color = color;
}
public void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name != "Ground Collider")
{
Debug.Log("giant was hit by " + collision.gameObject);
this.healthBart.LostALive();
}
}
}
|
using System;
using System.ComponentModel;
namespace Gibbed.MassEffect2.FileFormats.Save
{
[TypeConverter(typeof(ExpandableObjectConverter))]
public partial class Loadout : IUnrealSerializable
{
[UnrealFieldOffset(0x00)]
[UnrealFieldDisplayName("Unknown #1")]
public string Unknown0;
[UnrealFieldOffset(0x0C)]
[UnrealFieldDisplayName("Unknown #2")]
public string Unknown1;
[UnrealFieldOffset(0x18)]
[UnrealFieldDisplayName("Unknown #3")]
public string Unknown2;
[UnrealFieldOffset(0x24)]
[UnrealFieldDisplayName("Unknown #4")]
public string Unknown3;
[UnrealFieldOffset(0x30)]
[UnrealFieldDisplayName("Unknown #5")]
public string Unknown4;
[UnrealFieldOffset(0x3C)]
[UnrealFieldDisplayName("Unknown #6")]
public string Unknown5;
public void Serialize(IUnrealStream stream)
{
stream.Serialize(ref this.Unknown0);
stream.Serialize(ref this.Unknown1);
stream.Serialize(ref this.Unknown2);
stream.Serialize(ref this.Unknown3);
stream.Serialize(ref this.Unknown4);
stream.Serialize(ref this.Unknown5);
}
}
}
|
using System;
using System.Collections.Generic;
using UPT.BOT.Aplicacion.DTOs.BOT;
namespace UPT.BOT.Distribucion.Bot.Acceso.Encuesta
{
[Serializable]
public class EncuestaProxy : BaseProxy
{
public EncuestaProxy(string rutaApi) : base(rutaApi)
{
}
public List<EncuestaDto> Obtener()
{
return Ejecutar<List<EncuestaDto>>("encuesta");
}
public EncuestaDto ObtenerXCodigo(long codigoEncuesta)
{
return Ejecutar<EncuestaDto>(string.Format("encuesta/codigo/{0}", codigoEncuesta));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Linq.Extras.Internal;
namespace Linq.Extras
{
partial class XEnumerable
{
/// <summary>
/// Returns a sequence with distinct elements from the input sequence based on the specified key and key comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of <c>source</c>.</typeparam>
/// <typeparam name="TKey">The type of the key used for testing equality between elements.</typeparam>
/// <param name="source">The sequence to return distinct elements from.</param>
/// <param name="keySelector">A delegate that returns the key used to test equality between elements.</param>
/// <param name="keyComparer">A comparer used to test equality between keys (can be null).</param>
/// <returns>A sequence whose elements have distinct values for the specified key.</returns>
[Pure]
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
[NotNull] this IEnumerable<TSource> source,
[NotNull] Func<TSource, TKey> keySelector,
IEqualityComparer<TKey>? keyComparer = null)
{
source.CheckArgumentNull(nameof(source));
keySelector.CheckArgumentNull(nameof(keySelector));
var comparer = XEqualityComparer.By(keySelector, keyComparer);
return source.Distinct(comparer);
}
}
}
|
namespace HttpServer
{
partial class ServerManager
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnStartServer = new System.Windows.Forms.Button();
this.tbServerPath = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.lblLastReqPath = new System.Windows.Forms.Label();
this.lblLastResponse = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnStartServer
//
this.btnStartServer.Location = new System.Drawing.Point(12, 12);
this.btnStartServer.Name = "btnStartServer";
this.btnStartServer.Size = new System.Drawing.Size(277, 60);
this.btnStartServer.TabIndex = 0;
this.btnStartServer.Text = "Start Server";
this.btnStartServer.UseVisualStyleBackColor = true;
this.btnStartServer.Click += new System.EventHandler(this.btnStartServer_Click);
//
// tbServerPath
//
this.tbServerPath.Location = new System.Drawing.Point(416, 31);
this.tbServerPath.Name = "tbServerPath";
this.tbServerPath.Size = new System.Drawing.Size(253, 22);
this.tbServerPath.TabIndex = 1;
this.tbServerPath.Text = "http://localhost:8083";
this.tbServerPath.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(332, 34);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(28, 16);
this.label1.TabIndex = 2;
this.label1.Text = "AT:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.ForeColor = System.Drawing.Color.Brown;
this.label2.Location = new System.Drawing.Point(12, 90);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(89, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Last Request:";
//
// lblLastReqPath
//
this.lblLastReqPath.AutoSize = true;
this.lblLastReqPath.Location = new System.Drawing.Point(107, 90);
this.lblLastReqPath.Name = "lblLastReqPath";
this.lblLastReqPath.Size = new System.Drawing.Size(50, 16);
this.lblLastReqPath.TabIndex = 4;
this.lblLastReqPath.Text = "Offline !";
//
// lblLastResponse
//
this.lblLastResponse.AutoSize = true;
this.lblLastResponse.Location = new System.Drawing.Point(107, 124);
this.lblLastResponse.Name = "lblLastResponse";
this.lblLastResponse.Size = new System.Drawing.Size(50, 16);
this.lblLastResponse.TabIndex = 6;
this.lblLastResponse.Text = "Offline !";
//
// label4
//
this.label4.AutoSize = true;
this.label4.ForeColor = System.Drawing.Color.Brown;
this.label4.Location = new System.Drawing.Point(12, 124);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(89, 16);
this.label4.TabIndex = 5;
this.label4.Text = "Last Request:";
//
// ServerManager
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(681, 166);
this.Controls.Add(this.lblLastResponse);
this.Controls.Add(this.label4);
this.Controls.Add(this.lblLastReqPath);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.tbServerPath);
this.Controls.Add(this.btnStartServer);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ServerManager";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "ServerManager";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnStartServer;
private System.Windows.Forms.TextBox tbServerPath;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label lblLastReqPath;
private System.Windows.Forms.Label lblLastResponse;
private System.Windows.Forms.Label label4;
}
}
|
using Elsa.Models;
using Elsa.Persistence.YesSql.Documents;
using Elsa.Persistence.YesSql.Indexes;
using YesSql;
namespace Elsa.Persistence.YesSql
{
public static class WorkflowDefinitionDocumentExtensions
{
public static bool WithVersion(this WorkflowDefinitionDocument workflowDefinition, VersionOptions? version = default)
{
var versionOption = version ?? VersionOptions.Latest;
if (versionOption.IsDraft)
return !workflowDefinition.IsPublished;
if (versionOption.IsLatest)
return workflowDefinition.IsLatest;
if (versionOption.IsPublished)
return workflowDefinition.IsPublished;
if (versionOption.IsLatestOrPublished)
return workflowDefinition.IsPublished || workflowDefinition.IsLatest;
if (versionOption.Version > 0)
return workflowDefinition.Version == versionOption.Version;
return true;
}
public static IQuery<WorkflowDefinitionDocument, WorkflowDefinitionIndex> WithVersion(this IQuery<WorkflowDefinitionDocument, WorkflowDefinitionIndex> query, VersionOptions? version = default)
{
var versionOption = version ?? VersionOptions.Latest;
if (versionOption.IsDraft)
return query.Where(x => !x.IsPublished);
if (versionOption.IsLatest)
return query.Where(x => x.IsLatest);
if (versionOption.IsPublished)
return query.Where(x => x.IsPublished);
if (versionOption.IsLatestOrPublished)
return query.Where(x => x.IsPublished || x.IsLatest);
if (versionOption.Version > 0)
return query.Where(x => x.Version == versionOption.Version);
return query;
}
}
} |
using System;
namespace IsPrime
{
class Program
{
static void Main(string[] args)
{
double n;
System.Console.WriteLine("Type a number:");
n = Double.Parse(System.Console.ReadLine());
System.Console.WriteLine(checkIsPrime(n) ? "Prime" : "Not Prime");
}
internal static bool checkIsPrime(double n)
{
if (n == 1)
return false;
if (n == 2)
return true;
int squareRoot = (int)Math.Floor(Math.Sqrt(n));
for (int i = 3; i <= squareRoot; i += 2)
{
if (n % i == 0)
return false;
}
return false;
}
}
}
|
using System.Collections.Generic;
using System.IO;
using WireMock.Handlers;
namespace WireMock.Net.ConsoleApplication
{
internal class CustomFileSystemFileHandler : IFileSystemHandler
{
private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings");
/// <inheritdoc cref="IFileSystemHandler.FolderExists"/>
public bool FolderExists(string path)
{
return Directory.Exists(path);
}
/// <inheritdoc cref="IFileSystemHandler.CreateFolder"/>
public void CreateFolder(string path)
{
Directory.CreateDirectory(path);
}
/// <inheritdoc cref="IFileSystemHandler.EnumerateFiles"/>
public IEnumerable<string> EnumerateFiles(string path)
{
return Directory.EnumerateFiles(path);
}
/// <inheritdoc cref="IFileSystemHandler.GetMappingFolder"/>
public string GetMappingFolder()
{
return Path.Combine(@"c:\temp-wiremock", AdminMappingsFolder);
}
/// <inheritdoc cref="IFileSystemHandler.ReadMappingFile"/>
public string ReadMappingFile(string path)
{
return File.ReadAllText(path);
}
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile"/>
public void WriteMappingFile(string path, string text)
{
File.WriteAllText(path, text);
}
}
} |
using System.Threading;
namespace Knapcode.ExplorePackages
{
public class UrlReporterProvider
{
private readonly AsyncLocal<IUrlReporter> _currentUrlReporter;
public UrlReporterProvider()
{
_currentUrlReporter = new AsyncLocal<IUrlReporter>();
}
public void SetUrlReporter(IUrlReporter urlReporter)
{
_currentUrlReporter.Value = urlReporter;
}
public IUrlReporter GetUrlReporter()
{
return _currentUrlReporter.Value ?? NullUrlReporter.Instance;
}
}
}
|
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using SlackNet.Interaction;
using ActionElement = SlackNet.Interaction.ActionElement;
using Button = SlackNet.Interaction.Button;
namespace SlackNet.EventsExample
{
public class LegacyCounter : IInteractiveMessageHandler
{
public static readonly string ActionName = "add";
private static readonly Regex _counterPattern = new Regex("Counter: (\\d+)");
public async Task<MessageResponse> Handle(InteractiveMessage message)
{
var counterText = _counterPattern.Match(message.OriginalAttachment.Text);
if (counterText.Success)
{
var count = int.Parse(counterText.Groups[1].Value);
var increment = int.Parse(message.Action.Value);
message.OriginalAttachment.Text = $"Counter: {count + increment}";
message.OriginalAttachment.Actions = Actions;
return new MessageResponse
{
ReplaceOriginal = true,
Message = message.OriginalMessage
};
}
return null;
}
public static IList<ActionElement> Actions => new List<ActionElement>
{
new Button
{
Name = ActionName,
Value = "1",
Text = "Add 1"
},
new Button
{
Name = ActionName,
Value = "5",
Text = "Add 5"
},
new Button
{
Name = ActionName,
Value = "10",
Text = "Add 10"
}
};
}
} |
using System;
using UnityEngine;
namespace GibFrame
{
/// <summary>
/// Define a wrapper for an object that can safely be null
/// </summary>
/// <typeparam name="T"> </typeparam>
[Serializable]
public class Optional<T> where T : class
{
[SerializeField] private T obj;
public Optional(Func<T> factory)
{
obj = factory();
}
public Optional()
{
obj = null;
}
/// <summary>
/// Try to retrieve a value from the underlying object
/// </summary>
/// <typeparam name="TResult"> </typeparam>
/// <param name="provider"> </param>
/// <returns> The value if <see cref="obj"/> is not null, <see cref="default"/> otherwise </returns>
public bool TryGet<TResult>(Func<T, TResult> provider, out TResult result)
{
if (IsNull())
{
result = default;
return false;
}
result = provider(obj);
return true;
}
/// <summary>
/// Try to retrieve the underlying optional
/// </summary>
/// <typeparam name="TResult"> </typeparam>
/// <param name="provider"> </param>
/// <returns> The value if <see cref="obj"/> is not null, <see cref="default"/> otherwise </returns>
public bool TryGet(out T result) => TryGet((elem) => elem, out result);
/// <summary>
/// Try execute a method on the underlying object
/// </summary>
/// <param name="func"> </param>
public void Try(Action<T> func)
{
if (IsNull())
{
return;
}
func?.Invoke(obj);
}
public bool IsNull() => (obj is null) || (obj is UnityEngine.Object uobj && !uobj);
}
} |
using System.Data.Common;
using System.Data.SqlClient;
using Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Presentation.Settings;
using Presentation.Windows;
namespace Presentation.Extensions
{
public static class ServiceCollectionExtensions
{
public static void AddPresentationDependencies(this IServiceCollection services)
{
services.AddTransient<MainWindow>();
}
public static void AddDataDependencies(this IServiceCollection services)
{
IConfiguration configuration = SettingsLoader.Configuration;
services.AddSingleton(configuration);
services.AddSingleton<DbConnection>(
new SqlConnection(configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<PeopleRepository>();
}
}
}
|
using System;
using System.Collections.Generic;
static class LogLine
{
public static Dictionary<string, string> ParseLogLine(string logLine)
{
string[] logLineComponents = logLine.Split(":");
return new Dictionary<string, string>()
{
{ "level", logLineComponents[0].Trim('[', ']').ToLower() },
{ "message", logLineComponents[1].Trim() }
};
}
public static string Message(string logLine) => ParseLogLine(logLine)["message"];
public static string LogLevel(string logLine) => ParseLogLine(logLine)["level"];
public static string Reformat(string logLine)
{
Dictionary<string, string> parsed = ParseLogLine(logLine);
return $"{parsed["message"]} ({parsed["level"]})";
}
}
|
using WeixinSDK.Work.Common;
using WeixinSDK.Work.Models.Message;
namespace WeixinSDK.Work.Apis
{
/// <summary>
/// 消息发送接口
/// </summary>
public class MessageApi : ApiBase
{
/// <summary>
/// 实例化消息发送接口
/// </summary>
/// <param name="client"></param>
public MessageApi(ApiClientBase client) : base(client)
{
}
/// <summary>
/// 发送文本消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendText(SendTextRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送图片消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendImage(SendImageRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送语音消息
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendVoice(SendVoiceRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送视频消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendVideo(SendVideoRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送文件消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendFile(SendFileRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送文本卡片消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendTextCard(SendTextCardRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送图文消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendNews(SendNewsRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送图文消息(mpnews)
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult SendMpNews(SendMpNewsRequest request)
{
if (request.agentid == 0)
{
request.agentid = Client.AgentId;
}
return Send(request);
}
/// <summary>
/// 发送文本、图片、视频、文件、图文等类型消息
/// 文档:https://work.weixin.qq.com/api/doc#10167
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>返回结果</returns>
public SendMessageResult Send(SendMessageRequest request)
{
var accessToken = Client.GetToken();
return Client.PostAsJson<SendMessageResult>("/message/send", new {accessToken.access_token},
request);
}
}
}
|
using osuElements.Helpers;
using osuElements.Storyboards;
namespace osuElements.Beatmaps.Events
{
public class BreakEvent : EventBase
{
public BreakEvent(int time, int endTime)
{
Type = EventTypes.Break;
StartTime = time;
EndTime = endTime;
}
public override string ToString()
{
return $"{(int) Type},{StartTime},{EndTime}";
}
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
namespace ToolKit.DirectoryServices.ServiceInterfaces
{
/// <summary>
/// Specifies available ADSI query dialects.
/// </summary>
[SuppressMessage(
"Microsoft.Naming",
"CA1707:IdentifiersShouldNotContainUnderscores",
Justification = "This enumeration represents Win32API which include underscores.")]
[Flags]
public enum ADSI_DIALECT
{
/// <summary>
/// ADSI queries are based on the LDAP dialect.
/// </summary>
LDAP = 0,
/// <summary>
/// ADSI queries are based on the SQL dialect.
/// </summary>
SQL = 0x1
}
}
|
namespace SequelNet.SchemaGenerator
{
public enum DalIndexIndexType
{
None,
BTREE,
HASH,
RTREE
}
} |
using System;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace Crowdin.Api.Screenshots
{
[PublicAPI]
public class Screenshot
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("userId")]
public int UserId { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("size")]
public Size Size { get; set; }
[JsonProperty("tagsCount")]
public int TagsCount { get; set; }
[JsonProperty("tags")]
public Tag[] Tags { get; set; }
[JsonProperty("createdAt")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty("updatedAt")]
public DateTimeOffset UpdatedAt { get; set; }
}
} |
using CleanMedApi.Data.DTOs.EnderecoDTOs;
namespace CleanMedApi.Data.DTOs.UsuarioDTOs
{
public class UsuarioCreateDto
{
public string? NomeCompleto { get; set; }
public DateOnly? DataNascimento { get; set; }
public string? CpfCnpj { get; set; }
public string Email { get; set; }
public string? Sexo { get; set; }
public string? Conselho { get; set; }
public int? NumeroConselho { get; set; }
public string? Senha { get; set; }
public string? Celular { get; set; }
public string? Telefone { get; set; }
public bool? IsPessoaJuridica { get; set; }
public bool? IsUsuarioLogin { get; set; }
public bool? IsProfissional { get; set; }
public bool? IsFuncionario { get; set; }
public string? Observacao { get; set; }
public int IdEndereco { get; set; }
public int IdEmpresa { get; set; }
public EnderecoCreateDto Endereco { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Baseline.Validate
{
public abstract partial class BaseValidator<TToValidate>
{
/// <summary>
/// Gets and returns an immediate child validation result with the keys combined with the key defined by the
/// expression.
/// </summary>
/// <param name="expression">The expression which returns the child field that has failed validation.</param>
/// <param name="childValidationResult">The result from a nested validation result.</param>
protected ValidationResult FailureFor<TField>(
Expression<Func<TToValidate, TField>> expression,
ValidationResult childValidationResult
)
{
return FailureFor(GetNameOfField(expression), childValidationResult);
}
/// <summary>
/// Gets and returns an immediate child validation result with the keys combined with the key specified.
/// </summary>
/// <param name="property">The property which has failed validation.</param>
/// <param name="childValidationResult">The result from a nested validation result.</param>
protected ValidationResult FailureFor(
string property,
ValidationResult childValidationResult
)
{
if (childValidationResult.Success)
{
return Success();
}
var validationResult = new ValidationResult(ValidatingTypeName);
foreach (var (key, value) in childValidationResult.Failures)
{
validationResult.Failures.Add(
$"{(string.IsNullOrWhiteSpace(property) ? string.Empty : $"{property}.")}{key}",
value
);
}
return validationResult;
}
/// <summary>
/// Immediately returns a failure for a request property defined by the expression.
/// </summary>
/// <param name="expression">The expression which returns the field that has failed validation.</param>
/// <param name="message">The message to return.</param>
protected ValidationResult FailureFor<TField>(Expression<Func<TToValidate, TField>> expression, string message)
{
return FailureFor(GetNameOfField(expression), message);
}
/// <summary>
/// Immediately returns a failure for a request property.
/// </summary>
/// <param name="property">The property which has failed validation.</param>
/// <param name="message">The message to return.</param>
protected ValidationResult FailureFor(string property, string message)
{
var validationResult = new ValidationResult(ValidatingTypeName);
validationResult.Failures.Add(property, new List<string> { message.Replace(":property", property) });
return validationResult;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class SpaceShipController : MonoBehaviour
{
#region variables
[Header("Ship Camera")]
public CinemachineVirtualCamera shipCamFollow;
[Header("Initialize")] [Space(15)]
public ShipInitialize shipInit;
public GunInitialize defaultGunInit;
public GameObject ship;
[Header("Ships")]
public List<ShipInitialize> shipInits;
public List<ShipInitialize> ownedShips;
[Header("Player")] [Space(15)]
public int level = 1;
public int money = 0;
public float exp = 0.0f;
[SerializeField] private float _expLimit = 20;
[SerializeField] private int _health;
public int Health{ get => _health; set => _health = Mathf.Clamp(value, 0, shipInit.health); }
// Enemy
[Header("Target")]
public bool isReachToDestination;
public Transform target;
// Requirements
private UiManager _uiManager;
private GunController _gunController;
private MineController _mineController;
#endregion
private void Start() {
_gunController = GameObject.Find("Gun_Manager").GetComponent<GunController>();
_uiManager = GameObject.Find("UI_Manager").GetComponent<UiManager>();
_mineController = GameObject.Find("Enemy_Manager").GetComponent<MineController>();
CreateShipObject(true);
ownedShips.Add(shipInit);
}
public void UpdateLevel(float amount){
exp += amount;
if(exp >= _expLimit){
exp -= _expLimit;
_expLimit += level * 21.0f;
level++;
_uiManager.UpdateLevelUI();
}
}
public void HealthRegen(int amount) => Health += amount;
public void CreateShipObject(bool healthRegenerate) {
GameObject newShip = null;
if(ship != null){
newShip = Instantiate(shipInit.shipObject, ship.transform.position, ship.transform.rotation);
newShip.AddComponent<SpaceShipMovement>();
Destroy(ship);
}
else{
newShip = Instantiate(shipInit.shipObject, Vector3.zero, Quaternion.identity);
newShip.AddComponent<SpaceShipMovement>();
}
ship = newShip;
ship.transform.SetParent(GameObject.Find("Player").transform);
_mineController.ship = ship.transform;
_mineController.shipMovement = ship.GetComponent<SpaceShipMovement>();
shipCamFollow.m_Follow = ship.transform;
shipCamFollow.m_LookAt = ship.transform;
// add guns to the ship
List<Transform> gunSlots = _gunController.GetGunSlots();
_gunController.wearedGuns.Clear();
if(_gunController.ownedGuns.Count > 0){
for(int i = 0; i < gunSlots.Count; i++){
if(_gunController.ownedGuns.Count - (i + 1) < 0) break;
_gunController.AddNewGun(_gunController.ownedGuns[_gunController.ownedGuns.Count - (i + 1)], i, false);
}
}
else{
_gunController.AddNewGun(defaultGunInit, 0, true);
}
if(healthRegenerate)
HealthRegen(shipInit.health);
}
}
|
using System;
using System.Diagnostics;
namespace DevZest.Windows.Docking
{
partial class DockItem
{
private sealed class ToggleAutoHideCommand : CommandBase
{
public static void Execute(DockItem dockItem, DockItemShowMethod showMethod)
{
DockControl dockControl = dockItem.DockControl;
if (dockControl.CanEnterUndo)
dockControl.ExecuteCommand(new ToggleAutoHideCommand(dockItem, showMethod));
else
dockItem.DoToggleAutoHide(showMethod);
}
private DockItemShowMethod _showMethod;
private DockItemShowMethod _undoShowMethod;
private ToggleAutoHideCommand(DockItem dockItem, DockItemShowMethod showMethod)
: base(dockItem)
{
_showMethod = showMethod;
_undoShowMethod = GetShowMethod(dockItem, dockItem.FirstPane);
}
public override void Execute(DockControl dockControl)
{
GetDockItem(dockControl).DoToggleAutoHide(_showMethod);
}
public override void UnExecute(DockControl dockControl)
{
GetDockItem(dockControl).DoToggleAutoHide(_undoShowMethod);
}
}
}
}
|
namespace kmd.Core.Explorer.Contracts
{
public enum ExplorerItemsStates
{
Default,
Filtered,
Expanded
}
} |
using Dapper;
using MedicalSystem.Services.Consultation.Api.Options;
using MedicalSystem.Services.Consultation.Api.ViewModels;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
namespace MedicalSystem.Services.Consultation.Api.Queries
{
public class DoctorQueries : IDoctorQueries
{
private readonly IOptionsMonitor<DatabaseOptions> _optionsAccessor;
public DoctorQueries(IOptionsMonitor<DatabaseOptions> optionsAccessor)
{
_optionsAccessor = optionsAccessor;
}
IEnumerable<DoctorViewModel> IDoctorQueries.GetAll()
{
dynamic dbResultModels;
using (var con = new SqlConnection(_optionsAccessor.CurrentValue.ConsultationDbConnectionString))
{
dbResultModels = con.Query<dynamic>(
@"SELECT d.Id, d.FirstName, d.LastName
FROM Doctors d
ORDER BY d.FirstName DESC");
}
if (dbResultModels == null || dbResultModels!.Count == 0)
{
return new List<DoctorViewModel>();
}
var doctorViewModels = new List<DoctorViewModel>();
foreach (dynamic? dbResultModel in dbResultModels!)
{
var doctorViewModel = new DoctorViewModel()
{
Id = dbResultModel!.Id,
FirstName = dbResultModel.FirstName,
LastName = dbResultModel.LastName
};
doctorViewModels.Add(doctorViewModel);
}
return doctorViewModels;
}
}
}
|
namespace Pathfinder.Event
{
public abstract class PathfinderEvent
{
public bool IsCancelled { get; set; }
public void CallEvent() { EventManager.CallEvent(this); }
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
namespace DotNetProjects.WPF.Converters.Converters
{
public class NullableDecimalToPercentageConverter : IValueConverter
{
//E.g. DB 0.042367 --> UI "4.24 %"
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
var fraction = decimal.Parse(value.ToString());
return fraction.ToString("P2");
}
//E.g. UI "4.2367 %" --> DB 0.042367
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
//Trim any trailing percentage symbol that the user MAY have included
var valueWithoutPercentage = value.ToString().TrimEnd(' ', '%');
return decimal.Parse(valueWithoutPercentage) / 100;
}
}
}
|
namespace ClientsRpki
{
public interface IRipeRpkiLocation
{
public string Url { get; set; }
}
public class RipeRpkiTestLocation : IRipeRpkiLocation
{
public string Url { get; set; } = "https://localcert.ripe.net/api/rpki";
}
public class RipeRpkiProductionLocation : IRipeRpkiLocation
{
public string Url { get; set; } = "https://my.ripe.net/api/rpki";
}
}
|
using Gw2_Launchbuddy.ObjectManagers;
using System;
using System.Windows;
using System.Windows.Controls;
namespace Gw2_Launchbuddy
{
/// <summary>
/// Interaction logic for GUI_ApplicationManager.xaml
/// </summary>
public partial class GUI_ApplicationManager : Window
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public GUI_ApplicationManager()
{
InitializeComponent();
this.Left = Properties.Settings.Default.instance_win_X;
this.Top = Properties.Settings.Default.instance_win_Y;
}
private void bt_close_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
lv_instances.ItemsSource = ClientManager.ActiveClients;
}
private void lv_gfx_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var client=lv_instances.SelectedItem as Client;
if(client!=null)client.Focus();
}
private void bt_closeinstance_Click(object sender, RoutedEventArgs e)
{
var client = (sender as Button).DataContext as Client;
client.Close();
lv_instances.ItemsSource = ClientManager.ActiveClients;
}
private void bt_maxmin_Click(object sender, RoutedEventArgs e)
{
var client = (sender as Button).DataContext as Client;
client.Focus();
}
private void Window_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
this.DragMove();
}
private void Window_Initialized(object sender, EventArgs e)
{
}
private void bt_suspend_Click(object sender, RoutedEventArgs e)
{
((sender as Button).DataContext as Client).Suspend();
}
private void bt_resume_Click(object sender, RoutedEventArgs e)
{
((sender as Button).DataContext as Client).Resume();
}
}
} |
using System.Collections.Generic;
namespace SnakeBattleNet.Core.Prototypes
{
internal class ChipBasedMind : IMind
{
public ChipBasedMind(IEnumerable<MindChip> mindChips)
{
}
public MoveDirection GetMoveDirection(VisibleArea visibleArea)
{
throw new System.NotImplementedException();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Central : MonoBehaviour {
public GameObject play_button, practice_button;
public GameObject GM;
public int cur_scene;
private GameObject bonus_obj;
public List<GameObject> bonus = new List<GameObject>();
public GameObject extra_bg;
//price of each item
public int[] price = new int[5];
//modifier, the rate at which the price of the item increase
public int[] modifier = new int[5];
//the amount of each current item
public int[] rss = new int[5];
public int gold;
public int highscore;
public bool in_shop;
//UI
public GameObject[] label_obj = new GameObject[4];
public UILabel[] label = new UILabel[4];
// Use this for initialization
void Start () {
cur_scene = 0;
Init();
SetUpLabel();
InitLabel();
//Invoke("FadeOut", 2);
}
public void FadeIn()
{
extra_bg.SendMessage("FadeIn");
}
public void FadeOut()
{
extra_bg.SendMessage("FadeOut");
}
private void Init()
{
//Get them from playerPref
}
#region Button
#region ShoppingButton
public void Shopping_0 ()
{
Buy(0);
}
public void Shopping_1()
{
Buy(1);
}
public void Shopping_2()
{
Buy(2);
}
public void Shopping_3()
{
Buy(3);
}
public void Shopping_4()
{
Buy(4);
}
public void Shopping_5()
{
Camera.main.transform.position = new Vector3(36, -30, -10);
in_shop = true;
}
public void Buy(int item)
{
//Check Price
if(gold >= price[item])
{
Debug.Log("Transaction Successful");
//if price is good, remove gold by the amount and increase comodity by one
gold -= price[item];
price[item] = price[item] * modifier[item];
rss[item]++;
InitLabel();
}
else
{
Debug.Log("NotEnoughMoney");
}
}
private int current_bonus;
public void DisplayPractice(int b)
{
Debug.Log(b);
//Set BG to Fade in
FadeIn();
current_bonus = b-1;
//Invoke("RepealAndReplace",1);
//Set BG to fade out
//Invoke("FadeOut", 2);
}
public void RepealAndReplace()
{
//if there is an old one, destroy it
if(bonus_obj!=null)
{
Destroy(bonus_obj);
}
Debug.Log(bonus[current_bonus]);
//Instantiate the item
bonus_obj = Instantiate(bonus[current_bonus], new Vector3(36,-28,0), Quaternion.identity);
FadeOut();
}
#endregion
public void Play()
{
play_button.SetActive(false);
GM.SendMessage("Restart");
}
public void PracticePlay()
{
GM.SendMessage("Practice");
Camera.main.transform.position = new Vector3(0, -4, -10);
}
public void PractiveOver()
{
Camera.main.transform.position = new Vector3(36, -4, -10);
}
#endregion
// Update is called once per frame
void Update () {
}
#region UI
private void SetUpLabel()
{
for (int i = 0; i < label_obj.Length; i++)
{
label[i] = label_obj[i].GetComponent<UILabel>();
}
}
public void InitLabel()
{
label[0].text = "" + gold;
SetUpPrice();
SetUpRss();
}
public void SetUpPrice()
{
for(int i = 1; i < 6; i++)
{
label[i].text = " " + price[i-1];
}
}
public void SetUpRss()
{
for (int i = 6; i <11; i++)
{
label[i].text = " " + rss[i-6];
}
}
#endregion
public void GameOver()
{
play_button.SetActive(true);
}
public void Restart()
{
play_button.SetActive(true);
}
public void TurnRight()
{
}
}
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// ReSharper disable CheckNamespace
// ReSharper disable CommentTypo
// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedType.Global
/* SomeValues.cs -- содержит 0, 1 или много значений класса
* Ars Magna project, http://arsmagna.ru
*/
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
#endregion
#nullable enable
namespace AM.Collections
{
//
// Источник вдохновения:
// https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Primitives/src/StringValues.cs
//
/// <summary>
/// Содержит 0, 1 или много экземпляров ссылочного типа.
/// </summary>
public readonly struct SomeValues<T>
: IList<T>
where T: class
{
#region Construction
/// <summary>
/// Конструктор: одно значение.
/// </summary>
public SomeValues
(
T value
)
: this()
{
_values = value;
} // constructor
/// <summary>
/// Конструктор: не одно значение: либо 0 (в т. ч. <c>null</c>), либо много.
/// </summary>
public SomeValues
(
T[]? values
)
: this()
{
if (values is not null && values.Length == 1)
{
_values = values[0];
}
else
{
_values = values;
}
} // constructor
#endregion
#region Private members
private readonly object? _values;
#endregion
#region Public methods
/// <summary>
/// Выдать значение как единственное.
/// </summary>
public T? AsSingle()
{
// Take local copy of _values so type checks remain
// valid even if the StringValues is overwritten in memory
var value = _values;
if (value is T result1)
{
return result1;
}
if (value is null)
{
return null;
}
// Not T, not null, can only be T[]
var result2 = Unsafe.As<T[]>(value);
return result2.Length == 0 ? null : result2[0];
} // method AsSingle
/// <summary>
/// Выдать значение как массив.
/// </summary>
public T[] AsArray()
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T result1)
{
return new[] { result1 };
}
if (value is null)
{
return Array.Empty<T>();
}
// Not T, not null, can only be T[]
return Unsafe.As<T[]>(value);
} // method AsArray
/// <summary>
/// Контейнер пуст?
/// </summary>
public bool IsNullOrEmpty()
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T)
{
return false;
}
if (value is null)
{
return true;
}
// Not T, not null, can only be T[]
var array = Unsafe.As<T[]>(value);
return array.Length == 0;
} // method IsNullOrEmpty
/// <summary>
/// Оператор неявного преобразования.
/// </summary>
public static implicit operator SomeValues<T> (T value)
=> new(value);
/// <summary>
/// Оператор неявного преобразования.
/// </summary>
public static implicit operator SomeValues<T> (T[] values)
=> new(values);
/// <summary>
/// Оператор неявного преобразования.
/// </summary>
public static implicit operator T? (SomeValues<T> values)
=> values.AsSingle();
/// <summary>
/// Оператор неявного преобразования.
/// </summary>
public static implicit operator T[](SomeValues<T> values)
=> values.AsArray();
#endregion
#region IList<T> members
/// <inheritdoc cref="IEnumerable.GetEnumerator"/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator"/>
public IEnumerator<T> GetEnumerator()
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T result1)
{
yield return result1;
}
else if (value is not null)
{
// Not T, not null, can only be T[]
var array = Unsafe.As<T[]>(value);
foreach (var one in array)
{
yield return one;
}
}
} // method GetEnumerator
/// <summary>
/// Not implemented.
/// </summary>
public void Add(T item) => throw new NotImplementedException();
/// <summary>
/// Not implemented.
/// </summary>
public void Clear() => throw new NotImplementedException();
/// <inheritdoc cref="ICollection{T}.Contains"/>
public bool Contains(T item)
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
var comparer = EqualityComparer<T>.Default;
if (value is T one)
{
return comparer.Equals(item, one);
}
if (value is null)
{
return false;
}
// Not T, not null, can only be T[]
var array = Unsafe.As<T[]>(value);
foreach (var other in array)
{
if (comparer.Equals(item, other))
{
return true;
}
}
return false;
} // method Contains
/// <inheritdoc cref="ICollection{T}.CopyTo"/>
public void CopyTo
(
T[] array,
int arrayIndex
)
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T one)
{
array[arrayIndex] = one;
}
else if (value is not null)
{
// Not T, not null, can only be T[]
var many = Unsafe.As<T[]>(value);
Array.Copy(many, 0, array, arrayIndex, many.Length);
}
} // method CopyTo
/// <summary>
/// Not implemented.
/// </summary>
public bool Remove(T item) => throw new NotImplementedException();
/// <summary>
/// <inheritdoc cref="ICollection{T}.Count"/>
/// </summary>
public int Count
{
get
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T)
{
return 1;
}
if (value is null)
{
return 0;
}
// Not T, not null, can only be T[]
return Unsafe.As<T[]>(value).Length;
}
}
/// <inheritdoc cref="ICollection{T}.IsReadOnly"/>
public bool IsReadOnly => true;
/// <inheritdoc cref="IList{T}.IndexOf"/>
public int IndexOf
(
T item
)
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
var comparer = EqualityComparer<T>.Default;
if (value is T one)
{
return comparer.Equals(item, one) ? 0 : -1;
}
if (value is null)
{
return -1;
}
// Not T, not null, can only be T[]
var array = Unsafe.As<T[]>(value);
for (var index = 0; index < array.Length; index++)
{
if (comparer.Equals(item, array[index]))
{
return index;
}
}
return -1;
} // method IndexOf
/// <summary>
/// Not implemented.
/// </summary>
public void Insert(int index, T item) => throw new NotImplementedException();
/// <summary>
/// Not implemented
/// </summary>
public void RemoveAt(int index) => throw new NotImplementedException();
/// <inheritdoc cref="IList{T}.this"/>
public T this[int index]
{
get
{
// Take local copy of _values so type checks remain
// valid even if the SomeValues is overwritten in memory
var value = _values;
if (value is T value1)
{
return index == 0
? value1
: throw new IndexOutOfRangeException();
}
if (value is null)
{
throw new IndexOutOfRangeException();
}
// Not T, not null, can only be T[]
return Unsafe.As<T[]>(value) [index];
}
set => throw new NotImplementedException();
}
#endregion
#region Object members
/// <inheritdoc cref="object.ToString"/>
public override string ToString()
=> AsSingle()?.ToString() ?? string.Empty;
#endregion
} // struct SomeValues
} // namespace AM.Collections
|
using System;
using RESTfull;
namespace RESTClient.Responses
{
namespace Responses
{
[Serializable]
public class TokenResponse : BaseRequestResponse
{
public string token;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace StansAssets.Foundation.Extensions
{
/// <summary>
/// CSharp List extension methods.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Resizes the list. In case of increase list size - fills it with default elements.
/// </summary>
/// <param name="list">The current list.</param>
/// <param name="newSize">The new size of the list.</param>
/// <param name="defaultValue">The default value to set as new list elements.</param>
public static void Resize<T>(this List<T> list, int newSize, T defaultValue = default(T))
{
int currentSize = list.Count;
if (newSize < currentSize)
{
list.RemoveRange(newSize, currentSize - newSize);
}
else if (newSize > currentSize)
{
if (newSize > list.Capacity)
list.Capacity = newSize;
list.AddRange(Enumerable.Repeat(defaultValue, newSize - currentSize));
}
}
/// <summary>
/// Creates a deep copy of the list.
/// </summary>
/// <param name="list">The current list.</param>
/// <returns>The deep copy of the current list.</returns>
public static List<T> Clone<T>(this List<T> list) where T : ICloneable
{
return list.Select(item => (T)item.Clone()).ToList();
}
/// <summary>
/// Creates a shallow copy of the list.
/// </summary>
/// <param name="list">The current list.</param>
/// <returns>The shallow copy of the current list.</returns>
public static List<T> ShallowCopy<T>(this List<T> list)
{
return list.ToList();
}
/// <summary>
/// Fast remove method with O(1) complexity. Do not use it if an elements' order matters
/// </summary>
/// <param name="list">The current list.</param>
/// <param name="index">Index of the element.</param>
public static void RemoveBySwap<T>(this List<T> list, int index)
{
list[index] = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
}
/// <summary>
/// Fast remove method with O(n) complexity. Do not use it if an elements' order matters
/// </summary>
/// <param name="list">The current list.</param>
/// <param name="item">An element to be removed.</param>
public static void RemoveBySwap<T>(this List<T> list, T item)
{
int index = list.IndexOf(item);
RemoveBySwap(list, index);
}
/// <summary>
/// Fast remove method with O(n) complexity. Do not use it if an elements' order matters
/// </summary>
/// <param name="list">The current list.</param>
/// <param name="predicate">An element evaluation predicate.</param>
public static void RemoveBySwap<T>(this List<T> list, Predicate<T> predicate)
{
int index = list.FindIndex(predicate);
RemoveBySwap(list, index);
}
}
}
|
using System.Threading.Tasks;
using MassTransit;
namespace EntityDemo
{
public class UpdateEntityMetadataConsumer
: IConsumer<UpdateEntityMetadata>
{
private readonly IEntityManager _entityManager;
public UpdateEntityMetadataConsumer(IEntityManager entityManager)
{
_entityManager = entityManager;
}
public Task Consume(ConsumeContext<UpdateEntityMetadata> context)
{
var msg = context.Message;
_entityManager.UpdateMetadata(msg.EntityId, msg.Index, msg.Type, msg.Data);
return Task.CompletedTask;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Uri = Android.Net.Uri;
namespace MonoIO
{
class NotifyingAsyncQueryHandler : AsyncQueryHandler
{
private WeakReference mListener;
/**
* Interface to listen for completed query operations.
*/
public interface AsyncQueryListener {
void OnQueryComplete(int token, Java.Lang.Object cookie, ICursor cursor);
}
public NotifyingAsyncQueryHandler(ContentResolver resolver, AsyncQueryListener listener) : base(resolver)
{
SetQueryListener(listener);
}
/**
* Assign the given {@link AsyncQueryListener} to receive query events from
* asynchronous calls. Will replace any existing listener.
*/
public void SetQueryListener(AsyncQueryListener listener)
{
mListener = new WeakReference(listener);
}
/**
* Clear any {@link AsyncQueryListener} set through
* {@link #setQueryListener(AsyncQueryListener)}
*/
public void ClearQueryListener() {
mListener = null;
}
/**
* Begin an asynchronous query with the given arguments. When finished,
* {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is
* called if a valid {@link AsyncQueryListener} is present.
*/
public void StartQuery(Uri uri, String[] projection) {
StartQuery(-1, null, uri, projection, null, null, null);
}
/**
* Begin an asynchronous query with the given arguments. When finished,
* {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
* if a valid {@link AsyncQueryListener} is present.
*
* @param token Unique identifier passed through to
* {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)}
*/
public void StartQuery(int token, Uri uri, String[] projection) {
StartQuery(token, null, uri, projection, null, null, null);
}
/**
* Begin an asynchronous query with the given arguments. When finished,
* {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
* if a valid {@link AsyncQueryListener} is present.
*/
public void StartQuery(Uri uri, String[] projection, String sortOrder) {
StartQuery(-1, null, uri, projection, null, null, sortOrder);
}
/**
* Begin an asynchronous query with the given arguments. When finished,
* {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called
* if a valid {@link AsyncQueryListener} is present.
*/
public void StartQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) {
StartQuery(-1, null, uri, projection, selection, selectionArgs, orderBy);
}
/**
* Begin an asynchronous update with the given arguments.
*/
public void StartUpdate(Uri uri, ContentValues values) {
StartUpdate(-1, null, uri, values, null, null);
}
public void StartInsert(Uri uri, ContentValues values) {
StartInsert(-1, null, uri, values);
}
public void StartDelete(Uri uri) {
StartDelete(-1, null, uri, null, null);
}
protected override void OnQueryComplete (int token, Java.Lang.Object cookie, ICursor cursor)
{
var listener = mListener == null ? null : mListener.Target as AsyncQueryListener;
if (listener != null) {
listener.OnQueryComplete(token, cookie, cursor);
} else if (cursor != null) {
cursor.Close();
}
}
}
}
|
using Microsoft.IdentityModel.Tokens;
using System;
namespace NetDevPack.Security.JwtExtensions
{
public sealed class JwkList
{
public JwkList(JsonWebKeySet jwkTaskResult)
{
Jwks = jwkTaskResult;
When = DateTime.Now;
}
public DateTime When { get; set; }
public JsonWebKeySet Jwks { get; set; }
}
} |
namespace NotatnikMechanika.Shared
{
public static class CrudPaths
{
public const string ByIdPath = "{id}";
public const string AllPath = "all";
public const string CreatePath = "";
public const string UpdatePath = "{id}";
public const string DeletePath = "{id}";
public static string ById<TModel>(int id)
{
return CrudPathByModel<TModel>(ByIdPath).Replace("{id}", id.ToString());
}
public static string All<TModel>()
{
return CrudPathByModel<TModel>(AllPath);
}
public static string Create<TModel>()
{
return CrudPathByModel<TModel>(CreatePath);
}
public static string Update<TModel>(int id)
{
return CrudPathByModel<TModel>(UpdatePath).Replace("{id}", id.ToString());
}
public static string Delete<TModel>(int id)
{
return CrudPathByModel<TModel>(DeletePath).Replace("{id}", id.ToString());
}
private static string CrudPathByModel<TModel>(string path)
{
string controllerName = "api/" + typeof(TModel).Name.Replace("Model", "").ToLower();
return controllerName + "/" + path;
}
}
public static class AccountPaths
{
public const string Name = "api/account";
public const string LoginPath = "login";
public const string RegisterPath = "create";
public const string UpdatePath = "";
public const string DeletePath = "";
public static string Login()
{
return Name + "/" + LoginPath;
}
public static string Register()
{
return Name + "/" + RegisterPath;
}
public static string Update()
{
return Name + "/" + UpdatePath;
}
public static string Delete()
{
return Name + "/" + DeletePath;
}
}
public static class CarPaths
{
public const string Name = "api/car";
public const string ByCustomerPath = "byCustomer/{customerId}";
public static string ByCustomer(int customerId)
{
return Name + "/" + ByCustomerPath.Replace("{customerId}", customerId.ToString());
}
}
public static class CustomerPaths
{
public const string Name = "api/customer";
}
public static class OrderPaths
{
public const string Name = "api/order";
public const string ExtendedOrderPath = "extendedOrder/{orderId}";
public const string ExtendedOrdersPath = "extendedOrders/{archived}";
public const string AddExtendedOrderPath = "addExtendedOrder";
public const string UpdateServiceStatusPath = "updateServiceStatus/{orderId}/{serviceId}/{finished}";
public const string UpdateCommodityStatusPath = "updateCommodityStatus/{orderId}/{commodityId}/{finished}";
public static string Extended(bool archived = false)
{
return Name + "/" + ExtendedOrdersPath.Replace("{archived}", archived.ToString());
}
public static string Extended(int orderId)
{
return Name + "/" + ExtendedOrderPath.Replace("{orderId}", orderId.ToString());
}
public static string AddExtended()
{
return Name + "/" + AddExtendedOrderPath;
}
public static string UpdateServiceStatus(int orderId, int serviceId, bool finished)
{
return Name + "/" + UpdateServiceStatusPath
.Replace("{orderId}", orderId.ToString())
.Replace("{serviceId}", serviceId.ToString())
.Replace("{finished}", finished.ToString());
}
public static string UpdateCommodityStatus(int orderId, int commodityId, bool finished)
{
return Name + "/" + UpdateCommodityStatusPath
.Replace("{orderId}", orderId.ToString())
.Replace("{commodityId}", commodityId.ToString())
.Replace("{finished}", finished.ToString());
}
}
public static class ServicePaths
{
public const string Name = "api/service";
public const string ByOrderPath = "byOrder/{orderId}";
public static string ByOrder(int orderId)
{
return Name + "/" + ByOrderPath.Replace("{orderId}", orderId.ToString());
}
}
public static class CommodityPaths
{
public const string Name = "api/commodity";
public const string ByOrderPath = "byOrder/{orderId}";
public static string ByOrder(int orderId)
{
return Name + "/" + ByOrderPath.Replace("{orderId}", orderId.ToString());
}
}
}
|
// ------------------------------------------------------------------------------
// <auto-generated>
// This file was generated by Extensibility Tools v1.10.211
// </auto-generated>
// ------------------------------------------------------------------------------
namespace FileIcons
{
static class Vsix
{
public const string Id = "4772D066-28FF-46F1-B50F-DB736816DE19";
public const string Name = "Material Icons";
public const string Description = @"Adds icons for files that are not recognized by Solution Explorer";
public const string Language = "en-US";
public const string Version = "1.0.8";
public const string Author = "Duong.Nguyen";
public const string Tags = "icon, file, image";
}
}
|
using Godot;
using System;
public class Camera : Spatial{
Vector2 velocity = new Vector2();
[Export] public float Speed = 0.1f;
private Godot.Camera camera;
public override void _Ready() {
camera = GetNode("Camera")as Godot.Camera;
}
public override void _PhysicsProcess(float delta){
GetInput();
Translate (new Vector3(velocity.x,0,velocity.y));
}
public void GetInput(){
velocity = new Vector2();
if (Input.IsActionPressed("ui_right")) velocity.x += 1;
if (Input.IsActionPressed("ui_left")) velocity.x -= 1;
if (Input.IsActionPressed("ui_down")) velocity.y += 1;
if (Input.IsActionPressed("ui_up")) velocity.y -= 1;
velocity = velocity.Normalized() * Speed;
}
}
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20150501Preview.Outputs
{
/// <summary>
/// Specifies the peering config
/// </summary>
[OutputType]
public sealed class ExpressRouteCircuitPeeringConfigResponse
{
/// <summary>
/// Gets or sets the reference of AdvertisedPublicPrefixes
/// </summary>
public readonly ImmutableArray<string> AdvertisedPublicPrefixes;
/// <summary>
/// Gets or sets AdvertisedPublicPrefixState of the Peering resource
/// </summary>
public readonly string? AdvertisedPublicPrefixesState;
/// <summary>
/// Gets or Sets CustomerAsn of the peering.
/// </summary>
public readonly int? CustomerASN;
/// <summary>
/// Gets or Sets RoutingRegistryName of the config.
/// </summary>
public readonly string? RoutingRegistryName;
[OutputConstructor]
private ExpressRouteCircuitPeeringConfigResponse(
ImmutableArray<string> advertisedPublicPrefixes,
string? advertisedPublicPrefixesState,
int? customerASN,
string? routingRegistryName)
{
AdvertisedPublicPrefixes = advertisedPublicPrefixes;
AdvertisedPublicPrefixesState = advertisedPublicPrefixesState;
CustomerASN = customerASN;
RoutingRegistryName = routingRegistryName;
}
}
}
|
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media.Imaging;
using Timotheus.Utility;
namespace Timotheus.Views
{
public partial class Settings : Dialog
{
private string _associationName = string.Empty;
public string AssociationName
{
get
{
return _associationName;
}
set
{
_associationName = value;
NotifyPropertyChanged(nameof(AssociationName));
}
}
private string _associationAddress = string.Empty;
public string AssociationAddress
{
get
{
return _associationAddress;
}
set
{
_associationAddress = value;
NotifyPropertyChanged(nameof(AssociationAddress));
}
}
private string _imagePath = string.Empty;
public string ImagePath
{
get
{
return _imagePath;
}
set
{
_imagePath = value;
if (System.IO.File.Exists(value))
Image = new Bitmap(value);
NotifyPropertyChanged(nameof(ImagePath));
}
}
private Bitmap _image = null;
public Bitmap Image
{
get
{
return _image;
}
set
{
_image = value;
NotifyPropertyChanged(nameof(Image));
}
}
public Settings()
{
DataContext = this;
AvaloniaXamlLoader.Load(this);
}
private async void Browse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new();
FileDialogFilter imgFilter = new();
imgFilter.Extensions.Add("png");
imgFilter.Extensions.Add("jpg");
imgFilter.Name = "Images (.png, .jpg)";
openFileDialog.Filters = new();
openFileDialog.Filters.Add(imgFilter);
string[] result = await openFileDialog.ShowAsync(this);
if (result != null && result.Length > 0)
ImagePath = result[0];
}
private void Ok_Click(object sender, RoutedEventArgs e)
{
DialogResult = DialogResult.OK;
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
} |
namespace GameOfTournaments.Web.Cache.ApplicationUsers
{
using System.Collections.Generic;
using GameOfTournaments.Data.Models;
using GameOfTournaments.Shared;
public class ApplicationUserCacheModel
{
public int Id { get; set; }
public List<PermissionModel> Permissions { get; set; } = new();
// IP checks, browser (client) checks
}
} |
namespace OstoslistaData
{
public class ShopperFriendRequestEntity : BaseShopperFriendEntity
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// ManagerBase 的摘要说明
/// </summary>
public abstract class ManagerBase<T> where T : class, new()
{
public abstract List<T> GetServerList();
/// <summary>
/// 获得该表格的所有数据
/// </summary>
/// <returns></returns>
public abstract IList<T> GetAllUser();
/// <summary>
/// 根据用户名字获得表格的用户名数据,如果用户名是唯一的,那么返回的集合里面只有一个元素
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public abstract IList<T> GetUserByUsername(string username);
/// <summary>
/// 根据站点名称获得表格的用户名数据
/// </summary>
/// <param name="site"></param>
/// <returns></returns>
public abstract IList<T> GetUseBySite(string site);
/// <summary>
/// 保存表格
/// </summary>
/// <param name="user"></param>
public abstract void SaveUser(T user);
/// <summary>
/// 删除表格
/// </summary>
/// <param name="id"></param>
public abstract void DeleteById(int id);
/// <summary>
/// 更新表格数据
/// </summary>
/// <param name="tu"></param>
public abstract void UpdateUser(T tu);
} |
using System;
namespace iGeospatial.Geometries.IO
{
/// <summary>
/// Summary description for GeometryGml3Reader.
/// </summary>
public class GeometryGml3Reader : MarshalByRefObject
{
public GeometryGml3Reader()
{
}
}
}
|
using System;
using System.Xml;
using System.IO;
namespace DigitalPlatform.Xml
{
/*
<?xml version='1.0' encoding='utf-8' ?>
<stringtable>
<s id="1">
<v lang="zh-CN">中文</v>
<v lang="en">Chinese</v>
</s>
<s id="中文id">
<v lang="en">Chinese value</v>
<v lang="zh-CN">中文值</v>
</s>
</stringtable>
*/
/* 后来改为规范的语言表示方法
<stringtable>
<!-- /////////////////////////////////// login ////////////////////////////-->
<s id="用户名">
<v lang="zh-CN">用户名</v>
<v lang="en-us">User name</v>
</s>
<s id="密码">
<v lang="zh-CN">密码</v>
<v lang="en-us">Password</v>
</s>
</stringtable>
*/
/// <summary>
/// 多语种字符串对照
/// </summary>
public class StringTable
{
XmlDocument dom = new XmlDocument();
public string ContainerElementName = "stringtable";
public string CurrentLang = "zh-CN"; // 缺省为中文
public string DefaultValue = "????";
public bool ThrowException = false;
public string ItemElementName = "s";
public string ValueElementName = "v";
public string IdAttributeName = "id";
public StringTable()
{
//
// TODO: Add constructor logic here
//
}
public StringTable(string strFileName)
{
this.dom.PreserveWhitespace = true; //设PreserveWhitespace为true
dom.Load(strFileName);
}
public StringTable(Stream s)
{
dom.Load(s);
}
// 以指定的语言得到或设置字符串
public string this[string strID, string strLang]
{
get
{
return GetString(strID,
strLang,
ThrowException,
this.DefaultValue);
}
set
{
}
}
// 以当前语言得到或者设置字符串
public string this[string strID]
{
get
{
return GetString(strID,
CurrentLang,
ThrowException,
this.DefaultValue);
}
set
{
}
}
// 成对出现的字符串
public string[] GetStrings(string strLang)
{
string xpath = "";
xpath = "//"
+ ContainerElementName
+ "/"+ItemElementName + "/"
+ ValueElementName + "[@lang='" + strLang + "']";
XmlNodeList nodes = dom.DocumentElement.SelectNodes(xpath);
string [] result = new string [nodes.Count*2];
for(int i=0;i<nodes.Count;i++)
{
result[i*2] = DomUtil.GetAttr(nodes[i].ParentNode, "id");
result[i*2 + 1] = DomUtil.GetNodeText(nodes[i]);
}
return result;
}
public string GetString(string strID,
string strLang,
bool bThrowException,
string strDefault)
{
XmlNode node = null;
string xpath = "";
if (strLang == null || strLang == "")
{
xpath = "//"
+ ContainerElementName
+ "/" + ItemElementName + "[@"
+ IdAttributeName + "='" + strID + "']/"
+ ValueElementName;
node = dom.DocumentElement.SelectSingleNode(xpath);
}
else
{
REDO:
xpath = "//"
+ ContainerElementName
+ "/"+ItemElementName +"[@"
+ IdAttributeName + "='" + strID + "']/"
+ ValueElementName + "[@lang='" +strLang + "']";
node = dom.DocumentElement.SelectSingleNode(xpath);
// 任延华加
if (node == null)
{
int nIndex = strLang.IndexOf('-');
if (nIndex != -1)
{
strLang = strLang.Substring(nIndex+1);
goto REDO;
}
}
}
if (node == null)
{
if (bThrowException)
throw(new StringNotFoundException("id为" +strID+ "lang为"+strLang+"的字符串没有找到"));
if (strDefault == "@id")
return strID;
return strDefault;
}
return DomUtil.GetNodeText(node);
}
}
// 字符串在对照表中没有找到
public class StringNotFoundException : Exception
{
public StringNotFoundException (string s) : base(s)
{
}
}
}
|
namespace Nest
{
public interface IChangePasswordResponse : IResponse { }
public class ChangePasswordResponse : ResponseBase, IChangePasswordResponse { }
}
|
using System;
using HL7Models;
using CollectorFormatterSample.Collector;
using CollectorFormatterSample.Formatter;
using CollectorFormatterSample.Translator;
namespace CollectorFormatterSample
{
public class Program
{
static void Main(string[] args)
{
// Collect or Gather Data
var hL7MessageCollector = new HL7MessageCollector();
var hL7MessageRoot = hL7MessageCollector.Collect();
// Translate data
Translate(hL7MessageRoot);
// Format and display as XML
Console.WriteLine("Display HL7 message as XML\n");
var xmlOutput = FormatToXML(hL7MessageRoot);
Console.WriteLine(xmlOutput);
// Format and display as JSON
Console.WriteLine("\nDisplay HL7 message as JSON\n");
var jsonOutput = FormatToJSON(hL7MessageRoot);
Console.WriteLine(jsonOutput);
Console.ReadLine();
}
static string FormatToXML(HL7MessageRoot hL7MessageRoot)
{
var hL7MessageFormatter = new HL7MessageFormatter(hL7MessageRoot);
return hL7MessageFormatter.Format(new HL7XMLFormatter());
}
static string FormatToJSON(HL7MessageRoot hL7MessageRoot)
{
var hL7JSONFormatter = new HL7MessageFormatter(hL7MessageRoot);
return hL7JSONFormatter.Format(new HL7JsonFormatter());
}
static void Translate(HL7MessageRoot hL7MessageRoot)
{
var phoneNumber = hL7MessageRoot.Message.PatientIdentification.PhoneHome;
var phoneNumberTranslator = new PhoneNumberTranslator();
if (!string.IsNullOrEmpty(phoneNumber))
{
hL7MessageRoot.Message.PatientIdentification.PhoneHome = phoneNumberTranslator.Translate(phoneNumber);
}
var ssn = hL7MessageRoot.Message.PatientIdentification.SSN;
var ssnMaskTranslator = new SSNMaskTranslator();
if (!string.IsNullOrEmpty(ssn))
{
hL7MessageRoot.Message.PatientIdentification.SSN = ssnMaskTranslator.Translate(ssn);
}
ssn = hL7MessageRoot.Message.Guarantor.SSN;
if (!string.IsNullOrEmpty(ssn))
{
hL7MessageRoot.Message.Guarantor.SSN = ssnMaskTranslator.Translate(ssn);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace FlightORM.CommonTests
{
public static class Helpers
{
public static Stream GetInputFile(string filename)
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
string path = "FlightORM.CommonTests.TestFiles";
return thisAssembly.GetManifestResourceStream(path + "." + filename);
}
}
}
|
namespace ClassLibraryTvShows
{
public class Rating
{
public double? average { get; set; }
}
}
|
using System.IO;
using Wave.Common;
using Wave.Platform.Messaging;
using Wave.Services;
namespace Wave.Platform
{
public class MapPluginBlockDefinition : BlockDefinition, ICacheable
{
public bool IsZoomEnabled { get; private set; }
public bool IsScrollEnabled { get; private set; }
public bool IsAnimationEnabled { get; private set; }
public bool ShowUserLocation { get; private set; }
public WaveMapMode Mode { get; private set; }
public PaintStyle? Background { get; protected set; }
public MapPluginBlockDefinition()
: base()
{
}
public void Unpack(FieldList source)
{
if (source == null)
return;
UnpackDefinitionID(source);
Background = new PaintStyle(source, DefAgentFieldID.BackgroundPaintStyle);
IsZoomEnabled = source[DefAgentFieldID.MapZoomEnabled].AsBoolean() ?? true;
IsScrollEnabled = source[DefAgentFieldID.MapScrollEnabled].AsBoolean() ?? true;
IsAnimationEnabled = source[DefAgentFieldID.MapAnimationsEnabled].AsBoolean() ?? true;
ShowUserLocation = source[DefAgentFieldID.MapShowUserLocEnabled].AsBoolean() ?? false;
Mode = (WaveMapMode)(source[DefAgentFieldID.MapMode].AsShort() ?? (short)WaveMapMode.Standard);
UnpackBlockHints(source);
// done
IsUnpacked = true;
}
#region ICacheable implementation
public override CacheableType StoredType
{
get { return CacheableType.MapPluginBlockDefinition; }
}
public override void Persist(Stream str)
{
base.Persist(str);
str.WriteByte(0);
// background
str.WriteBool(Background.HasValue);
if (Background.HasValue)
Background.Value.Persist(str);
// other settings
str.WriteBool(IsZoomEnabled);
str.WriteBool(IsScrollEnabled);
str.WriteBool(IsAnimationEnabled);
str.WriteBool(ShowUserLocation);
str.WriteShort((short)Mode);
}
public override void Restore(Stream str)
{
base.Restore(str);
if (str.ReadByte() == 0)
{
// background
if (str.ReadBool())
{
PaintStyle bg = new PaintStyle();
bg.Restore(str);
Background = bg;
}
else
Background = null;
// other settings
IsZoomEnabled = str.ReadBool();
IsScrollEnabled = str.ReadBool();
IsAnimationEnabled = str.ReadBool();
ShowUserLocation = str.ReadBool();
Mode = (WaveMapMode)str.ReadShort();
}
}
#endregion
}
public enum WaveMapMode : short
{
Standard = 1,
Satellite = 2,
Hybrid = 3
}
}
|
using NUnit.Framework;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Linq;
using ExplainPowershell.SyntaxAnalyzer;
using explainpowershell.models;
namespace ExplainPowershell.SyntaxAnalyzer.Tests
{
public class GetParameterSetDataTests
{
private HelpEntity helpItem;
private List<ParameterData> doc;
[SetUp]
public void Setup()
{
var filename = "../../../testfiles/test_get_help.json";
var json = File.ReadAllText(filename);
helpItem = JsonSerializer.Deserialize<HelpEntity>(json);
doc = JsonSerializer.Deserialize<List<ParameterData>>(helpItem.Parameters);
}
[Test]
public void ShouldReadParameterSetDetails()
{
var parameterData = doc[4]; // The -Full parameter
Assert.AreEqual(
Helpers.GetParameterSetData(
parameterData,
helpItem.ParameterSetNames.Split(", ")).FirstOrDefault().ParameterSetName,
"AllUsersView"
);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Controls;
using DotVVM.Framework.ViewModel;
using Newtonsoft.Json;
namespace DotVVM.Samples.BasicSamples.ViewModels.ControlSamples.GridView
{
public class Customer
{
[Bind(Name = "CoolId")]
public int Id { get; set; }
public string Name { get; set; }
public GridViewDataSet<ShoppingCartItem> ShoppingCartItems { get; set; }
}
public class ShoppingCartItem
{
[JsonProperty("CoolItem")]
public string Item { get; set; }
public int Quantity { get; set; }
}
public class NestedGridViewInlineEditingViewModel : DotvvmViewModelBase
{
public GridViewDataSet<Customer> Customers { get; set; } = new GridViewDataSet<Customer>() {
RowEditOptions = { PrimaryKeyPropertyName = "Id" }
};
private static IQueryable<Customer> GetCustomersData()
{
var customers = new List<Customer>()
{
new Customer() { Id = 1, Name = "John Doe" },
new Customer() { Id = 2, Name = "John Deer" },
new Customer() { Id = 3, Name = "Johnny Walker" },
new Customer() { Id = 4, Name = "Jim Hacker" },
new Customer() { Id = 5, Name = "Joe E. Brown" },
};
customers.ForEach(customer => {
customer.ShoppingCartItems = new GridViewDataSet<ShoppingCartItem>() {
RowEditOptions = { PrimaryKeyPropertyName = "Item" }
};
customer.ShoppingCartItems.LoadFromQueryable(GetShoppingCartData());
});
return customers.AsQueryable();
}
private static IQueryable<ShoppingCartItem> GetShoppingCartData()
{
var shoppingCartItems = new List<ShoppingCartItem>()
{
new ShoppingCartItem() { Item = "Apple", Quantity = 3 },
new ShoppingCartItem() { Item = "Orange", Quantity = 11 },
};
return shoppingCartItems.AsQueryable();
}
public override async Task PreRender()
{
if (!Context.IsPostBack)
{
Customers.LoadFromQueryable(GetCustomersData());
}
await base.PreRender();
}
public void EditShoppingCart(Customer customer, ShoppingCartItem item)
{
//var student = Students.Items.Where(x => x.Grades.Items.Any(y => y.GradeId == grade.GradeId)).First();
customer.ShoppingCartItems.RowEditOptions.EditRowId = item.Item;
}
public void UpdateShoppingCart(Customer customer, ShoppingCartItem item)
{
customer.ShoppingCartItems.RowEditOptions.EditRowId = null;
}
public void CancelEditShoppingCart()
{
Customers.RequestRefresh();
}
public void EditCustomer(Customer customer)
{
Customers.RowEditOptions.EditRowId = customer.Id;
}
public void UpdateCustomer(Customer customer)
{
Customers.RowEditOptions.EditRowId = null;
}
public void CancelEditCustomer()
{
Customers.RowEditOptions.EditRowId = null;
Customers.RequestRefresh();
}
}
}
|
namespace GildedRoseInn.Items
{
public sealed class SulfurasItem : AbstractItem
{
#region Public Constructor
public SulfurasItem() : base("Sulfuras, Hand of Ragnaros", 0, 80, isSpeical: true)
{
}
#endregion
/*- "Sulfuras", being a legendary item, never has to be sold or decreases in Quality
- however "Sulfuras" is a legendary item and as such its Quality is 80 and it never alters.
- (Quality==80, SellIn==0)
*/
#region Protected Override Methods
protected override void UpdateSellIn()
{
//do nothing.
}
protected override void UpdateQuality()
{
//do nothing.
}
protected override void CheckQualityRange()
{
//Quality == 80
//do nothing == no check.
}
#endregion
}
} |
@using QuickStartTemplate
@using Karambolo.AspNetCore.Bundling.ViewHelpers
@namespace QuickStartTemplate.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Karambolo.AspNetCore.Bundling
|
using System;
#nullable enable
namespace EventStore.Client {
/// <summary>
/// Exception thrown when an append exceeds the maximum size set by the server.
/// </summary>
public class MaximumAppendSizeExceededException : Exception {
/// <summary>
/// The configured maximum append size.
/// </summary>
public uint MaxAppendSize { get; }
/// <summary>
/// Constructs a new <see cref="MaximumAppendSizeExceededException"/>.
/// </summary>
/// <param name="maxAppendSize"></param>
/// <param name="innerException"></param>
public MaximumAppendSizeExceededException(uint maxAppendSize, Exception? innerException = null) :
base($"Maximum Append Size of {maxAppendSize} Exceeded.", innerException) {
MaxAppendSize = maxAppendSize;
}
/// <summary>
/// Constructs a new <see cref="MaximumAppendSizeExceededException"/>.
/// </summary>
/// <param name="maxAppendSize"></param>
/// <param name="innerException"></param>
public MaximumAppendSizeExceededException(int maxAppendSize, Exception? innerException = null) : this(
(uint)maxAppendSize, innerException) {
}
}
}
|
using System;
namespace QuickNetChat.View.SplashScreen.Exceptions
{
public class SplashScreenProgressException : Exception
{
public SplashScreenProgressException(string message) : base(CustomExceptionMessage(message))
{
}
private static string CustomExceptionMessage(string message)
{
return $"SplashScreen progress - {message}";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using System.Runtime.InteropServices;
using System.Threading;
using System;
public class SSPStreamingThread : MonoBehaviour
{
[DllImport("__Internal")]
public static extern int ssp_server(
[MarshalAs(UnmanagedType.LPStr)]string filename);
[DllImport("__Internal")]
public static extern void use_session(IntPtr session);
private Thread serverThread;
private string file_location;
public ARSession arSession;
private bool hasntLaunched = true;
// Start is called before the first frame update
void Start()
{
}
void RunServer()
{
Debug.Log("attempting to grab session");
System.IntPtr session = (arSession.subsystem.nativePtr);
use_session(session);
Debug.Log(file_location);
ssp_server(file_location);
}
// Update is called once per frame
void Update()
{
if (hasntLaunched)
{
file_location = Application.dataPath + "/Raw/serve_ios_raw.yaml";
//We create our new thread that be running the method "ListenForMessages"
serverThread = new Thread(() => RunServer());
//We configure the thread we just created
serverThread.IsBackground = true;
//We note that it is running so we don't forget to turn it off
// threadRunning = true;
//Now we start the thread
serverThread.Start();
hasntLaunched = false;
}
}
void OnDestroy()
{
serverThread.Abort();
}
}
|
using System;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Windows.Forms;
using Uno.Diagnostics;
using Uno.Platform.Internal;
using Uno.AppLoader.WinForms;
namespace Uno.AppLoader
{
public partial class MainForm : Form, IUnoWindow
{
FormWindowState _state = FormWindowState.Normal;
FormBorderStyle _style = FormBorderStyle.Sizable;
readonly UnoGLControl _control = new UnoGLControl();
public MainForm(Action initializeApp)
{
InitializeComponent();
Controls.Add(_control);
_control.Initialize(this);
var dpi = DpiAwareness.GetDpi(Handle);
_control.SetDensity((float)dpi);
ClientSize = new Size((int)(375*dpi), (int)(667*dpi));
FormClosing += (sender, e) => e.Cancel = _control.OnClosing();
FormClosed += (sender, e) => _control.OnClosed();
Title = GetAssemblyTitle();
initializeApp();
DotNetApplication.Start();
}
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(Environment.GetEnvironmentVariable("UNO_WINDOW_HIDDEN") != "1" && value);
}
string GetAssemblyTitle()
{
return (string) typeof(MainForm).Assembly.CustomAttributes
.First(a => a.AttributeType.Name == "AssemblyTitleAttribute")
.ConstructorArguments.First().Value;
}
public void MainLoop()
{
var context = new ApplicationContext(this);
context.MainForm.Visible = true;
var openAdapter = new D3DKMT_OPENADAPTERFROMHDC();
var waitForVblankEvent = new D3DKMT_WAITFORVERTICALBLANKEVENT();
openAdapter.hDc = CreateDC(Screen.PrimaryScreen.DeviceName, null, null, IntPtr.Zero);
bool useD3DKMT = false;
double targetTime = 1.0 / 60;
if (D3DKMTOpenAdapterFromHdc(ref openAdapter) == 0)
{
useD3DKMT = true;
waitForVblankEvent.hAdapter = openAdapter.hAdapter;
waitForVblankEvent.hDevice = 0;
waitForVblankEvent.VidPnSourceId = openAdapter.VidPnSourceId;
}
else
{
var mode = new DEVMODE();
if (EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref mode) && mode.dmBitsPerPel > 0)
targetTime = 1.0 / mode.dmDisplayFrequency;
}
while (!IsDisposed)
{
var msg = new MSG();
while (PeekMessage(ref msg, IntPtr.Zero, 0, 0, 0x0001 /*PM_REMOVE*/))
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
if (useD3DKMT)
{
D3DKMTWaitForVerticalBlankEvent(ref waitForVblankEvent);
if (!_control.OnRender())
return;
}
else
{
var startTime = Clock.GetSeconds();
if (!_control.OnRender())
return;
var renderTime = Clock.GetSeconds() - startTime;
var msTimeout = (int)((targetTime - renderTime) * 1000.0 + 0.5);
if (msTimeout > 0)
Thread.Sleep(msTimeout);
}
}
}
public string Title
{
get { return Text; }
set { Text = value; }
}
public bool IsFullscreen
{
get
{
return FormBorderStyle == FormBorderStyle.None;
}
set
{
if (value != IsFullscreen)
{
if (value)
{
_style = FormBorderStyle;
_state = WindowState;
WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
else
{
FormBorderStyle = _style;
WindowState = _state;
}
}
}
}
public void SetClientSize(int width, int height)
{
ClientSize = new Size(width, height);
}
[DllImport("gdi32.dll")]
static extern IntPtr CreateDC(string strDriver, string strDevice, string strOutput, IntPtr pData);
[DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
public struct D3DKMT_OPENADAPTERFROMHDC
{
public IntPtr hDc;
public uint hAdapter;
public uint AdapterLuidLowPart;
public uint AdapterLuidHighPart;
public uint VidPnSourceId;
}
[DllImport("gdi32.dll")]
public static extern uint D3DKMTOpenAdapterFromHdc(ref D3DKMT_OPENADAPTERFROMHDC pData);
public struct D3DKMT_WAITFORVERTICALBLANKEVENT
{
public uint hAdapter;
public uint hDevice;
public uint VidPnSourceId;
}
[DllImport("gdi32.dll")]
public static extern uint D3DKMTWaitForVerticalBlankEvent(ref D3DKMT_WAITFORVERTICALBLANKEVENT pData);
[SuppressUnmanagedCodeSecurity]
[DllImport("user32.dll")]
public static extern bool PeekMessage(ref MSG msg, IntPtr hWnd, int messageFilterMin, int messageFilterMax, int flags);
[SuppressUnmanagedCodeSecurity]
[DllImport("user32.dll")]
public static extern bool TranslateMessage(ref MSG msg);
[SuppressUnmanagedCodeSecurity]
[DllImport("user32.dll")]
public static extern bool DispatchMessage(ref MSG msg);
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);
const int ENUM_CURRENT_SETTINGS = -1;
public struct MSG
{
public IntPtr HWnd;
public uint Message;
public IntPtr WParam;
public IntPtr LParam;
public uint Time;
public POINT Point;
}
}
}
|
using System;
using System.ComponentModel;
using System.Resources;
namespace ClaudiaIDE.Localized
{
internal class LocalManager
{
internal static ResourceManager _rm = null;
private static ResourceManager GetInstance()
{
if (_rm == null)
{
_rm = ResLocalized.ResourceManager;
}
return _rm;
}
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Module |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Property |
AttributeTargets.Field |
AttributeTargets.Event |
AttributeTargets.Interface |
AttributeTargets.Parameter |
AttributeTargets.Delegate |
AttributeTargets.ReturnValue |
AttributeTargets.GenericParameter)]
internal class LocalizedDescriptionAttribute : DescriptionAttribute
{
private static string Localize(string _key)
{
return GetInstance().GetString(_key);
}
internal LocalizedDescriptionAttribute(string _key) : base(Localize(_key))
{
}
}
[AttributeUsage(AttributeTargets.All)]
internal class LocalizedCategoryAttribute : CategoryAttribute
{
private static string Localize(string _key)
{
return GetInstance().GetString(_key);
}
internal LocalizedCategoryAttribute(string _key) : base(Localize(_key))
{
}
}
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Method |
AttributeTargets.Property |
AttributeTargets.Event)]
internal class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private static string Localize(string _key)
{
return GetInstance().GetString(_key);
}
internal LocalizedDisplayNameAttribute(string _key) : base(Localize(_key))
{
}
}
}
} |
using CodingArena.AI;
using CodingArena.Annotations;
using CodingArena.Common;
using CodingArena.Main.Battlefields.Bots;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace CodingArena.Main.Battlefields.Bullets
{
public class Bullet : Movable, IBullet
{
private static readonly Random myRandom = new Random();
public Bullet(
[NotNull] Battlefield battlefield,
[NotNull] IBot shooter,
double speed,
double damage,
double maxBulletDistance) : base(battlefield)
{
Radius = 3;
Shooter = shooter ?? throw new ArgumentNullException(nameof(shooter));
Direction = CalculateDirection();
Speed = speed;
Damage = damage;
var weaponX = Shooter.Position.X + 30 * Math.Cos(Shooter.Angle * Math.PI / 180);
var weaponY = Shooter.Position.Y + 30 * Math.Sin(Shooter.Angle * Math.PI / 180);
Position = new Point(weaponX, weaponY);
MaxDistance = maxBulletDistance;
}
private Vector CalculateDirection()
{
var angle = Shooter.Angle;
var accuracy = Shooter.EquippedWeapon.Accuracy;
var angleDif = (360 - 360 * accuracy / 100) / 2;
angleDif = myRandom.NextDouble() * angleDif;
var newAngle = myRandom.Next(2) == 1 ? angle - angleDif : angle + angleDif;
return new Vector(Math.Cos(newAngle * Math.PI / 180), Math.Sin(newAngle * Math.PI / 180));
}
public IBot Shooter { get; }
public double Damage { get; }
public double Distance { get; private set; }
public double MaxDistance { get; }
public override async Task UpdateAsync()
{
await base.UpdateAsync();
Move();
}
public virtual void Move()
{
var movement = GetMovement();
var afterMove = GetAfterMove(movement);
if (IsOutOfBattlefield(afterMove) && OnOutOfBattlefield())
{
return;
}
Distance += movement.Length;
if (IsMaxDistanceReached() && OnMaxDistanceReached())
{
return;
}
var damageBots = GetDamageBots(afterMove);
if (damageBots.Any() && OnCollisionWith(damageBots))
{
return;
}
OnMoved(afterMove);
OnChanged();
}
protected virtual void OnMoved(Bullet afterMove) =>
Position = new Point(afterMove.Position.X, afterMove.Position.Y);
protected virtual List<Bot> GetDamageBots(Bullet afterMove) =>
Battlefield.Bots.Except(new[] { Shooter }).OfType<Bot>()
.Where(bot => bot.IsInCollisionWith(afterMove)).ToList();
protected virtual bool OnCollisionWith(List<Bot> bots)
{
bots.ForEach(bot => bot.TakeDamageFrom(this));
OnChanged();
Battlefield.Remove(this);
return true;
}
protected virtual bool OnMaxDistanceReached()
{
Battlefield.Remove(this);
return true;
}
protected virtual bool IsMaxDistanceReached() => Distance > MaxDistance;
protected virtual bool OnOutOfBattlefield()
{
Battlefield.Remove(this);
return true;
}
protected virtual bool IsOutOfBattlefield(Bullet afterMove) =>
afterMove.Position.X > Battlefield.Width - 1 ||
afterMove.Position.X < 0 ||
afterMove.Position.Y > Battlefield.Height - 1 ||
afterMove.Position.Y < 0;
protected virtual Bullet GetAfterMove(Vector movement) =>
new Bullet(Battlefield, Shooter, Speed, Damage, MaxDistance)
{
Position = new Point(Position.X + movement.X, Position.Y + movement.Y),
Radius = Radius
};
protected virtual Vector GetMovement()
{
var movement = new Vector(Direction.X, Direction.Y);
movement.X *= Speed * DeltaTime.TotalSeconds;
movement.Y *= Speed * DeltaTime.TotalSeconds;
return movement;
}
}
} |
namespace KafkaFlow.Serializer
{
using System;
using KafkaFlow.Dependency;
/// <summary>
/// The default implementation of <see cref="IMessageTypeResolver"/>
/// </summary>
public class DefaultMessageTypeResolver : IMessageTypeResolver
{
private const string MessageType = "Message-Type";
/// <summary>
/// Get the message type when consuming
/// </summary>
/// <param name="context">The message context</param>
/// <returns></returns>
public Type OnConsume(IMessageContext context)
{
var typeName = context.Headers.GetString(MessageType);
return Type.GetType(typeName);
}
/// <summary>
/// Fills the type metadata when producing
/// </summary>
/// <param name="context"></param>
public void OnProduce(IMessageContext context)
{
if (context.Message is null)
{
return;
}
context.Headers.SetString(
MessageType,
$"{context.Message.GetType().FullName}, {context.Message.GetType().Assembly.GetName().Name}");
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static async Task VerifyCSharpAnalyzerAsync(
ReferenceAssemblies referenceAssemblies,
string source,
params DiagnosticResult[] expected)
{
var csharpTest = new VerifyCS.Test
{
ReferenceAssemblies = referenceAssemblies,
TestState =
{
Sources = { source },
}
};
csharpTest.ExpectedDiagnostics.AddRange(expected);
await csharpTest.RunAsync();
}
private static async Task VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies referenceAssemblies,
string source,
params DiagnosticResult[] expected)
{
var visualBasicTest = new VerifyVB.Test
{
ReferenceAssemblies = referenceAssemblies,
TestState =
{
Sources = { source },
}
};
visualBasicTest.ExpectedDiagnostics.AddRange(expected);
await visualBasicTest.RunAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeadManSwitch.Data
{
/// <summary>
/// Repository for simple reference data information
/// that had an Id and a description.
/// </summary>
/// <remarks>
/// This breaks the Single Responsiblity Principle,
/// but this is a small app, so I'm purposely breaking
/// the rule to simplify things.
/// </remarks>
public interface IReferenceDataRepository
{
/// <summary>
/// Retrieves all escalation action types.
/// </summary>
/// <returns></returns>
Dictionary<int, string> EscalationActionTypes();
Dictionary<int, string> EarlyCheckInOptions();
Dictionary<int, string> EscalationDelayMinuteOptions();
Dictionary<int, string> CheckInHourOptions();
Dictionary<int, string> CheckInMinuteOptions();
Dictionary<string, string> CheckInAmPmOptions();
}
}
|
// Copyright (c) 2019 SceneGate
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace SceneGate.Lemon.Containers.Converters
{
using System;
using SceneGate.Lemon.Containers.Converters.Ivfc;
using Yarhl.FileFormat;
using Yarhl.FileSystem;
using Yarhl.IO;
/// <summary>
/// Converter for Binary streams into a file system following the
/// IVFC tree format.
/// </summary>
/// <remarks>
/// <para>The binary IVFC format consists in the following sections:</para>
/// * IVFC Header
/// * Level 0
/// * Level 3
/// |--* File system header
/// |--* Directories hash
/// |--* Directories info
/// |--* Files hash
/// |--* Files info
/// |--* File data
/// * Level 1
/// * Level 2.
/// <para>Level 0, 1 and 2 only contain SHA-256 hashes of the upper layer.
/// Level 3 contains the file system metadata and file data.</para>
/// </remarks>
public class NodeContainer2BinaryIvfc :
IInitializer<DataStream>,
IConverter<NodeContainerFormat, BinaryFormat>
{
const int BlockSizeLog = 0x0C;
const int BlockSize = 1 << BlockSizeLog;
DataStream stream;
/// <summary>
/// Gets the magic identifier of the format.
/// </summary>
/// <value>The magic ID of the format.</value>
public static string MagicId {
get { return "IVFC"; }
}
/// <summary>
/// Gets the format version.
/// </summary>
/// <value>The format version.</value>
public static uint Version {
get { return 0x0001_0000; }
}
/// <summary>
/// Initialize the converter by providing the stream to write to.
/// </summary>
/// <param name="parameters">Stream to write to.</param>
public void Initialize(DataStream parameters)
{
this.stream = parameters;
}
/// <summary>
/// Converts a file system into a memory binary stream with IVFC format.
/// </summary>
/// <param name="source">The node file system to convert.</param>
/// <returns>The memory binary stream with IVFC format.</returns>
public BinaryFormat Convert(NodeContainerFormat source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var binary = (stream != null) ? new BinaryFormat(stream) : new BinaryFormat();
var writer = new DataWriter(binary.Stream);
// Analyze the file system to pre-calculate the sizes.
// As said, Level 3 contains the whole file system,
// the other level just contain SHA-256 hashes of every block
// from the lower layer. So we get the number of blocks
// (number of hashes) and multiple by the hash size.
var fsWriter = new FileSystemWriter(source.Root);
const int LevelHashSize = 0x20; // SHA-256 size
long[] levelSizes = new long[4];
levelSizes[3] = fsWriter.Size;
levelSizes[2] = (levelSizes[3].Pad(BlockSize) / BlockSize) * LevelHashSize;
levelSizes[1] = (levelSizes[2].Pad(BlockSize) / BlockSize) * LevelHashSize;
levelSizes[0] = (levelSizes[1].Pad(BlockSize) / BlockSize) * LevelHashSize;
WriteHeader(writer, levelSizes);
writer.WritePadding(0x00, 0x10);
long level0DataOffset = binary.Stream.Position;
writer.WriteTimes(0x00, levelSizes[0]); // pre-allocate
writer.WritePadding(0x00, BlockSize);
long level3Offset = binary.Stream.Position;
// Increase the base length so we can create a substream of the correct size
// This operation doesn't write and it returns almost immediately,
// the write happens on the first byte written on the new file space.
long level3Padded = levelSizes[3].Pad(BlockSize);
binary.Stream.BaseStream.SetLength(binary.Stream.BaseStream.Length + level3Padded);
binary.Stream.SetLength(binary.Stream.Length + level3Padded);
// Create "special" data streams that will create hashes on-the-fly.
using (var level1 = new LevelStream(BlockSize))
using (var level2 = new LevelStream(BlockSize))
using (var level3 = new LevelStream(BlockSize, binary.Stream.BaseStream))
using (var level0Stream = new DataStream(binary.Stream, level0DataOffset, levelSizes[0]))
using (var level1Stream = new DataStream(level1))
using (var level2Stream = new DataStream(level2))
using (var level3Stream = new DataStream(level3, level3Offset, level3Padded, true)) {
level3.BlockWritten += (_, e) => level2Stream.Write(e.Hash, 0, e.Hash.Length);
level2.BlockWritten += (_, e) => level1Stream.Write(e.Hash, 0, e.Hash.Length);
level1.BlockWritten += (_, e) => level0Stream.Write(e.Hash, 0, e.Hash.Length);
fsWriter.Write(level3Stream);
// Pad remaining block size in order.
new DataWriter(level3Stream).WritePadding(0x00, BlockSize);
new DataWriter(level2Stream).WritePadding(0x00, BlockSize);
new DataWriter(level1Stream).WritePadding(0x00, BlockSize);
// Write streams in order.
binary.Stream.Position = binary.Stream.Length;
level1Stream.WriteTo(binary.Stream);
level2Stream.WriteTo(binary.Stream);
}
return binary;
}
static void WriteHeader(DataWriter writer, long[] sizes)
{
const uint HeaderSize = 0x5C;
// Calculate the "logical" offset.
// This does not reflect the offset in the actual file,
// but how it would be if the layers were in order.
long level1LogicalOffset = 0x00; // first level
long level2LogicalOffset = level1LogicalOffset + sizes[1].Pad(BlockSize);
long level3LogicalOffset = level2LogicalOffset + sizes[2].Pad(BlockSize);
writer.Write(MagicId, nullTerminator: false);
writer.Write(Version);
writer.Write((int)sizes[0]);
writer.Write(level1LogicalOffset);
writer.Write(sizes[1]);
writer.Write(BlockSizeLog);
writer.Write(0x00); // reserved
writer.Write(level2LogicalOffset);
writer.Write(sizes[2]);
writer.Write(BlockSizeLog);
writer.Write(0x00); // reserved
writer.Write(level3LogicalOffset);
writer.Write(sizes[3]);
writer.Write(BlockSizeLog);
writer.Write(0x00); // reserved
writer.Write(HeaderSize);
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OCM.API.Common.Model;
using OCM.API.Common.Model.Extended;
using OCM.Core.Settings;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
namespace OCM.API.Common
{
[Serializable]
public class LatLon
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public static LatLon Parse(string val)
{
var temp = val.ToString().Trim();
if (temp.StartsWith(",")) temp = temp.Substring(1, temp.Length - 1).Trim();
var fragments = temp.Split(',');
var ll = new LatLon
{
Latitude = double.Parse(fragments[0].Substring(1, fragments[0].Length - 1)),
Longitude = double.Parse(fragments[1])
};
if (ll.Latitude < -90) ll.Latitude = -90;
if (ll.Latitude > 90) ll.Latitude = 90;
if (ll.Longitude < -180) ll.Longitude = -180;
if (ll.Longitude > 180) ll.Longitude = 180;
return ll;
}
}
[Serializable]
public class LocationLookupResult : LatLon
{
public string IP { get; set; }
public string Country_Code { get; set; }
public string Country_Name { get; set; }
public string Region_Code { get; set; }
public string Region_Name { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
public bool SuccessfulLookup { get; set; }
public int? CountryID { get; set; }
public int? LocationID { get; set; }
}
public class LocationImage
{
public string ImageRepositoryID { get; set; }
public string ImageID { get; set; }
public string Title { get; set; }
public string Submitter { get; set; }
public string SubmitterURL { get; set; }
public string DetailsURL { get; set; }
public string ImageURL { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public class GeocodingHelper
{
public bool IncludeExtendedData { get; set; }
public bool IncludeQueryURL { get; set; }
private CoreSettings _settings;
public GeocodingHelper(CoreSettings settings)
{
_settings = settings;
}
/* public GeocodingResult GeolocateAddressInfo_Google(AddressInfo address)
{
var result = GeolocateAddressInfo_Google(address.ToString());
result.AddressInfoID = address.ID;
return result;
}*/
public GeocodingResult GeolocateAddressInfo_MapquestOSM(AddressInfo address)
{
var result = GeolocateAddressInfo_MapquestOSM(address.ToString());
result.AddressInfoID = address.ID;
return result;
}
public GeocodingResult ReverseGecode_MapquestOSM(double latitude, double longitude, ReferenceDataManager refDataManager)
{
GeocodingResult result = new GeocodingResult();
result.Service = "MapQuest Open";
string url = "http://open.mapquestapi.com/geocoding/v1/reverse?location=" + latitude + "," + longitude + "&key=" + _settings.ApiKeys.MapQuestOpenAPIKey;
if (IncludeQueryURL) result.QueryURL = url;
string data = "";
try
{
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
client.Encoding = Encoding.GetEncoding("UTF-8");
data = client.DownloadString(url);
if (IncludeExtendedData)
{
result.ExtendedData = data;
}
else
{
System.Diagnostics.Debug.WriteLine(data);
}
if (data == "[]")
{
System.Diagnostics.Debug.WriteLine("No geocoding results:" + url);
result.ResultsAvailable = false;
}
else
{
JObject o = JObject.Parse(data);
var locations = o["results"][0]["locations"];
if (locations.Any())
{
var item = o["results"][0]["locations"][0];
result.AddressInfo = new AddressInfo();
result.AddressInfo.Title = item["street"]?.ToString();
result.AddressInfo.Postcode = item["postalCode"]?.ToString();
result.AddressInfo.AddressLine1 = item["street"]?.ToString();
if (item["adminArea5Type"]?.ToString() == "City")
{
result.AddressInfo.Town = item["adminArea5"]?.ToString();
}
if (item["adminArea3Type"]?.ToString() == "State")
{
result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString();
}
if (item["adminArea3Type"]?.ToString() == "State")
{
result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString();
}
if (item["adminArea1Type"]?.ToString() == "Country")
{
var countryCode = item["adminArea1"]?.ToString();
var country = refDataManager.GetCountryByISO(countryCode);
if (country != null)
{
result.AddressInfo.CountryID = country.ID;
}
}
result.Latitude = latitude;
result.Longitude = longitude;
result.Attribution = "Portions © OpenStreetMap contributors"; // using mapquest open so results are from OSM
result.AddressInfo.Latitude = latitude;
result.AddressInfo.Longitude = longitude;
result.ResultsAvailable = true;
}
else
{
result.ResultsAvailable = false;
}
}
}
catch (Exception)
{
//
}
return result;
}
public GeocodingResult GeolocateAddressInfo_MapquestOSM(string address)
{
GeocodingResult result = new GeocodingResult();
result.Service = "MapQuest Open";
string url = "https://open.mapquestapi.com/geocoding/v1/address?key=" + _settings.ApiKeys.MapQuestOpenAPIKey + "&location=" + Uri.EscapeDataString(address.ToString());
if (IncludeQueryURL) result.QueryURL = url;
string data = "";
try
{
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
client.Encoding = Encoding.GetEncoding("UTF-8");
data = client.DownloadString(url);
if (IncludeExtendedData) result.ExtendedData = data;
if (data == "[]")
{
System.Diagnostics.Debug.WriteLine("No geocoding results:" + url);
result.ResultsAvailable = false;
}
else
{
JObject o = JObject.Parse(data);
var locations = o["results"][0]["locations"];
if (locations.Any())
{
var item = o["results"][0]["locations"][0]["latLng"];
result.Latitude = double.Parse(item["lat"].ToString());
result.Longitude = double.Parse(item["lng"].ToString());
result.ResultsAvailable = true;
}
else
{
result.ResultsAvailable = false;
}
}
}
catch (Exception)
{
//
}
return result;
}
public GeocodingResult ReverseGecode_OSM(double latitude, double longitude, ReferenceDataManager refDataManager)
{
GeocodingResult result = new GeocodingResult();
result.Service = "Nominatim OSM";
string url = $"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude}&lon={longitude}&zoom=18&addressdetails=1";
if (IncludeQueryURL) result.QueryURL = url;
string data = "";
try
{
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
client.Encoding = Encoding.GetEncoding("UTF-8");
data = client.DownloadString(url);
/* e.g.:
{
"place_id": 101131804,
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_type": "way",
"osm_id": 61267076,
"lat": "-32.1685328505288",
"lon": "115.9882328723638",
"display_name": "Eleventh Road, Haynes, Armadale, Western Australia, 6112, Australia",
"address": {
"road": "Eleventh Road",
"suburb": "Haynes",
"town": "Armadale",
"state": "Western Australia",
"postcode": "6112",
"country": "Australia",
"country_code": "au"
},
"boundingbox": [
"-32.1689883",
"-32.1619497",
"115.9805577",
"115.9887699"
]
}
* */
if (IncludeExtendedData)
{
result.ExtendedData = data;
}
else
{
System.Diagnostics.Debug.WriteLine(data);
}
if (data == "{}")
{
System.Diagnostics.Debug.WriteLine("No geocoding results:" + url);
result.ResultsAvailable = false;
}
else
{
JObject o = JObject.Parse(data);
var item = o["address"];
result.AddressInfo = new AddressInfo();
result.AddressInfo.Title = item["road"]?.ToString();
result.AddressInfo.Postcode = item["postcode"]?.ToString();
result.AddressInfo.AddressLine1 = item["road"]?.ToString();
result.AddressInfo.AddressLine2 = item["suburb"]?.ToString();
result.AddressInfo.Town = item["town"]?.ToString();
result.AddressInfo.StateOrProvince = item["state"]?.ToString();
var countryCode = item["country_code"]?.ToString();
var country = refDataManager.GetCountryByISO(countryCode);
if (country != null)
{
result.AddressInfo.CountryID = country.ID;
}
result.Latitude = latitude;
result.Longitude = longitude;
result.Attribution = "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright";
result.AddressInfo.Latitude = latitude;
result.AddressInfo.Longitude = longitude;
result.ResultsAvailable = true;
}
}
catch (Exception)
{
//
}
return result;
}
public GeocodingResult GeolocateAddressInfo_OSM(AddressInfo address)
{
var result = GeolocateAddressInfo_OSM(address.ToString());
result.AddressInfoID = address.ID;
return result;
}
public GeocodingResult GeolocateAddressInfo_OSM(string address)
{
GeocodingResult result = new GeocodingResult();
result.Service = "OSM Nominatim";
if (String.IsNullOrWhiteSpace(address))
{
result.ResultsAvailable = false;
}
else
{
string url = "https://nominatim.openstreetmap.org/search?q=" + address.ToString() + "&format=json&polygon=0&addressdetails=1&email=" + _settings.ApiKeys.OSMApiKey;
if (IncludeQueryURL) result.QueryURL = url;
string data = "";
try
{
//enforce rate limiting
System.Threading.Thread.Sleep(1000);
//make api request
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
client.Encoding = Encoding.GetEncoding("UTF-8");
data = client.DownloadString(url);
if (IncludeExtendedData) result.ExtendedData = data;
if (data == "[]")
{
result.ResultsAvailable = false;
}
else
{
JArray o = JArray.Parse(data);
result.Latitude = double.Parse(o.First["lat"].ToString());
result.Longitude = double.Parse(o.First["lon"].ToString());
result.Attribution = o.First["licence"].ToString();
result.ResultsAvailable = true;
}
}
catch (Exception)
{
//oops
}
}
return result;
}
public static LocationLookupResult GetLocationFromIP_FreegeoIP(string ipAddress)
{
if (!ipAddress.StartsWith("::"))
{
try
{
WebClient url = new WebClient();
//http://freegeoip.net/json/{ip}
string urlString = "https://freegeoip.net/json/" + ipAddress;
string result = url.DownloadString(urlString);
LocationLookupResult lookup = JsonConvert.DeserializeObject<LocationLookupResult>(result);
lookup.SuccessfulLookup = true;
/* -- example result:
{
"ip":"116.240.210.146",
"country_code":"AU",
"country_name":"Australia",
"region_code":"08",
"region_name":"Western Australia",
"city":"Perth",
"zipcode":"",
"latitude":-31.9522,
"longitude":115.8614,
"metro_code":"",
"area_code":""
}
*/
return lookup;
}
catch (Exception)
{
; ;//failed
}
}
return new LocationLookupResult { SuccessfulLookup = false };
}
}
} |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Profiler
{
/// <summary>
/// Coverage data for a source range.
/// </summary>
[SupportedBy("Chrome")]
public class CoverageRange
{
/// <summary>
/// Gets or sets JavaScript script source offset for the range start.
/// </summary>
public long StartOffset { get; set; }
/// <summary>
/// Gets or sets JavaScript script source offset for the range end.
/// </summary>
public long EndOffset { get; set; }
/// <summary>
/// Gets or sets Collected execution count of the source range.
/// </summary>
public long Count { get; set; }
}
}
|
//---------------------------------------------------------------------
// <copyright file="DbExpressionVisitor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner Microsoft
// @backupOwner Microsoft
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Metadata.Edm;
namespace System.Data.Common.CommandTrees
{
/// <summary>
/// The expression visitor pattern abstract base class that should be implemented by visitors that do not return a result value.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Db")]
public abstract class DbExpressionVisitor
{
/// <summary>
/// Called when an expression of an otherwise unrecognized type is encountered.
/// </summary>
/// <param name="expression">The expression</param>
public abstract void Visit(DbExpression expression);
/// <summary>
/// Visitor pattern method for DbAndExpression.
/// </summary>
/// <param name="expression">The DbAndExpression that is being visited.</param>
public abstract void Visit(DbAndExpression expression);
/// <summary>
/// Visitor pattern method for DbApplyExpression.
/// </summary>
/// <param name="expression">The DbApplyExpression that is being visited.</param>
public abstract void Visit(DbApplyExpression expression);
/// <summary>
/// Visitor pattern method for DbArithmeticExpression.
/// </summary>
/// <param name="expression">The DbArithmeticExpression that is being visited.</param>
public abstract void Visit(DbArithmeticExpression expression);
/// <summary>
/// Visitor pattern method for DbCaseExpression.
/// </summary>
/// <param name="expression">The DbCaseExpression that is being visited.</param>
public abstract void Visit(DbCaseExpression expression);
/// <summary>
/// Visitor pattern method for DbCastExpression.
/// </summary>
/// <param name="expression">The DbCastExpression that is being visited.</param>
public abstract void Visit(DbCastExpression expression);
/// <summary>
/// Visitor pattern method for DbComparisonExpression.
/// </summary>
/// <param name="expression">The DbComparisonExpression that is being visited.</param>
public abstract void Visit(DbComparisonExpression expression);
/// <summary>
/// Visitor pattern method for DbConstantExpression.
/// </summary>
/// <param name="expression">The DbConstantExpression that is being visited.</param>
public abstract void Visit(DbConstantExpression expression);
/// <summary>
/// Visitor pattern method for DbCrossJoinExpression.
/// </summary>
/// <param name="expression">The DbCrossJoinExpression that is being visited.</param>
public abstract void Visit(DbCrossJoinExpression expression);
/// <summary>
/// Visitor pattern method for DbDerefExpression.
/// </summary>
/// <param name="expression">The DbDerefExpression that is being visited.</param>
public abstract void Visit(DbDerefExpression expression);
/// <summary>
/// Visitor pattern method for DbDistinctExpression.
/// </summary>
/// <param name="expression">The DbDistinctExpression that is being visited.</param>
public abstract void Visit(DbDistinctExpression expression);
/// <summary>
/// Visitor pattern method for DbElementExpression.
/// </summary>
/// <param name="expression">The DbElementExpression that is being visited.</param>
public abstract void Visit(DbElementExpression expression);
/// <summary>
/// Visitor pattern method for DbExceptExpression.
/// </summary>
/// <param name="expression">The DbExceptExpression that is being visited.</param>
public abstract void Visit(DbExceptExpression expression);
/// <summary>
/// Visitor pattern method for DbFilterExpression.
/// </summary>
/// <param name="expression">The DbFilterExpression that is being visited.</param>
public abstract void Visit(DbFilterExpression expression);
/// <summary>
/// Visitor pattern method for DbFunctionExpression
/// </summary>
/// <param name="expression">The DbFunctionExpression that is being visited.</param>
public abstract void Visit(DbFunctionExpression expression);
/// <summary>
/// Visitor pattern method for DbEntityRefExpression.
/// </summary>
/// <param name="expression">The DbEntityRefExpression that is being visited.</param>
public abstract void Visit(DbEntityRefExpression expression);
/// <summary>
/// Visitor pattern method for DbRefKeyExpression.
/// </summary>
/// <param name="expression">The DbRefKeyExpression that is being visited.</param>
public abstract void Visit(DbRefKeyExpression expression);
/// <summary>
/// Visitor pattern method for DbGroupByExpression.
/// </summary>
/// <param name="expression">The DbGroupByExpression that is being visited.</param>
public abstract void Visit(DbGroupByExpression expression);
/// <summary>
/// Visitor pattern method for DbIntersectExpression.
/// </summary>
/// <param name="expression">The DbIntersectExpression that is being visited.</param>
public abstract void Visit(DbIntersectExpression expression);
/// <summary>
/// Visitor pattern method for DbIsEmptyExpression.
/// </summary>
/// <param name="expression">The DbIsEmptyExpression that is being visited.</param>
public abstract void Visit(DbIsEmptyExpression expression);
/// <summary>
/// Visitor pattern method for DbIsNullExpression.
/// </summary>
/// <param name="expression">The DbIsNullExpression that is being visited.</param>
public abstract void Visit(DbIsNullExpression expression);
/// <summary>
/// Visitor pattern method for DbIsOfExpression.
/// </summary>
/// <param name="expression">The DbIsOfExpression that is being visited.</param>
public abstract void Visit(DbIsOfExpression expression);
/// <summary>
/// Visitor pattern method for DbJoinExpression.
/// </summary>
/// <param name="expression">The DbJoinExpression that is being visited.</param>
public abstract void Visit(DbJoinExpression expression);
/// <summary>
/// Visitor pattern method for DbLambdaExpression.
/// </summary>
/// <param name="expression">The DbLambdaExpression that is being visited.</param>
public virtual void Visit(DbLambdaExpression expression)
{
throw EntityUtil.NotSupported();
}
/// <summary>
/// Visitor pattern method for DbLikeExpression.
/// </summary>
/// <param name="expression">The DbLikeExpression that is being visited.</param>
public abstract void Visit(DbLikeExpression expression);
/// <summary>
/// Visitor pattern method for DbLimitExpression.
/// </summary>
/// <param name="expression">The DbLimitExpression that is being visited.</param>
public abstract void Visit(DbLimitExpression expression);
#if METHOD_EXPRESSION
/// <summary>
/// Visitor pattern method for MethodExpression.
/// </summary>
/// <param name="expression">The MethodExpression that is being visited.</param>
public abstract void Visit(MethodExpression expression);
#endif
/// <summary>
/// Visitor pattern method for DbNewInstanceExpression.
/// </summary>
/// <param name="expression">The DbNewInstanceExpression that is being visited.</param>
public abstract void Visit(DbNewInstanceExpression expression);
/// <summary>
/// Visitor pattern method for DbNotExpression.
/// </summary>
/// <param name="expression">The DbNotExpression that is being visited.</param>
public abstract void Visit(DbNotExpression expression);
/// <summary>
/// Visitor pattern method for DbNullExpression.
/// </summary>
/// <param name="expression">The DbNullExpression that is being visited.</param>
public abstract void Visit(DbNullExpression expression);
/// <summary>
/// Visitor pattern method for DbOfTypeExpression.
/// </summary>
/// <param name="expression">The DbOfTypeExpression that is being visited.</param>
public abstract void Visit(DbOfTypeExpression expression);
/// <summary>
/// Visitor pattern method for DbOrExpression.
/// </summary>
/// <param name="expression">The DbOrExpression that is being visited.</param>
public abstract void Visit(DbOrExpression expression);
/// <summary>
/// Visitor pattern method for DbParameterReferenceExpression.
/// </summary>
/// <param name="expression">The DbParameterReferenceExpression that is being visited.</param>
public abstract void Visit(DbParameterReferenceExpression expression);
/// <summary>
/// Visitor pattern method for DbProjectExpression.
/// </summary>
/// <param name="expression">The DbProjectExpression that is being visited.</param>
public abstract void Visit(DbProjectExpression expression);
/// <summary>
/// Visitor pattern method for DbPropertyExpression.
/// </summary>
/// <param name="expression">The DbPropertyExpression that is being visited.</param>
public abstract void Visit(DbPropertyExpression expression);
/// <summary>
/// Visitor pattern method for DbQuantifierExpression.
/// </summary>
/// <param name="expression">The DbQuantifierExpression that is being visited.</param>
public abstract void Visit(DbQuantifierExpression expression);
/// <summary>
/// Visitor pattern method for DbRefExpression.
/// </summary>
/// <param name="expression">The DbRefExpression that is being visited.</param>
public abstract void Visit(DbRefExpression expression);
/// <summary>
/// Visitor pattern method for DbRelationshipNavigationExpression.
/// </summary>
/// <param name="expression">The DbRelationshipNavigationExpression that is being visited.</param>
public abstract void Visit(DbRelationshipNavigationExpression expression);
/// <summary>
/// Visitor pattern method for DbScanExpression.
/// </summary>
/// <param name="expression">The DbScanExpression that is being visited.</param>
public abstract void Visit(DbScanExpression expression);
/// <summary>
/// Visitor pattern method for DbSkipExpression.
/// </summary>
/// <param name="expression">The DbSkipExpression that is being visited.</param>
public abstract void Visit(DbSkipExpression expression);
/// <summary>
/// Visitor pattern method for DbSortExpression.
/// </summary>
/// <param name="expression">The DbSortExpression that is being visited.</param>
public abstract void Visit(DbSortExpression expression);
/// <summary>
/// Visitor pattern method for DbTreatExpression.
/// </summary>
/// <param name="expression">The DbTreatExpression that is being visited.</param>
public abstract void Visit(DbTreatExpression expression);
/// <summary>
/// Visitor pattern method for DbUnionAllExpression.
/// </summary>
/// <param name="expression">The DbUnionAllExpression that is being visited.</param>
public abstract void Visit(DbUnionAllExpression expression);
/// <summary>
/// Visitor pattern method for DbVariableReferenceExpression.
/// </summary>
/// <param name="expression">The DbVariableReferenceExpression that is being visited.</param>
public abstract void Visit(DbVariableReferenceExpression expression);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AbandonedAudioTrigger : MonoBehaviour
{
public AudioSource AbandonedAudioSource = null;
//dont destroy info
GameObject PositionPlayer;
public DontDestroy dontdestroyinfo;
//audio van puzzle memory kan nog spelen
public AudioFragments MemoryAudio = null;
public Collider TriggerZone;
// Start is called before the first frame update
void Start()
{
PositionPlayer = GameObject.Find("PlayerPosition");
dontdestroyinfo = PositionPlayer.GetComponent<DontDestroy>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(){
if (dontdestroyinfo.AbandonedAudio && !MemoryAudio.KeyAudio.isPlaying){
AbandonedAudioSource.Play();
dontdestroyinfo.AbandonedAudio = false;
}
}
}
|
using System;
using System.Collections.Concurrent;
namespace com.bitscopic.hilleman.core.domain.hl7
{
public class MemoryHL7MessageRouter : IHL7MessageRouter
{
ConcurrentQueue<HL7Message> _messageQueue;
public MemoryHL7MessageRouter()
{
_messageQueue = new ConcurrentQueue<HL7Message>();
}
public void handleMessage(HL7Message message)
{
_messageQueue.Enqueue(message);
// save to db or whatever for logging
// dequeue and process message
}
public void handleRaw(string rawMessage)
{
throw new NotImplementedException();
}
public void log(HL7Message receivedMsg, HL7Message ackMsg)
{
throw new NotImplementedException();
}
void backgroundMessageProcessor()
{
HL7Message currentMsg = null;
while (true)
{
if (_messageQueue.TryDequeue(out currentMsg))
{
}
else
{
System.Threading.Thread.Sleep(1000);
}
}
}
}
} |
//
// SimpleLUI Source
//
// Copyright (c) 2019 ADAM MAJCHEREK ALL RIGHTS RESERVED
//
using SimpleLUI.API.Util;
using System;
using UnityEngine;
using Object = UnityEngine.Object;
namespace SimpleLUI.API.Core.Components
{
public sealed class SLUICanvasGroup : SLUIComponent
{
public float alpha
{
get => Original.alpha;
set => Original.alpha = value;
}
public bool blocksRaycasts
{
get => Original.blocksRaycasts;
set => Original.blocksRaycasts = value;
}
public bool ignoreParentGroups
{
get => Original.ignoreParentGroups;
set => Original.ignoreParentGroups = value;
}
public bool interactable
{
get => Original.interactable;
set => Original.interactable = value;
}
internal new CanvasGroup Original { get; private set; }
/// <inheritdoc />
public override Type ResolveObjectType() => typeof(CanvasGroup);
/// <inheritdoc />
public override Component OnLoadOriginalComponent()
{
return Original = OriginalGameObject.CollectComponent<CanvasGroup>();
}
#if UNITY_EDITOR
/// <inheritdoc />
public override void CollectObjectDefinition(Object obj)
{
var t = (CanvasGroup) obj;
var parentName = SLUILuaBuilderSyntax.CollectVar(t.GetComponent<RectTransform>());
var name = SLUILuaBuilderSyntax.CollectVar(t);
String.AppendLine($"local {name} = {parentName}:AddComponent('CanvasGroup')");
}
/// <inheritdoc />
public override void CollectObjectProperty(Object obj)
{
var t = (CanvasGroup) obj;
var name = SLUILuaBuilderSyntax.CollectVar(t);
if (System.Math.Abs(t.alpha - 1f) > float.Epsilon)
String.AppendLine($"{name}.alpha = {t.alpha}");
if (!t.interactable)
String.AppendLine($"{name}.interactable = false");
if (!t.blocksRaycasts)
String.AppendLine($"{name}.blocksRaycasts = false");
if (t.ignoreParentGroups)
String.AppendLine($"{name}. ignoreParentGroups = true");
}
#endif
}
}
|
using PerchikSharp.Events;
using Telegram.Bot.Types.Enums;
namespace PerchikSharp.Commands
{
class StartCommand : INativeCommand
{
public string Command => "start";
public async void OnExecution(object sender, CommandEventArgs command)
{
var bot = sender as Pieprz;
var message = command.Message;
await bot.SendTextMessageAsync(
chatId: message.Chat.Id,
text: StringManager.FromFile(Program.strManager["INFO_PATH"]),
parseMode: ParseMode.Markdown);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsServiceTaskDemo.Codes
{
public class ConfigurationConstant
{
/// <summary>
/// 日志记录名
/// </summary>
public static string WIN_SERVICE_LOG_NAME = "";
/// <summary>
/// 定时任务windows服务名
/// </summary>
public static string WIN_SERVICE_NAME = "";
/// <summary>
/// 定时任务windows服务显示名
/// </summary>
public static string WIN_DISPLAY_NAME = "";
/// <summary>
/// 定时任务windows服务描述
/// </summary>
public static string WIN_DESCRIPTION = "";
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace System.Diagnostics.ProcessTests
{
public class ProcessTestBase : IDisposable
{
protected const int WaitInMS = 100 * 1000;
protected const string CoreRunName = "corerun";
protected const string TestExeName = "System.Diagnostics.Process.TestConsoleApp.exe";
protected const int SuccessExitCode = 100;
protected Process _process;
protected List<Process> _processes = new List<Process>();
public ProcessTestBase()
{
_process = CreateProcessInfinite();
_process.Start();
}
protected Process CreateProcessInfinite()
{
return CreateProcess("infinite");
}
protected Process CreateProcess(string optionalArgument = ""/*String.Empty is not a constant*/)
{
Process p = new Process();
_processes.Add(p);
p.StartInfo.FileName = CoreRunName;
p.StartInfo.Arguments = string.IsNullOrWhiteSpace(optionalArgument) ?
TestExeName :
TestExeName + " " + optionalArgument;
// Profilers / code coverage tools doing coverage of the test process set environment
// variables to tell the targeted process what profiler to load. We don't want the child process
// to be profiled / have code coverage, so we remove these environment variables for that process
// before it's started.
p.StartInfo.Environment.Remove("Cor_Profiler");
p.StartInfo.Environment.Remove("Cor_Enable_Profiling");
p.StartInfo.Environment.Remove("CoreClr_Profiler");
p.StartInfo.Environment.Remove("CoreClr_Enable_Profiling");
return p;
}
protected void Sleep(double delayInMs)
{
Task.Delay(TimeSpan.FromMilliseconds(delayInMs)).Wait();
}
protected void Sleep()
{
Sleep(50D);
}
protected void StartAndKillProcessWithDelay(Process p)
{
p.Start();
Sleep();
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
CleanUp();
}
internal void CleanUp()
{
// Ensure that there are no open processes with the same name as ProcessName
foreach (Process p in _processes)
{
if (!p.HasExited)
{
try
{
p.Kill();
}
catch (InvalidOperationException) { } // in case it was never started
Assert.True(p.WaitForExit(WaitInMS));
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TPS.ConsoleApp;
namespace TPS.Test
{
[TestClass]
public class TryParseAsTests
{
[TestMethod]
public void NullValue()
{
String value = null;
Object parsed = null;
var isParsed = value.TryParseAs(ref parsed);
Assert.IsFalse(isParsed);
}
[TestMethod]
public void ParseInt32_BlankString()
{
String value = "";
Int32 parsedValue = -1;
var isParsed = value.TryParseAs(ref parsedValue);
Assert.IsFalse(isParsed);
Assert.AreEqual(parsedValue, -1);
}
[TestMethod]
public void ParseInt32_Value()
{
String value = "123";
Int32 parsedValue = 0;
var isParsed = value.TryParseAs(ref parsedValue);
Assert.IsTrue(isParsed);
Assert.AreEqual(parsedValue, 123);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace wuffSonic.Models
{
[XmlRoot(ElementName = "subsonic-response", Namespace = "http://subsonic.org/restapi")]
public class GetNewestPodcastsResponse
{
[XmlAttribute(AttributeName = "version")]
public string version { get; set; }
[XmlAttribute(AttributeName = "status")]
public string status { get; set; }
[XmlElement(ElementName = "newestPodcasts")]
public NewestPodcasts newestPodcasts { get; set; }
}
public class NewestPodcasts
{
[XmlElement(ElementName = "episode")]
public Episode[] episode { get; set; }
}
public class GetNewestPodcasts : Request
{
/// <summary>
/// Returns the most recently published Podcast episodes.
/// </summary>
/// <param name="count">The maximum number of episodes to return.</param>
public GetNewestPodcasts(string count = "20")
: base(nameof(count), count)
{
}
public GetNewestPodcastsResponse Response
{
get
{
return (GetNewestPodcastsResponse)_response;
}
}
public override string method
{
get
{
return "GetNewestPodcasts.view";
}
}
}
}
|
using System;
using System.Security.Principal;
using WebSocketCore.Net.WebSockets;
namespace WebSocketCore.Net
{
/// <summary>
/// Provides the access to the HTTP request and response objects used by
/// the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// This class cannot be inherited.
/// </remarks>
public sealed class HttpListenerContext
{
#region Private Fields
private HttpConnection _connection;
private string _error;
private int _errorStatus;
private HttpListener _listener;
private HttpListenerRequest _request;
private HttpListenerResponse _response;
private IPrincipal _user;
private HttpListenerWebSocketContext _websocketContext;
#endregion
#region Internal Constructors
internal HttpListenerContext(HttpConnection connection)
{
_connection = connection;
_errorStatus = 400;
_request = new HttpListenerRequest(this);
_response = new HttpListenerResponse(this);
}
#endregion
#region Internal Properties
internal HttpConnection Connection
{
get { return _connection; }
}
internal string ErrorMessage
{
get { return _error; }
set { _error = value; }
}
internal int ErrorStatus
{
get { return _errorStatus; }
set { _errorStatus = value; }
}
internal bool HasError
{
get { return _error != null; }
}
internal HttpListener Listener
{
get { return _listener; }
set { _listener = value; }
}
#endregion
#region Public Properties
/// <summary>
/// Gets the HTTP request object that represents a client request.
/// </summary>
/// <value>
/// A <see cref="HttpListenerRequest"/> that represents the client request.
/// </value>
public HttpListenerRequest Request
{
get { return _request; }
}
/// <summary>
/// Gets the HTTP response object used to send a response to the client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerResponse"/> that represents a response to the client request.
/// </value>
public HttpListenerResponse Response
{
get { return _response; }
}
/// <summary>
/// Gets the client information (identity, authentication, and security roles).
/// </summary>
/// <value>
/// A <see cref="IPrincipal"/> instance that represents the client information.
/// </value>
public IPrincipal User
{
get { return _user; }
}
#endregion
#region Internal Methods
internal bool Authenticate()
{
var schm = _listener.SelectAuthenticationScheme(_request);
if (schm == AuthenticationSchemes.Anonymous)
return true;
if (schm == AuthenticationSchemes.None)
{
_response.Close(HttpStatusCode.Forbidden);
return false;
}
var realm = _listener.GetRealm();
var user =
HttpUtility.CreateUser(
_request.Headers["Authorization"],
schm,
realm,
_request.HttpMethod,
_listener.GetUserCredentialsFinder()
);
if (user == null || !user.Identity.IsAuthenticated)
{
_response.CloseWithAuthChallenge(new AuthenticationChallenge(schm, realm).ToString());
return false;
}
_user = user;
return true;
}
internal bool Register()
{
return _listener.RegisterContext(this);
}
internal void Unregister()
{
_listener.UnregisterContext(this);
}
#endregion
#region Public Methods
/// <summary>
/// Accepts a WebSocket handshake request.
/// </summary>
/// <returns>
/// A <see cref="HttpListenerWebSocketContext"/> that represents
/// the WebSocket handshake request.
/// </returns>
/// <param name="protocol">
/// A <see cref="string"/> that represents the subprotocol supported on
/// this WebSocket connection.
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="protocol"/> is empty.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocol"/> contains an invalid character.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// This method has already been called.
/// </exception>
public HttpListenerWebSocketContext AcceptWebSocket(string protocol)
{
if (_websocketContext != null)
throw new InvalidOperationException("The accepting is already in progress.");
if (protocol != null)
{
if (protocol.Length == 0)
throw new ArgumentException("An empty string.", nameof(protocol));
if (!protocol.IsToken())
throw new ArgumentException("Contains an invalid character.", nameof(protocol));
}
_websocketContext = new HttpListenerWebSocketContext(this, protocol);
return _websocketContext;
}
#endregion
}
} |
using System;
using System.IO;
using System.Linq;
namespace Essentions.IO
{
internal static class DirectoryDeleter
{
/// <exception cref="IOException">The directory <paramref name="path.FullPath"/> does not exist. -or-
/// Cannot delete directory <paramref name="path.FullPath"/> without recursion since it's not empty.
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="env"/> is <see langword="null"/></exception>
/// <exception cref="InvalidOperationException">Cannot delete directory when <paramref name="env.FS"/> is null.
/// </exception>
public static void Delete(IFileSystemEnvironment env, DirectoryPath path, bool recursive)
{
if (env == null) {
throw new ArgumentNullException(nameof(env));
}
if (path == null) {
throw new ArgumentNullException(nameof(path));
}
if (env.FS == null) {
throw new InvalidOperationException(
$"Cannot delete directory when {nameof(env)}.{nameof(env.FS)} is null");
}
if (path.IsRelative) {
path = path.MakeAbsolute(env);
}
var directory = env.FS.GetDirectory(path);
if (!directory.Exists) {
throw new IOException($"The directory '{path.FullPath}' does not exist.");
}
var hasDirectories = directory.GetDirectories("*", SearchScope.Current).Any();
var hasFiles = directory.GetFiles("*", SearchScope.Current).Any();
if (!recursive && (hasDirectories || hasFiles)) {
throw new IOException($"Cannot delete directory '{path.FullPath}' " +
"without recursion since it's not empty.");
}
directory.Delete(recursive);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;
using WeaverCore.Enums;
using WeaverCore.Implementations;
namespace WeaverCore.Utilities
{
/// <summary>
/// Used for getting assets/resources from the WeaverCore Bundle
/// </summary>
public static class WeaverAssets
{
public static readonly string WeaverAssetBundleName = "weavercore_modclass_bundle";
static WeaverAssets_I Impl;
/// <summary>
/// Loads a Asset from a WeaverCore Asset Bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <param name="name">The name of the asset to load</param>
/// <returns>Returns the loaded asset, or null of the asset wasn't found</returns>
public static T LoadWeaverAsset<T>(string name) where T : UnityEngine.Object
{
if (Impl == null)
{
Impl = ImplFinder.GetImplementation<WeaverAssets_I>();
Impl.Initialize();
}
return Impl.LoadAsset<T>(name);
}
/// <summary>
/// Loads weaver assets with the same name in the WeaverCore Bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <param name="name">The name of the asset to load</param>
/// <returns>Returns a list of loaded assets</returns>
public static IEnumerable<T> LoadWeaverAssets<T>(string name) where T : UnityEngine.Object
{
if (Impl == null)
{
Impl = ImplFinder.GetImplementation<WeaverAssets_I>();
Impl.Initialize();
}
return Impl.LoadAssets<T>(name);
}
/// <summary>
/// Gets the names of all the loaded WeaverCore Asset Bundles
/// </summary>
public static IEnumerable<string> AllBundles()
{
return Impl.AllAssetBundles;
}
/// <summary>
/// Loads a Asset from a WeaverCore Asset Bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <param name="bundleName">The bundle to load from</param>
/// <param name="name">The name of the asset to load</param>
/// <returns>Returns the loaded asset, or null of the asset wasn't found</returns>
public static T LoadAssetFromBundle<T>(string bundleName, string name) where T : UnityEngine.Object
{
return Impl.LoadAssetFromBundle<T>(bundleName, name);
}
/// <summary>
/// Loads an asset from a mod bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <param name="modType">The mod to load the bundle from</param>
/// <param name="name">The name of the asset to load</param>
/// <returns>Returns the loaded asset, or null of the asset wasn't found</returns>
public static T LoadAssetFromBundle<T>(Type modType, string name) where T : UnityEngine.Object
{
var bundleName = $"{modType.Name.ToLower()}_bundle";
return Impl.LoadAssetFromBundle<T>(bundleName, name);
}
/// <summary>
/// Loads an asset from a mod bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <typeparam name="ModType">The mod to load the bundle from</typeparam>
/// <param name="name">The name of the asset to load</param>
/// <returns>Returns the loaded asset, or null of the asset wasn't found</returns>
public static T LoadAssetFromBundle<T, ModType>(string name) where T : UnityEngine.Object
{
return LoadAssetFromBundle<T>(typeof(ModType), name);
}
/// <summary>
/// Loads weaver assets with the same name from a bundle
/// </summary>
/// <typeparam name="T">The type of assets to load</typeparam>
/// <param name="bundleName">The bundle to load from</param>
/// <param name="name">The name of the assets to load</param>
/// <returns>Returns the loaded assets</returns>
public static IEnumerable<T> LoadAssetsFromBundle<T>(string bundleName, string name) where T : UnityEngine.Object
{
return Impl.LoadAssetsFromBundle<T>(bundleName, name);
}
/// <summary>
/// Loads weaver assets with the same name from a bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <param name="modType">The mod to load the bundle from</param>
/// <param name="name">ThThe name of the assets to load</param>
/// <returns>Returns the loaded assets</returns>
public static IEnumerable<T> LoadAssetsFromBundle<T>(Type modType, string name) where T : UnityEngine.Object
{
var bundleName = $"{modType.Name.ToLower()}_bundle";
return Impl.LoadAssetsFromBundle<T>(bundleName, name);
}
/// <summary>
/// Loads weaver assets with the same name from a bundle
/// </summary>
/// <typeparam name="T">The type of asset to load</typeparam>
/// <typeparam name="ModType">The mod to load the bundle from</typeparam>
/// <param name="name">The name of the assets to load</param>
/// <returns>Returns the loaded assets</returns>
public static IEnumerable<T> LoadAssetsFromBundle<T, ModType>(string name) where T : UnityEngine.Object
{
return LoadAssetsFromBundle<T>(typeof(ModType), name);
}
}
}
|
/***********************************************************************
* Project: CoreCms
* ProjectName: 核心内容管理系统
* Web: https://www.corecms.net
* Author: 大灰灰
* Email: jianweie@163.com
* CreateTime: 2021/7/29 21:25:51
* Description: 暂无
***********************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoreCms.Net.WeChat.Service.Models
{
/// <summary>
/// 微信公众服务器Post过来的加密参数集合(不包括PostData)
/// <para>如需使用 NeuChar,需要在 MessageHandler 中提供 PostModel 并设置 AppId</para>
/// </summary>
public class PostModel : EncryptPostModel
{
public override string DomainId
{
get => this.AppId;
set => this.AppId = value;
}
public string AppId { get; set; }
/// <summary>设置服务器内部保密信息</summary>
/// <param name="token"></param>
/// <param name="encodingAESKey"></param>
/// <param name="appId"></param>
public void SetSecretInfo(string token, string encodingAESKey, string appId)
{
this.Token = token;
this.EncodingAESKey = encodingAESKey;
this.AppId = appId;
}
}
}
|
using UnityEngine;
using System.Collections;
public class FaceToObject : MonoBehaviour {
public Transform objectToFollow = null;
public bool followPlayer = false;
private Transform theTransform = null;
void Awake() {
theTransform = GetComponent<Transform> ();
if (!followPlayer)
return;
GameObject thePlayer = GameObject.FindGameObjectWithTag ("Player");
if (thePlayer != null) {
objectToFollow = thePlayer.GetComponent<Transform> ();
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (objectToFollow == null)
return;
Vector3 directionToFollow = objectToFollow.position - theTransform.position;
if (directionToFollow != Vector3.zero) {
theTransform.localRotation = Quaternion.LookRotation (directionToFollow.normalized, Vector3.up);
}
}
}
|
using Filmstudion.Data.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Filmstudion.Data
{
public interface IRentedFilmRepository
{
IEnumerable<RentedFilm> AllRentedFilms { get; }
Task<IEnumerable<RentedFilm>> GetAllRentedFilmsByUserAsync(string username);
bool CheckIfRented(int filmid, int studioid);
RentedFilm CreateRentedFilm(Film originfilm, Studio rentingstudio);
bool AddRentedFilm(RentedFilm rentedfilm);
bool RemoveRentedFilm(int filmid, int studioid);
}
}
|
@*
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
@ViewBag.Data
<h2>raw info:</h2>
@Html.Raw(ViewBag.Data)
|
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>
<link rel="stylesheet" href="/css/styles.css">
<title>Contact List</title>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1><strong> Address Lookup </strong></h1>
</div>
<h1>Contacts:</h1>
<ul>
@foreach (var Contact in Model)
{
<h3> @Contact.firstName() @Contact.lastName() </h3>
<p> @Contact.number() </p>
<p> @Contact.email() </p>
<p> @Contact.address() </p>
}
</ul>
<ul>
@foreach (var Address in Model)
{
<p>
@Address.streetNum()
@Address.streetName()
</p>
<p>
@Address.city()
@Address.state()
@Address.zipcode()
</p>
}
</ul>
</div>
</body>
</html>
|
#region Copyright (C) 2005-2020 Team MediaPortal
// Copyright (C) 2005-2020 Team MediaPortal
// http://www.team-mediaportal.com
//
// MediaPortal is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// MediaPortal is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with MediaPortal. If not, see <http://www.gnu.org/licenses/>.
#endregion
namespace MediaInfo.Model
{
/// <summary>
/// Describes video color space
/// </summary>
public enum ColorSpace
{
/// <summary>
/// Generic film
/// </summary>
Generic,
/// <summary>
/// Printing density
/// </summary>
PrintingDensity,
/// <summary>
/// BT.601 NTSC
/// </summary>
NTSC,
/// <summary>
/// BT.601 PAL
/// </summary>
PAL,
/// <summary>
/// ADX
/// </summary>
ADX,
/// <summary>
/// BT.470 System M
/// </summary>
BT470M,
/// <summary>
/// BT.470 System B/G
/// </summary>
BT470BG,
/// <summary>
/// BT.601 PAL or NTSC
/// </summary>
BT601,
/// <summary>
/// BT.709
/// </summary>
BT709,
/// <summary>
/// BT.1361
/// </summary>
BT1361,
/// <summary>
/// BT.2020 (10 bit or 12 bit)
/// </summary>
BT2020,
/// <summary>
/// BT.2100
/// </summary>
BT2100,
/// <summary>
/// EBU Tech 3213
/// </summary>
EBUTech3213,
/// <summary>
/// SMPTE 240M
/// </summary>
SMPTE240M,
/// <summary>
/// SMPTE 274M
/// </summary>
SMPTE274M,
/// <summary>
/// SMPTE 428M
/// </summary>
SMPTE428M,
/// <summary>
/// SMPTE ST 2065-1
/// </summary>
ACES,
/// <summary>
/// SMPTE ST 2067-40 / ISO 11664-3
/// </summary>
XYZ,
/// <summary>
/// DCI-P3
/// </summary>
DCIP3,
/// <summary>
/// Display P3
/// </summary>
DisplayP3
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace ManagementSystem.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
[Display(Name = "Joined Date")]
public DateTime JoinedDate { get; set; } = DateTime.Now;
[Required]
public string Name { get; set; }
[Required]
[Display(Name = "Job Title")]
public string JobTitle { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:0}", ApplyFormatInEditMode = true)]
[Display(Name = "Monthly Salary")]
public decimal MonthlySalary { get; set; }
[Required]
public string Department { get; set; }
public int? ManagerId { get; set; }
public Employee Manager { get; set; }
[Display(Name = "Comments Count")]
public List<Comment> Comments { get; set; }
}
}
|
@using Microsoft.AspNetCore.Identity
@using eComplaints
@using eComplaints.Models
@using eComplaints.Models.AccountViewModels
@using eComplaints.Models.ManageViewModels
@using NonFactors.Mvc.Grid;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
namespace Kudu.Core.Deployment
{
internal class CascadeLogger : ILogger
{
private readonly ILogger _primary;
private readonly ILogger _secondary;
public CascadeLogger(ILogger primary, ILogger secondary)
{
_primary = primary;
_secondary = secondary;
}
public ILogger Log(string value, LogEntryType type)
{
_secondary.Log(value, type);
return _primary.Log(value, type);
}
}
}
|
namespace IdSharp.Tagging.ID3v2.Frames
{
/// <summary>
/// <para>Linked information</para>
///
/// <para>From the ID3v2 specification:</para>
///
/// <para>To keep space waste as low as possible this frame may be used to link
/// information from another ID3v2 tag that might reside in another audio
/// file or alone in a binary file. It is recommended that this method is
/// only used when the files are stored on a CD-ROM or other
/// circumstances when the risk of file seperation is low. The frame
/// contains a frame identifier, which is the frame that should be linked
/// into this tag, a URL field, where a reference to the file where
/// the frame is [is] given, and additional ID data, if needed. Data should be
/// retrieved from the first tag found in the file to which this link
/// points. There may be more than one "LINK" frame in a tag, but only
/// one with the same contents. A linked frame is to be considered as
/// part of the tag and has the same restrictions as if it was a physical
/// part of the tag (i.e. only one "RVRB" frame allowed, whether it's
/// linked or not).</para>
///
/// <para>[Header for 'Linked information', ID: "LINK"]<br />
/// Frame identifier $xx xx xx xx<br />
/// URL [text string] $00<br />
/// ID and additional data [text string(s)]</para>
///
/// <para>Frames that may be linked and need no additional data are "IPLS",
/// "MCID", "ETCO", "MLLT", "SYTC", "RVAD", "EQUA", "RVRB", "RBUF", the
/// text information frames and the URL link frames.</para>
///
/// <para>The "TXXX", "APIC", "GEOB" and "AENC" frames may be linked with
/// the content descriptor as additional ID data.</para>
///
/// <para>The "COMM", "SYLT" and "USLT" frames may be linked with three bytes
/// of language descriptor directly followed by a content descriptor as
/// additional ID data.</para>
///
/// TODO: Did this change with ID3v2.4?
/// </summary>
public interface ILinkedInformation : IFrame
{
/// <summary>
/// Gets or sets the linked frame ID (ie, "TALB").
/// </summary>
/// <value>The linked frame ID.</value>
string FrameIdentifier { get; set; }
/// <summary>
/// Gets or sets the URL where a reference to the file where the frame is is given.
/// </summary>
/// <value>The URL where a reference to the file where the frame is is given..</value>
string Url { get; set; }
/// <summary>
/// Gets or sets the additional data. Returns a copy of the raw data, therefore the byte array cannot
/// be modified directly. Use the set property to update the raw data.
/// </summary>
/// <value>The additional data.</value>
byte[] AdditionalData { get; set; }
}
}
|
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace BODi.Performance.Tests.Benchmarks
{
public class ResolveAllFromType : SingleContainerBenchmarkBase
{
[Benchmark(Baseline = true, Description = "v1.4")]
public object Version_1_4()
{
// v1.4 returned a yet unresolved IEnumerable, so we need to force resolution
return Container14.ResolveAll<IAllRegisteredFromType>().ToList();
}
[Benchmark(Description = "v1.BoDi_Concurrent_Dictionary_And_Lazy")]
public object Version_1_BoDi_Concurrent_Dictionary_And_Lazy()
{
return Container1Concurrent_Dictionary_And_Lazy.ResolveAll<IAllRegisteredFromType>();
}
[Benchmark(Description = "Current")]
public object CurrentVersion()
{
// current returns a yet unresolved IEnumerable, so we need to force resolution
return ContainerCurrent.ResolveAll<IAllRegisteredFromType>().ToList();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AlgoraArt.WebApp.Models
{
public class RequestFunds
{
[Key]
public int Id { get; set; }
[Required]
public string FundTitle { get; set; }
[Required]
public string FundDescription { get; set; }
[Required]
public int AmountNeeded { get; set; }
[Required]
public DateTime Created { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual IEnumerable<Funders> Funders { get; set; }
}
}
|
using UnityEngine.InputSystem;
/// <summary>
/// How you access Unity's Input System. You don't want to touch Input Master,
/// that's a class generated by Unity and if you go messing with it things might break.
/// This class gives you control over how to interact with the input system.
/// </summary>
public class InputManager : Singleton<InputManager>
{
// We'll need a reference to an InputMaster - this is the class generated for us by Unity.
private InputMaster inputMaster;
/// <summary>
/// Delegates are template functions.
/// They allow you to pass reference to a function.
/// </summary>
/// <param name="direction"></param>
public delegate void Move(float direction);
/// <summary>
/// Events are a list of functions.
/// When something happens - in this case movement - everyone who is SUBSCRIBED
/// to this event will be alerted (i.e. their function will be called).
/// </summary>
public event Move OnMove;
/*
* Delegates and Events are advanced C#, but they are incredibly useful for situations
* like providing input. I'll make some more detailed notes going over them and post in
* #resources.
*/
public delegate void Jump();
public event Jump OnJump;
/// <summary>
/// Remember, Awake is good for getting components attached to yourself and for
/// instantiating variables.
///
/// Start is good for communicating with other GameObjects.
/// </summary>
private void Awake()
{
// Instantiate a new InputMaster
inputMaster = new InputMaster();
}
/*
* OnEnable and OnDisable:
* When a Scene starts, Unity will go through all your objects and ENABLE their components,
* when it does so it will call OnEnable if you've written it.
*
* When a GameObject is deactivated or destroyed, Unity will call OnDisable.
*
* Usually, you don't need to worry about these functions. We need them here to enable our
* inputMaster and manage our event subscriptions.
*/
private void OnEnable()
{
// Enable inputMaster and subscribe our functions to input events.
inputMaster.Enable();
// These are Arrow Functions, also advanced C#, also very handy.
// I'll try to post notes on them in #resources as well.
inputMaster.Base.Move.performed += ctx => PerformMove(ctx);
inputMaster.Base.Jump.performed += ctx => PerformJump(ctx);
}
private void OnDisable()
{
// Unsubscribe from input events and
inputMaster.Base.Move.performed -= ctx => PerformMove(ctx);
inputMaster.Base.Jump.performed -= ctx => PerformJump(ctx);
inputMaster.Disable();
}
/// <summary>
/// Check if there are movement subscribers and alert them.
/// </summary>
/// <param name="ctx">
/// The context of the input. In this case it will be either 1 or -1, implying right or left.
/// </param>
private void PerformMove(InputAction.CallbackContext ctx)
{
// If the event is null, there are no subscribers.
if(OnMove != null)
{
OnMove(ctx.ReadValue<float>());
}
}
private void PerformJump(InputAction.CallbackContext ctx)
{
if(OnJump != null)
{
OnJump();
}
}
}
|
using System;
using System.Threading.Tasks;
using Advertise.ServiceLayer.Contracts;
using Microsoft.AspNet.Identity;
namespace Advertise.ServiceLayer.EFServices
{
public class SmsService : IIdentityMessageService,ISmsService
{
public void Create()
{
throw new NotImplementedException();
}
public void Edit()
{
throw new NotImplementedException();
}
public void Delete()
{
throw new NotImplementedException();
}
public void Get()
{
throw new NotImplementedException();
}
public Task SendAsync(IdentityMessage message)
{
// Plug in your sms service here to send a text message.
return Task.FromResult(0);
}
}
} |
namespace PocketGauger.Dtos
{
public enum RiverState
{
Rising = 0,
Falling,
Steady,
Peak,
Trough,
Comments1
}
}
|
using System.Collections.Generic;
using NGraphQL.Core.Scalars;
using NGraphQL.Server.Parsing;
namespace NGraphQL.Model.Request {
// equiv of Value in Gql spec
public abstract class ValueSource : RequestObjectBase {
public virtual bool IsConstNull() => false;
}
public class VariableValueSource : ValueSource {
public string VariableName;
public override string ToString() => VariableName;
public VariableValueSource() { }
}
public class TokenValueSource : ValueSource {
public TokenData TokenData;
public override string ToString() => TokenData.ParsedValue?.ToString();
public override bool IsConstNull() => TokenData?.TermName == TermNames.NullValue;
}
public class ListValueSource : ValueSource {
public ValueSource[] Values;
public override string ToString() => $"(Count {Values?.Length})";
}
public class ObjectValueSource : ValueSource {
public IDictionary<string, ValueSource> Fields = new Dictionary<string, ValueSource>();
public override string ToString() => "(input object)";
}
}
|
using Ocelot.Configuration.Authentication;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HashMatcherTests
{
private string _password;
private string _hash;
private string _salt;
private bool _result;
private HashMatcher _hashMatcher;
public HashMatcherTests()
{
_hashMatcher = new HashMatcher();
}
[Fact]
public void should_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(true))
.BDDfy();
}
[Fact]
public void should_not_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret1";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(false))
.BDDfy();
}
private void GivenThePassword(string password)
{
_password = password;
}
private void GivenTheHash(string hash)
{
_hash = hash;
}
private void GivenTheSalt(string salt)
{
_salt = salt;
}
private void WhenIMatch()
{
_result = _hashMatcher.Match(_password, _salt, _hash);
}
private void ThenTheResultIs(bool expected)
{
_result.ShouldBe(expected);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipChunkContainer : ChunkContainer
{
void Start()
{
InitializeNewShip();
}
public void InitializeNewShip()
{
Chunk initialChunk = CreateChunk(new ChunkCoordinate(0, 0, 0));
if (initialChunk != null)
{
initialChunk.SetCell(0, 0, 0, BlockType.ShipCore);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.