content stringlengths 23 1.05M |
|---|
using System.Web;
using ClassGenMacros;
namespace tspHandler
{
public class Navigator
{
public string userAgent
{
get
{
return HttpContext.Current.Request.UserAgent;
}
}
public string appVersion
{
get
{
return this.userAgent.SubstringAfter("/");
}
}
}
}
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using Merlin.Testing.TypeSample;
namespace Merlin.Testing.Property {
#region Explicitly implemented property
public interface IData {
int Number { get; set; }
}
public class ClassExplicitlyImplement : IData {
private int _value;
int IData.Number {
get { return _value; }
set { _value = value; }
}
}
public struct StructExplicitlyImplement : IData {
private int _value;
int IData.Number {
get { return _value; }
set { _value = value; }
}
}
public interface IReadOnlyData {
string Number { get; }
}
public interface IWriteOnlyData {
SimpleStruct Number { set; }
}
public class ClassExplicitlyReadOnly : IReadOnlyData {
private string _iv = "python";
string IReadOnlyData.Number {
get { return _iv; }
}
}
public struct StructExplicitlyWriteOnly : IWriteOnlyData {
private SimpleStruct _iv;
SimpleStruct IWriteOnlyData.Number {
set { Flag.Set(10 + value.Flag); _iv = value; }
}
}
#endregion
#region ReadOnly/WriteOnly static/instance properties
public class ClassWithReadOnly {
private int _iv = 9;
private static string _sv = "dlr";
public int InstanceProperty {
get { return _iv; }
}
public static string StaticProperty {
get { return _sv; }
}
}
public class ClassWithWriteOnly {
private int _iv;
private static string _sv;
public int InstanceProperty {
set { Flag.Set(11); _iv = value; }
}
public static string StaticProperty {
set { Flag.Set(12); _sv = value; }
//get { return "abc"; }
}
}
public class ReadOnlyBase {
public int Number {
get { return 21; }
}
}
public class WriteOnlyDerived : ReadOnlyBase {
public new int Number {
set { Flag.Set(value); }
}
}
#endregion
public class ClassWithProperties {
private int _iv1;
public int InstanceInt32Property {
get { return _iv1; }
set { _iv1 = value; }
}
private SimpleStruct _iv2;
public SimpleStruct InstanceSimpleStructProperty {
get { return _iv2; }
set { _iv2 = value; }
}
private SimpleClass _iv3;
public SimpleClass InstanceSimpleClassProperty {
get { return _iv3; }
set { _iv3 = value; }
}
private static int _sv1;
public static int StaticInt32Property {
get { return _sv1; }
set { _sv1 = value; }
}
private static SimpleStruct _sv2;
public static SimpleStruct StaticSimpleStructProperty {
get { return _sv2; }
set { _sv2 = value; }
}
private static SimpleClass _sv3;
public static SimpleClass StaticSimpleClassProperty {
get { return _sv3; }
set { _sv3 = value; }
}
}
public class DerivedClass : ClassWithProperties { }
public struct StructWithProperties {
private int _iv1;
public int InstanceInt32Property {
get { return _iv1; }
set { _iv1 = value; }
}
public SimpleStruct _iv2;
public SimpleStruct InstanceSimpleStructProperty {
get { return _iv2; }
set { _iv2 = value; }
}
private SimpleClass _iv3;
public SimpleClass InstanceSimpleClassProperty {
get { return _iv3; }
set { _iv3 = value; }
}
private static int _sv1;
public static int StaticInt32Property {
get { return _sv1; }
set { _sv1 = value; }
}
private static SimpleStruct _sv2;
public static SimpleStruct StaticSimpleStructProperty {
get { return _sv2; }
set { _sv2 = value; }
}
private static SimpleClass _sv3;
public static SimpleClass StaticSimpleClassProperty {
get { return _sv3; }
set { _sv3 = value; }
}
}
} |
using UnityEngine;
using UnityEngine.Events;
[RequireComponent(typeof(Animator))]
public class UIController : MonoBehaviour {
public enum OnHideAction {
None,
Disable,
Destroy,
}
public class PlayAsync : CustomYieldInstruction {
public PlayAsync(UIController controller, bool isShow) {
this.m_Obj = controller;
this.m_ObjName = controller.ToString();
if (isShow) {
controller.Show(this.OnCompleted);
}
else {
controller.Hide(this.OnCompleted);
}
}
public override bool keepWaiting {
get {
if (this.m_Obj == null) {
throw new System.Exception(this.m_ObjName + " is be destroy, you can't keep waiting.");
}
return !this.m_IsDone;
}
}
private UIController m_Obj;
private string m_ObjName;
private bool m_IsDone;
private void OnCompleted() {
this.m_IsDone = true;
}
}
public bool showOnAwake = true;
public OnHideAction onHideAction = OnHideAction.Disable;
[SerializeField] private UnityEvent m_OnShow = new UnityEvent();
[SerializeField] private UnityEvent m_OnHide = new UnityEvent();
private UnityEvent m_OnShowDisposable = new UnityEvent();
private UnityEvent m_OnHideDisposable = new UnityEvent();
private Animator m_Animator;
public UnityEvent onShow {
get { return this.m_OnShow; }
}
public UnityEvent onHide {
get { return this.m_OnHide; }
}
public bool isShow {
get {
if (this.animator.runtimeAnimatorController == null) {
return this.isShowWhenNoController;
}
if (!this.animator.isInitialized) {
return false;
}
return this.animator.GetBool("Is Show");
}
private set {
if (this.animator.runtimeAnimatorController == null) {
this.isShowWhenNoController = value;
if (value) {
this.OnShow();
}
else {
this.OnHide();
}
return;
}
this.animator.SetBool("Is Show", value);
this.animator.SetTrigger("Play");
}
}
public bool isPlaying {
get {
if (this.animator.runtimeAnimatorController == null) {
return false;
}
if (!this.animator.isInitialized) {
return false;
}
AnimatorStateInfo currentState = this.animator.GetCurrentAnimatorStateInfo(0);
return (currentState.IsName("Show") || currentState.IsName("Hide"))
&& currentState.normalizedTime < 1;
}
}
public Animator animator {
get {
if (this.m_Animator == null) {
this.m_Animator = this.GetComponent<Animator>();
}
return this.m_Animator;
}
}
private bool canTransitionToSelf {
get {
if (this.animator.runtimeAnimatorController == null) {
return true;
}
if (!this.animator.isInitialized) {
return true;
}
return this.animator.GetBool("Can Transition To Self");
}
}
private bool isShowWhenNoController;
private int lastShowAtFrame = -1;
// Show/Hide must fast by Show(UnityAction)Hide(UnityAction), make SendMessage("Show/Hide") working in Inspector
public virtual void Show() {
if (!this.canTransitionToSelf && this.isShow) {
if (!this.isPlaying) {
this.OnShow();
}
return;
}
if (!this.gameObject.activeSelf) {
this.lastShowAtFrame = Time.frameCount;
this.gameObject.SetActive(true);
}
this.isShow = true;
}
public virtual void Hide() {
if (!this.canTransitionToSelf && !this.isShow) {
if (!this.isPlaying) {
this.OnHide();
}
return;
}
this.isShow = false;
}
public void Show(UnityAction onShow) {
if (onShow != null) {
m_OnShowDisposable.AddListener(onShow);
}
this.Show();
}
public void Hide(UnityAction onHide) {
if (onHide != null) {
m_OnHideDisposable.AddListener(onHide);
}
this.Hide();
}
public PlayAsync ShowAsync() {
return new PlayAsync(this, true);
}
public PlayAsync HideAsync() {
return new PlayAsync(this, false);
}
protected virtual void OnEnable() {
// this.animator.Update(0);
if (this.showOnAwake && Time.frameCount != this.lastShowAtFrame) {
this.Show();
}
this.lastShowAtFrame = -1;
}
protected virtual void OnShow() {
this.onShow.Invoke();
this.m_OnShowDisposable.Invoke();
this.m_OnShowDisposable.RemoveAllListeners();
}
protected virtual void OnHide() {
switch (this.onHideAction) {
case OnHideAction.None:
break;
case OnHideAction.Disable:
this.gameObject.SetActive(false);
this.animator.Rebind();
break;
case OnHideAction.Destroy:
Destroy(this.gameObject);
break;
}
this.onHide.Invoke();
this.m_OnHideDisposable.Invoke();
this.m_OnHideDisposable.RemoveAllListeners();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TerrariaChatRelay.Command;
namespace TerrariaChatRelay
{
public class TCRClientUser
{
public string Client { get; set; }
public string Username { get; set; }
public Permission PermissionLevel { get; set; }
public TCRClientUser(string client, string username, Permission permissionLevel)
{
Client = client;
Username = username;
PermissionLevel = permissionLevel;
}
}
}
|
using System;
namespace Coosu.Storyboard.Extensions.Optimizing
{
public class StoryboardEventArgs : EventArgs
{
public string? Message { get; set; }
public virtual bool Continue { get; set; }
}
} |
using System.IO;
using System.Xml;
namespace MikuMikuModel.Modules.Xml
{
public class XmlDocumentModule : FormatModule<XmlDocument>
{
public override FormatModuleFlags Flags => FormatModuleFlags.Import | FormatModuleFlags.Export;
public override string Name => "Xml Document";
public override string[] Extensions => new[] { "xml" };
protected override XmlDocument ImportCore( Stream source, string fileName )
{
var document = new XmlDocument();
document.Load( source );
return document;
}
protected override void ExportCore( XmlDocument model, Stream destination, string fileName )
{
model.Save( destination );
}
}
} |
using System;
namespace EasyAbp.LoggingManagement.SystemLogs.Dtos
{
public class SystemLogDto
{
public string LogName { get; set; }
public string LogValue { get; set; }
public DateTime? Time { get; set; }
public string Level { get; set; }
}
} |
@model toDoList.ViewModels.ConConfigViewModel
@{
ViewData["Title"] = "Edit";
//Layout = "~/Views/Shared/_Layout.cshtml";
var idEmpresa = @Model.EmpresaId;
}
<style>
.aLink {
color: rgb(82,123,255) !important;
}
.aLink:hover {
color: rgb(82,123,255) !important;
text-decoration: underline !important;
cursor: pointer !important;
}
</style>
<form asp-action="Edit" method="post">
<div class="card">
<div class="card-header">
<h1>Nome Empresa: @ViewBag.NomeEmpresa | ID Empresa: @Model.EmpresaId</h1>
<h1>Alterar a conexao: <strong>@Model.NomeServidor</strong></h1>
<h2 id="myIdEmpresa" hidden>@idEmpresa</h2>
<hr />
</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
@*<form method="post">*@
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input id="myConexaoID" type="hidden" asp-for="ConexaoID" />
<input id="myEmpresaID" type="hidden" asp-for="EmpresaId" />
<div class="form-group">
<label asp-for="NomeServidor" class="control-label"></label>
<input id="myNomeServidor" asp-for="NomeServidor" class="form-control" />
<span id="myNomeServidorSpan" class="text-danger" style="display:none;"></span>
</div>
<div class="form-group">
<label asp-for="InstanciaSQL" class="control-label"></label>
<input id="myInstanciaSQL" asp-for="InstanciaSQL" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Utilizador" class="control-label"></label>
<input id="myUtilizador" asp-for="Utilizador" class="form-control" />
<span id="myUtilizadorSpan" class="text-danger" style="display:none;"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input id="myPassword" asp-for="Password" class="form-control" />
<span id="myPasswordSpan" class="text-danger" style="display:none;"></span>
</div>
<div class="form-check m-1">
<input id="myActiveConnection" asp-for="ActiveConnection" type="checkbox" />
<label class="form-check-label" asp-for="ActiveConnection"></label>
</div>
<div class="form-group">
<input id="btnGravar" value="Gravar" class="btn btn-primary" />
</div>
</div>
</div>
</div>
<div class="card-footer">
<a id="aBackToConnectionList" class="aLink">Voltar a lista</a>
</div>
</div>
</form>
<script>
$('#aBackToConnectionList').click(function () {
var _id = $('#myIdEmpresa').text();
var b = RenderWithNoRefreshWithData("/ConConfig/Index/", { EmpresaId: _id }, "GET")
});
$('#btnGravar').click(function () {
var _nServer = $('#myNomeServidor').val();
var _conId = $('#myConexaoID').val();
var _emprId = $('#myEmpresaID').val();
var _InstanciaSQL = $('#myInstanciaSQL').val();
var _Utilizador = $('#myUtilizador').val();
var _Password = $('#myPassword').val();
var _ActiveConnection = $('#myActiveConnection').val();
var _data = {
ConexaoID: _conId,
EmpresaId: _emprId,
NomeServidor: _nServer,
InstanciaSQL: _InstanciaSQL,
Utilizador: _Utilizador,
Password: _Password,
ActiveConnection: _ActiveConnection
};
// alert(_data);
$.ajax({
url: "/ConConfig/EditJson",
type: "post",
cache: false,
data: _data,
success:
function (data) {
if (data.success === true) {
RenderWithNoRefreshWithData("/ConConfig/Index/", { EmpresaId: _emprId }, "GET");
};
if (data.success === false) {
if (data.field === "NomeServidor") {
$('#myNomeServidorSpan').text(data.msg);
$('#myNomeServidorSpan').show().css("display", "inline").fadeOut(3000);
};
if (data.field === "Utilizador") {
$('#myUtilizadorSpan').text(data.msg);
$('#myUtilizadorSpan').show().css("display", "inline").fadeOut(3000);
};
if (data.field === "Password") {
$('#myPasswordSpan').text(data.msg);
$('#myPasswordSpan').show().css("display", "inline").fadeOut(3000);
};
};
},
error:
function (xhr) {
ProcessError(xhr);//alert(xhr.responseText);
}
});
});
function ProcessError(xhr) {
var _emprId = $('#myEmpresaID').val();
var _data = {
Signal: "notok",
ErrorTitle: "Erro de atualização!",
ErrorMessage: "Não foi possível atualizar os dados de conexão no servidor, " +
" se o erro persistir, entre em contato com o suporte!" + xhr.responseText,
UrlToRedirect: "/ConConfig/Index/",
OptionalData: "new { EmpresaId : " + _emprId + " }",
StringButton: "Voltar para as conexões"
};
var c = RenderWithNoRefreshWithData("/Error/GeneralError/", _data, "GET");
}
</script>
|
@model TMXN.Web.ViewModels.Teams.TeamViewModel
@using Microsoft.AspNetCore.Identity
@using TMXN.Data.Models
@inject UserManager<ApplicationUser> userManager
@{string userId = userManager.GetUserId(this.User);}
<div class="card mr-3" style="width: 15rem;">
<img class="card-img-top" src="@Model.Logo" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">@Model.Name</h5>
<h2 class="card-title">@Model.Tag</h2>
@if (Model.ApplicationUsers.Any(x => x.Id == userId))
{
<a href="/Teams/Leave?teamId=@Model.Id" type="button" class="btn btn-primary center-block">Leave!</a>
}
else
{
<a href="/Teams/Join?teamId=@Model.Id" type="button" class="btn btn-primary center-block">Join us!</a>
}
<a href="/Teams/TeamInfo?teamId=@Model.Id" type="button" class="btn btn-primary center-block">Info!</a>
</div>
</div> |
namespace SpaceEngineers.Core.GenericEndpoint.TestExtensions.Internals
{
using System.Collections.Generic;
using Contract.Abstractions;
/// <summary>
/// ITestIntegrationContext
/// </summary>
public interface ITestIntegrationContext
{
/// <summary>
/// Messages
/// </summary>
IReadOnlyCollection<IIntegrationMessage> Messages { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetadataLocal.UbisoftLibrary
{
public class UbisoftSearchResponse
{
public List<Hits> results { get; set; }
}
public class Hits
{
public List<GameStoreSearchResponse> hits { get; set; }
}
public class GameStoreSearchResponse
{
public string id { get; set; }
public string title { get; set; }
public string link { get; set; }
public string image_link { get; set; }
public string additional_image_link { get; set; }
//public string mobile_link { get; set; }
//public string availability { get; set; }
//public Dictionary<string, string> availability_date { get; set; }
//public string sale_price_effective_date { get; set; }
//public string google_product_category { get; set; }
//public Dictionary<string, string> product_type { get; set; }
//public string brand { get; set; }
//public string gtin { get; set; }
//public string mpn { get; set; }
//public string identifier_exists { get; set; }
//public string adult { get; set; }
//public string gender { get; set; }
//public string Game { get; set; }
//public Dictionary<string, string> Genre { get; set; }
//public string Platform { get; set; }
//public string Edition { get; set; }
//public string Rating { get; set; }
public List<Dictionary<string, string>> html_description { get; set; }
//public Dictionary<string, string> default_price { get; set; }
//public Dictionary<string, string> price { get; set; }
//public Dictionary<string, string> price_range { get; set; }
//public string merch_type { get; set; }
//public string popularity { get; set; }
//public int club_units { get; set; }
//public string Novelty { get; set; }
//public string Exclusivity { get; set; }
//public string Free_offer { get; set; }
//public string Searchable { get; set; }
//public string MasterID { get; set; }
//public string promotion_percentage { get; set; }
//public string preorder { get; set; }
//public string dlcType { get; set; }
//public string release_year { get; set; }
//public string short_title { get; set; }
//public Dictionary<string, string> minimum_price { get; set; }
//public string upc_included { get; set; }
//public string linkWeb { get; set; }
//public string linkUpc { get; set; }
//public string platforms_availability { get; set; }
//public string sub_brand { get; set; }
//public int orders_data { get; set; }
//public double revenue_data { get; set; }
//public string comingSoon { get; set; }
//public string Loyalty_units { get; set; }
//public string objectID { get; set; }
//public class _highlightResult { get; set; }
}
}
|
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Internal;
namespace MVCForumAutomation
{
public class DiscussionHeader
{
private readonly IWebElement _topicRow;
public DiscussionHeader(IWebElement topicRow)
{
_topicRow = topicRow;
}
public string Title
{
get
{
var titleElement = _topicRow.FindElement(By.TagName("h3"));
return titleElement.Text;
}
}
public Discussion OpenDiscussion()
{
var link = _topicRow.FindElement(By.TagName("h3"));
link.Click();
var driver = ((IWrapsDriver) _topicRow).WrappedDriver;
return new Discussion(driver);
}
}
} |
using HL7Data.Contracts.Messages.StockRequisitionOrderMessages;
using HL7Data.Models.Types;
namespace HL7Data.Models.Messages.StockRequisitionOrderMessages
{
public class StockRequisitionOrder : BaseStockRequisitionOrderMessage, IStockRequisitionOrder
{
public override TriggerEventTypes TriggerEventType => TriggerEventTypes.OMS_O05;
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace Hoops.Core.Models
{
public partial class VwDivision
{
[Key]
public int DivisionId { get; set; }
public int CompanyId { get; set; }
public Object SeasonId { get; set; }
public string DivDesc { get; set; }
public Object Teams { get; set; }
public string Gender { get; set; }
public Object MinDate { get; set; }
public Object MaxDate { get; set; }
public string Gender2 { get; set; }
public Object MinDate2 { get; set; }
public Object MaxDate2 { get; set; }
public Object AD { get; set; }
public string HousePhone { get; set; }
public string Cellphone { get; set; }
public string DraftVenue { get; set; }
public Object DraftDate { get; set; }
public string DraftTime { get; set; }
public Object DirectorId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
}
|
using System.Linq;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.Experimental.GraphView;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace RealmSchema.Editor
{
public class SchemaEditorWindow : EditorWindow
{
private EditorDataSO _data = null;
private SchemaGraphView _graphView = null;
private StyleSheet _styleSheet = null;
private bool _wasLoaded = false;
private Toolbar _toolbar = null;
private ToolbarButton _saveButton = null;
private ToolbarButton _addRoleButton = null;
private ToolbarButton _addSchemaButton = null;
[OnOpenAsset(1)]
public static bool ShowWindow(int instanceId, int line)
{
Object asset = EditorUtility.InstanceIDToObject(instanceId);
if (!(asset is EditorDataSO)) return false;
SchemaEditorWindow window = GetWindow<SchemaEditorWindow>("Schema Editor");
window._data = (EditorDataSO)asset;
window._wasLoaded = false;
window.minSize = new Vector2(512, 512);
return false;
}
private void OnGUI()
{
if (!_wasLoaded) Load();
}
private void OnEnable()
{
_styleSheet = Resources.Load<StyleSheet>("Style Sheet");
rootVisualElement.styleSheets.Add(_styleSheet);
_graphView = new SchemaGraphView(_styleSheet);
rootVisualElement.Add(_graphView);
_toolbar = new Toolbar();
_saveButton = new ToolbarButton(Save);
_saveButton.text = "Save";
_toolbar.Add(_saveButton);
_addRoleButton = new ToolbarButton(() => _graphView.AddRole(Vector2.zero));
_addRoleButton.text = "Add Role";
_toolbar.Add(_addRoleButton);
_addSchemaButton = new ToolbarButton(() => _graphView.AddSchema(Vector2.zero));
_addSchemaButton.text = "Add Schema";
_toolbar.Add(_addSchemaButton);
rootVisualElement.Add(_toolbar);
Load();
}
private void OnDisable()
{
rootVisualElement.Remove(_graphView);
rootVisualElement.Remove(_toolbar);
}
private void Load()
{
if (!_data) return;
_graphView.NextRoleIndex = _data.NextRoleIndex;
_graphView.NextSchemaIndex = _data.NextSchemaIndex;
foreach (Role role in _data.Roles)
{
_graphView.AddRole(role.Position, role);
}
foreach (Schema schema in _data.Schemas)
{
_graphView.AddSchema(schema.Position, schema);
}
foreach (Connection connection in _data.Connections)
{
BaseNode inputNode = (BaseNode)_graphView.nodes.Where(
(Node node) => ((BaseNode)node).Guid == connection.InputNodeGuid).First();
BaseNode outputNode = (BaseNode)_graphView.nodes.Where(
(Node node) => ((BaseNode)node).Guid == connection.OutputNodeGuid).First();
Port inputPort = (Port)inputNode.inputContainer[connection.InputPortIndex];
Port outputPort = (Port)outputNode.outputContainer[connection.OutputPortIndex];
Edge edge = inputPort.ConnectTo(outputPort);
_graphView.AddElement(edge);
}
_wasLoaded = true;
}
private void Save()
{
_data.Roles.Clear();
_data.Schemas.Clear();
_data.Connections.Clear();
_data.NextRoleIndex = _graphView.NextRoleIndex;
_data.NextSchemaIndex = _graphView.NextSchemaIndex;
foreach (Node node in _graphView.nodes)
{
if (node is RoleNode)
{
RoleNode roleNode = (RoleNode)node;
Role role = roleNode.Role;
role.Guid = roleNode.Guid;
role.Position = roleNode.GetPosition().position;
_data.Roles.Add(role);
}
else if (node is SchemaNode)
{
SchemaNode schemaNode = (SchemaNode)node;
Schema schema = schemaNode.Schema;
schema.Guid = schemaNode.Guid;
schema.Position = schemaNode.GetPosition().position;
schema.NextFieldIndex = schemaNode.NextFieldIndex;
_data.Schemas.Add(schema);
}
}
foreach (Edge connection in _graphView.edges)
{
BaseNode inputNode = (BaseNode)connection.input.node;
BaseNode outputNode = (BaseNode)connection.output.node;
_data.Connections.Add(new Connection
{
InputNodeGuid = inputNode.Guid,
InputPortIndex = inputNode.inputContainer.IndexOf(connection.input),
OutputNodeGuid = outputNode.Guid,
OutputPortIndex = outputNode.outputContainer.IndexOf(connection.output),
});
}
}
}
}
|
#if ENDEL_NATIVE_WEBSOCKET
using System.Collections.Generic;
using System.Threading.Tasks;
using NativeWebSocket;
namespace Alteracia.Web
{
public class WebSocketHandler : IWebSocketHandler
{
private WebSocket _socket;
public async Task Connect(string url, Dictionary<string, string> headers = null, Events events = null)
{
_socket = new WebSocket(url);
AssignEvents(events);
await _socket.Connect();
}
public Task Send(byte[] bytes)
{
return _socket?.Send(bytes);
}
public Task SendText(string message)
{
return _socket?.SendText(message);
}
public Task Close()
{
return _socket?.Close();
}
private void AssignEvents(Events events = null)
{
if (_socket == null || events == null) return;
_socket.OnOpen += () =>
{
events.OnOpen?.Invoke();
DispatchLoop();
};
_socket.OnMessage += data =>
{
events.OnMessage?.Invoke(data);
};
_socket.OnError += error =>
{
_socket.CancelConnection();
_socket.Close();
events.OnError?.Invoke(error);
};
_socket.OnClose += closeCode =>
{
_socket.CancelConnection();
events.OnClose?.Invoke((CloseCode)closeCode);
};
}
private async void DispatchLoop()
{
#if !UNITY_WEBGL || UNITY_EDITOR
while (_socket.State == WebSocketState.Open)
{
_socket.DispatchMessageQueue();
await Task.Delay(1000);
}
#endif
}
}
}
#endif // ENDEL_NATIVE_WEBSOCKET |
namespace Paytrim.ValidationHelper
{
public class SwedishBank
{
public SwedishBank(string name, int type, int comment, string regex)
{
Name = name;
Type = type;
Comment = comment;
Regex = regex;
}
public string Name { get; set; }
public int Type { get; set; }
public int Comment { get; set; }
public string Regex { get; set; }
}
}
|
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using NakedFramework;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.FacetFactory;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.Metamodel.Utils;
using NakedFramework.ParallelReflector.FacetFactory;
using NakedFunctions.Reflector.Facet;
using NakedFunctions.Reflector.Utils;
namespace NakedFunctions.Reflector.FacetFactory {
public sealed class ActionValidateViaFunctionFacetFactory : FunctionalFacetFactoryProcessor, IMethodPrefixBasedFacetFactory, IMethodFilteringFacetFactory {
private static readonly string[] FixedPrefixes = {
RecognisedMethodsAndPrefixes.ValidatePrefix
};
private readonly ILogger<ActionValidateViaFunctionFacetFactory> logger;
public ActionValidateViaFunctionFacetFactory(IFacetFactoryOrder<ActionValidateViaFunctionFacetFactory> order, ILoggerFactory loggerFactory)
: base(order.Order, loggerFactory, FeatureType.ActionsAndActionParameters) =>
logger = loggerFactory.CreateLogger<ActionValidateViaFunctionFacetFactory>();
public string[] Prefixes => FixedPrefixes;
#region IMethodFilteringFacetFactory Members
private static bool MatchParams(MethodInfo methodInfo, Type[] toMatch) {
var actualParams = InjectUtils.FilterParms(methodInfo).Select(p => p.ParameterType).ToArray();
if (actualParams.Length == 0 || actualParams.Length != toMatch.Length) {
return false;
}
return actualParams.Zip(toMatch).All(i => i.First == i.Second);
}
private static bool Matches(MethodInfo methodInfo, string name, Type type, Type targetType, Type[] paramTypes) =>
methodInfo.Matches(name, type, typeof(string), targetType) &&
MatchParams(methodInfo, paramTypes);
private IImmutableDictionary<string, ITypeSpecBuilder> FindAndAddFacetToParameterValidateMethod(Type declaringType, Type targetType, string name, Type paramType, ISpecificationBuilder parameter, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
bool Matcher(MethodInfo mi) => Matches(mi, name, declaringType, targetType, new[] {paramType});
var methodToUse = FactoryUtils.FindComplementaryMethod(declaringType, name, Matcher, logger);
if (methodToUse is not null) {
// add facets directly to parameters, not to actions
FacetUtils.AddFacet(new ActionParameterValidationViaFunctionFacet(methodToUse, parameter, LoggerFactory.CreateLogger<ActionParameterValidationViaFunctionFacet>()));
}
return metamodel;
}
private IImmutableDictionary<string, ITypeSpecBuilder> FindAndAddFacetToActionValidateMethod(Type declaringType, Type targetType, string name, Type[] paramTypes, ISpecificationBuilder action, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
bool Matcher(MethodInfo mi) => Matches(mi, name, declaringType, targetType, paramTypes);
var methodToUse = FactoryUtils.FindComplementaryMethod(declaringType, name, Matcher, logger);
if (methodToUse is not null) {
FacetUtils.AddFacet(new ActionValidationViaFunctionFacet(methodToUse, action, LoggerFactory.CreateLogger<ActionValidationViaFunctionFacet>()));
}
return metamodel;
}
public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo actionMethod, ISpecificationBuilder action, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
var name = $"{RecognisedMethodsAndPrefixes.ValidatePrefix}{NameUtils.CapitalizeName(actionMethod.Name)}";
var declaringType = actionMethod.DeclaringType;
var targetType = actionMethod.ContributedToType();
var parameters = InjectUtils.FilterParms(actionMethod).Select(p => p.ParameterType).ToArray();
return FindAndAddFacetToActionValidateMethod(declaringType, targetType, name, parameters, action, metamodel);
}
public override IImmutableDictionary<string, ITypeSpecBuilder> ProcessParams(IReflector reflector, MethodInfo actionMethod, int paramNum, ISpecificationBuilder holder, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
var name = $"{RecognisedMethodsAndPrefixes.ValidatePrefix}{paramNum}{NameUtils.CapitalizeName(actionMethod.Name)}";
var declaringType = actionMethod.DeclaringType;
var targetType = actionMethod.ContributedToType();
var parameter = actionMethod.GetParameters()[paramNum];
return FindAndAddFacetToParameterValidateMethod(declaringType, targetType, name, parameter.ParameterType, holder, metamodel);
}
public bool Filters(MethodInfo method, IClassStrategy classStrategy) => method.Name.StartsWith(RecognisedMethodsAndPrefixes.ValidatePrefix);
#endregion
}
} |
using System.Reactive.Subjects;
namespace Tel.Egram.Model.Notifications
{
public class NotificationController : INotificationController
{
public Subject<NotificationModel> Trigger { get; } = new Subject<NotificationModel>();
public void Show(NotificationModel model)
{
Trigger.OnNext(model);
}
}
} |
// NoRealm licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using NoRealm.ExpressionLite.Error;
using System;
using System.Diagnostics;
namespace NoRealm.ExpressionLite.ExpressionTree
{
/// <summary>
/// Represent a unary expression
/// </summary>
[DebuggerDisplay("{DebugHelper.Render(this), nq}")]
public class UnaryExpression : IExpression
{
/// <inheritdoc />
public NodeType NodeType { get; }
/// <inheritdoc />
public Type StaticType { get; internal set; }
/// <summary>
/// Get unary expression operand
/// </summary>
public IExpression Operand { get; internal set; }
/// <inheritdoc />
public IExpression Accept(IExpressionVisitor visitor)
=> NodeType switch
{
NodeType.UnaryMinus => visitor.VisitNegation(this),
NodeType.UnaryPlus => visitor.VisitUnaryPlus(this),
NodeType.LogicNot => visitor.VisitLogicalNot(this),
_ => throw Errors.UnknownExpressionNode.ToException(ErrorSource.Parser, NodeType)
};
internal UnaryExpression(NodeType nodeType)
=> NodeType = nodeType;
}
}
|
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License
// Copyright (c) Lokad 2010-2011, http://www.lokad.com
// This code is released as Open Source under the terms of the New BSD Licence
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace Lokad.Cqrs.Feature.AtomicStorage
{
public sealed class AtomicStorageInitialization : IEngineProcess
{
readonly IEnumerable<IAtomicStorageFactory> _storage;
readonly ISystemObserver _observer;
public AtomicStorageInitialization(IEnumerable<IAtomicStorageFactory> storage, ISystemObserver observer)
{
_storage = storage;
_observer = observer;
}
public void Dispose() {}
public void Initialize()
{
foreach (var atomicStorageFactory in _storage)
{
var folders = atomicStorageFactory.Initialize();
if (folders.Any())
{
_observer.Notify(new AtomicStorageInitialized(folders.ToArray(), atomicStorageFactory.GetType()));
}
}
}
public Task Start(CancellationToken token)
{
// don't do anything
return new Task(() => { });
}
}
} |
using TheSaga.Handlers.Events;
namespace TheSaga.Handlers.Builders
{
public interface IHandlersBuilderHandle<TEvent> : IHandlersBuilderThen
where TEvent : IHandlersEvent
{
IHandlersBuilderHandle<TEvent> HandleBy<TEventHandler>()
where TEventHandler : IHandlersCompensateEventHandler<TEvent>;
IHandlersBuilderHandle<TEvent> HandleByAsync<TEventHandler>()
where TEventHandler : IHandlersCompensateEventHandler<TEvent>;
}
}
|
namespace CryptoDNS.Models
{
public class MasternodeEntry
{
public string IP { get; set; }
public int Version { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plugin.LocalNotification;
using Xamarin.Forms;
namespace LocalNotification.Sample
{
public partial class MainPage : ContentPage
{
private int _tapCount;
public MainPage()
{
InitializeComponent();
NotifyDatePicker.MinimumDate = DateTime.Today;
NotifyTimePicker.Time = DateTime.Now.TimeOfDay.Add(TimeSpan.FromSeconds(10));
}
private void Button_Clicked(object sender, EventArgs e)
{
_tapCount++;
var list = new List<string>
{
typeof(NotificationPage).FullName,
_tapCount.ToString()
};
var notifyDateTime = NotifyDatePicker.Date.Add(NotifyTimePicker.Time);
if (notifyDateTime <= DateTime.Now)
{
notifyDateTime = DateTime.Now.AddSeconds(10);
}
var serializeReturningData = ObjectSerializer<List<string>>.SerializeObject(list);
var notification = new NotificationRequest
{
NotificationId = 100,
Title = "Test",
Description = $"Tap Count: {_tapCount}",
BadgeNumber = _tapCount,
ReturningData = serializeReturningData,
NotifyTime = UseNotifyTimeSwitch.IsToggled ? notifyDateTime : (DateTime?) null // if not specified notification will show immediately.
};
NotificationCenter.Current.Show(notification);
}
}
}
|
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using Datagrams.AbstractTypes;
using tools;
using UnityEngine;
namespace Udp.UdpConnector
{
public class UdpDataListener
{
public event Action<AbstractDatagram> OnDataRetrieved;
private UdpClient _client;
public UdpDataListener(UdpClient client)
{
_client = client;
ExeListen();
}
public void Stop()
{
_client = null;
}
private void ExeListen()
{
Task.Run(async () => { await Listening(); });
}
private async Task Listening()
{
while (_client != null)
{
try
{
var result = await _client.ReceiveAsync();
var abstractDatagram = BinarySerializer.Deserialize<AbstractDatagram>(result.Buffer);
OnDataRetrieved?.Invoke(abstractDatagram);
}
catch (Exception e)
{
throw e;
Debug.Log("Exception Occurs: " + e + "Listening Continued");
ExeListen();
break;
}
}
}
}
}
|
using SFML.Graphics;
namespace BlackCoat.ParticleSystem
{
/// <summary>
/// Abstract base class of all pixel based Particles.
/// </summary>
/// <seealso cref="BlackCoat.ParticleSystem.ParticleBase" />
public abstract class PixelParticleBase : ParticleBase
{
// CTOR ############################################################################
/// <summary>
/// Initializes a new instance of the <see cref="PixelParticleBase"/> class.
/// </summary>
/// <param name="core">The Engine core.</param>
public PixelParticleBase(Core core) : base(core)
{
}
// Methods #########################################################################
/// <summary>
/// Resets the used vertices into a neutral/reusable state.
/// </summary>
/// <param name="vPtr">First vertex of this particle</param>
override protected unsafe void Clear(Vertex* vPtr)
{
vPtr->Color = Color.Transparent;
}
/// <summary>
/// Updates the particle with the behavior defined by inherited classes.
/// </summary>
/// <param name="deltaT">Current Frame Time.</param>
/// <param name="vPtr">First vertex of this particle</param>
/// <returns>True if the particle needs to be removed otherwise false.</returns>
override protected unsafe bool UpdateInternal(float deltaT, Vertex* vPtr)
{
vPtr->Position = _Position;
vPtr->Color = _Color; // Alpha component is updated in base class
return false;
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Din.Controllers
{
public class AdminController : BaseController
{
#region injections
#endregion injections
#region constructors
#endregion constructors
#region endpoints
[Authorize(Roles = "Admin")]
public IActionResult Index()
{
return View();
}
#endregion endpoints
}
} |
using SevenTiny.Bantina.Bankinate.Attributes;
namespace SevenTiny.Cloud.MultiTenantPlatform.Core.Entity
{
/// <summary>
/// 和对象相关的所有类型的基类,默认提供了MetaObjectId,方便公共操作
/// </summary>
public abstract class MetaObjectManageInfo: CommonInfo
{
[Column]
public int MetaObjectId { get; set; }
}
}
|
@inject IEncryptionService service
@model SupervisorModel
<div class="row summary-row-container">
<div class="col-10 offset-1">
<a asp-controller="Supervisors" asp-action="Details" asp-route-_lp="@service.Encrypt("parkId",Model.ParkId)"
class="w3-hover-text-amber w3-hover-border-amber">
<div class="d-flex flex-row justify-content-between flex-wrap m-1 p-1 card border align-items-center">
<div class="flex-column position-relative">
<h2 class="bg-light font-weight-bolder text-info shadow">@Model.ParkName Supervisor</h2>
<h4 class="alert-warning font-weight-bold">
<i class="fa fa-user"></i>
@Model.FirstName @Model.LastName
</h4>
</div>
<div class="flex-column position-relative pr-5">
<p class="rounded bg-danger text-white border-dark font-weight-bolder p-1"
style="font-size: 24px;">
<i class="fa fa-phone-square"></i> @Model.EmergencyNumber
</p>
</div>
</div>
</a>
</div>
</div> |
using IntegrationTool.Module.WriteToDynamicsCrm.SDK.Enums;
using IntegrationTool.SDK.Controls.Generic;
using IntegrationTool.SDK.Database;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntegrationTool.Module.WriteToDynamicsCrm.Logging
{
public class Logger
{
private int pagingLastRecordLogId;
private const int PAGINGSIZE = 100000000;
private IDatabaseInterface databaseInterface;
public Logger(IDatabaseInterface databaseInterface)
{
this.databaseInterface = databaseInterface;
pagingLastRecordLogId = -1;
}
public void InitializeDatabase()
{
this.databaseInterface.ExecuteNonQuery(
"CREATE TABLE [main].[tblRecordLog]( " +
"[pkRecordLogId] INTEGER PRIMARY KEY NOT NULL UNIQUE, " +
"[CombinedBusinessKey] NVARCHAR(256), " +
"[ImportMode] INT, " +
"[WriteFault] NVARCHAR(512) " +
");");
}
public void AddRecord(int record)
{
this.databaseInterface.ExecuteNonQuery(
"INSERT INTO tblRecordLog (pkRecordLogId) " +
"values (" + record.ToString() + ")");
}
public void SetBusinessKeyAndImportTypeForRecord(int record, string businessKey, ImportMode importMode)
{
this.databaseInterface.ExecuteNonQuery(
"Update tblRecordLog set CombinedBusinessKey = '" + SafeString(businessKey) + "', " +
"ImportMode=" + (int)importMode + " " +
"Where pkRecordLogId = " + record);
}
public void SetWriteFault(int record, string writeFault)
{
this.databaseInterface.ExecuteNonQuery(
"Update tblRecordLog set WriteFault = '" + SafeString(writeFault) + "' " +
"Where pkRecordLogId = " + record);
}
private string SafeString(string value)
{
value = value.Replace("'", "\"");
return value;
}
public ObservableCollection<RecordLog> ReadPagedRecords(int pageNumber)
{
ObservableCollection<RecordLog> recordLogs = new ObservableCollection<RecordLog>();
string pagingSqlCommand =
"SELECT " +
"pkRecordLogId, " +
"CombinedBusinessKey, " +
"ImportMode, " +
"WriteFault " +
"FROM tblRecordLog " +
"WHERE pkRecordLogId > " + pagingLastRecordLogId.ToString() + " " +
"ORDER BY pkRecordLogId " +
"LIMIT " + PAGINGSIZE;
DbDataReader dataReader = this.databaseInterface.ExecuteQuery(pagingSqlCommand);
while(dataReader.Read())
{
RecordLog recordLog = new RecordLog();
recordLog.RecordLogId = dataReader.GetInt32(0);
recordLog.CombinedBusinessKey = dataReader.GetString(1).Replace("##", " ");
recordLog.ImportMode = "";
if(dataReader.IsDBNull(2) == false)
{
int importMode = dataReader.GetInt32(2);
recordLog.ImportMode = ((ImportMode)importMode).ToString();
}
recordLog.WriteError = dataReader.IsDBNull(3) ? "" : dataReader.GetValue(3).ToString();
recordLogs.Add(recordLog);
}
return recordLogs;
}
public static LogSummary LoadLogSummary(IDatabaseInterface databaseInterface)
{
LogSummary logSummary = new LogSummary();
object result = null;
result = databaseInterface.ExecuteScalar("Select count(*) from tblRecordLog");
logSummary.NumberOfRecordsLoaded = result == null ? -1 : Convert.ToInt32(result);
result = databaseInterface.ExecuteScalar("Select count(*) from tblRecordLog where WriteFault IS NULL");
logSummary.NumberOfSuccessfulRecords = result == null ? -1 : Convert.ToInt32(result);
result = databaseInterface.ExecuteScalar("Select count(*) from tblRecordLog where WriteFault IS NOT NULL");
logSummary.NumberOfFailedRecords = result == null ? -1 : Convert.ToInt32(result);
return logSummary;
}
}
}
|
namespace Oliviann.Tests.Extensions
{
#region Usings
using System;
using System.Collections.Generic;
using Oliviann.Common.TestObjects.Xml;
using Oliviann.IO;
using TestObjects;
using Xunit;
#endregion Usings
[Trait("Category", "CI")]
public class GenericExtensionsTests
{
#region AsLazy Tests
[Fact]
public void AsLazyTest_NullFunction()
{
Func<string> function = null;
Assert.Throws<ArgumentNullException>(() => function.AsLazy());
}
[Fact]
public void AsLazyTest_ValueFunction()
{
Func<string> function = () => "Tacos";
Lazy<string> result = function.AsLazy();
Assert.NotNull(result);
Assert.Equal("Tacos", result.Value);
}
[Fact]
public void AsLazyFromValueTest_NullValue()
{
string value = null;
Lazy<string> result = value.AsLazyFromValue();
Assert.NotNull(result);
Assert.Null(result.Value);
}
[Fact]
public void AsLazyFromValueTest_ValidValue()
{
string value = "Tacos";
Lazy<string> result = value.AsLazyFromValue();
Assert.NotNull(result);
Assert.Equal("Tacos", result.Value);
}
#endregion
#region CloneT Tests
[Fact]
public void CloneTTest_Null()
{
string nullString = null;
Assert.Throws<NullReferenceException>(() => nullString.CloneT());
}
[Fact]
public void CloneTTest_Object()
{
var orig = new MocCloneableClass
{
PropInt = 99,
PropTestClass =
{
PropInt = 100,
PropString = "Test"
}
};
var copy = orig.CloneT();
copy.PropInt = 25;
copy.PropTestClass.PropInt = 50;
copy.PropTestClass.PropString = "Hello";
Assert.Equal(99, orig.PropInt);
Assert.Equal(25, copy.PropInt);
Assert.Equal(50, orig.PropTestClass.PropInt);
Assert.Equal("Hello", orig.PropTestClass.PropString);
}
#endregion CloneT Tests
#region Copy Tests
[Fact]
public void CopyTest_Null()
{
string nullString = null;
string cpy = nullString.Copy();
}
[Fact]
public void CopyTest_NotSerializableClass()
{
var sect = new Section("Name");
Assert.Throws<ArgumentException>(() => sect.Copy());
}
[Fact]
public void CopyTest_Object()
{
var orig = new MocCloneableClass
{
PropInt = 99,
PropTestClass =
{
PropInt = 100,
PropString = "Test"
}
};
var copy = orig.Copy();
copy.PropInt = 25;
copy.PropTestClass.PropInt = 50;
copy.PropTestClass.PropString = "Hello";
Assert.Equal(99, orig.PropInt);
Assert.Equal(25, copy.PropInt);
Assert.Equal(100, orig.PropTestClass.PropInt);
Assert.Equal("Test", orig.PropTestClass.PropString);
Assert.Equal(50, copy.PropTestClass.PropInt);
Assert.Equal("Hello", copy.PropTestClass.PropString);
}
#endregion Copy Tests
#region GetSafeHashCode Tests
[Fact]
public void GetSafeHashCodeTest_Null()
{
string nullString = null;
int result = nullString.GetSafeHashCode();
Assert.Equal(0, result);
}
[Fact]
public void GetSafeHashCodeTest_String()
{
const string TestString = "Test";
const int ExpectedResult1 = -354185577;
int result = TestString.GetSafeHashCode();
if (result == ExpectedResult1)
{
Assert.Equal(result, ExpectedResult1);
return;
}
// This is to match the hash code returned on the build box. This method
// may return different results based on .NET Framework versions.
const int ExpectedResult2 = -871204762;
Assert.Equal(result, ExpectedResult2);
}
#endregion GetSafeHashCode Tests
#region GetValueOrDefault Tests
/// <summary>
/// Verifies the default result is returned when the nullable doesn't
/// have a value.
/// </summary>
[Fact]
public void GetValueOrDefaultTest_Nullable_NullSource()
{
int? source = null;
Func<int?, string> act = i => i.Value.ToString();
string result = source.GetValueOrDefault(act, "Hello");
Assert.Equal("Hello", result);
}
/// <summary>
/// Verifies the source result is returned when the nullable has a
/// value.
/// </summary>
[Fact]
public void GetValueOrDefaultTest_Nullable_ValueSource()
{
int? source = 17;
Func<int?, string> act = i => i.Value.ToString();
string result = source.GetValueOrDefault(act, "Hello");
Assert.Equal("17", result);
}
/// <summary>
/// Verifies the default result is returned for a null object.
/// </summary>
[Fact]
public void GetValueOrDefaultTest_Ref_NullSource()
{
string source = null;
Func<string, int> act = s => s.ToInt32(99);
int result = source.GetValueOrDefault(act, 241);
Assert.Equal(241, result);
}
/// <summary>
/// Verifies the source result is returned when the source is not null.
/// </summary>
[Fact]
public void GetValueOrDefaultTest_Ref_ValueSource()
{
string source = "17";
Func<string, int> act = s => s.ToInt32(99);
int result = source.GetValueOrDefault(act, 241);
Assert.Equal(17, result);
}
#endregion GetValueOrDefault Tests
#region IsDefault Tests
/// <summary>
/// Verifies a null object returns a true value.
/// </summary>
[Fact]
public void IsDefaultTest_NullValue()
{
object val = null;
bool result = val.IsDefault();
Assert.True(result);
}
/// <summary>
/// Verifies a non-null string returns a false value.
/// </summary>
[Fact]
public void IsDefaultTest_NonNullValue()
{
string val = "Hello World!";
bool result = val.IsDefault();
Assert.False(result);
}
/// <summary>
/// Verifies a default struct returns a true value.
/// </summary>
[Fact]
public void IsDefaultTest_Struct()
{
var val = new KeyValuePair<string, object>();
bool result = val.IsDefault();
Assert.True(result);
}
#endregion IsDefault Tests
#region PutList Tests
[Theory]
[InlineData(null, 1)]
[InlineData("Test", 1)]
public void PutListTest_ValidValues(string input, int expectedCount)
{
List<string> result = input.PutList();
Assert.Equal(expectedCount, result.Count);
Assert.Equal(input, result[0]);
}
[Fact]
public void PutListTest_Object()
{
var bk = new Book { Author = "Me" };
List<Book> result = bk.PutList();
Assert.Single(result);
Assert.Equal(bk.Author, result[0].Author);
}
#endregion PutList Tests
#region With Tests
[Fact]
public void ActionWith_NullObject()
{
Action<GenericMocTestClass> act = c => c.PropBool = true;
GenericMocTestClass nullObject = null;
Assert.Throws<NullReferenceException>(() => nullObject.With(act));
}
[Fact]
public void ActionWith_NullAction()
{
var mocObject = new GenericMocTestClass();
Assert.Throws<NullReferenceException>(() => mocObject.With(null));
}
[Fact]
public void ActionWith_ExecuteAction()
{
Action<GenericMocTestClass> act = c =>
{
c.PropBool = true;
c.PropInt = 100;
c.PropString = "Test";
};
var mocObject = new GenericMocTestClass();
mocObject.With(act);
Assert.True(mocObject.PropBool, "Action bool property wasn't set correctly.");
Assert.Equal(100, mocObject.PropInt);
Assert.Equal("Test", mocObject.PropString);
}
#endregion With Tests
}
} |
using JetBrains.Application;
using JetBrains.Application.Shortcuts;
using JetBrains.Application.UI.ActionsRevised.Loader;
namespace JetBrains.ReSharper.Plugins.PresentationAssistant
{
[ShellComponent]
public class OverriddenShortcutFinder
{
// This is the current key binding for the command being overridden by an action
// By definition, this is the VS key binding (because we're overriding an existing
// VS command and using its key bindings)
public virtual ActionShortcut GetOverriddenVsShortcut(IActionDefWithId def)
{
return null;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Take.Elephant.Tests
{
public abstract class GuidItemKeyValueMapQueryableStorageFacts : KeyValueMapQueryableStorageFacts<Guid, Item>
{
public override Expression<Func<KeyValuePair<Guid, Item>, bool>> CreateFilter(KeyValuePair<Guid, Item> value)
{
var randomGuid = Guid.NewGuid();
return
i =>
i.Key != randomGuid &&
i.Key.Equals(value.Key) &&
i.Value.GuidProperty == value.Value.GuidProperty &&
i.Value.IntegerProperty.Equals(value.Value.IntegerProperty) &&
i.Value.IntegerProperty != -11241213 &&
i.Value.StringProperty.Equals(value.Value.StringProperty);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace RadonTestsManager.Controllers {
public class ContinuousRadonMonitorDTO {
[Required]
[Range(0, 99999999)]
public int MonitorNumber { get; set; }
[Required]
[Range(0, 99999999)]
public int SerialNumber { get; set; }
public DateTime LastCalibrationDate { get; set; }
public DateTime PurchaseDate { get; set; }
public DateTime LastBatteryChangeDate { get; set; }
public DateTime TestStart { get; set; }
public DateTime? TestFinish { get; set; }
[MaxLength(255)]
public string Status { get; set; }
}
} |
using System.Collections.Generic;
using System.Linq;
namespace ACSE.Core.Modifiable
{
public class ModifiedHandler : IModifiable
{
public readonly Stack<IModifiable> UndoStack;
public readonly Stack<IModifiable> RedoStack;
public ModifiedHandler()
{
UndoStack = new Stack<IModifiable>();
RedoStack = new Stack<IModifiable>();
}
// Undo & Redo logic
public void Undo()
{
if (UndoStack.Any()) return;
var previousChange = UndoStack.Pop();
RedoStack.Push(previousChange);
previousChange.Undo();
}
public void Redo()
{
if (!RedoStack.Any()) return;
var previousChange = RedoStack.Pop();
UndoStack.Push(previousChange);
previousChange.Redo();
}
public void NewChange(object change)
{
RedoStack.Clear();
if (!(change is IModifiable modifier)) return;
UndoStack.Push(modifier);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Novel.Common.Models
{
public class SearchResult
{
public string Caption { get; set; }
public List<SearchResultContent> Contents { get; set; }
}
public class SearchResultContent
{
public string Title { get; set; }
public string NovelUrl { get; set; }
public string Newest { get; set; }
public string NewestUrl { get; set; }
public string Author { get; set; }
public string WordSize { get; set; }
public string UpdateTime { get; set; }
public string Status { get; set; }
}
}
|
/*
* FileName: ITreeNode.cs
* Author: functionghw<functionghw@hotmail.com>
* CreateTime: 4/9/2015 3:25:00 PM
* Version: v1.0
* Description:
* */
namespace HelperLibrary.Core.Tree
{
using System.Collections.Generic;
/// <summary>
/// Interface of a simply tree structure
/// </summary>
/// <typeparam name="T">element type</typeparam>
public interface ITreeNode<T>
{
/// <summary>
/// Gets or sets the value of this node
/// </summary>
T Value { get; set; }
/// <summary>
/// Gets the parent node of this node.
/// </summary>
TreeNode<T> Parent { get; }
/// <summary>
/// Gets children node list of this node.
/// </summary>
IList<TreeNode<T>> Children { get; }
/// <summary>
/// Check if this node has any child.
/// </summary>
/// <returns>true if has one or more children, otherwise false.</returns>
bool HasChildren();
/// <summary>
/// Check if the specific node is a child of this node.
/// </summary>
/// <param name="child">the node to check</param>
/// <returns>true if the given node is a child of this node, otherwise false.</returns>
bool ContainsChild(TreeNode<T> child);
/// <summary>
/// Add a given node to this node's children list.
/// </summary>
/// <param name="child">the node to add</param>
void AddChild(TreeNode<T> child);
/// <summary>
/// Remove a specific child from this node's children list.
/// </summary>
/// <param name="child">the node to remove</param>
void RemoveChild(TreeNode<T> child);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class GameManager : MonoBehaviour
{
public bool gameOver;
public bool levelCompleted;
public GameObject gameOverPanel;
public GameObject levelCompletedPanel;
public int currentLevel;
public Slider gameProgressSlider;
public int currentLevelIndex;
public TextMeshProUGUI currentLevelText;
public TextMeshProUGUI NextLevelText;
public int numberOfPassedRings;
public int progress;
// Start is called before the first frame update
private void Awake()
{
currentLevelIndex = PlayerPrefs.GetInt("CurrentLevelIndex",1);
}
void Start()
{
numberOfPassedRings = 0;
Time.timeScale = 1;
// gameOver = levelCompleted = false;
}
// Update is called once per frame
void Update()
{
currentLevelText.text = currentLevelIndex.ToString();
NextLevelText.text = (currentLevelIndex+1).ToString();
progress = numberOfPassedRings * 100 / FindObjectOfType<Manager>().numberRings;
gameProgressSlider.value = progress;
if (gameOver)
{
Time.timeScale = 0;
gameOverPanel.SetActive(true);
if (Input.GetButtonDown("Fire1"))
{
SceneManager.LoadScene(0);
currentLevelIndex = 0;
currentLevelText.text = currentLevelIndex.ToString();
currentLevel = 0;
}
}
if(levelCompleted == true)
{
levelCompletedPanel.SetActive(true);
Time.timeScale = 0;
if (Input.GetButtonDown("Fire1"))
{
PlayerPrefs.SetInt("CurrentLevelIndex", currentLevelIndex + 1);
SceneManager.LoadScene(0);
}
}
}
}
|
using Editions;
using Ship;
namespace SquadBuilderNS
{
public class ShipRecord
{
public GenericShip Instance { get; }
public string ShipName => Instance.ShipInfo.ShipName;
public string ShipNameCanonical => Instance.ShipTypeCanonical;
public string ShipNamespace { get; }
public ShipRecord(string shipNamespace)
{
ShipNamespace = shipNamespace;
// shipTypeNameFull must have format like Ship.SecondEdition.XWing.XWing
string shipTypeNameFull = shipNamespace + shipNamespace.Substring(shipNamespace.LastIndexOf('.'));
Instance = (GenericShip) System.Activator.CreateInstance(System.Type.GetType(shipTypeNameFull));
Edition.Current.AdaptShipToRules(Instance);
}
}
}
|
using System;
using Acme.Common;
using NUnit.Framework;
namespace Acme.CommonTestsNUnit
{
[TestFixture()]
public class LoggingServiceTests
{
[Test()]
public void LogAction_Success()
{
// Arrange
var expected = "Action: Test Action";
// Act
var actual = LoggingService.LogAction("Test Action");
// Assert
Assert.AreEqual(expected, actual);
}
}
}
|
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace BepuPhysics.CollisionDetection
{
/// <summary>
/// Packed indirection to data associated with a pair cache entry.
/// </summary>
public struct PairCacheIndex
{
internal ulong packed;
/// <summary>
/// Gets whether this index actually refers to anything. The Type and Index should only be used if this is true.
/// </summary>
public bool Exists
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (packed & (1UL << 63)) > 0; }
}
/// <summary>
/// Gets whether this index refers to an active cache entry. If false, the entry exists in an inactive set.
/// </summary>
public bool Active
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (packed & (1UL << 62)) > 0; }
}
/// <summary>
/// Gets the index of the cache that owns the entry.
/// </summary>
public int Cache
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (int)(packed >> 38) & 0x3FFFFF; } //24 bits
}
/// <summary>
/// Gets the type index of the object.
/// </summary>
public int Type
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (int)(packed >> 30) & 0xFF; } //8 bits
}
/// <summary>
/// Gets the index of the object within the type specific list.
/// </summary>
public int Index
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (int)(packed & 0x3FFF_FFFF); } //30 bits
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public PairCacheIndex(int cache, int type, int index)
{
Debug.Assert(cache >= 0 && cache < (1 << 24), "Do you really have that many threads, or is the index corrupt?");
Debug.Assert(type >= 0 && type < (1 << 8), "Do you really have that many type indices, or is the index corrupt?");
//Note the inclusion of a set bit in the most significant 2 bits.
//The MSB encodes that the index was explicitly constructed, so it is a 'real' reference.
//A default constructed PairCacheIndex will have a 0 in the MSB, so we can use the default constructor for empty references.
//The second most significant bit sets the active flag. This constructor is used only by active references.
packed = (ulong)((3L << 62) | ((long)cache << 38) | ((long)type << 30) | (long)index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PairCacheIndex CreateInactiveReference(int cache, int type, int index)
{
Debug.Assert(cache >= 0 && cache < (1 << 24), "Do you really have that many sets, or is the index corrupt?");
Debug.Assert(type >= 0 && type < (1 << 8), "Do you really have that many type indices, or is the index corrupt?");
//Note the inclusion of a set bit in the most significant 2 bits.
//The MSB encodes that the index was explicitly constructed, so it is a 'real' reference.
//A default constructed PairCacheIndex will have a 0 in the MSB, so we can use the default constructor for empty references.
//The second most significant bit is left unset. This function creates only inactive references..
PairCacheIndex toReturn;
toReturn.packed = (ulong)((1L << 63) | ((long)cache << 38) | ((long)type << 30) | (long)index);
return toReturn;
}
public override string ToString()
{
return $"{{{Cache}, {Type}, {Index}}}";
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Clide
{
public class SolutionExtensionsSpec
{
ISolutionExplorer explorer;
public SolutionExtensionsSpec()
{
var solution = new FakeSolution
{
Nodes =
{
new FakeSolutionFolder("Solution Items")
{
Nodes =
{
new FakeSolutionItem("Readme.md"),
}
},
new FakeSolutionFolder("CSharp")
{
Nodes =
{
new FakeProject("CsConsole")
{
Nodes =
{
new FakeItem("Class1.cs"),
}
}
}
},
new FakeSolutionFolder("VB")
{
Nodes =
{
new FakeProject("VbConsole")
{
Nodes =
{
new FakeItem("Class1.vb"),
}
}
}
},
}
};
explorer = new FakeSolutionExplorer
{
Solution = Awaitable.Create<ISolutionNode>(async () => solution)
};
}
[Fact]
public async Task when_getting_relative_path_from_class_to_solution_folder_then_makes_relative_path()
{
var c = (await explorer.Solution).Nodes.Traverse(TraverseKind.DepthFirst, node => node.Nodes)
.OfType<IItemNode>().First(i => i.Name == "Class1.cs");
var f = (await explorer.Solution).Nodes.Traverse(TraverseKind.DepthFirst, node => node.Nodes)
.OfType<FakeSolutionFolder>().First(i => i.Name == "CSharp");
var path = c.RelativePathTo(f);
Assert.Equal("CsConsole\\Class1.cs", path);
}
[Fact]
public async Task when_ancestor_node_is_not_ancestor_then_throws_arguement_exception()
{
var c = (await explorer.Solution).Nodes.Traverse(TraverseKind.DepthFirst, node => node.Nodes)
.OfType<IItemNode>().First(i => i.Name == "Class1.cs");
var f = (await explorer.Solution).Nodes.Traverse(TraverseKind.DepthFirst, node => node.Nodes)
.OfType<FakeSolutionFolder>().First(i => i.Name == "VB");
Assert.Throws<ArgumentException>(() => c.RelativePathTo(f));
}
[Fact]
public async Task when_getting_relative_path_from_solution_item_to_solution_then_makes_relative_path()
{
var c = (await explorer.Solution).Nodes.Traverse(TraverseKind.DepthFirst, node => node.Nodes)
.OfType<ISolutionItemNode>().First();
var path = c.RelativePathTo((await explorer.Solution));
Assert.Equal("Solution Items\\Readme.md", path);
}
[Fact]
public async Task when_getting_relative_path_from_project_to_solution_then_makes_relative_path()
{
var c = (await explorer.Solution).Nodes.Traverse(TraverseKind.BreadthFirst, node => node.Nodes)
.OfType<IProjectNode>().First();
var path = c.RelativePathTo((await explorer.Solution));
Assert.Equal("CSharp\\CsConsole", path);
}
[Fact]
public async Task when_finding_all_projects_then_gets_all()
{
var projects = (await explorer.Solution).FindProjects().ToList();
Assert.Equal(2, projects.Count);
}
[Fact]
public async Task when_finding_all_projects_with_filter_then_gets_all_matches()
{
var projects = (await explorer.Solution).FindProjects(p => p.Name.Contains("Console")).ToList();
Assert.Equal(2, projects.Count);
}
[Fact]
public async Task when_finding_project_then_can_filter_by_name()
{
var project = (await explorer.Solution).FindProject(p => p.Name == "CsConsole");
Assert.NotNull(project);
}
}
}
|
using System.Text.Json;
namespace Contracts
{
public class Serializer : ISerializer
{
public T Deserialize<T>(string text) where T : class
{
return JsonSerializer.Deserialize<T>(text);
}
public string Serialize<T>(T obj) where T : class
{
return JsonSerializer.Serialize(obj);
}
}
}
|
using System.Web.UI;
[assembly: WebResource("FarsiLibrary.Web.Images.OpenButton.gif", "img/gif")] |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.Interfaced;
using SlimHttp.Interface;
namespace SlimHttp.Program.Client
{
internal class Program
{
private static void Main(string[] args)
{
var requestWaiter = new SlimRequestWaiter { Root = new Uri("http://localhost:9000") };
// Greeter
Console.WriteLine("\n*** Greeter ***");
var greeter = new GreeterRef(new SlimActorTarget("greeter"), requestWaiter, null);
PrintResult(greeter.Greet("World"));
PrintResult(greeter.Greet("Actor"));
PrintResult(greeter.GetCount());
// Calculator
Console.WriteLine("\n*** Calculator ***");
var calculator = new CalculatorRef(new SlimActorTarget("calculator"), requestWaiter, null);
PrintResult(calculator.Concat("Hello", "World"));
PrintResult(calculator.Concat(null, "Error"));
PrintResult(calculator.Sum(1, 2));
// Counter
Console.WriteLine("\n*** Counter ***");
var counter = new CounterRef(new SlimActorTarget("counter"), requestWaiter, null);
counter.IncCounter(1);
counter.IncCounter(2);
counter.IncCounter(3);
PrintResult(counter.GetCounter());
// Pedantic
Console.WriteLine("\n*** Pedantic ***");
var pedantic = new PedanticRef(new SlimActorTarget("pedantic"), requestWaiter, null);
pedantic.TestCall().Wait();
PrintResult(pedantic.TestOptional(null));
PrintResult(pedantic.TestOptional(1));
PrintResult(pedantic.TestTuple(Tuple.Create(1, "One")));
PrintResult(pedantic.TestParams(1, 2, 3));
PrintResult(pedantic.TestPassClass(new TestParam { Name = "Mouse", Price = 10 }));
PrintResult(pedantic.TestReturnClass(1, 2));
}
private static void PrintResult<TResult>(Task<TResult> task)
{
try
{
Console.WriteLine("Result: " + task.Result);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
}
|
using System;
namespace Global {
public enum ObjectType {
TREE,
WATER,
BUILDING,
PAVEMENT,
GRASS
}
public static class ObjectTypeImplementation {
public static bool AllowsVision(this ObjectType self) {
switch (self) {
case ObjectType.TREE:
case ObjectType.BUILDING:
return false;
default:
return true;
}
}
public static bool AllowsMovement(this ObjectType self) {
switch (self) {
case ObjectType.BUILDING:
case ObjectType.WATER:
return false;
default:
return true;
}
}
}
} |
using System;
using System.Diagnostics;
namespace AndcultureCode.CSharp.Testing.Factories
{
public abstract class Factory
{
#region Public Methods
/// <summary>
/// Define your factory
/// </summary>
public abstract void Define();
public long Milliseconds => DateTimeOffset.Now.ToUnixTimeMilliseconds();
public long UniqueNumber
{
get
{
long nano = 10000L * Stopwatch.GetTimestamp();
nano /= TimeSpan.TicksPerMillisecond;
nano *= 100L;
return nano;
}
}
#endregion
}
} |
namespace TraktNet.Objects.Basic.Tests.Json.Reader
{
using FluentAssertions;
using System;
using System.Threading.Tasks;
using Trakt.NET.Tests.Utility.Traits;
using TraktNet.Objects.Basic.Json.Reader;
using Xunit;
[Category("Objects.Basic.JsonReader")]
public partial class IdsObjectJsonReader_Tests
{
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Complete()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_COMPLETE);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_1()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_1);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_2()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_2);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_3()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_3);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_4()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_4);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_5()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_5);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_6()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_6);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_7()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_7);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_8()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_8);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_9()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_9);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_10()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_10);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_11()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_11);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Incomplete_12()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_INCOMPLETE_12);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_1()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_1);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_2()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_2);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_3()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_3);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_4()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_4);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_5()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_5);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().Be(24493U);
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_6()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_6);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(1390);
traktIds.Slug.Should().Be("game-of-thrones");
traktIds.Tvdb.Should().Be(121361U);
traktIds.Imdb.Should().Be("tt0944947");
traktIds.Tmdb.Should().Be(1399U);
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Not_Valid_7()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(JSON_NOT_VALID_7);
traktIds.Should().NotBeNull();
traktIds.Trakt.Should().Be(0);
traktIds.Slug.Should().BeNull();
traktIds.Tvdb.Should().BeNull();
traktIds.Imdb.Should().BeNull();
traktIds.Tmdb.Should().BeNull();
traktIds.TvRage.Should().BeNull();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Null()
{
var jsonReader = new IdsObjectJsonReader();
Func<Task<ITraktIds>> traktIds = () => jsonReader.ReadObjectAsync(default(string));
await traktIds.Should().ThrowAsync<ArgumentNullException>();
}
[Fact]
public async Task Test_IdsObjectJsonReader_ReadObject_From_Json_String_Empty()
{
var jsonReader = new IdsObjectJsonReader();
var traktIds = await jsonReader.ReadObjectAsync(string.Empty);
traktIds.Should().BeNull();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Sirenix.OdinInspector;
namespace Procedural
{
[ExecuteInEditMode]
public class RandomizeColor : MonoBehaviour
{
// Start is called before the first frame update
//private void Start()
//{
// ChangeAleaColor();
//}
[Button(ButtonSizes.Gigantic)]
void ChangeAleaColor()
{
Random.InitState((int)System.DateTime.Now.Ticks);
GetComponent<MeshRenderer>().sharedMaterial.color = Random.ColorHSV();
//Debug.Log("Done");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class ChaseTarget : MonoBehaviour
{
NavMeshAgent navMeshAgent;
public GameObject target;
[Tooltip("Won't chase target if they're closer than this, leave at 0 to ignore.")]
public float MinChaseDistance = 0;
[Tooltip("Won't chase target if they're further than this, leave at 0 to ignore.")]
public float MaxChaseDistance = 0;
[Tooltip("How many seconds inbetween destination updates.")]
public float UpdateFrequency = 0.1f;
float updateTracker = 0;
// Start is called before the first frame update
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
if (navMeshAgent == null)
Debug.LogWarning("No nav mesh agent");
}
// Update is called once per frame
void Update()
{
if(target == null)
{
var player = FindObjectOfType<Player>();
if(player != null)
target = player.gameObject;
}
if (target == null)
return;
updateTracker += Time.deltaTime;
if (updateTracker < UpdateFrequency)
return;
updateTracker = 0;
bool tooClose = false, tooFar = false;
float distance = Vector3.Distance(this.transform.position, target.transform.position);
if (distance > MaxChaseDistance && MaxChaseDistance != 0)
tooFar = true;
if (distance < MinChaseDistance && MinChaseDistance != 0)
tooClose = true;
if(tooClose || tooFar)
{
if (navMeshAgent.hasPath)
navMeshAgent.ResetPath();
return;
}
if (navMeshAgent.isOnNavMesh)
navMeshAgent.destination = target.transform.position;
}
}
|
using Newtonsoft.Json;
namespace YouTrackSharp.AgileBoards
{
/// <summary>
/// A class that represents a YouTrack field used in the context of an agile board
/// </summary>
public class Field
{
/// <summary>
/// Gets or sets the name of the field
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the localized name of the field
/// </summary>
[JsonProperty("localizedName")]
public string LocalizedName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OAuth2Provider
{
public interface IConsumer
{
string ClientId { get; }
string Secret { get; }
long ConsumerId { get; }
string ApplicationName { get; }
string Domain { get; }
string RedirectUrl { get; }
bool IsEnabled { get; }
}
}
|
using System.Collections.Generic;
namespace App.Models.Spotify
{
public class SpotifyData
{
public SpotifyDataVersion Version { get; set; }
public string UserId { get; set; }
public string DisplayName { get; set; }
public List<SpotifyPlaylist> Playlists { get; set; }
public List<SpotifyPlaylistTrack> Tracks { get; set; }
public List<string> FollowPlaylists { get; set; }
public SpotifyData()
{
Playlists = new List<SpotifyPlaylist>();
Tracks = new List<SpotifyPlaylistTrack>();
FollowPlaylists = new List<string>();
Version = SpotifyDataVersion.VERSION_1;
}
}
} |
using UnityEditor;
using UnityEditor.MARS.Simulation;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.MARS.Rules.RulesEditor
{
class ProxyRow : EntityRow
{
const string k_ProxyRowPath = k_Directory + "ProxyRow.uxml";
const string k_SimMatchCountName = "simMatchCount";
const string k_ContentContainerName = "contentContainer";
const string k_AddButtonProxyAnalyticsLabel = "Margin add button (Proxy row)";
Transform m_Transform;
Transform m_SimulatedObject;
Label m_SimMatchCount;
internal override Transform ContainerObject => m_Transform;
internal override GameObject BackingObject => m_Entity.gameObject;
public ProxyRow(Proxy proxy)
{
m_Entity = proxy;
m_Transform = m_Entity.transform;
m_SimulatedObject = SimulatedObjectsManager.instance.GetCopiedTransform(m_Transform);
SetupUI();
}
protected sealed override void SetupUI()
{
var proxyRowAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_ProxyRowPath);
proxyRowAsset.CloneTree(this);
base.SetupUI();
SetupProxyPresetUI(m_Entity);
m_ProxyField.value = m_Entity;
m_SimMatchCount = this.Q<Label>(k_SimMatchCountName);
if (m_SimulatedObject == null)
m_SimMatchCount.style.display = DisplayStyle.None;
m_ContentContainer = this.Q<VisualElement>(k_ContentContainerName);
m_ContentRows = new ContentRow[m_Transform.childCount];
for (int i = 0; i < m_Transform.childCount; i++)
{
var child = m_Transform.GetChild(i);
if (!ContentRow.IsApplicableToTransform(child))
continue;
var contentRow = new ContentRow(m_Transform, child);
m_ContentContainer.Add(contentRow);
m_ContentRows[i] = contentRow;
}
CreateAddContentButton();
}
internal sealed override bool HasChanged(MARSEntity entity)
{
var entityTransform = entity.transform;
if (base.HasChanged(entity) || entityTransform.childCount != m_ContentRows.Length)
return true;
for (int i = 0; i < entityTransform.childCount; i++)
{
var contentRow = m_ContentRows[i];
var content = entityTransform.GetChild(i);
if (contentRow.HasChanged(content))
return true;
}
return false;
}
internal override void Select()
{
base.Select(m_Entity, m_Transform, m_Transform.gameObject);
}
protected override void OnAddButton()
{
RulesModule.AddContent(m_Entity.transform);
EditorEvents.RulesUiUsed.Send(new RuleUiArgs
{
label = k_AddButtonProxyAnalyticsLabel
});
}
}
}
|
namespace Smart.IO.ByteMapper.Expressions
{
using Smart.IO.ByteMapper.Builders;
internal sealed class MapByteExpression : IMemberMapExpression
{
//--------------------------------------------------------------------------------
// Expression
//--------------------------------------------------------------------------------
IMapConverterBuilder IMemberMapExpression.GetMapConverterBuilder() => ByteConverterBuilder.Default;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using XNodeEditor;
#endif
namespace InteractML.DataTypeNodes
{
/// <summary>
/// Editor class drawing a IMLVector2 Feature - receiving a Vector2 or drawing editable Vector2 field
/// </summary>
[CustomNodeEditor(typeof(Vector2Node))]
public class Vector2NodeEditor : IMLNodeEditor
{
/// <summary>
/// Reference to the node itself
/// </summary>
private Vector2Node m_Vector2Node;
/// <summary>
/// Initialise node specific interface values
/// </summary>
public override void OnCreate()
{
// Get reference to the current node
m_Vector2Node = (target as Vector2Node);
// Initialise node name
NodeName = "VECTOR2";
// Initialise node body height
m_BodyRect.height = 110;
nodeSpace = 110;
// Initialise input port labels
InputPortsNamesOverride = new Dictionary<string, string>();
base.InputPortsNamesOverride.Add("m_In", "Vector2\nData In");
// Initialise output port labels
OutputPortsNamesOverride = new Dictionary<string, string>();
base.OutputPortsNamesOverride.Add("m_Out", "Vector2\nData Out");
// Initialise node tooltips
base.nodeTips = m_Vector2Node.tooltips;
// Initialise axis labels
feature_labels = new string[2] { "x: ", "y: " };
}
/// <summary>
/// Draws node specific body fields
/// </summary>
protected override void ShowBodyFields()
{
// draws each feature in the node
DataTypeNodeEditorMethods.DrawFeatureOrEditableFields(this, m_Vector2Node, m_BodyRect);
}
}
}
|
using System;
using System.Collections.Generic;
namespace ExtraDomainEvent.Abstractions
{
/// <summary>
/// Defines a publisher for domain-event(s).
/// </summary>
public interface IDomainEventPublisher : IDisposable
{
/// <summary>
/// Publishes a domain-event.
/// </summary>
/// <param name="event">The instance of domain-event.</param>
void Publish(IDomainEvent @event);
/// <summary>
/// Publishes multiple domain-events.
/// </summary>
/// <param name="events">The collection of domain-events to handle.</param>
void Publish(IEnumerable<IDomainEvent> events);
/// <summary>
/// Removes all domain-events waiting to be handled.
/// </summary>
void ClearEvents();
/// <summary>
/// Removes a domain-event from the collection.
/// </summary>
/// <param name="event"></param>
/// <returns></returns>
bool RemoveEvent(IDomainEvent @event);
/// <summary>
/// Get all domain-events waiting to be handled.
/// </summary>
/// <returns>The collection of domain-events waiting to handle.</returns>
IEnumerable<IDomainEvent> GetEvents();
}
} |
namespace JQDT.Exceptions
{
using System;
using JQDT.Enumerations;
/// <summary>
/// Thrown when try to perform operation on a type that is not valid for it.
/// </summary>
/// <seealso cref="JQDT.Exceptions.JQDataTablesException" />
[Serializable]
internal class InvalidTypeForOperationException : JQDataTablesException
{
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTypeForOperationException"/> class.
/// </summary>
public InvalidTypeForOperationException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTypeForOperationException"/> class.
/// </summary>
/// <param name="message">The message.</param>
public InvalidTypeForOperationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTypeForOperationException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public InvalidTypeForOperationException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidTypeForOperationException"/> class.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="operation">The operation.</param>
public InvalidTypeForOperationException(Type type, OperationTypesEnum operation)
: this($"Invalid type {type.FullName} for {operation.ToString()} operation.")
{
}
}
} |
// Copyright (c) Jeremy Likness. All rights reserved.
// Licensed under the MIT License. See LICENSE in the repository root for license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NovaFetch.Api;
using NovaFetch.Model;
namespace NovaFetch
{
/// <summary>
/// Main engine to drive the process.
/// </summary>
public class Engine
{
private readonly TokenManager tokenManager;
private readonly Configuration config;
private readonly INovaApi api;
/// <summary>
/// Initializes a new instance of the <see cref="Engine"/> class.
/// </summary>
/// <param name="manager">The <see cref="TokenManager"/>.</param>
/// <param name="configuration">The configuration.</param>
public Engine(TokenManager manager, Configuration configuration)
{
tokenManager = manager;
config = configuration;
api = new NovaApi(manager);
}
/// <summary>
/// Run the engine.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task RunAsync()
{
try
{
if (await LoginAsync())
{
ShowConfig();
if (!config.ExistingJob)
{
await UploadAsync();
}
if (!config.SubmitOnly)
{
var result = await JobStatusAsync();
if (result.Stage != Stages.Calibrated)
{
Console.WriteLine("Failed to plate solve.");
return;
}
var jobId = result.Jobs[0].Value;
config.SetJob(jobId.ToString());
await DownloadFilesAsync(jobId);
await DownloadCalibrationAsync(jobId);
Console.WriteLine("Final tasks...");
Console.WriteLine("Copying original file...");
var tgtPath = Path.Combine(config.TargetDirectory, $"{config.Name}.jpg");
File.Copy(config.FilePath, tgtPath);
Console.WriteLine("Creating thumbnail...");
var image = Image.FromFile(tgtPath);
var ratio = image.Width / 256;
int height = image.Height / ratio;
var thumb = image.GetThumbnailImage(256, height, null, IntPtr.Zero);
var thumbPath = Path.Combine(config.TargetDirectory, "thumb.jpg");
thumb.Save(thumbPath);
}
Console.WriteLine("Done.");
}
}
catch (Exception ex)
{
Console.WriteLine("Oops! Something unexpected happened.");
Console.WriteLine($"The error: {ex.Message}.");
throw;
}
}
private static string DegreesToRA(double deg)
{
var h = 0;
double v = 360.0 / 24;
while (deg >= v)
{
h++;
deg -= v;
}
var m = 0;
v = 15.0 / 60;
while (deg >= v)
{
m++;
deg -= v;
}
var s = 0;
v = 0.25 / 60;
while (deg >= v)
{
s++;
deg -= v;
}
var ds = 0;
v = 0.25 / 60 / 10;
while (deg >= v)
{
ds++;
deg -= v;
}
return $"{h}h {m}m {s}.{ds}s";
}
private static string DecToDegrees(double dec)
{
var sign = dec < 0 ? "-" : "+";
dec = Math.Abs(dec);
var degrees = Math.Floor(dec);
var remainder = dec - degrees;
var arcmin = remainder * 60;
var arcminValue = Math.Floor(arcmin);
var arcminDisplay = arcminValue < 10 ? $"0{(int)arcminValue}" : ((int)arcminValue).ToString();
remainder = arcmin - arcminValue;
var arcseconds = Math.Round(remainder * 60, 3);
return $"{sign}{(int)degrees}° {arcminDisplay}' {arcseconds}";
}
private async Task DownloadCalibrationAsync(int jobId)
{
var calibration = await api.GetCalibrationDataAsync(jobId.ToString());
var objects = await api.GetObjectsAsync(jobId.ToString());
var dataFile = new List<string>
{
"---",
$"title: \"{config.Name}\"",
"type:",
"tags: [" +
string.Join(",", objects.Objects.Select(o => $"\"{o}\"").ToArray()) +
"]",
"description:",
$"image: /assets/images/gallery/{config.Name}/thumb.jpg",
"telescope: Stellina",
"length: \"400mm\"",
"aperture: \"80mm\"",
$"folder: {config.TargetDirectory.Split(Path.DirectorySeparatorChar)[^1]}",
"exposure: ",
"lights: ",
"sessions: ",
"firstCapture: ",
"lastCapture:",
$"ra: \"{DegreesToRA(calibration.RightAscension)}\"",
$"dec: \"{DecToDegrees(calibration.Declination)}\"",
$"size: \"{Math.Round(calibration.Width / 60, 3)} x {Math.Round(calibration.Height / 60, 3)} arcmin\"",
$"radius: \"{Math.Round(calibration.Radius, 3)} deg\"",
$"scale: \"{Math.Round(calibration.PixelScale, 3)} arcsec/pixel\"",
"---",
};
var fileName = Path.Combine(config.TargetDirectory, $"{config.Name}.md");
Console.WriteLine(string.Join(Environment.NewLine, dataFile));
Console.WriteLine($"Writing data to {fileName}");
await File.WriteAllLinesAsync(fileName, dataFile);
}
private async Task DownloadFilesAsync(int jobId)
{
Console.WriteLine("Downloading result files...");
var files = new (string src, string tgt)[]
{
("annotated_display", "-annotated"),
("grid_display", "-grid"),
("annotated_full", "-annotated-fs"),
};
foreach (var (src, tgt) in files)
{
var tgtFileName = $"{config.Name}{tgt}.jpg";
var tgtPath = Path.Combine(config.TargetDirectory, tgtFileName);
Console.WriteLine($"Downloading {tgtFileName}...");
await api.DownloadImageAsync(jobId.ToString(), src, tgtPath);
}
}
private async Task<StatusResponse> JobStatusAsync()
{
Console.WriteLine($"Getting status for job {config.JobId}...");
var done = false;
StatusResponse status = null;
Stages stage = Stages.None;
var timeOut = DateTime.Now.AddMinutes(15);
while (!done && DateTime.Now < timeOut)
{
status = await api.CheckStatusAsync(config.JobId);
done = status.Stage == Stages.Calibrated;
if ((int)status.Stage > (int)stage)
{
stage = status.Stage;
Console.WriteLine($"{Environment.NewLine}{stage}");
}
Thread.Sleep(1000);
Console.Write(".");
}
// wind-down an extra 10 seconds
Thread.Sleep(10000);
return status;
}
private async Task UploadAsync()
{
Console.WriteLine($"Uploading {config.FilePath} to Nova...");
await api.UploadFileAsync(config);
}
/// <summary>
/// Perform the login to retrieve the session.
/// </summary>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
private async Task<bool> LoginAsync()
{
var result = await api.LoginAsync();
if (result)
{
Console.WriteLine($"Established session with id {tokenManager.Session}.");
}
return result;
}
private void ShowConfig()
{
if (!config.ExistingJob)
{
Console.WriteLine($"Target file: {Path.GetFileName(config.FilePath)}");
}
if (!config.SubmitOnly)
{
Console.WriteLine($"Target directory: {config.TargetDirectory}");
}
}
}
}
|
using System;
using Amazon.XRay.Recorder.Core.Internal.Entities;
using Amazon.XRay.Recorder.Core.Internal.Emitters;
using Amazon.XRay.Recorder.Core.Sampling;
namespace Amazon.XRay.Recorder.Core.Strategies
{
/// <summary>
/// The default streaming strategy. It uses the total count of a segment's children subsegments as a threshold. If the threshold is breached, it uses subtree streaming to stream out.
/// </summary>
public class DefaultStreamingStrategy : IStreamingStrategy
{
/// <summary>
/// Default max subsegment size to stream for the strategy.
/// </summary>
private const long DefaultMaxSubsegmentSize = 100;
/// <summary>
/// Max subsegment size to stream fot the strategy.
/// </summary>
public long MaxSubsegmentSize { get; private set; } = DefaultMaxSubsegmentSize;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultStreamingStrategy"/> class.
/// </summary>
public DefaultStreamingStrategy() : this(DefaultMaxSubsegmentSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultStreamingStrategy"/> class.
/// </summary>
/// <param name="maxSubsegmentSize"></param>
public DefaultStreamingStrategy(long maxSubsegmentSize)
{
if(maxSubsegmentSize < 0)
{
throw new ArgumentException("maxSubsegmentSize cannot be a negative number.");
}
MaxSubsegmentSize = maxSubsegmentSize;
}
/// <summary>
/// Checks whether subsegments of the current instance of <see cref="Entity"/> should be streamed.
/// </summary>
/// <param name="entity">Instance of <see cref="Entity"/></param>
/// <returns>True if the subsegments are streamable.</returns>
public bool ShouldStream(Entity entity)
{
return entity.Sampled == SampleDecision.Sampled && entity.RootSegment != null && entity.RootSegment.Size >= MaxSubsegmentSize;
}
/// <summary>
/// Streams subsegments of instance of <see cref="Entity"/>.
/// </summary>
/// <param name="entity">Instance of <see cref="Entity"/>.</param>
/// <param name="emitter">Instance of <see cref="ISegmentEmitter"/>.</param>
public void Stream(Entity entity, ISegmentEmitter emitter)
{
lock (entity.Subsegments)
{
foreach (var next in entity.Subsegments)
{
Stream(next, emitter);
}
entity.Subsegments.RemoveAll(x => x.HasStreamed);
}
if (entity is Segment || entity.IsInProgress || entity.Reference > 0 || entity.IsSubsegmentsAdded)
{
return;
}
Subsegment subsegment = entity as Subsegment;
subsegment.TraceId = entity.RootSegment.TraceId;
subsegment.Type = "subsegment";
subsegment.ParentId = subsegment.Parent.Id;
emitter.Send(subsegment);
subsegment.RootSegment.DecrementSize();
subsegment.HasStreamed = true;
}
}
}
|
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
/* ------------------------------------------------------------------------- */
using Cube.Pdf.Ghostscript;
using NUnit.Framework;
using System;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Cube.Pdf.Converter.Tests
{
/* --------------------------------------------------------------------- */
///
/// ViewModelTest
///
/// <summary>
/// 各種 ViewModel のテスト用クラスです。
/// </summary>
///
/// <remarks>
/// 変換処理を含むテストは ConverterTest で実行しています。
/// </remarks>
///
/// <see cref="ConverterTest" />
///
/* --------------------------------------------------------------------- */
[TestFixture]
class ViewModelTest : ViewModelFixture
{
#region Tests
/* ----------------------------------------------------------------- */
///
/// MainViewModel
///
/// <summary>
/// MainViewModel の各種プロパティを確認します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void MainViewModel() => Invoke(vm =>
{
Assert.That(vm.Title, Does.StartWith(nameof(MainViewModel)));
Assert.That(vm.Title, Does.Contain(vm.Product));
Assert.That(vm.Title, Does.Contain(vm.Version));
Assert.That(vm.Version, Does.StartWith("1.0.0"));
Assert.That(vm.Uri, Is.EqualTo(new Uri("https://www.cube-soft.jp/cubepdf/")));
});
/* ----------------------------------------------------------------- */
///
/// SettingsViewModel
///
/// <summary>
/// SettingsViewModel の各種プロパティを確認します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void SettingsViewModel() => Invoke(vm =>
{
var vms = vm.Settings;
Assert.That(vms.FormatOption, Is.EqualTo(FormatOption.Pdf17));
Assert.That(vms.Resolution, Is.EqualTo(600));
Assert.That(vms.Language, Is.EqualTo(Language.Auto));
Assert.That(vms.IsAutoOrientation, Is.True, nameof(vms.IsAutoOrientation));
Assert.That(vms.IsPortrait, Is.False, nameof(vms.IsPortrait));
Assert.That(vms.IsLandscape, Is.False, nameof(vms.IsLandscape));
Assert.That(vms.Grayscale, Is.False, nameof(vms.Grayscale));
Assert.That(vms.ImageCompression, Is.True, nameof(vms.ImageCompression));
Assert.That(vms.Linearization, Is.False, nameof(vms.Linearization));
Assert.That(vms.CheckUpdate, Is.True, nameof(vms.CheckUpdate));
Assert.That(vms.EnableFormatOption, Is.True, nameof(vms.EnableFormatOption));
Assert.That(vms.EnableUserProgram, Is.False, nameof(vms.EnableUserProgram));
Assert.That(vms.SourceEditable, Is.False, nameof(vms.SourceEditable));
Assert.That(vms.SourceVisible, Is.False, nameof(vms.SourceVisible));
vms.Format = Format.Png;
Assert.That(vms.EnableFormatOption, Is.False, nameof(vms.EnableFormatOption));
vms.PostProcess = PostProcess.Others;
Assert.That(vms.EnableUserProgram, Is.True, nameof(vms.EnableUserProgram));
vms.IsPortrait = true;
Assert.That(vms.IsAutoOrientation, Is.False, nameof(vms.IsAutoOrientation));
Assert.That(vms.IsPortrait, Is.True, nameof(vms.IsPortrait));
Assert.That(vms.IsLandscape, Is.False, nameof(vms.IsLandscape));
vms.IsLandscape = true;
Assert.That(vms.IsAutoOrientation, Is.False, nameof(vms.IsAutoOrientation));
Assert.That(vms.IsPortrait, Is.False, nameof(vms.IsPortrait));
Assert.That(vms.IsLandscape, Is.True, nameof(vms.IsLandscape));
});
/* ----------------------------------------------------------------- */
///
/// MetadataViewModel
///
/// <summary>
/// MetadataViewModel の各種プロパティを確認します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void MetadataViewModel() => Invoke(vm =>
{
var vmm = vm.Metadata;
Assert.That(vmm.Title, Is.Empty, nameof(vmm.Title));
Assert.That(vmm.Author, Is.Empty, nameof(vmm.Author));
Assert.That(vmm.Subject, Is.Empty, nameof(vmm.Subject));
Assert.That(vmm.Keywords, Is.Empty, nameof(vmm.Keywords));
Assert.That(vmm.Creator, Is.EqualTo("CubePDF"));
Assert.That(vmm.Options, Is.EqualTo(ViewerOptions.OneColumn));
});
/* ----------------------------------------------------------------- */
///
/// EncryptionViewModel
///
/// <summary>
/// EncryptionViewModel の各種プロパティを確認します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void EncryptionViewModel() => Invoke(vm =>
{
var vme = vm.Encryption;
Assert.That(vme.Enabled, Is.False, nameof(vme.Enabled));
Assert.That(vme.OwnerPassword, Is.Empty, nameof(vme.OwnerPassword));
Assert.That(vme.OwnerConfirm, Is.Empty, nameof(vme.OwnerConfirm));
Assert.That(vme.OpenWithPassword, Is.False, nameof(vme.OpenWithPassword));
Assert.That(vme.UseOwnerPassword, Is.False, nameof(vme.UseOwnerPassword));
Assert.That(vme.EnableUserPassword, Is.False, nameof(vme.EnableUserPassword));
Assert.That(vme.UserPassword, Is.Empty, nameof(vme.UserPassword));
Assert.That(vme.UserConfirm, Is.Empty, nameof(vme.UserConfirm));
Assert.That(vme.AllowCopy, Is.False, nameof(vme.AllowCopy));
Assert.That(vme.AllowInputForm, Is.False, nameof(vme.AllowInputForm));
Assert.That(vme.AllowModify, Is.False, nameof(vme.AllowModify));
Assert.That(vme.AllowPrint, Is.False, nameof(vme.AllowPrint));
Assert.That(vme.EnablePermission, Is.True, nameof(vme.EnablePermission));
vme.Enabled = true;
vme.OwnerPassword = "Password";
vme.OwnerConfirm = "Password";
vme.OpenWithPassword = true;
Assert.That(vme.Enabled, Is.True, nameof(vme.Enabled));
Assert.That(vme.OpenWithPassword, Is.True, nameof(vme.OpenWithPassword));
Assert.That(vme.UseOwnerPassword, Is.False, nameof(vme.UseOwnerPassword));
Assert.That(vme.EnableUserPassword, Is.True, nameof(vme.EnableUserPassword));
Assert.That(vme.EnablePermission, Is.True, nameof(vme.EnablePermission));
vme.UseOwnerPassword = true;
Assert.That(vme.UseOwnerPassword, Is.True, nameof(vme.UseOwnerPassword));
Assert.That(vme.EnableUserPassword, Is.False, nameof(vme.EnableUserPassword));
Assert.That(vme.EnablePermission, Is.False, nameof(vme.EnablePermission));
});
/* ----------------------------------------------------------------- */
///
/// BrowseUserProgram
///
/// <summary>
/// 保存パスを選択するテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void BrowseSource() => Invoke(vm =>
{
var done = $"{nameof(BrowseSource)}_Done.pdf";
vm.Messenger.OpenFileDialog.Subscribe(e =>
{
Assert.That(e.Title, Is.EqualTo("入力ファイルを選択"));
Assert.That(e.InitialDirectory, Is.Null);
Assert.That(e.FileName, Is.Not.Null.And.Not.Empty);
Assert.That(e.Filter, Is.Not.Null.And.Not.Empty);
Assert.That(e.FilterIndex, Is.EqualTo(0));
Assert.That(e.CheckPathExists, Is.True);
e.FileName = done;
e.Result = System.Windows.Forms.DialogResult.OK;
});
vm.Settings.Language = Language.Japanese;
vm.BrowseSource();
Assert.That(vm.Settings.Source, Is.EqualTo(done));
});
/* ----------------------------------------------------------------- */
///
/// BrowseDestination
///
/// <summary>
/// 保存パスを選択するテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void BrowseDestination() => Invoke(vm =>
{
var done = $"{nameof(BrowseDestination)}_Done.pdf";
vm.Messenger.SaveFileDialog.Subscribe(e =>
{
Assert.That(e.Title, Is.EqualTo("名前を付けて保存"));
Assert.That(e.InitialDirectory, Is.Null);
Assert.That(e.FileName, Is.EqualTo(nameof(BrowseDestination)));
Assert.That(e.Filter, Is.Not.Null.And.Not.Empty);
Assert.That(e.FilterIndex, Is.EqualTo(1));
Assert.That(e.OverwritePrompt, Is.False);
Assert.That(e.CheckPathExists, Is.False);
e.FileName = done;
e.Result = System.Windows.Forms.DialogResult.OK;
});
vm.Settings.Language = Language.Japanese;
vm.BrowseDestination();
Assert.That(vm.Settings.Destination, Is.EqualTo(done));
});
/* ----------------------------------------------------------------- */
///
/// BrowseUserProgram
///
/// <summary>
/// ユーザプログラムを選択するテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void BrowseUserProgram() => Invoke(vm =>
{
var done = $"{nameof(BrowseUserProgram)}_Done.pdf";
vm.Messenger.OpenFileDialog.Subscribe(e =>
{
Assert.That(e.Title, Is.EqualTo("変換完了時に実行するプログラムを選択"));
Assert.That(e.InitialDirectory, Is.Null);
Assert.That(e.FileName, Is.Empty);
Assert.That(e.Filter, Is.Not.Null.And.Not.Empty);
Assert.That(e.FilterIndex, Is.EqualTo(0));
Assert.That(e.CheckPathExists, Is.True);
e.FileName = done;
e.Result = System.Windows.Forms.DialogResult.OK;
});
vm.Settings.Language = Language.Japanese;
vm.BrowseUserProgram();
Assert.That(vm.Settings.UserProgram, Is.EqualTo(done));
});
/* ----------------------------------------------------------------- */
///
/// Validate_OwnerPassword
///
/// <summary>
/// 管理用パスワードの入力チェック処理のテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void Validate_OwnerPassword() => Invoke(vm =>
{
vm.Settings.Language = Language.English;
vm.Encryption.Enabled = true;
vm.Encryption.OwnerPassword = nameof(Validate_OwnerPassword);
Assert.That(WaitMessage(vm), Is.True, "Timeout");
Assert.That(Message, Is.Not.Null.And.Not.Empty);
vm.Encryption.OwnerConfirm = "Dummy";
Assert.That(WaitMessage(vm), Is.True, "Timeout");
Assert.That(Message, Is.Not.Null.And.Not.Empty);
});
/* ----------------------------------------------------------------- */
///
/// Validate_UserPassword
///
/// <summary>
/// 管理用パスワードの入力チェック処理のテストを実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
[Test]
public void Validate_UserPassword() => Invoke(vm =>
{
vm.Settings.Language = Language.English;
vm.Encryption.Enabled = true;
vm.Encryption.OwnerPassword = nameof(Validate_OwnerPassword);
vm.Encryption.OwnerConfirm = nameof(Validate_OwnerPassword);
vm.Encryption.OpenWithPassword = true;
vm.Encryption.UserPassword = nameof(Validate_UserPassword);
Assert.That(WaitMessage(vm), Is.True, "Timeout");
Assert.That(Message, Is.Not.Null.And.Not.Empty);
vm.Encryption.UserConfirm = "Dummy";
Assert.That(WaitMessage(vm), Is.True, "Timeout");
Assert.That(Message, Is.Not.Null.And.Not.Empty);
});
#endregion
#region Others
/* ----------------------------------------------------------------- */
///
/// Invoke
///
/// <summary>
/// ViewModel オブジェクトを生成し、処理を実行します。
/// </summary>
///
/* ----------------------------------------------------------------- */
private void Invoke(Action<MainViewModel> action, [CallerMemberName] string name = null)
{
var args = CreateArgs(name);
var dest = Create(Combine(args, "Sample.ps"));
using (Locale.Subscribe(SetUiCulture))
using (var vm = new MainViewModel(dest, new SynchronizationContext()))
{
vm.Messenger.MessageBox.Subscribe(SetMessage);
action(vm);
}
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class MoverCapsula : MonoBehaviour {
public float velocidad=1f; //en metros por segundo
// Update is called once per frame
void Update () {
float x = Input.GetAxis("Horizontal") * Time.deltaTime * velocidad;
float z = Input.GetAxis("Vertical") * Time.deltaTime * velocidad;
transform.Translate(new Vector3(x, 0f, z));
// Vamos a menejar Input.(...)
// Aplicar Traslate a la transformada del objeto
// Ajustar la velocidad con Time.deltaTime
}
}
|
using System;
using System.Net;
using System.Net.Http;
namespace Thismaker.Aba.Client
{
[Serializable]
public class ClientException : Exception
{
public ClientException() { }
public ClientException(string message) : base(message) { }
public ClientException(Exception inner) : base(null, inner) { }
public ClientException(string message, Exception inner) : base(message, inner) { }
protected ClientException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class VersionMismatchException : ClientException
{
public VersionMismatchException() { }
public VersionMismatchException(string message) : base(message) { }
public VersionMismatchException(Exception inner) : base(inner) { }
public VersionMismatchException(string message, Exception inner) : base(message, inner) { }
protected VersionMismatchException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class ConnectionFailedException : ClientException
{
public ConnectionFailedException() { }
public ConnectionFailedException(string message) : base(message) { }
public ConnectionFailedException(Exception inner) : base(inner) { }
public ConnectionFailedException(string message, Exception inner) : base(message, inner) { }
protected ConnectionFailedException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class ExpiredTokenException : ClientException
{
public ExpiredTokenException() { }
public ExpiredTokenException(string message) : base(message) { }
public ExpiredTokenException(string message, Exception inner) : base(message, inner) { }
protected ExpiredTokenException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
[Serializable]
public class SimpleRequestException : HttpRequestException
{
public HttpStatusCode StatusCode => ResponseMessage.StatusCode;
public HttpResponseMessage ResponseMessage { get; set; }
public SimpleRequestException(HttpResponseMessage responseMessage)
{
ResponseMessage = responseMessage;
}
}
}
|
using System.Collections.Generic;
using Application.Core.Data;
namespace LMPlatform.Models
{
public class Module : ModelBase
{
public string Name
{
get;
set;
}
public string DisplayName
{
get;
set;
}
public bool Visible { get; set; }
public ModuleType ModuleType
{
get;
set;
}
public ICollection<SubjectModule> SubjectModules
{
get;
set;
}
public int Order { get; set; }
}
} |
namespace ReleaseCleaner.Input
{
using System;
using System.Text;
using IO = System.Console;
internal class Console : IConsole
{
public string ReadUsername()
{
IO.WriteLine("Please enter your Github username");
// simple ReadLine, because we don't need to mask
return IO.ReadLine();
}
// SecureString is recommended to not be used, see platform-compat/DE0001
public string ReadPassword(string username)
{
IO.WriteLine($"Please enter the Github password for {username}");
var password = new StringBuilder();
ConsoleKeyInfo keyInfo;
do
{
// true intercepts the keypress, effectively masking the password
keyInfo = IO.ReadKey(true);
if (keyInfo.Key == ConsoleKey.Backspace)
{
if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
{
password.Clear();
}
else
{
password.Remove(password.Length - 1, 1);
}
}
// for all other cases
password.Append(keyInfo.KeyChar);
} while (keyInfo.Key != ConsoleKey.Enter);
IO.WriteLine();
return password.ToString();
}
public void Write(string output)
{
IO.WriteLine(output);
}
}
} |
namespace _02.BankAccounts
{
using System;
public class MortgageAccounts : IAccounts
{
public MortgageAccounts(ICustomers customer, decimal balance, decimal interesRate)
{
this.Customer = customer;
this.Balance = balance;
this.InterestRate = interesRate;
}
public ICustomers Customer { get; set; }
public decimal Balance { get; set; }
public decimal InterestRate { get; set; }
public decimal DepositMoney(decimal money)
{
this.Balance += money;
return this.Balance;
}
public decimal CalculateInterestAmount(int numberOfMounths)
{
if (numberOfMounths < 0)
{
throw new ArgumentOutOfRangeException("Number of months must be bigger than 0!");
}
if (this.Customer is Individuals)
{
if (numberOfMounths > 6)
{
return numberOfMounths * this.InterestRate;
}
return 0;
}
else
{
if (numberOfMounths > 12)
{
return numberOfMounths * this.InterestRate;
}
return (numberOfMounths * this.InterestRate) / 2;
}
}
public decimal DrawMoney(decimal money)
{
Console.WriteLine("You cannot draw money!");
return this.Balance;
}
}
}
|
// --------------------------------------------------------------------------------------------
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// <remarks>
// Generated by IDLImporter from file nsIAccessRulesManager.idl
//
// You should use these interfaces when you access the COM objects defined in the mentioned
// IDL/IDH file.
// </remarks>
// --------------------------------------------------------------------------------------------
namespace Gecko
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.CompilerServices;
/// <summary>
///Copyright © 2015, Deutsche Telekom, Inc. </summary>
[ComImport()]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("7baedd2a-3189-4b03-b2a3-34016043b5e2")]
public interface nsIAccessRulesManager
{
/// <summary>
/// Initiates Access Rules Manager, this should perform the initial
/// reading of rules from access rule source
/// @return Promise which is resolved if init is successful or rejected
/// otherwise
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Gecko.JsVal Init();
/// <summary>
/// Retrieves all access rules.
///
/// Rules are stored in an array. Each rule contains the following properties:
/// - applet - describes an SE applet referenced by this rule. Might equal
/// to an applet AID (as a byte array), or to a wildcard "all"
/// meaning all applets.
/// - application - describes an application referenced by this rule. Might
/// be an array of developer certificate hashes (each as
/// a byte array) in which case it lists all applications
/// allowed access. Alternatively, might equal to wildcard
/// "allowed-all" or "denied-all".
///
/// Example rule format:
/// [{ applet: ALL_APPLET,
/// application: [[0x01, 0x02, ..., 0x20],
/// [0x20, 0x19, ...., 0x01]],
/// { applet: [0x00, 0x01, ..., 0x05],
/// application: ALLOW_ALL}}]
///
/// @return Promise which resolves with Array containing parsed access rules
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
Gecko.JsVal GetAccessRules();
}
/// <summary>nsIAccessRulesManagerConsts </summary>
public class nsIAccessRulesManagerConsts
{
// <summary>
//Wildcard: rule allows all applications to access an SE applet </summary>
public const ushort ALLOW_ALL = 1;
// <summary>
//Wildcard: rule denies all applications to access an SE applet </summary>
public const ushort DENY_ALL = 2;
// <summary>
//Wildcard: rule allows application(s) access to all SE applets </summary>
public const ushort ALL_APPLET = 3;
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Gpg.NET.Interop
{
internal class AnsiCharPtrMarshaler : ICustomMarshaler
{
private static readonly AnsiCharPtrMarshaler Instance = new AnsiCharPtrMarshaler();
public static ICustomMarshaler GetInstance(string cookie)
{
return Instance;
}
public object MarshalNativeToManaged(IntPtr pNativeData)
{
return Marshal.PtrToStringAnsi(pNativeData);
}
public IntPtr MarshalManagedToNative(object managedObj)
{
return IntPtr.Zero;
}
public void CleanUpNativeData(IntPtr pNativeData)
{
// It should be up to Gpg to free native strings.
// Emphasis on should - I'm not actually sure.
// Uncomment this if it turns out to be necessary after all.
//Marshal.FreeHGlobal(pNativeData);
}
public void CleanUpManagedData(object managedObj)
{
// The managed object is a string, so no further cleanup is necessary.
}
public int GetNativeDataSize()
{
return IntPtr.Size;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace KOS.Waves
{
[CreateAssetMenu(menuName = "Waves/Spawn Ruleset")]
public class SpawnRuleset : ScriptableObject
{
public float recoveryPeriod = 45f;
public float spawnSpeed = 60f;
public float spawnSpeedMultiplier = 1.15f;
public SpawnRule[] spawnRules;
public int QueueWave(ref SpawnQueue spawnQueue, int currentWave)
{
foreach (var rule in spawnRules)
{
var spawnEntry = rule.GetWave(currentWave);
spawnQueue.AddMany(spawnEntry);
}
spawnQueue.Shuffle();
return spawnQueue.Count;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Reflection;
using System.Text;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.OData;
using System.Web.Http.OData.Extensions;
using System.Web.Http.OData.Query;
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Query;
namespace NuGet.Lucene.Web.OData
{
public class NoSelectODataQueryOptions<T> : ODataQueryOptions<T>
{
private static readonly MethodInfo limitResultsGenericMethod = typeof(ODataQueryOptions).GetMethod("LimitResults");
private readonly IAssembliesResolver assembliesResolver;
public NoSelectODataQueryOptions(ODataQueryContext context, HttpRequestMessage request) : base(context, request)
{
if (request.GetConfiguration() != null)
{
assembliesResolver = request.GetConfiguration().Services.GetAssembliesResolver();
}
// fallback to the default assemblies resolver if none available.
assembliesResolver = assembliesResolver ?? new DefaultAssembliesResolver();
}
public override IQueryable ApplyTo(IQueryable query, ODataQuerySettings querySettings)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (querySettings == null)
{
throw new ArgumentNullException(nameof(querySettings));
}
var result = query;
// Construct the actual query and apply them in the following order: filter, orderby, skip, top
if (Filter != null)
{
result = Filter.ApplyTo(result, querySettings, assembliesResolver);
}
if (InlineCount != null && Request.ODataProperties().TotalCount == null)
{
long? count = InlineCount.GetEntityCount(result);
if (count.HasValue)
{
Request.ODataProperties().TotalCount = count.Value;
}
}
OrderByQueryOption orderBy = OrderBy;
// $skip or $top require a stable sort for predictable results.
// Result limits require a stable sort to be able to generate a next page link.
// If either is present in the query and we have permission,
// generate an $orderby that will produce a stable sort.
if (querySettings.EnsureStableOrdering &&
(Skip != null || Top != null || querySettings.PageSize.HasValue))
{
// If there is no OrderBy present, we manufacture a default.
// If an OrderBy is already present, we add any missing
// properties necessary to make a stable sort.
// Instead of failing early here if we cannot generate the OrderBy,
// let the IQueryable backend fail (if it has to).
orderBy = orderBy == null
? GenerateDefaultOrderBy(Context)
: EnsureStableSortOrderBy(orderBy, Context);
}
if (orderBy != null)
{
result = orderBy.ApplyTo(result, querySettings);
}
if (Skip != null)
{
result = Skip.ApplyTo(result, querySettings);
}
if (Top != null)
{
result = Top.ApplyTo(result, querySettings);
}
if (querySettings.PageSize.HasValue)
{
bool resultsLimited;
result = LimitResults(result, querySettings.PageSize.Value, out resultsLimited);
if (resultsLimited && Request.RequestUri != null && Request.RequestUri.IsAbsoluteUri && Request.ODataProperties().NextLink == null)
{
Uri nextPageLink = GetNextPageLink(Request, querySettings.PageSize.Value);
Request.ODataProperties().NextLink = nextPageLink;
}
}
return result;
}
private static OrderByQueryOption EnsureStableSortOrderBy(OrderByQueryOption orderBy, ODataQueryContext context)
{
Contract.Assert(orderBy != null);
Contract.Assert(context != null);
// Strategy: create a hash of all properties already used in the given OrderBy
// and remove them from the list of properties we need to add to make the sort stable.
var usedPropertyNames =
new HashSet<string>(orderBy.OrderByNodes.OfType<OrderByPropertyNode>().Select(node => node.Property.Name));
var propertiesToAdd = GetAvailableOrderByProperties(context).Where(prop => !usedPropertyNames.Contains(prop.Name)).ToArray();
if (propertiesToAdd.Any())
{
// The existing query options has too few properties to create a stable sort.
// Clone the given one and add the remaining properties to end, thereby making
// the sort stable but preserving the user's original intent for the major
// sort order.
orderBy = new OrderByQueryOption(orderBy.RawValue, context);
foreach (var property in propertiesToAdd)
{
orderBy.OrderByNodes.Add(new OrderByPropertyNode(property, OrderByDirection.Ascending));
}
}
return orderBy;
}
private static OrderByQueryOption GenerateDefaultOrderBy(ODataQueryContext context)
{
var orderByRaw = string.Join(",",
GetAvailableOrderByProperties(context)
.Select(property => property.Name));
return string.IsNullOrEmpty(orderByRaw)
? null
: new OrderByQueryOption(orderByRaw, context);
}
// Returns a sorted list of all properties that may legally appear
// in an OrderBy. If the entity type has keys, all are returned.
// Otherwise, when no keys are present, all primitive properties are returned.
private static IEnumerable<IEdmStructuralProperty> GetAvailableOrderByProperties(ODataQueryContext context)
{
Contract.Assert(context != null);
var entityType = context.ElementType as IEdmEntityType;
if (entityType == null) return Enumerable.Empty<IEdmStructuralProperty>();
var properties =
entityType.Key().Any()
? entityType.Key()
: entityType
.StructuralProperties()
.Where(property => property.Type.IsPrimitive());
// Sort properties alphabetically for stable sort
return properties.OrderBy(property => property.Name);
}
internal static IQueryable LimitResults(IQueryable queryable, int limit, out bool resultsLimited)
{
var genericMethod = limitResultsGenericMethod.MakeGenericMethod(queryable.ElementType);
var args = new object[] { queryable, limit, null };
var results = genericMethod.Invoke(null, args) as IQueryable;
resultsLimited = (bool)args[2];
return results;
}
internal static Uri GetNextPageLink(HttpRequestMessage request, int pageSize)
{
Contract.Assert(request != null);
Contract.Assert(request.RequestUri != null);
Contract.Assert(request.RequestUri.IsAbsoluteUri);
return GetNextPageLink(request.RequestUri, request.GetQueryNameValuePairs(), pageSize);
}
internal static Uri GetNextPageLink(Uri requestUri, int pageSize)
{
Contract.Assert(requestUri != null);
Contract.Assert(requestUri.IsAbsoluteUri);
return GetNextPageLink(requestUri, new FormDataCollection(requestUri), pageSize);
}
internal static Uri GetNextPageLink(Uri requestUri, IEnumerable<KeyValuePair<string, string>> queryParameters, int pageSize)
{
Contract.Assert(requestUri != null);
Contract.Assert(queryParameters != null);
Contract.Assert(requestUri.IsAbsoluteUri);
var queryBuilder = new StringBuilder();
var nextPageSkip = pageSize;
foreach (KeyValuePair<string, string> kvp in queryParameters)
{
var key = kvp.Key;
var value = kvp.Value;
switch (key)
{
case "$top":
int top;
if (int.TryParse(value, out top))
{
// There is no next page if the $top query option's value is less than or equal to the page size.
Contract.Assert(top > pageSize);
// We decrease top by the pageSize because that's the number of results we're returning in the current page
value = (top - pageSize).ToString(CultureInfo.InvariantCulture);
}
break;
case "$skip":
int skip;
if (int.TryParse(value, out skip))
{
// We increase skip by the pageSize because that's the number of results we're returning in the current page
nextPageSkip += skip;
}
continue;
}
if (key.Length > 0 && key[0] == '$')
{
// $ is a legal first character in query keys
key = '$' + Uri.EscapeDataString(key.Substring(1));
}
else
{
key = Uri.EscapeDataString(key);
}
value = Uri.EscapeDataString(value);
queryBuilder.Append(key);
queryBuilder.Append('=');
queryBuilder.Append(value);
queryBuilder.Append('&');
}
queryBuilder.AppendFormat("$skip={0}", nextPageSkip);
var uriBuilder = new UriBuilder(requestUri)
{
Query = queryBuilder.ToString()
};
return uriBuilder.Uri;
}
}
}
|
using Speckle.Newtonsoft.Json;
using Speckle.Core.Kits;
using Speckle.Core.Models;
using System.Collections.Generic;
using Objects.Structural.Geometry;
using Objects.Structural.Materials;
using Objects.Structural.Properties.Profiles;
namespace Objects.Structural.Properties
{
public class Property1D : Property //SectionProperty as alt class name
{
public MemberType memberType { get; set; }
[DetachProperty]
public Material material { get; set; }
[DetachProperty]
public SectionProfile profile { get; set; } //section description
public BaseReferencePoint referencePoint { get; set; }
public double offsetY { get; set; } = 0; //offset from reference point
public double offsetZ { get; set; } = 0; //offset from reference point
public Property1D() { }
[SchemaInfo("Property1D (by name)", "Creates a Speckle structural 1D element property", "Structural", "Properties")]
public Property1D(string name)
{
this.name = name;
}
[SchemaInfo("Property1D", "Creates a Speckle structural 1D element property", "Structural", "Properties")]
public Property1D(string name, Material material, SectionProfile profile)
{
this.name = name;
this.material = material;
this.profile = profile;
}
}
}
|
using System;
namespace ClangNet.Samples
{
/// <summary>
/// Behavior Info Factory
/// </summary>
public static class BehaviorInfoFactory
{
/// <summary>
/// Create Behavior Info
/// </summary>
/// <param name="cursor">Clang Cursor</param>
/// <returns>Behavior Info</returns>
public static BehaviorInfo Create(ClangCursor cursor)
{
switch(cursor.Kind)
{
case CursorKind.Constructor:
return new ConstructorInfo(cursor);
case CursorKind.Destructor:
return new DestructorInfo(cursor);
case CursorKind.FunctionDeclaration:
return new FunctionInfo(cursor);
case CursorKind.CXXMethod:
return new CppMethodInfo(cursor);
default:
throw new ArgumentException($"Not Behavior Cursor");
}
}
}
}
|
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using DeepL;
using Discord;
using Discord.WebSocket;
using Humanizer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Vanslate;
using Vanslate.Entities;
using Vanslate.Helpers;
using Vanslate.Services;
using Version = Vanslate.Version;
namespace Gommon
{
public static partial class Extensions
{
public static IServiceCollection AddAllServices(this IServiceCollection coll) =>
coll.AddBotServices()
.AddSingleton<CancellationTokenSource>()
.AddSingleton(new DeepLClient(Config.DeepL.FormattedToken, !Config.DeepL.UsePro))
.AddSingleton(new HttpClient
{
Timeout = 10.Seconds()
})
.AddSingleton(new DiscordSocketClient(new DiscordSocketConfig
{
AlwaysAcknowledgeInteractions = false,
LogLevel = Severity,
GatewayIntents = Intents,
AlwaysDownloadUsers = false,
ConnectionTimeout = 10000,
MessageCacheSize = 0
}));
private static LogSeverity Severity => Version.IsDevelopment ? LogSeverity.Debug : LogSeverity.Verbose;
private static GatewayIntents Intents
=> GatewayIntents.Guilds;
private static bool IsEligibleService(Type type) => type.Inherits<IVanslateService>() && !type.IsAbstract;
public static IServiceCollection AddBotServices(this IServiceCollection serviceCollection)
=> serviceCollection.Apply(coll =>
{
//get all the classes that inherit IVanslateService, and aren't abstract.
var l = typeof(Bot).Assembly.GetTypes()
.Where(IsEligibleService).Apply(ls => ls.ForEach(coll.TryAddSingleton));
Logger.Info(LogSource.Bot, $"Injected {"service".ToQuantity(l.Count())} into the service provider.");
});
}
} |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EnemyManager : MonoBehaviour
{
PlayerCharacterController m_PlayerController;
public List<EnemyController> enemies { get; private set; }
public int numberOfEnemiesTotal { get; private set; }
public int numberOfEnemiesRemaining => enemies.Count;
public UnityAction<EnemyController, int> onRemoveEnemy;
private void Awake()
{
m_PlayerController = FindObjectOfType<PlayerCharacterController>();
DebugUtility.HandleErrorIfNullFindObject<PlayerCharacterController, EnemyManager>(m_PlayerController, this);
enemies = new List<EnemyController>();
}
public void RegisterEnemy(EnemyController enemy)
{
enemies.Add(enemy);
numberOfEnemiesTotal++;
}
public void UnregisterEnemy(EnemyController enemyKilled)
{
int enemiesRemainingNotification = numberOfEnemiesRemaining - 1;
onRemoveEnemy.Invoke(enemyKilled, enemiesRemainingNotification);
// removes the enemy from the list, so that we can keep track of how many are left on the map
enemies.Remove(enemyKilled);
}
}
|
using System.Collections.Generic;
using Framework.DomainDriven.Metadata;
namespace Framework.DomainDriven.DAL.Sql
{
public class ListTypeFieldMapper : Mapper<ListTypeFieldMetadata>
{
protected override IEnumerable<SqlFieldMappingInfo> GetMapping(ListTypeFieldMetadata field)
{
yield break;
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HaloOnline.Server.Core.Repository.Model
{
[Table("UserChallenge")]
public class UserChallenge
{
[Key]
[Column(Order = 0)]
public int UserId { get; set; }
[Key]
[Column(Order = 1)]
public string ChallengeId { get; set; }
public DateTime? FinishedAt { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[ForeignKey("ChallengeId")]
public virtual Challenge Challenge { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
}
}
|
namespace AluraCar.Model
{
public enum Opcionais
{
ArCondicionado = 800,
Mp3Player = 1500,
FreioAbs = 1000
}
}
|
using System.Collections.Generic;
namespace Fossil
{
public abstract class ExclusiveSettingsValue : SettingsValue<ExclusiveOption>
{
public abstract List<ExclusiveOption> GetPossibleValues();
}
} |
using NHamcrest.Core;
using Xunit;
using NHAssert = NHamcrest.Tests.Internal.Assert;
namespace NHamcrest.Tests.Core
{
public class IsLessThanOrEqualToTests
{
[Fact]
public void Match_if_less()
{
const int five = 5;
NHAssert.That(five, Is.LessThanOrEqualTo(6));
}
[Fact]
public void No_match_if_not_less()
{
var lessThanOrEqualTo = new IsLessThanOrEqualTo<int>(8);
var matches = lessThanOrEqualTo.Matches(9);
Assert.False(matches);
}
[Fact]
public void Match_if_equal()
{
var isLessThanOrEqualTo = new IsLessThanOrEqualTo<int>(8);
var matches = isLessThanOrEqualTo.Matches(8);
Assert.True(matches);
}
[Fact]
public void Append_description()
{
const int six = 6;
var lessThan = Is.LessThanOrEqualTo(six);
var description = new StringDescription();
lessThan.DescribeTo(description);
Assert.Equal(description.ToString(), "less than or equal to " + six);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CustomLogProviders;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
namespace SampleConsumer
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context,logging) =>
{
logging.AddConfiguration(context.Configuration.GetSection("Logging"));
logging.ClearProviders();
// add builtin providers
logging.AddConsole();
logging.AddDebug();
// add my own log provider
logging.AddFileLogger(options =>
{
options.MaxFileSizeInMB = 5;
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
} |
using System;
using System.Collections.Generic;
namespace DynamicList.Portable.Migrations
{
public class Migration_002
{
public IList<string> GetSteps(){
var steps = new List<string>();
steps.Add (@"CREATE TABLE Properties (Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Type INTEGER NOT NULL)");
return steps;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class JsonDataSaver : IDataSaver
{
// persistentDataPath:
// mac: /User/xxx/Library/Application Support/company name/product name
// windows: Users/xxxx/AppData/LocalLow/CompanyName/ProductName
// android: /storage/emulated/0/Android/data/<packagename>/files
// ios: /var/mobile/Containers/Data/Application/<guid>/Documents
public static string GetSaveFullPath(string filename)
{
return string.Format("{0}/{1}", Application.persistentDataPath, filename);
}
public void Save(PlayerData dat)
{
string fn = GetSaveFullPath ("player.txt");
string json = JsonUtility.ToJson (dat);
using (StreamWriter writer = new StreamWriter (new FileStream (fn, FileMode.Create)))
{
writer.Write (json);
}
}
public bool Load(PlayerData dat)
{
string fn = GetSaveFullPath ("player.txt");
if (File.Exists (fn))
{
using (StreamReader reader = new StreamReader (new FileStream (fn, FileMode.Open)))
{
JsonUtility.FromJsonOverwrite (reader.ReadToEnd (), dat);
}
return true;
}
return false;
}
}
|
using System.Collections.Generic;
namespace Entities.PostBlog
{
public class Blog
{
public int Id;
public string Name;
public ICollection<Post> Posts;
}
}
|
using OctoAwesome.Basics.Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace OctoAwesome.Basics.Definitions.Blocks
{
public sealed class RedPlankBlockDefinition : BlockDefinition
{
public override string Name
{
get { return Languages.OctoBasics.RedPlank; }
}
public override string Icon
{
get { return "planks"; }
}
public override bool HasMetaData { get { return true; } }
public override string[] Textures
{
get
{
return new[] {
"planks"};
}
}
public override PhysicalProperties GetProperties(ILocalChunkCache manager, int x, int y, int z)
{
return new PhysicalProperties()
{
Density = 0.87f,
FractureToughness = 0.3f,
Granularity = 0.9f,
Hardness = 0.1f
};
}
public override void Hit(IBlockDefinition block, PhysicalProperties itemProperties)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace System.Printing {
public class PrintJobSettings
{
public PrintTicket CurrentPrintTicket
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string Description
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
internal PrintJobSettings()
{
}
}
}
|
// Copyright (c) Lionel Vallet. All rights reserved.
// Licensed under the Apache License, Version 2.0.
namespace ReHackt.Linq.AutoMapperExtensions.UnitTests.Models
{
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
}
|
using GetAllLinks.Core.Helpers;
using GetAllLinks.Core.Infrastructure.Interfaces;
using GetAllLinks.Core.Infrastructure.Services;
using MvvmCross.Core.ViewModels;
namespace GetAllLinks.Core.ViewModels
{
public class SettingsViewModel : MvxViewModel, ICloseable
{
private readonly IDownloader _downloader;
public string ListUrl
{
get { return Settings.ListUrl; }
set
{
Settings.ListUrl = value;
RaisePropertyChanged();
}
}
public int SimultaneousDownloads
{
get { return Settings.SimultaneousDownloads; }
set
{
Settings.SimultaneousDownloads = value;
RaisePropertyChanged();
}
}
public string DestinationDirectory
{
get
{
if (string.IsNullOrWhiteSpace(Settings.DestinationDirectory))
Settings.DestinationDirectory = _downloader.GetDefaultDownloadDir().Result;
return Settings.DestinationDirectory;
}
set
{
Settings.DestinationDirectory = value;
RaisePropertyChanged();
}
}
public SettingsViewModel(IDownloader downloader)
{
_downloader = downloader;
}
public void OnClose()
{
}
}
}
|
namespace Phoenix.WPF {
using Phoenix.WPF.CustomControls;
public partial class ReportViewerWindow : WindowBase {
public ReportViewerWindow() : base(true, true, false) {
InitializeComponent();
}
}
} |
using GoogleAnalytics;
using Microsoft.Toolkit.Uwp;
using Microsoft.Toolkit.Uwp.UI.Animations;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace SampleManager
{
public sealed partial class SampleDescription : UserControl
{
public event EventHandler CloseClicked;
private string _cacheFileName = "description.md";
public SampleDescription(string mdLocal, string mdRemote = null)
{
this.RequiresPointer = RequiresPointer.WhenFocused;
this.InitializeComponent();
if (!Sample.IsXbox())
{
CloseButton.Visibility = Visibility.Visible;
}
else
{
}
var nop = Init(mdLocal, mdRemote);
}
private async Task Init(string mdFilename, string mdRemote)
{
string md = null;
try
{
if (mdRemote != null)
{
var client = new HttpClient();
md = await client.GetStringAsync(new Uri(mdRemote));
if (string.IsNullOrWhiteSpace(md))
{
md = null;
}
else
{
await StorageFileHelper.WriteTextToLocalFileAsync(md, _cacheFileName);
}
}
}
catch (Exception){}
// get from cache if not available online
if (md == null)
{
try
{
md = await StorageFileHelper.ReadTextFromLocalFileAsync(_cacheFileName);
}
catch (Exception) {}
}
// get packaged copy if not available in cache
if (md == null)
{
md = await StorageFileHelper.ReadTextFromPackagedFileAsync(mdFilename);
}
MTB.Text = md;
ProgressRinger.IsEnabled = false;
ProgressRinger.Visibility = Visibility.Collapsed;
Content.Fade(1, 200).Start();
}
private void Close_Clicked(object sender, RoutedEventArgs e)
{
CloseClicked?.Invoke(this, null);
}
public void FocusWebView()
{
MTB.Focus(FocusState.Keyboard);
}
private async void MTB_LinkClicked(object sender, Microsoft.Toolkit.Uwp.UI.Controls.LinkClickedEventArgs e)
{
var link = e.Link;
if (link.StartsWith("#"))
{
link = link.Remove(0, 1);
}
await Launcher.LaunchUriAsync(new Uri(link, UriKind.Absolute));
}
}
}
|
namespace DuplicateFileFinder.FileSizers
{
public interface FileSizer
{
long SizeFile(FileData fileData);
}
} |
namespace Assignment2
{
class Person
{
public string FirstName;
public string LastName;
public int Age;
public string City;
public GenderType Gender;
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Platibus.SampleApi.Widgets
{
public class InMemoryWidgetRepository : IWidgetRepository
{
private readonly ConcurrentDictionary<string, Widget> _widgets = new ConcurrentDictionary<string, Widget>();
public Task Add(Widget widget)
{
if (widget == null) throw new ArgumentNullException(nameof(widget));
if (string.IsNullOrWhiteSpace(widget.Id))
{
widget.Id = Guid.NewGuid().ToString();
}
if (!_widgets.TryAdd(widget.Id, CopyOf(widget)))
{
throw new WidgetAlreadyExistsException(widget.Id);
}
return Task.FromResult(0);
}
public Task Update(Widget widget)
{
if (widget == null)
{
throw new ArgumentNullException(nameof(widget));
}
if (string.IsNullOrWhiteSpace(widget.Id))
{
throw new ArgumentException("ID is required");
}
_widgets[widget.Id] = CopyOf(widget);
return Task.FromResult(0);
}
public Task<Widget> Get(string id)
{
_widgets.TryGetValue(id, out Widget widget);
if (widget == null) throw new WidgetNotFoundException(id);
return Task.FromResult(CopyOf(widget));
}
public Task<IEnumerable<Widget>> List()
{
var widgets = _widgets.Values.Select(CopyOf).ToList();
return Task.FromResult<IEnumerable<Widget>>(widgets);
}
public Task Remove(string id)
{
if (!_widgets.TryRemove(id, out var _))
{
throw new WidgetNotFoundException(id);
}
return Task.FromResult(0);
}
private static Widget CopyOf(Widget widget)
{
return new Widget
{
Id = widget.Id,
PartNumber = widget.PartNumber,
Description = widget.Description,
Length = widget.Length,
Width = widget.Width,
Height = widget.Height
};
}
}
} |
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Cybtans.Automation
{
public class WebDriverManager: BarrierManager
{
private class WebDriverCacheItem
{
public IWebDriver Driver;
public int ReferenceCount;
}
static WebDriverManager()
{
AppDomain.CurrentDomain.ProcessExit += (sender, arg) =>
{
Instance.Dispose();
BarrierManager.Manager.Dispose();
};
}
private Dictionary<string, WebDriverCacheItem> _cache = new Dictionary<string, WebDriverCacheItem>();
public static WebDriverManager Instance { get; } = new WebDriverManager();
public IWebDriver CreateDriver(string driverType, string driverName, int maxReferenceCount)
{
CheckDisposed();
lock (_cache)
{
if (!_cache.TryGetValue(driverName, out var item))
{
item = new WebDriverCacheItem
{
Driver = CreateDriver(driverType),
ReferenceCount = maxReferenceCount
};
_cache.Add(driverName, item);
}
return item.Driver;
}
}
public bool ContainsDriver(string driverName)
{
return _cache.ContainsKey(driverName);
}
public IWebDriver GetDriver(string driverName)
{
lock (_cache)
{
if(!_cache.TryGetValue(driverName, out var driver))
{
new InvalidOperationException($"Driver for {driverName} not found");
}
return _cache[driverName].Driver;
}
}
public static IWebDriver CreateDriver(string driver)
{
switch (driver)
{
case SupportedDrivers.DRIVER_CHROME:
return new ChromeDriver();
//case SupportedDrivers.DRIVER_FIREFOX:
// return new FirefoxDriver();
//case SupportedDrivers.DRIVER_IE:
// return new InternetExplorerDriver();
//case SupportedDrivers.DRIVER_Edge:
// return new EdgeDriver();
case SupportedDrivers.DRIVER_CHROME_HEADLESS:
{
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
return new ChromeDriver(chromeOptions);
}
default:
throw new InvalidOperationException("Driver not found");
}
}
public async Task<IWebDriver> WaitForDriver(string driverName)
{
CheckDisposed();
await GetWaitHandler(driverName).CreateTask();
return GetDriver(driverName);
}
public void ReleaseReference(string driverName)
{
CheckDisposed();
lock (_cache)
{
_cache.TryGetValue(driverName, out var item);
item.ReferenceCount--;
if (item.ReferenceCount <= 0)
{
item.Driver.Quit();
_cache.Remove(driverName);
RemoveHandler(driverName);
}
}
}
public void ReleaseBarrier(string barrier)
{
CheckDisposed();
GetWaitHandler(barrier).Set();
}
#region IDisposable Support
//~WebDriverManager()
//{
// try
// {
// Dispose(false);
// }
// catch
// {
// }
//}
protected override void Dispose(bool disposing)
{
if (!isDisposed)
{
foreach (var item in _cache.Values)
{
item.Driver.Quit();
}
_cache = null;
}
base.Dispose(disposing);
}
#endregion
}
}
|
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Runtime;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace BudgeteeServer.Extensions
{
public static class AwsConfigServiceCollectionExtensions
{
public static IServiceCollection AddAwsDynamoDb(
this IServiceCollection services, IConfiguration config)
{
var credentials = new BasicAWSCredentials(config["awsAccessKey"], config["awsSecretKey"]);
var dynamoDbConfig = new AmazonDynamoDBConfig
{
RegionEndpoint = RegionEndpoint.APSoutheast2
};
var client = new AmazonDynamoDBClient(credentials, dynamoDbConfig);
services.AddSingleton<IAmazonDynamoDB>(client);
services.AddSingleton<IDynamoDBContext, DynamoDBContext>();
return services;
}
}
}
|
using Advobot.Services.HelpEntries;
using Advobot.Tests.Fakes.Services.HelpEntries;
using Advobot.Tests.TestBases;
using Advobot.TypeReaders;
using AdvorangesUtils;
using Discord.Commands;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Advobot.Tests.Core.TypeReaders;
[TestClass]
public sealed class CloseHelpEntryTypeReader_Tests : TypeReaderTestsBase
{
private readonly HelpEntryService _HelpEntries = new();
protected override TypeReader Instance { get; } = new CloseHelpEntryTypeReader();
[TestMethod]
public async Task Valid_Test()
{
foreach (var name in new[]
{
"dog",
"bog",
"pneumonoultramicroscopicsilicovolcanoconiosis"
})
{
_HelpEntries.Add(new FakeHelpEntry
{
Name = name,
});
}
var result = await ReadAsync(_HelpEntries.GetHelpEntries().First().Name).CAF();
Assert.IsTrue(result.IsSuccess);
Assert.IsInstanceOfType(result.BestMatch, typeof(IEnumerable<IModuleHelpEntry>));
}
protected override void ModifyServices(IServiceCollection services)
{
services
.AddSingleton<IHelpEntryService>(_HelpEntries);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerNetworkCs : MonoBehaviour {
//[SerializeField] private GameObject thisPlayerCamera;
[SerializeField] private PlayerBehaviourCs playerControlScript;
private PhotonView photonView;
// Use this for initialization
void Start ()
{
// faster than using photon.monobehaviour
photonView = GetComponent<PhotonView>();
playerControlScript = GetComponent<PlayerBehaviourCs>();
Initilaze();
}
void Initilaze ()
{
if (photonView.isMine)
{
}
// handles fucntionality for non local character
else
{
// disbale its camera
//thisPlayerCamera.SetActive(false);
//disable its control scripts
playerControlScript.enabled = false;
}
}
}
|
namespace CraftopiaActions
{
public class RefillHunger: AmountAction<RefillHunger>
{
}
} |
using BenchmarkDotNet.Attributes;
using System.Linq;
namespace LinqFasterer.Benchmarks.Benchmarks
{
public class FirstBenchmark : Benchmarkable
{
[Benchmark(Baseline = true)]
public int FirstLinq()
{
return Data.First();
}
[Benchmark]
public int FirstFaster()
{
return Data.FirstF();
}
}
public class FirstPredicateBenchmark : Benchmarkable
{
[Benchmark(Baseline = true)]
public int FirstPredicateLinq()
{
return Data.First(v => v == Data[Data.Length / 2]);
}
[Benchmark]
public int FirstPredicateFaster()
{
return Data.FirstF(v => v == Data[Data.Length / 2]);
}
}
} |
namespace CakesWebApp.Views
{
public class FileView : IView
{
private readonly string _htmlString;
public FileView(string htmlString)
{
_htmlString = htmlString;
}
public string View()
{
return _htmlString;
}
}
}
|
using System;
namespace MFDSettingsManager.Configuration.Collections
{
/// <summary>
/// Module configuration collection
/// </summary>
public class ModulesConfigurationCollection : ConfigurationSectionCollectionBase<ModuleConfiguration>
{
/// <summary>
/// Definition of a key
/// </summary>
/// <returns></returns>
protected override Func<ModuleConfiguration, object> GetDefaultKey()
{
return (element) =>
{
return element.ModuleName;
};
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.