content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
namespace GCL.Db.Ni {
public class NiQueryDataCommand : IDataCommand {
#region IDataCommand Members
public virtual void ExcuteCommand(IDataResource res, IDbCommand command, NiDataResult result) {
//为ObjectDb特别处理
if (command is INeedNiDataResult) {
((INeedNiDataResult)command).DataResult = result;
}
object v;
if(command.CommandText.ToLower().StartsWith("delete")) v = command.ExecuteNonQuery();
else v = command.ExecuteScalar();
FillDataTable(result.DataSet, command, "Query", v);
}
#endregion
/// <summary>
/// 这里主要是对表的一些设置
/// </summary>
/// <param name="ds"></param>
/// <param name="command"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void FillDataTable(DataSet ds, IDbCommand command, string name, object v) {
DataTable dt = ds.Tables.Add();
if (command.CommandType == CommandType.StoredProcedure && command.CommandText.IndexOf(" ") < 0) {
if (ds.Tables.Contains(command.CommandText)) ds.Tables.Remove(command.CommandText);
dt.TableName = command.CommandText;
}
command.Connection = null;
FillDataTable(dt, name, v);
}
/// <summary>
/// 这里主要处理表内的具体字段
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="v"></param>
/// <returns></returns>
public static DataTable FillDataTable(DataTable dt, string name, object v) {
if (v == null) dt.Columns.Add(new DataColumn(name, typeof(string)));
else dt.Columns.Add(new DataColumn(name, v.GetType()));
DataRow row = dt.Rows.Add();
row[0] = v;
dt.Rows.Add();
return dt;
}
}
}
|
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace AutoFrontend.Controls
{
/// <summary>
/// Summary description for CodeTextBox.
/// </summary>
public class CodeTextBox : TextBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components;
public CodeTextBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
Multiline = true;
Font = new Font("Courier New", 11);
MaxLength = 0;
ScrollBars = ScrollBars.Both;
WordWrap = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: Add custom paint code here
// Calling the base class OnPaint
base.OnPaint(pe);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
} |
using System.Collections.Generic;
namespace HAD.Contracts
{
public interface ICommandProcessor
{
string Process(IList<string> arguments);
}
} |
namespace System {
/* Polyfill for System.Index from .NET Core, to allow C# 8.0 [start..end] notation */
public readonly struct Range {
public Index Start { get; }
public Index End { get; }
public Range(Index start, Index end) { Start = start; End = end; }
public static Range StartAt(Index start) => new Range(start, new Index(-1));
public static Range EndAt(Index end) => new Range(new Index(0), end);
public static Range All => new Range(new Index(0), new Index(-1));
}
}
|
using System.Net;
namespace Kasp.HttpException.Core {
public class NotFoundException : HttpExceptionBase {
public override HttpStatusCode StatusCode { get; } = HttpStatusCode.NotFound;
public NotFoundException() {
}
public NotFoundException(string message) : base(message) {
}
public NotFoundException(string message, System.Exception innerException) : base(message, innerException) {
}
}
} |
using Essensoft.AspNetCore.Payment.LianLianPay;
using Essensoft.AspNetCore.Payment.LianLianPay.Notify;
using Essensoft.AspNetCore.Payment.LianLianPay.Request;
using Microsoft.AspNetCore.Mvc;
using WebApplicationSample.Models;
using System.Threading.Tasks;
namespace WebApplicationSample.Controllers
{
public class LianLianPayController : Controller
{
private readonly LianLianPayClient _client = null;
private readonly LianLianPayNotifyClient _notifyClient = null;
public LianLianPayController(LianLianPayClient client, LianLianPayNotifyClient notifyClient)
{
_client = client;
_notifyClient = notifyClient;
}
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult WebQuickPay()
{
return View();
}
[HttpPost]
public async Task<IActionResult> WebQuickPay(LianLianPayWebQuickPayViewModel viewModel)
{
var request = new LianLianPayWebQuickPayRequest()
{
NoOrder = viewModel.NoOrder,
DtOrder = viewModel.DtOrder,
MoneyOrder = viewModel.MoneyOrder,
NameGoods = viewModel.NameGoods,
UserId = viewModel.UserId,
NotifyUrl = viewModel.NotifyUrl,
UrlReturn = viewModel.UrlReturn,
BankCode = viewModel.BankCode,
PayType = viewModel.PayType,
NoAgree = viewModel.NoAgree,
RiskItem = viewModel.RiskItem,
IdType = viewModel.IdType,
IdNo = viewModel.IdNo,
AcctName = viewModel.AcctName,
CardNo = viewModel.CardNo,
};
var response = await _client.PageExecuteAsync(request);
return Content(response.Body, "text/html;charset=utf-8");
}
[HttpGet]
public IActionResult WapQuickPay()
{
return View();
}
[HttpPost]
public async Task<IActionResult> WapQuickPay(LianLianPayWapQuickPayViewModel viewModel)
{
var request = new LianLianPayWapQuickPayRequest()
{
NoOrder = viewModel.NoOrder,
DtOrder = viewModel.DtOrder,
MoneyOrder = viewModel.MoneyOrder,
NameGoods = viewModel.NameGoods,
UserId = viewModel.UserId,
AppRequest = viewModel.AppRequest,
NotifyUrl = viewModel.NotifyUrl,
UrlReturn = viewModel.UrlReturn,
NoAgree = viewModel.NoAgree,
RiskItem = viewModel.RiskItem,
IdType = viewModel.IdType,
IdNo = viewModel.IdNo,
AcctName = viewModel.AcctName,
CardNo = viewModel.CardNo,
};
var response = await _client.PageReqDataExecuteAsync(request);
return Content(response.Body, "text/html;charset=utf-8");
}
[HttpGet]
public IActionResult OrderQuery()
{
return View();
}
[HttpPost]
public async Task<IActionResult> OrderQuery(LianLianPayOrderQueryViewModel viewModel)
{
var request = new LianLianPayOrderQueryRequest()
{
NoOrder = viewModel.NoOrder,
DtOrder = viewModel.DtOrder,
OidPayBill = viewModel.OidPayBill
};
var response = await _client.ExecuteAsync(request);
ViewData["response"] = response.Body;
return View();
}
[HttpGet]
public IActionResult Refund()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Refund(LianLianPayRefundViewModel viewModel)
{
var request = new LianLianPayRefundRequest()
{
NoRefund = viewModel.NoRefund,
DtRefund = viewModel.DtRefund,
MoneyRefund = viewModel.MoneyRefund,
NoOrder = viewModel.NoOrder,
DtOrder = viewModel.DtOrder,
OidPaybill = viewModel.OidPayBill,
NotifyUrl = viewModel.NotifyUrl,
};
var response = await _client.ExecuteAsync(request);
ViewData["response"] = response.Body;
return View();
}
[HttpGet]
public IActionResult RefundQuery()
{
return View();
}
[HttpPost]
public async Task<IActionResult> RefundQuery(LianLianPayRefundQueryViewModel viewModel)
{
var request = new LianLianPayRefundQueryRequest()
{
NoRefund = viewModel.NoRefund,
DtRefund = viewModel.DtRefund,
OidRefundNo = viewModel.OidRefundNo,
};
var response = await _client.ExecuteAsync(request);
ViewData["response"] = response.Body;
return View();
}
[HttpPost]
public async Task<IActionResult> WebQuickPayReturn()
{
try
{
var notify = await _notifyClient.ExecuteAsync<LianLianPayWebQuickPayReturnResponse>(Request);
ViewData["response"] = "支付成功";
return View();
}
catch
{
ViewData["response"] = "出现错误";
return View();
}
}
[HttpPost]
public async Task<IActionResult> WapQuickPayReturn()
{
try
{
var notify = await _notifyClient.ExecuteAsync<LianLianPayWapQuickPayReturnResponse>(Request);
ViewData["response"] = "支付成功";
return View();
}
catch
{
ViewData["response"] = "出现错误";
return View();
}
}
}
}
|
using UnityEngine;
namespace BennyKok.RuntimeDebug.DebugInput
{
[System.Serializable]
public class InputManagerLayer : InputLayer
{
public KeyCode menuKey = KeyCode.Tab;
public bool Check() => true;
public bool IsConfirmAction()
{
return Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.RightArrow);
}
public bool IsBackAction()
{
return Input.GetKeyDown(KeyCode.Backspace) || Input.GetKeyDown(KeyCode.LeftArrow);
}
public bool IsMenuAction()
{
return Input.GetKeyDown(menuKey);
}
public bool IsKeyDown(string keycode)
{
return Input.GetKeyDown(keycode);
}
public bool IsUpPressing()
{
return Input.GetKey(KeyCode.UpArrow);
}
public bool IsUpReleased()
{
return Input.GetKeyUp(KeyCode.UpArrow);
}
public bool IsUp()
{
return Input.GetKeyDown(KeyCode.UpArrow);
}
public bool IsDownPressing()
{
return Input.GetKey(KeyCode.DownArrow);
}
public bool IsDownReleased()
{
return Input.GetKeyUp(KeyCode.DownArrow);
}
public bool IsDown()
{
return Input.GetKeyDown(KeyCode.DownArrow);
}
public void Update()
{
}
public void Enable() { }
public void Disable() { }
}
} |
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace BuildTrigger
{
public interface IBuildTrigger
{
Task<HttpResponseMessage> TriggerAsync(int buildNumber);
Task<List<Build>> GetBuildsAsync();
}
}
|
using System;
using System.Collections.Generic;
using DotnetExlib.Properties;
namespace DotnetExlib.IO.Database
{
/// <summary>
/// データベースの一つのノードを表します。
/// この機能はまだ完成していません。
/// </summary>
[Obsolete("この機能はまだ完成していません。")]
[Author("Takym", copyright: "Copyright (C) 2017 Takym.")]
public interface INode
{
/// <summary>
/// このノードの名前です。ファイル名に利用できない文字は使用しないでください。
/// </summary>
string Name { get; set; }
/// <summary>
/// このノードの値です。この<see cref="byte"/>配列の値は、継承したクラスまたは構造体が解析します。
/// </summary>
byte[] Value { get; set; }
/// <summary>
/// このノードの親ノードです。この値が<c>null</c>の場合、
/// 必ず<see cref="DotnetExlib.IO.Database.INode.IsRoot"/>の値は<c>true</c>になります。
/// </summary>
INode Parent { get; }
/// <summary>
/// このノードの子ノードを格納しているリストオブジェクトです。
/// </summary>
IList<INode> Children { get; }
/// <summary>
/// このノードがルートノードの場合は<c>true</c>、それ以外は<c>false</c>です。
/// このプロパティを継承する場合、必ず<c>this.Parent == null</c>の値を返すようにしてください。
/// </summary>
bool IsRoot { get; }
/// <summary>
/// このノードの親ノードを設定します。
/// <c>null</c>値を利用する事でルートノードに設定する事ができます。
/// </summary>
/// <param name="parent">親ノードにしたいオブジェクトです。</param>
void SetParent(INode parent);
/// <summary>
/// このノードをディスク上に保存する時の拡張子を返します。
/// </summary>
/// <returns><c>".xxx"</c>形式の拡張子です。</returns>
string GetTypeExtension();
}
}
|
using Newtonsoft.Json;
namespace OntApiClient.Rpc.DTOs
{
public class Payload
{
[JsonProperty("Nonce")]
public long Nonce { get; set; }
[JsonProperty("Code")]
public string Code { get; set; }
[JsonProperty("GasLimit")]
public int GasLimit { get; set; }
[JsonProperty("VmType")]
public int VmType { get; set; }
//todo: depends on txtype, return here
[JsonProperty("NeedStorage")]
public bool NeedStorage { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("CodeVersion")]
public string CodeVersion { get; set; }
[JsonProperty("Author")]
public string Author { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
}
}
|
namespace Winston.Inventory
{
public enum ToolType
{
Hoe,
Sickle,
Milker,
WaterCan,
PickAxe
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace UnityUITable
{
public abstract class InteractableCellStyle : TableCellStyle
{
public BoolSetting interactable = new BoolSetting(
(cell, v) =>
{
cell.GetComponentsInChildren<Graphic>().ForEach(g => g.raycastTarget = v);
((InteractableCellInterface)cell).interactable = v;
},
(cell) => cell.GetComponentInChildren<Graphic>().raycastTarget);
}
}
|
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
using System.Collections;
public class WallManager : MonoBehaviour {
/// <summary>
/// Walls color
/// </summary>
Color defaultColor;
/// <summary>
/// Use particle for damage effect
/// </summary>
public ParticleEmitter damageEffect = null;
/// <summary>
/// Variables for flashing objects
/// </summary>
public bool onFlashEffect;
float flashCycle = 0.0f;
float timer = 0.0f;
float lastTime = 0.0f;
bool needDefault = false;
/// <summary>
/// Start in MonoBehaviour: Instantiate materials
/// </summary>
void Start ()
{
if (onFlashEffect)
{
this.GetComponent<Renderer>().material = Instantiate(this.GetComponent<Renderer>().material) as Material;
defaultColor = this.GetComponent<Renderer>().material.color;
}
damageEffect = Instantiate(damageEffect) as ParticleEmitter;
damageEffect.transform.SetParent(this.transform);
damageEffect.emit = false;
}
/// <summary>
/// Update in MonoBehaviour: Instantiate materials
/// </summary>
void Update()
{
// If need to be back to default color, it will set in 0.15 secs.
if (Time.time - lastTime > 0.15f && needDefault == true && onFlashEffect)
{
timer = 0.0f;
this.GetComponent<Renderer>().material.color = defaultColor;
needDefault = false;
}
}
/// <summary>
/// Flash objects while object is hit by crosshair
/// </summary>
public void FlashObject(bool hitObject)
{
if (hitObject && onFlashEffect)
{
timer += Time.deltaTime * 5.0f;
flashCycle = Mathf.Round(timer);
if (flashCycle % 2.0f == 0.0f)
{
needDefault = true;
this.GetComponent<Renderer>().material.color = new Color(0.5f, 0.5f, 0.5f);
}
else
{
this.GetComponent<Renderer>().material.color = defaultColor;
needDefault = false;
}
}
lastTime = Time.time;
}
/// <summary>
/// Generate hit effect
/// </summary>
public void Damage(Vector3 hitPos, float activeTime)
{
this.damageEffect.transform.position = hitPos;
StartCoroutine(DamageEffectProcess(activeTime));
}
/// <summary>
/// IEnumerator
/// </summary>
IEnumerator DamageEffectProcess(float fireActiveTime)
{
damageEffect.emit = true;
float deltaTime = 0.0f;
while (deltaTime < fireActiveTime)
{
deltaTime += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
damageEffect.emit = false;
yield return null;
}
}
|
using Newtonsoft.Json;
namespace TetrioStats.Api.Domain.Json.Users
{
public class UserData
: ITetrioResponsePayload<UserStatistics>
{
[JsonProperty("user")]
public UserStatistics Payload { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AreaTrigger : MonoBehaviour
{
public bool autoClose = true;
public Collider target;
public UnityEvent onTargetDrop;
public bool isTargetInArea;
void OnTriggerEnter(Collider other)
{
if (!enabled) return;
if (target == other)
isTargetInArea = true;
var dt = other.GetComponent<DragTrigger>();
if (dt)
{
dt.SetAreaTrigger(this);
}
}
void OnTriggerExit(Collider other)
{
if (!enabled) return;
if (target == other)
isTargetInArea = false;
}
}
|
namespace NaturalSelection {
public class DnaFitness {
public DnaFitness(Dna dna, double fitness) {
this.dna = dna;
this.fitness = fitness;
}
public Dna dna;
public double fitness;
}
} |
using System.Windows.Forms;
using PipelineBuilder.Data;
namespace PipelineBuilderExtension.UI.Forms
{
public partial class PathHelpForm : Form
{
#region Variables
#endregion
#region Constructor & destructor
/// <summary>
/// Initializes a new instance of the <see cref="PathHelpForm"/> class.
/// </summary>
public PathHelpForm()
{
// Initialize component
InitializeComponent();
// Initialize paths
InitializePaths();
}
#endregion;
#region Properties
#endregion
#region Methods
/// <summary>
/// Initializes the paths.
/// </summary>
private void InitializePaths()
{
// Clear
constantsListView.Items.Clear();
// Get all path constants
PathConstant[] pathConstants = PathConstants.GetAllPathConstants();
foreach (PathConstant pathConstant in pathConstants)
{
// Create listview item
ListViewItem listViewItem = new ListViewItem(pathConstant.Constant);
listViewItem.SubItems.Add(pathConstant.Description);
// Add listview item
constantsListView.Items.Add(listViewItem);
}
}
#endregion
}
} |
using System.Threading.Tasks;
using Helpdesk.Domain.Common;
namespace Helpdesk.Services.Common
{
internal class EmptyEventService : IEventService
{
public Task Publish<TEvent>(TEvent @event) where TEvent : DomainEvent
{
return Task.CompletedTask;
}
}
} |
using CopaceticSoftware.pMixins.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Genesis.Net.Entities.Responses.Error
{
[XmlRoot("payment_response", Namespace = "CashUErrorResponse")]
public class CashUErrorResponse : AlternativePaymentMethodErrorResponse
{
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
// This interface is used to decouple the error reporting
// implementation from the error detection source.
internal interface IErrorSink
{
void SubmitError(CParameterizedError error);
int ErrorCount();
}
}
|
// <copyright file="RecentFoldersPresenter.cs" company="CRLFLabs">
// Copyright (c) CRLFLabs. All rights reserved.
// </copyright>
using System;
using System.ComponentModel;
namespace CRLFLabs.ViewSize.Mvp
{
public class RecentFoldersPresenter : PresenterBase<IRecentFoldersView, IMainModel>
{
public RecentFoldersPresenter(IRecentFoldersView view, IMainModel model) : base(view, model)
{
}
protected override void OnViewLoad(object sender, EventArgs e)
{
base.OnViewLoad(sender, e);
View.SetRecentFolders(Model.RecentFolders);
Model.PropertyChanged += Model_PropertyChanged;
}
private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == MainModel.RecentFoldersPropertyName)
{
View.SetRecentFolders(Model.RecentFolders);
}
}
}
}
|
using System;
using System.IO;
using System.Web;
namespace html5FileUploadDemo
{
/// <summary>
/// AjaxFile 的摘要说明
/// </summary>
public class AjaxFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var data = context.Request.Files["data"]; //slice方法用于切出文件的一部分
var lastModified = context.Request.Form["lastModified"];
var name = context.Request.Form["name"];
var total = Convert.ToInt32(context.Request.Form["total"].ToString()); //总片数
var index = Convert.ToInt32(context.Request.Form["index"].ToString());//当前是第几片
string dir = context.Server.MapPath("~/Upload");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
string file = Path.Combine(dir, name + "_" + index);
data.SaveAs(file);
//如果已经是最后一个分片,组合
//当然你也可以用其它方法比如接收每个分片时直接写到最终文件的相应位置上,但要控制好并发防止文件锁冲突
if (index == total)
{
file = Path.Combine(dir, name);
var fs = new FileStream(file, FileMode.Create);
for (int i = 1; i <= total; ++i)
{
string part = Path.Combine(dir, name + "_" + i);
var bytes = System.IO.File.ReadAllBytes(part);
fs.Write(bytes, 0, bytes.Length);
bytes = null;
System.IO.File.Delete(part);
}
fs.Close();
}
context.Response.ContentType = "text/plain";
context.Response.Write(index);
}
public bool IsReusable
{
get
{
return false;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Topics.Radical.Helpers
{
/// <summary>
/// An helper class to generate hash codes based on a value set.
/// </summary>
public class HashCodeBuilder
{
Int64 combinedHashCode;
/// <summary>
/// Initializes a new instance of the <see cref="HashCodeBuilder"/> class.
/// </summary>
/// <param name="initialHashCode">The initial hash code.</param>
public HashCodeBuilder( Int64 initialHashCode )
{
this.combinedHashCode = initialHashCode;
}
/// <summary>
/// Adds the given value to the generated has code.
/// </summary>
/// <param name="value">The value.</param>
public void AddObject( object value )
{
var h = value.GetHashCode();
this.combinedHashCode = ( ( this.combinedHashCode << 5 ) + this.combinedHashCode ) ^ h;
}
/// <summary>
/// Gets the combined hash as an <c>Int32</c> value.
/// </summary>
/// <value>The combined hash code.</value>
public Int32 CombinedHash32
{
get { return this.combinedHashCode.GetHashCode(); }
}
/// <summary>
/// Gets the combined hash code.
/// </summary>
/// <value>The combined hash code.</value>
public Int64 CombinedHash
{
get { return this.combinedHashCode; }
}
}
} |
using System.Collections.Generic;
namespace ADAPT.DTOs.Equipment
{
public class EndgunTableDto
{
public EndgunTableDto()
{
TableEntries = new List<EndgunTableEntryDto>();
}
public List<EndgunTableEntryDto> TableEntries { get; set; }
}
} |
namespace UnityAnimatables
{
public class LimitVelocity : Animatable, IAnimate
{
public float MaxVelocity = 1f;
private void OnEnable()
{
AnimController.I.Add(this);
}
private void OnDisable()
{
AnimController.I.Remove(this);
}
public void Animate()
{
RB.velocity = RB.velocity.magnitude > MaxVelocity ? RB.velocity.normalized * MaxVelocity : RB.velocity;
}
}
} |
using Magic.Framework.Schools;
using SpaceCore;
using StardewValley;
namespace Magic.Framework.Spells
{
internal class RewindSpell : Spell
{
/*********
** Public methods
*********/
public RewindSpell()
: base(SchoolId.Arcane, "rewind") { }
public override int GetMaxCastingLevel()
{
return 1;
}
public override bool CanCast(Farmer player, int level)
{
return base.CanCast(player, level) && player.hasItemInInventory(336, 1);
}
public override int GetManaCost(Farmer player, int level)
{
return 0;
}
public override IActiveEffect OnCast(Farmer player, int level, int targetX, int targetY)
{
player.consumeObject(336, 1);
Game1.timeOfDay -= 200;
player.AddCustomSkillExperience(Magic.Skill, 25);
return null;
}
}
}
|
using System;
using Newtonsoft.Json;
namespace BbcFeed.Api
{
public class RealtimePollingResult
{
[JsonProperty("generated")] public DateTimeOffset Generated { get; set; }
[JsonProperty("providers")] public string[] Providers { get; set; }
[JsonProperty("packages")] public Packages Packages { get; set; }
[JsonProperty("timeouts")] public Timeouts Timeouts { get; set; }
}
public class Packages
{
[JsonProperty("richtracks")] public Richtrack[] Richtracks { get; set; }
[JsonProperty("on-air")] public OnAir OnAir { get; set; }
}
public class OnAir
{
[JsonProperty("broadcasts")] public Next[] Broadcasts { get; set; }
[JsonProperty("broadcastNowIndex")] public long BroadcastNowIndex { get; set; }
[JsonProperty("now")] public Next Now { get; set; }
[JsonProperty("next")] public Next Next { get; set; }
}
public class Next
{
[JsonProperty("entityName")] public string EntityName { get; set; }
[JsonProperty("pid")] public string Pid { get; set; }
[JsonProperty("imagePID")] public string ImagePid { get; set; }
[JsonProperty("imageTemplateURL")] public string ImageTemplateUrl { get; set; }
[JsonProperty("url")] public string Url { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("shortSynopsis")] public string ShortSynopsis { get; set; }
[JsonProperty("shortestSynopsis")] public string ShortestSynopsis { get; set; }
[JsonProperty("mediumSynopsis")] public string MediumSynopsis { get; set; }
[JsonProperty("mediumestSynopsis")] public string MediumestSynopsis { get; set; }
[JsonProperty("longSynopsis")] public string LongSynopsis { get; set; }
[JsonProperty("longestSynopsis")] public string LongestSynopsis { get; set; }
[JsonProperty("duration")] public string Duration { get; set; }
[JsonProperty("mediaType")] public string MediaType { get; set; }
[JsonProperty("canShare")] public bool CanShare { get; set; }
[JsonProperty("canFavourite")] public bool CanFavourite { get; set; }
[JsonProperty("canPlay")] public bool CanPlay { get; set; }
[JsonProperty("canLove")] public bool CanLove { get; set; }
[JsonProperty("percentage")] public long Percentage { get; set; }
[JsonProperty("isOnNow")] public bool IsOnNow { get; set; }
[JsonProperty("start_time")] public string StartTime { get; set; }
[JsonProperty("end_time")] public string EndTime { get; set; }
[JsonProperty("primary_title")] public string PrimaryTitle { get; set; }
[JsonProperty("secondary_title")] public string SecondaryTitle { get; set; }
}
public class Richtrack
{
[JsonProperty("record_id")] public string RecordId { get; set; }
[JsonProperty("artist")] public string Artist { get; set; }
[JsonProperty("contributions")] public Contribution[] Contributions { get; set; }
[JsonProperty("title")] public string Title { get; set; }
[JsonProperty("duration")] public Duration Duration { get; set; }
[JsonProperty("start")] public string Start { get; set; }
[JsonProperty("end")] public string End { get; set; }
[JsonProperty("service")] public Service Service { get; set; }
[JsonProperty("musicbrainz_id")] public string MusicbrainzId { get; set; }
[JsonProperty("image")] public Image Image { get; set; }
[JsonProperty("is_now_playing")] public bool IsNowPlaying { get; set; }
[JsonProperty("programme_offset")] public long ProgrammeOffset { get; set; }
[JsonProperty("has_snippet")] public bool HasSnippet { get; set; }
[JsonProperty("last_played")] public long LastPlayed { get; set; }
[JsonProperty("track_type")] public string TrackType { get; set; }
}
public class Contribution
{
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("role")] public string Role { get; set; }
[JsonProperty("musicbrainz_id", NullValueHandling = NullValueHandling.Ignore)]
public Guid? MusicbrainzId { get; set; }
[JsonProperty("sort_name", NullValueHandling = NullValueHandling.Ignore)]
public string SortName { get; set; }
[JsonProperty("image_pid", NullValueHandling = NullValueHandling.Ignore)]
public string ImagePid { get; set; }
[JsonProperty("contributor_pid")] public string ContributorPid { get; set; }
[JsonProperty("contribution_pid")] public string ContributionPid { get; set; }
}
public class Duration
{
[JsonProperty("seconds")] public long Seconds { get; set; }
[JsonProperty("minutes")] public long Minutes { get; set; }
}
public class Image
{
[JsonProperty("pid")] public string Pid { get; set; }
[JsonProperty("type")] public string Type { get; set; }
}
public class Service
{
[JsonProperty("sid")] public string Sid { get; set; }
[JsonProperty("name")] public string Name { get; set; }
[JsonProperty("type")] public string Type { get; set; }
[JsonProperty("region")] public string Region { get; set; }
}
public class Timeouts
{
[JsonProperty("polling_timeout")] public long PollingTimeout { get; set; }
}
}
|
//---------------------------------------------------------------------
// <copyright file="EntityDataSourceQueryBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner Microsoft
// @backupOwner Microsoft
//---------------------------------------------------------------------
namespace System.Web.UI.WebControls
{
using System.Collections;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
internal abstract class EntityDataSourceQueryBuilder<T>
{
private readonly DataSourceSelectArguments _arguments;
private readonly string _commandText;
private readonly ObjectParameter[] _commandParameters;
private readonly string _whereExpression;
private readonly ObjectParameter[] _whereParameters;
private readonly string _entitySetQueryExpression;
private readonly OrderByBuilder _orderByBuilder;
private string _includePaths;
private TypeUsage _resultType;
private Nullable<int> _count;
protected EntityDataSourceQueryBuilder(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths)
{
_arguments = arguments;
_commandText = commandText;
_commandParameters = commandParameters;
_whereExpression = whereExpression;
_whereParameters = whereParameters;
_entitySetQueryExpression = entitySetQueryExpression;
_orderByBuilder = orderByBuilder;
_includePaths = includePaths;
}
internal delegate EntityDataSourceQueryBuilder<T> Creator(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths);
internal TypeUsage ResultType
{
get
{
Debug.Assert(_resultType != null, "ResultType is only valid after Build()");
return _resultType;
}
}
internal int TotalCount
{
get
{
Debug.Assert(_count.HasValue, "Count is not valid until after Build. And only then if computeCount is true");
return _count.Value;
}
}
internal IEnumerable Execute(ObjectQuery<T> queryT)
{
return (IEnumerable)(((IListSource)(queryT)).GetList());
}
internal ObjectQuery<T> BuildBasicQuery(ObjectContext context, bool computeCount)
{
ObjectQuery<T> queryT = QueryBuilderUtils.ConstructQuery<T>(context, _entitySetQueryExpression, _commandText, _commandParameters);
queryT = ApplyWhere(queryT);
queryT = ApplySelect(queryT); // Select and/or GroupBy application
_resultType = queryT.GetResultType();
return queryT;
}
internal ObjectQuery<T> CompleteBuild(ObjectQuery<T> queryT, ObjectContext context, bool computeCount, bool wasExtended)
{
if (computeCount)
{
_count = queryT.Count();
}
queryT = wasExtended ? ApplyQueryableOrderByAndPaging(queryT) : ApplyOrderByAndPaging(queryT);
queryT = ApplyIncludePaths(queryT);
return queryT;
}
private ObjectQuery<T> ApplyWhere(ObjectQuery<T> queryT)
{
if (!String.IsNullOrEmpty(_whereExpression))
{
queryT = queryT.Where(_whereExpression, _whereParameters);
}
return queryT;
}
protected abstract ObjectQuery<T> ApplySelect(ObjectQuery<T> queryT);
internal ObjectQuery<T> ApplyOrderBy(ObjectQuery<T> queryT)
{
string orderByClause;
ObjectParameter[] orderByParameters;
// Apply all possible ordering except the sort expression, because it might only be valid after the query has been extended
_orderByBuilder.Generate(_resultType, out orderByClause, out orderByParameters, false /*applySortExpression*/);
return String.IsNullOrEmpty(orderByClause) ? queryT : queryT.OrderBy(orderByClause, orderByParameters);
}
private ObjectQuery<T> ApplyOrderByAndPaging(ObjectQuery<T> queryT)
{
// This re-applys the order-by as part of the skip
string orderByClause;
ObjectParameter[] orderByParameters;
_orderByBuilder.Generate(_resultType, out orderByClause, out orderByParameters, true /*applySortExpression*/);
bool paging = _arguments.MaximumRows > 0 && _arguments.StartRowIndex >= 0;
var hasOrderByClause = !String.IsNullOrEmpty(orderByClause);
if (paging)
{
if (!hasOrderByClause)
{
throw new InvalidOperationException(Strings.EntityDataSourceQueryBuilder_PagingRequiresOrderBy);
}
queryT = queryT.Skip(orderByClause, _arguments.StartRowIndex.ToString(CultureInfo.InvariantCulture), orderByParameters).Top(_arguments.MaximumRows.ToString(CultureInfo.InvariantCulture), QueryBuilderUtils.EmptyObjectParameters);
}
else
{
if (hasOrderByClause)
{
queryT = queryT.OrderBy(orderByClause, orderByParameters);
}
}
return queryT;
}
private ObjectQuery<T> ApplyQueryableOrderByAndPaging(ObjectQuery<T> queryT)
{
queryT = _orderByBuilder.BuildQueryableOrderBy(queryT) as ObjectQuery<T>;
bool paging = _arguments.MaximumRows > 0 && _arguments.StartRowIndex >= 0;
if (paging)
{
queryT = queryT.Skip(_arguments.StartRowIndex).Take(_arguments.MaximumRows) as ObjectQuery<T>;
}
return queryT;
}
private ObjectQuery<T> ApplyIncludePaths(ObjectQuery<T> objectQuery)
{
if (!string.IsNullOrEmpty(_includePaths))
{
foreach (string include in _includePaths.Split(','))
{
string trimmedInclude = include.Trim();
if (!string.IsNullOrEmpty(trimmedInclude))
{
objectQuery = objectQuery.Include(trimmedInclude);
}
}
}
return objectQuery;
}
}
internal class EntityDataSourceObjectQueryBuilder<T> : EntityDataSourceQueryBuilder<T>
{
private EntityDataSourceObjectQueryBuilder(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths)
: base(arguments,
commandText, commandParameters,
whereExpression, whereParameters, entitySetQueryExpression,
selectExpression, groupByExpression, selectParameters,
orderByBuilder,
includePaths)
{
}
static internal EntityDataSourceQueryBuilder<T>.Creator GetCreator()
{
return Create;
}
static internal EntityDataSourceQueryBuilder<T> Create(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths)
{
return new EntityDataSourceObjectQueryBuilder<T>(arguments,
commandText, commandParameters,
whereExpression, whereParameters, entitySetQueryExpression,
selectExpression, groupByExpression, selectParameters,
orderByBuilder,
includePaths);
}
protected override ObjectQuery<T> ApplySelect(ObjectQuery<T> queryT)
{
return queryT;
}
}
internal class EntityDataSourceRecordQueryBuilder : EntityDataSourceQueryBuilder<DbDataRecord>
{
private readonly string _selectExpression;
private readonly string _groupByExpression;
private readonly ObjectParameter[] _selectParameters;
private EntityDataSourceRecordQueryBuilder(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths)
: base(arguments,
commandText, commandParameters,
whereExpression, whereParameters, entitySetQueryExpression,
selectExpression, groupByExpression, selectParameters,
orderByBuilder,
includePaths)
{
_selectExpression = selectExpression;
_groupByExpression = groupByExpression;
_selectParameters = selectParameters;
}
static internal EntityDataSourceQueryBuilder<DbDataRecord> Create(DataSourceSelectArguments arguments,
string commandText, ObjectParameter[] commandParameters,
string whereExpression, ObjectParameter[] whereParameters, string entitySetQueryExpression,
string selectExpression, string groupByExpression, ObjectParameter[] selectParameters,
OrderByBuilder orderByBuilder,
string includePaths)
{
return new EntityDataSourceRecordQueryBuilder(arguments,
commandText, commandParameters,
whereExpression, whereParameters, entitySetQueryExpression,
selectExpression, groupByExpression, selectParameters,
orderByBuilder,
includePaths);
}
protected override ObjectQuery<DbDataRecord> ApplySelect(ObjectQuery<DbDataRecord> queryT)
{
Debug.Assert(!String.IsNullOrEmpty(_selectExpression), "Select expression should not be of zero length.");
if (!string.IsNullOrEmpty(_groupByExpression))
{
queryT = queryT.GroupBy(_groupByExpression, _selectExpression, _selectParameters);
}
else
{
queryT = queryT.Select(_selectExpression, _selectParameters);
}
return queryT;
}
}
internal static class QueryBuilderUtils
{
internal static readonly ObjectParameter[] EmptyObjectParameters = new ObjectParameter[] { };
internal static ObjectQuery<T> ConstructQuery<T>(ObjectContext context,
string entitySetQueryExpression,
string commandText,
ObjectParameter[] commandParameters)
{
string queryExpression;
ObjectParameter[] queryParameters;
if (!string.IsNullOrEmpty(commandText))
{
queryExpression = commandText;
queryParameters = commandParameters;
}
else
{
queryExpression = entitySetQueryExpression;
queryParameters = QueryBuilderUtils.EmptyObjectParameters;
}
return context.CreateQuery<T>(queryExpression, queryParameters);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Displays Area Attributes
/// </summary>
public class AreaAttributeDisplay : MonoBehaviour {
[SerializeField]
private Text statNameDisplay;
[SerializeField]
private Text currentValueDisplay;
[SerializeField]
private Text additionalValueDisplay;
/// <summary>
/// Updates the text fields and position for the attribute display
/// </summary>
public void UpdateAttributeDisplay(string statName, string currentValue, string additionalValue, Vector3 position)
{
statNameDisplay.text = statName;
currentValueDisplay.text = currentValue;
additionalValueDisplay.text = "+ " + additionalValue;
RectTransform rT = GetComponent<RectTransform>();
rT.position = position;
}
}
|
using PropertyChanged;
namespace Zaggoware.Prism.Forms.ViewModels
{
using System.Threading.Tasks;
using global::Prism.Navigation;
using global::Prism.Services;
using Xamarin.Essentials;
using Xamarin.Forms;
public abstract class ApiPageViewModelBase<TData> : PageViewModelBase
where TData : class
{
public ApiPageViewModelBase(
INavigationService navigationService,
IPageDialogService pageDialogService)
: base(navigationService, pageDialogService)
{
}
public bool HasContent { get; set; } = true;
public bool HasInternetConnection => Connectivity.NetworkAccess == NetworkAccess.Internet;
public bool IsLoading { get; set; }
public override async void OnAppearing()
{
base.OnAppearing();
Connectivity.ConnectivityChanged += OnConnectivityChanged;
await OnLoadAsync();
}
public override void OnDisappearing()
{
base.OnDisappearing();
Connectivity.ConnectivityChanged -= OnConnectivityChanged;
}
protected async Task<TData?> LoadApiDataAsync()
{
var data = await Task.Run(async () => await OnLoadApiDataAsync()).ConfigureAwait(false);
Device.BeginInvokeOnMainThread(() => UpdateContent(data));
return data;
}
protected TData? LoadCachedData()
{
var data = OnLoadCachedData();
UpdateContent(data);
return data;
}
[SuppressPropertyChangedWarnings]
protected virtual async void OnConnectivityChanged(object sender, ConnectivityChangedEventArgs args)
{
if (args.NetworkAccess == NetworkAccess.Internet)
{
await LoadApiDataAsync();
}
}
protected abstract Task<TData?> OnLoadApiDataAsync();
protected virtual async Task OnLoadAsync()
{
IsLoading = true;
LoadCachedData();
if (!HasInternetConnection)
{
IsLoading = false;
return;
}
await LoadApiDataAsync();
IsLoading = false;
}
protected abstract TData? OnLoadCachedData();
protected abstract void OnUpdateContent(TData data);
private void UpdateContent(TData? data)
{
HasContent = data != null;
if (data != null)
{
OnUpdateContent(data);
}
}
}
} |
using UnityEngine;
using System.Collections;
public class FPH_NumPad_Interactor : MonoBehaviour {
public GameObject numpadCamera;
public GameObject ingameCamera;
public string codeToCheck;
public bool controlWithKeyboard;
public FPH_NumPad_Buttons numpadButtons00;
public FPH_NumPad_Buttons numpadButtons01;
public FPH_NumPad_Buttons numpadButtons02;
public FPH_NumPad_Buttons numpadButtons03;
public FPH_NumPad_Buttons numpadButtons04;
public FPH_NumPad_Buttons numpadButtons05;
public FPH_NumPad_Buttons numpadButtons06;
public FPH_NumPad_Buttons numpadButtons07;
public FPH_NumPad_Buttons numpadButtons08;
public FPH_NumPad_Buttons numpadButtons09;
public FPH_NumPad_Buttons numpadButtonsBack;
public FPH_NumPad_Buttons numpadButtonsConfirm;
public MeshRenderer numpadButtonMeshes00;
public MeshRenderer numpadButtonMeshes01;
public MeshRenderer numpadButtonMeshes02;
public MeshRenderer numpadButtonMeshes03;
public MeshRenderer numpadButtonMeshes04;
public MeshRenderer numpadButtonMeshes05;
public MeshRenderer numpadButtonMeshes06;
public MeshRenderer numpadButtonMeshes07;
public MeshRenderer numpadButtonMeshes08;
public MeshRenderer numpadButtonMeshes09;
public MeshRenderer numpadButtonMeshesBack;
public MeshRenderer numpadButtonMeshesConfirm;
public Material notSelectedMaterial;
public Material selectedMaterial;
// If the code we entered on the numpad is right we can send a message to an object or save a value
public string[] onOkArray = new string[] {"SendMessage", "SetVar"};
public int onOk;
public bool reEnableOnOk; // Do you want to reenable the collider when you exit the numpad screen?
public GameObject sendMessageTo; // Object you want to send the message to
public string messageToSend; // The message we want to send
public string[] keyTypeArray = new string[] {"Float", "Int", "String", "Bool"};
public int keyType;
// In case you want to save a value you can choose from four different value
public string neededKey;
public float valueToSet_Float;
public int valueToSet_Int;
public string valueToSet_String;
public bool valueToSet_Bool;
private Collider thisColl;
private string[,] keyboardArray = new string[4, 3] {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"BACK", "0", "OK"}
};
private Vector2 arrayPos = new Vector2(0.0f, 0.0f);
// Use this for initialization
void Start(){
thisColl = gameObject.GetComponent<Collider>();
if(onOk == 1){ // SetVar
// We check if the value has been setted before, in this case we toggle the collider
if(keyType == 0){ // Float
float floatToCheck = PlayerPrefs.GetFloat(neededKey);
if(floatToCheck == valueToSet_Float){
thisColl.enabled = false;
}
}
else if(keyType == 1){ // Int
int intToCheck = PlayerPrefs.GetInt(neededKey);
if(intToCheck == valueToSet_Int){
thisColl.enabled = false;
}
}
else if(keyType == 2){ // String
string stringToCheck = PlayerPrefs.GetString(neededKey);
if(stringToCheck == valueToSet_String){
thisColl.enabled = false;
}
}
else if(keyType == 3){ // Bool
bool boolToCheck = FPH_ControlManager.LoadBool(neededKey);
if(boolToCheck == valueToSet_Bool){
thisColl.enabled = false;
}
}
}
}
// Update is called once per frame
void Update(){
if(controlWithKeyboard && numpadCamera.activeSelf){
if(Input.GetKeyUp(KeyCode.RightArrow)){
if(arrayPos.x <= 2.0f){
arrayPos.x++;
}
if(arrayPos.x > 2.0f){
arrayPos.x = 0;
}
}
if(Input.GetKeyUp(KeyCode.LeftArrow)){
if(arrayPos.x >= 0.0f){
arrayPos.x--;
}
if(arrayPos.x < 0.0f){
arrayPos.x = 2.0f;
}
}
if(Input.GetKeyUp(KeyCode.UpArrow)){
if(arrayPos.y >= 0.0f){
arrayPos.y--;
}
if(arrayPos.y < 0.0f){
arrayPos.y = 3.0f;
}
}
if(Input.GetKeyUp(KeyCode.DownArrow)){
if(arrayPos.y <= 3.0f){
arrayPos.y++;
}
if(arrayPos.y > 3.0f){
arrayPos.y = 0;
}
}
string currentSelected = keyboardArray[(int)arrayPos.y, (int)arrayPos.x];
if(currentSelected == "0"){
numpadButtonMeshes00.material = selectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons00.OnTouchUp();
}
}
if(currentSelected == "1"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = selectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons01.OnTouchUp();
}
}
if(currentSelected == "2"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = selectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons02.OnTouchUp();
}
}
if(currentSelected == "3"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = selectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons03.OnTouchUp();
}
}
if(currentSelected == "4"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = selectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons04.OnTouchUp();
}
}
if(currentSelected == "5"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = selectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons05.OnTouchUp();
}
}
if(currentSelected == "6"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = selectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons06.OnTouchUp();
}
}
if(currentSelected == "7"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = selectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons07.OnTouchUp();
}
}
if(currentSelected == "8"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = selectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons08.OnTouchUp();
}
}
if(currentSelected == "9"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = selectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtons09.OnTouchUp();
}
}
if(currentSelected == "BACK"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = selectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtonsBack.OnTouchUp();
}
}
if(currentSelected == "OK"){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = selectedMaterial;
if(Input.GetKeyUp(KeyCode.Return)){
numpadButtonsConfirm.OnTouchUp();
}
}
}
}
public void Interact(){
FPH_ControlManager.isScreenLocked = false; // Screen.lockCursor = false;
thisColl.enabled = false;
ingameCamera.SetActive(false);
numpadCamera.SetActive(true);
FPH_ControlManager.canBeControlled = false;
}
// If the code is right we send the message/setvalue and then deactivate the numpadCamera
public void DoneCode(){
if(onOk == 0){ // SendMessage
if(sendMessageTo != null){
sendMessageTo.SendMessage(messageToSend);
}
if(sendMessageTo == null){
Debug.LogWarning("No receiver for message - FPH_NumPad_Interactor " + this.gameObject.name);
}
if(reEnableOnOk){
thisColl.enabled = true;
}
if(controlWithKeyboard){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
}
ingameCamera.SetActive(true);
numpadCamera.SetActive(false);
FPH_ControlManager.canBeControlled = true;
FPH_ControlManager.isScreenLocked = true; // Screen.lockCursor = true;
}
else if(onOk == 1){ // SetVar
if(keyType == 0){ // Float
PlayerPrefs.SetFloat(neededKey, valueToSet_Float);
}
else if(keyType == 1){ // Int
PlayerPrefs.SetInt(neededKey, valueToSet_Int);
}
else if(keyType == 2){ // String
PlayerPrefs.SetString(neededKey, valueToSet_String);
}
else if(keyType == 3){ // Bool
FPH_ControlManager.SaveBool(neededKey, valueToSet_Bool);
}
if(reEnableOnOk){
thisColl.enabled = true;
}
if(controlWithKeyboard){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
}
ingameCamera.SetActive(true);
numpadCamera.SetActive(false);
FPH_ControlManager.canBeControlled = true;
FPH_ControlManager.isScreenLocked = true; // Screen.lockCursor = true;
}
}
public void ExitNumpad(){
if(controlWithKeyboard){
numpadButtonMeshes00.material = notSelectedMaterial;
numpadButtonMeshes01.material = notSelectedMaterial;
numpadButtonMeshes02.material = notSelectedMaterial;
numpadButtonMeshes03.material = notSelectedMaterial;
numpadButtonMeshes04.material = notSelectedMaterial;
numpadButtonMeshes05.material = notSelectedMaterial;
numpadButtonMeshes06.material = notSelectedMaterial;
numpadButtonMeshes07.material = notSelectedMaterial;
numpadButtonMeshes08.material = notSelectedMaterial;
numpadButtonMeshes09.material = notSelectedMaterial;
numpadButtonMeshesBack.material = notSelectedMaterial;
numpadButtonMeshesConfirm.material = notSelectedMaterial;
}
FPH_ControlManager.isScreenLocked = true; // Screen.lockCursor = true;
thisColl.enabled = true;
ingameCamera.SetActive(true);
numpadCamera.SetActive(false);
FPH_ControlManager.canBeControlled = true;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.ValueProviders;
namespace ConsoleApplicationOWIN.Providers
{
public class DummyValueProvider : IValueProvider
{
public DummyValueProvider()
{
}
public bool ContainsPrefix(string prefix)
{
return true;
}
public ValueProviderResult GetValue(string key)
{
return null;
}
}
public class DummyValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return new DummyValueProvider();
}
}
}
|
using NSubstitute;
using NUnit.Framework;
using ygo.domain.Services;
using ygo.domain.SystemIO;
using ygo.tests.core;
namespace ygo.domain.unit.tests.ServiceTests.FileSystemServiceTests
{
[TestFixture]
[Category(TestType.Unit)]
public class DeleteTests
{
private IFileSystem _fileSystem;
private FileSystemService _sut;
[SetUp]
public void SetUp()
{
_fileSystem = Substitute.For<IFileSystem>();
_sut = new FileSystemService(_fileSystem);
}
[Test]
public void Given_A_LocalFileFullPath_Should_Invoke_Delete_Method_Once()
{
// Arrange
const string localFileFullPath = @"c:\images\pic.png";
// Act
_sut.Delete(localFileFullPath);
// Assert
_fileSystem.Received(1).Delete(Arg.Is(localFileFullPath));
}
}
} |
namespace EA.Iws.Web.Infrastructure
{
using System.Web.Mvc;
public static class NavigationExtensions
{
public static Navigation Navigation(this HtmlHelper htmlHelper)
{
return new Navigation(htmlHelper);
}
}
} |
using Xms.Core.Data;
using Xms.Data.Import.Domain;
namespace Xms.Data.Import.Data
{
/// <summary>
/// 导入字段映射仓储
/// </summary>
public class ImportMapRepository : DefaultRepository<ImportMap>, IImportMapRepository
{
public ImportMapRepository(IDbContext dbContext) : base(dbContext)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using FytSoa.Core.Model.Bbs;
using FytSoa.Core.Model.Member;
namespace FytSoa.Service.DtoModel
{
/// <summary>
/// 前端右侧数据汇总
/// </summary>
public class PageRightDto
{
/// <summary>
/// 问题总数
/// </summary>
public int QuestionCount { get; set; } = 0;
/// <summary>
/// 会员总数
/// </summary>
public int UserCount { get; set; } = 0;
/// <summary>
/// 热门标签
/// </summary>
public List<TagsCount> TagList { get; set; }
/// <summary>
/// 热门问题
/// </summary>
public List<Bbs_Questions> RedQuestionList { get; set; }
/// <summary>
/// 推荐专家
/// </summary>
public List<MemberQuestion> ExpertList { get; set; }
}
/// <summary>
/// 常用标签
/// </summary>
public class TagsCount
{
public string TagName { get; set; }
public string EnTagName { get; set; }
public int TagCount { get; set; }
}
/// <summary>
/// 热门话题
/// </summary>
public class MemberQuestion
{
/// <summary>
/// 编号
/// </summary>
public string Guid { get; set; }
/// <summary>
/// 昵称
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 头像
/// </summary>
public string HeadPic { get; set; }
/// <summary>
/// 加入时间
/// </summary>
public DateTime AddTime { get; set; }
/// <summary>
/// 回答总数
/// </summary>
public int AnswerCount { get; set; }
/// <summary>
/// 采纳总数
/// </summary>
public int AdoptCount { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using mybooks.contracts;
using mybooks.eventstoreprovider;
using mybooks.logic;
namespace mybooks
{
public class Interactors
{
private readonly IEventStoreProvider _eventStoreProvider;
private readonly Booklending _booklending = new Booklending();
public Interactors() : this(new EventStoreProvider()) {
}
internal Interactors(IEventStoreProvider eventStoreProvider) {
_eventStoreProvider = eventStoreProvider;
}
public IEnumerable<Book> Start() {
var events = _eventStoreProvider.Read_all_events();
var books = _booklending.Create_list_of_books(events);
return books;
}
public IEnumerable<Book> New_book(string titel) {
var bookCreatedEvent = _booklending.Create_book(titel);
_eventStoreProvider.Save_event(bookCreatedEvent);
var events = _eventStoreProvider.Read_all_events();
var books = _booklending.Create_list_of_books(events);
return books;
}
public IEnumerable<Book> Lend_book(Guid id, string name) {
var bookLendedEvent = _booklending.Lend_book(id, name);
_eventStoreProvider.Save_event(bookLendedEvent);
var events = _eventStoreProvider.Read_all_events();
var books = _booklending.Create_list_of_books(events);
return books;
}
public IEnumerable<Book> Book_got_back(Guid id) {
var bookReturnedEvent = _booklending.Return_book(id);
_eventStoreProvider.Save_event(bookReturnedEvent);
var events = _eventStoreProvider.Read_all_events();
var books = _booklending.Create_list_of_books(events);
return books;
}
public IEnumerable<Book> Remove_book(Guid id) {
var bookDeletedEvent = _booklending.Delete_book(id);
_eventStoreProvider.Save_event(bookDeletedEvent);
var events = _eventStoreProvider.Read_all_events();
var books = _booklending.Create_list_of_books(events);
return books;
}
}
} |
using System;
using Microsoft.Extensions.DependencyInjection;
using StrawberryShake.Transport.WebSockets;
namespace StrawberryShake
{
/// <summary>
/// Common extensions of <see cref="IClientBuilder"/> for <see cref="WebSocketConnection"/>
/// </summary>
public static class WebSocketClientBuilderExtensions
{
/// <summary>
/// Adds the <see cref="ISocketClientFactory"/> and related services to the
/// <see cref="IServiceCollection"/> and configures a <see cref="WebSocketClient"/>
/// with the correct name
/// </summary>
/// <param name="clientBuilder">
/// The <see cref="IClientBuilder{T}"/>
/// </param>
/// <param name="configureClient">
/// A delegate that is used to configure an <see cref="WebSocketClient"/>.
/// </param>
public static IClientBuilder<T> ConfigureWebSocketClient<T>(
this IClientBuilder<T> clientBuilder,
Action<ISocketClient> configureClient)
where T : IStoreAccessor
{
if (clientBuilder == null)
{
throw new ArgumentNullException(nameof(clientBuilder));
}
if (configureClient == null)
{
throw new ArgumentNullException(nameof(configureClient));
}
clientBuilder.Services.AddWebSocketClient(clientBuilder.ClientName, configureClient);
return clientBuilder;
}
/// <summary>
/// Adds the <see cref="ISocketClientFactory"/> and related services to the
/// <see cref="IServiceCollection"/> and configures a <see cref="WebSocketClient"/>
/// with the correct name
/// </summary>
/// <param name="clientBuilder">
/// The <see cref="IClientBuilder{T}"/>
/// </param>
/// <param name="configureClient">
/// A delegate that is used to configure an <see cref="WebSocketClient"/>.
/// </param>
public static IClientBuilder<T> ConfigureWebSocketClient<T>(
this IClientBuilder<T> clientBuilder,
Action<IServiceProvider, ISocketClient> configureClient)
where T : IStoreAccessor
{
if (clientBuilder == null)
{
throw new ArgumentNullException(nameof(clientBuilder));
}
if (configureClient == null)
{
throw new ArgumentNullException(nameof(configureClient));
}
clientBuilder.Services.AddWebSocketClient(clientBuilder.ClientName, configureClient);
return clientBuilder;
}
}
}
|
using System;
using System.Text;
using Confluent.Kafka;
using IFramework.Infrastructure;
namespace IFramework.MessageQueue.ConfluentKafka.MessageFormat
{
public class KafkaMessageDeserializer<TValue>: IDeserializer<TValue>
{
public TValue Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
{
return Encoding.UTF8.GetString(data.ToArray()).ToJsonObject<TValue>();
}
}
} |
using FluentMigrator;
namespace Discussion.Migrations
{
[Migration(22)]
public class AddUserIdToWeChatAccountTable : Migration
{
public override void Up()
{
Alter.Table(CreateWeChatAccountTable.TABLE_NAME)
.AddColumn("UserId").AsInt32().Nullable();
}
public override void Down()
{
Delete.Column("UserId")
.FromTable(CreateWeChatAccountTable.TABLE_NAME);
}
}
}
|
using System;
using System.IO;
using System.Windows.Forms;
namespace NPlant.UI
{
public static class SystemEnvironment
{
public static string ExecutionDirectory
{
get { return Path.GetDirectoryName(Application.ExecutablePath); }
}
public static SystemSettings GetSettings()
{
string javaHome = Environment.GetEnvironmentVariable("NPLANT_JAVA_HOME", EnvironmentVariableTarget.User);
if(javaHome.IsNullOrEmpty())
javaHome = System.Environment.GetEnvironmentVariable("JAVA_HOME", EnvironmentVariableTarget.User);
return new SystemSettings()
{
JavaPath = javaHome
};
}
public static void SetSettings(SystemSettings settings)
{
Environment.SetEnvironmentVariable("NPLANT_JAVA_HOME", settings.JavaPath, EnvironmentVariableTarget.User);
}
}
public class SystemSettings
{
public string JavaPath { get; set; }
}
}
|
using System.Collections.Generic;
namespace MTGAHelper.Lib.OutputLogParser.Models.GRE.MatchToClient.GroupReq
{
public class GroupReqRaw : GreMatchToClientSubMessageBase
{
public Prompt prompt { get; set; }
public GroupReq groupReq { get; set; }
public Prompt nonDecisionPlayerPrompt { get; set; }
public string allowCancel { get; set; }
}
public class GroupReq
{
public List<int> instanceIds { get; set; }
public List<GroupSpec> groupSpecs { get; set; }
public int totalSelected { get; set; }
public string groupType { get; set; }
public string context { get; set; }
}
public class GroupSpec
{
public int lowerBound { get; set; }
public int upperBound { get; set; }
public string zoneType { get; set; }
public string subZoneType { get; set; }
}
}
|
// Copyright (c) 2013 Francesco Pretto
// This file is subject to the MS-PL license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio;
using System.Windows;
namespace CodePortify
{
class TextViewPasteCmdTarget : OleCommandTarget
{
private TextViewIdentity _identity;
private TextViewMarginSite _site;
public TextViewPasteCmdTarget(TextViewMarginSite site, TextViewIdentity identity)
{
_site = site;
_identity = identity;
}
public override int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt,
IntPtr pvaIn, IntPtr pvaOut)
{
if (pguidCmdGroup == VSConstants.CMDSETID.StandardCommandSet97_guid &&
nCmdID == (uint)VSConstants.VSStd97CmdID.Paste)
{
// It's a paste command
string pasteText = Clipboard.GetText(TextDataFormat.UnicodeText)
?? Clipboard.GetText(TextDataFormat.Text);
if (!string.IsNullOrEmpty(pasteText))
{
NormalizationSettings settings = MainSite.SettingsCache[_identity];
if (settings != null)
{
char[] processed = TextOperations.Normalize(pasteText.ToCharArray(), settings);
_site.Paste(new string(processed));
}
}
return VSConstants.S_OK;
}
return exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentVerification : MonoBehaviour
{
private Dictionary<string, string> solutionSet;
private int numberOfConnections;
List<List<string>> allConnectedObjects;
public bool verify(){
createSolutionSet();
return getAllConnections();
}
void createSolutionSet(){
solutionSet = new Dictionary<string, string>();
solutionSet.Add("N_north", "L1");
solutionSet.Add("L1", "N_north");
solutionSet.Add("L_north", "C");
solutionSet.Add("C", "L_north");
solutionSet.Add("PE_north", "PE");
solutionSet.Add("PE", "PE_north");
numberOfConnections = 3;
}
public bool getAllConnections(){
ComponentWireTrigger[] componentArray = GameObject.FindObjectsOfType<ComponentWireTrigger>();
List<ComponentWireTrigger> componentList = new List<ComponentWireTrigger>(componentArray);
List<GameObject> connectionList = new List<GameObject>();
foreach(ComponentWireTrigger cWT in componentList){
connectionList.Add(cWT.gameObject);
}
Debug.Log("BA21 - Found " + connectionList.Count + "Components");
int i = 1;
foreach(GameObject connector in connectionList){
Debug.Log("Name Conector" + i + ": " + connector.name);
i++;
}
return checkNumberOfOverallConnections(connectionList);
}
public bool checkNumberOfOverallConnections(List<GameObject> list){
if(list.Count == numberOfConnections){
getListOfConnectedBodies(list);
return checkNumberOfConnectionsPerComponent();
} else{
Debug.Log("False Number of Overall Connections");
return false;
}
}
public void getListOfConnectedBodies(List<GameObject> list){
Debug.Log("entered ListCB");
allConnectedObjects = new List<List<string>>();
foreach(GameObject component in list){
Debug.Log("entered FE1");
FixedJoint[] fixedJoints = component.GetComponents<FixedJoint>();
List<FixedJoint> fixedJointsList = new List<FixedJoint>(fixedJoints);
int i = 1;
foreach(FixedJoint fJList in fixedJointsList){
Debug.Log("Name CB" + i + ": " + fJList.gameObject.name);
i++;
}
allConnectedObjects.Add(extractConnectedBodiesFromFixedJoint(fixedJointsList));
/*int i = 1;
foreach(FixedJoint fJ in fixedJoints){
Debug.Log("entered FE2");
Debug.Log("Name FixedJoint" + i + ": " + fJ.connectedBody.gameObject.name);
i++;
}*/
}
foreach(List<string> tagList in allConnectedObjects){
int i = 1;
foreach(string tag in tagList){
Debug.Log("Name CB" + i + ": " + tag);
i++;
}
}
}
public List<string> extractConnectedBodiesFromFixedJoint(List<FixedJoint> fixedJointList){
Debug.Log("reached extract-method");
List<string> connectedBodies = new List<string>();
foreach(FixedJoint fJ in fixedJointList){
connectedBodies.Add(fJ.connectedBody.gameObject.tag);
connectedBodies.Add(fJ.gameObject.tag);
Debug.Log("added cB " + fJ.connectedBody.gameObject.tag);
}
return connectedBodies;
}
public bool checkNumberOfConnectionsPerComponent(){
bool passed = true;
foreach(List<string> tagList in allConnectedObjects){
Debug.Log("Anzahl Tags : " + tagList.Count);
if(tagList.Count != 2){
passed = false;
}
}
if (passed){
return checkConnections();
} else{
Debug.Log("False Number of Connections per Component");
return false;
}
}
public bool checkConnections(){
bool passed = true;
foreach(List<string> tagList in allConnectedObjects){
Debug.Log("Anzahl Listenelemente: " + tagList.Count);
bool connectionVerification = checkConductorPair(tagList);
if(connectionVerification == false){
passed = false;
}
}
if (passed){
return true;
} else{
Debug.Log("False Connections");
return false;
}
}
public bool checkConductorPair(List<string> tagList){
string tag1 = tagList[0];
string tag2 = tagList[1];
Debug.Log("tag 1/2: " + tag1 + ", " + tag2);
if((solutionSet.ContainsKey(tag1) && solutionSet[tag1].Equals(tag2))){
Debug.Log("True Connection found: " + tag1 + " " + tag2);
return true;
} else {
Debug.Log("PAIR FAILURE DETECTED");
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Axis.Pollux.Common.Models;
namespace Axis.Pollux.Identity.Models
{
public class BioData: BaseModel<Guid>, IUserOwned
{
public DateTimeOffset? DateOfBirth { get; set; }
public string Gender { get; set; }
public string CountryOfBirth { get; set; }
public User Owner { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestProtobuf : MonoBehaviour
{
public static byte[] Encode(ProtoBuf.IExtensible msgBase)
{
using (var memory = new System.IO.MemoryStream())
{
ProtoBuf.Serializer.Serialize(memory, msgBase);
return memory.ToArray();
}
}
public static ProtoBuf.IExtensible Decode(string protoName, byte[] bytes, int offset, int count)
{
using (var memory = new System.IO.MemoryStream(bytes, offset, count))
{
System.Type t = System.Type.GetType(protoName);
return (ProtoBuf.IExtensible)ProtoBuf.Serializer.NonGeneric.Deserialize(t, memory);
}
}
// Start is called before the first frame update
void Start()
{
proto.BattleMsg.MsgMove msgMove = new proto.BattleMsg.MsgMove();
msgMove.x = 214;
byte[] bs = Encode(msgMove);
Debug.Log(System.BitConverter.ToString(bs));
ProtoBuf.IExtensible m = Decode(msgMove.ToString(), bs, 0, bs.Length);
proto.BattleMsg.MsgMove m2 = (proto.BattleMsg.MsgMove)m;
Debug.Log(m2.x);
}
// Update is called once per frame
void Update()
{
}
}
|
using Godot;
using System;
public class BottomlessPit : Area2D
{
private void OnBottomlessPitBodyEntered(Godot.Object body)
{
if (body.HasMethod("Dead"))
{
body.Call("Dead");
}
}
}
|
using Microsoft.IdentityModel.Tokens;
namespace GT.WebServices.API.Application.Security
{
public interface IJwtTokenService
{
string GenerateToken(string serialNumber);
(bool, SecurityToken) ValidateToken(string token);
}
} |
using AutoMapper;
using Fox.Common.Extensions;
using RabbitMQ.Consumer.Models;
namespace RabbitMQ.Consumer.Configurations.AutoMapper
{
public class ProductMapping : Profile
{
public ProductMapping()
{
CreateMap<ProductResponse, Products>(MemberList.None)
.IgnoreAllNonExisting();
}
}
}
|
using CarsManager.Application.Common.Constants;
using FluentValidation;
namespace CarsManager.Application.Repairs.Commands.UpdateRepair
{
public class UpdateRepairCommandValidator : AbstractValidator<UpdateRepairCommand>
{
public UpdateRepairCommandValidator()
{
RuleFor(r => r.Mileage)
.GreaterThanOrEqualTo(RepairConstants.MIN_MILEAGE);
RuleFor(r => r.FinalPrice)
.GreaterThanOrEqualTo(RepairConstants.MIN_INITIAL_PRICE);
}
}
}
|
namespace Sep.Git.Tfs.Core.TfsInterop
{
public interface IItem
{
IVersionControlServer VersionControlServer { get; }
int ChangesetId { get; }
string ServerItem { get; }
decimal DeletionId { get; }
TfsItemType ItemType { get; }
int ItemId { get; }
void DownloadFile(string file);
}
} |
using System.Net;
using System.Threading.Tasks;
namespace FTServer.Network
{
public interface ISender
{
Task SendAsync(byte[] data, IPEndPoint endPoint);
Task RudpSendAsync(byte[] data, IPEndPoint endPoint, int type);
}
}
|
using NPC.Common;
using NPC.Presenter.GameObjects;
using System.Collections.Generic;
namespace NPC.Presenter
{
public interface IFactory
{
IGameObject CreateNew(ObjectType type);
IGameObject Duplicate(IGameObjectReference reference);
IEnumerable<IGameObject> Duplicate(IEnumerable<IGameObjectReference> references);
void CopyTo(IGameObject target, IGameObjectReference source);
}
}
|
using UnityEngine;
namespace uDllExporter
{
public class Test3 : MonoBehaviour
{
void Start()
{
Debug.Log("Test3");
}
}
} |
using System;
using System.Threading;
namespace AsyncOperationInPool
{
class Program
{
/// <summary>
/// reuse the thread by threadpooling
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
const int x = 1;
const int y = 2;
const string lambdaState = "lambda state 2";
ThreadPool.QueueUserWorkItem(AsyncOperation, "async state");
Thread.Sleep(TimeSpan.FromSeconds(1));
ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine($"Operation State:{state ?? (null)}");
Console.WriteLine($"Work thread is:{Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine($"Is Current Thread in ThreadPool:{Thread.CurrentThread.IsThreadPoolThread}");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}, "lambda state");
Thread.Sleep(TimeSpan.FromSeconds(1));
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine($"Operation state:{x + y},{lambdaState}");
Console.WriteLine($"Work thread is:{Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine($"Is Current Thread in ThreadPool:{Thread.CurrentThread.IsThreadPoolThread}");
Thread.Sleep(TimeSpan.FromSeconds(2));
}, "lambda state");
Thread.Sleep(TimeSpan.FromSeconds(2));
}
private static void AsyncOperation(object state)
{
Console.WriteLine($"Operation State:{state ?? (null)}");
Console.WriteLine($"Work thread is:{Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine($"Is Current Thread in ThreadPool:{Thread.CurrentThread.IsThreadPoolThread}");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
}
}
|
using System;
using System.Threading.Tasks;
namespace Kana.Pipelines
{
public interface IMiddleware<TState, TResult>
{
Task<TResult> ExecuteAsync(TState state, Func<Task<TResult>> next);
}
public interface IMiddleware<TState>
{
Task ExecuteAsync(TState state, Func<Task> next);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ExpensesTrackerApp.Core.Account;
using ExpensesTrackerApp.Core;
namespace ExpensesTrackerApp.Core.Account
{
public class AccountBase : IEntity
{
public AccountBase()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public Guid AccountHolderId { get; set; }
public string Iban { get; set; }
public decimal Amount { get; protected set; }
public Customer AccountHolder { get; set; }
public void Deposit(decimal amount)
{
Amount += amount;
}
public decimal Withdraw(decimal amount)
{
if (Amount < amount)
{
throw new InvalidOperationException("Insufficient funds!");
}
else Amount -= amount;
return amount;
}
}
}
|
using System.Collections.Generic;
using System.Data.Linq.Provider.NodeTypes;
namespace System.Data.Linq.Provider.Visitors
{
/// <summary>
/// Validates the integrity of super-SQL trees.
/// </summary>
internal class SqlSupersetValidator
{
List<SqlVisitor> validators = new List<SqlVisitor>();
/// <summary>
/// Add a validator to the collection of validators to run.
/// </summary>
internal void AddValidator(SqlVisitor validator)
{
this.validators.Add(validator);
}
/// <summary>
/// Execute each current validator.
/// </summary>
internal void Validate(SqlNode node)
{
foreach(SqlVisitor validator in this.validators)
{
validator.Visit(node);
}
}
}
} |
namespace CyberCAT.Core.DumpedEnums
{
public enum gamedataWorkspotActionType
{
DeviceInvestigation = 0,
FearHide = 1,
LookAround = 2,
Count = 3,
Invalid = 4
}
}
|
using MELHARFI.Gfx;
namespace MMORPG.Net.Messages.Response
{
internal class ActorDisconnectedResponseMessage : IResponseMessage
{
public void Fetch(string[] commandStrings)
{
#region
// deconnexion du joueur
// suppression de ibPlayer si on ai pas en combat
string _actor = commandStrings[1];
if (MMORPG.Battle.state == Enums.battleState.state.idle)
{
Bmp allPlayers = CommonCode.AllActorsInMap.Find(f => ((Actor)f.tag).pseudo == _actor);
if (allPlayers != null)
{
allPlayers.visible = false;
CommonCode.AllActorsInMap.Remove(allPlayers);
}
}
else
{
CommonCode.ChatMsgFormat("S", "null", _actor + " " + CommonCode.TranslateText(119));
}
//check si nous avons recus une demande de combat ou c'est nous qui ont envoyé cette demande
if (CommonCode.ChallengeTo == _actor)
{
if (CommonCode.annulerChallengeMeDlg != null)
CommonCode.CancelChallengeAsking(_actor);
else
CommonCode.CancelChallengeRespond(_actor);
}
#endregion
}
}
}
|
using UnityEngine;
public interface IColliderMsg
{
void ColliderMsg(Transform other);
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Cake.Core;
using Cake.Core.Diagnostics;
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace Cake.Hosts.Tests
{
public class CakeHostsTests : IDisposable
{
private readonly CakeHosts sut;
private readonly string hostsPath;
public CakeHostsTests()
{
var context = Substitute.For<ICakeContext>();
var log = Substitute.For<ICakeLog>();
sut = new CakeHosts(context, new TestsHostPathProvider(), log);
hostsPath = new TestsHostPathProvider().GetHostsFilePath();
File.Copy(hostsPath, hostsPath + ".backup", overwrite: true);
}
[Fact]
public void RecordExists_WithRecord_True()
{
// Act
var result = sut.HostsRecordExists("127.0.0.1", "NotFound");
// Assert
result.Should().BeTrue();
}
[Fact]
public void NoRecordExists_False()
{
// Act
var result = sut.HostsRecordExists("0.0.0.0", "NotFound");
// Assert
result.Should().BeFalse();
}
[Fact]
public void RecordExists_CommentedHost_False()
{
// Act
var result = sut.HostsRecordExists("127.0.0.1", "DisabledHost.dev");
// Assert
result.Should().BeFalse();
}
[Fact]
public void AddRecord_Always_Adds()
{
// Act
sut.AddHostsRecord("127.0.0.1", "MyTest.dev");
// Assert
var hostsLines = ReadHostsLines();
var hasRecord = hostsLines.Any(l => l == "127.0.0.1 MyTest.dev");
hasRecord.Should().BeTrue();
}
[Fact]
public void AddRecord_CommentedAlready_AddsAnyway()
{
// Act
sut.AddHostsRecord("127.0.0.1", "DisabledHost.dev");
// Assert
var hostsLines = ReadHostsLines();
var hasRecord = hostsLines.Any(l => l == "127.0.0.1 DisabledHost.dev");
var numberOfMentions = hostsLines.Count(l => l.Contains("DisabledHost.dev"));
hasRecord.Should().BeTrue();
numberOfMentions.Should().Be(2);
}
[Fact]
public void AddRecord_AlreadyExist_DoesNotAdd()
{
// Act
sut.AddHostsRecord("127.0.0.1", "ImSpecial");
sut.AddHostsRecord("127.0.0.1", "ImSpecial");
// Assert
var hostsLines = ReadHostsLines();
var numberOfMentions = hostsLines.Count(l => l.Contains("ImSpecial"));
numberOfMentions.Should().Be(1);
}
[Fact]
public void RemoveHostsRecord_Removes_Always()
{
// Act
sut.RemoveHostsRecord("127.0.0.1", "ToBeRemoved.dev");
// Assert
// validate hosts file does not contain the record anymore
var hostsLines = ReadHostsLines();
var hasRecord = hostsLines.Any(l => l.ToLower().Contains("ToBeRemoved.dev".ToLower()));
hasRecord.Should().BeFalse();
}
[Fact]
public void RemoveHostsRecord_Commented_DoesNotChange()
{
// Act
sut.RemoveHostsRecord("127.0.0.1", "ToBeRemoved.disabled");
// Assert
// validate hosts file does not contain the record anymore
var hostsLines = ReadHostsLines();
var hasRecord = hostsLines.Any(l => l.ToLower().Contains("ToBeRemoved.disabled".ToLower()));
hasRecord.Should().BeTrue();
}
[Fact]
public void RemoveHosts_WithoutMathingHost_DoesNotChangeFile()
{
// Arrange
var fileContentsBefore = File.ReadAllText(hostsPath);
// Act
sut.RemoveHostsRecord("8.8.8.8", "blah");
// Assert
var contentsAfter = File.ReadAllText(hostsPath);
contentsAfter.Should().Be(fileContentsBefore);
}
public void Dispose()
{
File.Copy(hostsPath + ".backup", hostsPath, overwrite: true);
}
private List<String> ReadHostsLines()
{
var allLines = File.ReadAllLines(hostsPath).ToList();
return allLines;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace TvMaze.Infrastructure.Data.Factories
{
public class TvMazeDbContextFactory : IDesignTimeDbContextFactory<TvMazeDbContext>
{
public TvMazeDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<TvMazeDbContext>();
builder.UseSqlite("DataSource=tvmaze.db");
return new TvMazeDbContext(builder.Options);
}
}
}
|
public class FloorSection : PoolableObject
{
public int Index;
public delegate void ReachEndEvent(FloorSection Section);
public ReachEndEvent OnReachEnd;
public ReachEndEvent OnReachBeginning;
public override void OnDisable()
{
OnReachBeginning = null;
OnReachEnd = null;
base.OnDisable();
}
}
|
using UnityEngine;
using System.Collections;
/*
* Holder for event names
* Created By: NeilDG
*/
public class EventNames {
public const string ON_UPDATE_SCORE = "ON_UPDATE_SCORE";
public const string ON_CORRECT_MATCH = "ON_CORRECT_MATCH";
public const string ON_WRONG_MATCH = "ON_WRONG_MATCH";
public const string ON_INCREASE_LEVEL = "ON_INCREASE_LEVEL";
public const string ON_PICTURE_CLICKED = "ON_PICTURE_CLICKED";
public class ARBluetoothEvents {
public const string ON_START_BLUETOOTH_DEMO = "ON_START_BLUETOOTH_DEMO";
public const string ON_RECEIVED_MESSAGE = "ON_RECEIVED_MESSAGE";
}
public class ARPhysicsEvents {
public const string ON_FIRST_TARGET_SCAN = "ON_FIRST_TARGET_SCAN";
public const string ON_FINAL_TARGET_SCAN = "ON_FINAL_TARGET_SCAN";
}
public class ExtendTrackEvents {
public const string ON_TARGET_SCAN = "ON_TARGET_SCAN";
public const string ON_TARGET_HIDE = "ON_TARGET_HIDE";
public const string ON_SHOW_ALL = "ON_SHOW_ALL";
public const string ON_HIDE_ALL = "ON_HIDE_ALL";
public const string ON_DELETE_ALL = "ON_DELETE_ALL";
public const string ON_RESET_CLICKED = "ON_RESET_CLICKED";
}
public class VideoAREvents {
public const string ON_VIDEO_DISJOINTED = "ON_VIDEO_DISJOINTED";
public const string ON_VIDEO_ANCHORED = "ON_VIDEO_ANCHORED";
}
public class ARPathFindEvents {
public const string ON_PLATFORM_DETECTED = "ON_PLATFORM_DETECTED";
public const string ON_PLATFORM_HIDDEN = "ON_PLATFORM_HIDDEN";
public const string ON_BEACON_DETECTED = "ON_BEACON_DETECTED";
}
public class ARMoleculeEvents {
public const string ON_BTN_STRUCTURE_CLICKED = "ON_BTN_STRUCTURE_CLICKED";
}
public class ARWreckBallEvents {
public const string ON_RESET_CLICKED = "ON_RESET_CLICKED";
}
}
|
using ShowdownReplayScouter.Core.Data;
using System.Collections.Generic;
namespace ShowdownReplayScouter.Core.Util
{
public static class OutputPrinter
{
public static string Print(ScoutingRequest scoutingRequest, IEnumerable<Team> teams)
{
var output = "";
if (scoutingRequest.Users != null)
{
output += string.Join(", ", scoutingRequest.Users);
}
output += scoutingRequest.Tiers != null ? $" ({string.Join(", ", scoutingRequest.Tiers)})" : "";
output += ":\r\n\r\n";
foreach (var team in teams)
{
output += $"{team}:\r\n";
output += string.Join("\r\n", team.Links);
output += "\r\n\r\n";
output += TeamPrinter.Print(team);
output += "\r\n\r\n\r\n";
}
return output;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FortRun.Model;
using FortRun.BLL.HepSystem;
namespace FortRun.Web.Controllers
{
public class MenuController : BaseController
{
//
// GET: /Menu/
[UserAuthorize]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetMenuList()
{
var json = new JsonData {rows = new MenuHelper(ViewBag.Guid).GetMenu(), success = true};
return Json(json);
}
}
}
|
namespace Solver;
public interface IWordProvider
{
string[] All();
bool Exists(string word);
}
|
// Copyright (c) IEvangelist. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.CosmosRepository.Attributes;
namespace Microsoft.Azure.CosmosRepository.Providers
{
/// <inheritdoc />
class DefaultCosmosUniqueKeyPolicyProvider : ICosmosUniqueKeyPolicyProvider
{
/// <inheritdoc />
public UniqueKeyPolicy? GetUniqueKeyPolicy<TItem>() where TItem : IItem =>
GetUniqueKeyPolicy(typeof(TItem));
public UniqueKeyPolicy? GetUniqueKeyPolicy(Type itemType)
{
Type attributeType = typeof(UniqueKeyAttribute);
Dictionary<string, List<string>> keyNameToPathsMap = new();
foreach ((UniqueKeyAttribute uniqueKey, string propertyName) in itemType.GetProperties()
.Where(x => Attribute.IsDefined(x, attributeType))
.Select(x => (x.GetCustomAttribute<UniqueKeyAttribute>(), x.Name)))
{
string propertyValue = uniqueKey.PropertyPath ?? $"/{propertyName}";
if (keyNameToPathsMap.ContainsKey(uniqueKey.KeyName))
{
keyNameToPathsMap[uniqueKey.KeyName].Add(propertyValue);
continue;
}
keyNameToPathsMap[uniqueKey.KeyName] = new List<string> {propertyValue};
}
if (!keyNameToPathsMap.Any())
{
return null;
}
UniqueKeyPolicy policy = new();
foreach (KeyValuePair<string, List<string>> keyNameToPaths in keyNameToPathsMap)
{
UniqueKey key = new();
foreach (string path in keyNameToPaths.Value)
{
key.Paths.Add(path);
}
policy.UniqueKeys.Add(key);
}
return policy;
}
}
} |
@{
ViewBag.Title = "Cassette | Stylesheets";
}
<h1>Stylesheets</h1>
<p>
Cassette encourages you to break up monolithic stylesheets into a collection of manageable files.
This makes them easier to maintain.
</p>
<p>The order of these files still matters. There are two ways to tell Cassette about the dependencies.
It will then sort them correctly for you.</p>
<h2>Reference Comments</h2>
<p>Use comments at the top of a CSS file to reference other CSS files. For example:</p>
<pre><code><span class="comment">/*
@@reference "reset.css";
@@reference "fonts.css";
*/</span>
<span class="tag">body</span> {
...
}</code></pre>
<p class="minor">Note that @@import was not chosen because that is designed for browser-side evaluation.</p>
<h2>Bundle Descriptor File</h2>
<p>If you'd rather not use reference comments, then this is the alternative.</p>
<p>Create a file called <code>bundle.txt</code> in the same directory as your stylesheets.</p>
<p>List each CSS file name, relative to the directory. For example:</p>
<pre><code>reset.css
fonts.css
main.css
footer.css</code></pre>
<h2>Production Mode</h2>
<p>
When your application is in production mode, the assets of each stylesheet bundle
are concatenated and minified. By default, Cassette uses the Microsoft Ajax CSS Minifier.
</p>
<h2>Image URLs</h2>
<p>Image URLs in the CSS are rewritten. For example, a file <code>~/styles/main.css</code>, with the content:</p>
<pre><code>body { background-image: url(img/bg.jpg); }</code></pre>
<p>is transformed into:</p>
<pre><code>body { background-image: url(/cassette.axd/file/styles/img/bg-25cb72e61bd5ag2.jpg);</code></pre>
<p>This ensures that the URL is domain absolute and not relative to the CSS file. This matters because the CSS file itself
is served from a different URL in production.</p>
<p>In addition, the image file hash is included in the URL. So if the image changes in future, the URL will also change.
This ensures clients never see an out-of-date version of the image.</p>
<p>Cassette uses a custom HTTP handler to serve the image. This handler sends caching headers with the image to make browsers
aggresively cache it.</p> |
using System;
namespace Sidekick.Presentation.Wpf
{
public static class PropertyChangedNotificationInterceptor
{
public static void Intercept(object target, Action onPropertyChangedAction, string propertyName)
{
System.Windows.Application.Current.Dispatcher.Invoke(onPropertyChangedAction);
}
}
}
|
using M.WFEngine.AccessService;
using M.WorkFlow.Model;
namespace M.WFEngine.Task
{
public interface IBaseTask
{
string GetBisData(WFTaskEntity taskEntity, string dataId, string serviceId, EAccessMessageType messageType);
}
}
|
using Livet;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reactive.Linq;
using System.Windows;
using WinCap.ViewModels;
using WinCap.Views;
using WpfUtility.Lifetime;
using WpfUtility.Mvvm;
namespace WinCap.Services
{
/// <summary>
/// ウィンドウを制御する機能を提供します。
/// </summary>
public sealed class WindowService : IDisposableHolder
{
/// <summary>
/// 基本CompositeDisposable
/// </summary>
private readonly LivetCompositeDisposable compositeDisposable;
/// <summary>
/// ウィンドウを格納するコンテナ
/// </summary>
private readonly Dictionary<string, Window> container;
/// <summary>
/// コンストラクタ
/// </summary>
public WindowService()
{
this.compositeDisposable = new LivetCompositeDisposable();
this.container = new Dictionary<string, Window>();
}
/// <summary>
/// コントロール選択ウィンドウを表示します。
/// </summary>
/// <returns>選択したウィンドウハンドル</returns>
public IntPtr? ShowControlSelectionWindow()
{
var window = GetWindow<ControlSelectionWindow, ControlSelectionWindowViewModel>();
var viewModel = window.DataContext as ControlSelectionWindowViewModel;
window.ShowDialog();
return viewModel.Result;
}
/// <summary>
/// 領域選択ウィンドウを表示します。
/// </summary>
/// <returns>選択した領域</returns>
public Rectangle? ShowRegionSelectionWindow()
{
var window = GetWindow<RegionSelectionWindow, RegionSelectionWindowViewModel>();
var viewModel = window.DataContext as RegionSelectionWindowViewModel;
window.ShowDialog();
return viewModel.Result;
}
/// <summary>
/// ウィンドウを取得します。
/// </summary>
/// <typeparam name="TWindow">ウィンドウの型</typeparam>
/// <typeparam name="TViewModel">ViewModelの型</typeparam>
/// <returns>ウィンドウのインスタンス</returns>
private TWindow GetWindow<TWindow, TViewModel>()
where TWindow : Window, new()
where TViewModel : WindowViewModel, new()
{
var windowName = typeof(TWindow).Name;
if (!this.container.ContainsKey(windowName))
{
var viewModel = new TViewModel();
var window = new TWindow()
{
DataContext = viewModel
};
Observable.FromEventPattern(window, nameof(window.Closed))
.Subscribe(x => this.container.Remove(windowName))
.AddTo(this);
Observable.FromEventPattern(window, nameof(window.ContentRendered))
.Subscribe(x => (x.Sender as TWindow).Activate())
.AddTo(this);
Observable.FromEventPattern(window, nameof(window.Activated))
.Select(x => (x.Sender as TWindow).DataContext as TViewModel)
.Where(x => x.IsInitialized)
.Subscribe(_ => viewModel.Initialize())
.AddTo(this);
this.container.Add(windowName, window);
}
return this.container[windowName] as TWindow;
}
#region IDisposableHoloder members
ICollection<IDisposable> IDisposableHolder.CompositeDisposable => this.compositeDisposable;
/// <summary>
/// このインスタンスによって使用されているリソースを全て破棄します。
/// </summary>
public void Dispose()
{
this.compositeDisposable.Dispose();
}
#endregion
}
}
|
using System.Reflection;
namespace Xunit.v3
{
/// <summary>
/// Represents a reflection-backed implementation of <see cref="_IAssemblyInfo"/>.
/// </summary>
public interface _IReflectionAssemblyInfo : _IAssemblyInfo
{
/// <summary>
/// Gets the underlying <see cref="Assembly"/> for the assembly.
/// </summary>
Assembly Assembly { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Compiler
{
public class JumpToken
{
private JumpTokenKind kind;
private List<IntToken> jumpSite32 = new List<IntToken>();
private List<LongToken> jumpSite64 = new List<LongToken>();
private Placeholder destination;
private bool destinationSet;
public bool DestinationSet { get { return destinationSet; } }
public int JumpCount { get { return jumpSite32.Count + jumpSite64.Count; } }
public void SetKind(JumpTokenKind kind)
{
this.kind = kind;
}
public void SetDestination(Placeholder location)
{
if (destinationSet)
throw new InvalidOperationException();
destination = location;
destinationSet = true;
if ((jumpSite32 != null) || (jumpSite64 != null))
Complete();
}
public void SetJumpSite(IntToken jumpSite)
{
if (jumpSite == null)
throw new ArgumentNullException("jumpSite");
this.jumpSite32.Add(jumpSite);
if (destinationSet)
Complete();
}
public void SetJumpSite(LongToken jumpSite)
{
if (jumpSite == null)
throw new ArgumentNullException("jumpSite");
this.jumpSite64.Add(jumpSite);
if (destinationSet)
Complete();
}
public void Complete()
{
if (kind == JumpTokenKind.Absolute)
{
Require.Implementation("Cannot complete an absolute jumptoken.");
}
else
{
foreach (IntToken entry in jumpSite32)
entry.SetValue((int)destination.MemoryDistanceFrom(entry.Location.Increment(4)));
foreach (LongToken entry in jumpSite64)
entry.SetValue(destination.MemoryDistanceFrom(entry.Location.Increment(8)));
}
}
}
public enum JumpTokenKind { Relative, Absolute };
} |
/******************************************************************************
* Project 1 - Tic Tac Toe
*
* Develop a Tic Tac Toe intelligent agent that players as 'O'.
* Author: Emmanuel Ndubuisi
* Date: March 11, 2021
*
* Compilation and Execution: https://repl.it/@mcndubuisi/TicTacToe
******************************************************************************/
using System;
using System.Collections.Generic;
class TicTacToe
{
public static char[,] board = new char[3,3]{{'-', '-', '-'}, {'-', '-', '-'}, {'-', '-', '-'}};
public static char computer = 'O';
public static char human = 'X';
public static void play()
{
int[] coordinates = bestMove();
board[coordinates[0], coordinates[1]] = computer;
printBoard();
if(hasWon()) System.Environment.Exit(1);
}
// find the best move for agent
public static int[] bestMove()
{
int bestScore = int.MinValue;
int[] move = null;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i,j] == '-')
{
board[i,j] = computer;
int score = minimax(board, 0, false);
board[i,j] = '-';
if (score > bestScore)
{
bestScore = score;
move = new int[] { i, j };
}
}
}
}
return move;
}
// minimax algorithm that return best score per move
public static int minimax(char[,] board, int depth, bool isMaximizing)
{
string result = checkWinner();
var scores = new Dictionary<string, int>(){
{"X", -10}, {"O", 10}, {"tie", 0}
};
if (result != null)
{
return scores[result];
}
if (isMaximizing)
{
int bestScore = int.MinValue;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i,j] == '-')
{
board[i,j] = computer;
int score = minimax(board, depth + 1, false);
board[i,j] = '-';
bestScore = Math.Max(score, bestScore);
}
}
}
return bestScore;
}
else
{
int bestScore = int.MaxValue;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// Is the spot available?
if (board[i,j] == '-') {
board[i,j] = human;
int score = minimax(board, depth + 1, true);
board[i,j] = '-';
bestScore = Math.Min(score, bestScore);
}
}
}
return bestScore;
}
}
// check if board is empty
public static bool isEmpty(int x, int y)
{
if(board[x,y] == '-')
{
return true;
}
return false;
}
// check if there is a winner or a full board.
public static bool hasWon()
{
if (checkWinner() == "tie")
{
Console.Write("It was a draw.\n");
}
else if (checkWinner() != null)
{
Console.Write($"Player {checkWinner()} wins!\n");
}
return checkRow() != null || checkColumn() != null || checkDiagonal() != null || isBoardFull();
}
// return the name of the winner
public static string checkWinner()
{
if (isBoardFull()) return "tie";
return checkRow() ?? checkColumn() ?? checkDiagonal();
}
// check rows for winner
public static string checkRow()
{
for(int i=0; i<3; i++)
{
if(board[i,0] != '-' && board[i,0] == board[i,1] && board[i,1] == board[i,2])
{
return Char.ToString(board[i,0]);
}
}
return null;
}
// check column for winner
public static string checkColumn()
{
for(int i=0; i<3; i++)
{
if(board[0,i] != '-' && board[0,i] == board[1,i] && board[1,i] == board[2,i])
{
return Char.ToString(board[0,i]);
}
}
return null;
}
// check diagonal for winner
public static string checkDiagonal()
{
if (board[0,0] != '-' && board[0,0] == board[1,1] && board[1,1] == board[2,2])
{
return Char.ToString(board[0,0]);
}
else if (board[0,2] != '-' && board[0,2] == board[1,1] && board[1,1] == board[2,0])
{
return Char.ToString(board[0,2]);
}
return null;
}
// print tic tac toe board
public static void printBoard()
{
Console.WriteLine("\n {0} | {1} | {2} \n---|---|--- \n {3} | {4} | {5} \n---|---|--- \n {6} | {7} | {8} \n",
board[0,0], board[0,1], board[0,2], board[1,0], board[1,1], board[1,2], board[2,0], board[2,1], board[2,2]);
}
// check if board is full
public static bool isBoardFull()
{
for(int j=0; j<3; j++)
{
for(int k=0; k<3; k++)
{
if(board[j, k] == '-')
{
return false;
}
}
}
return true;
}
public static void Main(string[] args)
{
Console.Write("Welcome to Tic Tac Toe.\n");
Console.Write("Enter the (x, y) coordinate of where you want to make your move on the board.\n");
printBoard();
// request human to play if board isn't full
while(isBoardFull() == false)
{
Console.Write("Player X's turn\n");
Console.Write("Enter x-coordinate: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter y-coordinate: ");
int y = Convert.ToInt32(Console.ReadLine());
// check if tile is empty
try
{
if(isEmpty(x, y))
{
board[x, y] = 'X';
// stop program is there is a winner
if (hasWon()) System.Environment.Exit(1);
play();
}
else
{
Console.WriteLine("\nThat square is not empty. Try Again!\n");
}
}
catch(Exception)
{
Console.WriteLine("\nInvalid move. Please try again!\n");
}
}
}
}
|
namespace Eventures.Web.Extensions
{
using System;
public static class DatetimeExtentions
{
public static string ToEventuresFormat (this DateTime date)
{
return date.ToString("dd-MMM-yyyy hh:mm:ss");
}
}
}
|
using Merchello.Core.Models;
using Merchello.Core.Models.TypeFields;
using Merchello.Tests.Base.TypeFields;
using NUnit.Framework;
namespace Merchello.Tests.UnitTests.TypeFields
{
[TestFixture]
[Category("TypeField")]
public class AppliedPaymentTypeFieldTests
{
private ITypeField _mockTransactionCredit;
private ITypeField _mockTransactionDebit;
[SetUp]
public void Setup()
{
_mockTransactionCredit = TypeFieldMock.AppliedPaymentCredit;
_mockTransactionDebit = TypeFieldMock.AppliedPaymentDebit;
}
/// <summary>
/// Asserts the TransactionType Debit returns the expected transaction configuration
/// </summary>
[Test]
public void AppliedPaymentType_debit_matches_configuration()
{
var type = EnumTypeFieldConverter.AppliedPayment.Debit;
Assert.AreEqual(_mockTransactionDebit.Alias, type.Alias);
Assert.AreEqual(_mockTransactionDebit.Name, type.Name);
Assert.AreEqual(_mockTransactionDebit.TypeKey, type.TypeKey);
}
/// <summary>
/// Asserts the TransactionType Credit returns the expected wishlist configuration
/// </summary>
[Test]
public void AppliedPayment_Credit_matches_configuration()
{
var type = EnumTypeFieldConverter.AppliedPayment.Credit;
Assert.AreEqual(_mockTransactionCredit.Alias, type.Alias);
Assert.AreEqual(_mockTransactionCredit.Name, type.Name);
Assert.AreEqual(_mockTransactionCredit.TypeKey, type.TypeKey);
}
}
}
|
using DpdtInject.Extension.Helper;
namespace DpdtInject.Extension.UI.ViewModel
{
public abstract class ChainViewModel : BaseViewModel
{
protected ChainViewModel()
: base()
{
}
public abstract System.Threading.Tasks.Task StartAsync();
}
}
|
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
namespace SharpMap.Web.Wfs
{
/// <summary>
/// Class for requesting and parsing a WFS servers capabilities
/// </summary>
[Serializable]
public class Client : IClient
{
private XmlNamespaceManager _nsmgr;
#region WFS Data structures
#endregion
#region Properties
private string _version;
private XmlDocument _xmlDoc;
private string _baseUrl;
private string _capabilitiesUrl;
private IWebProxy _proxy;
private int _timeOut;
private ICredentials _credentials;
private XmlNode _vendorSpecificCapabilities;
/// <summary>
/// Exposes the capabilities VendorSpecificCapabilities as XmlNode object. External modules
/// could use this to parse the vendor specific capabilities for their specific purpose.
/// </summary>
public XmlNode VendorSpecificCapabilities
{
get { return _vendorSpecificCapabilities; }
}
/// <summary>
/// Timeout of webrequest in milliseconds. Defaults to 10 seconds
/// </summary>
public int TimeOut
{
get { return _timeOut; }
set { _timeOut = value; }
}
///<summary>
///</summary>
public ICredentials Credentials
{
get { return _credentials; }
set { _credentials = value; }
}
/// <summary>
///
/// </summary>
public IWebProxy Proxy
{
get{return _proxy;}
set{_proxy = value;}
}
/// <summary>
/// Gets or sets the base URL for the server without any OGC specific name=value pairs
/// </summary>
public string BaseUrl
{
get
{
return _baseUrl;
}
set
{
_baseUrl = value;
_capabilitiesUrl = CreateCapabilitiesUrl(_baseUrl);
}
}
/// <summary>
/// Gets the entire XML document as text
/// </summary>
public string CapabilitiesUrl
{
get { return _capabilitiesUrl; }
}
/// <summary>
/// Gets the entire XML document as text
/// </summary>
public string GetXmlAsText
{
get
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
XmlDoc.WriteTo(xw);
return sw.ToString();
}
}
/// <summary>
/// Gets the entire XML document as byte[]
/// </summary>
public byte[] GetXmlAsByteArray
{
get
{
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
XmlDoc.WriteTo(xw);
byte[] baData = System.Text.Encoding.UTF8.GetBytes(sw.ToString());
return baData;
}
}
private Capabilities.WfsServiceIdentification _serviceIdentification;
/// <summary>
/// Gets the service description
/// </summary>
public Capabilities.WfsServiceIdentification ServiceIdentification
{
get { return _serviceIdentification; }
}
private Capabilities.WfsServiceProvider _serviceProvider;
/// <summary>
/// Gets the service provider
/// </summary>
public Capabilities.WfsServiceProvider ServiceProvider
{
get { return _serviceProvider; }
}
/// <summary>
/// Gets the version of the WFS server (ex. "1.1.0")
/// </summary>
public string Version
{
get { return _version; }
set { _version = value; }
}
private string[] _exceptionFormats;
/// <summary>
/// Gets a list of available exception mime type formats
/// </summary>
public string[] ExceptionFormats
{
get
{
return _exceptionFormats;
}
}
/// <summary>
/// Gets the capabilities information as <see cref="XmlDocument"/>
/// </summary>
public XmlDocument XmlDoc
{
get { return _xmlDoc; }
}
#endregion
#region Constructors
/// <summary>
/// Just instantiate, no parameters
/// </summary>
public Client() { }
/// <summary>
/// Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
public Client(string url)
: this(url, null, 10000, null, "") { }
/// <summary>
/// This Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
public Client(string url, IWebProxy proxy)
: this(url, proxy, 10000, null, "") { }
/// <summary>
/// This Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
/// <param name="timeOut">Web request timeout</param>
public Client(string url, IWebProxy proxy, int timeOut)
: this(url, proxy, timeOut, null, "") { }
/// <summary>
/// Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
/// <param name="credentials">Credentials for authenticating against remote WFS-server</param>
public Client(string url, IWebProxy proxy, ICredentials credentials)
: this(url, proxy, 10000, credentials, "") { }
/// <summary>
/// Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
/// <param name="timeOut">Web request timeout</param>
/// <param name="credentials">Credentials for authenticating against remote WFS-server</param>
public Client(string url, IWebProxy proxy, int timeOut, ICredentials credentials)
: this(url, proxy, timeOut, credentials, "") { }
/// <summary>
/// Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
/// <param name="timeOut">Web request timeout</param>
/// <param name="version"></param>
public Client(string url, IWebProxy proxy, int timeOut, string version)
: this(url, proxy, timeOut, null, version) { }
/// <summary>
/// Initializes WFS server and parses the Capabilities request
/// </summary>
/// <param name="url">URL of wfs server</param>
/// <param name="proxy">Proxy to use</param>
/// <param name="timeOut">Web request timeout</param>
/// <param name="version"></param>
/// <param name="credentials">Credentials for authenticating against remote WFS-server</param>
public Client(string url, IWebProxy proxy, int timeOut, ICredentials credentials, string version)
{
_baseUrl = url;
_proxy = proxy;
_timeOut = timeOut;
_version = version;
_credentials = credentials;
_capabilitiesUrl = CreateCapabilitiesUrl(url);
_xmlDoc = GetRemoteXml();
ParseVersion();
ParseCapabilities();
}
/// <summary>
/// Hydrates Client object based on byte array version of XML document
/// </summary>
/// <param name="byteXml">byte array version of capabilities document</param>
public Client(byte[] byteXml)
{
Stream stream = new MemoryStream(byteXml);
var r = new XmlTextReader(stream)
{
XmlResolver = null
};
_xmlDoc = new XmlDocument();
XmlDoc.XmlResolver = null;
XmlDoc.Load(r);
stream.Close();
_nsmgr = new XmlNamespaceManager(XmlDoc.NameTable);
_baseUrl = "";
_proxy = null;
_timeOut = 10000;
_version = "";
_credentials = null;
ParseVersion();
ParseCapabilities();
}
#endregion
#region Methods
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string CreateCapabilitiesUrl(string url)
{
var strReq = new StringBuilder(url);
if (!url.Contains("?"))
strReq.Append("?");
if (!strReq.ToString().EndsWith("&") && !strReq.ToString().EndsWith("?"))
strReq.Append("&");
if (!url.ToLower().Contains("service=wfs"))
strReq.AppendFormat("SERVICE=WFS&");
if (!url.ToLower().Contains("request=getcapabilities"))
strReq.AppendFormat("REQUEST=GetCapabilities&");
if (_version != "")
strReq.AppendFormat("VERSION=" + _version + "&");
return strReq.ToString();
}
/// <summary>
/// Downloads servicedescription from WFS service
/// </summary>
/// <returns>XmlDocument from Url. Null if Url is empty or inproper XmlDocument</returns>
public XmlDocument GetRemoteXml()
{
Stream stream;
try
{
var myRequest = WebRequest.Create(_capabilitiesUrl);
myRequest.Credentials = _credentials ?? CredentialCache.DefaultCredentials;
myRequest.Timeout = _timeOut;
if (_proxy != null) myRequest.Proxy = _proxy;
using (var myResponse = myRequest.GetResponse())
{
stream = myResponse.GetResponseStream();
}
if (stream == null)
throw new ApplicationException("No response stream");
}
catch (Exception ex)
{
throw new ApplicationException("Could not download capabilities document from the server. The server may not be available right now." + ex.Message);
}
try
{
var xmlTextReader = new XmlTextReader(_capabilitiesUrl, stream)
{
XmlResolver = null
};
_xmlDoc = new XmlDocument
{
XmlResolver = null
};
_xmlDoc.Load(xmlTextReader);
_nsmgr = new XmlNamespaceManager(_xmlDoc.NameTable);
return _xmlDoc;
}
catch (Exception /*ex*/)
{
throw new ApplicationException("Could not convert the capabilities file into an XML document. Do you have illegal characters in the document.");
}
finally
{
stream.Close();
}
}
/// <summary>
/// Method to parse the web-server's version
/// </summary>
public void ParseVersion()
{
var doc = XmlDoc.DocumentElement;
if (doc == null)
throw new InvalidOperationException("Could not get DocumentElement");
if (doc.Attributes["version"] != null)
{
_version = doc.Attributes["version"].Value;
if (_version != "1.0.0" && _version != "1.1.0" && _version != "2.0.0")
throw new ApplicationException("WFS Version " + _version + " is not currently supported");
}
else
throw (new ApplicationException("No service version number was found in the WFS capabilities XML file!"));
}
/// <summary>
/// Parses a servicedescription and stores the data in the ServiceIdentification property
/// </summary>
public void ParseCapabilities()
{
if(_xmlDoc == null)
{
throw (new ApplicationException("A valid WFS capabilities XML file was not loaded!"));
}
var documentElement = _xmlDoc.DocumentElement;
if (documentElement == null)
throw (new ApplicationException("A valid WFS capabilities XML file was not loaded!"));
switch (_version)
{
case "1.0.0":
if (documentElement.Attributes["version"] != null)
{
_nsmgr.AddNamespace(String.Empty, "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("sm", "");
_nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
_nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
else
throw (new ApplicationException("No service version number found!"));
var xnService = documentElement.SelectSingleNode("sm:Service", _nsmgr);
if (xnService != null)
ParseService(xnService);
else
throw (new ApplicationException("No service tag found!"));
//XmlNode xnCapability = doc.DocumentElement.SelectSingleNode("sm:Capability", _nsmgr);
break;
case "1.1.0":
case "2.0.0":
if (documentElement.Attributes["version"] != null)
{
_version = documentElement.Attributes["version"].Value;
if (_version != "1.1.0" && _version != "2.0.0")
throw new ApplicationException("WFS Version " + _version + " is not currently supported");
_nsmgr.AddNamespace(String.Empty, "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("ows", "http://www.opengis.net/ows");
_nsmgr.AddNamespace("ogc", "http://www.opengis.net/ogc");
_nsmgr.AddNamespace("wfs", "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
_nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
_nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
else
throw (new ApplicationException(
"No service version number was found in the WFS capabilities XML file!"));
var xnServiceIdentification = documentElement.SelectSingleNode("ows:ServiceIdentification", _nsmgr);
if (xnServiceIdentification != null)
ParseServiceIdentification(xnServiceIdentification);
else
throw (new ApplicationException(
"No ServiceIdentification tag found in the capabilities XML file!"));
var xnServiceProvider = documentElement.SelectSingleNode("ows:ServiceProvider", _nsmgr);
if (xnServiceProvider != null)
ParseServiceProvider(xnServiceProvider);
else
throw (new ApplicationException("No service tag found in the capabilities XML file!"));
break;
default:
throw new ApplicationException("Invalid Version");
}
/*
if (_version == "1.0.0")
{
#region Version 1.0.0
if (_xmlDoc.DocumentElement.Attributes["version"] != null)
{
_nsmgr.AddNamespace(String.Empty, "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("sm", "");
_nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
_nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
else
throw (new ApplicationException("No service version number found!"));
XmlNode xnService = _xmlDoc.DocumentElement.SelectSingleNode("sm:Service", _nsmgr);
//XmlNode xnCapability = doc.DocumentElement.SelectSingleNode("sm:Capability", _nsmgr);
if (xnService != null)
ParseService(xnService);
else
throw (new ApplicationException("No service tag found!"));
//if (xnCapability != null)
// ParseCapability(xnCapability);
//else
// throw (new ApplicationException("No capability tag found!"));
#endregion
}
else
{
#region Versions 1.1.0 and 2.0.0
if (_xmlDoc.DocumentElement.Attributes["version"] != null)
{
_version = _xmlDoc.DocumentElement.Attributes["version"].Value;
if (_version != "1.1.0" && _version != "2.0.0")
throw new ApplicationException("WFS Version " + _version + " is not currently supported");
_nsmgr.AddNamespace(String.Empty, "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("ows", "http://www.opengis.net/ows");
_nsmgr.AddNamespace("ogc", "http://www.opengis.net/ogc");
_nsmgr.AddNamespace("wfs", "http://www.opengis.net/wfs");
_nsmgr.AddNamespace("gml", "http://www.opengis.net/gml");
_nsmgr.AddNamespace("xlink", "http://www.w3.org/1999/xlink");
_nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
else
throw (new ApplicationException("No service version number was found in the WFS capabilities XML file!"));
XmlNode xnServiceIdentification = _xmlDoc.DocumentElement.SelectSingleNode("ows:ServiceIdentification", _nsmgr);
if (xnServiceIdentification != null)
ParseServiceIdentification(xnServiceIdentification);
else
throw (new ApplicationException("No ServiceIdentification tag found in the capabilities XML file!"));
XmlNode xnServiceProvider = XmlDoc.DocumentElement.SelectSingleNode("ows:ServiceProvider", _nsmgr);
if (xnServiceProvider != null)
ParseServiceProvider(xnServiceProvider);
else
throw (new ApplicationException("No service tag found in the capabilities XML file!"));
//XmlNode xnCapability = XmlDoc.DocumentElement.SelectSingleNode("sm:Capability", _nsmgr);
//if (xnCapability != null)
// ParseCapability(xnCapability);
//else
// throw (new ApplicationException("No capability tag found in the capabilities XML file!"));
#endregion
}
*/
_vendorSpecificCapabilities = documentElement.SelectSingleNode("sm:VendorSpecificCapabilities");
}
/// <summary>
/// Parses service description node
/// </summary>
/// <param name="xnlService"></param>
private void ParseService(XmlNode xnlService)
{
XmlNode node = xnlService.SelectSingleNode("sm:Title", _nsmgr);
_serviceIdentification.Title = (node?.InnerText);
node = xnlService.SelectSingleNode("sm:Abstract", _nsmgr);
_serviceIdentification.Abstract = (node?.InnerText);
node = xnlService.SelectSingleNode("sm:Fees", _nsmgr);
_serviceIdentification.Fees = (node?.InnerText);
node = xnlService.SelectSingleNode("sm:AccessConstraints", _nsmgr);
_serviceIdentification.AccessConstraints = (node?.InnerText);
XmlNodeList xnlKeywords = xnlService.SelectNodes("sm:KeywordList/sm:Keyword", _nsmgr);
if (xnlKeywords != null)
{
_serviceIdentification.Keywords = new string[xnlKeywords.Count];
for (int i = 0; i < xnlKeywords.Count; i++)
_serviceIdentification.Keywords[i] = xnlKeywords[i].InnerText;
}
}
/// <summary>
/// Parses service description node
/// </summary>
/// <param name="xnlServiceId"></param>
private void ParseServiceIdentification(XmlNode xnlServiceId)
{
XmlNode node = xnlServiceId.SelectSingleNode("ows:Title", _nsmgr);
_serviceIdentification.Title = (node?.InnerText);
node = xnlServiceId.SelectSingleNode("ows:Abstract", _nsmgr);
_serviceIdentification.Abstract = (node?.InnerText);
XmlNodeList xnlKeywords = xnlServiceId.SelectNodes("ows:Keywords/ows:Keyword", _nsmgr);
if (xnlKeywords != null)
{
_serviceIdentification.Keywords = new string[xnlKeywords.Count];
for (int i = 0; i < xnlKeywords.Count; i++)
_serviceIdentification.Keywords[i] = xnlKeywords[i].InnerText;
}
node = xnlServiceId.SelectSingleNode("ows:ServiceType", _nsmgr);
_serviceIdentification.ServiceType = (node?.InnerText);
node = xnlServiceId.SelectSingleNode("ows:ServiceTypeVersion", _nsmgr);
_serviceIdentification.ServiceTypeVersion = (node?.InnerText);
node = xnlServiceId.SelectSingleNode("ows:Fees", _nsmgr);
_serviceIdentification.Fees = (node?.InnerText);
node = xnlServiceId.SelectSingleNode("ows:AccessConstraints", _nsmgr);
_serviceIdentification.AccessConstraints = (node?.InnerText);
}
private void ParseServiceProvider(XmlNode xnlServiceProvider)
{
XmlNode node = xnlServiceProvider.SelectSingleNode("ows:ProviderName", _nsmgr);
_serviceProvider.ProviderName = (node?.InnerText);
node = xnlServiceProvider.SelectSingleNode("ows:ProviderSite", _nsmgr);
_serviceProvider.ProviderSite = (node?.InnerText);
XmlNode nodeServiceContact = xnlServiceProvider.SelectSingleNode("ows:ServiceContact", _nsmgr);
if(nodeServiceContact != null)
{
XmlNode node2 = nodeServiceContact.SelectSingleNode("ows:IndividualName", _nsmgr);
_serviceProvider.ServiceContactDetail.IndividualName = (node2?.InnerText);
node2 = node2.SelectSingleNode("ows:PositionName", _nsmgr);
_serviceProvider.ServiceContactDetail.PositionName = (node2?.InnerText);
XmlNode nodeContactInfo = xnlServiceProvider.SelectSingleNode("ows:ContactInfo", _nsmgr);
if(nodeContactInfo != null)
{
XmlNode nodePhone = nodeContactInfo.SelectSingleNode("ows:Phone", _nsmgr);
XmlNode nodeAddress = nodeContactInfo.SelectSingleNode("ows:Address", _nsmgr);
if(nodePhone != null)
{
XmlNode node4 = nodePhone.SelectSingleNode("ows:Voice", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.Telephone.Voice = (node4?.InnerText);
node4 = node.SelectSingleNode("ows:Facsimile", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.Telephone.Facsimile = (node4?.InnerText);
}
if(nodeAddress != null)
{
XmlNode node5 = nodeAddress.SelectSingleNode("ows:DeliveryPoint", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.DeliveryPoint = (node5?.InnerText);
node5 = nodeAddress.SelectSingleNode("ows:City", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.City = (node5?.InnerText);
node5 = nodeAddress.SelectSingleNode("ows:AdministrativeArea", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.AdministrativeArea = (node5?.InnerText);
node5 = nodeAddress.SelectSingleNode("ows:PostalCode", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.PostalCode = (node5?.InnerText);
node5 = nodeAddress.SelectSingleNode("ows:Country", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.Country= (node5?.InnerText);
node5 = nodeAddress.SelectSingleNode("ows:ElectronicMailAddress", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.AddressDetails.ElectronicMailAddress = (node5?.InnerText);
}
XmlNode node6 = nodeContactInfo.SelectSingleNode("sm:OnlineResource/@xlink:href", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.OnlineResource = (node6?.InnerText);
node6 = nodeContactInfo.SelectSingleNode("ows:HoursOfService", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.HoursOfService = (node6?.InnerText);
node6 = nodeContactInfo.SelectSingleNode("ows:ContactInstructions", _nsmgr);
_serviceProvider.ServiceContactDetail.ContactInformation.ContactInstructions = (node6?.InnerText);
}
node2 = nodeServiceContact.SelectSingleNode("ows:Role", _nsmgr);
_serviceProvider.ServiceContactDetail.Role = (node2?.InnerText);
}
}
/// <summary>
/// Method to validate the web server's response
/// </summary>
public void ValidateXml()
{
throw new NotImplementedException();
}
#endregion
}
}
|
using System.Threading.Tasks;
namespace Dime.Scheduler.Sdk
{
public abstract class EndpointBuilder<T>
{
private readonly IAuthenticator _authn;
private readonly string _uri;
public EndpointBuilder(string uri, IAuthenticator authn)
{
_uri = uri;
_authn = authn;
}
protected abstract T Create(AuthenticationOptions opts);
internal async Task<T> Create()
{
string authenticationToken = await _authn.AuthenticateAsync();
return Create(new AuthenticationOptions { AuthenticationToken = authenticationToken, Uri = _uri });
}
}
} |
using CupCake.Core.Events;
namespace CupCake.HostAPI.IO
{
public class InputEvent : Event
{
public InputEvent(string input)
{
this.Input = input;
}
public string Input { get; set; }
}
} |
namespace OnlinePerfumeShop.Models.Perfumes
{
using OnlinePerfumeShop.Services.Models;
using System;
using System.Collections.Generic;
public class ListPerfumeViewModel
{
public IEnumerable<ListPerfumesServiceModel> Perfumes { get; set; }
public int PerfumeCount { get; set; }
public int WomenPerfumeCount { get; set; }
public int MenPerfumeCount { get; set; }
public int Page { get; set; }
public int PageCount => (int)Math.Ceiling((double)this.PerfumeCount / this.ItemsPerPage);
public int WomenPageCount => (int)Math.Ceiling((double)this.WomenPerfumeCount / this.ItemsPerPage);
public int MenPageCount => (int)Math.Ceiling((double)this.MenPerfumeCount / this.ItemsPerPage);
public bool HasNextPage => this.Page < PageCount;
public bool HasWomenNextPage => this.Page < WomenPageCount;
public bool HasMenNextPage => this.Page < MenPageCount;
public bool HasPreviousPage => this.Page > 1;
public int PreviousPage => this.Page - 1;
public int NextPage => this.Page + 1;
public int ItemsPerPage { get; set; }
}
}
|
namespace PLSS.Models
{
public class TokenContainer
{
public TokenContainer(string token)
{
Token = token;
}
public string Token { get; set; }
public override string ToString()
{
return string.Format("Token: {0}", Token);
}
}
} |
namespace Reline.Compilation.Syntax.Nodes;
public sealed record class LabelSyntax(
SyntaxToken Identifier,
SyntaxToken ColonToken
) : SyntaxNode {
public override T Accept<T>(ISyntaxVisitor<T> visitor) => visitor.VisitLabel(this);
public override TextSpan GetTextSpan() =>
TextSpan.FromBounds(Identifier.Span, ColonToken.Span);
}
|
using MemorieDeFleurs.Databese.SQLite;
using MemorieDeFleurs.Models.Entities;
using MemorieDeFleursTest.ModelTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data.Common;
using System.Linq;
using YasT.Framework.Logging;
namespace MemorieDeFleursTest.ModelEntityTest
{
[TestClass]
public class EFInventoryActionTest : MemorieDeFleursTestBase
{
private static string PartCodeKey = "@part";
private static string SupplierCodeKey = "@supplier";
private static string NameKey = "@name";
private static string ExpectedPartCode = "BA001";
private static string ExpectedPartName = "薔薇(赤)";
private static int ExpectedSupplierCode = 1;
private static string ExpectedSupplierName = "新橋園芸";
private static string ExpectedSupplierAddress = "東京都中央区銀座";
public EFInventoryActionTest() : base()
{
AfterTestBaseInitializing += AppendSomeObjects;
BeforeTestBaseCleaningUp += CleanupTestData;
}
private void AppendSomeObjects(object sender, EventArgs unused)
{
LogUtil.Debug($"EFInventoryActionTest#AppendBouquetParts() is called.");
// Entity 未作成の単品情報は、SQLを使って直接登録する
AppendBouquetParts();
AppendSuppliers();
AppendPartSuppliers();
}
private void AppendBouquetParts()
{
using (var cmd = TestDB.CreateCommand())
{
cmd.CommandText = $"insert into BOUQUET_PARTS values ( {PartCodeKey}, {NameKey}, 1, 100, 3, 0 )";
cmd.Parameters.AddWithValue(PartCodeKey, ExpectedPartCode);
cmd.Parameters.AddWithValue(NameKey, ExpectedPartName);
cmd.ExecuteNonQuery();
}
}
private void AppendSuppliers()
{
using (var context = new MemorieDeFleursDbContext(TestDB))
{
var supplier = new Supplier()
{
Code = ExpectedSupplierCode,
Name = ExpectedSupplierName,
Address1 = ExpectedSupplierAddress,
};
context.Suppliers.Add(supplier);
context.SaveChanges();
}
}
private void AppendPartSuppliers()
{
using (var cmd = TestDB.CreateCommand())
{
cmd.CommandText = $"insert into BOUQUET_SUPPLIERS values ( {SupplierCodeKey}, {PartCodeKey} )";
cmd.Parameters.AddWithValue(SupplierCodeKey, ExpectedSupplierCode);
cmd.Parameters.AddWithValue(PartCodeKey, ExpectedPartCode);
cmd.ExecuteNonQuery();
}
}
private void CleanupTestData(object sender, EventArgs unused)
{
LogUtil.Debug($"EFInventoryActionTest#CleanupTestData() is called.");
// テーブル全削除はORマッピングフレームワークが持つ「DBを隠蔽する」意図にそぐわないため
// DbContext.Customers.Clear() のような操作は用意されていない。
// DbConnection 経由かDbContext.Database.ExecuteSqlRaw() を使い、DELETEまたはTRUNCATE文を発行すること。
CleanupTable(TestDB, "INVENTORY_ACTIONS");
CleanupTable(TestDB, "BOUQUET_SUPPLIERS");
CleanupTable(TestDB, "BOUQUET_PARTS");
CleanupTable(TestDB, "SUPPLIERS");
}
private void CleanupTable(DbConnection connection, string table)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = $"delete from {table}";
cmd.ExecuteNonQuery();
}
}
[TestMethod]
public void CanAddInventoryAction()
{
using (var context =new MemorieDeFleursDbContext(TestDB))
{
var code = ExpectedPartCode;
InventoryAction action = new InventoryAction()
{
ActionDate = new DateTime(DateConst.Year, 03, 30),
Action = InventoryActionType.SCHEDULED_TO_ARRIVE,
PartsCode = ExpectedPartCode,
ArrivalDate = new DateTime(DateConst.Year, 03, 30),
InventoryLotNo = 1,
Quantity = 200,
Remain = 200
};
context.InventoryActions.Add(action);
context.SaveChanges();
Assert.AreEqual(1, context.InventoryActions
.Count(x => x.PartsCode == ExpectedPartCode));
Assert.IsTrue(context.InventoryActions
.Where(x => x.PartsCode == ExpectedPartCode)
.All(x => x.BouquetPart.Name == ExpectedPartName));
}
}
}
}
|
using System.Windows;
namespace LaunchPad2.Controls
{
public class CueMovingEventArgs : RoutedEventArgs
{
public CueMovingEventArgs(RoutedEvent routedEvent, CueMoveMode cueMoveMode)
: base(routedEvent)
{
CueMoveMode = cueMoveMode;
}
public CueMoveMode CueMoveMode { get; set; }
}
}
|
namespace MsgPack
{
using System;
public interface IUnpackable
{
void UnpackFromMessage(Unpacker unpacker);
}
}
|
using System;
using System.Collections.Generic;
namespace Lab_03_SumMinMaxAverage
{
public class sumMinMaxAverage
{
public static void Main(string[] args)
{
ReceiveInput();
}
static void ReceiveInput()
{
var count = int.Parse(Console.ReadLine());
List<int> listOfNumbers = new List<int>();
for (var index = 1; index <= count; index++)
{
listOfNumbers.Add(int.Parse(Console.ReadLine()));
}
Calculate(listOfNumbers, count);
}
static void Calculate(List<int> listOfNumbers, int count)
{
var sum = 0.0;
double min = listOfNumbers[0];
double max = listOfNumbers[0];
var average = 0.0;
foreach (var num in listOfNumbers)
{
sum += num;
if (min > num)
{
min = num;
}
if (max < num)
{
max = num;
}
}
average = sum / count;
Print(sum, min, max, average);
}
static void Print(double sum, double min, double max, double average)
{
Console.WriteLine("Sum = " + sum);
Console.WriteLine("Min = " + min);
Console.WriteLine("Max = " + max);
Console.WriteLine("Average = " + average);
}
}
}
|
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using Newtonsoft.Json;
namespace NewRelic.Agent.IntegrationTestHelpers.Models
{
public class UrlRule
{
[JsonProperty("match_expression")]
public string MatchExpression { get; set; }
[JsonProperty("replacement")]
public string Replacement { get; set; }
[JsonProperty("ignore")]
public bool Ignore { get; set; }
[JsonProperty("eval_order")]
public int EvalOrder { get; set; }
[JsonProperty("terminate_chain")]
public bool TerminateChain { get; set; }
[JsonProperty("replace_all")]
public bool ReplaceAll { get; set; }
[JsonProperty("each_segment")]
public bool EachSegment { get; set; }
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace StormyCommerce.Api.Framework
{
//!This Probably is Useless
//!I Planned to use to Test, but I chose to put virtual methods on the Startup on WebHost
public class Startup
{
protected readonly IHostingEnvironment _hostingEnvironment;
protected readonly IConfiguration _configuration;
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
{
_configuration = configuration;
_hostingEnvironment = hostingEnvironment;
}
public virtual void ConfigureServices(IServiceCollection services)
{
}
public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
}
}
}
|
/*
Copyright ©2020-2021 WellEngineered.us, all rights reserved.
Distributed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
using System;
using WellEngineered.Solder.Configuration;
namespace WellEngineered.Solder.Component
{
public abstract partial class ConfigurableComponent<TComponentConfiguration>
: Component, IConfigurableComponent<TComponentConfiguration>
where TComponentConfiguration : IComponentConfigurationObject
{
#region Constructors/Destructors
protected ConfigurableComponent()
{
}
#endregion
#region Fields/Constants
private TComponentConfiguration configuration;
#endregion
#region Properties/Indexers/Events
public Type ConfigurationType
{
get
{
return typeof(TComponentConfiguration);
}
}
public TComponentConfiguration Configuration
{
get
{
return this.configuration;
}
set
{
this.configuration = value;
}
}
IConfigurationObject IConfigurable.Configuration
{
get
{
return this.Configuration;
}
set
{
this.Configuration = (TComponentConfiguration)value;
}
}
#endregion
#region Methods/Operators
private void AssertValidConfiguration()
{
if ((object)this.Configuration == null)
throw new InvalidOperationException(string.Format("Configuration missing: '{0}'.", nameof(this.Configuration)));
}
protected override void CoreCreate(bool creating)
{
if (this.IsCreated)
return;
if (creating)
{
base.CoreCreate(creating);
this.AssertValidConfiguration();
}
}
protected override void CoreDispose(bool disposing)
{
if (this.IsDisposed)
return;
if (disposing)
{
this.Configuration = default(TComponentConfiguration);
base.CoreDispose(disposing);
}
}
#endregion
}
} |
namespace HtmlGenerator
{
public class HtmlOutputElement : HtmlElement
{
public HtmlOutputElement() : base("output") { }
public HtmlOutputElement WithFor(string value) => this.WithAttribute(Attribute.For(value));
public HtmlOutputElement WithForm(string value) => this.WithAttribute(Attribute.Form(value));
public HtmlOutputElement WithName(string value) => this.WithAttribute(Attribute.Name(value));
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour
{
public float speed = 3.5f;
public float size = 0.5f;
public float sizetop = 0.7f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//movement
Vector2 position = transform.position;
position.y = position.y + Input.GetAxis("Vertical") * speed * Time.deltaTime;
position.x = position.x + Input.GetAxis("Horizontal") * speed * Time.deltaTime;
//screen width
float screensize = (float)Screen.width / (float)Screen.height;
float finalsize = Camera.main.orthographicSize * screensize;
//y boundries
if (position.y + sizetop > Camera.main.orthographicSize){
position.y = Camera.main.orthographicSize - sizetop;
}
if(position.y - size < -Camera.main.orthographicSize){
position.y = -Camera.main.orthographicSize + size;
}
//x boundries
if (position.x + size > finalsize){
position.x = finalsize - size;
}
if (position.x - size < -finalsize){
position.x = -finalsize + size;
}
//final upadate
transform.position = position;
}
}
|
using System.Threading.Tasks;
using Checkout.Common;
using Shouldly;
using Xunit;
namespace Checkout.Customers.Four
{
public class CustomersIntegrationTest : SandboxTestFixture
{
public CustomersIntegrationTest() : base(PlatformType.Four)
{
}
[Fact]
private async Task ShouldCreateAndGetCustomer()
{
var request = new CustomerRequest
{
Email = GenerateRandomEmail(),
Name = "Customer",
Phone = new Phone
{
CountryCode = "1",
Number = "4155552671"
}
};
var customerResponse = await FourApi.CustomersClient().Create(request);
customerResponse.ShouldNotBeNull();
var customerDetails = await FourApi.CustomersClient().Get(customerResponse.Id);
customerDetails.ShouldNotBeNull();
customerDetails.Email.ShouldBe(request.Email);
customerDetails.Name.ShouldBe(request.Name);
customerDetails.Phone.ShouldNotBeNull();
customerDetails.DefaultId.ShouldBeNull();
customerDetails.Instruments.ShouldBeEmpty();
}
[Fact]
private async Task ShouldCreateAndUpdateCustomer()
{
//Create Customer
var request = new CustomerRequest
{
Email = GenerateRandomEmail(),
Name = "Customer",
Phone = new Phone
{
CountryCode = "1",
Number = "4155552671"
}
};
var customerResponse = await FourApi.CustomersClient().Create(request);
customerResponse.ShouldNotBeNull();
//Edit Customer
request.Email = GenerateRandomEmail();
request.Name = "Changed Name";
var customerId = customerResponse.Id;
await FourApi.CustomersClient().Update(customerId, request);
var customerDetails = await FourApi.CustomersClient().Get(customerId);
customerDetails.ShouldNotBeNull();
customerDetails.Email.ShouldBe(request.Email);
customerDetails.Name.ShouldBe(request.Name);
}
[Fact]
private async Task ShouldCreateAndDeleteCustomer()
{
var request = new CustomerRequest
{
Email = GenerateRandomEmail(),
Name = "Customer",
Phone = new Phone
{
CountryCode = "1",
Number = "4155552671"
}
};
var customerResponse = await FourApi.CustomersClient().Create(request);
customerResponse.ShouldNotBeNull();
var customerId = customerResponse.Id;
await FourApi.CustomersClient().Delete(customerId);
await Nap();
await AssertNotFound(FourApi.CustomersClient().Get(customerId));
}
}
} |
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NotTwitter.API.Filters
{
public class AuthourizeCheckFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var methodAttributes = context.MethodInfo.GetCustomAttributes(true);
var controllerAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true);
var methodAllowAnonymous = methodAttributes.OfType<AllowAnonymousAttribute>().Any();
var authorize = methodAttributes.Union(controllerAttributes).OfType<AuthorizeAttribute>().Any();
if (!methodAllowAnonymous && authorize)
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
var bearerScheme = new OpenApiSecurityScheme
{
// the id here must match the security scheme name defined in the startup file
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "BearerAuth" }
};
operation.Security = new List<OpenApiSecurityRequirement>
{
// scope list should be empty when definition type is bearer
new OpenApiSecurityRequirement { [ bearerScheme ] = Array.Empty<string>() }
};
}
}
}
}
|
using UnityEngine;
public class HighScoreManager : MonoBehaviour
{
#region Init
private void Awake()
{
HighScore = GetComponentInChildren<HighScore>();
_endScore = GameObject.Find("ScoreStop");
}
#endregion
#region Start
private void Start()
{
HighScore._highScore = PlayerPrefs.GetInt("HighScore", 0);
}
#endregion
#region Update
private void Update()
{
//_convert += Time.deltaTime;
//HighScore._highScore = (int)_convert;
//Debug.Log(HighScore._highScore);
Debug.Log(HighScore._highScore);
StopScore();
}
#endregion
#region Methods
private void StopScore()
{
if(_endScore == null)
{
_convert += Time.deltaTime;
HighScore._highScore = (int)_convert;
}
}
#endregion
#region Private
private HighScore HighScore;
private float _convert;
private GameObject _endScore;
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace Microsoft.ServiceModel.Samples
{
class DurableInstanceContextInputSessionChannel : DurableInstanceContextChannelBase,
IInputSessionChannel
{
IInputSessionChannel innerInputSessionChannel;
// Indicates whether the current message is the first
// message in a session or not.
bool isFirstMessage;
// Lock should be acquired on this object before changing the
// state of this channel.
object stateLock;
// Once the context id is read out from the first incoming message,
// it will be cached here.
string contextId;
public DurableInstanceContextInputSessionChannel(
ChannelManagerBase channelManager,
ContextType contextType,
IInputSessionChannel innerChannel)
: base(channelManager, innerChannel)
{
this.isFirstMessage = true;
this.innerInputSessionChannel = innerChannel;
this.contextType = contextType;
this.stateLock = new object();
}
public IInputSession Session
{
get
{
return this.innerInputSessionChannel.Session;
}
}
public IAsyncResult BeginReceive(TimeSpan timeout,
AsyncCallback callback, object state)
{
return this.innerInputSessionChannel.BeginReceive(
timeout, callback, state);
}
public IAsyncResult BeginReceive(AsyncCallback callback, object state)
{
return BeginReceive(
DefaultReceiveTimeout, callback, state);
}
public IAsyncResult BeginTryReceive(TimeSpan timeout,
AsyncCallback callback, object state)
{
return this.innerInputSessionChannel.BeginTryReceive(
timeout, callback, state);
}
public IAsyncResult BeginWaitForMessage(TimeSpan timeout,
AsyncCallback callback, object state)
{
return this.innerInputSessionChannel.BeginWaitForMessage(
timeout, callback, state);
}
public Message EndReceive(IAsyncResult result)
{
Message message =
this.innerInputSessionChannel.EndReceive(result);
ReadAndAddContextIdToMessage(message);
return message;
}
public bool EndTryReceive(IAsyncResult result, out Message message)
{
if (this.innerInputSessionChannel.EndTryReceive(
result, out message))
{
ReadAndAddContextIdToMessage(message);
return true;
}
return false;
}
public bool EndWaitForMessage(IAsyncResult result)
{
return this.innerInputSessionChannel.EndWaitForMessage(result);
}
public EndpointAddress LocalAddress
{
get { return this.innerInputSessionChannel.LocalAddress; }
}
public Message Receive(TimeSpan timeout)
{
Message message =
this.innerInputSessionChannel.Receive(timeout);
ReadAndAddContextIdToMessage(message);
return message;
}
public Message Receive()
{
return Receive(DefaultReceiveTimeout);
}
public bool TryReceive(TimeSpan timeout, out Message message)
{
if (this.innerInputSessionChannel.TryReceive(timeout, out message))
{
ReadAndAddContextIdToMessage(message);
return true;
}
return false;
}
public bool WaitForMessage(TimeSpan timeout)
{
return this.innerInputSessionChannel.WaitForMessage(timeout);
}
//Reads the context id from an incoming message and adds
//it to the properties collection of the message.
void ReadAndAddContextIdToMessage(Message message)
{
// Check the session terminating null message.
if (message != null)
{
lock (stateLock)
{
// Read the context if this is the first message.
// Otherwise add the context id in the cache to
// the message properties.
if (isFirstMessage)
{
this.contextId = ReadContextId(message);
isFirstMessage = false;
}
else
{
message.Properties.Add(DurableInstanceContextUtility.ContextIdProperty,
this.contextId);
}
}
}
}
}
}
|
using System;
namespace Grappachu.Core.Media
{
/// <summary>
/// Defines a component that interacts in a time interval
/// </summary>
public interface ITimeable
{
/// <summary>
/// Gets the time position for the current interaction
/// </summary>
TimeSpan Position { get; }
/// <summary>
/// Gets the total time interval where the <see cref="Position" /> can move
/// </summary>
TimeSpan Duration { get; }
}
} |
namespace Project_Setup.So_EventSystem.So_Events
{
public class IntEventListener : BaseEventListener<int, IntEventSo>
{
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.