content stringlengths 23 1.05M |
|---|
using System;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// MybankPaymentTradeNormalpayTransferModel Data Structure.
/// </summary>
[Serializable]
public class MybankPaymentTradeNormalpayTransferModel : AlipayObject
{
/// <summary>
/// 金额,单位:分
/// </summary>
[JsonProperty("amount")]
public string Amount { get; set; }
/// <summary>
/// 外部平台的单据号,网商订单与外部平台订单一一对应
/// </summary>
[JsonProperty("biz_no")]
public string BizNo { get; set; }
/// <summary>
/// 币种
/// </summary>
[JsonProperty("currency_value")]
public string CurrencyValue { get; set; }
/// <summary>
/// 扩展参数,内容是JSON格式,并用urlconde编码,按场景约定具体字段。
/// </summary>
[JsonProperty("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 操作场景类型 CHARGE - 收费
/// </summary>
[JsonProperty("operate_scene_type")]
public string OperateSceneType { get; set; }
/// <summary>
/// 收方资产信息,内容是JSON格式,并用urlencode编码,按场景约定具体字段
/// </summary>
[JsonProperty("payee_fund_detail")]
public string PayeeFundDetail { get; set; }
/// <summary>
/// 付方资产信息,内容是JSON格式,并用urlencode编码,按场景约定具体字段
/// </summary>
[JsonProperty("payer_fund_detail")]
public string PayerFundDetail { get; set; }
/// <summary>
/// 支付备注
/// </summary>
[JsonProperty("remark")]
public string Remark { get; set; }
/// <summary>
/// 请求流水号,表示外部一次请求,幂等字段
/// </summary>
[JsonProperty("request_no")]
public string RequestNo { get; set; }
/// <summary>
/// 请求时间,格式是yyyyMMddHHmmss
/// </summary>
[JsonProperty("request_time")]
public string RequestTime { get; set; }
}
}
|
using Framework;
namespace SuperSport
{
public class TitleContextContainer : SystemContextContainer
{
public int SelectRace {
get;
}
public TitleContextContainer(int selectRace)
{
SelectRace = selectRace;
}
}
} |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FoodSourceLogic : MonoBehaviour
{
private IngameSceneLogicScript ingameLogicScript = null;
public float ResourceCount = 5000.0f;
public float MaxResourceCount = 5000.0f;
public TextMesh ResourceUnitsText;
public UnitLogic[] influencingUnits;
public float tapRatePerSec = 25.0f;
public GameObject foodParticleSystem;
void Start()
{
GameObject ingameLogic = GameObject.Find("IngameLogic");
if (ingameLogic == null)
{
return;
}
ingameLogicScript = ingameLogic.GetComponent<IngameSceneLogicScript>();
}
void Update()
{
bool didReduceResources = false;
if (ResourceUnitsText != null)
{
int flatResourceCount = (int)ResourceCount;
ResourceUnitsText.text = flatResourceCount.ToString();
ResourceUnitsText.transform.rotation = Camera.main.transform.rotation;
}
if(influencingUnits.Length == 0 || ResourceCount <= 0.0f)
{
if (!didReduceResources && foodParticleSystem.activeSelf)
{
foodParticleSystem.SetActive(false);
}
return;
}
float deltaTime = Time.deltaTime;
float tapRateThisFrame = tapRatePerSec * deltaTime;
if(ResourceCount - tapRateThisFrame < 0.0f)
{
tapRateThisFrame = ResourceCount;
}
float tappedValue = (tapRateThisFrame) / influencingUnits.Length;
foreach(UnitLogic unit in influencingUnits)
{
tappedValue *= ingameLogicScript.GetTeamFoodCollectFactor(unit.TeamNumber);
BreederLogic breederLogic = unit.gameObject.GetComponent<BreederLogic>();
DroneLogic droneLogic = unit.GetComponent<DroneLogic>();
float maxFoodResourceCount = 0;
if (breederLogic != null)
{
maxFoodResourceCount = ingameLogicScript.GetBreederMaxFoodResource(unit.TeamNumber);
}
else if (droneLogic != null)
{
maxFoodResourceCount = ingameLogicScript.GetDroneMaxFoodResource(unit.TeamNumber);
}
if (unit.FoodResourceCount < maxFoodResourceCount)
{
float newFoodValue = tappedValue;
if (unit.FoodResourceCount + newFoodValue > maxFoodResourceCount)
{
newFoodValue = maxFoodResourceCount - unit.FoodResourceCount;
}
unit.FoodResourceCount += newFoodValue;
if(unit.FoodResourceCount > maxFoodResourceCount)
{
unit.FoodResourceCount = maxFoodResourceCount;
}
ResourceCount -= newFoodValue;
didReduceResources = true;
}
}
if (didReduceResources && !foodParticleSystem.activeSelf)
{
foodParticleSystem.SetActive(true);
}
else if (!didReduceResources && foodParticleSystem.activeSelf)
{
foodParticleSystem.SetActive(false);
}
}
void OnTriggerEnter(Collider other)
{
UnitLogic unitLogicScript = other.gameObject.GetComponent<UnitLogic>();
if(unitLogicScript != null)
{
List<UnitLogic> listOfUnitsInfluencing = new List<UnitLogic>();
foreach(UnitLogic unit in influencingUnits)
{
listOfUnitsInfluencing.Add(unit);
}
if (!listOfUnitsInfluencing.Contains(unitLogicScript))
{
listOfUnitsInfluencing.Add(unitLogicScript);
}
influencingUnits = listOfUnitsInfluencing.ToArray();
}
}
void OnTriggerExit(Collider other)
{
UnitLogic unitLogicScript = other.gameObject.GetComponent<UnitLogic>();
if (unitLogicScript != null)
{
List<UnitLogic> listOfUnitsInfluencing = new List<UnitLogic>();
foreach (UnitLogic unit in influencingUnits)
{
if(unitLogicScript == unit)
{
continue;
}
listOfUnitsInfluencing.Add(unit);
}
influencingUnits = listOfUnitsInfluencing.ToArray();
}
}
}
|
using ESFA.DC.ILR.Model.Interface;
namespace ESFA.DC.ILR.Tests.Model
{
public class TestLearningDeliveryHE : ILearningDeliveryHE
{
public string NUMHUS { get; set; }
public string SSN { get; set; }
public string QUALENT3 { get; set; }
public int? SOC2000Nullable { get; set; }
public int? SECNullable { get; set; }
public string UCASAPPID { get; set; }
public int TYPEYR { get; set; }
public int MODESTUD { get; set; }
public int FUNDLEV { get; set; }
public int FUNDCOMP { get; set; }
public decimal? STULOADNullable { get; set; }
public int YEARSTU { get; set; }
public int MSTUFEE { get; set; }
public decimal? PCOLABNullable { get; set; }
public decimal? PCFLDCSNullable { get; set; }
public decimal? PCSLDCSNullable { get; set; }
public decimal? PCTLDCSNullable { get; set; }
public int SPECFEE { get; set; }
public int? NETFEENullable { get; set; }
public int? GROSSFEENullable { get; set; }
public string DOMICILE { get; set; }
public int? ELQNullable { get; set; }
public string HEPostCode { get; set; }
}
}
|
namespace OverridingConventions
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Video
{
public Video()
{
Tags = new HashSet<Tag>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
public int? Genre_Id { get; set; }
public byte Classification { get; set; }
public virtual Genre Genre { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
}
|
using System.Collections.Generic;
using System.Data;
namespace DatabaseSchemaReader.SqlGen.SqLite
{
class SqLiteDataTypeMapper : DataTypeMapper
{
private readonly IDictionary<DbType, string> _mapping = new Dictionary<DbType, string>();
public SqLiteDataTypeMapper()
{
Init();
}
private void Init()
{
_mapping.Add(DbType.AnsiStringFixedLength, "TEXT");
_mapping.Add(DbType.AnsiString, "TEXT");
_mapping.Add(DbType.Binary, "BLOB");
_mapping.Add(DbType.Boolean, "NUMERIC(1)");
_mapping.Add(DbType.Byte, "NUMERIC(1)");
_mapping.Add(DbType.Currency, "NUMERIC(15,4)");
_mapping.Add(DbType.Date, "DATETIME");
_mapping.Add(DbType.DateTime, "DATETIME");
_mapping.Add(DbType.DateTime2, "DATETIME");
_mapping.Add(DbType.DateTimeOffset, "DATETIME");
_mapping.Add(DbType.Decimal, "NUMERIC");
_mapping.Add(DbType.Double, "NUMERIC");
_mapping.Add(DbType.Guid, "TEXT");
_mapping.Add(DbType.Int16, "INTEGER");
_mapping.Add(DbType.Int32, "INTEGER");
_mapping.Add(DbType.Int64, "INTEGER");
_mapping.Add(DbType.Single, "NUMERIC");
_mapping.Add(DbType.StringFixedLength, "TEXT");
_mapping.Add(DbType.String, "TEXT");
_mapping.Add(DbType.Time, "DATETIME");
_mapping.Add(DbType.Xml, "TEXT");
}
public override string Map(DbType dbType)
{
if (_mapping.ContainsKey(dbType))
return _mapping[dbType];
return null;
}
}
}
|
using Newtonsoft.Json;
namespace Sora.Entities.MessageElement.CQModel
{
/// <summary>
/// 图片
/// </summary>
public struct Image
{
#region 属性
/// <summary>
/// 文件名/绝对路径/URL/base64
/// </summary>
[JsonProperty(PropertyName = "file")]
public string ImgFile { get; internal set; }
/// <summary>
/// 图片类型
/// </summary>
[JsonProperty(PropertyName = "type", NullValueHandling = NullValueHandling.Ignore)]
public string ImgType { get; internal set; }
/// <summary>
/// 图片链接
/// </summary>
[JsonProperty(PropertyName = "url", NullValueHandling = NullValueHandling.Ignore)]
public string Url { get; internal set; }
/// <summary>
/// 只在通过网络 URL 发送时有效,表示是否使用已缓存的文件
/// </summary>
[JsonProperty(PropertyName = "cache", NullValueHandling = NullValueHandling.Ignore)]
public int? UseCache { get; internal set; }
/// <summary>
/// 通过网络下载图片时的线程数,默认单线程。
/// </summary>
[JsonProperty(PropertyName = "c", NullValueHandling = NullValueHandling.Ignore)]
public int? ThreadCount { get; internal set; }
/// <summary>
/// 发送秀图时的特效id,默认为40000
/// </summary>
[JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)]
public int? Id { get; internal set; }
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace VALR.Net.Objects
{
public class VALRSimpleBuySellOrderStatus
{
public string OrderId { get; set; } //"9fed72b4-5d59-4bd7-b4fc-26cf43d27c94"
public string Success { get; set; } //true
public string Processing { get; set; } //false
public string PaidAmount { get; set; } //"0.0008"
public string PaidCurrency { get; set; } //"BTC"
public string ReceivedAmount { get; set; } //"54.49553877"
public string ReceivedCurrency { get; set; } //"ADA"
public string FeeAmount { get; set; } //"0.000006"
public string FeeCurrency { get; set; } //"BTC"
public string OrderExecutedAt { get; set; } //"2019-04-20T13:57:56.618"
}
}
|
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
public class SetQuality : UdonSharpBehaviour
{
public CustomRenderTexture buffer;
public MeshRenderer[] screens;
public override void Interact()
{
foreach (MeshRenderer screen in screens)
{
CustomRenderTexture rt = (CustomRenderTexture)screen.material.GetTexture("_MainTex");
rt.updateMode = CustomRenderTextureUpdateMode.OnDemand;
buffer.updateMode = CustomRenderTextureUpdateMode.Realtime;
screen.material.SetTexture("_MainTex", buffer);
}
}
}
|
/* MBC, the number one terrestrial broadcast station in Korea (Republic of) ***
*
* History
* ----------------------------------------------------------------------------
* 2014.06.24, JeeBum Koh, Initial release
*
*
******************************************************************************/
namespace MBC.Adobe.PhotoShop.Connection
{
/// <summary>
/// collection of photoshop constants
/// </summary>
public static class PhotoShopConstants
{
/// <summary>
/// salt value used in PBKDF2 key generation.
/// this must match the value used in Photoshop, DO NOT CHANGE
/// </summary>
public const string SALT = "Adobe Photoshop";
/// <summary>
/// iteration count value used in PBKDF2 key generation.
/// this must match the value used in Photoshop, DO NOT CHANGE
/// </summary>
public const int ITERATION_COUNT = 1000;
/// <summary>
/// key length(bytes) value used in PBKDF2 key generation.
/// this must match the value used in Photoshop, DO NOT CHANGE
/// </summary>
public const int KEY_LENGTH = 24;
/// <summary>
/// Communication Status Def, NON-Error = 0, otherwise error.
/// </summary>
public const int NO_COMM_ERROR = 0;
/// <summary>
/// current protocol version
/// </summary>
public const int PROTOCOL_VERSION = 1;
/// <summary>
/// length of the header not including
/// the actual length byte or the communication status
/// </summary>
public const int PROTOCOL_LENGTH = 4 + 4 + 4;
/// <summary>
/// length of communication status field
/// </summary>
public const int COMM_LENGTH = 4;
/// <summary>
/// predefined communication port for PhotoShop communication
/// </summary>
public const int COMMUNICATION_PORT = 49494;
}
/// <summary>
/// collection of constants used in this library
/// </summary>
public static class Constants
{
/// <summary>
/// default local port for constructing SOCKET.
/// </summary>
public const int LOCAL_PORT_DEFAULT = 59595;
/// <summary>
/// default image width for PS communication
/// </summary>
public const int IMG_WIDTH = 1920;
/// <summary>
/// default image height for PS communication
/// </summary>
public const int IMG_HEIGHT = 1080;
/// <summary>
/// we're planning to use initial transaction id like this.
/// </summary>
public const int INITIAL_TRANSACTION_ID = 100;
}
}
|
using System;
using System.Data.SqlClient;
namespace BKTMManager.Types {
public class Reseller : TypeRepo {
public Reseller() { }
public Reseller(SqlDataReader reader) {
_id = reader.GetInt32(reader.GetOrdinal("re_id"));
_location = reader.GetString(reader.GetOrdinal("location"));
_name = reader.GetString(reader.GetOrdinal("reName"));
tableNormal = String.Format("ID: {0} ; LOC: {1} ; NAME: {2}", _id, _location, _name);
}
private int _id;
public int id {
get { return _id; }
set { _id = value; }
}
private string _location;
public string location {
get { return _location; }
set { _location = value; }
}
private string _name;
public string name {
get { return _name; }
set { _name = value; }
}
}
}
|
using System;
using UnityEngine;
using System.Collections.Generic;
public class AnimationUtil
{
public static string ExtractPropertyName (string un)
{
switch (un) {
case "m_LocalPosition.x":
return "px";
case "m_LocalPosition.y":
return "py";
case "m_LocalPosition.z":
return "pz";
case "m_LocalEulerAnglesHint.x":
return "rx";
case "m_LocalEulerAnglesHint.y":
return "ry";
case "m_LocalEulerAnglesHint.z":
return "rz";
case "m_LocalRotation.x":
return "rx";
case "m_LocalRotation.y":
return "ry";
case "m_LocalRotation.z":
return "rz";
case "m_LocalRotation.w":
return "rw";
default:
return un;
}
}
public static bool CheckForEulerHint(string un) {
return un.IndexOf("m_LocalEulerAnglesHint") == -1;
}
public static Vector3 adaptPosition(Vector3 p) {
p.z = -p.z;
return p;
}
}
|
// Copyright (c) 2013-2021 Jean-Philippe Bruyère <jp_bruyere@hotmail.com>
//
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
using System;
using System.Diagnostics;
namespace Crow.Text
{
[DebuggerDisplay ("{Line}, {Column}, {VisualCharXPosition}")]
public struct CharLocation : IEquatable<CharLocation>
{
public readonly int Line;
/// <summary>
/// Character position in current line. If equals '-1', the visualX must contains the on screen position.
///
/// </summary>
public int Column;
public double VisualCharXPosition;
public CharLocation (int line, int column, double visualX = -1) {
Line = line;
Column = column;
VisualCharXPosition = visualX;
}
public bool HasVisualX => Column >= 0 && VisualCharXPosition >= 0;
public void ResetVisualX () => VisualCharXPosition = -1;
public static bool operator == (CharLocation a, CharLocation b)
=> a.Equals (b);
public static bool operator != (CharLocation a, CharLocation b)
=> !a.Equals (b);
public bool Equals (CharLocation other) {
return Column < 0 ?
Line == other.Line && VisualCharXPosition == other.VisualCharXPosition :
Line == other.Line && Column == other.Column;
}
public override bool Equals (object obj) => obj is CharLocation loc ? Equals (loc) : false;
public override int GetHashCode () {
return Column < 0 ?
HashCode.Combine (Line, VisualCharXPosition) :
HashCode.Combine (Line, Column);
}
public override string ToString () => $"{Line}, {Column}";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace Detached.RuntimeTypes.Expressions
{
public class IncludeExpression : ExtendedExpression
{
public IncludeExpression(IEnumerable<Expression> expression)
{
Expressions = expression;
}
public IEnumerable<Expression> Expressions { get; }
public override Expression Reduce()
{
throw new InvalidOperationException($"Include can't be added outside of a Block.");
}
}
} |
//-----------------------------------------------------------------------------
// Implementation of the Singleton design pattern with templates.
//
// __Defense Sample for Game Programming Algorithms and Techniques
// Copyright (C) Sanjay Madhav. All rights reserved.
//
// Released under the Microsoft Permissive License.
// See LICENSE.txt for full details.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace itp380.Patterns
{
public class Singleton<T> where T : new()
{
private static T m_Instance;
public static T Get()
{
if (m_Instance == null)
{
m_Instance = new T();
return m_Instance;
}
else
{
return m_Instance;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace KellermanSoftware.CompareNetObjects.TypeComparers
{
/// <summary>
/// Compare two properties (Note: inherits from BaseComparer instead of TypeComparer).
/// </summary>
public class PropertyComparer : BaseComparer
{
private readonly RootComparer _rootComparer;
private readonly IndexerComparer _indexerComparer;
private static readonly string[] _baseList = { "Count", "Capacity", "Item" };
/// <summary>
/// Constructor that takes a root comparer
/// </summary>
/// <param name="rootComparer"></param>
public PropertyComparer(RootComparer rootComparer)
{
_rootComparer = rootComparer;
_indexerComparer = new IndexerComparer(rootComparer);
}
/// <summary>
/// Compare the properties of a class
/// </summary>
public void PerformCompareProperties(CompareParms parms, bool ignoreBaseList= false)
{
List<PropertyEntity> object1Properties = GetCurrentProperties(parms, parms.Object1, parms.Object1Type);
List<PropertyEntity> object2Properties = GetCurrentProperties(parms, parms.Object2, parms.Object2Type);
foreach (PropertyEntity propertyEntity in object1Properties)
{
if (ignoreBaseList && _baseList.Contains(propertyEntity.Name))
continue;
CompareProperty(parms, propertyEntity, object2Properties);
if (parms.Result.ExceededDifferences)
return;
}
}
/// <summary>
/// Compare a single property of a class
/// </summary>
/// <param name="parms"></param>
/// <param name="info"></param>
/// <param name="object2Properties"></param>
private void CompareProperty(CompareParms parms, PropertyEntity info, List<PropertyEntity> object2Properties)
{
//If we can't read it, skip it
if (info.CanRead == false)
return;
//Skip if this is a shallow compare
if (!parms.Config.CompareChildren && TypeHelper.CanHaveChildren(info.PropertyType))
return;
//Skip if it should be excluded based on the configuration
if (info.PropertyInfo != null && ExcludeLogic.ShouldExcludeMember(parms.Config, info.PropertyInfo, info.DeclaringType))
return;
//This is a dynamic property to be excluded on an expando object
if (info.IsDynamic && ExcludeLogic.ShouldExcludeDynamicMember(parms.Config, info.Name, info.DeclaringType))
return;
//If we should ignore read only, skip it
if (!parms.Config.CompareReadOnly && info.CanWrite == false)
return;
//If we ignore types then we must get correct PropertyInfo object
PropertyEntity secondObjectInfo = GetSecondObjectInfo(info, object2Properties);
//If the property does not exist, and we are ignoring the object types, skip it - unless we have set IgnoreMissingProperties = true
if ((parms.Config.IgnoreObjectTypes || parms.Config.IgnoreConcreteTypes) && secondObjectInfo == null && parms.Config.IgnoreMissingProperties)
return;
//Check if we have custom function to validate property
BaseTypeComparer customComparer = null;
if (info.PropertyInfo != null)
customComparer = CustomValidationLogic.CustomValidatorForMember(parms.Config, info.PropertyInfo, info.DeclaringType)
?? CustomValidationLogic.CustomValidatorForDynamicMember(parms.Config, info.Name, info.DeclaringType);
object objectValue1;
object objectValue2;
if (!IsValidIndexer(parms.Config, info, parms.BreadCrumb))
{
objectValue1 = info.Value;
objectValue2 = secondObjectInfo != null ? secondObjectInfo.Value : null;
}
else
{
_indexerComparer.CompareIndexer(parms, info, secondObjectInfo);
return;
}
bool object1IsParent = objectValue1 != null && (objectValue1 == parms.Object1 || parms.Result.IsParent(objectValue1));
bool object2IsParent = objectValue2 != null && (objectValue2 == parms.Object2 || parms.Result.IsParent(objectValue2));
//Skip properties where both point to the corresponding parent
if ((TypeHelper.IsClass(info.PropertyType) || TypeHelper.IsInterface(info.PropertyType) || TypeHelper.IsStruct(info.PropertyType))
&& (object1IsParent && object2IsParent))
{
return;
}
string currentBreadCrumb = AddBreadCrumb(parms.Config, parms.BreadCrumb, info.Name);
CompareParms childParms = new CompareParms
{
Result = parms.Result,
Config = parms.Config,
ParentObject1 = parms.Object1,
ParentObject2 = parms.Object2,
Object1 = objectValue1,
Object2 = objectValue2,
BreadCrumb = currentBreadCrumb,
CustomPropertyComparer = customComparer,
Object1DeclaredType = info?.PropertyType,
Object2DeclaredType = secondObjectInfo?.PropertyType
};
_rootComparer.Compare(childParms);
}
private static PropertyEntity GetSecondObjectInfo(PropertyEntity info, List<PropertyEntity> object2Properties)
{
foreach (var object2Property in object2Properties)
{
if (info.Name == object2Property.Name)
return object2Property;
}
return null;
}
private static List<PropertyEntity> GetCurrentProperties(CompareParms parms, object objectValue, Type objectType)
{
return HandleDynamicObject(objectValue, objectType)
?? HandleInterfaceMembers(parms, objectValue, objectType)
?? HandleNormalProperties(parms, objectValue, objectType);
}
private static List<PropertyEntity> HandleNormalProperties(CompareParms parms, object objectValue, Type objectType)
{
IEnumerable<PropertyInfo> properties = Cache.GetPropertyInfo(parms.Result.Config, objectType);
return AddPropertyInfos(parms, objectValue, objectType, properties);
}
private static List<PropertyEntity> AddPropertyInfos(CompareParms parms,
object objectValue,
Type objectType,
IEnumerable<PropertyInfo> properties)
{
List<PropertyEntity> currentProperties = new List<PropertyEntity>();
foreach (var property in properties)
{
if (ExcludeLogic.ShouldExcludeMember(parms.Config, property, objectType))
continue;
PropertyEntity propertyEntity = new PropertyEntity();
propertyEntity.IsDynamic = false;
propertyEntity.Name = property.Name;
propertyEntity.CanRead = property.CanRead;
propertyEntity.CanWrite = property.CanWrite;
propertyEntity.PropertyType = property.PropertyType;
#if !NETSTANDARD
propertyEntity.ReflectedType = property.ReflectedType;
#endif
propertyEntity.Indexers.AddRange(property.GetIndexParameters());
propertyEntity.DeclaringType = objectType;
if (propertyEntity.CanRead && (propertyEntity.Indexers.Count == 0))
{
try
{
propertyEntity.Value = property.GetValue(objectValue, null);
}
catch (System.Reflection.TargetInvocationException)
{
}
catch (System.NotSupportedException)
{
}
}
propertyEntity.PropertyInfo = property;
currentProperties.Add(propertyEntity);
}
return currentProperties;
}
private static List<PropertyEntity> HandleInterfaceMembers(CompareParms parms, object objectValue, Type objectType)
{
List<PropertyEntity> currentProperties = new List<PropertyEntity>();
if (parms.Config.InterfaceMembers.Count > 0)
{
Type[] interfaces = objectType.GetInterfaces();
foreach (var type in parms.Config.InterfaceMembers)
{
if (interfaces.Contains(type))
{
var properties = Cache.GetPropertyInfo(parms.Result.Config, type);
foreach (var property in properties)
{
PropertyEntity propertyEntity = new PropertyEntity();
propertyEntity.IsDynamic = false;
propertyEntity.Name = property.Name;
propertyEntity.CanRead = property.CanRead;
propertyEntity.CanWrite = property.CanWrite;
propertyEntity.PropertyType = property.PropertyType;
propertyEntity.Indexers.AddRange(property.GetIndexParameters());
propertyEntity.DeclaringType = objectType;
if (propertyEntity.Indexers.Count == 0)
{
propertyEntity.Value = property.GetValue(objectValue, null);
}
propertyEntity.PropertyInfo = property;
currentProperties.Add(propertyEntity);
}
}
}
}
if (currentProperties.Count == 0)
return null;
return currentProperties;
}
private static List<PropertyEntity> HandleDynamicObject(object objectValue, Type objectType)
{
if (TypeHelper.IsExpandoObject(objectValue))
{
return AddExpandoPropertyValues(objectValue, objectType);
}
return null;
}
private static List<PropertyEntity> AddExpandoPropertyValues(Object objectValue, Type objectType)
{
IDictionary<string, object> expandoPropertyValues = objectValue as IDictionary<string, object>;
if (expandoPropertyValues == null)
return new List<PropertyEntity>();
List<PropertyEntity> currentProperties = new List<PropertyEntity>();
foreach (var propertyValue in expandoPropertyValues)
{
PropertyEntity propertyEntity = new PropertyEntity();
propertyEntity.IsDynamic = true;
propertyEntity.Name = propertyValue.Key;
propertyEntity.Value = propertyValue.Value;
propertyEntity.CanRead = true;
propertyEntity.CanWrite = true;
propertyEntity.DeclaringType = objectType;
if (propertyValue.Value == null)
{
propertyEntity.PropertyType = null;
propertyEntity.ReflectedType = null;
}
else
{
propertyEntity.PropertyType = propertyValue.GetType();
propertyEntity.ReflectedType = propertyEntity.PropertyType;
}
currentProperties.Add(propertyEntity);
}
return currentProperties;
}
private bool IsValidIndexer(ComparisonConfig config, PropertyEntity info, string breadCrumb)
{
if (info.Indexers.Count == 0)
{
return false;
}
if (info.Indexers.Count > 1)
{
if (config.SkipInvalidIndexers)
return false;
throw new Exception("Cannot compare objects with more than one indexer for object " + breadCrumb);
}
if (info.Indexers[0].ParameterType != typeof(Int32))
{
if (config.SkipInvalidIndexers)
return false;
throw new Exception("Cannot compare objects with a non integer indexer for object " + breadCrumb);
}
#if !NETSTANDARD
var type = info.ReflectedType;
#else
var type = info.DeclaringType;
#endif
if (type == null)
{
if (config.SkipInvalidIndexers)
return false;
throw new Exception("Cannot compare objects with a null indexer for object " + breadCrumb);
}
if (type.GetProperty("Count") == null
|| type.GetProperty("Count").PropertyType != typeof(Int32))
{
if (config.SkipInvalidIndexers)
return false;
throw new Exception("Indexer must have a corresponding Count property that is an integer for object " + breadCrumb);
}
return true;
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Riven.Extensions;
namespace Riven.Localization
{
public class DefaultRequestCultureProvider : RequestCultureProvider
{
public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
var cultureManager = httpContext.RequestServices.GetService<ICultureAccessor>();
return await cultureManager.GetDefaultRequestCulture(httpContext);
}
}
}
|
using Xunit;
using Shouldly;
namespace Laconic.CodeGeneration.Tests
{
public class Signal
{
public readonly object? Payload;
readonly object? _p1;
readonly object? _p2;
public Signal(object? payload) => (Payload, _p1, _p2) = (payload, payload, null);
public Signal(object p1, object? p2) => (Payload, _p1, _p2) = (p1, p1, p2);
public void Deconstruct(out object? p1, out object? p2) => (p1, p2) = (_p1, _p2);
public override string ToString() => $"{GetType()}: {_p1?.ToString()} {_p2?.ToString()}";
}
public class Signal<T> : Signal
{
public Signal(T payload) : base(payload)
{
}
public new T Payload => (T) base.Payload!;
}
[Signals]
interface __MySignal
{
Signal NoPayload();
Signal WithOneParam(string id);
Signal WithTwoParams(int id, string name);
Signal WithThreeParams(int id, string first, string second);
}
public class SignalTests
{
[Fact]
public void Signal_generation_works()
{
var noPayload = new NoPayload();
noPayload.ShouldBeAssignableTo<Signal>();
noPayload.ShouldBeAssignableTo<MySignal>();
noPayload.Payload.ShouldBeNull();
var twoParams = new WithTwoParams(1, "one");
twoParams.Id.ShouldBe(1);
twoParams.Name.ShouldBe("one");
var (id, name) = twoParams;
id.ShouldBe(1);
name.ShouldBe("one");
var threeParams = new WithThreeParams(1, "one", "two");
threeParams.Id.ShouldBe(1);
threeParams.First.ShouldBe("one");
threeParams.Second.ShouldBe("two");
}
}
} |
using AspectInjector.Broker;
using AspectInjector.Core.Contracts;
using AspectInjector.Core.Extensions;
using AspectInjector.Core.Models;
using AspectInjector.Rules;
using FluentIL.Logging;
using Mono.Cecil;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace AspectInjector.Core.Services
{
public class AspectReader : IAspectReader
{
private static readonly ConcurrentDictionary<TypeDefinition, AspectDefinition> _cache = new ConcurrentDictionary<TypeDefinition, AspectDefinition>();
private readonly IEnumerable<IEffectReader> _effectExtractors;
private readonly ILogger _log;
public AspectReader(IEnumerable<IEffectReader> effectExtractors, ILogger logger)
{
_effectExtractors = effectExtractors;
_log = logger;
}
public IReadOnlyCollection<AspectDefinition> ReadAll(AssemblyDefinition assembly)
{
return assembly.Modules.SelectMany(m => m.GetTypes().Select(Read).Where(a => a != null)).Where(a => a.Validate(_log)).ToList();
}
public AspectDefinition Read(TypeDefinition type)
{
if (!_cache.TryGetValue(type, out var aspectDef))
{
var effects = ExtractEffects(type).ToList();
var aspect = ExtractAspectAttribute(type);
if (aspect != null)
aspectDef = new AspectDefinition
{
Host = type,
Scope = aspect.GetConstructorValue<Scope>(0),
Factory = aspect.GetPropertyValue<TypeReference>(nameof(Aspect.Factory)),
Effects = effects
};
else if (effects.Any())
_log.Log(EffectRules.EffectMustBePartOfAspect, type, type.Name);
_cache.AddOrUpdate(type, aspectDef, (k, o) => aspectDef);
}
return aspectDef;
}
private CustomAttribute ExtractAspectAttribute(TypeDefinition type)
{
var aspectUsage = type.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.FullName == WellKnownTypes.Aspect);
return aspectUsage;
}
private IEnumerable<Effect> ExtractEffects(TypeDefinition type)
{
var effects = Enumerable.Empty<Effect>();
effects = effects.Concat(ExtractEffectsFromProvider(type));
effects = effects.Concat(type.Methods.SelectMany(ExtractEffectsFromProvider));
return effects;
}
private List<Effect> ExtractEffectsFromProvider(ICustomAttributeProvider host)
{
var effects = new List<Effect>();
foreach (var extractor in _effectExtractors)
effects.AddRange(extractor.Read(host));
return effects;
}
}
} |
using System;
using System.Runtime.InteropServices;
using System.Threading;
using HardDev.Context;
namespace HardDev.Awaiter
{
[StructLayout(LayoutKind.Auto)]
public struct ThreadContextAwaiter : IAwaiter
{
public IAwaiter GetAwaiter() => this;
public bool IsCompleted => _context.Context == SynchronizationContext.Current;
private readonly ThreadContext _context;
public ThreadContextAwaiter(ThreadContext context)
{
_context = context;
}
public void OnCompleted(Action action)
{
_context.Post(action);
}
public void GetResult()
{
}
}
} |
namespace Merchain.Web.ViewModels.PromoCodes
{
using System;
using System.ComponentModel.DataAnnotations;
public class PromoCodesGenerateViewModel
{
[Range(1, 1000000)]
[Required]
[Display(Name = "Брой")]
public int Count { get; set; }
[Display(Name = "% Отстъпка")]
[Range(1, 99)]
[Required]
public int PercentageDiscount { get; set; }
[Display(Name = "Валиден До:")]
[Required]
public DateTime ValidUntil
{
get => DateTime.UtcNow.ToLocalTime().AddDays(1);
set { this.ValidUntil = value; }
}
}
}
|
namespace MvcTurbine.Web.Blades {
using System.Web.Mvc;
using MvcTurbine.Blades;
/// <summary>
/// Blade for handling the registration of <see cref="IDependencyResolver"/>.
/// </summary>
public class DependencyResolverBlade : CoreBlade {
public override void Spin(IRotorContext context) {
var dependencyResolver = GetDependencyResolver(context);
DependencyResolver.SetResolver(dependencyResolver);
}
/// <summary>
/// Gets the registered <see cref="IDependencyResolver"/> that's configured with the system.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
protected virtual IDependencyResolver GetDependencyResolver(IRotorContext context) {
var serviceLocator = context.ServiceLocator;
try {
return serviceLocator.Resolve<IDependencyResolver>();
} catch {
return new TurbineDependencyResolver(serviceLocator);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HudSwitch : MonoBehaviour
{
public GameObject[] ui;
bool active = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void ShowUI()
{
foreach(GameObject window in ui)
{
window.GetComponent<ShowHideUI>().OnMouseOverUI();
}
}
public void HideUI()
{
foreach (GameObject window in ui)
{
window.GetComponent<ShowHideUI>().OnMouseExitUI();
}
}
public void DisableUI()
{
active = !active;
foreach (GameObject window in ui)
{
if(active)
window.SetActive(false);
else
window.SetActive(true);
}
}
public void EnableUI()
{
foreach (GameObject window in ui)
{
window.SetActive(true);
}
}
}
|
using Xunit;
namespace HotChocolate.Types.Pagination
{
public class ConnectionPageInfoTests
{
[InlineData(true, true, "a", "b", null)]
[InlineData(true, false, "a", "b", null)]
[InlineData(false, true, "a", "b", null)]
[InlineData(true, true, null, "b", null)]
[InlineData(true, true, "a", null, null)]
[InlineData(true, true, "a", "b", 1)]
[InlineData(true, false, "a", "b", 2)]
[InlineData(false, true, "a", "b", 3)]
[InlineData(true, true, null, "b", 4)]
[InlineData(true, true, "a", null, 5)]
[Theory]
public void CreatePageInfo_ArgumentsArePassedCorrectly(
bool hasNextPage, bool hasPreviousPage,
string startCursor, string endCursor,
int? totalCount)
{
// arrange
// act
var pageInfo = new ConnectionPageInfo(
hasNextPage, hasPreviousPage,
startCursor, endCursor,
totalCount);
// assert
Assert.Equal(hasNextPage, pageInfo.HasNextPage);
Assert.Equal(hasPreviousPage, pageInfo.HasPreviousPage);
Assert.Equal(startCursor, pageInfo.StartCursor);
Assert.Equal(endCursor, pageInfo.EndCursor);
Assert.Equal(totalCount, pageInfo.TotalCount);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Xen2D;
using Microsoft.Xna.Framework.Graphics;
namespace Xen2D_UnitTests
{
internal static class MockGraphics
{
static InjectableDummyGame _mockGame = new InjectableDummyGame();
public static GraphicsDeviceManager Graphics
{
get { return _mockGame.graphics; }
}
public static GraphicsDevice GraphicsDevice
{
get { return _mockGame.graphics.GraphicsDevice; }
}
public static ContentManager Content
{
get { return _mockGame.Content; }
}
}
}
|
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Auth0WebApp {
public class LoggingOpenIdConnectEvents : OpenIdConnectEvents {
private ILogger _logger;
private ILogger GetLogger<TOptions>(BaseContext<TOptions> context) where TOptions : AuthenticationSchemeOptions {
if (_logger == null) {
_logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<LoggingOpenIdConnectEvents>>();
}
return _logger;
}
// Invoked when an access denied error was returned by the remote server.
public override Task AccessDenied(AccessDeniedContext context) {
GetLogger(context).LogCallerMethodName();
return base.AccessDenied(context);
}
// Invoked when there is a remote failure.
public override Task RemoteFailure(RemoteFailureContext context) {
GetLogger(context).LogCallerMethodName();
return base.RemoteFailure(context);
}
// Invoked after the remote ticket has been received.
public override Task TicketReceived(TicketReceivedContext context) {
GetLogger(context).LogCallerMethodName();
return base.TicketReceived(context);
}
public override Task AuthenticationFailed(AuthenticationFailedContext context) {
GetLogger(context).LogCallerMethodName();
return base.AuthenticationFailed(context);
}
public override Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context) {
GetLogger(context).LogCallerMethodName();
return base.AuthorizationCodeReceived(context);
}
public override Task MessageReceived(MessageReceivedContext context) {
GetLogger(context).LogCallerMethodName();
return base.MessageReceived(context);
}
public override Task RedirectToIdentityProvider(RedirectContext context) {
GetLogger(context).LogCallerMethodName();
return base.RedirectToIdentityProvider(context);
}
public override Task RedirectToIdentityProviderForSignOut(RedirectContext context) {
GetLogger(context).LogCallerMethodName();
return base.RedirectToIdentityProviderForSignOut(context);
}
public override Task RemoteSignOut(RemoteSignOutContext context) {
GetLogger(context).LogCallerMethodName();
return base.RemoteSignOut(context);
}
public override Task SignedOutCallbackRedirect(RemoteSignOutContext context) {
GetLogger(context).LogCallerMethodName();
return base.SignedOutCallbackRedirect(context);
}
public override Task TokenResponseReceived(TokenResponseReceivedContext context) {
GetLogger(context).LogCallerMethodName();
return base.TokenResponseReceived(context);
}
public override Task TokenValidated(TokenValidatedContext context) {
GetLogger(context).LogCallerMethodName();
return base.TokenValidated(context);
}
public override Task UserInformationReceived(UserInformationReceivedContext context) {
GetLogger(context).LogCallerMethodName();
return base.UserInformationReceived(context);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using TressFXLib.Numerics;
namespace TressFXLib.Formats
{
/// <summary>
/// Ascii scene exporter file format implementation.
/// This file format can only get imported, not exported.
///
/// Important Note:
/// The ASE File Format does not specify hairsimulation parameters,
/// so after importing the ase data the simulation parameters must get prepared manually in order to do a correct import!
///
/// TODO: Re-implement! (ATM just Quick'n'Dirty code)
/// </summary>
public class AseFormat : IHairFormat
{
public void Export(BinaryWriter writer, string path, Hair hair)
{
throw new NotImplementedException("Hair cannot get exported as ASE file");
}
public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
{
reader.Close();
// Initialize the import
// Load the ase file content
// Create a List for all meshes
// Create a list for the current-mesh strands
string[] aseContent = File.ReadAllLines(path);
List<HairMesh> hairMeshes = new List<HairMesh>();
List<HairStrand> currentStrands = new List<HairStrand>();
// Init "state"-variables
int currentStrand = 0;
int currentHairId = -1;
// Now the hard part begins...
for (int i = 0; i < aseContent.Length; i++)
{
string[] tokens = aseContent[i].Split('\t');
if (aseContent[i].Contains("*SHAPE_LINECOUNT"))
{
tokens = tokens[1].Split(' ');
}
else if (aseContent[i].Contains("SHAPE_LINE"))
{
tokens = tokens[1].Split(' ');
}
if (tokens.Length >= 2)
{
if (tokens[0] == "*SHAPE_LINECOUNT")
{
if (currentStrand > 0)
{
// Start parsing next mesh after flushing the current strands buffer
currentHairId++;
currentStrand = 0;
// Add to mesh list / flush current strands buffer
HairMesh hairMesh = new HairMesh();
foreach (HairStrand strand in currentStrands)
{
hairMesh.strands.Add(strand);
}
hairMeshes.Add(hairMesh);
// Clear current strands
currentStrands.Clear();
}
}
else if (tokens[0] == "*SHAPE_LINE")
{
HairStrand strand = new HairStrand();
strand.isGuidanceStrand = true;
string[] vertexCountTokens = aseContent[i + 1].Split(' ');
// Parse the current line
int vertexCount = int.Parse(vertexCountTokens[1]);
// Parse vertices
for (int j = 0; j < vertexCount; j++)
{
string[] vertexTokens = aseContent[i + 2 + j].Replace('.', ',').Split('\t');
if (vertexTokens[2] == "*SHAPE_VERTEX_INTERP")
continue;
System.Globalization.NumberFormatInfo nf
= new System.Globalization.NumberFormatInfo()
{
NumberGroupSeparator = "."
};
vertexTokens[4] = vertexTokens[4].Replace(',', '.');
vertexTokens[5] = vertexTokens[5].Replace(',', '.');
vertexTokens[6] = vertexTokens[6].Replace(',', '.');
Vector3 position = new Vector3(float.Parse(vertexTokens[4], nf), float.Parse(vertexTokens[6], nf), float.Parse(vertexTokens[5], nf));
position = Vector3.Multiply(position, importSettings.scale);
HairStrandVertex v = new HairStrandVertex(position, Vector3.Zero, Vector4.Zero);
if (strand.vertices.Count == 0)
v.isMovable = false;
strand.vertices.Add(v);
}
currentStrands.Add(strand);
// Increment file-line-pointer
i = i + 1 + vertexCount;
currentStrand++;
}
}
}
// Shuffle strands
currentStrands = FormatHelper.Shuffle(currentStrands);
// Get last mesh
HairMesh lastMesh = new HairMesh();
lastMesh.strands.AddRange(currentStrands);
hairMeshes.Add(lastMesh);
return hairMeshes.ToArray();
}
}
}
|
using Amazon.SellingPartner.Serialization.NewtonsoftJson;
using RestSharp.Serializers.NewtonsoftJson;
namespace Amazon.SellingPartner.Auth.RestSharp
{
public class SafeRestSharpJsonNetSerializer : JsonNetSerializer
{
public SafeRestSharpJsonNetSerializer()
{
DefaultSettings.ContractResolver = new AmazonSellingPartnerSafeContractResolver();
}
}
} |
namespace ExtendingBogus
{
/// <summary>
/// Augment the existing <seealso cref="Bogus.DataSets.Address"/> DataSet via C# extension method.
/// </summary>
public static class ExtensionsForAddress
{
private static readonly string[] CanadaDowntownTorontoPostalCodes =
{
"M5S", "M5B", "M5X", "M5V", "M4W", "M4X", "M4Y",
"M5A", "M5C", "M5T", "M5E", "M5G", "M5H", "M5J",
"M5K", "M5L", "M6G"
};
public static string DowntownTorontoPostalCode(this Bogus.DataSets.Address address)
{
return address.Random.ArrayElement(CanadaDowntownTorontoPostalCodes);
}
}
}
|
namespace Carna.ConsoleRunner.Configuration
{
/// <summary>
/// Provides the function to parse a command line.
/// </summary>
public interface ICarnaRunnerCommandLineParser
{
/// <summary>
/// Parses the specified arguments of the command line.
/// </summary>
/// <param name="args">The arguments of the command line.</param>
/// <returns>The new instance of the <see cref="CarnaRunnerCommandLineOptions"/>.</returns>
/// <exception cref="InvalidCommandLineOptionException">
/// The argument of the command line is not specified and
/// a settings file does not exist.
/// </exception>
CarnaRunnerCommandLineOptions Parse(string[] args);
}
}
|
using Unity.Entities;
using UnityEngine;
using UnityEngine.AI;
public class EnemyMovementSystem : ComponentSystem
{
private EntityQuery enemyQuery;
private EntityQuery playerQuery;
protected override void OnCreate()
{
enemyQuery = GetEntityQuery(
ComponentType.ReadOnly<EnemyData>(),
ComponentType.ReadOnly<HealthData>(),
ComponentType.ReadOnly<NavMeshAgent>(),
ComponentType.Exclude<DeadData>());
playerQuery = GetEntityQuery(
ComponentType.ReadOnly<Transform>(),
ComponentType.ReadOnly<PlayerData>(),
ComponentType.ReadOnly<HealthData>());
}
protected override void OnUpdate()
{
GameObject player = null;
var playerHp = 0;
Entities.With(playerQuery).ForEach(
(Entity entity, Transform transform, ref HealthData hp) =>
{
player = transform.gameObject;
playerHp = hp.Value;
});
if (player == null)
return;
Entities.With(enemyQuery).ForEach(
(Entity entity, NavMeshAgent agent, ref HealthData hp) =>
{
if (hp.Value > 0 && playerHp > 0)
agent.SetDestination(player.transform.position);
else
agent.enabled = false;
});
}
}
|
using System;
using Indice.Types;
using Xunit;
namespace Indice.Common.Tests
{
public class ListOptionsTests
{
[Fact]
public void CanConvertListOptionsToDictionary() {
var now = DateTime.UtcNow;
var listOptions = new ListOptions<DocumentListFilter> {
Page = 1,
Size = 50,
Filter = new DocumentListFilter {
Code = "abc123",
From = now,
IsMarked = true,
Status = new[] { DocumentStatus.Issued, DocumentStatus.Paid }
}
};
var parameters = listOptions.ToDictionary();
Assert.True(parameters["page"].ToString() == "1");
Assert.True(parameters["size"].ToString() == "50");
Assert.True(parameters["filter.Code"].ToString() == "abc123");
Assert.True(parameters["filter.From"].ToString() == now.ToString("yyyy-MM-ddTHH:mm:ssZ"));
Assert.True(parameters["filter.IsMarked"].ToString() == bool.TrueString);
Assert.True(((string[])parameters["filter.Status"])[0] == "Issued");
Assert.True(((string[])parameters["filter.Status"])[1] == "Paid");
}
}
public class DocumentListFilter
{
public string Code { get; set; }
public DateTime? From { get; set; }
public DocumentStatus[] Status { get; set; }
public bool? IsMarked { get; set; }
}
public enum DocumentStatus : short
{
Draft = 0,
Issued = 1,
Overdue = 2,
Partial = 3,
Paid = 4,
Void = 5,
Deleted = 6
}
}
|
/*
作者:niniBoom
CSDN:http://blog.csdn.net/nini_boom?viewmode=contents
163邮箱:13063434858@163.com
-----------------------------------------------------------------
创建一个大型缓冲区可以划分并分配给SocketAsyncEventArgs 对象,
用在每个套接字I/O 操作。 这使缓冲区可以轻松地重复使用,可防止
堆内存碎片化
-----------------------------------------------------------------
注:这块的代码不多,逻辑简单,但是不建议全部去消化,很多地方需
要花费不小的学习成本去理解,只记住它的功能即可
-----------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace UDP_IOCP.UIOCP_Kernel
{
class BufferManager
{
int numBytes;
byte[] buffer;
Stack<int> freeIndexPool;
int currentIndex;
int bufferSize;
/// <summary>
/// 缓存管理,创建缓存块
/// </summary>
/// <param name="totalBytes">缓存的总大小</param>
/// <param name="bufferSize">每块缓存的大小</param>
public BufferManager(int totalBytes, int bufferSize)
{
numBytes = totalBytes;
currentIndex = 0;
this.bufferSize = bufferSize;
freeIndexPool = new Stack<int>();
}
/// <summary>
/// 为buffer创建空间
/// </summary>
public void InitBuffer()
{
buffer = new byte[numBytes];
}
/// <summary>
/// 为一个SocketAsyncEventArgs对象设置缓存区大小
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public bool SetBuffer(SocketAsyncEventArgs args)
{
if (freeIndexPool.Count > 0)
{
//如果freeIndexPool不为空,说明已经被用了,那么就在目前的栈顶部的偏移位开始Set,
args.SetBuffer(buffer, freeIndexPool.Pop(), bufferSize);
}
else
{
if ((numBytes - bufferSize) < currentIndex)
{
return false;
}
args.UserToken = currentIndex;
args.SetBuffer(buffer, currentIndex, bufferSize);
currentIndex += bufferSize;
}
return true;
}
public void SetBufferValue(SocketAsyncEventArgs args, byte[] value)
{
//取出SocketAsyncEventArgs的对象
int offsize = (int)args.UserToken;
for (int i = offsize; i < bufferSize + offsize; ++i)
{
if (i >= value.Length)
{
break;
}
buffer[i] = value[i - offsize];
}
}
public void FreeBuffer(SocketAsyncEventArgs args)
{
freeIndexPool.Push(args.Offset);
args.SetBuffer(null,0,0);
}
}
}
|
using CairoDesktop.Configuration;
using ManagedShell.Common.Enums;
using ManagedShell.Common.Helpers;
using ManagedShell.Interop;
using ManagedShell.UWPInterop;
using ManagedShell.WindowsTasks;
using System;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
namespace CairoDesktop.SupportingClasses
{
public class TaskGroup : INotifyPropertyChanged, IDisposable
{
private bool _singleWindowMode;
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged();
}
}
private ImageSource _icon;
public ImageSource Icon
{
get
{
return _icon;
}
set
{
_icon = value;
OnPropertyChanged();
}
}
public ApplicationWindow.WindowState State
{
get
{
return getState();
}
}
public ImageSource OverlayIcon
{
get
{
return getOverlayIcon();
}
}
public string OverlayIconDescription
{
get
{
return getOverlayIconDescription();
}
}
public NativeMethods.TBPFLAG ProgressState
{
get
{
return getProgressState();
}
}
public int ProgressValue
{
get
{
return getProgressValue();
}
}
public ReadOnlyObservableCollection<object> Windows;
private StoreApp _storeApp;
public TaskGroup(ReadOnlyObservableCollection<object> windows)
{
if (windows == null)
{
return;
}
Windows = windows;
(Windows as INotifyCollectionChanged).CollectionChanged += TaskGroup_CollectionChanged;
foreach(var aWindow in Windows)
{
if (aWindow is ApplicationWindow appWindow)
{
appWindow.PropertyChanged += ApplicationWindow_PropertyChanged;
}
}
setDisplayValues();
}
private void setDisplayValues()
{
if (Windows.Count > 1)
{
_singleWindowMode = false;
setDisplayValuesApp();
}
else
{
_singleWindowMode = true;
setDisplayValuesWindow();
}
}
private void setDisplayValuesApp()
{
if (Windows.Count > 0 && Windows[0] is ApplicationWindow window)
{
if (window.IsUWP)
{
_storeApp = StoreAppHelper.AppList.GetAppByAumid(window.AppUserModelID);
Title = _storeApp.DisplayName;
Icon = window.Icon;
}
else
{
Title = window.WinFileDescription;
Task.Factory.StartNew(() =>
{
Icon = IconImageConverter.GetImageFromAssociatedIcon(window.WinFileName, IconHelper.ParseSize(Settings.Instance.TaskbarIconSize) == IconSize.Small ? IconSize.Small : IconSize.Large);
}, CancellationToken.None, TaskCreationOptions.None, IconHelper.IconScheduler);
}
}
}
private void setDisplayValuesWindow()
{
if (Windows.Count > 0 && Windows[0] is ApplicationWindow window)
{
Title = window.Title;
Icon = window.Icon;
}
}
private ApplicationWindow.WindowState getState()
{
if (Windows.Any(win =>
{
if (win is ApplicationWindow window)
{
return window.State == ApplicationWindow.WindowState.Flashing;
}
return false;
}))
{
return ApplicationWindow.WindowState.Flashing;
}
if (Windows.Any(win =>
{
if (win is ApplicationWindow window)
{
return window.State == ApplicationWindow.WindowState.Active;
}
return false;
}))
{
return ApplicationWindow.WindowState.Active;
}
return ApplicationWindow.WindowState.Inactive;
}
private ImageSource getOverlayIcon()
{
return getOverlayIconWindow()?.OverlayIcon;
}
private string getOverlayIconDescription()
{
return getOverlayIconWindow()?.OverlayIconDescription;
}
private ApplicationWindow getOverlayIconWindow()
{
ApplicationWindow windowWithOverlay = (ApplicationWindow)Windows.FirstOrDefault(win =>
{
if (win is ApplicationWindow window)
{
return window.OverlayIcon != null;
}
return false;
});
if (windowWithOverlay != null && windowWithOverlay.OverlayIcon != null)
{
return windowWithOverlay;
}
return null;
}
private NativeMethods.TBPFLAG getProgressState()
{
if (Windows.Any(win =>
{
if (win is ApplicationWindow window)
{
return window.ProgressState == NativeMethods.TBPFLAG.TBPF_INDETERMINATE;
}
return false;
}))
{
return NativeMethods.TBPFLAG.TBPF_INDETERMINATE;
}
if (Windows.Any(win =>
{
if (win is ApplicationWindow window)
{
return window.ProgressState == NativeMethods.TBPFLAG.TBPF_NORMAL;
}
return false;
}))
{
return NativeMethods.TBPFLAG.TBPF_NORMAL;
}
return NativeMethods.TBPFLAG.TBPF_NOPROGRESS;
}
private int getProgressValue()
{
int count = Windows.Count(win =>
{
if (win is ApplicationWindow window)
{
return window.ProgressValue > 0;
}
return false;
});
if (count < 1)
{
return 0;
}
int total = Windows.Sum(win => {
if (win is ApplicationWindow window)
{
return window.ProgressValue > 0 ? window.ProgressValue : 0;
}
return 0;
});
if (total < 1)
{
return 0;
}
return total / count;
}
private void ApplicationWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "State":
OnPropertyChanged("State");
break;
case "OverlayIcon":
OnPropertyChanged("OverlayIcon");
break;
case "OverlayIconDescription":
OnPropertyChanged("OverlayIconDescription");
break;
case "ProgressState":
OnPropertyChanged("ProgressState");
break;
case "ProgressValue":
OnPropertyChanged("ProgressValue");
break;
case "Title" when _singleWindowMode:
if (Windows.Count > 0 && Windows[0] is ApplicationWindow titleWindow)
{
Title = titleWindow.Title;
}
break;
case "Icon":
if (Windows.Count > 0 && Windows[0] is ApplicationWindow iconWindow && (_singleWindowMode || iconWindow.IsUWP))
{
Icon = iconWindow.Icon;
}
break;
}
}
private void TaskGroup_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (var newItem in e.NewItems)
{
if (newItem is ApplicationWindow appWindow)
{
appWindow.PropertyChanged += ApplicationWindow_PropertyChanged;
}
}
}
if (e.OldItems != null)
{
foreach (var oldItem in e.OldItems)
{
if (oldItem is ApplicationWindow appWindow)
{
appWindow.PropertyChanged -= ApplicationWindow_PropertyChanged;
}
}
if (e.OldItems.Count > 0)
{
// If windows were removed, update progress values in case the window was destroyed before updating its progress value
OnPropertyChanged("ProgressState");
OnPropertyChanged("ProgressValue");
}
}
// If the window count has changed such that single window mode should toggle
if (_singleWindowMode == (Windows.Count > 1))
{
setDisplayValues();
}
OnPropertyChanged("State");
}
public void Dispose()
{
foreach (var aWindow in Windows)
{
if (aWindow is ApplicationWindow appWindow)
{
appWindow.PropertyChanged -= ApplicationWindow_PropertyChanged;
}
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class nodoXML {
[XmlAttribute("id")]
public string id;
public List<opcionXML> opciones = new List<opcionXML>();
public List<TextoXML> textos = new List<TextoXML>();
public nodoXML(){
textos = new List<TextoXML> (2);
opciones = new List<opcionXML>(1);
}
public void addTexto(TextoXML text){
textos.Add (text);
}
public void addOpcion(opcionXML opcion){
opciones.Add (opcion);
}
public opcionXML getOpcion(int index){
return null;
}
}
|
using System;
using System.Collections.Generic;
namespace Lab6
{
public class Task2
{
public IRemoteClient CreateRemoteClient(IRemoteService remoteService)
{
return new RemoteClient(remoteService);
}
}
public class RemoteClient : IRemoteClient
{
private readonly IRemoteService remoteService;
public RemoteClient(IRemoteService remoteService)
{
this.remoteService = remoteService;
}
public IRemoteResult SendData(string[] data)
{
throw new NotImplementedException();
}
}
public class RemoteResult : IRemoteResult
{
public IEnumerable<Exception> Exceptions => throw new NotImplementedException();
public bool IsSuccess => throw new NotImplementedException();
public void Add(Exception exception)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace SimpleForm_RegisterUserWithPhoto.Utility {
public static class MyGuid {
public static string Generate () =>
Guid.NewGuid ().ToString ("N");
}
} |
using System.Threading.Tasks;
using Integracja.Server.Infrastructure.Models;
namespace Integracja.Server.Infrastructure.Services.Interfaces
{
public interface IAuthService
{
Task<DetailUserDto> Login(LoginDto dto);
Task Logout(int userId);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace iLit.Core
{
public interface INodeRepository
{
/*Checks if the Node already exists and if it creates a new NodeDTO.*/
Task<NodeDTO> createNewNode(NodeCreateDTO newNode);
/*Deletes the Node where INode.getID = ID.*/
Task<Response> deleteNode(int ID);
/*Returns a list of all Nodes.*/
Task<IReadOnlyCollection<NodeDTO>> getAllNodes();
/*Returns the NodeDTO of the Node with the given ID.*/
Task<Option<NodeDTO>> getNode(int ID);
}
}
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Lex.Outputs
{
[OutputType]
public sealed class BotIntent
{
/// <summary>
/// The name of the intent. Must be less than or equal to 100 characters in length.
/// </summary>
public readonly string IntentName;
/// <summary>
/// The version of the intent. Must be less than or equal to 64 characters in length.
/// </summary>
public readonly string IntentVersion;
[OutputConstructor]
private BotIntent(
string intentName,
string intentVersion)
{
IntentName = intentName;
IntentVersion = intentVersion;
}
}
}
|
using DZY.DotNetUtil.Helpers;
using LiveWallpaper.Store.Models.Settngs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
namespace LiveWallpaper.Store.Services
{
public class AppService
{
public AppService()
{
//var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//appData = $"{appData}\\LiveWallpaperStore";
//SettingPath = $"{appData}\\Config\\setting.json";
}
///// <summary>
///// 配置文件地址
///// </summary>
//public string SettingPath { get; private set; }
public SettingObject Setting { get; private set; }
public async Task LoadConfig()
{
string json = null;
bool ok = ApplicationData.Current.LocalSettings.Values.TryGetValue("config", out object temp);
if (ok)
json = temp.ToString();
if (string.IsNullOrEmpty(json))
{
SettingObject setting = SettingObject.GetDefaultSetting();
json = await JsonHelper.JsonSerializeAsync(setting);
}
var config = await JsonHelper.JsonDeserializeAsync<SettingObject>(json);
config.CheckDefaultSetting();
Setting = config;
}
public static bool IsLocked(string serverUrl)
{
return "whosyourdady" != serverUrl;
}
}
}
|
namespace JobSpawn.Proxy
{
public interface IProxyBuilder
{
TContract BuildProxy<TContract>();
}
} |
using System;
using System.Collections.Generic;
using FChoice.Foundation.Clarify;
using FChoice.Foundation.DataObjects;
using FubuCore;
namespace Dovetail.SDK.Bootstrap.Clarify
{
public interface ICurrentSDKUser
{
string Username { get; }
string ImpersonatingUsername { get; }
string Fullname { get; }
string Sitename { get; }
bool IsAuthenticated { get; }
bool HasPermission(string permission);
ITimeZone Timezone { get; }
IEnumerable<SDKUserQueue> Queues { get; }
string Workgroup { get; }
string PrivClass { get; }
void SignOut();
void SetUser(string clarifyLoginName);
void SetTimezone(ITimeZone timezone);
}
public class CurrentSDKUser : ICurrentSDKUser
{
private readonly DovetailDatabaseSettings _settings;
private readonly IUserDataAccess _userDataAccess;
private readonly IClarifySessionCache _sessionCache;
private readonly ILogger _logger;
private readonly ILocaleCache _localeCache;
private Lazy<SDKUser> _user;
private Lazy<ITimeZone> _timezone;
private Lazy<HashSet<string>> _permissionsByName;
public string Fullname
{
get
{
if (!IsAuthenticated) return "";
var user = _user.Value;
return user.FirstName + " " + user.LastName;
}
}
public bool IsAuthenticated { get; private set; }
public string Username
{
get { return _user.Value.Login; }
}
public string Sitename
{
get { return _user.Value.SiteName; }
}
public string ImpersonatingUsername
{
get { return _user.Value.ImpersonatingLogin; }
}
public ITimeZone Timezone
{
get
{
if (!IsAuthenticated)
{
return _localeCache.ServerTimeZone;
}
return _timezone.Value;
}
}
public void SetTimezone(ITimeZone timezone)
{
_timezone = new Lazy<ITimeZone>(() => timezone);
}
public IEnumerable<SDKUserQueue> Queues
{
get
{
if (!IsAuthenticated)
{
return new SDKUserQueue[0];
}
return _user.Value.Queues;
}
}
public string Workgroup
{
get
{
if (!IsAuthenticated)
{
return "";
}
return _user.Value.Workgroup;
}
}
public string PrivClass
{
get
{
if (!IsAuthenticated)
{
return "";
}
return _user.Value.PrivClass;
}
}
public CurrentSDKUser(DovetailDatabaseSettings settings,
ILocaleCache localeCache,
IUserDataAccess userDataAccess,
IClarifySessionCache sessionCache,
ILogger logger)
{
_settings = settings;
_userDataAccess = userDataAccess;
_sessionCache = sessionCache;
_logger = logger;
_localeCache = localeCache;
//set up defaults
SignOut();
}
public bool HasPermission(string permission)
{
return _permissionsByName.Value.Contains(permission);
}
public void SetUser(string clarifyLoginName)
{
_logger.LogDebug("CurrentSDK user set via principal to {0}.".ToFormat(clarifyLoginName));
changeUser(clarifyLoginName);
IsAuthenticated = true;
}
public void SignOut()
{
_logger.LogDebug("Signing out currentSDK user.");
IsAuthenticated = false;
//when no user is authenticated the application user is used
changeUser(_settings.ApplicationUsername);
}
public void changeUser(string login)
{
_logger.LogDebug("Changing the current SDK user to be {0}.", login);
_user = new Lazy<SDKUser>(() => GetUser(login));
_permissionsByName = new Lazy<HashSet<string>>(GetSessionPermissions);
_timezone = new Lazy<ITimeZone>(() => _user.Value.Timezone);
}
private SDKUser GetUser(string login)
{
return _userDataAccess.GetUser(login);
}
private HashSet<string> GetSessionPermissions()
{
var session = _sessionCache.GetSession(_user.Value.Login);
var set = new HashSet<string>();
set.UnionWith(session.Permissions);
_logger.LogDebug("Permission set for {0} setup with {1} permissions.".ToFormat(_user.Value.Login, set.Count));
return set;
}
}
}
|
namespace KafkaFlow
{
using System.Collections.Generic;
/// <summary>
/// Represents a collection of message headers
/// </summary>
public interface IMessageHeaders : IEnumerable<KeyValuePair<string, byte[]>>
{
/// <summary>
/// Adds a new header to the enumeration
/// </summary>
/// <param name="key">The header key.</param>
/// <param name="value">The header value (possibly null)</param>
void Add(string key, byte[] value);
/// <summary>
/// Gets the header with specified key
/// </summary>
/// <param name="key">The zero-based index of the element to get</param>
byte[] this[string key] { get; set; }
}
}
|
namespace Vetuviem.SourceGenerator.Features.Core
{
/// <summary>
/// Represents the logic used for driving type searching in a UI platform.
/// </summary>
public interface IPlatformResolver
{
/// <summary>
/// Gets the assembly names used to resolve platform types.
/// </summary>
/// <returns>one or more assembly names.</returns>
string[] GetAssemblyNames();
/// <summary>
/// Gets the fully qualified type that UI elements within the platform inherit from.
/// </summary>
/// <returns>Fully qualified type name.</returns>
string GetBaseUiElement();
/// <summary>
/// Gets the fully qualified type that platform uses for commands.
/// </summary>
/// <returns>Fully qualified type name, or null if no command implementation in the platform.</returns>
string? GetCommandInterface();
}
}
|
#nullable disable
using System.Runtime.Serialization;
using VocaDb.Model.Domain.Globalization;
using VocaDb.Model.Domain.Tags;
namespace VocaDb.Model.DataContracts.Tags
{
[DataContract(Namespace = Schemas.VocaDb)]
public class TagUsageForApiContract
{
public TagUsageForApiContract() { }
public TagUsageForApiContract(TagUsage tagUsage, ContentLanguagePreference languagePreference)
{
Count = tagUsage.Count;
Tag = new TagBaseContract(tagUsage.Tag, languagePreference, includeAdditionalNames: true, includeCategory: true);
}
public TagUsageForApiContract(Tag tag, int count, ContentLanguagePreference languagePreference)
{
Count = count;
Tag = new TagBaseContract(tag, languagePreference, includeAdditionalNames: true, includeCategory: true);
}
[DataMember]
public int Count { get; init; }
[DataMember]
public TagBaseContract Tag { get; init; }
}
}
|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Laobian.Share.Misc;
namespace Laobian.Api.Service;
public interface IGitFileService
{
Task PullAsync(CancellationToken cancellationToken = default);
Task PushAsync(string message, CancellationToken cancellationToken = default);
Task<List<GitFileStat>> GetGitFileStatsAsync(CancellationToken cancellationToken = default);
} |
using System;
namespace Endless
{
public static partial class Function
{
/// <summary>
/// Functional composition. g.Then(f)(x) = f(g(x)).
/// </summary>
/// <param name="first">Function that is applied first (inner)</param>
/// <param name="second">Function that is applied second (outer)</param>
public static Func<T1, T3> Then<T1, T2, T3>(this Func<T1, T2> first, Func<T2, T3> second)
{
if (first == null) throw new ArgumentNullException(nameof(first));
if (second == null) throw new ArgumentNullException(nameof(second));
var result = new Func<T1, T3>(x => second(first(x)));
return result;
}
}
} |
using System.Xml.Serialization;
#nullable disable
namespace EasyKeys.Shipping.Usps.Tracking.Models
{
[XmlRoot(ElementName = "PTSRRERESULT")]
public class PTSRreResult
{
[XmlElement(ElementName = "ResultText")]
public string ResultText { get; set; }
[XmlElement(ElementName = "ReturnCode")]
public string ReturnCode { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fade : MonoBehaviour
{
[SerializeField] bool startOpaque;
[SerializeField] float fadeTime;
float fadeCounter;
float alpha;
bool transparent;
bool fadeIn;
bool fadeOut;
Image sprite;
void Start ()
{
sprite = GetComponent<Image>();
fadeCounter = fadeTime;
if (startOpaque)
{
transparent = false;
sprite.color = new Color(sprite.color.r, sprite.color.g, sprite.color.b, 1);
}
else
{
transparent = true;
sprite.color = new Color(sprite.color.r, sprite.color.g, sprite.color.b, 0);
}
}
void Update ()
{
if(fadeIn)
{
if(fadeCounter > 0)
{
fadeCounter -= Time.deltaTime;
alpha = Easing.ExpoEaseOut(fadeCounter, 1, -1, fadeTime);
sprite.color = new Color(sprite.color.r, sprite.color.g, sprite.color.b, alpha);
}
else
{
fadeIn = false;
fadeCounter = fadeTime;
transparent = false;
}
}
if(fadeOut)
{
if (fadeCounter > 0)
{
fadeCounter -= Time.deltaTime;
alpha = Easing.ExpoEaseOut(fadeCounter, 0, 1, fadeTime);
sprite.color = new Color(sprite.color.r, sprite.color.g, sprite.color.b, alpha);
}
else
{
fadeOut = false;
fadeCounter = fadeTime;
transparent = true;
}
}
}
public void FadeIn()
{
fadeIn = true;
}
public void FadeOut()
{
fadeOut = true;
}
public bool Transparent { get { return transparent; } }
}
|
using ContactListSample.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace ContactListSample.ViewModels
{
public class ItemDetailViewModel : BaseViewModel
{
public Contact Item { get; set; }
public ItemDetailViewModel(Contact item = null)
{
Title = item?.Name;
Item = item;
}
}
}
|
namespace AdventOfCode2021.Common
{
// I should have done this at the beginning.
public static class ReadFileHelper
{
/// <summary>
/// This is the routine that will read through the Advent of Code files. It reads the passed file, then
/// this constructs the full path to the file and opens it, reads all the contents and returns
/// the contents as a nullable string[]. The file MUST be in the Data folder
/// </summary>
/// <param name="TextFileName">The name of the text file, for example: Day1.txt </param>
/// <returns>A nullable string array which is the contents of the file passed to this routine</returns>
public static string[]? ReadTextFileReturnContents(string TextFileName)
{
// inspired by: https://stackoverflow.com/questions/13762338/read-files-from-a-folder-present-in-project
string executionPath = Environment.CurrentDirectory;
var path = executionPath + @"\Data\" + TextFileName;
// read in the contents of the text file, returning the contents to the calling routine
return File.ReadAllLines(path);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PilaDocumentos
{
class Carta : Documento
{
string fecha;
string origen;
string asunto;
public Carta(string fecha, string origen, string asunto)
{
this.fecha = fecha;
this.origen = origen;
this.asunto = asunto;
}
public string mostrar()
{
return "Carta- fecha:" + fecha + "origen:" + origen + "asunto:" + asunto;
}
public override string ToString()
{
return mostrar();
}
}
}
|
using System;
using Cafemoca.MinecraftCommandStudio.ViewModels.Panes.Bases;
using Reactive.Bindings;
namespace Cafemoca.MinecraftCommandStudio.ViewModels.Panes.Documents
{
public class StartPageViewModel : DocumentPaneViewModel
{
public ReactiveCommand NewCommand { get; private set; }
public ReactiveCommand OpenCommand { get; private set; }
public StartPageViewModel()
: base()
{
this.Title.Value = "スタート ページ";
this.NewCommand = new ReactiveCommand();
this.NewCommand.Subscribe(_ => App.MainViewModel.NewCommand.Execute());
this.OpenCommand = new ReactiveCommand();
this.OpenCommand.Subscribe(_ => App.MainViewModel.OpenCommand.Execute());
}
}
}
|
//
// Copyright SmartFormat Project maintainers and contributors.
// Licensed under the MIT license.
namespace SmartFormat.Pooling.ObjectPools;
internal interface IPoolCounters
{
/// <summary>
/// The total number of active and inactive objects.
/// </summary>
int CountAll { get; }
/// <summary>
/// Number of objects that have been created by the pool but are currently in use and have not yet been returned.
/// </summary>
int CountActive { get; }
/// <summary>
/// Number of objects that are currently available in the pool.
/// </summary>
int CountInactive { get; }
} |
using System;
using AutoMapper;
using Domain.Common;
using Domain.Entities;
namespace Domain.Models
{
public class ReservationVm : IMapFrom<Reservation>
{
public string Id { get; set; }
public HotelRoomShortVm ReservedRoom { get; set; }
public DateTime ReservedForDate { get; set; }
public DateTime ReservedUntilDate { get; set; }
public bool IncludeFood { get; set; }
public bool AllInclusive { get; set; }
public decimal Price { get; set; }
public void Mapping(Profile profile) =>
profile.CreateMap<Reservation, ReservationVm>()
.ForMember(f => f.ReservedRoom, f => f.MapFrom(s => s.ReservedRoom));
}
public class ReservationShortVm : IMapFrom<Reservation>
{
public string Id { get; set; }
public DateTime ReservedForDate { get; set; }
public DateTime ReservedUntilDate { get; set; }
public void Mapping(Profile profile) =>
profile.CreateMap<Reservation, ReservationShortVm>();
}
} |
using osu.Framework.Graphics.Sprites;
using osu.Game.Overlays.Dialog;
using System;
namespace osu.Game.Rulesets.OvkTab.UI.Components.Account
{
public class LogoutDialog : PopupDialog
{
public LogoutDialog(Action callback)
{
Icon = FontAwesome.Solid.SignOutAlt;
HeaderText = "Do you want to log out from this account?";
BodyText = "Session data and token will be deleted.";
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Log out",
Action = callback
},
new PopupDialogCancelButton
{
Text = @"Cancel",
},
};
}
}
}
|
using System;
namespace Basiclog.Internals
{
internal class InternalValuedLog : IValuedLog
{
private InternalValuedLog(object value)
{
Value = value;
Message = string.Empty;
LogType = LogType.Info;
DateTime = DateTime.Now;
}
private InternalValuedLog(object value, ILog log)
{
Value = value;
Message = log.Message;
LogType = log.LogType;
DateTime = log.DateTime;
}
private InternalValuedLog(object value, string message, LogType logType = LogType.Info)
{
Value = value;
Message = message;
LogType = logType;
DateTime = DateTime.Now;
}
private InternalValuedLog(object value, string message, LogType logType, DateTime dateTime)
{
Value = value;
Message = message;
LogType = logType;
DateTime = dateTime;
}
public DateTime DateTime { get; }
public LogType LogType { get; }
public string Message { get; }
public TimeSpan Time { get; }
public string TimeString { get; }
public object Value { get; }
public static IValuedLog New(object value)
{
return new InternalValuedLog(value);
}
public static IValuedLog New(object value, ILog log)
{
return new InternalValuedLog(value, log);
}
public static IValuedLog New(object value, string message, LogType type = LogType.Info)
{
return new InternalValuedLog(value, message, type);
}
public static IValuedLog New(object value, string message, LogType logType, DateTime dateTime)
{
return new InternalValuedLog(value, message, logType, dateTime);
}
public static IValuedLog NewError(object value, string message)
{
return new InternalValuedLog(value, message, LogType.Error);
}
public static IValuedLog NewFailure(object value, string message)
{
return new InternalValuedLog(value, message, LogType.Failure);
}
public static IValuedLog NewInfo(object value, string message)
{
return new InternalValuedLog(value, message, LogType.Info);
}
public static IValuedLog NewSuccess(object value, string message)
{
return new InternalValuedLog(value, message, LogType.Success);
}
public static IValuedLog NewWarning(object value, string message)
{
return new InternalValuedLog(value, message, LogType.Warning);
}
}
internal class InternalValuedLog<T> : IValuedLog<T>
{
private InternalValuedLog(T value)
{
Value = value;
Message = string.Empty;
LogType = LogType.Info;
DateTime = DateTime.Now;
}
private InternalValuedLog(T value, ILog log)
{
Value = value;
Message = log.Message;
LogType = log.LogType;
DateTime = log.DateTime;
}
private InternalValuedLog(T value, string message, LogType logType = LogType.Info)
{
Value = value;
Message = message;
LogType = logType;
DateTime = DateTime.Now;
}
private InternalValuedLog(T value, string message, LogType logType, DateTime dateTime)
{
Value = value;
Message = message;
LogType = logType;
DateTime = dateTime;
}
public DateTime DateTime { get; }
public LogType LogType { get; }
public string Message { get; }
public TimeSpan Time { get; }
public string TimeString { get; }
public T Value { get; }
object IValuedLog.Value => Value;
public static IValuedLog<T> New(T value)
{
return new InternalValuedLog<T>(value);
}
public static IValuedLog<T> New(T value, ILog log)
{
return new InternalValuedLog<T>(value, log);
}
public static IValuedLog<T> New(T value, string message, LogType type = LogType.Info)
{
return new InternalValuedLog<T>(value, message, type);
}
public static IValuedLog<T> New(T value, string message, LogType logType, DateTime dateTime)
{
return new InternalValuedLog<T>(value, message, logType, dateTime);
}
public static IValuedLog<T> NewError(T value, string message)
{
return new InternalValuedLog<T>(value, message, LogType.Error);
}
public static IValuedLog<T> NewFailure(T value, string message)
{
return new InternalValuedLog<T>(value, message, LogType.Failure);
}
public static IValuedLog<T> NewInfo(T value, string message)
{
return new InternalValuedLog<T>(value, message, LogType.Info);
}
public static IValuedLog<T> NewSuccess(T value, string message)
{
return new InternalValuedLog<T>(value, message, LogType.Success);
}
public static IValuedLog<T> NewWarning(T value, string message)
{
return new InternalValuedLog<T>(value, message, LogType.Warning);
}
}
} |
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace Entoarox.Framework.Interface
{
public class GenericComponentCollection : BaseComponentCollection
{
/*********
** Public methods
*********/
public GenericComponentCollection(string name, Rectangle bounds, int layer = 0)
: base(name, bounds, layer) { }
public GenericComponentCollection(string name, Rectangle bounds, IEnumerable<IComponent> components, int layer = 0)
: base(name, bounds, layer)
{
foreach (IComponent component in components)
this.AddComponent(component);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Spark.Interop;
using Microsoft.Spark.Interop.Ipc;
namespace Microsoft.Spark.ML.Feature.Param
{
/// <summary>
/// A param to value map.
/// </summary>
public class ParamMap : IJvmObjectReferenceProvider
{
private static readonly string s_ParamMapClassName = "org.apache.spark.ml.param.ParamMap";
/// <summary>
/// Creates a new instance of a <see cref="ParamMap"/>
/// </summary>
public ParamMap() : this(SparkEnvironment.JvmBridge.CallConstructor(s_ParamMapClassName))
{
}
internal ParamMap(JvmObjectReference jvmObject) => Reference = jvmObject;
public JvmObjectReference Reference { get; private set; }
/// <summary>
/// Puts a (param, value) pair (overwrites if the input param exists).
/// </summary>
/// <param name="param">The param to be add</param>
/// <param name="value">The param value to be add</param>
public ParamMap Put<T>(Param param, T value) =>
WrapAsParamMap((JvmObjectReference)Reference.Invoke("put", param, value));
/// <summary>
/// Returns the string representation of this ParamMap.
/// </summary>
/// <returns>representation as string value.</returns>
public override string ToString() =>
(string)Reference.Invoke("toString");
private static ParamMap WrapAsParamMap(object obj) =>
new ParamMap((JvmObjectReference)obj);
}
}
|
using DbSqlHelper;
using Xunit;
using Dapper;
namespace DbSqlHelperTest
{
public class DbTest : BaseTest
{
[Fact]
public void SqlFormat()
{
//default Database
{
var sql = "select * from {1}orders{2} where id = {0}id".SqlFormat();
//if db is sqlserver
Assert.Equal("select * from [orders] where id = @id", sql);
//if db is oracle
//Assert.Equal("select * from "orders" where id = :id", sql);
}
//Mutiple Database
{
var sql = "sqlserver".SqlFormat("select * from {1}orders{2} where id = {0}id");
Assert.Equal("select * from [orders] where id = @id", sql);
}
//SqlSimpleFormat
{
var sql = "select * from orders where id = @id".SqlSimpleFormat();
//if db is sqlserver
Assert.Equal("select * from orders where id = @id", sql);
//if db is oracle
//Assert.Equal("select * from orders where id = :id", sql);
}
}
[Fact]
public void SqlQuery()
{
var result = Db.SqlQuery(connection => connection.CreateCommand("select 'Hello Github'").ExecuteScalar());
Assert.Equal("Hello Github", result);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClassUsingInputController : MonoBehaviour
{
KeyCode key;
// Start is called before the first frame update
void Start()
{
key = (KeyCode)Random.Range(0, (int)KeyCode.Joystick8Button9);
InputController.Instance.RegisterTrackKey(key, KeyInteraction.KeyDown, Jump);
}
private void Jump()
{
Debug.Log("Jump");
}
}
|
using System;
namespace ESIConnectionLibrary.PublicModels
{
public class V1CalendarSummary
{
public DateTime? EventDate { get; set; }
public int? EventId { get; set; }
public V1CalendarSummaryEventResponses? EventResponse { get; set; }
public int? Importance { get; set; }
public string Title { get; set; }
}
} |
using Amazon.Lambda.Core;
namespace Devon4Net.Infrastructure.AWS.Lambda.Interfaces
{
public interface IMessageHandler<in TInput, TOutput> where TInput : class
{
Task<TOutput> HandleMessage(TInput message, ILambdaContext context);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace NVM
{
public class Util
{
// change version here
public const string Version = "0.0.2";
// delegate PATH actions to `Util.Path` property
public static string Path
{
get
{
return Environment.GetEnvironmentVariable("PATH",EnvironmentVariableTarget.Machine);
}
set
{
Environment.SetEnvironmentVariable("PATH",value,EnvironmentVariableTarget.Machine);
}
}
public static string EnsureVer(string ver)
{
if(ver[0] != 'v')
{
if(ver[0] == 'V')
{
ver = ver.ToLower();
}
else
{
ver = "v" + ver;
}
}
return ver;
}
public static string GetCurrentVer()
{
var path = Environment.GetEnvironmentVariable("PATH",EnvironmentVariableTarget.Machine);
var dir = AppDomain.CurrentDomain.BaseDirectory; // ends with \
foreach(var p in path.Split(';'))
{
if(p.StartsWith(dir + "v",StringComparison.OrdinalIgnoreCase)) // /v0.10.33/node.exe
{
var ver = p.Substring(dir.Length); // v0.10.33
if(!string.IsNullOrWhiteSpace(ver))
{
return ver;
}
}
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Nest;
using Rehber.Model.DataModels;
namespace Rehber.Services.Elasticsearch.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UnitsController : ControllerBase
{
ElasticsearchClient _elasticClient;
public UnitsController()
{
_elasticClient = new ElasticsearchClient();
}
// PUT
[HttpPut]
public IActionResult Put([FromBody] Units unit)
{
if (unit.UnitId > 0)
{
_elasticClient.IndexUnit(unit);
return Ok();
}
else
{
return BadRequest();
}
}
// GET
[HttpGet , Route("{unitId}")]
public ActionResult<IEnumerable<string>> Get(int unitId)
{
var unit = _elasticClient.GetUnitById(unitId);
if (unit != null)
{
return Ok(unit);
}
return NotFound();
}
//// GET
//[HttpGet("UserId")]
//public ActionResult<IEnumerable<string>> GetFiltered(int UserId)
//{
// var request = new SearchRequest
// {
// From = 0,
// Size = 10,
// Query = new TermQuery { Field = "UserId", Value = UserId }
// /*
// ||
// new MatchQuery { Field = "Name", Query = "NAME" }
// */
// };
// var response = _client.Search<Users>(request);
// return new JsonResult(response);
//}
}
}
|
namespace SubmissionEvaluation.Shared.Classes.Config
{
public class ApplicationSettings
{
public int Delaytime { get; internal set; }
public string PathToLogger { get; internal set; }
public string PathToServerWwwRoot { get; set; }
public string PathToData { get; set; }
public bool Inactive { get; internal set; }
public int InstancePort { get; internal set; }
public string InstanceName { get; internal set; }
public string WebApiPassphrase { get; internal set; }
public string SiteUrl { get; internal set; }
}
}
|
namespace OpenGLBindings
{
/// <summary>
/// Used in GL.ConvolutionParameter, GL.GetConvolutionParameter
/// </summary>
public enum ConvolutionParameterExt
{
/// <summary>
/// Original was GL_CONVOLUTION_BORDER_MODE = 0x8013
/// </summary>
ConvolutionBorderMode = 32787,
/// <summary>
/// Original was GL_CONVOLUTION_BORDER_MODE_EXT = 0x8013
/// </summary>
ConvolutionBorderModeExt = 32787,
/// <summary>
/// Original was GL_CONVOLUTION_FILTER_SCALE = 0x8014
/// </summary>
ConvolutionFilterScale = 32788,
/// <summary>
/// Original was GL_CONVOLUTION_FILTER_SCALE_EXT = 0x8014
/// </summary>
ConvolutionFilterScaleExt = 32788,
/// <summary>
/// Original was GL_CONVOLUTION_FILTER_BIAS = 0x8015
/// </summary>
ConvolutionFilterBias = 32789,
/// <summary>
/// Original was GL_CONVOLUTION_FILTER_BIAS_EXT = 0x8015
/// </summary>
ConvolutionFilterBiasExt = 32789
}
} |
using System.Threading.Tasks;
using NUnit.Framework;
using Quickpay;
namespace QuickPay.IntegrationTests
{
[TestFixture]
public class RestClientSmokeTests
{
[Test]
public void CanPingGetSync()
{
var sut = new PingExample(QpConfig.ApiKey);
var result = sut.GetPing();
StringAssert.Contains("Pong", result.Msg);
}
[Test]
public async Task CanPingGetAsync()
{
var sut = new PingExample(QpConfig.ApiKey);
var result = await sut.GetPingAsync();
StringAssert.Contains("Pong", result.Msg);
}
[Test]
public void CanPingPostSync()
{
var sut = new PingExample(QpConfig.ApiKey);
var result = sut.PostPing();
StringAssert.Contains("Pong", result.Msg);
}
[Test]
public void CanGetAccountInformation()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.Account();
Assert.AreNotEqual(null, result);
}
[Test]
public void CanGetAclResources()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.AclResources(AccountType.Merchant, new PageParameters{Page = 1, PageSize = 20});
Assert.AreNotEqual(0, result.Count);
Assert.NotNull(result[0].Description);
}
[Test]
public void GetsPayments()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.Payments();
Assert.AreNotEqual (0, result.Count);
}
[Test]
public void GetsAgreements()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.Agreements(null, new SortingParameters{SortDirection = SortDirection.asc, SortBy = "id"});
Assert.AreNotEqual (0, result.Count);
}
[Test]
public void GetsBrandings()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.Branding();
Assert.AreNotEqual (0, result.Count);
}
[Test]
public void GetsActivity()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.Activity();
Assert.AreNotEqual (0, result.Count);
}
[Test]
public void GetsAcquirerOperationalStatus()
{
var sut = new MerchantExample(QpConfig.ApiKey);
var result = sut.AcquirerOperationalStatus();
Assert.AreNotEqual (0, result.Count);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using DTO;
namespace BUS
{
public class BUS_HangHoa
{
private static BUS_HangHoa instance;
public BUS_HangHoa() { }
public static BUS_HangHoa Instance
{
get
{
if (instance == null)
instance = new BUS_HangHoa();
return instance;
}
}
public String generateAutoID()
{
return Helper.generateAutoID("HangHoa", "MaHangHoa", "HH");
}
public static List<DTO_HangHoa> showData()
{
return HangHoa.Instance.showHH();
}
public static List<DTO_HangHoa> showDataDKD()
{
return HangHoa.Instance.showHHDKD();
}
public static bool Delete(DTO_HangHoa obj)
{
return HangHoa.Instance.DeleteHH(obj);
}
public bool Insert(DTO_HangHoa obj)
{
return HangHoa.Instance.InsertHH(obj);
}
public bool Update(DTO_HangHoa obj)
{
return HangHoa.Instance.update(obj);
}
public List<DTO_HangHoa> searchData(bool trangthai ,String str)
{
return HangHoa.Instance.search(trangthai ,str);
}
public decimal getGiaBan(string maHangHoa)
{
return HangHoa.Instance.getGiaBan(maHangHoa);
}
public bool UpdateSoLuong(DTO_HangHoa obj)
{
return HangHoa.Instance.updateSoLuong(obj);
}
public int getSoLuong(string tenHangHoa)
{
return HangHoa.Instance.getSoLuong(tenHangHoa);
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using Advertise.DomainClasses.Entities.Public;
namespace Advertise.DomainClasses.Configurations.Public
{
/// <summary>
/// </summary>
public class ConversationConfig : EntityTypeConfiguration<Conversation>
{
/// <summary>
/// </summary>
public ConversationConfig()
{
Property(message => message.Body).IsRequired().HasMaxLength(1000);
Property(message => message.Title).IsOptional().HasMaxLength(100);
Property(message => message.RowVersion).IsRowVersion();
}
}
} |
using System;
using System.Collections.Generic;
using DL.ClientLayer.Infrastructure.IoC;
using DL.Data.Infrastructure.ContextControl;
using DL.Tests.Infrastructure.Fakes;
using Microsoft.Extensions.DependencyInjection;
namespace DL.Tests.Infrastructure.TestBases
{
public class IntegratedFor<T> : ArrangeActAssertOn
where T : class
{
protected readonly List<Action<IServiceCollection>> DependencyFakes = new List<Action<IServiceCollection>>();
protected T SUT;
public IntegratedFor()
{
SharedBeforeAll();
SUT = Resolve<T>();
}
protected TResolveFor Resolve<TResolveFor>()
{
return DependencyRegistrations.Resolve<TResolveFor>(DependencyFakes);
}
private void SharedBeforeAll()
{
DependencyFakes.Add((services) =>
{
services.AddScoped<IDbContextFactory, EntityFrameworkInMemoryDbContextFactory>();
});
}
}
} |
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace FinanceDataMigrationApi.V1.Infrastructure.Accounts
{
[Table("DMDynamoTenureHouseHoldMembers")]
public class DMPrimaryTenantsDbEntity
{
[Column("row_id")]
public long RowId { get; set; }
[Column("id")]
public Guid Id { get; set; }
[Column("fullname")]
public string FullName { get; set; }
[Column("is_responsible")]
public bool IsResponsible { get; set; }
[Column("tenure_id")]
public Guid TenureId { get; set; }
public DmTenureDbEntity TenureDbEntity { get; set; }
}
}
|
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
namespace ShaderForge {
[System.Serializable]
public class SF_Node_Arithmetic : SF_Node {
public void PrepareArithmetic(int inputCount = 2, ValueType inputType = ValueType.VTvPending, ValueType outputType = ValueType.VTvPending) {
base.showColor = true;
UseLowerReadonlyValues( true );
if( inputCount == 2 ) {
connectors = new SF_NodeConnector[]{
SF_NodeConnector.Create( this, "OUT", "", ConType.cOutput, outputType, false ),
SF_NodeConnector.Create( this, "A", "A", ConType.cInput, inputType, false ).SetRequired( true ),
SF_NodeConnector.Create( this, "B", "B", ConType.cInput, inputType, false ).SetRequired( true )};
base.conGroup = ScriptableObject.CreateInstance<SFNCG_Arithmetic>().Initialize( connectors[0], connectors[1], connectors[2] );
} else if( inputCount == 1 ){
connectors = new SF_NodeConnector[]{
SF_NodeConnector.Create( this, "OUT", "", ConType.cOutput, outputType, false ),
SF_NodeConnector.Create( this, "IN", "", ConType.cInput, inputType, false ).SetRequired( true )};
base.conGroup = ScriptableObject.CreateInstance<SFNCG_Arithmetic>().Initialize( connectors[0], connectors[1]);
}
}
public override int GetEvaluatedComponentCount() {
int max = 0;
foreach(SF_NodeConnector con in connectors){
if( con.conType == ConType.cOutput || !con.IsConnected()) // Only connected ones, for now
continue;
//Debug.Log("GetEvaluatedComponentCount from node " + nodeName + " [" + con.label + "] cc = " + con.GetCompCount());
max = Mathf.Max( max, con.GetCompCount() );
}
return max;
}
public override bool IsUniformOutput() {
if(InputsConnected()){
if( connectors.Length > 2)
return ( GetInputData( "A" ).uniform && GetInputData( "B" ).uniform );
return ( GetInputData( "IN" ).uniform );
}
return true;
}
// New system
public override void RefreshValue() {
if( connectors.Length == 3 )
RefreshValue( 1, 2 );
else
RefreshValue( 1, 1 );
}
}
} |
namespace Dx.Runtime.Tests.Data
{
public class NonDistributedObject : BaseType
{
public NonDistributedObject() : base(new OtherType())
{
}
}
}
|
using SAPbobsCOM;
using SAPDIExamples.Extensions;
using System;
using System.Collections.Generic;
namespace SAPDIExamples.Handlers
{
/// <summary>
/// Business partner handler
/// </summary>
public class BusinessPartners
{
/// <summary>
/// Load first 5 business partners
/// </summary>
/// <param name="db">Database connection</param>
/// <returns>Business partners list data</returns>
public List<Dictionary<string, string>> LoadAll(DBConnection db)
{
db.SQLCommand.CommandText =
@"SELECT TOP 5 [CardCode], [CardName], [CardType], [LicTradNum]
FROM [OCRD]
ORDER BY [CardCode]";
return db.CreateDataTable().ToList();
}
/// <summary>
/// Load single record to load
/// </summary>
/// <param name="db">Database connection</param>
/// <returns>Attributes for C1111 customer</returns>
public Dictionary<string, string> LoadSingle(DBConnection db)
{
return LoadByCode(db, "C1111");
}
/// <summary>
/// Load single record to load
/// </summary>
/// <param name="db">Database connection</param>
/// <param name="code">Code to load</param>
/// <returns>Attributes for C1111 customer</returns>
public Dictionary<string, string> LoadByCode(DBConnection db, string code)
{
db.SQLCommand.CommandText =
@"SELECT [CardCode], [CardName], [CardType], [LicTradNum]
FROM [OCRD]
WHERE [CardCode] = @code";
db.SQLCommand.Parameters.Add("@code", System.Data.SqlDbType.VarChar, 15).Value = code;
return db.CreateDataTable().ToList().First();
}
/// <summary>
/// Create a new business partner
/// </summary>
/// <param name="sap">SAP connection</param>
/// <param name="cardCode">Card code</param>
/// <param name="cardName">Card name</param>
/// <param name="cardType">Card type</param>
/// <param name="licTradeNumber">Lic trade number</param>
/// <returns>Retrieve new object key</returns>
public string Create(
SAPConnection sap,
string cardCode,
string cardName,
string licTradeNumber,
BoCardTypes cardType)
{
IBusinessPartners partner = sap.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners);
partner.CardCode = cardCode;
partner.CardName = cardName;
partner.CardType = cardType;
partner.FederalTaxID = licTradeNumber;
sap.CheckResponse(partner.Add());
return sap.Company.GetNewObjectKey();
}
/// <summary>
/// Delete SAP record if exist
/// </summary>
/// <param name="sap">SAP connection</param>
/// <param name="key">Key to delete</param>
/// <returns></returns>
public bool Delete(SAPConnection sap, string key)
{
IBusinessPartners partner = sap.Company.GetBusinessObject(BoObjectTypes.oBusinessPartners);
if (partner.GetByKey(key))
{
sap.CheckResponse(partner.Remove());
return true;
}
return false;
}
}
}
|
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace Google.Protobuf.Collections
{
/// <summary>
/// The contents of a repeated field: essentially, a collection with some extra
/// restrictions (no null values) and capabilities (deep cloning).
/// </summary>
/// <remarks>
/// This implementation does not generally prohibit the use of types which are not
/// supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases.
/// </remarks>
/// <typeparam name="T">The element type of the repeated field.</typeparam>
public sealed class RepeatedField<T> : IList<T>, IList
{
private static readonly T[] EmptyArray = new T[0];
private const int MinArraySize = 8;
private T[] array = EmptyArray;
private int count = 0;
/// <summary>
/// Adds the entries from the given input stream, decoding them with the specified codec.
/// </summary>
/// <param name="input">The input stream to read from.</param>
/// <param name="codec">The codec to use in order to read each entry.</param>
public void AddEntriesFrom(CodedInputStream input, FieldCodec<T> codec)
{
// TODO: Inline some of the Add code, so we can avoid checking the size on every
// iteration.
uint tag = input.LastTag;
var reader = codec.ValueReader;
// Non-nullable value types can be packed or not.
if (FieldCodec<T>.IsPackedRepeatedField(tag))
{
int length = input.ReadLength();
if (length > 0)
{
int oldLimit = input.PushLimit(length);
while (!input.ReachedLimit)
{
Add(reader(input));
}
input.PopLimit(oldLimit);
}
// Empty packed field. Odd, but valid - just ignore.
}
else
{
// Not packed... (possibly not packable)
do
{
Add(reader(input));
} while (input.MaybeConsumeTag(tag));
}
}
/// <summary>
/// Calculates the size of this collection based on the given codec.
/// </summary>
/// <param name="codec">The codec to use when encoding each field.</param>
/// <returns>The number of bytes that would be written to a <see cref="CodedOutputStream"/> by <see cref="WriteTo"/>,
/// using the same codec.</returns>
public int CalculateSize(FieldCodec<T> codec)
{
if (count == 0)
{
return 0;
}
uint tag = codec.Tag;
if (codec.PackedRepeatedField)
{
int dataSize = CalculatePackedDataSize(codec);
return CodedOutputStream.ComputeRawVarint32Size(tag) +
CodedOutputStream.ComputeLengthSize(dataSize) +
dataSize;
}
else
{
var sizeCalculator = codec.ValueSizeCalculator;
int size = count * CodedOutputStream.ComputeRawVarint32Size(tag);
for (int i = 0; i < count; i++)
{
size += sizeCalculator(array[i]);
}
return size;
}
}
private int CalculatePackedDataSize(FieldCodec<T> codec)
{
int fixedSize = codec.FixedSize;
if (fixedSize == 0)
{
var calculator = codec.ValueSizeCalculator;
int tmp = 0;
for (int i = 0; i < count; i++)
{
tmp += calculator(array[i]);
}
return tmp;
}
else
{
return fixedSize * Count;
}
}
/// <summary>
/// Writes the contents of this collection to the given <see cref="CodedOutputStream"/>,
/// encoding each value using the specified codec.
/// </summary>
/// <param name="output">The output stream to write to.</param>
/// <param name="codec">The codec to use when encoding each value.</param>
public void WriteTo(CodedOutputStream output, FieldCodec<T> codec)
{
if (count == 0)
{
return;
}
var writer = codec.ValueWriter;
var tag = codec.Tag;
if (codec.PackedRepeatedField)
{
// Packed primitive type
uint size = (uint)CalculatePackedDataSize(codec);
output.WriteTag(tag);
output.WriteRawVarint32(size);
for (int i = 0; i < count; i++)
{
writer(output, array[i]);
}
}
else
{
// Not packed: a simple tag/value pair for each value.
// Can't use codec.WriteTagAndValue, as that omits default values.
for (int i = 0; i < count; i++)
{
output.WriteTag(tag);
writer(output, array[i]);
}
}
}
private void EnsureSize(int size)
{
if (array.Length < size)
{
size = Math.Max(size, MinArraySize);
int newSize = Math.Max(array.Length * 2, size);
var tmp = new T[newSize];
Array.Copy(array, 0, tmp, 0, array.Length);
array = tmp;
}
}
/// <summary>
/// Adds the specified item to the collection.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(T item)
{
ProtoPreconditions.CheckNotNullUnconstrained(item, "item");
EnsureSize(count + 1);
array[count++] = item;
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public void Clear()
{
array = EmptyArray;
count = 0;
}
/// <summary>
/// Determines whether this collection contains the given item.
/// </summary>
/// <param name="item">The item to find.</param>
/// <returns><c>true</c> if this collection contains the given item; <c>false</c> otherwise.</returns>
public bool Contains(T item)
{
return IndexOf(item) != -1;
}
/// <summary>
/// Copies this collection to the given array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">The first index of the array to copy to.</param>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(this.array, 0, array, arrayIndex, count);
}
/// <summary>
/// Removes the specified item from the collection
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns><c>true</c> if the item was found and removed; <c>false</c> otherwise.</returns>
public bool Remove(T item)
{
int index = IndexOf(item);
if (index == -1)
{
return false;
}
Array.Copy(array, index + 1, array, index, count - index - 1);
count--;
array[count] = default(T);
return true;
}
/// <summary>
/// Gets the number of elements contained in the collection.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Adds all of the specified values into this collection.
/// </summary>
/// <param name="values">The values to add to this collection.</param>
public void AddRange(IEnumerable<T> values)
{
ProtoPreconditions.CheckNotNull(values, "values");
// Optimization 1: If the collection we're adding is already a RepeatedField<T>,
// we know the values are valid.
var otherRepeatedField = values as RepeatedField<T>;
if (otherRepeatedField != null)
{
EnsureSize(count + otherRepeatedField.count);
Array.Copy(otherRepeatedField.array, 0, array, count, otherRepeatedField.count);
count += otherRepeatedField.count;
return;
}
// Optimization 2: The collection is an ICollection, so we can expand
// just once and ask the collection to copy itself into the array.
var collection = values as ICollection;
if (collection != null)
{
var extraCount = collection.Count;
// For reference types and nullable value types, we need to check that there are no nulls
// present. (This isn't a thread-safe approach, but we don't advertise this is thread-safe.)
// We expect the JITter to optimize this test to true/false, so it's effectively conditional
// specialization.
if (default(T) == null)
{
// TODO: Measure whether iterating once to check and then letting the collection copy
// itself is faster or slower than iterating and adding as we go. For large
// collections this will not be great in terms of cache usage... but the optimized
// copy may be significantly faster than doing it one at a time.
foreach (var item in collection)
{
if (item == null)
{
throw new ArgumentException("Sequence contained null element", "values");
}
}
}
EnsureSize(count + extraCount);
collection.CopyTo(array, count);
count += extraCount;
return;
}
// We *could* check for ICollection<T> as well, but very very few collections implement
// ICollection<T> but not ICollection. (HashSet<T> does, for one...)
// Fall back to a slower path of adding items one at a time.
foreach (T item in values)
{
Add(item);
}
}
/// <summary>
/// Adds all of the specified values into this collection. This method is present to
/// allow repeated fields to be constructed from queries within collection initializers.
/// Within non-collection-initializer code, consider using the equivalent <see cref="AddRange"/>
/// method instead for clarity.
/// </summary>
/// <param name="values">The values to add to this collection.</param>
public void Add(IEnumerable<T> values)
{
AddRange(values);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < count; i++)
{
yield return array[i];
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return Equals(obj as RepeatedField<T>);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 0;
for (int i = 0; i < count; i++)
{
hash = hash * 31 + array[i].GetHashCode();
}
return hash;
}
/// <summary>
/// Compares this repeated field with another for equality.
/// </summary>
/// <param name="other">The repeated field to compare this with.</param>
/// <returns><c>true</c> if <paramref name="other"/> refers to an equal repeated field; <c>false</c> otherwise.</returns>
public bool Equals(RepeatedField<T> other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(other, this))
{
return true;
}
if (other.Count != this.Count)
{
return false;
}
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < count; i++)
{
if (!comparer.Equals(array[i], other.array[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the index of the given item within the collection, or -1 if the item is not
/// present.
/// </summary>
/// <param name="item">The item to find in the collection.</param>
/// <returns>The zero-based index of the item, or -1 if it is not found.</returns>
public int IndexOf(T item)
{
ProtoPreconditions.CheckNotNullUnconstrained(item, "item");
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < count; i++)
{
if (comparer.Equals(array[i], item))
{
return i;
}
}
return -1;
}
/// <summary>
/// Inserts the given item at the specified index.
/// </summary>
/// <param name="index">The index at which to insert the item.</param>
/// <param name="item">The item to insert.</param>
public void Insert(int index, T item)
{
ProtoPreconditions.CheckNotNullUnconstrained(item, "item");
if (index < 0 || index > count)
{
throw new ArgumentOutOfRangeException("index");
}
EnsureSize(count + 1);
Array.Copy(array, index, array, index + 1, count - index);
array[index] = item;
count++;
}
/// <summary>
/// Removes the item at the given index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
if (index < 0 || index >= count)
{
throw new ArgumentOutOfRangeException("index");
}
Array.Copy(array, index + 1, array, index, count - index - 1);
count--;
array[count] = default(T);
}
/// <summary>
/// Gets or sets the item at the specified index.
/// </summary>
/// <value>
/// The element at the specified index.
/// </value>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <returns>The item at the specified index.</returns>
public T this[int index]
{
get
{
if (index < 0 || index >= count)
{
throw new ArgumentOutOfRangeException("index");
}
return array[index];
}
set
{
if (index < 0 || index >= count)
{
throw new ArgumentOutOfRangeException("index");
}
ProtoPreconditions.CheckNotNullUnconstrained(value, "value");
array[index] = value;
}
}
#region Explicit interface implementation for IList and ICollection.
bool IList.IsFixedSize
{
get
{
return false;
}
}
void ICollection.CopyTo(Array array, int index)
{
Array.Copy(this.array, 0, array, index, count);
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return this;
}
}
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (T)value; }
}
int IList.Add(object value)
{
Add((T)value);
return count - 1;
}
bool IList.Contains(object value)
{
return (value is T && Contains((T)value));
}
int IList.IndexOf(object value)
{
if (!(value is T))
{
return -1;
}
return IndexOf((T)value);
}
void IList.Insert(int index, object value)
{
Insert(index, (T)value);
}
void IList.Remove(object value)
{
if (!(value is T))
{
return;
}
Remove((T)value);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using Grasshopper.Kernel;
using Rhino.Geometry;
namespace Angelfish
{
public class GhcCalculateRegions : GH_Component
{
int currentI;
Gradient gradient;
public GhcCalculateRegions()
: base("Calculate Regions", "Regions",
"Calulates the Grey Scott Reaction Diffusion pattern on points or vertices in a region",
"Angelfish", "2.Calculate")
{
}
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddGenericParameter("Gradient", "Gradient", "Gradient", GH_ParamAccess.item);
pManager.AddBooleanParameter("Solid Arround", "Solid", "Solid Arround", GH_ParamAccess.item, true);
pManager.AddIntegerParameter("Iterations", "Iterations", "Iterations of calculation", GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddGenericParameter("RD", "RD", "RD", GH_ParamAccess.item);
pManager.AddNumberParameter("PrintOut", "PrintOut", "PrintOut", GH_ParamAccess.list);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
int iterations = 0;
DA.GetData("Iterations", ref iterations);
currentI = 0;
gradient = null;
DA.GetData(0, ref gradient);
bool solid = true;
DA.GetData(1, ref solid);
while (currentI < iterations)
{
for (int i = 0; i < gradient.regions.Count; i++)
{
gradient.regions[i].Update();
}
currentI++;
}
Pattern outPattern = new Pattern(gradient.Apoints);
for (int i = 0; i < outPattern.Apoints.Count; i++)
{
if (solid) outPattern.a[i] = 0.0;
else outPattern.a[i] = 1.0;
}
for (int i = 0; i < gradient.regions.Count; i++)
{
for (int j = 0; j < gradient.regions[i].Apoints.Count; j++)
{
int current = gradient.regions[i].Apoints[j].Index;
outPattern.Apoints[current] = gradient.regions[i].Apoints[j];
outPattern.a[current] = gradient.regions[i].a[j];
}
}
DA.SetData(0, outPattern);
}
protected override System.Drawing.Bitmap Icon
{
get
{
//You can add image files to your project resources and access them like this:
// return Resources.IconForThisComponent;
return null;
}
}
/// <summary>
/// Gets the unique ID for this component. Do not change this ID after release.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("9b197e54-28c6-4b5a-b381-6903ba7ca00e"); }
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace NaiveSocketImplementation
{
class Program
{
private const short PORT = 6568;
private static TcpListener listener;
static void Main(string[] args)
{
TcpClient tcpclient = ListenForClient();
try
{
ReadDataFromClient(tcpclient);
}
catch (IOException ioex)
{
Console.WriteLine("Ex1: " + ioex.Message);
}
catch (SocketException sex)
{
Console.WriteLine("Ex2: " + sex.Message);
}
finally
{
CloseConnection(tcpclient);
}
}
private static void ReadDataFromClient(TcpClient tcpclient)
{
var nwStream = tcpclient.GetStream();
var buffer = new byte[4096];
int i = 0;
string message = "";
while ((i = nwStream.Read(buffer, 0, buffer.Length)) != 0)
{
message = Encoding.UTF8.GetString(buffer, 0, i);
Console.WriteLine("Recieved {0}", message);
}
}
private static TcpClient ListenForClient()
{
listener = new TcpListener(IPAddress.Any, PORT);
Console.WriteLine("Listening on port: {0}", PORT);
listener.Start();
return listener.AcceptTcpClient();
}
private static void CloseConnection(TcpClient client)
{
client.Close();
listener.Stop();
client = null;
listener = null;
}
}
}
|
using AutoMapper;
using Contracts;
using Contracts.Services;
using Entities.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class UserChatService : IUserChatService
{
private readonly IRepositoryManager _repository;
private readonly IMapper _mapper;
public UserChatService(IRepositoryManager repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
public async Task Update(Chat chat)
{
_repository.UserChats.Up(chat);
await _repository.SaveAsync();
}
public async Task<Chat> TryGet(string chatName, IEnumerable<User> users)
{
var user = users.FirstOrDefault();
if (user == null)
return null;
var chats = await _repository.UserChats.GetUserChatsAsync(false);
var chatFromDb = chats.FirstOrDefault(c => c.Name == chatName && c.Users.Contains(user));
return chatFromDb;
}
public async Task Create(Chat chat)
{
await _repository.UserChats.Add(chat);
await _repository.SaveAsync();
}
}
}
|
namespace Core3.Sagas.Timeouts
{
public class MyCustomTimeout
{
}
} |
using System.Linq;
using ProjectEuler.Maths;
using ProjectEuler.Problems;
namespace ProjectEuler
{
//The prime factors of 13195 are 5, 7, 13 and 29.
//
//What is the largest prime factor of the number 600851475143?
public class Problem3 : IProblem
{
public long Solve()
{
var primeFactors = new PrimeFactorsList(600851475143);
return primeFactors.Max();
}
}
} |
using System.Diagnostics;
using UnityEditor;
public static class OpenConfigFileLocationMenuItem
{
[MenuItem("Ultraleap/Reach/Open Config File Location")]
static void _OpenConfigFileLocation()
{
Process.Start(PhysicalConfigurable.ConfigFileDirectory);
}
}
|
using System;
using System.IO;
using RoxieMobile.CSharpCommons.Extensions;
using Xunit.Sdk;
namespace RoxieMobile.CSharpCommons.Diagnostics.UnitTests.Diagnostics
{
public partial class CheckTests
{
// MARK: - Private Methods
protected void CheckThrowsException(string method, Type classOfT, Action action)
{
CheckArgument(!string.IsNullOrEmpty(method), () => $"{nameof(method)} is empty");
CheckArgument(classOfT != null, () => $"{nameof(classOfT)} is null");
CheckArgument(action != null, () => $"{nameof(action)} is null");
Exception? cause = null;
try {
action?.Invoke();
}
catch (Exception e) {
cause = e;
}
if (cause != null) {
if (cause.GetType() == classOfT) {
// Do nothing
}
else {
throw new XunitException($"{method}: Unknown exception is thrown");
}
}
else {
throw new XunitException($"{method}: Method not thrown an exception");
}
}
protected void CheckThrowsException(string method, Action action) =>
CheckThrowsException(method, typeof(CheckException), action);
// --
protected void CheckNotThrowsException(string method, Type classOfT, Action action)
{
CheckArgument(!string.IsNullOrEmpty(method), () => $"{nameof(method)} is empty");
CheckArgument(classOfT != null, () => $"{nameof(classOfT)} is null");
CheckArgument(action != null, () => $"{nameof(action)} is null");
Exception? cause = null;
try {
action?.Invoke();
}
catch (Exception e) {
cause = e;
}
if (cause != null) {
if (cause.GetType() == classOfT) {
throw new XunitException($"{method}: Method thrown an exception");
}
else {
throw new XunitException($"{method}: Unknown exception is thrown");
}
}
else {
// Do nothing
}
}
protected void CheckNotThrowsException(string method, Action action) =>
CheckNotThrowsException(method, typeof(CheckException), action);
// --
protected void CheckArgument(bool condition, Func<string> block)
{
if (condition) {
return;
}
if (block == null) {
throw new ArgumentNullException(nameof(block));
}
throw new ArgumentException(block());
}
// MARK: - Private Methods
protected string LoadJsonString(string filename)
{
if (filename.IsEmpty()) {
throw new ArgumentException(nameof(filename));
}
var fixturePath = $"Fixtures/{filename}.json";
var filePath = Path.Combine(AppContext.BaseDirectory, fixturePath);
return File.ReadAllText(filePath);
}
}
}
|
/*===================================================================================
*
* Copyright (c) Userware/OpenSilver.net
*
* This file is part of the OpenSilver Runtime (https://opensilver.net), which is
* licensed under the MIT license: https://opensource.org/licenses/MIT
*
* As stated in the MIT license, "the above copyright notice and this permission
* notice shall be included in all copies or substantial portions of the Software."
*
\*====================================================================================*/
#if MIGRATION
using System.Windows;
#else
using Windows.UI.Xaml;
#endif
namespace Microsoft.Expression.Media.Effects
{
/// <summary>
/// Transition effect that waves the current visual while introducing the new visual.
/// </summary>
public sealed class WaveTransitionEffect : TransitionEffect
{
/// <summary>
/// Dependency property that modifies the Frequency variable within the pixel shader.
/// </summary>
public static readonly DependencyProperty FrequencyProperty =
DependencyProperty.Register(
nameof(Frequency),
typeof(double),
typeof(WaveTransitionEffect),
new PropertyMetadata(20.0));
/// <summary>
/// Dependency property that modifies the Magnitude variable within the pixel shader.
/// </summary>
public static readonly DependencyProperty MagnitudeProperty =
DependencyProperty.Register(
nameof(Magnitude),
typeof(double),
typeof(WaveTransitionEffect),
new PropertyMetadata(0.1));
/// <summary>
/// Dependency property that modifies the Phase variable within the pixel shader.
/// </summary>
public static readonly DependencyProperty PhaseProperty =
DependencyProperty.Register(
nameof(Phase),
typeof(double),
typeof(WaveTransitionEffect),
new PropertyMetadata(14.0));
/// <summary>
/// Creates an instance of the shader.
/// </summary>
public WaveTransitionEffect() { }
/// <summary>
/// Gets or sets the magnitude of the wave.
/// </summary>
public double Frequency
{
get => (double)GetValue(FrequencyProperty);
set => SetValue(FrequencyProperty, value);
}
/// <summary>
/// Gets or sets the magnitude of the wave.
/// </summary>
public double Magnitude
{
get => (double)GetValue(MagnitudeProperty);
set => SetValue(MagnitudeProperty, value);
}
/// <summary>
/// Gets or sets the phase of the wave.
/// </summary>
public double Phase
{
get => (double)GetValue(PhaseProperty);
set => SetValue(PhaseProperty, value);
}
/// <summary>
/// Makes a deep copy of the WaveTransitionEffect effect.
/// </summary>
/// <returns>
/// A clone of the current instance of the WaveTransitionEffect effect.
/// </returns>
protected override TransitionEffect DeepCopy()
{
return new WaveTransitionEffect
{
Frequency = Frequency,
Magnitude = Magnitude,
Phase = Phase,
};
}
}
}
|
using System;
using System.Collections.Generic;
namespace FarseerGames.FarseerPhysics.Dynamics
{
/// <summary>
/// Provides an implementation of a strongly typed List with Arbiter
/// </summary>
public class ArbiterList : List<Arbiter>
{
private List<Arbiter> _markedForRemovalList;
public ArbiterList()
{
_markedForRemovalList = new List<Arbiter>();
}
public void ForEachSafe(Action<Arbiter> action)
{
for (int i = 0; i < Count; i++)
{
action(this[i]);
}
}
public void RemoveAllSafe(Predicate<Arbiter> match)
{
for (int i = 0; i < Count; i++)
{
if (match(this[i]))
{
_markedForRemovalList.Add(this[i]);
}
}
for (int j = 0; j < _markedForRemovalList.Count; j++)
{
Remove(_markedForRemovalList[j]);
_markedForRemovalList[j].Reset();
}
_markedForRemovalList.Clear();
}
public void RemoveContactCountEqualsZero(Pool<Arbiter> arbiterPool)
{
for (int i = 0; i < Count; i++)
{
if (ContactCountEqualsZero(this[i]))
{
_markedForRemovalList.Add(this[i]);
}
}
for (int j = 0; j < _markedForRemovalList.Count; j++)
{
Remove(_markedForRemovalList[j]);
arbiterPool.Insert(_markedForRemovalList[j]);
if (_markedForRemovalList[j].GeometryA.OnSeparation != null)
{
_markedForRemovalList[j].GeometryA.OnSeparation(_markedForRemovalList[j].GeometryA,
_markedForRemovalList[j].GeometryB);
}
if (_markedForRemovalList[j].GeometryB.OnSeparation != null)
{
_markedForRemovalList[j].GeometryB.OnSeparation(_markedForRemovalList[j].GeometryB,
_markedForRemovalList[j].GeometryA);
}
}
_markedForRemovalList.Clear();
}
public void RemoveContainsDisposedBody(Pool<Arbiter> arbiterPool)
{
for (int i = 0; i < Count; i++)
{
if (ContainsDisposedBody(this[i]))
{
_markedForRemovalList.Add(this[i]);
}
}
for (int j = 0; j < _markedForRemovalList.Count; j++)
{
Remove(_markedForRemovalList[j]);
arbiterPool.Insert(_markedForRemovalList[j]);
}
_markedForRemovalList.Clear();
}
internal static bool ContactCountEqualsZero(Arbiter a)
{
return a.ContactCount == 0;
}
internal static bool ContainsDisposedBody(Arbiter a)
{
return a.ContainsDisposedGeom();
}
}
} |
namespace App.Infrastructure.Security
{
public class SecurityKeys
{
public const string Issuer = "tokenIssuer";
}
} |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Simple.Web.MediaTypeHandling;
using Simple.Web.TestHelpers;
using Simple.Web.TestHelpers.Sample;
using Simple.Web.TestHelpers.Xml;
using Xunit;
namespace Simple.Web.Xml.Tests
{
public class DataContractXmlContentTypeHandlerTests
{
[Fact]
public void SerializesOrder()
{
var content = new Content(new Uri("http://test.com/order/42"), new OrderHandler(),
new Order {Id = 54, CustomerId = 42});
var target = new DataContractXmlMediaTypeHandler();
string actual;
using (var stream = new StringBuilderStream())
{
target.Write<Order>(content, stream).Wait();
actual = stream.StringValue;
}
Assert.NotNull(actual);
const string expected =
"<Order xmlns='http://schemas.datacontract.org/2004/07/Simple.Web.TestHelpers.Sample'" +
" xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
" <CustomerId>42</CustomerId>" +
" <Id>54</Id>" +
" <link href='/order/54' rel='self' type='application/vnd.order+xml' xmlns='' />" +
"</Order>";
XElement.Parse(actual).ShouldEqual(expected);
}
[Fact]
public void PicksUpOrdersLinkFromCustomer()
{
var content = new Content(new Uri("http://test.com/customer/42"), new CustomerHandler(),
new Customer {Id = 42});
var target = new DataContractXmlMediaTypeHandler();
string actual;
using (var stream = new StringBuilderStream())
{
target.Write<Customer>(content, stream).Wait();
actual = stream.StringValue;
}
Assert.NotNull(actual);
const string expected = "<?xml version='1.0' encoding='utf-8'?>" +
"<Customer xmlns='http://schemas.datacontract.org/2004/07/Simple.Web.TestHelpers.Sample'" +
" xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
" <Id>42</Id>" +
" <Orders i:nil='true' />" +
" <link href='/customer/42/contacts' rel='customer.contacts' type='application/vnd.contact+xml' xmlns='' />" +
" <link href='/customer/42/orders' rel='customer.orders' type='application/vnd.list.order+xml' xmlns='' />" +
" <link href='/customer/42' rel='self' type='application/vnd.customer+xml' xmlns='' />" +
"</Customer>";
XElement.Parse(actual).ShouldEqual(expected);
}
[Fact]
public void PicksUpOrdersLinkFromCustomers()
{
var content = new Content(new Uri("http://test.com/customer/42"), new CustomerHandler(),
new[] {new Customer {Id = 42}});
var target = new DataContractXmlMediaTypeHandler();
string actual;
using (var stream = new StringBuilderStream())
{
target.Write<IEnumerable<Customer>>(content, stream).Wait();
actual = stream.StringValue;
}
Assert.NotNull(actual);
const string expected = "<?xml version='1.0' encoding='utf-8'?>" +
"<Customers>" +
" <Customer xmlns='http://schemas.datacontract.org/2004/07/Simple.Web.TestHelpers.Sample'" +
" xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
" <Id>42</Id>" +
" <Orders i:nil='true' />" +
" <link href='/customer/42/contacts' rel='customer.contacts' type='application/vnd.contact+xml' xmlns='' />" +
" <link href='/customer/42/orders' rel='customer.orders' type='application/vnd.list.order+xml' xmlns='' />" +
" <link href='/customer/42' rel='self' type='application/vnd.customer+xml' xmlns='' />" +
" </Customer>" +
"</Customers>";
XElement.Parse(actual).ShouldEqual(expected);
}
}
} |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPromotion
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPromotion() : base()
{
FormClosed += frmPromotion_FormClosed;
KeyPress += frmPromotion_KeyPress;
Resize += frmPromotion_Resize;
Load += frmPromotion_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public DateTimePicker _DTFields_3;
public DateTimePicker _DTFields_2;
public System.Windows.Forms.CheckBox _chkFields_2;
private System.Windows.Forms.Button withEventsField_cmdDelete;
public System.Windows.Forms.Button cmdDelete {
get { return withEventsField_cmdDelete; }
set {
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click -= cmdDelete_Click;
}
withEventsField_cmdDelete = value;
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click += cmdDelete_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdAdd;
public System.Windows.Forms.Button cmdAdd {
get { return withEventsField_cmdAdd; }
set {
if (withEventsField_cmdAdd != null) {
withEventsField_cmdAdd.Click -= cmdAdd_Click;
}
withEventsField_cmdAdd = value;
if (withEventsField_cmdAdd != null) {
withEventsField_cmdAdd.Click += cmdAdd_Click;
}
}
}
private System.Windows.Forms.ListView withEventsField_lvPromotion;
public System.Windows.Forms.ListView lvPromotion {
get { return withEventsField_lvPromotion; }
set {
if (withEventsField_lvPromotion != null) {
withEventsField_lvPromotion.DoubleClick -= lvPromotion_DoubleClick;
withEventsField_lvPromotion.KeyPress -= lvPromotion_KeyPress;
}
withEventsField_lvPromotion = value;
if (withEventsField_lvPromotion != null) {
withEventsField_lvPromotion.DoubleClick += lvPromotion_DoubleClick;
withEventsField_lvPromotion.KeyPress += lvPromotion_KeyPress;
}
}
}
public System.Windows.Forms.CheckBox _chkFields_1;
public System.Windows.Forms.CheckBox _chkFields_0;
public DateTimePicker _DTFields_0;
private System.Windows.Forms.TextBox withEventsField__txtFields_0;
public System.Windows.Forms.TextBox _txtFields_0 {
get { return withEventsField__txtFields_0; }
set {
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter -= txtFields_Enter;
}
withEventsField__txtFields_0 = value;
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter += txtFields_Enter;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public DateTimePicker _DTFields_1;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label Label1;
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_38;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
//Public WithEvents DTFields As DateTimePicker
//Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPromotion));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._DTFields_3 = new System.Windows.Forms.DateTimePicker();
this._DTFields_2 = new System.Windows.Forms.DateTimePicker();
this._chkFields_2 = new System.Windows.Forms.CheckBox();
this.cmdDelete = new System.Windows.Forms.Button();
this.cmdAdd = new System.Windows.Forms.Button();
this.lvPromotion = new System.Windows.Forms.ListView();
this._chkFields_1 = new System.Windows.Forms.CheckBox();
this._chkFields_0 = new System.Windows.Forms.CheckBox();
this._DTFields_0 = new System.Windows.Forms.DateTimePicker();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this._DTFields_1 = new System.Windows.Forms.DateTimePicker();
this.Label2 = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this._lblLabels_1 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._lbl_5 = new System.Windows.Forms.Label();
//Me.DTFields = New AxDTPickerArray(components)
//Me.chkFields = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this._DTFields_3).BeginInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_2).BeginInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_0).BeginInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_1).BeginInit();
//CType(Me.DTFields, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.chkFields, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Edit Promotion Details";
this.ClientSize = new System.Drawing.Size(455, 460);
this.Location = new System.Drawing.Point(73, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPromotion";
//_DTFields_3.OcxState = CType(resources.GetObject("_DTFields_3.OcxState"), System.Windows.Forms.AxHost.State)
this._DTFields_3.Size = new System.Drawing.Size(130, 21);
this._DTFields_3.Location = new System.Drawing.Point(291, 112);
this._DTFields_3.TabIndex = 20;
this._DTFields_3.Name = "_DTFields_3";
//_DTFields_2.OcxState = CType(resources.GetObject("_DTFields_2.OcxState"), System.Windows.Forms.AxHost.State)
this._DTFields_2.Size = new System.Drawing.Size(130, 21);
this._DTFields_2.Location = new System.Drawing.Point(104, 112);
this._DTFields_2.TabIndex = 19;
this._DTFields_2.Name = "_DTFields_2";
this._chkFields_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._chkFields_2.Text = "Only for Specific Time";
this._chkFields_2.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_2.Size = new System.Drawing.Size(151, 17);
this._chkFields_2.Location = new System.Drawing.Point(270, 152);
this._chkFields_2.TabIndex = 16;
this._chkFields_2.CausesValidation = true;
this._chkFields_2.Enabled = true;
this._chkFields_2.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_2.Appearance = System.Windows.Forms.Appearance.Normal;
this._chkFields_2.TabStop = true;
this._chkFields_2.CheckState = System.Windows.Forms.CheckState.Unchecked;
this._chkFields_2.Visible = true;
this._chkFields_2.Name = "_chkFields_2";
this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdDelete.Text = "&Delete";
this.cmdDelete.Size = new System.Drawing.Size(94, 25);
this.cmdDelete.Location = new System.Drawing.Point(352, 176);
this.cmdDelete.TabIndex = 14;
this.cmdDelete.TabStop = false;
this.cmdDelete.BackColor = System.Drawing.SystemColors.Control;
this.cmdDelete.CausesValidation = true;
this.cmdDelete.Enabled = true;
this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdDelete.Name = "cmdDelete";
this.cmdAdd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdAdd.Text = "&Add";
this.cmdAdd.Size = new System.Drawing.Size(94, 25);
this.cmdAdd.Location = new System.Drawing.Point(2, 176);
this.cmdAdd.TabIndex = 13;
this.cmdAdd.TabStop = false;
this.cmdAdd.BackColor = System.Drawing.SystemColors.Control;
this.cmdAdd.CausesValidation = true;
this.cmdAdd.Enabled = true;
this.cmdAdd.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdAdd.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdAdd.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdAdd.Name = "cmdAdd";
this.lvPromotion.Size = new System.Drawing.Size(445, 250);
this.lvPromotion.Location = new System.Drawing.Point(2, 206);
this.lvPromotion.TabIndex = 11;
this.lvPromotion.View = System.Windows.Forms.View.Details;
this.lvPromotion.LabelWrap = true;
this.lvPromotion.HideSelection = false;
this.lvPromotion.FullRowSelect = true;
this.lvPromotion.GridLines = true;
this.lvPromotion.ForeColor = System.Drawing.SystemColors.WindowText;
this.lvPromotion.BackColor = System.Drawing.SystemColors.Window;
this.lvPromotion.LabelEdit = true;
this.lvPromotion.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lvPromotion.Name = "lvPromotion";
this._chkFields_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._chkFields_1.Text = "Disabled:";
this._chkFields_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_1.Size = new System.Drawing.Size(64, 13);
this._chkFields_1.Location = new System.Drawing.Point(54, 138);
this._chkFields_1.TabIndex = 7;
this._chkFields_1.CausesValidation = true;
this._chkFields_1.Enabled = true;
this._chkFields_1.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_1.Appearance = System.Windows.Forms.Appearance.Normal;
this._chkFields_1.TabStop = true;
this._chkFields_1.CheckState = System.Windows.Forms.CheckState.Unchecked;
this._chkFields_1.Visible = true;
this._chkFields_1.Name = "_chkFields_1";
this._chkFields_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_0.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._chkFields_0.Text = "Apply Only to POS Channel";
this._chkFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_0.Size = new System.Drawing.Size(151, 13);
this._chkFields_0.Location = new System.Drawing.Point(270, 138);
this._chkFields_0.TabIndex = 8;
this._chkFields_0.CausesValidation = true;
this._chkFields_0.Enabled = true;
this._chkFields_0.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_0.Appearance = System.Windows.Forms.Appearance.Normal;
this._chkFields_0.TabStop = true;
this._chkFields_0.CheckState = System.Windows.Forms.CheckState.Unchecked;
this._chkFields_0.Visible = true;
this._chkFields_0.Name = "_chkFields_0";
//_DTFields_0.OcxState = CType(resources.GetObject("_DTFields_0.OcxState"), System.Windows.Forms.AxHost.State)
this._DTFields_0.Size = new System.Drawing.Size(130, 22);
this._DTFields_0.Location = new System.Drawing.Point(105, 87);
this._DTFields_0.TabIndex = 4;
this._DTFields_0.Name = "_DTFields_0";
this._txtFields_0.AutoSize = false;
this._txtFields_0.Size = new System.Drawing.Size(315, 19);
this._txtFields_0.Location = new System.Drawing.Point(105, 66);
this._txtFields_0.TabIndex = 2;
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.CausesValidation = true;
this._txtFields_0.Enabled = true;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.HideSelection = true;
this._txtFields_0.ReadOnly = false;
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.Multiline = false;
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_0.TabStop = true;
this._txtFields_0.Visible = true;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Name = "_txtFields_0";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(455, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 10;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(192, 3);
this.cmdPrint.TabIndex = 15;
this.cmdPrint.TabStop = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(369, 3);
this.cmdClose.TabIndex = 12;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.TabIndex = 9;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
//_DTFields_1.OcxState = CType(resources.GetObject("_DTFields_1.OcxState"), System.Windows.Forms.AxHost.State)
this._DTFields_1.Size = new System.Drawing.Size(130, 22);
this._DTFields_1.Location = new System.Drawing.Point(291, 87);
this._DTFields_1.TabIndex = 6;
this._DTFields_1.Name = "_DTFields_1";
this.Label2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this.Label2.Text = "To Time:";
this.Label2.Size = new System.Drawing.Size(51, 15);
this.Label2.Location = new System.Drawing.Point(238, 116);
this.Label2.TabIndex = 18;
this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label2.Enabled = true;
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.UseMnemonic = true;
this.Label2.Visible = true;
this.Label2.AutoSize = false;
this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label2.Name = "Label2";
this.Label1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this.Label1.Text = "From Time:";
this.Label1.Size = new System.Drawing.Size(57, 17);
this.Label1.Location = new System.Drawing.Point(48, 116);
this.Label1.TabIndex = 17;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_1.Text = "End Date:";
this._lblLabels_1.Size = new System.Drawing.Size(48, 13);
this._lblLabels_1.Location = new System.Drawing.Point(240, 90);
this._lblLabels_1.TabIndex = 5;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Enabled = true;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.UseMnemonic = true;
this._lblLabels_1.Visible = true;
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_1.Name = "_lblLabels_1";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_0.Text = "Start Date:";
this._lblLabels_0.Size = new System.Drawing.Size(51, 13);
this._lblLabels_0.Location = new System.Drawing.Point(52, 90);
this._lblLabels_0.TabIndex = 3;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Enabled = true;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.UseMnemonic = true;
this._lblLabels_0.Visible = true;
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_38.Text = "Promotion Name:";
this._lblLabels_38.Size = new System.Drawing.Size(81, 13);
this._lblLabels_38.Location = new System.Drawing.Point(19, 69);
this._lblLabels_38.TabIndex = 1;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Enabled = true;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.UseMnemonic = true;
this._lblLabels_38.Visible = true;
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_38.Name = "_lblLabels_38";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(415, 112);
this._Shape1_2.Location = new System.Drawing.Point(15, 60);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Text = "&1. General";
this._lbl_5.Size = new System.Drawing.Size(60, 13);
this._lbl_5.Location = new System.Drawing.Point(15, 45);
this._lbl_5.TabIndex = 0;
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this.Controls.Add(_DTFields_3);
this.Controls.Add(_DTFields_2);
this.Controls.Add(_chkFields_2);
this.Controls.Add(cmdDelete);
this.Controls.Add(cmdAdd);
this.Controls.Add(lvPromotion);
this.Controls.Add(_chkFields_1);
this.Controls.Add(_chkFields_0);
this.Controls.Add(_DTFields_0);
this.Controls.Add(_txtFields_0);
this.Controls.Add(picButtons);
this.Controls.Add(_DTFields_1);
this.Controls.Add(Label2);
this.Controls.Add(Label1);
this.Controls.Add(_lblLabels_1);
this.Controls.Add(_lblLabels_0);
this.Controls.Add(_lblLabels_38);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this.Controls.Add(_lbl_5);
this.Controls.Add(ShapeContainer1);
this.picButtons.Controls.Add(cmdPrint);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(cmdCancel);
//Me.DTFields.SetIndex(_DTFields_3, CType(3, Short))
//Me.DTFields.SetIndex(_DTFields_2, CType(2, Short))
//Me.DTFields.SetIndex(_DTFields_0, CType(0, Short))
//Me.DTFields.SetIndex(_DTFields_1, CType(1, Short))
//Me.chkFields.SetIndex(_chkFields_2, CType(2, Short))
//Me.chkFields.SetIndex(_chkFields_1, CType(1, Short))
//Me.chkFields.SetIndex(_chkFields_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short))
//Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
//Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
//Me.txtFields.SetIndex(_txtFields_0, CType(0, Short))
this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.chkFields, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.DTFields, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this._DTFields_1).EndInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_0).EndInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_2).EndInit();
((System.ComponentModel.ISupportInitialize)this._DTFields_3).EndInit();
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
|
using System.Threading.Tasks;
using BK9K.Game.Processors;
using BK9K.Mechanics.Grids;
namespace BK9K.Game.Levels.Processors
{
public class LevelGridProcessor : IProcessor<Level>
{
public int Priority => 2;
public Task Process(Level context)
{
context.Grid = SetupGrid();
return Task.CompletedTask;
}
public Grid SetupGrid()
{
return GridBuilder.Create()
.WithSize(5, 5)
.Build();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using LocalAppVeyor.Engine.Configuration;
namespace LocalAppVeyor.Engine
{
public class MatrixJob
{
public string OperatingSystem { get; }
public string Platform { get; }
public string Configuration { get; }
public IReadOnlyCollection<Variable> Variables { get; }
private string name;
public string Name
{
get
{
if (name != null)
{
return name;
}
if (string.IsNullOrEmpty(OperatingSystem) &&
string.IsNullOrEmpty(Platform) &&
string.IsNullOrEmpty(Configuration) &&
Variables.Count == 0)
{
return "Default Job";
}
var nameParts = new List<string>();
if (!string.IsNullOrEmpty(OperatingSystem))
{
nameParts.Add($"OS: {OperatingSystem}");
}
if (Variables.Count > 0)
{
nameParts.Add($"Environment: {string.Join(", ", Variables.Select(v => v.ToString()))}");
}
if (!string.IsNullOrEmpty(Configuration))
{
nameParts.Add($"Configuration: {Configuration}");
}
if (!string.IsNullOrEmpty(Platform))
{
nameParts.Add($"Platform: {Platform}");
}
return name = string.Join("; ", nameParts);
}
}
public MatrixJob(
string operatingSystem,
IReadOnlyCollection<Variable> variables,
string configuration,
string platform)
{
OperatingSystem = operatingSystem;
Platform = platform;
Configuration = configuration;
Variables = variables ?? new Variable[0];
}
public override string ToString()
{
return Name;
}
}
} |
namespace Sitecore.Plugin.IdentityProvider.Auth0.Configuration
{
public class AppSettings
{
public static readonly string SectionName = "Sitecore:ExternalIdentityProviders:IdentityProviders:Auth0";
public Auth0IdentityProvider Auth0IdentityProvider { get; set; } = new Auth0IdentityProvider();
}
}
|
using System.Diagnostics;
namespace Wolf
{
class InstalledProgram
{
private string programName = "";
private string programVersion = "";
private string programInstDate = "";
private string programUninstallCMD = "";
private bool CanBeUninstalled = true;
public InstalledProgram()
{
}
public InstalledProgram(string name, string version, string date, string UCMD)
{
setProgramName(name);
setProgramVersion(version);
setInstallDate(date);
setUninstallCMD(UCMD);
if ((UCMD == "")||(UCMD == null))
{
CanBeUninstalled = false;
}
}
private void setProgramName(string name)
{
programName = name;
}
private void setProgramVersion(string version)
{
programVersion = version;
}
private void setInstallDate(string date)
{
if ((date != null)&&(date != ""))
{
if (!(date.Contains("/")))
{
date = date.Insert(4, "/");
date = date.Insert(7, "/");
}
}
else
{
date = "Unknown";
}
programInstDate = date;
}
private void setUninstallCMD(string UCMD)
{
if (UCMD != "")
{
programUninstallCMD = UCMD;
}
else
{
programUninstallCMD = "Unknown";
}
}
//Executes a cmd process to use the Uninstall via command line process
//similar to Windows Control Panel.
public void funcUninstall()
{
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "cmd.exe";
procStartInfo.WorkingDirectory = @"C:\";
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.Arguments = "/C \"" + programUninstallCMD + "\"";
Process startProc = Process.Start(procStartInfo);
startProc.WaitForExit();
}
public string getProgramName()
{
return programName;
}
public string getProgramVersion()
{
return programVersion;
}
public string getProgramInstallDate()
{
return programInstDate;
}
public string getUninstallCommand()
{
return programUninstallCMD;
}
public bool IsProgramUninstallable()
{
return CanBeUninstalled;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace LINQ_ExtensionsLib
{
/// <summary>
/// Sequence class for Select.
/// </summary>
/// <typeparam name="TSource"> Type of Source. </typeparam>
/// <typeparam name="TResult"> Type of Result. </typeparam>
internal class Sequence<TSource, TResult> : IEnumerable<TResult>
{
/// <summary>
/// Base sequence for this class.
/// </summary>
private IEnumerable<TSource> baseEnumerable;
/// <summary>
/// Selector function.
/// </summary>
private Func<TSource, TResult> selector;
/// <summary>
/// Creates new instance of Sequence class.
/// </summary>
/// <param name="source"> Source. </param>
/// <param name="selector"> Selector. </param>
public Sequence(IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
this.baseEnumerable = source;
this.selector = selector;
}
public IEnumerable<TSource> BaseEnumerable
{
get { return this.baseEnumerable; }
}
/// <summary>
/// Gets enumerator for Sequence class.
/// </summary>
/// <returns> Returns enumerator of Sequence class. </returns>
public IEnumerator<TResult> GetEnumerator()
{
return new Enumerator<TResult>(this);
}
/// <summary>
/// Gets enumerator for Sequence class.
/// </summary>
/// <returns> Returns enumerator of Sequence class. </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Enumerator class for Sequence class.
/// </summary>
/// <typeparam name="T"> Type of generic argument.</typeparam>
class Enumerator<T> : IEnumerator<T>
{
/// <summary>
/// Sequence
/// </summary>
private Sequence<TSource, T> enumerable;
/// <summary>
/// Current element.
/// </summary>
private T current;
/// <summary>
/// Enumerator.
/// </summary>
private IEnumerator<TSource> iterator;
/// <summary>
/// Creates new instance of Enumerator.
/// </summary>
/// <param name="source"> </param>
public Enumerator(Sequence<TSource, T> source)
{
this.enumerable = source;
this.current = default(T);
this.iterator = source.baseEnumerable.GetEnumerator();
}
/// <summary>
/// Gets the current.
/// </summary>
public T Current
{
get { return this.current; }
}
/// <summary>
/// Gets the current.
/// </summary>
object IEnumerator.Current
{
get { return this.current; }
}
/// <summary>
/// Dispose method for Enumerator.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Moves to the next element if it exists.
/// </summary>
/// <returns> Returns true if next element exists. </returns>
public bool MoveNext()
{
while (this.iterator.MoveNext())
{
this.current = this.enumerable.selector(this.iterator.Current);
return true;
}
return false;
}
public void Reset()
{
this.current = default(T);
this.iterator.Reset();
}
}
}
} |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace Client.Pages.Utility
{
public class LogoutBase : ComponentBase
{
[Inject] private NavigationManager NavigationManager { get; set; }
[Inject] private IJSRuntime JSRuntime { get; set; }
protected override async Task OnInitializedAsync()
{
await JSRuntime.InvokeVoidAsync("Logout");
NavigationManager.NavigateTo("/");
}
}
}
|
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;
namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Tree
{
public partial interface IActivePatternId
{
[CanBeNull] IActivePatternCaseDeclaration GetCase(int index);
TreeTextRange GetCasesRange();
}
}
|
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// Constructs an editor populated a list of scenes.
/// </summary>
[CreateAssetMenu]
public class SceneList : ScriptableObject
// Author: Christopher Chamberlain - 2018
{
[SerializeField] private List<SceneField> _scenes;
/// <summary>
/// The collection of scenes.
/// </summary>
public IReadOnlyList<SceneField> Scenes => _scenes;
#if UNITY_EDITOR
[CustomEditor(typeof(SceneList))]
private class SceneListEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Separator();
if (GUILayout.Button(new GUIContent("Apply as Scene Build List")))
{
UpdateEditorBuildList(target as SceneList);
}
}
public static void UpdateEditorBuildList(SceneList data)
{
var scenes = data.Scenes.Select(scene => scene.Path);
// Create a list ( holding existing build scenes )
var buildList = new List<EditorBuildSettingsScene>();
// Append the new scenes
foreach (var scene in scenes.Where(path => !string.IsNullOrEmpty(path)))
{
var sceneToAdd = new EditorBuildSettingsScene(scene, true);
buildList.Add(sceneToAdd);
}
// Write new scenes back to build
EditorBuildSettings.scenes = buildList.ToArray();
}
}
#endif
} |
using SimpleThreadMonitor;
using System;
using System.Collections.Generic;
using System.Text;
namespace EngineIOSharp.Common.Static
{
/// <summary>
/// C# implementation of <see href="https://github.com/unshiftio/yeast">Yeast</see>.
/// </summary>
internal static class EngineIOTimestamp
{
private static readonly object GeneratorMutex = new object();
private static readonly string Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
private static readonly Dictionary<char, int> AlphabetIndex = new Dictionary<char, int>();
private static readonly int AlphabetLength = Alphabet.Length;
private static string PreviousKey = string.Empty;
private static int Seed = 0;
public static string Encode(long Value)
{
StringBuilder Encoded = new StringBuilder();
do
{
Encoded.Insert(0, Alphabet[(int)(Value % AlphabetLength)]);
Value /= AlphabetLength;
} while (Value > 0);
return Encoded.ToString();
}
public static long Decode(string Value)
{
long Decoded = 0;
for (int i = 0; i < Value.Length; i++)
{
Decoded *= AlphabetLength;
Decoded += AlphabetIndex[Value[i]];
}
return Decoded;
}
public static string Generate()
{
string Key = null;
SimpleMutex.Lock(GeneratorMutex, () =>
{
Key = Encode((long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds);
if (!Key.Equals(PreviousKey))
{
Seed = 0;
PreviousKey = Key;
}
else
{
Key = string.Format("{0}.{1}", Key, Encode(Seed++));
}
});
return Key;
}
static EngineIOTimestamp()
{
if (AlphabetIndex.Count == 0)
{
for (int i = 0; i < AlphabetLength; i++)
{
AlphabetIndex[Alphabet[i]] = i;
}
}
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainViewModel.cs" company="PropertyTools">
// Copyright (c) 2014 PropertyTools contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CustomFactoryDemo
{
public class MainViewModel
{
public TestObject TestObject { get; set; }
public CustomPropertyGridControlFactory CustomPropertyGridControlFactory { get; set; }
public CustomPropertyGridOperator CustomPropertyGridOperator { get; set; }
public MainViewModel()
{
this.CustomPropertyGridControlFactory = new CustomPropertyGridControlFactory();
this.CustomPropertyGridOperator = new CustomPropertyGridOperator();
this.TestObject = new TestObject { Title = "Title", Range1 = new Range { Minimum = 0, Maximum = 100 } };
}
}
} |
namespace DotNet.Basics.Tests.Pipelines.PipelineHelpers
{
public class ConcreteClass : AbstractClass
{ }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.