content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Spear.Core
{
/// <summary> 单例辅助 </summary>
public class Singleton
{
/// <summary> 所有单例 </summary>
protected static ConcurrentDictionary<Type, object> AllSingletons { get; }
static Singleton()
{
AllSingletons = new ConcurrentDictionary<Type, object>();
}
}
/// <summary> 单例泛型辅助 </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> : Singleton
{
/// <summary> 单例 </summary>
public static T Instance
{
get
{
if (AllSingletons.TryGetValue(typeof(T), out var instance))
return (T)instance;
return default(T);
}
set => AllSingletons.AddOrUpdate(typeof(T), value, (type, obj) => value == null ? obj : value);
}
}
/// <summary>
/// 单例泛型列表辅助
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonList<T> : Singleton<IList<T>>
{
static SingletonList()
{
Singleton<IList<T>>.Instance = new List<T>();
}
/// <summary>
/// The singleton instance for the specified type T. Only one instance (at the time) of this list for each type of T.
/// </summary>
public new static IList<T> Instance => Singleton<IList<T>>.Instance;
}
} |
namespace elFinder.Net.Core.Models.Command
{
public class TreeCommand : TargetCommand
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VirtualPath.Tests;
namespace VirtualPath.SshNet.Tests
{
public class IVirtualPathProviderTests : IVirtualPathProviderFixture
{
public IVirtualPathProviderTests()
: base(() => new SftpVirtualPathProvider("127.0.0.1", "test", "test"))
{ }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bedrock.Common;
namespace SmartSync.Common
{
using File = Bedrock.Common.File;
using Directory = Bedrock.Common.Directory;
public class BasicDirectory : Directory
{
public override string Name
{
get
{
return DirectoryInfo.Name;
}
set
{
throw new NotImplementedException();
}
}
public override Directory Parent
{
get
{
if (storage.Path.FullName == DirectoryInfo.FullName)
return null;
if (parent == null)
parent = new BasicDirectory(storage, DirectoryInfo.Parent);
return parent;
}
}
public override Storage Storage
{
get
{
return storage;
}
}
public override string Path
{
get
{
if (storage.Path.FullName == DirectoryInfo.FullName)
return "/";
return DirectoryInfo.FullName.Substring(storage.Path.FullName.Length).Replace('\\', '/');
}
}
public override IEnumerable<Directory> Directories
{
get
{
if (storage.UseCache)
return DirectoryInfo.GetDirectories().Select(d => new BasicDirectory(storage, this, d)).ToArray();
else
return DirectoryInfo.EnumerateDirectories().Select(d => new BasicDirectory(storage, this, d));
}
}
public override IEnumerable<File> Files
{
get
{
if (storage.UseCache)
return DirectoryInfo.GetFiles().Select(f => new BasicFile(storage, this, f)).ToArray();
else
return DirectoryInfo.EnumerateFiles().Select(f => new BasicFile(storage, this, f));
}
}
public DirectoryInfo DirectoryInfo { get; private set; }
private BasicDirectory parent;
private BasicStorage storage;
public BasicDirectory(BasicStorage storage, DirectoryInfo directoryInfo)
{
this.storage = storage;
DirectoryInfo = directoryInfo;
}
public BasicDirectory(BasicStorage storage, BasicDirectory parent, DirectoryInfo directoryInfo)
{
this.storage = storage;
this.parent = parent;
DirectoryInfo = directoryInfo;
}
public override Directory CreateDirectory(string name)
{
if (!Storage.IsNameValid(name))
throw new ArgumentException("The specified name contains invalid characters");
return new BasicDirectory(storage, DirectoryInfo.CreateSubdirectory(name));
}
public override void DeleteDirectory(Directory directory)
{
if (!directory.Parent.Equals(this))
throw new ArgumentException("The specified directory could not be found");
BasicDirectory basicDirectory = directory as BasicDirectory;
basicDirectory.DirectoryInfo.Delete(true);
}
public override File CreateFile(string name)
{
if (!Storage.IsNameValid(name))
throw new ArgumentException("The specified name contains invalid characters");
FileInfo fileInfo = new FileInfo(System.IO.Path.Combine(DirectoryInfo.FullName, name));
fileInfo.Create().Close();
return new BasicFile(storage, fileInfo);
}
public override void DeleteFile(File file)
{
if (!file.Parent.Equals(this))
throw new ArgumentException("The specified file could not be found");
BasicFile basicFile = file as BasicFile;
basicFile.FileInfo.Delete();
}
}
} |
namespace GiGraph.Dot.Output.Writers.Comments
{
public interface IDotCommentWriter
{
void Write(string comment);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using BDFramework.Core;
using BDFramework.UI;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;
[Obsolete("please use new uiframe: uflux.")]
static public partial class UITools
{
static private UITools_Data2UIValue _uiToolsData2UiValue;
static UITools()
{
_uiToolsData2UiValue = new UITools_Data2UIValue();
}
#region 自动设置值
/// <summary>
/// 根据数据结构自动给Transform赋值
/// </summary>
/// <param name="t"></param>
/// <param name="data"></param>
static public void AutoSetComValue(Transform t, object data)
{
_uiToolsData2UiValue.AutoSetValue(t, data);
}
private static Type checkType = typeof(Object);
/// <summary>
/// 绑定Windows的值
/// </summary>
/// <param name="o"></param>
static public void AutoSetTransformPath(AWindow win)
{
var vt = win.GetType();
var fields = vt.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
var vTransform = win.Transform;
foreach (var f in fields)
{
if (f.FieldType.IsSubclassOf(checkType) == false)
{
continue;
}
//1.自动获取节点
//TODO 热更层必须这样获取属性
var _attrs = f.GetCustomAttributes(typeof(TransformPath), false); //as Attribute[];
if (_attrs != null && _attrs.Length > 0)
{
var attr = _attrs[0] as TransformPath;
if (attr == null) continue;
//获取节点,并且获取组件
var trans = vTransform.Find(attr.Path);
if (trans == null)
{
BDebug.LogError(string.Format("自动设置节点失败:{0} - {1}", vt.FullName, attr.Path));
continue;
}
var com = trans.GetComponent(f.FieldType);
if (com == null)
{
BDebug.LogError(string.Format("节点没有对应组件:type【{0}】 - {1}", f.FieldType, attr.Path));
}
//设置属性
f.SetValue(win, com);
//Debug.LogFormat("字段{0}获取到setTransform ,path:{1}" , f.Name , attr.Path);
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicIntensity : MonoBehaviour
{
[FMODUnity.EventRef]
public string NAME_EVENT = "event:/Music";
public FMOD.Studio.EventInstance AUDIO_EVENT;
public FMOD.Studio.ParameterInstance PARAMETER_EVENT;
public float intensity;
float lastV;
// Start is called before the first frame update
void Start()
{
AUDIO_EVENT = FMODUnity.RuntimeManager.CreateInstance(NAME_EVENT);
AUDIO_EVENT.getParameter("music_intensity", out PARAMETER_EVENT);
AUDIO_EVENT.start();
PARAMETER_EVENT.setValue(0);
InvokeRepeating("CheckMusicIntensity", 3, 1);
}
// Update is called once per frame
void Update()
{
}
void CheckMusicIntensity()
{
int nplayers = 0;
GameManager.instance.players.ForEach((p) => { nplayers += p.shipCount; });
int maxp = 200;
float v = (float)nplayers / (float)maxp;
Debug.Log(v);
v += (v - lastV)/10;
if (Player.playersTargetedToCurrentPlanet > 1)
{
v = 1;
}
PARAMETER_EVENT.setValue(v);
}
}
|
namespace YuzuMarker.Model
{
public enum SelectionMode : int
{
New = 0,
Add = 1,
Subtract = 2,
Intersect = 3
}
} |
using System;
using System.IO;
using OWML.Common;
using OWML.Tests.Setup;
using Xunit;
using Xunit.Abstractions;
namespace OWML.GameFinder.Tests
{
public class GameFinderTests : OWMLTests
{
public GameFinderTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public void PathFinder_FindGamePath()
{
var pathFinder = new PathFinder(new OwmlConfig(), Console.Object);
var gamePath = pathFinder.FindGamePath();
Assert.Equal(new DirectoryInfo(SteamGamePath).FullName, new DirectoryInfo(gamePath).FullName, StringComparer.InvariantCultureIgnoreCase);
}
}
}
|
using System;
using KickStart.MongoDB;
// ReSharper disable once CheckNamespace
namespace KickStart
{
/// <summary>
/// KickStart Extension for MongoDB.
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Use the KickStart extension to configure MongoDB.
/// </summary>
/// <param name="configurationBuilder">The configuration builder.</param>
/// <returns>
/// A fluent <see langword="interface"/> to configure KickStart.
/// </returns>
public static IConfigurationBuilder UseMongoDB(this IConfigurationBuilder configurationBuilder)
{
var options = new MongoOptions();
var starter = new MongoStarter(options);
configurationBuilder.ExcludeAssemblyFor<MongoStarter>();
configurationBuilder.ExcludeAssemblyFor<global::MongoDB.Driver.IMongoDatabase>();
configurationBuilder.Use(starter);
return configurationBuilder;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamControl : MonoBehaviour
{
[SerializeField] Transform cam;
public Quaternion bodyRot;
[SerializeField] Options opt;
// Update is called once per frame
void FixedUpdate()
{
if (!Options.opt.obj.gameObject.activeSelf)
{
bodyRot = Quaternion.Euler(0, Input.GetAxis("Mouse X") * Options.opt.sensX, 0);
transform.rotation *= bodyRot;
var temp = cam.rotation;
cam.rotation *= Quaternion.Euler(Input.GetAxis("Mouse Y") * Options.opt.sensY, 0, 0);
if (Vector3.Angle(transform.forward, cam.forward) > 90)
{
cam.rotation = temp;
}
}
}
}
|
@model AzureKit.Models.MediaGalleryContent
@{
ViewBag.Title = "Edit Gallery";
}
<h2>Edit Gallery</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Gallery</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label for="Content" class="control-label col-md-2">Description</label>
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default wymupdate" />
</div>
</div>
</div>
}
@if (!String.IsNullOrEmpty(Model.Id))
{
<h4>Gallery Images</h4>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#imageUploadModal">
Add media
</button>
}
<div style="height:15px"></div>
<div id="galleryImages" class="gallery">
@if (Model.Items != null)
{
foreach (var item in Model.Items)
{
<div class="container galleryItem">
<a href="@(Model.BaseUrl + item.MediaUrl)" target="_blank">
<img src="@(Model.BaseUrl + item.ThumbnailUrl)" alt="@item.Name" />
</a>
<br />
<span>@item.Name</span>
<button class="btn btn-default" onclick="removeItem(this, '@item.Id')">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</button><br />
<span>@item.Description</span>
</div>
}
}
</div>
<!-- modal dialog for adding content-->
<div class="modal fade" id="imageUploadModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Upload media</h4>
</div>
<div class="modal-body">
<form name="imageUp" id="imageUp">
<label for="imageFile">File:</label>
<input type="file" id="imageFile" name="imageFile" />
<!-- inputs for metadata -->
<label for="imageTitle">Title: </label><input type="text" id="imageTitle" />
<br />
<label for="imageDescription">Description: </label><input type="text" id="imageDescription" />
<br />
<label for="imageTags">Tags:</label><input type="text" id="imageTags" placeholder="Enter tags separated by commas" />
<br />
<div id="imageFileDetailsPanel" style="display:none">
<h4>File details:</h4>
<fieldset name="imageFileDetails">
<label for="imageFileName">Name: </label><span id="imageFileName"></span>
<label for="imageFileSize">Size: </label><span id="imageFileSize"></span>
<label for="imageFileType">Type: </label><span id="imageFileType"></span>
</fieldset>
</div>
<div id="imageProgressPanel" style="display:none">
<label for="imageUpProgress">Upload progress: </label><progress id="imageUpProgress" value="0"></progress>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="startImageUpload" class="btn btn-primary">Upload</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
@section scripts
{
<script type="text/javascript">
//prep WYM editor
$(document).ready(function(){
$("#Content").wymeditor();
});
//setup XRSF token for Ajax calls
@functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
var xrsfTokenHeader = "@TokenHeaderValue()";
</script>
<script src="~/Scripts/Media/MediaFileContainer.js"></script>
<script src="~/Scripts/Media/MediaUploader.js"></script>
<script src="~/Scripts/Media/Media.js"></script>
}
|
using UnityEngine;
using System.Collections;
public class Platform : BaseBehavior
{
private Transform _player;
public bool IsBroken = false;
public bool IsDead = false;
public float JumpSpeed = 3.5F;
void Start()
{
_player = GameObject.Find("Player").transform;
}
void Update()
{
if (!_player)
return;
if (!collider2D.enabled && _player.position.y > transform.position.y && _player.rigidbody2D.velocity.y <= 0)
{
collider2D.enabled = true;
}
else if (collider2D.enabled && _player.position.y < transform.position.y)
{
collider2D.enabled = false;
}
if (IsBelowTheFold())
{
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D collision2D)
{
if (collision2D.rigidbody2D.velocity.y <= 0)
{
if (IsDead)
{
Destroy(gameObject);
}
else
{
collision2D.rigidbody2D.velocity = new Vector2(collision2D.rigidbody2D.velocity.x, JumpSpeed);
collider2D.enabled = false;
if (PlatformDirector.Current)
PlatformDirector.Current.audio.Play();
if (IsBroken)
{
Destroy(gameObject);
}
}
}
}
void OnTriggerStay2D(Collider2D collision2D)
{
if (collision2D.rigidbody2D.velocity.y <= 0)
{
if (IsDead)
{
Destroy(gameObject);
}
else
{
collision2D.rigidbody2D.velocity = new Vector2(collision2D.rigidbody2D.velocity.x, JumpSpeed);
collider2D.enabled = false;
PlatformDirector.Current.audio.Play();
if (IsBroken)
{
Destroy(gameObject);
}
}
}
}
}
|
using System.Globalization;
namespace EastAsianWidthDotNet
{
public static class StringExtensions
{
/// <summary>
/// Get the width of the string considering EastAsianWidth.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int GetWidth(this string value) =>
EastAsianWidth.Instance.GetWidth(value);
/// <summary>
/// Get the width of the string with respect to EastAsianWidth, according to CultureInfo.CurrentUICulture.
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfo"></param>
/// <returns></returns>
public static int GetWidth(this string value, CultureInfo cultureInfo) =>
EastAsianWidth.Instance.GetWidth(value, cultureInfo);
/// <summary>
/// Get the width of the string considering EastAsianWidth by specifying whether it is East Asia.
/// </summary>
/// <param name="value"></param>
/// <param name="isEastAsia"></param>
/// <returns></returns>
public static int GetWidth(this string value, bool isEastAsia) =>
EastAsianWidth.Instance.GetWidth(value, isEastAsia);
/// <summary>
/// Indicates whether this character is Full Width.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsFullWidth(this char value) =>
EastAsianWidth.Instance.IsFullWidth(value);
/// <summary>
/// Indicates whether this character is Full Width by specifying CultureInfo.
/// </summary>
/// <param name="value"></param>
/// <param name="cultureInfo"></param>
/// <returns></returns>
public static bool IsFullWidth(this char value, CultureInfo cultureInfo) =>
EastAsianWidth.Instance.IsFullWidth(value, cultureInfo);
/// <summary>
/// Indicates whether this character is Full Width by specifying whether it is East Asia.
/// </summary>
/// <param name="value"></param>
/// <param name="isEastAsia"></param>
/// <returns></returns>
public static bool IsFullWidth(this char value, bool isEastAsia) =>
EastAsianWidth.Instance.IsFullWidth(value, isEastAsia);
/// <summary>
/// Get the EastAsianWidthKind of the character.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static EastAsianWidthKind GetKind(this char value) =>
EastAsianWidth.Instance.GetKind(value);
}
} |
using System.Runtime.Serialization;
using UnityEngine;
[DataContract]
public class MonsterInfo : BaseInfoForServer
{
[DataMember]
public int monster_type_id;
[DataMember]
public int monster_num;
[DataMember]
public int radius;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class SubtractNode : BinaryExpNode
{
public SubtractNode(BrainTreeNode lhs, BrainTreeNode rhs)
: base(lhs, rhs)
{
}
public override double getValue(double elapsedTime, BodySegment seg)
{
return BrainMath.Clamp(LHS.getValue(elapsedTime, seg) - RHS.getValue(elapsedTime, seg), -1, 1);
}
} |
namespace AutoTask.Psa.Api.Data;
/// <summary>
/// RestUserAccessLevel
/// </summary>
[DataContract]
public enum RestUserAccessLevel
{
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class WorkCoordinatorRegistrationService
{
private partial class WorkCoordinator
{
private abstract class AsyncWorkItemQueue<TKey> : IDisposable
where TKey : class
{
private readonly AsyncSemaphore _semaphore = new AsyncSemaphore(initialCount: 0);
// map containing cancellation source for the item given out.
private readonly Dictionary<object, CancellationTokenSource> _cancellationMap = new Dictionary<object, CancellationTokenSource>();
private readonly object _gate = new object();
protected abstract int WorkItemCount_NoLock { get; }
protected abstract void Dispose_NoLock();
protected abstract bool AddOrReplace_NoLock(WorkItem item);
protected abstract bool TryTake_NoLock(TKey key, out WorkItem workInfo);
protected abstract bool TryTakeAnyWork_NoLock(ProjectId preferableProjectId, out WorkItem workItem);
public bool HasAnyWork
{
get
{
lock (_gate)
{
return WorkItemCount_NoLock > 0;
}
}
}
public int WorkItemCount
{
get
{
lock (_gate)
{
return WorkItemCount_NoLock;
}
}
}
public void RemoveCancellationSource(object key)
{
lock (_gate)
{
// just remove cancellation token from the map.
// the cancellation token might be passed out to other service
// so don't call cancel on the source only because we are done using it.
_cancellationMap.Remove(key);
}
}
public virtual Task WaitAsync(CancellationToken cancellationToken)
{
return _semaphore.WaitAsync(cancellationToken);
}
public bool AddOrReplace(WorkItem item)
{
lock (_gate)
{
if (AddOrReplace_NoLock(item))
{
// increase count
_semaphore.Release();
return true;
}
return false;
}
}
public void Dispose()
{
lock (_gate)
{
Dispose_NoLock();
_cancellationMap.Do(p => p.Value.Cancel());
_cancellationMap.Clear();
}
}
protected void Cancel_NoLock(object key)
{
CancellationTokenSource source;
if (_cancellationMap.TryGetValue(key, out source))
{
source.Cancel();
_cancellationMap.Remove(key);
}
}
public bool TryTake(TKey key, out WorkItem workInfo, out CancellationTokenSource source)
{
lock (_gate)
{
if (TryTake_NoLock(key, out workInfo))
{
source = GetNewCancellationSource_NoLock(key);
workInfo.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
public bool TryTakeAnyWork(ProjectId preferableProjectId, out WorkItem workItem, out CancellationTokenSource source)
{
lock (_gate)
{
// there must be at least one item in the map when this is called unless host is shutting down.
if (TryTakeAnyWork_NoLock(preferableProjectId, out workItem))
{
source = GetNewCancellationSource_NoLock(workItem.Key);
workItem.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
protected CancellationTokenSource GetNewCancellationSource_NoLock(object key)
{
Contract.Requires(!_cancellationMap.ContainsKey(key));
var source = new CancellationTokenSource();
_cancellationMap.Add(key, source);
return source;
}
}
}
}
}
|
using GameFramework;
using GameFramework.Resource;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;
namespace SG1
{
[RequireComponent(typeof(Image))]
[DisallowMultipleComponent]
public class UGUIImageBinding : TextLoadAssetBinding
{
[SerializeField, InspectorReadOnly] private Image m_Image;
public Image Image
{
get { return m_Image; }
set { m_Image = value; }
}
protected override void ApplyNewValue(string newValue)
{
if (!string.IsNullOrEmpty(newValue))
{
GameEntry.Resource.LoadAsset(newValue, typeof(Sprite), LoadAssetCallbacks);
}
}
protected override void OnLoadAssetSuccess(string assetname, object asset, float duration, object userdata)
{
Sprite sprite = asset as Sprite;
if (sprite != null && m_Image != null)
{
m_Image.sprite = sprite;
}
}
protected override void OnEditorValue()
{
base.OnEditorValue();
if (m_Image == null)
{
m_Image = GetComponent<Image>();
}
}
}
} |
// DigitalRune Engine - Copyright (C) DigitalRune GmbH
// This file is subject to the terms and conditions defined in
// file 'LICENSE.TXT', which is part of this source code package.
using System.Windows;
using System.Windows.Input;
namespace DigitalRune.Windows.Framework
{
/// <summary>
/// Represents the parameter of the <see cref="DragDropBehavior.DragCommand"/>.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="DragCommandParameter"/> is passed as the parameter of the
/// <see cref="ICommand.CanExecute"/> and <see cref="ICommand.Execute"/> methods.
/// <see cref="ICommand.CanExecute"/> is called directly before <see cref="ICommand.Execute"/>.
/// The same instance of the <see cref="DragCommandParameter"/> is passed to both methods.
/// </para>
/// </remarks>
public class DragCommandParameter
{
/// <summary>
/// Gets or sets the object associated with the <see cref="DragDropBehavior"/>.
/// </summary>
/// <value>
/// The object associated with the <see cref="DragDropBehavior"/>.
/// </value>
public DependencyObject AssociatedObject { get; set; }
/// <summary>
/// Gets or sets the visual that was hit by the mouse when the mouse button was pressed.
/// </summary>
/// <value>The visual that was hit by the mouse when the mouse button was pressed.</value>
public DependencyObject HitObject { get; set; }
/// <summary>
/// Gets or sets the mouse position relative to <see cref="AssociatedObject"/>.
/// </summary>
/// <value>The mouse position relative to <see cref="AssociatedObject"/>.</value>
public Point MousePosition { get; set; }
/// <summary>
/// Gets or sets an arbitrary object that can be used to store custom information.
/// </summary>
/// <value>The custom object. The default value is <see langword="null"/>.</value>
public object Tag { get; set; }
}
}
|
// ProgramIcon.cs, 10.06.2019
// Copyright (C) Dominic Beger 17.06.2019
using System;
namespace nUpdate.Administration.Core.Application.Extension
{
public class ProgramIcon
{
/// <summary>
/// Represents and empty or nonexistent Program Icon
/// </summary>
public static readonly ProgramIcon None = new ProgramIcon();
/// <summary>
/// Creates instance of ProgramIcon.
/// </summary>
/// <param name="path">Filename of file containing icon.</param>
/// <param name="index">Index of icon within the file.</param>
public ProgramIcon(string path, int index)
{
Path = path;
Index = index;
}
/// <summary>
/// Creates instance of ProgramIcon.
/// </summary>
/// <param name="path">Filename of file containing icon.</param>
public ProgramIcon(string path)
{
Path = path;
Index = 0;
}
/// <summary>
/// Creates instance of ProgramIcon.
/// </summary>
public ProgramIcon()
{
Path = string.Empty;
Index = 0;
}
/// <summary>
/// Gets or sets value that specifies icons index within a file.
/// </summary>
public int Index { get; set; }
/// <summary>
/// Gets or sets a value that specifies the file containing the icon.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Determines whether the specified System.Object is equal to the current System.Object.
/// </summary>
/// <param name="obj">The System.Object to compare with the current System.Object.</param>
/// <returns>true if the specified System.Object is equal to the current System.Object; otherwise, false.</returns>
public override bool Equals(object obj)
{
//Exists only to avoid compiler warning
return this == obj as ProgramIcon;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current System.Object.</returns>
public override int GetHashCode()
{
//Exists only to avoid compiler warning
return base.GetHashCode();
}
/// <summary>
/// </summary>
/// <param name="lv"></param>
/// <param name="rv"></param>
/// <returns></returns>
public static bool operator ==(ProgramIcon lv, ProgramIcon rv)
{
if (ReferenceEquals(lv, null) && ReferenceEquals(rv, null))
return true;
if (ReferenceEquals(lv, null) || ReferenceEquals(rv, null))
return false;
return lv.Path == rv.Path && lv.Index == rv.Index;
}
/// <summary>
/// </summary>
/// <param name="lv"></param>
/// <param name="rv"></param>
/// <returns></returns>
public static bool operator !=(ProgramIcon lv, ProgramIcon rv)
{
return !(lv == rv);
}
/// <summary>
/// Parses string to create and instance of ProgramIcon.
/// </summary>
/// <param name="regString">String specifying file path. Icon can be included as well.</param>
/// <returns>ProgramIcon based on input string.</returns>
public static ProgramIcon Parse(string regString)
{
if (regString == string.Empty)
return new ProgramIcon("");
if (regString.StartsWith("\"") && regString.EndsWith("\""))
if (regString.Length > 3)
regString = regString.Substring(1, regString.Length - 2);
var index = 0;
var commaPos = regString.IndexOf(",", StringComparison.Ordinal);
if (commaPos == -1)
commaPos = regString.Length;
else
index = int.Parse(regString.Substring(commaPos + 1));
var path = regString.Substring(0, commaPos);
return new ProgramIcon(path, index);
}
/// <summary>
/// Returns string representation of current ProgramIcon.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Path + "," + Index;
}
}
} |
using FistVR;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace H3VRMod
{
public class Patch
{
[HarmonyPatch(typeof(FVRMovementManager), "UpdateMovementWithHand")]
[HarmonyPrefix]
public static bool Patch_HandMovementUpdate(FVRMovementManager __instance, ref FVRViveHand hand)
{
if (__instance.Mode == FVRMovementManager.MovementMode.Dash)
{
__instance.AXButtonCheck(hand);
var tssts = GM.Options.MovementOptions.TwinStickSnapturnState;
GM.Options.MovementOptions.TwinStickSnapturnState = MovementOptions.TwinStickSnapturnMode.Disabled;
__instance.HandUpdateTwinstick(hand);
GM.Options.MovementOptions.TwinStickSnapturnState = tssts;
return false;
}
return true;
}
[HarmonyPatch(typeof(FVRMovementManager), "FU")]
[HarmonyPrefix]
public static bool Patch_MovementMathUpdate(FVRMovementManager __instance, out bool __state)
{
if (__instance.Mode == FVRMovementManager.MovementMode.Dash)
{
//set gravmode to 0 so that twinstick doesn't also simulate gravity again
var gravmode = GM.Options.SimulationOptions.PlayerGravityMode;
GM.Options.SimulationOptions.PlayerGravityMode = SimulationOptions.GravityMode.None;
__instance.UpdateModeTwoAxis(true);
GM.Options.SimulationOptions.PlayerGravityMode = gravmode;
//once it's done, set mode for armswinger and let the original method do its calcs
__instance.Mode = FVRMovementManager.MovementMode.Armswinger;
__state = true;
}
else
{
__state = false;
}
return true;
}
[HarmonyPatch(typeof(FVRMovementManager), "FU")]
[HarmonyPostfix]
public static void Patch_MovementMathUpdateEnd(FVRMovementManager __instance, bool __state)
{
if (__state)
{
__instance.Mode = FVRMovementManager.MovementMode.Dash;
}
}
//[HarmonyPatch(typeof(FVRPointableButton), "Awake")]
[HarmonyPatch(typeof(FVRPointable), "Update")]
[HarmonyPostfix]
public static void Patch_FixDashName(FVRPointable __instance)
{
//WristMenu/MenuGo/Canvas/Button_LocoSet_0 (1)/Text
if (__instance.MaxPointingRange == 1)
{
__instance.MaxPointingRange = 1.001f;
if (__instance is FVRWristMenuPointableButton)
{
var text = __instance.GetComponentInChildren<Text>();
if (text != null)
{
if (text.text == "Dash")
{
text.text = "TSS";
}
}
}
}
}
}
} |
using Lion.AbpPro.FreeSqlReppsitory.Tests;
using Lion.AbpPro.Localization;
namespace Lion.AbpPro.FreeSqlRepository.Tests
{
public abstract class AbpProFreeSqlRepositoryTestBase: AbpProTestBase<AbpProFreeSqlRepositoryTestModule>
{
protected AbpProFreeSqlRepositoryTestBase()
{
ServiceProvider.InitializeLocalization();
}
}
}
|
using System;
using NHibernate;
using System.Collections.Generic;
namespace lm.Comol.Core.DomainModel
{
[CLSCompliant(true)]
public interface iDataContext : IDisposable
{
bool isDirty { get; }
bool isInTransaction { get; }
void Add(object item);
void Delete(object item);
void Save(object item);
void SaveOrUpdate(object item);
void Update<t>(t item);
void Refresh<t>(t item);
void BeginTransaction();
void Commit();
void Rollback();
IList<T> GetAll<T>(FetchMode fetchplan = FetchMode.Default);
IList<T> GetAll<T>(int pageIndex, int pageSize, FetchMode fetchplan = FetchMode.Default);
int GetCount<T>();
T GetById<T>(object id);
// VERIFICARE SE MANTENERE O GENERALIZZARE
ICriteria AddPaging(ICriteria criteria, int pageIndex, int pageSize);
IQuery AddPaging(IQuery query, int pageIndex, int pageSize);
IList<T> GetByCriteria<T>(ICriteria criteria, FetchMode fetchplan = FetchMode.Default);
IList<T> GetByCriteria<T>(ICriteria criteria, int pageIndex, int pageSize, FetchMode fetchplan = FetchMode.Default);
T GetByCriteriaUnique<T>(ICriteria criteria, FetchMode fetchplan = FetchMode.Default);
IList<T> GetByQuery<T>(IQuery query, FetchMode fetchplan = FetchMode.Default);
IList<T> GetByQuery<T>(IQuery query, int pageIndex, int pageSize, FetchMode fetchplan = FetchMode.Default);
T GetByQueryUnique<T>(IQuery query, FetchMode fetchplan = FetchMode.Default);
int GetCount<T>(ICriteria criteria);
ICriteria CreateCriteria<T>();
IQuery CreateQuery(string query);
ISession GetCurrentSession();
}
} |
using System.Linq;
using System.Collections.Generic;
using HotChocolate.Language;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
#nullable enable
namespace HotChocolate.Configuration
{
internal sealed class SyntaxTypeReferenceHandler
: ITypeRegistrarHandler
{
public void Register(
ITypeRegistrar typeRegistrar,
IEnumerable<ITypeReference> typeReferences)
{
foreach (SyntaxTypeReference typeReference in
typeReferences.OfType<SyntaxTypeReference>())
{
if (Scalars.TryGetScalar(
typeReference.Type.NamedType().Name.Value,
out ClrTypeReference namedTypeReference))
{
if (!typeRegistrar.IsResolved(namedTypeReference))
{
typeRegistrar.Register(
typeRegistrar.CreateInstance(namedTypeReference.Type),
typeReference.Scope);
}
}
}
}
}
}
|
//Problem 10. Unicode characters
//Write a program that converts a string to a sequence of C# Unicode character literals.
//Use format strings.
using System;
using System.Linq;
using System.Text;
namespace UnicodeCharacters
{
class UnicodeCharacters
{
static void Main()
{
string input = Console.ReadLine();
foreach (var character in input)
{
Console.Write("|");
char a = character;
string escape = "\\u" + ((int)a).ToString("X").PadLeft(4, '0');
Console.Write(String.Format("{0}|",escape));
}
Console.WriteLine();
Console.ReadLine();
}
}
}
|
using ATech.Ring.Protocol.Events;
namespace ATech.Ring.Vsix.Client
{
public static class RunnableInfoExtensions
{
public static bool TryGetCsProjPath(this RunnableInfo r, out string csProjPath)
{
csProjPath = string.Empty;
if (r.Details == null || !r.Details.ContainsKey(DetailsKeys.CsProjPath)) return false;
csProjPath = r.Details[DetailsKeys.CsProjPath] as string;
return true;
}
}
} |
using System;
namespace HomelessDisturbance.Utils
{
internal static class Utilities
{
internal static readonly Random RANDOM = new Random();
internal static bool RandomBool => RANDOM.Next(1) == 0;
}
} |
using AS.Domain.Interfaces;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AS.Infrastructure.Validation
{
/// <summary>
/// E-Mail Address validator.
/// Uses validation rules of <see cref="EmailAddressAttribute"/>
/// </summary>
public class EmailAddressValidator : PropertyValidatorBase<string>
{
private readonly IResourceManager _resourceManager;
public EmailAddressValidator(IResourceManager resourceManager)
{
this._resourceManager = resourceManager;
}
/// <summary>
/// Validates e-mail address
/// </summary>
/// <param name="emailAddress">E-mail address to be validated</param>
/// <returns>Validation Result</returns>
public override IValidationResult Validate(string emailAddress)
{
bool valid = new EmailAddressAttribute().IsValid(emailAddress);
List<string> errors = new List<string>();
if (!valid)
errors.Add(_resourceManager.GetString("InvalidEmailAddress"));
return new ValidationResult(valid, errors);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWether.Class.Weather_params
{
class RainInfo
{
public float _1h {get; set;} // Rain volume for the last 1 hour , mm
public float _3h {get; set; } // Rain volume for the last 3 hours , mm
}
}
|
/*
* @author : Jagepard <jagepard@yandex.ru>
* @license https://mit-license.org/ MIT
*/
using System;
using System.Collections.Generic;
using System.Reflection;
namespace CsDesignPatterns_Mediator
{
internal class Mediator : IMediator
{
private IDictionary<string, AbstractListener> Listeners { get; } = new Dictionary<string, AbstractListener>();
private IDictionary<string, string> Events { get; } = new Dictionary<string, string>();
public void AddListener(AbstractListener listener, string methodName)
{
if (Listeners.ContainsKey(listener.GetType().Name) && Events.ContainsKey(listener.GetType().Name))
{
throw new Exception("Command already exists");
}
Listeners.Add(listener.GetType().Name, listener);
Events.Add(listener.GetType().Name, methodName);
}
public void Notify(string name, IHandler handler)
{
if (!Listeners.ContainsKey(name) && !Events.ContainsKey(name))
{
throw new Exception(name + " does not exist in the Dictionary");
}
var listener = Listeners[name];
var methodName = Events[name];
if (handler == null)
{
listener.GetType().GetMethod(methodName)?.Invoke(obj: listener, parameters: null);
return;
}
listener.GetType().GetMethod(methodName)?.Invoke(obj: listener, parameters: new object[] { handler });
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UI : MonoBehaviour
{
private GUIStyle guiStyle = new GUIStyle();
// Start is called before the first frame update
void Start()
{
guiStyle.fontSize = 24; //change the font size
guiStyle.alignment = TextAnchor.MiddleLeft;
}
void OnGUI()
{
GUI.Label(new Rect(10, 10, 200, 40), "Press R to Reset", guiStyle);
}
}
|
namespace JRayXLib.Shapes
{
public struct Ray
{
public Vect3 Origin { get; set; }
public Vect3 Direction { get; set; }
}
} |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace KwTools.Hosting.Interfaces
{
/// <summary>
/// ExtensionMethodes for IAddServices, IConfigureBuilder and IConfigureHost
/// </summary>
public static class InterfaceExtensions
{
/// <summary>
/// Enumerates an IAddServices collection and executes AddServices for all
/// </summary>
/// <param name="self">IAddServices collection</param>
/// <param name="serviceCollection">HostBuilder ServiceCollection</param>
/// <returns>async Task</returns>
public static async Task AddAllAsync(this IEnumerable<IAddServices> self, IServiceCollection serviceCollection)
{
var taskList = new List<Task>();
foreach (var addition in self)
{
taskList.Add(addition.AddServices(serviceCollection));
}
await Task.WhenAll(taskList);
}
/// <summary>
/// Enumerates an IConfigureBuilder collection and executes ConfigureBuilder for all
/// </summary>
/// <param name="self">IConfigureBuilder collection</param>
/// <param name="hostBuilder">HostBuilder</param>
/// <returns>async Task</returns>
public static async Task ConfAllAsync(this IEnumerable<IConfigureBuilder> self, IHostBuilder hostBuilder)
{
var taskList = new List<Task>();
foreach (var conf in self)
{
taskList.Add(conf.ConfigureBuilder(hostBuilder));
}
await Task.WhenAll(taskList);
}
/// <summary>
/// Enumerates an IConfigureHost collection and executes ConfigureHost for all
/// </summary>
/// <param name="self">IConfigureHost collection</param>
/// <param name="host">Host</param>
/// <returns>async Task</returns>
public static async Task ConfAllAsync(this IEnumerable<IConfigureHost> self, IHost host)
{
var taskList = new List<Task>();
foreach (var conf in self)
{
taskList.Add(conf.ConfigureHost(host));
}
await Task.WhenAll(taskList);
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace DurandalAuth.Domain.Models.Mapping
{
public class msds_locationMap : EntityTypeConfiguration<msds_location>
{
public msds_locationMap()
{
// Primary Key
this.HasKey(t => t.auto_number);
// Properties
this.Property(t => t.bl_id)
.IsFixedLength()
.HasMaxLength(8);
this.Property(t => t.container_cat)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.container_type)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.description)
.HasMaxLength(1024);
this.Property(t => t.eq_id)
.IsFixedLength()
.HasMaxLength(12);
this.Property(t => t.evacuation_radius_units)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.evacuation_radius_units_type)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.fl_id)
.IsFixedLength()
.HasMaxLength(4);
this.Property(t => t.pressure_units)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.pressure_units_type)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.quantity_units)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.quantity_units_type)
.IsFixedLength()
.HasMaxLength(32);
this.Property(t => t.rm_id)
.IsFixedLength()
.HasMaxLength(8);
this.Property(t => t.site_id)
.IsFixedLength()
.HasMaxLength(16);
this.Property(t => t.temperature_units)
.IsRequired()
.IsFixedLength()
.HasMaxLength(10);
// Table & Column Mappings
this.ToTable("msds_location", "afm");
this.Property(t => t.bl_id).HasColumnName("bl_id");
this.Property(t => t.container_cat).HasColumnName("container_cat");
this.Property(t => t.container_type).HasColumnName("container_type");
this.Property(t => t.date_end).HasColumnName("date_end");
this.Property(t => t.date_start).HasColumnName("date_start");
this.Property(t => t.date_updated).HasColumnName("date_updated");
this.Property(t => t.description).HasColumnName("description");
this.Property(t => t.eq_id).HasColumnName("eq_id");
this.Property(t => t.evacuation_radius).HasColumnName("evacuation_radius");
this.Property(t => t.evacuation_radius_units).HasColumnName("evacuation_radius_units");
this.Property(t => t.evacuation_radius_units_type).HasColumnName("evacuation_radius_units_type");
this.Property(t => t.fl_id).HasColumnName("fl_id");
this.Property(t => t.geo_objectid).HasColumnName("geo_objectid");
this.Property(t => t.lat).HasColumnName("lat");
this.Property(t => t.lon).HasColumnName("lon");
this.Property(t => t.msds_id).HasColumnName("msds_id");
this.Property(t => t.num_containers).HasColumnName("num_containers");
this.Property(t => t.pressure).HasColumnName("pressure");
this.Property(t => t.pressure_units).HasColumnName("pressure_units");
this.Property(t => t.pressure_units_type).HasColumnName("pressure_units_type");
this.Property(t => t.quantity).HasColumnName("quantity");
this.Property(t => t.quantity_units).HasColumnName("quantity_units");
this.Property(t => t.quantity_units_type).HasColumnName("quantity_units_type");
this.Property(t => t.rm_id).HasColumnName("rm_id");
this.Property(t => t.site_id).HasColumnName("site_id");
this.Property(t => t.temperature).HasColumnName("temperature");
this.Property(t => t.temperature_units).HasColumnName("temperature_units");
this.Property(t => t.auto_number).HasColumnName("auto_number");
// Relationships
this.HasOptional(t => t.bill_type)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.evacuation_radius_units_type);
this.HasOptional(t => t.bill_type1)
.WithMany(t => t.msds_location1)
.HasForeignKey(d => d.pressure_units_type);
this.HasOptional(t => t.bill_type2)
.WithMany(t => t.msds_location2)
.HasForeignKey(d => d.quantity_units_type);
this.HasOptional(t => t.bill_unit)
.WithMany(t => t.msds_location)
.HasForeignKey(d => new { d.evacuation_radius_units_type, d.evacuation_radius_units });
this.HasOptional(t => t.bill_unit1)
.WithMany(t => t.msds_location1)
.HasForeignKey(d => new { d.pressure_units_type, d.pressure_units });
this.HasOptional(t => t.bill_unit2)
.WithMany(t => t.msds_location2)
.HasForeignKey(d => new { d.quantity_units_type, d.quantity_units });
this.HasOptional(t => t.bl)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.bl_id);
this.HasOptional(t => t.eq)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.eq_id);
this.HasOptional(t => t.fl)
.WithMany(t => t.MsdsLocation)
.HasForeignKey(d => new { d.bl_id, d.fl_id });
this.HasOptional(t => t.hazard_container_cat)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.container_cat);
this.HasOptional(t => t.hazard_container_type)
.WithMany(t => t.msds_location)
.HasForeignKey(d => new { d.container_cat, d.container_type });
this.HasRequired(t => t.msds_data)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.msds_id);
this.HasOptional(t => t.rm)
.WithMany(t => t.msds_location)
.HasForeignKey(d => new { d.bl_id, d.fl_id, d.rm_id });
this.HasOptional(t => t.site)
.WithMany(t => t.msds_location)
.HasForeignKey(d => d.site_id);
}
}
}
|
using AlbaVulpes.API.Services.AWS;
using AlbaVulpes.API.Services.Content;
using Microsoft.Extensions.DependencyInjection;
namespace AlbaVulpes.API.Extensions
{
public static class AmazonServicesExtensions
{
public static void AddAmazonServices(this IServiceCollection services)
{
services.AddScoped<IAmazonClientResolverService, AmazonClientResolverService>();
services.AddScoped<ISecretsManagerService, SecretsManagerService>();
services.AddScoped<IFilesService, FilesService>();
}
}
} |
using System;
using Commercial;
var a = new Transaction[4];
a[0] = new Transaction("Turing 6/17/1990 644.08");
a[1] = new Transaction("Tarjan 3/26/2002 4121.85");
a[2] = new Transaction("Knuth 6/14/1999 288.34");
a[3] = new Transaction("Dijkstra 8/22/2007 2678.40");
Console.WriteLine("Unsorted");
for (var i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
Console.WriteLine();
Console.WriteLine("Sort by date");
Array.Sort(a, new Transaction.WhenOrder());
for (var i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
Console.WriteLine();
Console.WriteLine("Sort by customer");
Array.Sort(a, new Transaction.WhoOrder());
for (var i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
Console.WriteLine();
Console.WriteLine("Sort by amount");
Array.Sort(a, new Transaction.HowMuchOrder());
for (var i = 0; i < a.Length; i++)
Console.WriteLine(a[i]);
Console.WriteLine(); |
namespace AuthorizationWithRequirement.AuthorizationPolicies
{
public static class AuthorizationPolicyNames
{
public static string MyFeature => "MyFeature";
}
}
|
using System.CommandLine;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Ninjax.UdmLib;
#pragma warning disable 1998
namespace nx_udm_cli
{
class ClientCommand:Command
{
public ClientCommand() : base("client", "UDM Client")
{
AddOption(new Option<int>("--port", () => 8088, "port"));
AddOption(new Option<string>("--host", () => "239.0.0.1", "host"));
Handler = CommandHandler.Create<ClientOptions, IConsole, CancellationToken>(Run);
}
private async Task<int> Run(ClientOptions options, IConsole console, CancellationToken cancel)
{
if (options.Host == null)
{
console.Error.WriteLine($"Host not specified");
return 1;
}
var address = IPAddress.Parse(options.Host);
var endPoint = new IPEndPoint(address, options.Port);
console.Out.WriteLine($"C:JOINED: {endPoint}");
using var client = new UdmClient(endPoint, (data, ep) =>
{
var message = Encoding.ASCII.GetString(data);
console.Out.WriteLine($"C:RX: [{ep}] - {message}");
});
cancel.WaitHandle.WaitOne();
return 0;
}
public class ClientOptions
{
public int Port { get; set; }
public string? Host { get; set; }
}
}
} |
using UnityEngine;
using System.Collections;
public class FPSCamera : MonoBehaviour {
private GameObject player;
private Vector3 offset;
public float turnSpeed = 50f;
// Use this for initialization
void Start () {
player = Statics.PlayerBall;
transform.position = player.transform.position;
offset = transform.position - player.transform.position;
}
void Update() {
if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.A)) {
transform.Rotate (Vector3.up, -turnSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.RightArrow) || Input.GetKey (KeyCode.D)) {
transform.Rotate (Vector3.up, turnSpeed * Time.deltaTime);
}
}
// Update is called once per frame
void LateUpdate () {
transform.position = player.transform.position + offset;
}
}
|
namespace Dapper.Apex
{
/// <summary>
/// Defines the way the operation will be sent to the database for multiple entities.
/// </summary>
public enum OperationMode
{
OneByOne = 0,
SingleShot = 1
}
}
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// package quotedprintable -- go2cs converted at 2020 October 09 04:56:12 UTC
// import "mime/quotedprintable" ==> using quotedprintable = go.mime.quotedprintable_package
// Original source: C:\Go\src\mime\quotedprintable\writer.go
using io = go.io_package;
using static go.builtin;
namespace go {
namespace mime
{
public static partial class quotedprintable_package
{
private static readonly long lineMaxLen = (long)76L;
// A Writer is a quoted-printable writer that implements io.WriteCloser.
// A Writer is a quoted-printable writer that implements io.WriteCloser.
public partial struct Writer
{
public bool Binary;
public io.Writer w;
public long i;
public array<byte> line;
public bool cr;
}
// NewWriter returns a new Writer that writes to w.
public static ptr<Writer> NewWriter(io.Writer w)
{
return addr(new Writer(w:w));
}
// Write encodes p using quoted-printable encoding and writes it to the
// underlying io.Writer. It limits line length to 76 characters. The encoded
// bytes are not necessarily flushed until the Writer is closed.
private static (long, error) Write(this ptr<Writer> _addr_w, slice<byte> p)
{
long n = default;
error err = default!;
ref Writer w = ref _addr_w.val;
foreach (var (i, b) in p)
{
// Simple writes are done in batch.
if (b >= '!' && b <= '~' && b != '=')
continue;
else if (isWhitespace(b) || !w.Binary && (b == '\n' || b == '\r'))
continue;
if (i > n)
{
{
var err__prev2 = err;
var err = w.write(p[n..i]);
if (err != null)
{
return (n, error.As(err)!);
}
err = err__prev2;
}
n = i;
}
{
var err__prev1 = err;
err = w.encode(b);
if (err != null)
{
return (n, error.As(err)!);
}
err = err__prev1;
}
n++;
}
if (n == len(p))
{
return (n, error.As(null!)!);
}
{
var err__prev1 = err;
err = w.write(p[n..]);
if (err != null)
{
return (n, error.As(err)!);
}
err = err__prev1;
}
return (len(p), error.As(null!)!);
}
// Close closes the Writer, flushing any unwritten data to the underlying
// io.Writer, but does not close the underlying io.Writer.
private static error Close(this ptr<Writer> _addr_w)
{
ref Writer w = ref _addr_w.val;
{
var err = w.checkLastByte();
if (err != null)
{
return error.As(err)!;
}
}
return error.As(w.flush())!;
}
// write limits text encoded in quoted-printable to 76 characters per line.
private static error write(this ptr<Writer> _addr_w, slice<byte> p)
{
ref Writer w = ref _addr_w.val;
foreach (var (_, b) in p)
{
if (b == '\n' || b == '\r')
{
// If the previous byte was \r, the CRLF has already been inserted.
if (w.cr && b == '\n')
{
w.cr = false;
continue;
}
if (b == '\r')
{
w.cr = true;
}
{
var err__prev2 = err;
var err = w.checkLastByte();
if (err != null)
{
return error.As(err)!;
}
err = err__prev2;
}
{
var err__prev2 = err;
err = w.insertCRLF();
if (err != null)
{
return error.As(err)!;
}
err = err__prev2;
}
continue;
}
if (w.i == lineMaxLen - 1L)
{
{
var err__prev2 = err;
err = w.insertSoftLineBreak();
if (err != null)
{
return error.As(err)!;
}
err = err__prev2;
}
}
w.line[w.i] = b;
w.i++;
w.cr = false;
}
return error.As(null!)!;
}
private static error encode(this ptr<Writer> _addr_w, byte b)
{
ref Writer w = ref _addr_w.val;
if (lineMaxLen - 1L - w.i < 3L)
{
{
var err = w.insertSoftLineBreak();
if (err != null)
{
return error.As(err)!;
}
}
}
w.line[w.i] = '=';
w.line[w.i + 1L] = upperhex[b >> (int)(4L)];
w.line[w.i + 2L] = upperhex[b & 0x0fUL];
w.i += 3L;
return error.As(null!)!;
}
private static readonly @string upperhex = (@string)"0123456789ABCDEF";
// checkLastByte encodes the last buffered byte if it is a space or a tab.
// checkLastByte encodes the last buffered byte if it is a space or a tab.
private static error checkLastByte(this ptr<Writer> _addr_w)
{
ref Writer w = ref _addr_w.val;
if (w.i == 0L)
{
return error.As(null!)!;
}
var b = w.line[w.i - 1L];
if (isWhitespace(b))
{
w.i--;
{
var err = w.encode(b);
if (err != null)
{
return error.As(err)!;
}
}
}
return error.As(null!)!;
}
private static error insertSoftLineBreak(this ptr<Writer> _addr_w)
{
ref Writer w = ref _addr_w.val;
w.line[w.i] = '=';
w.i++;
return error.As(w.insertCRLF())!;
}
private static error insertCRLF(this ptr<Writer> _addr_w)
{
ref Writer w = ref _addr_w.val;
w.line[w.i] = '\r';
w.line[w.i + 1L] = '\n';
w.i += 2L;
return error.As(w.flush())!;
}
private static error flush(this ptr<Writer> _addr_w)
{
ref Writer w = ref _addr_w.val;
{
var (_, err) = w.w.Write(w.line[..w.i]);
if (err != null)
{
return error.As(err)!;
}
}
w.i = 0L;
return error.As(null!)!;
}
private static bool isWhitespace(byte b)
{
return b == ' ' || b == '\t';
}
}
}}
|
namespace TodoList.UnitTests.WebUITests
{
using System;
using TodoList.Core.Boundaries.Todo;
using Xunit;
public sealed class TodoPresenterTests : IClassFixture<ControllerFixture>
{
private ControllerFixture _controllerFixture;
public TodoPresenterTests(ControllerFixture controllerFixture)
{
_controllerFixture = controllerFixture;
}
[Fact]
public void ReturnsNotFound_WhenNull()
{
Response response = null;
_controllerFixture.TodoPresenter.Handle(response);
var actual = _controllerFixture
.TodoPresenter
.BuildResponse(_controllerFixture.Controller);
Assert.NotNull(actual);
Assert.IsType<Microsoft.AspNetCore.Mvc.NotFoundResult>(actual.Result);
}
[Fact]
public void ReturnsBadRequest_WhenInvalid()
{
Response response = new Response(Guid.Empty);
_controllerFixture.TodoPresenter.Handle(response);
var actual = _controllerFixture
.TodoPresenter
.BuildResponse(_controllerFixture.Controller);
Assert.NotNull(actual);
Assert.IsType<Microsoft.AspNetCore.Mvc.BadRequestResult>(actual.Result);
}
[Fact]
public void ReturnsCreatedAtActionResult_WhenValid()
{
Response response = new Response(_controllerFixture.ItemId1);
_controllerFixture.TodoPresenter.Handle(response);
var actual = _controllerFixture
.TodoPresenter
.BuildResponse(_controllerFixture.Controller);
Assert.NotNull(actual);
Assert.IsType<Microsoft.AspNetCore.Mvc.CreatedAtActionResult>(actual.Result);
}
}
} |
using Eshopworld.Tests.Core;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace CaptainHook.Cli.Tests.GenerateJson
{
public class WebhookRequestRulesTests: GenerateJsonCommandBase
{
private IEnumerable<JToken> AllWebhookRequestRules => JsonResult.SelectTokens("$..WebhookRequestRules[*]");
public WebhookRequestRulesTests(ITestOutputHelper output) : base(output)
{
}
[Fact, IsUnit]
public async Task HasSource()
{
PrepareCommand();
await Command.OnExecuteAsync(Application, Console);
AllWebhookRequestRules.Should().Contain(x => x["Source"] is JObject);
}
[Fact, IsUnit]
public async Task HasDestination()
{
PrepareCommand();
await Command.OnExecuteAsync(Application, Console);
AllWebhookRequestRules.Should().Contain(x => x["Destination"] is JObject);
}
[Fact, IsUnit]
public async Task HasRoutes()
{
PrepareCommand();
await Command.OnExecuteAsync(Application, Console);
new JArray(AllWebhookRequestRules)
.SelectTokens("[?(@.Destination.RuleAction=='Route')]")
.Should().Contain(x => x["Routes"].Count() > 0);
}
}
}
|
using System;
using NUnit.Framework;
using TagLib;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Jpeg;
using TagLib.Xmp;
namespace TagLib.Tests.Images
{
[TestFixture]
public class JpegOlympus3Test
{
private static string sample_file = "samples/sample_olympus3.jpg";
private static string tmp_file = "samples/tmpwrite_olympus3.jpg";
private TagTypes contained_types = TagTypes.TiffIFD;
private File file;
[TestFixtureSetUp]
public void Init () {
file = File.Create (sample_file);
}
[Test]
public void JpegRead () {
CheckTags (file);
}
[Test]
public void ExifRead () {
CheckExif (file);
}
[Test]
public void MakernoteRead () {
CheckMakerNote (file);
}
[Test]
public void PropertiesRead () {
CheckProperties (file);
}
[Test]
public void Rewrite () {
File tmp = Utils.CreateTmpFile (sample_file, tmp_file);
tmp.Save ();
tmp = File.Create (tmp_file);
CheckTags (tmp);
CheckExif (tmp);
CheckMakerNote (tmp);
CheckProperties (tmp);
}
[Test]
public void AddExif ()
{
AddImageMetadataTests.AddExifTest (sample_file, tmp_file, true);
}
[Test]
public void AddGPS ()
{
AddImageMetadataTests.AddGPSTest (sample_file, tmp_file, true);
}
[Test]
public void AddXMP1 ()
{
AddImageMetadataTests.AddXMPTest1 (sample_file, tmp_file, false);
}
[Test]
public void AddXMP2 ()
{
AddImageMetadataTests.AddXMPTest2 (sample_file, tmp_file, false);
}
public void CheckTags (File file) {
Assert.IsTrue (file is Jpeg.File, "not a Jpeg file");
Assert.AreEqual (contained_types, file.TagTypes);
Assert.AreEqual (contained_types, file.TagTypesOnDisk);
}
public void CheckExif (File file) {
var tag = file.GetTag (TagTypes.TiffIFD) as IFDTag;
Assert.IsNotNull (tag, "tag");
var exif_ifd = tag.Structure.GetEntry(0, IFDEntryTag.ExifIFD) as SubIFDEntry;
Assert.IsNotNull (exif_ifd, "Exif IFD");
Assert.AreEqual ("OLYMPUS IMAGING CORP. ", tag.Make);
Assert.AreEqual ("E-410 ", tag.Model);
Assert.AreEqual (100, tag.ISOSpeedRatings);
Assert.AreEqual (1.0d/125.0d, tag.ExposureTime);
Assert.AreEqual (6.3d, tag.FNumber);
Assert.AreEqual (42.0d, tag.FocalLength);
Assert.AreEqual (new DateTime (2009, 04, 11, 19, 45, 42), tag.DateTime);
Assert.AreEqual (new DateTime (2009, 04, 11, 19, 45, 42), tag.DateTimeDigitized);
Assert.AreEqual (new DateTime (2009, 04, 11, 19, 45, 42), tag.DateTimeOriginal);
}
public void CheckMakerNote (File file) {
IFDTag tag = file.GetTag (TagTypes.TiffIFD) as IFDTag;
Assert.IsNotNull (tag, "tag");
var makernote_ifd =
tag.ExifIFD.GetEntry (0, (ushort) ExifEntryTag.MakerNote) as MakernoteIFDEntry;
Assert.IsNotNull (makernote_ifd, "makernote ifd");
Assert.AreEqual (MakernoteType.Olympus2, makernote_ifd.MakernoteType);
var structure = makernote_ifd.Structure;
Assert.IsNotNull (structure, "structure");
/*{
var entry = structure.GetEntry (0, 0x01) as UndefinedIFDEntry;
Assert.IsNotNull (entry);
ByteVector read_bytes = entry.Data;
ByteVector expected_bytes = new ByteVector (new byte [] {48, 50, 49, 48});
Assert.AreEqual (expected_bytes.Count, read_bytes.Count);
for (int i = 0; i < expected_bytes.Count; i++)
Assert.AreEqual (expected_bytes[i], read_bytes[i]);
}
{
var entry = structure.GetEntry (0, 0x04) as StringIFDEntry;
Assert.IsNotNull (entry, "entry 0x04");
Assert.AreEqual ("FINE ", entry.Value);
}
{
var entry = structure.GetEntry (0, 0x08) as StringIFDEntry;
Assert.IsNotNull (entry, "entry 0x08");
Assert.AreEqual ("NORMAL ", entry.Value);
}
{
var entry = structure.GetEntry (0, 0x92) as SShortIFDEntry;
Assert.IsNotNull (entry, "entry 0x92");
Assert.AreEqual (0, entry.Value);
}
{
var entry = structure.GetEntry (0, 0x9A) as RationalArrayIFDEntry;
Assert.IsNotNull (entry, "entry 0x9A");
var values = entry.Values;
Assert.IsNotNull (values, "values of entry 0x9A");
Assert.AreEqual (2, values.Length);
Assert.AreEqual (78.0d/10.0d, (double) values[0]);
Assert.AreEqual (78.0d/10.0d, (double) values[1]);
}*/
}
public void CheckProperties (File file)
{
Assert.AreEqual (3648, file.Properties.PhotoWidth);
Assert.AreEqual (2736, file.Properties.PhotoHeight);
Assert.AreEqual (96, file.Properties.PhotoQuality);
}
}
}
|
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
public class DeleteAfterBuild
{
[PostProcessBuild(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) {
// Let's delete all streaming assets folder and meta file.
if (Directory.Exists(Path.Combine(Application.dataPath, "StreamingAssets")))
{
Directory.Delete(Path.Combine(Application.dataPath, "StreamingAssets"),true);
}
if (File.Exists(Path.Combine(Application.dataPath, "StreamingAssets.meta")))
{
File.Delete(Path.Combine(Application.dataPath, "StreamingAssets.meta"));
}
AssetDatabase.Refresh();
}
}
|
using System;
using UnityEditor;
using UnityEngine;
// Shapes © Freya Holmér - https://twitter.com/FreyaHolmer/
// Website & Documentation - https://acegikmo.com/shapes/
namespace Shapes {
[CustomEditor( typeof(Quad) )]
[CanEditMultipleObjects]
public class QuadEditor : ShapeRendererEditor {
SerializedProperty propA = null;
SerializedProperty propB = null;
SerializedProperty propC = null;
SerializedProperty propD = null;
SerializedProperty propColorMode = null;
SerializedProperty propColorB = null;
SerializedProperty propColorC = null;
SerializedProperty propColorD = null;
SerializedProperty propAutoSetD = null;
public override void OnInspectorGUI() {
serializedObject.Update();
base.BeginProperties( showColor: false );
EditorGUILayout.PropertyField( propColorMode );
bool dEnabled = propAutoSetD.boolValue == false;
Vector3 dAuto = ( target as Quad ).DAuto;
switch( (Quad.QuadColorMode)propColorMode.enumValueIndex ) {
case Quad.QuadColorMode.Single:
ShapesUI.PosColorField( "A", propA, base.propColor );
ShapesUI.PosColorField( "B", propB, base.propColor, false );
ShapesUI.PosColorField( "C", propC, base.propColor, false );
ShapesUI.PosColorFieldSpecialOffState( "D", propD, dAuto, base.propColor, false, dEnabled );
break;
case Quad.QuadColorMode.Horizontal:
ShapesUI.PosColorField( "A", propA, base.propColor );
ShapesUI.PosColorField( "B", propB, base.propColor, false );
ShapesUI.PosColorField( "C", propC, propColorC );
ShapesUI.PosColorFieldSpecialOffState( "D", propD, dAuto, propColorC, false, dEnabled );
break;
case Quad.QuadColorMode.Vertical:
ShapesUI.PosColorField( "A", propA, propColorD );
ShapesUI.PosColorField( "B", propB, propColorB );
ShapesUI.PosColorField( "C", propC, propColorB, false );
ShapesUI.PosColorFieldSpecialOffState( "D", propD, dAuto, propColorD, false, dEnabled );
break;
case Quad.QuadColorMode.PerCorner:
ShapesUI.PosColorField( "A", propA, base.propColor );
ShapesUI.PosColorField( "B", propB, propColorB );
ShapesUI.PosColorField( "C", propC, propColorC );
ShapesUI.PosColorFieldSpecialOffState( "D", propD, dAuto, propColorD, true, dEnabled );
break;
default:
throw new ArgumentOutOfRangeException();
}
using( new EditorGUILayout.HorizontalScope() ) {
GUILayout.Label( GUIContent.none, GUILayout.Width( ShapesUI.POS_COLOR_FIELD_LABEL_WIDTH ) );
EditorGUILayout.PropertyField( propAutoSetD, GUIContent.none, GUILayout.Width( 16 ) );
GUILayout.Label( "Auto-set D" );
}
base.EndProperties();
}
}
} |
namespace Phnx.AspNetCore.ETags.Tests.Fakes
{
public class FakeWeakResource
{
public FakeWeakResource()
{
}
public int Id { get; set; }
}
}
|
using System.Collections.Generic;
using MongoDB.Driver;
using Microsoft.Extensions.Configuration;
using System.Linq;
namespace TaskoMask.Infrastructure.Data.DbContext
{
/// <summary>
///
/// </summary>
public class MongoDbContext : IMongoDbContext
{
#region Fields
private readonly string _dbName;
private readonly string _connectionString;
private readonly IMongoDatabase _database;
private readonly IMongoClient _client;
#endregion
#region Ctors
public MongoDbContext(IConfiguration configuration)
{
_dbName = configuration["Mongo:Database"];
_connectionString = configuration["Mongo:Connection"];
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(_connectionString));
_client = new MongoClient(settings);
_database = _client.GetDatabase(_dbName);
}
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
public IMongoCollection<TEntity> GetCollection<TEntity>(string name = "")
{
if (string.IsNullOrEmpty(name))
name = typeof(TEntity).Name + "s";
return _database.GetCollection<TEntity>(name);
}
/// <summary>
///
/// </summary>
public void CreateCollection<TEntity>(string name = "")
{
if (string.IsNullOrEmpty(name))
name = typeof(TEntity).Name + "s";
_database.CreateCollection(name);
}
/// <summary>
///
/// </summary>
public IList<string> Collections()
{
var collections= _database.ListCollections().ToList();
return collections.Select(c => c["name"].ToString()).ToList();
}
#endregion
}
}
|
@using Syncfusion.JavaScript;
@using Syncfusion.JavaScript.DataVisualization;
@section SampleHeading{<span class="sampleName">Chart / Pyramid Chart </span>}
@section ControlsSection{
<div>
<ej-chart id="container" can-resize="true" load="loadTheme">
<e-title text="Sales Distribution of Car by Region"></e-title>
<e-size height="600"></e-size>
<e-legend visible="true"></e-legend>
<e-chart-series>
<e-series name="Newyork" type="@SeriesType.Pyramid" label-position="@ChartLabelPosition.Outside">
<e-marker>
<e-data-label visible="true" shape="@ChartShape.Rectangle">
<e-font size="15px" color="white" font-weight="@ChartFontWeight.Lighter"></e-font>
</e-data-label>
</e-marker>
<e-points>
<e-point x="India" y="24" text="India 28%"></e-point>
<e-point x="Japan" y="25" text="Japan 25%"></e-point>
<e-point x="Australia" y="20" text="Australia 20%"></e-point>
<e-point x="USA" y="35" text="USA 35%"></e-point>
<e-point x="China" y="23" text="China 23%"></e-point>
<e-point x="Germany" y="27" text="Germany 27%"></e-point>
<e-point x="France" y="22" text="France 22%"></e-point>
</e-points>
</e-series>
</e-chart-series>
</ej-chart>
<script>
$("#controlarea").css("visibility", "visible");
</script>
</div>
} |
namespace MSQBot_API.Core.DTOs
{
public record UserRefreshTokenDto : UserLoginDto
{
public string RefreshToken { get; set; } = string.Empty;
public string AccessToken { get; set; } = string.Empty;
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System;
using UnityEngine.UI;
namespace Mobcast.Coffee.UI.ScrollModule
{
/// <summary>
/// 自動的にスクロールが進行するモジュールです.
/// </summary>
[Serializable]
public class AutoRotationModule
{
#region Serialize
[SerializeField] bool m_AutoJumpToNext = false;
[SerializeField][Range(3f,10f)] float m_Delay = 6;
[SerializeField][Range(1f,5f)] float m_Interval = 2;
#endregion Serialize
#region Public
public ScrollRectEx handler { get; set;}
public bool autoJumpToNext { get{ return m_AutoJumpToNext;} set{ m_AutoJumpToNext = value;} }
public float interval { get{ return m_Interval;} set{ m_Interval = value;} }
public float delay { get{ return m_Delay;} set{ m_Delay = value;} }
public void OnBeginDrag(PointerEventData eventData)
{
_isDragging = true;
}
public void OnEndDrag(PointerEventData eventData)
{
_autoJumpTimer = delay;
_isDragging = false;
}
public void Update()
{
if (autoJumpToNext && _coAutoJump == null)
{
// 他のコントロールでスクロールした場合、再ディレイさせます.
if (_lastPosition != handler.scrollPosition || _autoJumpTimer <= 0)
{
_autoJumpTimer = Mathf.Max(_autoJumpTimer, delay);
}
// 非ドラッグ状態で、オートローテーションタイマが有効な場合、タイマを進め、トリガします.
else if (!_isDragging && 0 < _autoJumpTimer && (_autoJumpTimer -= Time.unscaledDeltaTime) <= 0)
{
_coAutoJump = handler.StartCoroutine(_CoAutoJump());
}
}
_lastPosition = handler.scrollPosition;
}
#endregion Public
#region Private
Coroutine _coAutoJump;
float _autoJumpTimer = 0;
bool _isDragging;
float _lastPosition = 0;
IEnumerator _CoAutoJump()
{
_autoJumpTimer = interval;
int index = handler.activeIndex + 1;
if (handler.loop || handler.CanJumpTo(index))
handler.JumpTo(index);
else
handler.JumpTo(0);
yield return new WaitForSeconds(handler.tweenDuration + 0.1f);
_coAutoJump = null;
}
#endregion Private
}
}
|
using GameScene;
using ServerModel;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace GameController.Services
{
public class MusicService: AbstractHttpService
{
public MusicController musicController;
public IEnumerator RequestNextSong()
{
yield return Request("music/next", null, OnNextSong);
}
private void OnNextSong(string data)
{
Song song = JsonUtility.FromJson<Song>(data);
musicController.PlayNext(song);
}
}
}
|
using System;
using AbpvNext.BlobStoring.Extensions;
using Volo.Abp.BlobStoring;
namespace Demo.Blob.Aliyun
{
[BlobContainerName(Name)]
[BlobContainerUrl(60*60*24*365)]
public class ProfilePictureContainer
{
public const string Name = "profile-pictures";
}
/*
public class Consts
{
public static readonly TimeSpan UrlExpiration = TimeSpan.FromDays(365);
}
*/
} |
using Xunit;
namespace Platform.Singletons.Tests
{
public class DefaultTests
{
[Fact]
public void StructInstanceTest()
{
Assert.Equal(0, Default<int>.Instance);
}
[Fact]
public void ClassInstanceTest()
{
Assert.NotNull(Default<object>.Instance);
}
[Fact]
public void StructThreadInstanceTest()
{
Assert.Equal(0, Default<int>.ThreadInstance);
}
[Fact]
public void ClassThreadInstanceTest()
{
Assert.NotNull(Default<object>.ThreadInstance);
}
}
}
|
using System.Diagnostics.CodeAnalysis;
using MonoMod;
using UnityEngine;
#pragma warning disable CS0626
namespace Frangiclave.Patches.Assets.CS.TabletopUI
{
[MonoModPatch("Assets.CS.TabletopUI.TabletopImageBurner")]
[SuppressMessage("ReSharper", "UnusedMember.Local")]
public class TabletopImageBurner : global::Assets.CS.TabletopUI.TabletopImageBurner
{
private extern Sprite orig_LoadBurnSprite(string imageName);
private Sprite LoadBurnSprite(string imageName)
{
return ResourcesManager.GetSprite("burnImages/", imageName);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlertBot : MonoBehaviour
{
public GameObject[] copies;
float alertDelay = 1f;
int jumpForce = 8;
Rigidbody rb;
public AudioSource alert;
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.tag == "Player")
{
alert.Play();
//decrease notoriety by 5, don't go below 0
NotorietyManager.Notoriety = NotorietyManager.Notoriety > 5 ? NotorietyManager.Notoriety - 5 : 0;
for (int i = 0; i < copies.Length; i++)
{
rb = copies[i].GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
Destroy(copies[i], alertDelay);
}
rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
Destroy(gameObject, alertDelay);
}
}
}
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
namespace Duck.Cameras.Windows.Controls
{
[DesignerCategory("Code")]
public class FloatButton : PictureBox
{
public FloatButton()
{
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
Width = 100;
Height = 100;
BackColor = Theme.Colors.Primary500;
}
public new int Width { get => base.Width; set => base.Width = value; }
public new int Height { get => base.Height; set => base.Height = value; }
}
}
|
namespace CreativeCoders.Config.Base
{
public interface ISettingScoped<out T> : ISetting<T>
where T : class
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace QFSW.QC.Actions
{
/// <summary>
/// Gradually types a message to the console.
/// </summary>
public class Typewriter : Composite
{
/// <summary>
/// Configuration for the Typewriter action.
/// </summary>
public struct Config
{
public enum ChunkType
{
Character,
Word,
Line
}
public float PrintInterval;
public ChunkType Chunks;
public static readonly Config Default = new Config
{
PrintInterval = 0f,
Chunks = ChunkType.Character
};
}
private static readonly Regex WhiteRegex = new Regex(@"(?<=[\s+])", RegexOptions.Compiled);
private static readonly Regex LineRegex = new Regex(@"(?<=[\n+])", RegexOptions.Compiled);
/// <param name="message">The message to display to the console.</param>
public Typewriter(string message)
: this(message, Config.Default)
{ }
/// <param name="message">The message to display to the console.</param>
/// <param name="config">The configuration to be used.</param>
public Typewriter(string message, Config config)
: base(Generate(message, config))
{ }
private static IEnumerator<ICommandAction> Generate(string message, Config config)
{
string[] chunks;
switch (config.Chunks)
{
case Config.ChunkType.Character: chunks = message.Select(c => c.ToString()).ToArray(); break;
case Config.ChunkType.Word: chunks = WhiteRegex.Split(message); break;
case Config.ChunkType.Line: chunks = LineRegex.Split(message); break;
default: throw new ArgumentException($"Chunk type {config.Chunks} is not supported.");
}
for (int i = 0; i < chunks.Length; i++)
{
yield return new WaitRealtime(config.PrintInterval);
yield return new Value(chunks[i], i == 0);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq;
using System.Text;
namespace GoogleAdmin
{
[Serializable()]
public class GoogleDirectoryResponseBase
{
[OptionalField()]
public GoogleDirectoryResponseError error;
[OptionalField()]
public String kind;
[OptionalField()]
public String nextPageToken;
}
[Serializable()]
public class GoogleDirectoryResponse : GoogleDirectoryResponseBase
{
[OptionalField()]
public List<GoogleDirectoryUserInfo> users;
}
[Serializable()]
public class GoogleDirectoryUserName
{
[OptionalField()]
public String givenName;
[OptionalField()]
public String familyName;
public String fullName;
}
[Serializable()]
public class GoogleDirectoryUserEmail
{
public String address;
[OptionalField()]
public Boolean primary;
}
[Serializable()]
public class GoogleDirectoryExternalIds
{
[OptionalField()]
public String value;
[OptionalField()]
public String type;
[OptionalField()]
public String customType;
}
[Serializable()]
public class GoogleDirectoryUserInfo : GoogleDirectoryResponseBase
{
[OptionalField()]
public String primaryEmail;
[OptionalField()]
public GoogleDirectoryUserName name;
[OptionalField()]
public String orgUnitPath;
[OptionalField()]
public String id;
[OptionalField()]
public Boolean isAdmin;
[OptionalField()]
public String lastLoginTime;
[OptionalField()]
public String creationTime;
[OptionalField()]
public Boolean suspended;
[OptionalField()]
public Boolean changePasswordAtNextLogin;
[OptionalField()]
public List<GoogleDirectoryUserEmail> emails;
[OptionalField()]
public String customerId;
[OptionalField()]
public List<GoogleDirectoryExternalIds> externalIds;
}
[Serializable()]
public class GoogleDirectoryResponseError
{
[OptionalField()]
public List<GoogleDirectoryResponseError> errors;
[OptionalField()]
public String code;
[OptionalField()]
public String message;
[OptionalField()]
public String domain;
[OptionalField()]
public String reason;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using FlowTomator.Common;
using SmartSync.Common;
namespace FlowTomator.SmartSync
{
[Node("Sync profile", "SmartSync", "Use the specified profile to perform a synchronization")]
public class ProfileSync : Task
{
public override IEnumerable<Variable> Inputs
{
get
{
yield return profile;
}
}
private Variable<FileInfo> profile = new Variable<FileInfo>("Profile", null, "The profile to sync");
public override NodeResult Run()
{
if (profile.Value == null)
{
Log.Error("You must specify a profile to sync");
return NodeResult.Fail;
}
if (!profile.Value.Exists)
{
Log.Error("The specified profile could not be found");
return NodeResult.Fail;
}
try
{
Profile p = null;
try
{
Environment.CurrentDirectory = Path.GetDirectoryName(profile.Value.FullName);
switch (profile.Value.Extension)
{
case ".xsync": p = XProfile.Load(XDocument.Load(profile.Value.FullName)); break;
}
}
catch (Exception e)
{
Log.Error("Error while loading the specified profile: " + e.Message);
}
// Compute differences and actions
Diff[] differences = p.GetDifferences().ToArray();
global::SmartSync.Common.Action[] actions = differences.Select(d => d.GetAction(p.SyncType)).ToArray();
if (actions.Length > 0)
{
// Process actions
for (int i = 0; i < actions.Length; i++)
{
Log.Info("{1} % - {0} ...", actions[i], i * 100 / actions.Length);
actions[i].Process();
}
Log.Info("Flushing data to storage...");
}
p.Dispose();
Log.Info("Everything is in sync. {0} actions processed.", actions.Length);
return NodeResult.Success;
}
catch (Exception e)
{
Log.Error("Error while trying to sync specified profile: " + e.Message);
return NodeResult.Fail;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class RoomItem : MonoBehaviour
{
public Text roomName;
public Text roomIP;
public Text member;
public Button join;
public void SetInfo(MyServerResponse info, Action<string> joinRoom) {
roomName.text = info.name;
roomIP.text = info.EndPoint.Address.ToString();
member.text = $"{info.playerCount}/{info.maxPlayerCount}";
join.onClick.RemoveAllListeners();
join.onClick.AddListener(() => joinRoom(info.deviceUniqueIdentifier));
}
}
|
using Newtonsoft.Json;
namespace ArgentPonyWarcraftClient
{
/// <summary>
/// An item.
/// </summary>
public class Item
{
/// <summary>
/// Gets links for the item.
/// </summary>
[JsonProperty("_links")]
public Links Links { get; set; }
/// <summary>
/// Gets the ID of the item.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets the name of the item.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Gets the item quality.
/// </summary>
[JsonProperty("quality")]
public EnumType Quality { get; set; }
/// <summary>
/// Gets the item level of the item.
/// </summary>
[JsonProperty("level")]
public long Level { get; set; }
/// <summary>
/// Gets the required character level for using the item.
/// </summary>
[JsonProperty("required_level")]
public long RequiredLevel { get; set; }
/// <summary>
/// Gets the media associated with this item.
/// </summary>
[JsonProperty("media")]
public Media Media { get; set; }
/// <summary>
/// Gets a reference to the item class.
/// </summary>
[JsonProperty("item_class")]
public ItemClassReference ItemClass { get; set; }
/// <summary>
/// Gets a reference to the item subclass.
/// </summary>
[JsonProperty("item_subclass")]
public ItemSubclassReference ItemSubclass { get; set; }
/// <summary>
/// Gets the inventory type for the item.
/// </summary>
[JsonProperty("inventory_type")]
public EnumType InventoryType { get; set; }
/// <summary>
/// Gets the purchase price of the item.
/// </summary>
[JsonProperty("purchase_price")]
public long PurchasePrice { get; set; }
/// <summary>
/// Gets the vendor sell price of the item.
/// </summary>
[JsonProperty("sell_price")]
public long SellPrice { get; set; }
/// <summary>
/// Gets the maximum count of the item, which applies to stackable items.
/// </summary>
[JsonProperty("max_count")]
public long MaxCount { get; set; }
/// <summary>
/// Gets a value indicating whether the item can be equipped.
/// </summary>
[JsonProperty("is_equippable")]
public bool IsEquippable { get; set; }
/// <summary>
/// Gets a value indicating whether the item can be stacked in inventory.
/// </summary>
[JsonProperty("is_stackable")]
public bool IsStackable { get; set; }
/// <summary>
/// Gets item preview data.
/// </summary>
[JsonProperty("preview_item")]
public PreviewItem PreviewItem { get; set; }
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Vulkan.Ext
{
/// <summary>
/// Provides extension methods for the <see cref="ShaderModule"/> class.
/// </summary>
public static class ShaderModuleExtensions
{
/// <summary>
/// Specify validation cache to use during shader module creation.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ShaderModuleValidationCacheCreateInfoExt
{
/// <summary>
/// The type of this structure.
/// </summary>
public StructureType Type;
/// <summary>
/// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure.
/// </summary>
public IntPtr Next;
/// <summary>
/// The <see cref="Ext.ValidationCacheExt"/> object from which the results of prior
/// validation attempts will be written, and to which new validation results for this
/// <see cref="ShaderModule"/> will be written (if not already present).
/// </summary>
public long ValidationCache;
}
}
}
|
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.CSharp.Articles
{
public class SetBackgroundPicture
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
// Define a string variable to store the image path.
string ImageUrl = dataDir+ "aspose-logo.jpg";
// Get the picture into the streams.
FileStream fs = File.OpenRead(ImageUrl);
// Define a byte array.
byte[] imageData = new Byte[fs.Length];
// Obtain the picture into the array of bytes from streams.
fs.Read(imageData, 0, imageData.Length);
// Close the stream.
fs.Close();
// Set the background image for the sheet.
sheet.BackgroundImage = imageData;
// Save the Excel file
workbook.Save(dataDir + "BackImageSheet.out.xlsx");
// Save the HTML file
workbook.Save(dataDir + "BackImageSheet1.out.html", SaveFormat.Html);
// ExEnd:1
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Axis
{
public const string VERTICAL_AXIS = "Vertical";
public const string HORIZONTAL_AXIS = "Horizontal";
}
public class Tags
{
public const string PLAYER_TAG = "Player";
}
public class AnimationTags
{
public const string NORMALWALK_PARAMETER = "NormalWalk";
public const string BLOCKING_PARAMETER = "Blocking";
public const string LEADJAB_TRIGGER = "LeadJab";
public const string BODYJAB_TRIGGER = "BodyJab";
public const string QUADPUNCH_TRIGGER = "QuadPunch";
public const string ISATTACKING_PARAMETER = "isAttacking";
public const string ELBOWUP_TRIGGER = "ElbowUp";
public const string HOOKUP_TRIGGER = "HookUp";
public const string LEGALKNEE_TRIGGER = "LegalKnee";
public const string LOWKICK_TRIGGER = "LowKick";
public const string ROUNDHOUSE_TRIGGER = "RoundHouse";
} |
using System.Threading;
using System.Threading.Tasks;
namespace Bogosoft.Qualification
{
class NegatedQualifierAsync<T> : IQualifyAsync<T>
{
AsyncQualifier<T> qualifier;
internal NegatedQualifierAsync(AsyncQualifier<T> qualifier)
{
this.qualifier = qualifier;
}
public async Task<bool> QualifyAsync(T @object, CancellationToken token)
{
return false == await qualifier.Invoke(@object, token).ConfigureAwait(false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
namespace WeekPicker
{
public static class NFLTeamDB
{
private static Dictionary<string, string> lookup = new Dictionary<string, string>()
{
{ "ARI", "Arizona" },
{ "ATL", "Atlanta" },
{ "BAL", "Baltimore" },
{ "BUF", "Buffalo" },
{ "CAR", "Carolina" },
{ "CHI", "Chicago" },
{ "CIN", "Cincinnati" },
{ "CLE", "Cleveland" },
{ "DAL", "Dallas" },
{ "DEN", "Denver" },
{ "DET", "Detroit" },
{ "GB", "Green Bay" },
{ "HOU", "Houston" },
{ "IND", "Indianapolis" },
{ "JAX", "Jacksonville" },
{ "KC", "Kansas City" },
{ "LA", "Los Angeles" },
{ "LAC", "Los Angeles" },
{ "MIA", "Miami" },
{ "MIN", "Minnesota" },
{ "NE", "New England" },
{ "NO", "New Orleans" },
{ "NYG", "New York" },
{ "NYJ", "New York" },
{ "OAK", "Las Vegas" },
{ "PHI", "Philadelphia" },
{ "PIT", "Pittsburgh" },
{ "SEA", "Seattle" },
{ "SF", "San Francisco" },
{ "TB", "Tampa Bay" },
{ "TEN", "Tennessee" },
{ "WAS", "Washington" }
};
private static Dictionary<string, string> invLookup = new Dictionary<string, string>()
{
{ "Arizona Cardinals", "ARI" },
{ "Atlanta Falcons", "ATL" },
{ "Baltimore Ravens", "BAL" },
{ "Buffalo Bills", "BUF" },
{ "Carolina Panthers", "CAR" },
{ "Chicago Bears", "CHI" },
{ "Cincinnati Bengals", "CIN" },
{ "Cleveland Browns", "CLE" },
{ "Dallas Cowboys", "DAL" },
{ "Denver Broncos", "DEN" },
{ "Detroit Lions", "DET" },
{ "Green Bay Packers", "GB" },
{ "Houston Texans", "HOU" },
{ "Indianapolis Colts", "IND" },
{ "Jacksonville Jaguars", "JAX" },
{ "Kansas City Chiefs", "KC" },
{ "Los Angeles Rams", "LA" },
{ "Los Angeles Chargers", "LAC" },
{ "Miami Dolphins", "MIA" },
{ "Minnesota Vikings", "MIN" },
{ "New England Patriots", "NE" },
{ "New Orleans Saints", "NO" },
{ "New York Giants", "NYG" },
{ "New York Jets", "NYJ" },
{ "Oakland Raiders", "OAK" },
{ "Las Vegas Raiders", "OAK" },
{ "Philadelphia Eagles", "PHI" },
{ "Pittsburgh Steelers", "PIT" },
{ "Seattle Seahawks", "SEA" },
{ "San Francisco 49ers", "SF" },
{ "Tampa Bay Buccaneers", "TB" },
{ "Tennessee Titans", "TEN" },
{ "Washington", "WAS" },
{ "Washington Redskins", "WAS" }
};
private static Dictionary<string, Bitmap> logoLookup = new Dictionary<string, Bitmap>()
{
{ "ARI", Properties.Resources.ARI },
{ "ATL", Properties.Resources.ATL },
{ "BAL", Properties.Resources.BAL },
{ "BUF", Properties.Resources.BUF },
{ "CAR", Properties.Resources.CAR },
{ "CHI", Properties.Resources.CHI },
{ "CIN", Properties.Resources.CIN },
{ "CLE", Properties.Resources.CLE },
{ "DAL", Properties.Resources.DAL },
{ "DEN", Properties.Resources.DEN },
{ "DET", Properties.Resources.DET },
{ "GB", Properties.Resources.GB },
{ "HOU", Properties.Resources.HOU },
{ "IND", Properties.Resources.IND },
{ "JAX", Properties.Resources.JAX },
{ "KC", Properties.Resources.KC },
{ "LA", Properties.Resources.LA },
{ "LAC", Properties.Resources.LAC },
{ "MIA", Properties.Resources.MIA },
{ "MIN", Properties.Resources.MIN },
{ "NE", Properties.Resources.NE },
{ "NO", Properties.Resources.NO },
{ "NYG", Properties.Resources.NYG },
{ "NYJ", Properties.Resources.NYJ },
{ "OAK", Properties.Resources.OAK },
{ "PHI", Properties.Resources.PHI },
{ "PIT", Properties.Resources.PIT },
{ "SEA", Properties.Resources.SEA },
{ "SF", Properties.Resources.SF },
{ "TB", Properties.Resources.TB },
{ "TEN", Properties.Resources.TEN },
{ "WAS", Properties.Resources.WAS }
};
public static string GetShortName(string fullname)
{
if (!invLookup.TryGetValue(fullname, out string shortname))
{
Console.WriteLine($"Could not get full name for full name {fullname}");
return "-NOT-FOUND-";
}
return shortname;
}
public static string GetFullname(string shortname)
{
if (!lookup.TryGetValue(shortname, out string fullname))
{
Console.WriteLine($"Could not get full name for short name {shortname}");
return "-NOT-FOUND-";
}
return fullname;
}
public static Bitmap GetLogo(string shortname)
{
if (!logoLookup.TryGetValue(shortname, out Bitmap logo))
{
Console.WriteLine($"Could not get logo for short name {shortname}");
return null;
}
return logo;
}
}
}
|
using MediatR;
namespace TorrentExtractor.Domain.Events
{
public class TorrentProcessedEvent : INotification
{
public TorrentProcessedEvent(string name, string destination)
{
Name = name;
Destination = destination;
}
public string Name { get; }
public string Destination { get; }
}
} |
<script src="~/admin/js/scripts.vendors.min.js"></script>
<script src="~/admin/js/scripts.min.js"></script> |
namespace Core.Entities.ApplicationIdentity.Access
{
public enum Actions
{
RefreshToken
}
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Compute.Models
{
public partial class ThrottledRequestsInput : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("blobContainerSasUri");
writer.WriteStringValue(BlobContainerSasUri.AbsoluteUri);
writer.WritePropertyName("fromTime");
writer.WriteStringValue(FromTime, "O");
writer.WritePropertyName("toTime");
writer.WriteStringValue(ToTime, "O");
if (Optional.IsDefined(GroupByThrottlePolicy))
{
writer.WritePropertyName("groupByThrottlePolicy");
writer.WriteBooleanValue(GroupByThrottlePolicy.Value);
}
if (Optional.IsDefined(GroupByOperationName))
{
writer.WritePropertyName("groupByOperationName");
writer.WriteBooleanValue(GroupByOperationName.Value);
}
if (Optional.IsDefined(GroupByResourceName))
{
writer.WritePropertyName("groupByResourceName");
writer.WriteBooleanValue(GroupByResourceName.Value);
}
if (Optional.IsDefined(GroupByClientApplicationId))
{
writer.WritePropertyName("groupByClientApplicationId");
writer.WriteBooleanValue(GroupByClientApplicationId.Value);
}
if (Optional.IsDefined(GroupByUserAgent))
{
writer.WritePropertyName("groupByUserAgent");
writer.WriteBooleanValue(GroupByUserAgent.Value);
}
writer.WriteEndObject();
}
}
}
|
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MicroPack.MailKit
{
public static class Extension
{
public static void AddMailKit(this ServiceCollection services, string sectionName = "mailkit")
{
var configuration = services.BuildServiceProvider().GetService<IConfiguration>();
var mailKitOptions = configuration.GetOptions<MailKitOptions>(sectionName);
services.AddSingleton(mailKitOptions);
}
}
} |
using Unity.Physics.Authoring;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
namespace Unity.Physics.Editor
{
[CustomEditor(typeof(PhysicsCategoryNames))]
[CanEditMultipleObjects]
class PhysicsCategoryNamesEditor : BaseEditor
{
#pragma warning disable 649
[AutoPopulate(ElementFormatString = "Category {0}", Resizable = false, Reorderable = false)]
ReorderableList m_CategoryNames;
#pragma warning restore 649
}
}
|
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
[SerializeField]
SettingManager settingManager;
// Use this for initialization
void Start () {
// Trout配置
//settingManager.GetComponent<SettingManager>().SetTrout();
// アイテム配置
// トラップ配置
// モンスター配置
// 階段配置
// キャラ配置
settingManager.GetComponent<SettingManager>().SetAll();
}
// Update is called once per frame
void Update () {
}
}
|
//
// This file is part of FreneticScript, created by Frenetic LLC.
// This code is Copyright (C) Frenetic LLC under the terms of the MIT license.
// See README.md or LICENSE.txt in the FreneticScript source root for the contents of the license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using FreneticScript.CommandSystem;
using FreneticScript.ScriptSystems;
using FreneticScript.TagHandlers;
using FreneticScript.TagHandlers.Objects;
namespace FreneticScript.CommandSystem.QueueCmds
{
/// <summary>The Goto command.</summary>
public class GotoCommand : AbstractCommand
{
// <--[command]
// @Name goto
// @Arguments <mark name>
// @Short Goes to the marked location in a script.
// @Updated 2016/04/28
// @Authors mcmonkey
// @Group Queue
// @Minimum 1
// @Maximum 1
// @Description
// Goes to the marked location in a script.
// See the <@link command mark>mark command<@/link>.
// TODO: Explain more!
// @Example
// // This example echos "hi".
// goto skip;
// echo nope;
// mark skip;
// echo hi;
// @Example
// // TODO: More examples!
// -->
/// <summary>Constructs the goto command.</summary>
public GotoCommand()
{
Name = "goto";
Arguments = "<mark name>";
Description = "Goes to the marked location in the script.";
IsFlow = true;
Asyncable = true;
MinimumArguments = 1;
MaximumArguments = 1;
ObjectTypes = new Action<ArgumentValidation>[]
{
TextTag.Validator
};
}
/// <summary>Adapts a command entry to CIL.</summary>
/// <param name="values">The adaptation-relevant values.</param>
/// <param name="entry">The present entry ID.</param>
public override void AdaptToCIL(CILAdaptationValues values, int entry)
{
CommandEntry cent = values.Entry.Entries[entry];
string targ = cent.Arguments[0].ToString();
for (int i = 0; i < values.Entry.Entries.Length; i++)
{
if (values.Entry.Entries[i].Command is MarkCommand
&& values.Entry.Entries[i].Arguments[0].ToString() == targ)
{
// TODO: call Outputter function?
values.ILGen.Emit(OpCodes.Br, values.Entry.AdaptedILPoints[i]);
return;
}
}
throw new Exception("GOTO command invalid: no matching mark!");
}
/// <summary>Executes the command.</summary>
/// <param name="queue">The command queue involved.</param>
/// <param name="entry">Entry to be executed.</param>
public static void Execute(CommandQueue queue, CommandEntry entry)
{
throw new NotImplementedException("Must be compiled!");
}
}
}
|
using System;
using System.Windows.Forms;
namespace dBosque.Stub.Editor.Controls.Behaviours
{
/// <summary>
/// DragDrop behaviour on a control
/// </summary>
public class DragDropPasteBehaviour
{
/// <summary>
/// The contol to act upon
/// </summary>
protected readonly Control _child;
/// <summary>
/// The event to invoke
/// </summary>
private readonly EventHandler<DragDropPasteContentEventArgs> _event;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="c">The control to act upon</param>
/// <param name="e">The event to invoke</param>
public DragDropPasteBehaviour(Control c , EventHandler<DragDropPasteContentEventArgs> e)
{
_child = c;
_child.AllowDrop = true;
_child.DragEnter += T_DragEnter;
_child.DragDrop += T_DragDrop;
_child.KeyUp += T_KeyUp;
_event = e;
}
/// <summary>
/// Key up
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void T_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
e.Handled = e.SuppressKeyPress = true;
string content = GetDataObjectData(Clipboard.GetDataObject());
_event?.Invoke(_child, new DragDropPasteContentEventArgs(content));
}
}
/// <summary>
/// Retrieve the data from the clipboard or the drag/drop event
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private string GetDataObjectData(IDataObject e)
{
// Only allow files
if (e.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.GetData(DataFormats.FileDrop);
if (files.Length == 1)
return new System.IO.StreamReader(files[0]).ReadToEnd();
}
if (e.GetDataPresent(DataFormats.Text))
return (string)e.GetData(DataFormats.Text);
return string.Empty;
}
/// <summary>
/// DragDrop event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void T_DragDrop(object sender, DragEventArgs e)
{
string content = GetDataObjectData(e.Data);
_event?.Invoke(_child, new DragDropPasteContentEventArgs(content));
}
/// <summary>
/// Drag enter
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void T_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Contracts.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
namespace API.Restful.Controllers
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}")]
public class RootController : Controller
{
private readonly IUrlHelper _urlHelper;
public RootController(IUrlHelper urlHelper)
{
_urlHelper = urlHelper;
}
[HttpGet(Name = "GetRoot")]
public IActionResult GetRoot([FromHeader(Name = "Accept")]string mediaType)
{
if (mediaType == "application/hal+json")
{
var links = new List<LinkDto>
{
new LinkDto(_urlHelper.Link("GetRoot", new { }), "self", "GET"),
new LinkDto(_urlHelper.Link("GetComputers", new { }), "computers", "GET"),
new LinkDto(_urlHelper.Link("CreateComputer", new { }), "create_computer", "POST")
};
return Ok(links);
}
return NoContent();
}
}
}
|
/*
* Created by SharpDevelop.
* User: 0x8BitDev Copyright 2017-2021 ( MIT license. See LICENSE.txt )
* Date: 26.11.2018
* Time: 17:38
*/
namespace MAPeD
{
partial class tiles_palette_form
{
/// <summary>
/// Designer variable used to keep track of non-visual components.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Disposes resources used by the form.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.PanelPaletteTiles = new System.Windows.Forms.FlowLayoutPanel();
this.PanelPaletteBlocks = new System.Windows.Forms.FlowLayoutPanel();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.panel1 = new System.Windows.Forms.Panel();
this.BtnBlocks = new System.Windows.Forms.Button();
this.BtnTiles = new System.Windows.Forms.Button();
this.BtnClose = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// PanelPaletteTiles
//
this.PanelPaletteTiles.AutoScroll = true;
this.PanelPaletteTiles.BackColor = System.Drawing.SystemColors.Info;
this.PanelPaletteTiles.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.PanelPaletteTiles.Cursor = System.Windows.Forms.Cursors.No;
this.PanelPaletteTiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.PanelPaletteTiles.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
this.PanelPaletteTiles.Location = new System.Drawing.Point(0, 0);
this.PanelPaletteTiles.Name = "PanelPaletteTiles";
this.PanelPaletteTiles.Size = new System.Drawing.Size(554, 537);
this.PanelPaletteTiles.TabIndex = 3;
//
// PanelPaletteBlocks
//
this.PanelPaletteBlocks.AutoScroll = true;
this.PanelPaletteBlocks.BackColor = System.Drawing.SystemColors.Info;
this.PanelPaletteBlocks.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.PanelPaletteBlocks.Cursor = System.Windows.Forms.Cursors.No;
this.PanelPaletteBlocks.Dock = System.Windows.Forms.DockStyle.Fill;
this.PanelPaletteBlocks.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
this.PanelPaletteBlocks.Location = new System.Drawing.Point(0, 0);
this.PanelPaletteBlocks.Name = "PanelPaletteBlocks";
this.PanelPaletteBlocks.Size = new System.Drawing.Size(554, 537);
this.PanelPaletteBlocks.TabIndex = 3;
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.PanelPaletteBlocks);
this.splitContainer1.Panel1.Controls.Add(this.PanelPaletteTiles);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.panel1);
this.splitContainer1.Size = new System.Drawing.Size(554, 573);
this.splitContainer1.SplitterDistance = 537;
this.splitContainer1.TabIndex = 5;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.Silver;
this.panel1.Controls.Add(this.BtnBlocks);
this.panel1.Controls.Add(this.BtnTiles);
this.panel1.Controls.Add(this.BtnClose);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(554, 32);
this.panel1.TabIndex = 1;
//
// BtnBlocks
//
this.BtnBlocks.Location = new System.Drawing.Point(86, 3);
this.BtnBlocks.Name = "BtnBlocks";
this.BtnBlocks.Size = new System.Drawing.Size(75, 23);
this.BtnBlocks.TabIndex = 1;
this.BtnBlocks.Text = "&Blocks";
this.BtnBlocks.UseVisualStyleBackColor = true;
this.BtnBlocks.Click += new System.EventHandler(this.BtnBlocksClick_Event);
//
// BtnTiles
//
this.BtnTiles.Location = new System.Drawing.Point(5, 3);
this.BtnTiles.Name = "BtnTiles";
this.BtnTiles.Size = new System.Drawing.Size(75, 23);
this.BtnTiles.TabIndex = 0;
this.BtnTiles.Text = "&Tiles";
this.BtnTiles.UseVisualStyleBackColor = true;
this.BtnTiles.Click += new System.EventHandler(this.BtnTilesClick_Event);
//
// BtnClose
//
this.BtnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.BtnClose.Location = new System.Drawing.Point(474, 3);
this.BtnClose.Name = "BtnClose";
this.BtnClose.Size = new System.Drawing.Size(75, 23);
this.BtnClose.TabIndex = 2;
this.BtnClose.Text = "&Close";
this.BtnClose.UseVisualStyleBackColor = true;
this.BtnClose.Click += new System.EventHandler(this.BtnCloseClick_Event);
//
// tiles_palette_form
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.ClientSize = new System.Drawing.Size(554, 573);
this.Controls.Add(this.splitContainer1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = global::MAPeD.Properties.Resources.MAPeD_icon;
this.IsMdiContainer = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "tiles_palette_form";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Palette";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Closing_Event);
this.Load += new System.EventHandler(this.BtnCloseClick_Event);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.FlowLayoutPanel PanelPaletteBlocks;
private System.Windows.Forms.Button BtnBlocks;
private System.Windows.Forms.Button BtnTiles;
private System.Windows.Forms.Button BtnClose;
private System.Windows.Forms.FlowLayoutPanel PanelPaletteTiles;
private System.Windows.Forms.Panel panel1;
}
}
|
using JetBrains.ReSharper.Plugins.Yaml.Psi;
using JetBrains.ReSharper.Psi;
using JetBrains.TestFramework;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Yaml.Tests.Psi
{
[TestFixture]
public class YamlLanguageTests : BaseTest
{
[Test]
public void LanguageIsRegistered()
{
Assert.NotNull(YamlLanguage.Instance);
Assert.NotNull(Languages.Instance.GetLanguageByName(YamlLanguage.Name));
}
}
} |
using CommandLine;
namespace Scavenger
{
public class Program
{
private static int Main(string[] args)
{
return Parser.Default.ParseArguments<StartOptions, InstallOptions, UninstallOptions, StatusOptions>(args)
.MapResult(
(StartOptions opts) => ServiceUtility.StartServiceDirectly(opts),
(InstallOptions opts) => ServiceUtility.RunRegistAndReturnExitCode(opts),
(UninstallOptions opts) => ServiceUtility.RunUnregistAndeReturnExitCode(opts),
(StatusOptions opts) => ServiceUtility.RunStatusAndReturnExitCode(opts),
errs => 1);
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace AspNetCore.ApiGateway
{
public class ApiInfo
{
public string BaseUrl { get; set; }
public Mediator Mediator { get; set; }
}
public class ApiOrchestrator : IApiOrchestrator
{
Dictionary<string, ApiInfo> apis = new Dictionary<string, ApiInfo>();
public IMediator AddApi(string apiKey, string baseUrl)
{
var mediator = new Mediator(this);
apis.Add(apiKey.ToLower(), new ApiInfo() { BaseUrl = baseUrl, Mediator = mediator });
return mediator;
}
public ApiInfo GetApi(string apiKey)
{
return apis[apiKey.ToLower()];
}
public IEnumerable<Orchestration> Orchestration => apis?.Select(x => new Orchestration
{
Api = x.Key,
Routes = x.Value.Mediator.Routes
});
}
}
|
using SpiceSharpParser.Common.Validation;
namespace SpiceSharpParser.Parsers
{
public class ParsingValidationResult : ValidationEntryCollection
{
}
}
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
function MainMenuGui::onAdd(%this)
{
//echo("MainMenuGui::onAdd()");
%this.zBitmapOffset = 0;
}
function MainMenuGui::onWake(%this)
{
//echo("MainMenuGui::onWake()");
MainMenuVersionString.setText($GameVersionString);
if (isFunction("getWebDeployment") &&
getWebDeployment() &&
isObject(%this-->ExitButton))
%this-->ExitButton.setVisible(false);
if($GameVersionType !$= "public" && $GameVersionFeedbackURL !$= "")
{
if(WelcomeDlg.zUnderstood == false)
Canvas.pushDialog(WelcomeDlg);
}
// Start tick thread.
%this.tickThread();
}
function MainMenuGui::onSleep(%this)
{
//echo("MainMenuGui::onSleep()");
// Stop tick thread.
cancel(%this.zTickThread);
}
function MainMenuGui::tickThread(%this)
{
//echo("MainMenuGui::tickThread()");
if(%this.zTickThread !$= "")
{
cancel(%this.zTickThread);
%this.zTickThread = "";
}
%this.zTickThread = %this.schedule(32, "tickThread");
%this.zBitmapOffset--;
%this-->Scanlines.setValue(%this.zBitmapOffset, %this.zBitmapOffset);
%this-->Noise.setValue(getRandom(0, 100), getRandom(0, 100));
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static string[] punctuation = new string[] { " ", ",", ".", "(", ")", ";", "-", "!", "?" };
static void Main(string[] args)
{
string searchWord = Console.ReadLine();
int paragraphsNumber = int.Parse(Console.ReadLine());
List<string> allParagraphs = new List<string>();
List<int> count = new List<int>();
for (int i = 0; i < paragraphsNumber; i++)
{
string[] line = Console.ReadLine().Split(punctuation, StringSplitOptions.RemoveEmptyEntries);
int tempCount = 0;
for (int j = 0; j < line.Length; j++)
{
if (line[j].ToLower() == searchWord.ToLower())
{
tempCount++;
line[j] = line[j].ToUpper();
}
}
count.Add(tempCount);
tempCount = 0;
allParagraphs.Add(String.Join(" ", line));
}
List<string> result = new List<string>();
while (result.Count < allParagraphs.Count)
{
int maxRelevent = 0;
int maxIndex = 0;
for (int i = 1; i < count.Count; i++)
{
if (maxRelevent < count[i])
{
maxRelevent = count[i];
maxIndex = i;
}
}
result.Add(allParagraphs[maxIndex]);
count[maxIndex] = -1;
}
result.ForEach(Console.WriteLine);
}
} |
using Xunit.Abstractions;
namespace LuckyDrawBot.Tests.Infrastructure
{
public class TestContext
{
public ITestOutputHelper Output { get; }
public TestContext(ITestOutputHelper output)
{
Output = output;
}
}
} |
using NUnit.Framework;
namespace Thuria.Zitidar.Extensions.Tests
{
[TestFixture]
public class TestStringExtensions
{
[TestCase("Test Case 1", "testCase1")]
[TestCase("test Case 1", "testCase1")]
[TestCase("Test case 1", "testCase1")]
[TestCase("Testcase 1", "testcase1")]
[TestCase("Test_Case%1", "testCase1")]
[TestCase("Test Case 1", "testCase1")]
[TestCase("Test__Case___1", "testCase1")]
public void CamelCase_GivenString_ShouldPascalCaseString(string inputString, string expectedResult)
{
//---------------Set up test pack-------------------
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
var result = inputString.CamelCase();
//---------------Test Result -----------------------
Assert.AreEqual(expectedResult, result);
}
[TestCase("Test Case 1", "TestCase1")]
[TestCase("test Case 1", "TestCase1")]
[TestCase("Test case 1", "TestCase1")]
[TestCase("Testcase 1", "Testcase1")]
[TestCase("Test_Case%1", "TestCase1")]
[TestCase("Test Case 1", "TestCase1")]
[TestCase("Test__Case___1", "TestCase1")]
public void PascalCase_GivenString_ShouldPascalCaseString(string inputString, string expectedResult)
{
//---------------Set up test pack-------------------
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
var result = inputString.PascalCase();
//---------------Test Result -----------------------
Assert.AreEqual(expectedResult, result);
}
[Test]
public void EscapeQuotes_GivenString_ShouldEscapeQuotes()
{
//---------------Set up test pack-------------------
var inputString = "Test \" Some string";
//---------------Assert Precondition----------------
//---------------Execute Test ----------------------
var result = inputString.EscapeQuotes();
//---------------Test Result -----------------------
Assert.AreEqual(@"Test \"" Some string", result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Slidezy.Core;
using Slidezy.Core.Events;
namespace Slidezy
{
public class SessionHub : Hub
{
public async Task JoinSession(string sessionId)
{
await this.Groups.AddToGroupAsync(this.Context.ConnectionId, sessionId, this.Context.ConnectionAborted);
}
public async Task AddSlide(string sessionId, AddSlideEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(AddSlide), @event);
}
public async Task SelectSlide(string sessionId, SelectSlideEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(SelectSlide), @event);
}
public async Task StartPath(string sessionId, StartPathEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(StartPath), @event);
}
public async Task ContinuePath(string sessionId, ContinuePathEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(ContinuePath), @event);
}
public async Task CompletePath(string sessionId, CompletePathEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(CompletePath), @event);
}
public async Task ClearSlidePaths(string sessionId, ClearSlidePathsEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(ClearSlidePaths), @event);
}
public async Task RemovePath(string sessionId, RemovePathEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(RemovePath), @event);
}
public async Task SetPencil(string sessionId, SetPencilEvent @event)
{
await this.Clients.OthersInGroup(sessionId).SendAsync(nameof(SetPencil), @event);
}
}
}
|
using System;
using Sitecore.Data.Items;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
namespace Feature.FormsExtensions.Fields.Bindings
{
[Serializable]
public class MultipleLineTextViewWithBindingsTokenModel : MultipleLineTextViewModel, IBindingSettings
{
public bool StoreBindingValue { get; set; }
protected override void InitItemProperties(Item item)
{
base.InitItemProperties(item);
this.InitBindingSettingsProperties(item);
}
protected override void UpdateItemFields(Item item)
{
base.UpdateItemFields(item);
this.UpdateBindingSettingsFields(item);
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using IO.Ably.Realtime;
using IO.Ably.Realtime.Workflow;
using IO.Ably.Tests.Infrastructure;
using IO.Ably.Transport;
using IO.Ably.Types;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace IO.Ably.Tests.NETFramework.Realtime
{
public class RealtimeWorkflowSpecs : AblyRealtimeSpecs
{
public class GeneralSpecs : AblyRealtimeSpecs
{
[Fact]
[Trait("spec", "RTN8b")]
public void ConnectedState_UpdatesConnectionInformation()
{
// Act
var connectedProtocolMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Connected)
{
ConnectionId = "1",
ConnectionSerial = 100,
ConnectionDetails = new ConnectionDetails
{
ClientId = "client1",
ConnectionKey = "validKey"
},
};
var client = GetRealtimeClient(options => options.AutoConnect = false);
client.Workflow.ProcessCommand(SetConnectedStateCommand.Create(connectedProtocolMessage, false));
// Assert
var connection = client.Connection;
connection.Id.Should().Be("1");
connection.Serial.Should().Be(100);
connection.Key.Should().Be("validKey");
client.Auth.ClientId.Should().Be("client1");
}
[Fact]
public async Task SetFailedState_ShouldClearConnectionKeyAndId()
{
var client = GetDisconnectedClient();
client.State.Connection.Key = "Test";
client.State.Connection.Id = "Test";
client.ExecuteCommand(SetFailedStateCommand.Create(null));
await client.ProcessCommands();
client.State.Connection.Key.Should().BeEmpty();
client.State.Connection.Id.Should().BeEmpty();
}
public GeneralSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class ConnectingStateSpecs : AblyRealtimeSpecs
{
[Fact]
[Trait("spec", "RTN14g")]
public async Task WithInboundErrorMessage_WhenNotTokenErrorAndChannelsEmpty_GoesToFailed()
{
var client = GetRealtimeClient(opts => opts.RealtimeHost = "non-default.ably.io"); // Force no fallback
await client.WaitForState(ConnectionState.Connecting);
// Arrange
ErrorInfo targetError = new ErrorInfo("test", 123);
// Act
client.Workflow.ProcessCommand(ProcessMessageCommand.Create(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = targetError }));
// Assert
await client.WaitForState(ConnectionState.Failed);
}
public ConnectingStateSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class ConnectingCommandSpecs : AblyRealtimeSpecs
{
[Fact]
public async Task WithInboundErrorMessageWhenItCanUseFallBack_ShouldClearsConnectionKey()
{
// Arrange
var client = GetRealtimeClient(options =>
{
options.RealtimeRequestTimeout = TimeSpan.FromSeconds(60);
options.DisconnectedRetryTimeout = TimeSpan.FromSeconds(60);
});
await client.WaitForState(ConnectionState.Connecting);
var messageWithError = new ProtocolMessage(ProtocolMessage.MessageAction.Error)
{
Error = new ErrorInfo("test", 123, System.Net.HttpStatusCode.InternalServerError),
};
// Act
await client.ProcessMessage(messageWithError);
client.State.Connection.Key.Should().BeEmpty();
}
[Fact]
public async Task WithInboundDisconnectedMessage_ShouldTransitionToDisconnectedState()
{
// Arrange
var client = GetRealtimeClient();
client.Connect();
await client.WaitForState(ConnectionState.Connecting);
var disconnectedMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Disconnected) { Error = ErrorInfo.ReasonDisconnected };
// Act
client.ExecuteCommand(ProcessMessageCommand.Create(disconnectedMessage));
await client.WaitForState(ConnectionState.Disconnected, TimeSpan.FromSeconds(5));
}
[Fact]
public async Task WhenDisconnectedWithFallback_ShouldRetryConnectionImmediately()
{
var client = GetClientWithFakeTransport();
await client.WaitForState(ConnectionState.Connecting);
var states = new List<ConnectionState>();
client.Connection.On(changes => states.Add(changes.Current));
client.ExecuteCommand(SetDisconnectedStateCommand.Create(ErrorInfo.ReasonClosed, true));
await client.ProcessCommands();
// Assert
states.Should().HaveCount(2);
states.Should().BeEquivalentTo(new[] { ConnectionState.Disconnected, ConnectionState.Connecting });
}
[Fact]
public async Task ShouldCreateTransport()
{
// Arrange
var client = GetClientWithFakeTransport(opts => opts.AutoConnect = false);
LastCreatedTransport.Should().BeNull();
client.ExecuteCommand(SetConnectingStateCommand.Create());
await client.ProcessCommands();
// Assert
LastCreatedTransport.Should().NotBeNull();
}
public ConnectingCommandSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class SuspendedCommandSpecs : AblyRealtimeSpecs
{
[Fact]
[Trait("spec", "RTN7c")]
[Trait("sandboxTest", "needed")]
public async Task OnAttached_ClearsAckQueue()
{
var client = GetDisconnectedClient();
client.State.WaitingForAck.Add(new MessageAndCallback(new ProtocolMessage(), null));
client.ExecuteCommand(SetSuspendedStateCommand.Create(null));
await client.ProcessCommands(); // Wait for the command to be executed
client.State.WaitingForAck.Should().BeEmpty();
}
public SuspendedCommandSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class ClosingCommandSpecs : AblyRealtimeSpecs
{
[Theory]
[InlineData(TransportState.Closed)]
[InlineData(TransportState.Closing)]
[InlineData(TransportState.Connecting)]
[InlineData(TransportState.Initialized)]
public async Task WhenTransportIsNotConnected_ShouldGoStraightToClosed(TransportState transportState)
{
var client = await GetConnectedClient();
// Arrange
client.ConnectionManager.Transport = new FakeTransport { State = transportState };
// Act
client.ExecuteCommand(SetClosingStateCommand.Create());
await client.ProcessCommands();
// Assert
client.State.Connection.State.Should().Be(ConnectionState.Closed);
}
[Fact]
[Trait("spec", "RTN12a")]
// When the closing state is initialised a Close message is sent
public async Task WhenTransportIsNotConnected_ShouldSendCloseMessage()
{
var client = await GetConnectedClient();
// Act
client.ExecuteCommand(SetClosingStateCommand.Create());
await client.ProcessCommands();
// Assert
LastCreatedTransport.LastMessageSend.Should().NotBeNull();
LastCreatedTransport.LastMessageSend.Action.Should().Be(ProtocolMessage.MessageAction.Close);
}
public ClosingCommandSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class SetFailedStateCommandSpecs : AblyRealtimeSpecs
{
[Fact]
[Trait("spec", "RTN7c")]
[Trait("sandboxTest", "needed")]
public async Task ShouldDestroyTransport()
{
var client = await GetConnectedClient();
client.ConnectionManager.Transport.Should().NotBeNull();
client.ExecuteCommand(SetFailedStateCommand.Create(ErrorInfo.ReasonFailed));
await client.ProcessCommands();
client.ConnectionManager.Transport.Should().BeNull();
}
[Fact]
[Trait("spec", "RTN7c")]
[Trait("sandboxTest", "needed")]
public async Task ShouldClearsAckQueue()
{
var client = GetDisconnectedClient();
client.State.WaitingForAck.Add(new MessageAndCallback(new ProtocolMessage(), null));
client.ExecuteCommand(SetClosedStateCommand.Create());
await client.ProcessCommands(); // Wait for the command to be executed
client.State.WaitingForAck.Should().BeEmpty();
}
public SetFailedStateCommandSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class ClosedCommandSpecs : AblyRealtimeSpecs
{
[Fact]
[Trait("spec", "RTN7c")]
[Trait("sandboxTest", "needed")]
public async Task OnAttached_ShouldDestroyTranspоrt()
{
var client = await GetConnectedClient();
client.ConnectionManager.Transport.Should().NotBeNull();
client.ExecuteCommand(SetClosedStateCommand.Create());
await client.ProcessCommands();
client.ConnectionManager.Transport.Should().BeNull();
}
[Fact]
[Trait("spec", "RTN7c")]
[Trait("sandboxTest", "needed")]
public async Task OnAttached_ClearsAckQueue()
{
var client = GetDisconnectedClient();
client.State.WaitingForAck.Add(new MessageAndCallback(new ProtocolMessage(), null));
client.ExecuteCommand(SetClosedStateCommand.Create());
await client.ProcessCommands(); // Wait for the command to be executed
client.State.WaitingForAck.Should().BeEmpty();
}
public ClosedCommandSpecs(ITestOutputHelper output)
: base(output)
{
}
}
public class AckProtocolTests : RealtimeWorkflowSpecs
{
[Theory]
[InlineData(ProtocolMessage.MessageAction.Message)]
[InlineData(ProtocolMessage.MessageAction.Presence)]
[Trait("spec", "RTN7a")]
[Trait("spec", "RTN7b")]
[Trait("sandboxTest", "needed")]
public async Task WhenSendingPresenceOrDataMessage_IncrementsMsgSerial(
ProtocolMessage.MessageAction messageAction)
{
// Arrange
var client = await GetConnectedClient();
var targetMessage1 = new ProtocolMessage(messageAction, "Test");
var targetMessage2 = new ProtocolMessage(messageAction, "Test");
var targetMessage3 = new ProtocolMessage(messageAction, "Test");
client.ExecuteCommand(SendMessageCommand.Create(targetMessage1));
client.ExecuteCommand(SendMessageCommand.Create(targetMessage2));
client.ExecuteCommand(SendMessageCommand.Create(targetMessage3));
await client.ProcessCommands();
// Assert
targetMessage1.MsgSerial.Should().Be(0);
targetMessage2.MsgSerial.Should().Be(1);
targetMessage3.MsgSerial.Should().Be(2);
}
// TODO: Move the test to the workflow tests for send message
[Theory]
[InlineData(ProtocolMessage.MessageAction.Ack)]
[InlineData(ProtocolMessage.MessageAction.Attach)]
[InlineData(ProtocolMessage.MessageAction.Attached)]
[InlineData(ProtocolMessage.MessageAction.Close)]
[InlineData(ProtocolMessage.MessageAction.Closed)]
[InlineData(ProtocolMessage.MessageAction.Connect)]
[InlineData(ProtocolMessage.MessageAction.Connected)]
[InlineData(ProtocolMessage.MessageAction.Detach)]
[InlineData(ProtocolMessage.MessageAction.Detached)]
[InlineData(ProtocolMessage.MessageAction.Disconnect)]
[InlineData(ProtocolMessage.MessageAction.Disconnected)]
[InlineData(ProtocolMessage.MessageAction.Error)]
[InlineData(ProtocolMessage.MessageAction.Heartbeat)]
[InlineData(ProtocolMessage.MessageAction.Nack)]
[InlineData(ProtocolMessage.MessageAction.Sync)]
[Trait("spec", "RTN7a")]
public async Task WhenSendingNotAPresenceOrDataMessage_MsgSerialNotIncremented(
ProtocolMessage.MessageAction messageAction)
{
// Arrange
var client = await GetConnectedClient();
var targetMessage1 = new ProtocolMessage(messageAction, "Test");
var targetMessage2 = new ProtocolMessage(messageAction, "Test");
var targetMessage3 = new ProtocolMessage(messageAction, "Test");
client.ExecuteCommand(SendMessageCommand.Create(targetMessage1));
client.ExecuteCommand(SendMessageCommand.Create(targetMessage2));
client.ExecuteCommand(SendMessageCommand.Create(targetMessage3));
await client.ProcessCommands();
// Assert
targetMessage1.MsgSerial.Should().Be(0);
targetMessage2.MsgSerial.Should().Be(0);
targetMessage3.MsgSerial.Should().Be(0);
}
[Theory]
[InlineData(ProtocolMessage.MessageAction.Ack)]
[InlineData(ProtocolMessage.MessageAction.Nack)]
public async Task WhenReceivingAckOrNackMessage_ShouldHandleAction(ProtocolMessage.MessageAction action)
{
var client = GetDisconnectedClient();
// Act
bool result = await client.Workflow.HandleAckMessage(new ProtocolMessage(action));
// Assert
result.Should().BeTrue();
}
[Theory]
[InlineData(ProtocolMessage.MessageAction.Attach)]
[InlineData(ProtocolMessage.MessageAction.Attached)]
[InlineData(ProtocolMessage.MessageAction.Close)]
[InlineData(ProtocolMessage.MessageAction.Closed)]
[InlineData(ProtocolMessage.MessageAction.Connect)]
[InlineData(ProtocolMessage.MessageAction.Connected)]
[InlineData(ProtocolMessage.MessageAction.Detach)]
[InlineData(ProtocolMessage.MessageAction.Detached)]
[InlineData(ProtocolMessage.MessageAction.Disconnect)]
[InlineData(ProtocolMessage.MessageAction.Disconnected)]
[InlineData(ProtocolMessage.MessageAction.Error)]
[InlineData(ProtocolMessage.MessageAction.Heartbeat)]
[InlineData(ProtocolMessage.MessageAction.Message)]
[InlineData(ProtocolMessage.MessageAction.Presence)]
[InlineData(ProtocolMessage.MessageAction.Sync)]
public async Task WhenReceivingNonAckOrNackMessage_ShouldNotHandleAction(
ProtocolMessage.MessageAction action)
{
var client = GetDisconnectedClient();
// Act
bool result = await client.Workflow.HandleAckMessage(new ProtocolMessage(action));
// Assert
result.Should().BeFalse();
}
[Fact]
public async Task OnAckReceivedForAMessage_AckCallbackCalled()
{
// Arrange
var client = await GetConnectedClient();
var callbacks = new List<ValueTuple<bool, ErrorInfo>>();
var message = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
void Callback(bool ack, ErrorInfo err)
{
callbacks.Add((ack, err));
}
// Act
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(ProcessMessageCommand.Create(
new ProtocolMessage(ProtocolMessage.MessageAction.Ack) { MsgSerial = 0, Count = 1 }));
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(ProcessMessageCommand.Create(
new ProtocolMessage(ProtocolMessage.MessageAction.Ack) { MsgSerial = 1, Count = 1 }));
await client.ProcessCommands();
// Assert
callbacks.Count.Should().Be(2);
Assert.True(callbacks.TrueForAll(c => c.Item1)); // Ack
Assert.True(callbacks.TrueForAll(c => c.Item2 == null)); // No error
}
[Fact]
public async Task WhenSendingMessage_AckCallbackCalled_ForMultipleMessages()
{
// Arrange
var client = await GetConnectedClient();
var callbacks = new List<ValueTuple<bool, ErrorInfo>>();
var message1 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
var message2 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
var message3 = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
var awaiter = new TaskCompletionAwaiter();
Action<bool, ErrorInfo> GetCallback(int forCount) =>
(ack, err) =>
{
if (callbacks.Count == forCount)
{
callbacks.Add((ack, err));
}
if (callbacks.Count == 3)
{
awaiter.SetCompleted();
}
};
var ackMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Ack) { MsgSerial = 0, Count = 3 };
// Act
client.Workflow.QueueAck(message1, GetCallback(0));
client.Workflow.QueueAck(message2, GetCallback(1));
client.Workflow.QueueAck(message3, GetCallback(2));
client.ExecuteCommand(ProcessMessageCommand.Create(ackMessage));
await client.ProcessCommands();
await awaiter.Task;
// Assert
callbacks.Count.Should().Be(3);
Assert.True(callbacks.TrueForAll(c => c.Item1)); // Ack
Assert.True(callbacks.TrueForAll(c => c.Item2 == null)); // No error
}
[Fact]
public async Task WithNackMessageReceived_CallbackIsCalledWithError()
{
// Arrange
var client = await GetConnectedClient();
var callbacks = new List<ValueTuple<bool, ErrorInfo>>();
var message = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
void Callback(bool ack, ErrorInfo err)
{
callbacks.Add((ack, err));
}
// Act
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(ProcessMessageCommand.Create(
new ProtocolMessage(ProtocolMessage.MessageAction.Nack) { MsgSerial = 0, Count = 1 }));
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(ProcessMessageCommand.Create(
new ProtocolMessage(ProtocolMessage.MessageAction.Nack) { MsgSerial = 1, Count = 1 }));
await client.ProcessCommands();
// Assert
callbacks.Count.Should().Be(2);
Assert.True(callbacks.TrueForAll(c => c.Item1 == false)); // Nack
Assert.True(callbacks.TrueForAll(c => c.Item2 != null)); // Error
}
[Fact]
public async Task WhenNackReceivedForMultipleMessage_AllCallbacksAreCalledAndErrorMessagePassed()
{
// Arrange
var client = await GetConnectedClient();
var callbacks = new List<ValueTuple<bool, ErrorInfo>>();
var message = new ProtocolMessage(ProtocolMessage.MessageAction.Message, "Test");
void Callback(bool ack, ErrorInfo err)
{
callbacks.Add((ack, err));
}
// Act
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
client.ExecuteCommand(SendMessageCommand.Create(message, Callback));
var error = new ErrorInfo("reason", 123);
client.ExecuteCommand(ProcessMessageCommand.Create(
new ProtocolMessage(ProtocolMessage.MessageAction.Nack) { MsgSerial = 0, Count = 3, Error = error }));
await client.ProcessCommands();
// Assert
callbacks.Count.Should().Be(3);
Assert.True(callbacks.TrueForAll(c => !c.Item1)); // Nack
Assert.True(callbacks.TrueForAll(c => ReferenceEquals(c.Item2, error))); // Error
}
public AckProtocolTests(ITestOutputHelper output)
: base(output)
{
}
}
public RealtimeWorkflowSpecs(ITestOutputHelper output)
: base(output)
{
}
}
}
|
// Copyright (c) Dmytro Kyshchenko. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Numerics;
namespace xFunc.Maths.Expressions.Hyperbolic;
/// <summary>
/// The base class for inverse hyperbolic functions.
/// </summary>
/// <seealso cref="UnaryExpression" />
public abstract class InverseHyperbolicExpression : UnaryExpression
{
/// <summary>
/// Initializes a new instance of the <see cref="InverseHyperbolicExpression" /> class.
/// </summary>
/// <param name="argument">The expression.</param>
protected InverseHyperbolicExpression(IExpression argument)
: base(argument)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InverseHyperbolicExpression"/> class.
/// </summary>
/// <param name="arguments">The argument of function.</param>
/// <seealso cref="IExpression"/>
internal InverseHyperbolicExpression(ImmutableArray<IExpression> arguments)
: base(arguments)
{
}
/// <summary>
/// Calculates this mathematical expression (using radian).
/// </summary>
/// <param name="radian">The calculation result of argument.</param>
/// <returns>
/// A result of the calculation.
/// </returns>
/// <seealso cref="ExpressionParameters" />
protected abstract AngleValue ExecuteInternal(NumberValue radian);
/// <summary>
/// Executes this expression.
/// </summary>
/// <param name="complex">The calculation result of argument.</param>
/// <returns>
/// A result of the execution.
/// </returns>
/// <seealso cref="ExpressionParameters" />
protected abstract Complex ExecuteComplex(Complex complex);
/// <inheritdoc />
public override object Execute(ExpressionParameters? parameters)
{
var result = Argument.Execute(parameters);
return result switch
{
NumberValue number => ExecuteInternal(number),
Complex complex => ExecuteComplex(complex),
_ => throw new ResultIsNotSupportedException(this, result),
};
}
} |
using Sql2Cdm.Library.Models;
using Sql2Cdm.Library.Models.Annotations;
using System.Collections.Generic;
using Xunit;
namespace Sql2Cdm.Library.Tests.Models
{
public class ColumnsTests
{
[Fact]
public void AnnotationsAreInitializedEmpty()
{
var column = new Column("name", null);
Assert.Empty(column.Annotations);
}
[Fact]
public void EqualAnnotationsAreInsertedJustOnce()
{
var args1 = new List<KeyValuePair<string, dynamic>>();
args1.Add(new KeyValuePair<string, dynamic>("key", "value"));
Annotation annotation12 = new TraitAnnotation("value", args1);
var args2 = new List<KeyValuePair<string, dynamic>>();
args2.Add(new KeyValuePair<string, dynamic>("key", "value"));
Annotation annotation22 = new TraitAnnotation("value", args2);
var res = annotation12 == annotation22;
var column = new Column("name", null);
Annotation annotation1 = new TraitAnnotation("value");
Annotation annotation2 = new TraitAnnotation("value");
column.Annotations.Add(annotation1);
column.Annotations.Add(annotation2);
Assert.Single(column.Annotations);
}
}
}
|
namespace Plaisted.PowershellHelper
{
internal interface IJsonObjectBridge
{
string Name { get; set; }
string EscapedName { get; }
object Object { get; set; }
void ReadFromTempFile();
string TemporaryFile { get; }
string CreateTempFile();
void Dispose();
}
} |
using RazorTechnologies.TagHelpers.Core.THelper;
using RazorTechnologies.TagHelpers.LayoutManager.ScopeGroup;
using System.Collections.Generic;
namespace RazorTechnologies.TagHelpers.LayoutManager
{
public interface ILayoutBody : IHtmlGeneratable
{
public IReadOnlyList<ILayoutScope> Scopes { get; }
}
} |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Data;
using System.Diagnostics;
using System.Collections.Generic;
using ESRI.ArcLogistics.ShapefileReader;
using System.IO;
namespace ESRI.ArcLogistics.App.Import
{
/// <summary>
/// Shape file data provider class
/// </summary>
internal sealed class SHPProvider : IDataProvider
{
#region Constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public SHPProvider()
{ }
#endregion // Constructors
#region static helpers
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets shape type of file.
/// </summary>
/// <param name="fileName">Shape file full name.</param>
/// <param name="messageFailure">Message failure.</param>
/// <returns>Readed shape type.</returns>
public static ShapeType GetShapeType(string fileName, out string messageFailure)
{
Debug.Assert(!string.IsNullOrEmpty(fileName));
ShapeType type = ShapeType.Null;
messageFailure = null;
try
{
Shapefile file = new Shapefile(fileName, false);
if (file.RecordCount < 1)
throw new NotSupportedException();
Shape shape = file.ReadRecord(0);
if (null == shape)
throw new NotSupportedException();
type = shape.ShapeType;
}
catch (Exception e)
{
Logger.Error(e);
messageFailure = e.Message;
}
return type;
}
/// <summary>
/// Check that projection file is present and projection is right.
/// </summary>
/// <param name="shapeFilePath">Path to shape file.</param>
/// <param name="messageFailure">Message failure.</param>
public static bool ProjectionIsRight(string shapeFilePath, out string messageFailure)
{
Debug.Assert(!string.IsNullOrEmpty(shapeFilePath));
// Check that projection file is present.
var prjFilePath = Path.ChangeExtension(shapeFilePath, PROJECTION_FILE_EXTENSION);
try
{
// Check that projection is right.
var projectionFileStart = File.ReadAllText(prjFilePath);
if (!projectionFileStart.StartsWith(WGS1984_FILESTART))
{
messageFailure = Properties.Resources.Error_WrongOrUnknownProjection;
return false;
}
}
// Catch exception in case if projection file isn't present.
catch(FileNotFoundException ex)
{
messageFailure = Properties.Resources.Error_WrongOrUnknownProjection;
return false;
}
// If we came here - projection is right.
messageFailure = null;
return true;
}
#endregion // static helpers
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Inits procedure.
/// </summary>
/// <param name="fileName">Shape file full name.</param>
/// <param name="messageFailure">Message failure.</param>
/// <returns>TRUE if initialize successed.</returns>
public bool Init(string fileName, out string messageFailure)
{
Debug.Assert(!string.IsNullOrEmpty(fileName));
messageFailure = null;
try
{
_file = new Shapefile(fileName, false);
DataTable table = _file.SchemaTable;
foreach (DataRow row in table.Rows)
{
string name = (string)row["ColumnName"];
if (!string.IsNullOrEmpty(name.Trim()))
_fieldsInfo.Add(new DataFieldInfo(name, (Type)row["DataType"]));
}
}
catch (Exception e)
{
_file = null;
Logger.Error(e);
messageFailure = e.Message;
// WORKAROUND: hardcoded replace info message
if (messageFailure.Contains(INVALID_FILE_SHAPELIB_ERROR_TEXT))
{
messageFailure = App.Current.FindString("ImportSHPFileInvalidMessage");
}
}
return _IsInited;
}
#endregion // public methods
#region IDataProvider
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Records count
/// </summary>
public int RecordsCount
{
get
{
Debug.Assert(_IsInited);
return _file.RecordCount;
}
}
/// <summary>
/// Set cursor to first row
/// </summary>
public void MoveFirst()
{
Debug.Assert(_IsInited);
_currentRowNum = 0;
_currentRow = _file.ReadAttributes(_currentRowNum);
}
/// <summary>
/// Move cursor to next row
/// </summary>
public void MoveNext()
{
Debug.Assert(_IsInited);
Debug.Assert(!IsEnd());
++_currentRowNum;
_currentRow = (IsEnd()) ? null : _file.ReadAttributes(_currentRowNum);
}
/// <summary>
/// All records iterated
/// </summary>
public bool IsEnd()
{
Debug.Assert(_IsInited);
return (RecordsCount <= _currentRowNum);
}
/// <summary>
/// Field count
/// </summary>
public int FieldCount
{
get
{
Debug.Assert(_IsInited);
return _fieldsInfo.Count;
}
}
/// <summary>
/// Obtain fields info list
/// </summary>
public ICollection<DataFieldInfo> FieldsInfo
{
get
{
Debug.Assert(_IsInited);
return _fieldsInfo;
}
}
/// <summary>
/// Obtain field value
/// </summary>
public object FieldValue(int index)
{
Debug.Assert(null != _currentRow);
return _currentRow[_fieldsInfo[index].Name];
}
/// <summary>
/// Flag is current record empty
/// </summary>
public bool IsRecordEmpty
{
get { return false; }
}
/// <summary>
/// Flag is format support geometry
/// </summary>
public bool IsGeometrySupport
{
get { return true; }
}
/// <summary>
/// Geometry
/// </summary>
/// <remarks>if format not support geometry - return null</remarks>
public object Geometry
{
get
{
Debug.Assert(_IsInited);
Shape shape = _file.ReadRecord(_currentRowNum);
return (object)shape.Geometry;
}
}
#endregion // IDataProvider
#region Private properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Is inited flag.
/// </summary>
public bool _IsInited
{
get
{
return (_file != null);
}
}
#endregion // Private properties
#region Private constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private const string INVALID_FILE_SHAPELIB_ERROR_TEXT = "Unable to find the specified file";
/// <summary>
/// File start for a projection file for WGS 1984 projection.
/// </summary>
private const string WGS1984_FILESTART = "GEOGCS[\"GCS_WGS_1984\"";
/// <summary>
/// Projection file extension.
/// </summary>
private const string PROJECTION_FILE_EXTENSION = ".prj";
#endregion // Private constants
#region Private members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private Shapefile _file = null;
private readonly List<DataFieldInfo> _fieldsInfo = new List<DataFieldInfo>();
private DataRow _currentRow = null;
private int _currentRowNum = 0;
#endregion // Private members
}
}
|
namespace SquirrelFramework.Configurations
{
#region using directives
using Microsoft.Extensions.Configuration;
using System;
#endregion using directives
public class Configurations
{
public static string MongoDBConnectionString { get; private set; }
public static string MongoDBDefaultDatabaseName { get; private set; }
public static string Status { get; private set; }
static Configurations()
{
try
{
var builder = new ConfigurationBuilder()
//.SetBasePath(currentDirectory)
.AddJsonFile("mongodb.json", true, true);
Config = builder.Build();
MongoDBConnectionString = GetConfig("MongoDBConnectionString");
MongoDBDefaultDatabaseName = GetConfig("MongoDBDefaultDatabase");
if (!string.IsNullOrWhiteSpace(MongoDBConnectionString))
{
Status = "loaded by json file";
}
else
{
Status = "json file not found";
}
}
catch (Exception ex)
{
Status = ex.Message;
}
}
public static void Configure(string mongoDBConnectionString, string mongoDBDefaultDatabaseName)
{
MongoDBConnectionString = mongoDBConnectionString;
MongoDBDefaultDatabaseName = mongoDBDefaultDatabaseName;
Status = "loaded by runtime configure";
}
// JSON Config Mode
public static IConfigurationRoot Config { get; }
public static string GetConfig(string key)
{
return Config.GetSection(key).Value;
}
public static bool GetBooleanConfig(string key)
{
return bool.Parse(GetConfig(key));
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Iot.Device.BrickPi3.Models
{
/// <summary>
/// All the supported SPI messages
/// </summary>
public enum SpiMessageType : byte
{
None = 0,
GetManufacturer,
GetName,
GetHardwareVersion,
GetFirmwareVersion,
GetId,
SetLed,
GetVoltage3V3,
GetVoltage5V,
GetVoltage9V,
GetVoltageVcc,
SetAddress,
SetSensorType,
GetSensor1,
GetSensor2,
GetSensor3,
GetSensor4,
I2CTransact1,
I2CTransact2,
I2CTransact3,
I2CTransact4,
SetMotorPower,
SetMotorPosition,
SetMotorPositionKP,
SetMotorPositionKD,
setMotorDps,
SetMotorDpsKP,
setMotorDpsKD,
setMotorLimits,
OffsetMotorEncoder,
GetMotorAEncoder,
GetMotorBEncoder,
GetMotorCEncoder,
GetMotorDEncoder,
GetMotorAStatus,
GetMotorBStatus,
GetMotorCStatus,
GetMotorDStatus
};
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using WorldGen.Generator.Data;
using WorldGen.Generator.Interfaces;
using WorldGen.Generator.Interfaces.Data;
namespace WorldGen.Generator.Generators
{
/// <summary>
/// A simple river simulator, places springs and runs rivers to the ocean, aborting if it
/// reaches a local minima in the heightmap.
/// </summary>
/// <typeparam name="TWorld">The type of the world that the generator operates on.</typeparam>
/// <typeparam name="TCell">The type of cells in the world that the generator operates on.</typeparam>
public class SimpleRiverSimulator<TWorld, TCell> : IGenerator<TWorld, TCell>
where TWorld : IHeightWorld<TCell>
where TCell : IHeightCell, IRainfallCell, IRiverCell
{
private const double SPRING_CHANCE_MOD = 0.004;
private const int RIVER_MIN_LENGTH = 3;
/// <summary>
/// The name of the generator, used for logging.
/// </summary>
public string Name
{
get { return "Simple River Simulator"; }
}
/// <summary>
/// Run the generator against a world.
/// </summary>
/// <param name="world">The world to generate against.</param>
public void RunGeneration(TWorld world)
{
var springs = PlaceSprings(world);
foreach (var spring in springs)
{
RunRiver(world, spring);
}
}
private List<CellAddress> PlaceSprings(TWorld world)
{
var rnd = new Random(world.Seed + "springs".GetHashCode());
var springs = new List<CellAddress>();
for (int x = 0; x < world.Width; x++)
{
for (int y = 0; y < world.Height; y++)
{
if (!IsOcean(x, y, world))
{
if (rnd.NextDouble() <= world.GetCell(x, y).Rainfall * SPRING_CHANCE_MOD)
{
springs.Add(new CellAddress(x, y));
}
}
}
}
return springs;
}
private void RunRiver(TWorld world, CellAddress springLocation)
{
var rnd = new Random(world.Seed + "rivers".GetHashCode());
var current = springLocation;
var river = new River();
var previousSegment = (RiverSegment)null;
while (!IsOcean(current.X, current.Y, world))
{
var currentCell = world.GetCell(current.X, current.Y);
if (currentCell.RiverSegmentHere != null)
{
// Now a tributary
if (river.Segments.Count >= RIVER_MIN_LENGTH)
{
currentCell.RiverSegmentHere.PreviousSegments.Add(previousSegment);
previousSegment.NextSegment = currentCell.RiverSegmentHere;
river.TributaryOf = currentCell.RiverSegmentHere.ParentRiver;
//world.AddRiver(river);
AddFlow(currentCell.RiverSegmentHere, 1);
return;
}
//Too short, abort
return;
}
previousSegment = river.AddSegment(current, previousSegment);
current = PickNextLocation(world, current, river, rnd);
if (current == null)
{
//Dead end, abort
return;
}
}
//Add the current location to the end of the river.
river.AddSegment(current, previousSegment);
if (river.Segments.Count < RIVER_MIN_LENGTH)
{
//Too short, abort
return;
}
//Add river to world
//world.AddRiver(river);
}
private void AddFlow(RiverSegment riverSegment, int flow)
{
while (riverSegment != null)
{
riverSegment.Flow += flow;
riverSegment = riverSegment.NextSegment;
}
}
private CellAddress PickNextLocation(TWorld world, CellAddress current, River river, Random rnd)
{
var eligable = new List<CellAddress>();
var oceans = new List<CellAddress>();
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
var n = new CellAddress(i + current.X, j + current.Y);
if ((i == 0 || j == 0) && n != current
&& !river.Segments.Any(x => x.Location == n)
&& world.InRange(n.X, n.Y))
{
eligable.Add(n);
if (world.GetCell(n.X, n.Y).Height < world.SeaLevel)
{
oceans.Add(n);
}
}
}
}
if (oceans.Any())
{
return rnd.PickRandom(oceans);
}
eligable = eligable
.Where(ca => world.GetCell(ca.X, ca.Y).Height <= world.GetCell(current.X, current.Y).Height)
.ToList();
if (eligable.Any(ca => world.GetCell(ca.X, ca.Y).RiverSegmentHere != null))
{
return eligable.First(ca => world.GetCell(ca.X, ca.Y).RiverSegmentHere != null);
}
if (eligable.Any())
{
return rnd.PickRandom(eligable);
}
return null;
}
private bool IsOcean(int x, int y, TWorld world)
{
return world.GetCell(x, y).Height < world.SeaLevel;
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace NuGet.ProjectManagement
{
/// <summary>
/// Enum for the type of NuGetAction
/// </summary>
public enum NuGetActionType
{
/// <summary>
/// Install
/// </summary>
Install,
/// <summary>
/// Uninstall
/// </summary>
Uninstall,
/// <summary>
/// Reinstall
/// </summary>
Reinstall,
/// <summary>
/// Update
/// </summary>
Update,
/// <summary>
/// UpdateAll
/// </summary>
UpdateAll
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.