content stringlengths 23 1.05M |
|---|
using System.Collections.Generic;
using Nest;
namespace InvertedIndex
{
public class Importer<T> where T : class
{
private readonly IElasticClient client;
public Importer()
{
client = ElasticClientFactory.CreateElasticClient();
}
public IResponse SendBulk(IEnumerable<T> entities, string indexName)
{
var bulk = MakeBulk(entities, indexName);
var response = client.Bulk(bulk);
return response;
}
public BulkDescriptor MakeBulk(IEnumerable<T> entities, string indexName)
{
var bulkDescriptor = new BulkDescriptor();
foreach (var entity in entities)
{
bulkDescriptor.Index<T>(s => s.Index(indexName).Document(entity));
}
return bulkDescriptor;
}
}
} |
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
//<snippetCustomActivity>
using System;
using System.Activities;
// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk;
// These namespaces are found in the Microsoft.Xrm.Sdk.Workflow.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk.Workflow;
namespace Microsoft.Crm.Sdk.Samples
{
/// <summary>
/// Creates a task with a subject equal to the ID of the input entity.
/// Input arguments:
/// "Input Entity". Type: EntityReference. Is the account entity.
/// Output argument:
/// "Task Created". Type: EntityReference. Is the task created.
/// </summary>
public sealed partial class CustomActivity : CodeActivity
{
/// <summary>
/// Creates a task with a subject equal to the ID of the input EntityReference
/// </summary>
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory =
executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service =
serviceFactory.CreateOrganizationService(context.UserId);
// Retrieve the id
Guid accountId = this.inputEntity.Get(executionContext).Id;
// Create a task entity
Entity task = new Entity();
task.LogicalName = "task";
task["subject"] = accountId.ToString();
task["regardingobjectid"] = new EntityReference("account", accountId);
Guid taskId = service.Create(task);
this.taskCreated.Set(executionContext,
new EntityReference("task", taskId));
}
// Define Input/Output Arguments
[RequiredArgument]
[Input("InputEntity")]
[ReferenceTarget("account")]
public InArgument<EntityReference> inputEntity { get; set; }
[Output("TaskCreated")]
[ReferenceTarget("task")]
public OutArgument<EntityReference> taskCreated { get; set; }
}
}
//</snippetCustomActivity> |
using System;
using UnityEngine;
public enum PlayerActions
{
Jump,
Dodge,
Run,
Attack
}
public class Player : MonoBehaviour
{
public Action OnPlayerJump;
public Action OnPlayerDodge;
public Action OnPlayerRun;
public Action OnPlayerAttack;
public void Jump()
{
OnPlayerJump?.Invoke();
}
public void Dodge()
{
OnPlayerDodge?.Invoke();
}
public void Run()
{
OnPlayerRun?.Invoke();
}
public void Attack()
{
OnPlayerAttack?.Invoke();
}
}
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
using System;
using System.IO;
using NUnit.Framework;
namespace Tangosol.IO.Pof
{
/// <summary>
/// Unit tests of custom serializer/deserialiser.
/// </summary>
/// <author>lh 2011.06.10</author>
[TestFixture]
public class SerializerTest
{
private MemoryStream m_stream;
private DataWriter m_writer;
private PofStreamWriter m_pofwriter;
private DataReader m_reader;
private PofStreamReader m_pofreader;
public void initPOF()
{
initPOFWriter();
initPOFReader();
}
private void initPOFReader()
{
m_stream.Position = 0;
m_reader = new DataReader(m_stream);
m_pofreader = new PofStreamReader(m_reader, new SimplePofContext());
}
private void initPOFWriter()
{
m_stream = new MemoryStream();
m_writer = new DataWriter(m_stream);
m_pofwriter = new PofStreamWriter(m_writer, new SimplePofContext());
}
[Test]
public void testSerialization()
{
String sPath = "config/reference-pof-config.xml";
var ctx = new ConfigurablePofContext(sPath);
var bal = new Balance();
var p = new Product(bal);
var c = new Customer("Customer", p, bal);
bal.setBalance(2.0);
bal.setCustomer(c);
initPOFWriter();
m_pofwriter = new PofStreamWriter(m_writer, ctx);
m_pofwriter.EnableReference();
m_pofwriter.WriteObject(0, c);
initPOFReader();
m_pofreader = new PofStreamReader(m_reader, ctx);
var cResult = (Customer) m_pofreader.ReadObject(0);
Assert.IsTrue(cResult.getProduct().getBalance() == cResult.getBalance());
}
}
} |
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace IIASA.FloodCitiSense.Mobile.Core.Services.Pages
{
public interface IPageService
{
Page MainPage { get; set; }
Task<Page> CreatePage(Type viewType, object navigationParameter);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using zwg_china.model;
namespace zwg_china.logic
{
/// <summary>
/// 用户的登陆信息池
/// </summary>
public class AuthorLoginInfoPond
{
#region 私有字段
/// <summary>
/// 当前已经登陆的用户的登陆信息(私有字段)
/// </summary>
static List<AuthorLoginInfo> infos = new List<AuthorLoginInfo>();
#endregion
#region 静态属性
/// <summary>
/// 当前已经登陆的用户的登陆信息
/// </summary>
public static List<AuthorLoginInfo> Infos
{
get { return infos; }
}
#endregion
#region 静态方法
/// <summary>
/// 声明用户登入
/// </summary>
/// <param name="db">数据库连接对象</param>
/// <param name="userId">用户信息的存储指针</param>
/// <returns>返回身份标识</returns>
public static string AddInfo(IModelToDbContextOfAuthor db, int userId)
{
lock (infos)
{
RemoveInfo(userId);
AuthorLoginInfo info = new AuthorLoginInfo(db, userId);
CallEvent(Logining, info);
infos.Add(info);
CallEvent(Logined, info);
return info.Token;
}
}
/// <summary>
/// 初始化
/// </summary>
public static void Initialize()
{
Timer timer = new Timer(5000);
timer.Elapsed += RemoveInfoOnTimeline;
timer.Start();
}
/// <summary>
/// 保持心跳
/// </summary>
/// <param name="db">数据库连接对象</param>
/// <param name="token">身份标识</param>
public static void KeepHeartbeat(IModelToDbContextOfAuthor db, string token)
{
AuthorLoginInfo info = infos.FirstOrDefault(x => x.Token == token);
if (info == null)
{
throw new Exception("指定的身份标识所标示的用户不存在");
}
info.KeepHeartbeat(db);
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="db">数据库连接对象</param>
/// <param name="token">身份标识</param>
/// <returns>返回用户信息</returns>
public static Author GetUserInfo(IModelToDbContextOfAuthor db, string token)
{
AuthorLoginInfo info = infos.FirstOrDefault(x => x.Token == token);
if (info == null)
{
throw new Exception("指定的身份标识所标示的用户不存在");
}
return info.GetUser(db);
}
#endregion
#region 私有方法
/// <summary>
/// 移除用户登陆信息
/// </summary>
/// <param name="userId">用户的存储指针</param>
static void RemoveInfo(int userId)
{
if (!infos.Any(x => x.UserId == userId)) { return; }
AuthorLoginInfo info = infos.First(x => x.UserId == userId);
CallEvent(Logouting, info);
infos.RemoveAll(x => x.UserId == userId);
CallEvent(Logouted, info);
}
/// <summary>
/// 定时移除已经超时的用户登陆信息
/// </summary>
/// <param name="sender">触发对象</param>
/// <param name="e">传递的数据集</param>
static void RemoveInfoOnTimeline(object sender, ElapsedEventArgs e)
{
lock (infos)
{
infos.Where(x => x.IsTimeout(e.SignalTime)).ToList()
.ForEach(x =>
{
RemoveInfo(x.UserId);
});
}
}
/// <summary>
/// 触发事件
/// </summary>
/// <param name="_event">事件</param>
/// <param name="info">数据集</param>
static void CallEvent(Action<AuthorLoginInfo> _event, AuthorLoginInfo info)
{
if (_event != null)
{
_event(info);
}
}
#endregion
#region 静态事件
/// <summary>
/// 声明用户登录前触发
/// </summary>
public static event Action<AuthorLoginInfo> Logining;
/// <summary>
/// 声明用户登陆后触发
/// </summary>
public static event Action<AuthorLoginInfo> Logined;
/// <summary>
/// 声明用户退出前触发
/// </summary>
public static event Action<AuthorLoginInfo> Logouting;
/// <summary>
/// 声明用户退出后触发
/// </summary>
public static event Action<AuthorLoginInfo> Logouted;
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project.Model;
using Project.Repository;
using Project.ViewModel;
namespace Project.Service
{
public interface IPaymentService : IBaseService<Payment>
{
List<Payment> GetListById(Guid id);
}
public class PaymentService : BaseService<Payment>, IPaymentService
{
private readonly IPaymentRepository _repository;
private readonly ICaseService _caseService;
public PaymentService(IPaymentRepository repository, ICaseService caseService): base(repository)
{
_repository = repository;
_caseService = caseService;
}
public List<Payment> GetListById(Guid id)
{
return _repository.GetListById(id).ToList();
}
public override bool Delete(Guid id)
{
var payment = _repository.GetById(id);
var delete = _repository.Delete(payment);
var commit = _repository.Commit();
if (!commit) return false;
var updatePriceTotal = _caseService.UpdatePriceTotal(payment.HddInfoId);
return updatePriceTotal;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
namespace KlaxRenderer.Debug
{
class CDebugLineShader : CDebugObjectShader
{
public CDebugLineShader()
{
VSFileName = "Resources/Shaders/DebugLineVS.hlsl";
PSFileName = "Resources/Shaders/DebugLinePS.hlsl";
InputElements = new []
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0)
};
}
}
}
|
using System.IO;
using System.Text.Json;
using Flurl.Http.Configuration;
namespace MtgApiManager.Lib.Core
{
/// <inheritdoc />
public class SystemTextJsonSerializer : ISerializer
{
/// <inheritdoc />
public T Deserialize<T>(string s)
{
return JsonSerializer.Deserialize<T>(s);
}
/// <inheritdoc />
public T Deserialize<T>(Stream stream)
{
using (var reader = new StreamReader(stream))
{
return JsonSerializer.Deserialize<T>(reader.ReadToEnd());
}
}
/// <inheritdoc />
public string Serialize(object obj)
{
return JsonSerializer.Serialize(obj);
}
}
} |
using System.Collections.Generic;
using System.Security.Claims;
namespace Tests.Helpers
{
public static class ClaimsData
{
public static List<Claim> GetClaims()
{
return new List<Claim>
{
new("username", "deneme"),
new("email", "test@test.com"),
new("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1A5C36D32156A")
};
}
}
} |
/*
* BouncerAPI.Standard
*
* This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BouncerAPI.Standard.Http.Request;
namespace BouncerAPI.Standard
{
internal partial class AuthUtility
{
/// <summary>
/// Appends the necessary Custom Authentication credentials for making this authorized call
/// </summary>
/// <param name="request">The out going request to access the resource</param>
internal static void AppendCustomAuthParams(HttpRequest request)
{
// TODO: Add your custom authentication here
// The following properties are available to use
//
// ie. Add a header through:
// request.header("Key", "Value");
if (!string.IsNullOrWhiteSpace(Configuration.ACCESS_TOKEN))
{
request.Headers.Add("Authorization", $"Bearer {Configuration.ACCESS_TOKEN}");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleSystemUnderTest.Calculator
{
public enum Operation
{
Add,
Subtract
}
}
|
#region Header
// Copyright (c) 2013 Hans Wolff
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Text;
namespace Simple.MailServer.Mime
{
public class QuotedPrintableEncoderStream : Stream
{
public Stream BaseStream { get; private set; }
private Encoding _defaultEncoding = Encoding.GetEncoding("iso-8859-1");
public Encoding DefaultEncoding
{
get { return _defaultEncoding; }
set { _defaultEncoding = value; }
}
public QuotedPrintableEncoderStream(Stream baseStream)
{
if (baseStream == null) throw new ArgumentNullException("baseStream");
BaseStream = baseStream;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return BaseStream.CanSeek; }
}
public override bool CanWrite
{
get { return BaseStream.CanWrite; }
}
public override long Length
{
get { return BaseStream.Length; }
}
public override long Position { get; set; }
public override void Flush()
{
BaseStream.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return BaseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
BaseStream.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
private int _charsInLine;
public void Write(string text)
{
var buf = DefaultEncoding.GetBytes(text);
Write(buf, 0, buf.Length);
}
public void Write(byte[] buffer)
{
Write(buffer, 0, buffer.Length);
}
private static readonly byte[] LineBreak = { (byte)'=', 13, 10 };
private readonly byte[] _triBuf = { (byte)'=', 0, 0 };
private static readonly byte[] Hex = Encoding.ASCII.GetBytes("0123456789ABCDEF");
public override void Write(byte[] buffer, int offset, int count)
{
for (int i = offset; i < count; i++)
{
int currentLen;
byte b = buffer[i];
if (b > 127 || b == '=')
{
_triBuf[1] = Hex[b >> 4];
_triBuf[2] = Hex[b % 16];
currentLen = 3;
}
else
{
if (b == 13 || b == 10)
{
BaseStream.WriteByte(b);
_charsInLine = 0;
continue;
}
currentLen = 1;
}
_charsInLine += currentLen;
if (_charsInLine > 75)
{
BaseStream.Write(LineBreak, 0, LineBreak.Length);
_charsInLine = currentLen;
}
if (currentLen == 1)
BaseStream.WriteByte(b);
else
BaseStream.Write(_triBuf, 0, _triBuf.Length);
}
}
}
} |
using UnityEngine;
using UnityEngine.AI;
/// <summary>
/// A wrapper class for movement of a bot using the A Star pathfinding.
/// </summary>
namespace KindlyBehave.Navigation
{
[RequireComponent(typeof(NavMeshAgent))]
public class NavMeshNavigationWrapper : AbstractNavigationWrapper
{
[SerializeField]
private IMovement m_Movement;
private NavMeshAgent m_NavMeshAgent;
private NavMeshPath m_NavMeshPath;
protected virtual void Awake()
{
if(m_Movement == null)
{
m_Movement = new Movement(1f); // TODO: Pull true value when location is implemented
}
m_NavMeshAgent = GetComponent<NavMeshAgent>();
}
public override void CalculatePath(Vector3 destination) { }
public override void SetDestination(Vector3 destination) { }
public override void OnReset()
{
m_NavMeshAgent.isStopped = true;
float speed = m_Movement.GetBaseSpeed();
m_NavMeshAgent.speed = speed;
m_NavMeshAgent.angularSpeed = speed;
m_Movement.OnReset();
}
}
} |
using System.DirectoryServices.AccountManagement;
namespace Passwd.SystemDirectoryServicesImpl
{
internal class PrincipalDomainContext : IDomainContext
{
private readonly PrincipalContext principalContext;
public PrincipalDomainContext(PrincipalContext principalContext)
{
this.principalContext = principalContext;
}
public bool TryFindUser(string accountName, out IDomainUser result)
{
result = null;
var findByIdentity =
UserPrincipal.FindByIdentity(this.principalContext, IdentityType.SamAccountName, accountName)
??
UserPrincipal.FindByIdentity(this.principalContext, IdentityType.UserPrincipalName, accountName);
if (findByIdentity == null)
return false;
result = new PrincipalDomainUser(findByIdentity);
return true;
}
public void Dispose()
{
this.principalContext.Dispose();
}
}
} |
using Lever.Dal;
using Lever.IBLL;
namespace Lever.Bll
{
public class ComponentBll: IComponentBll
{
private readonly ComponentDal _dal;
public ComponentBll(ComponentDal dal)
{
_dal = dal;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QF.GraphDesigner
{
public interface IPlatformOperations
{
void OpenScriptFile(string filePath);
void OpenLink(string link);
string GetAssetPath(object graphData);
bool MessageBox(string title, string message, string ok);
bool MessageBox(string title, string message, string ok, string cancel);
void SaveAssets();
void RefreshAssets();
void Progress(float progress, string message);
}
}
|
using ms17.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace ms17.BLL.Interface
{
public interface IPhotoService
{
Photo FindPhotoById(int ID);
bool CreatePhoto(Photo newPhoto, HttpPostedFileBase image);
Photo FindPhotoByTitle(string Title);
bool DeletePhotoById(int photoId);
IQueryable<Photo> Photos { get; }
}
}
|
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
private NavMeshAgent _agent;
private Transform _heart;
private void Start()
{
_agent = GetComponent<NavMeshAgent>();
_heart = GameObject.FindGameObjectWithTag("Heart").transform;
_agent.SetDestination(_heart.transform.position);
}
private void OnCollisionEnter(Collision collision)
{
if (collision.collider.CompareTag("Heart"))
{
GameManager.S.TakeDamage();
Destroy(gameObject);
}
else if (collision.collider.CompareTag("Bullet"))
{
Destroy(gameObject);
}
}
}
|
using System;
using System.Linq;
namespace Bojo_ParkingSystem
{
class Program
{
private static bool[][] parking;
private static int rows;
private static int cols;
static void Main(string[] args)
{
int[] dimensions = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
rows = dimensions[0];
cols = dimensions[1];
parking = new bool[rows][];
string command;
while ((command=Console.ReadLine())!= "stop")
{
int[] commandArgs = command.Split().Select(int.Parse).ToArray();
int entryRow = commandArgs[0];
int targetRow = commandArgs[1];
int targetCol = commandArgs[2];
if (IsSpotTaken(targetRow, targetCol))
{
targetCol = TryFindFreeSpot(targetRow, targetCol);
}
if (targetCol > 0)
{
MarkSpotAsTaken(targetRow,targetCol);
int distancePassed = Math.Abs(entryRow - targetRow) + targetCol + 1;
Console.WriteLine(distancePassed);
}
else
{
Console.WriteLine($"Row {targetRow} full");
}
}
}
private static void MarkSpotAsTaken(int targetRow, int targetCol)
{
if (parking[targetRow] == null)
{
parking[targetRow] = new bool[cols];
}
parking[targetRow][targetCol] = true;
}
private static int TryFindFreeSpot(int targetRow, int targetCol)
{
int parkingCol = 0;
int bestDistance = int.MaxValue;
for (int col = 1; col < cols; col++)
{
if (!parking[targetRow][col])
{
int distance = Math.Abs(col - targetCol);
if (distance < bestDistance)
{
parkingCol = col;
bestDistance = distance;
}
}
}
return parkingCol;
}
private static bool IsSpotTaken(int targetRow, int targetCol)
{
return parking[targetRow] != null && parking[targetRow][targetCol];
}
}
}
|
using UnityEngine;
public class AngularVelocity : MonoBehaviour {
public Vector3 angVel = new Vector3(10f, 10f, 0f);
Rigidbody body;
// Use this for initialization
void Start () {
body = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
if (body != null) {
body.angularVelocity = angVel;
} else {
transform.rotation = Quaternion.Euler(angVel*Time.fixedDeltaTime) * transform.rotation;
}
}
} |
using EduCATS.Helpers.Forms.Styles;
using EduCATS.Themes;
using Xamarin.Forms;
namespace EduCATS.Controls.Pickers
{
/// <summary>
/// Groups picker view.
/// </summary>
public class GroupsPickerView : Frame
{
/// <summary>
/// Chosen group property.
/// </summary>
/// <remarks>
/// <c>"ChosenGroup"</c> by default.
/// </remarks>
public string ChosenGroupProperty { get; set; }
/// <summary>
/// Chosen group command property.
/// </summary>
/// <remarks>
/// <c>"ChooseGroupCommand"</c> by default.
/// </remarks>
public string ChooseGroupCommandProperty { get; set; }
/// <summary>
/// Default chosen group property.
/// </summary>
const string _chosenGroupPropertyDefault = "ChosenGroup";
/// <summary>
/// Default choose group command property.
/// </summary>
const string _chooseGroupCommandPropertyDefault = "ChooseGroupCommand";
/// <summary>
/// Constructor.
/// </summary>
public GroupsPickerView()
{
HasShadow = false;
ChosenGroupProperty = _chosenGroupPropertyDefault;
ChooseGroupCommandProperty = _chooseGroupCommandPropertyDefault;
BackgroundColor = Color.FromHex(Theme.Current.BaseBlockColor);
createViews();
setGestureRecognizer();
}
/// <summary>
/// Create views.
/// </summary>
void createViews()
{
Content = new StackLayout {
HorizontalOptions = LayoutOptions.CenterAndExpand,
Children = {
createGroupLabel()
}
};
}
/// <summary>
/// Create group label.
/// </summary>
/// <returns>Group label.</returns>
Label createGroupLabel()
{
var group = new Label {
TextColor = Color.FromHex(Theme.Current.BasePickerTextColor),
HorizontalTextAlignment = TextAlignment.Center,
VerticalOptions = LayoutOptions.CenterAndExpand,
Style = AppStyles.GetLabelStyle()
};
group.SetBinding(Label.TextProperty, ChosenGroupProperty);
return group;
}
/// <summary>
/// Set tap gesture recognizer.
/// </summary>
void setGestureRecognizer()
{
var tapGesture = new TapGestureRecognizer();
tapGesture.SetBinding(TapGestureRecognizer.CommandProperty, ChooseGroupCommandProperty);
GestureRecognizers.Add(tapGesture);
}
}
}
|
#if NETSTANDARD2_0 || NET461
using Microsoft.Extensions.DependencyInjection;
#endif
namespace RudderStack.Extensions
{
public static class ServiceCollectionExtension
{
#if NETSTANDARD2_0 || NET461
public static void AddAnalytics(this IServiceCollection services, string writeKey, RudderConfig config = null)
{
RudderConfig configuration;
if(config == null)
configuration = new RudderConfig();
else
configuration = config;
var client = new RudderClient(writeKey, configuration);
services.AddSingleton<IRudderAnalyticsClient>(client);
}
#endif
}
}
|
namespace Photosphere.Console.Arguments.DataTransferObjects
{
public interface ICommandLineArguments {}
} |
namespace Bridge.ChartJS
{
[ObjectLiteral]
[External]
public class DataConfig
{
public Dataset[] Datasets;
public string[] Labels;
public string[] XLabels;
public string[] YLabels;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Moq;
using NUnit.Framework;
[TestFixture]
public class WeaverInitialiserTests
{
[Test]
public void ValidProps()
{
var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);
var innerWeaver = new InnerWeaver
{
Logger = new Mock<ILogger>().Object,
AssemblyFilePath = "AssemblyFilePath",
ProjectDirectoryPath = "ProjectDirectoryPath",
SolutionDirectoryPath = "SolutionDirectoryPath",
ReferenceDictionary = new Dictionary<string, string> {{"Ref1;Ref2", "Path1"}},
ReferenceCopyLocalPaths = new List<string> {"Ref1"},
ModuleDefinition = moduleDefinition,
DefineConstants = new List<string>{"Debug", "Release"}
};
var weaverEntry = new WeaverEntry
{
Element = "<foo/>",
AssemblyPath = @"c:\FakePath\Assembly.dll"
};
var moduleWeaver = new ValidModuleWeaver();
innerWeaver.SetProperties(weaverEntry, moduleWeaver, (typeof(ValidModuleWeaver)).BuildDelegateHolder());
Assert.IsNotNull(moduleWeaver.LogDebug);
Assert.IsNotNull(moduleWeaver.LogInfo);
Assert.IsNotNull(moduleWeaver.LogWarning);
Assert.IsNotNull(moduleWeaver.LogWarningPoint);
Assert.IsNotNull(moduleWeaver.LogError);
Assert.IsNotNull(moduleWeaver.LogErrorPoint);
Assert.AreEqual("Ref1", moduleWeaver.ReferenceCopyLocalPaths.First());
Assert.AreEqual("Debug", moduleWeaver.DefineConstants[0]);
Assert.AreEqual("Release", moduleWeaver.DefineConstants[1]);
// Assert.IsNotEmpty(moduleWeaver.References);
Assert.AreEqual(moduleDefinition, moduleWeaver.ModuleDefinition);
Assert.AreEqual(innerWeaver, moduleWeaver.AssemblyResolver);
Assert.AreEqual(@"c:\FakePath", moduleWeaver.AddinDirectoryPath);
Assert.AreEqual("AssemblyFilePath", moduleWeaver.AssemblyFilePath);
Assert.AreEqual("ProjectDirectoryPath", moduleWeaver.ProjectDirectoryPath);
Assert.AreEqual("SolutionDirectoryPath", moduleWeaver.SolutionDirectoryPath);
}
}
public class ValidModuleWeaver
{
public XElement Config { get; set; }
// public List<string> References { get; set; }
public string AssemblyFilePath { get; set; }
public string ProjectDirectoryPath { get; set; }
public string AddinDirectoryPath { get; set; }
public Action<string> LogDebug { get; set; }
public Action<string> LogInfo { get; set; }
public Action<string> LogWarning { get; set; }
public Action<string, SequencePoint> LogWarningPoint { get; set; }
public Action<string> LogError { get; set; }
public Action<string, SequencePoint> LogErrorPoint { get; set; }
public IAssemblyResolver AssemblyResolver { get; set; }
public ModuleDefinition ModuleDefinition { get; set; }
public string SolutionDirectoryPath { get; set; }
public List<string> DefineConstants { get; set; }
public List<string> ReferenceCopyLocalPaths { get; set; }
public bool ExecuteCalled;
public void Execute()
{
ExecuteCalled = true;
}
} |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Coinbase_Portfolio_Tracker.Models.Coinbase.Dto;
using Coinbase_Portfolio_Tracker.Models.Coinbase.Responses;
namespace Coinbase_Portfolio_Tracker.Services.Coinbase
{
public interface ICoinbaseBuyService
{
Task<CoinbaseBuy> GetBuyAsync(string accountId, string buyId);
}
public class CoinbaseBuyService : RequestService, ICoinbaseBuyService
{
public CoinbaseBuyService(ICoinbaseConnectService coinbaseConnectService)
: base(coinbaseConnectService)
{
}
public async Task<CoinbaseBuy> GetBuyAsync(string accountId, string buyId)
{
if (string.IsNullOrWhiteSpace(accountId) || string.IsNullOrWhiteSpace(buyId))
throw new ArgumentNullException($"AccountId or BuyId cannot be null, {accountId}, {buyId}");
var buyResponse = await SendApiRequest<CoinbaseBuyResponse>(HttpMethod.Get,
$"accounts/{accountId}/buys/{buyId}");
if (buyResponse?.Buy == null)
throw new NullReferenceException("Buy transaction json response is null");
var buy = buyResponse.Buy;
return new CoinbaseBuy()
{
BuyAmount = buy.Amount.Amount,
BuyAmountCurrency = buy.Amount.Currency,
FeeAmount = buy.Fee.Amount,
FeeAmountCurrency = buy.Fee.Currency,
SubtotalAmount = buy.Subtotal.Amount,
SubtotalAmountCurrency = buy.Subtotal.Currency,
TotalAmount = buy.Total.Amount,
TotalAmountCurrency = buy.Total.Currency
};
}
}
} |
@using SensorManagementSystem.App
@using SensorManagementSystem.App.Models
@using SensorManagementSystem.Models.Entities
@using SensorManagementSystem.App.Controllers
@using SensorManagementSystem.Common;
@using SensorManagementSystem.Models.ViewModels;
@using SensorManagementSystem.Common.Extensions;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
using System.Text.Json.Serialization;
namespace DotNetBungieAPI.Generated.Models.Content.Models;
public sealed class ContentTypeDefaultValue
{
[JsonPropertyName("whenClause")]
public string WhenClause { get; init; }
[JsonPropertyName("whenValue")]
public string WhenValue { get; init; }
[JsonPropertyName("defaultValue")]
public string DefaultValue { get; init; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Testing
{
class Program
{
const string CAMPAIGN_ID = "CAMPAIGN_ID";
const string ACCESS_TOKEN = "ACCESS_TOKEN";
static async Task Main(string[] args)
{
var patreon = new Patreon.NET.PatreonClient(ACCESS_TOKEN);
//var pledges = await patreon.GetCampaignPledges(CAMPAIGN_ID);
var members = await patreon.GetCampaignMembers(CAMPAIGN_ID);
//var campaign = await patreon.GetCampaign(CAMPAIGN_ID);
Console.Read();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DeviousCreation.CqrsIdentity.Core.Constants
{
public enum RemoteMfaType
{
Email
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MCTuristic_Centro_Historico.GUI
{
public partial class PagPrincipal : System.Web.UI.Page
{
int id;
int idUser;
protected void Page_Load(object sender, EventArgs e)
{
id = Convert.ToInt32(Session["idAdmin"]);
idUser = Convert.ToInt32(Session["idUser"]);
if (id > 0 || idUser > 0)
{
HyperLink1.Visible = true;
}
else
{
HyperLink1.Visible = false;
}
}
protected void btnCerrarSecion_Click1(object sender, EventArgs e)
{
Session["idAdmin"] = 0;
Session["idUser"] = 0;
Server.Transfer("PagPrincipal.aspx");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rainnier.DesignPattern.FlyWeight
{
class Program
{
static void Main(string[] args)
{
var factory = FlyweightFactory.GetInstance();
var chess1 = factory.GetChess("white");
var chess2 = factory.GetChess("white");
var chess3 = factory.GetChess("black");
chess1.Display(new Coordinate(1, 2));
chess2.Display(new Coordinate(2, 3));
chess3.Display(new Coordinate(4, 5));
Console.ReadKey();
}
}
}
|
/****************************************************************************
Copyright (c) 2015 Lingjijian
Created by Lingjijian on 2015
342854406@qq.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using UnityEngine;
using System.Collections.Generic;
namespace Lui
{
[SLua.CustomLuaClass]
public class LExpandListView : LScrollView
{
protected List<LExpandNode> _expandableNodeList;
public int nodeNum;
public int nodeItemNum;
public GameObject cell_tpl;
public GameObject cell_sub_tpl;
public LExpandListView()
{
direction = ScrollDirection.VERTICAL;
_expandableNodeList = new List<LExpandNode>();
}
public void expand(int idx)
{
_expandableNodeList[idx].setExpanded(true);
}
public void collapse(int idx)
{
_expandableNodeList[idx].setExpanded(false);
}
public void insertExpandableNodeAtLast(LExpandNode node)
{
if (node == null)
{
Debug.LogWarning("insert node is null");
return;
}
_expandableNodeList.Add(node);
node.transform.SetParent(container.transform);
}
public void insertExpandableNodeAtFront(LExpandNode node)
{
if (node == null)
{
Debug.LogWarning("insert node is null");
return;
}
_expandableNodeList.Insert(0, node);
node.transform.SetParent(container.transform);
}
public void removeExpandNode(LExpandNode node)
{
if (node == null)
{
Debug.LogWarning("insert node is null");
return;
}
if (_expandableNodeList.Count == 0) return;
_expandableNodeList.Remove(node);
}
public void removeExpandNodeAtIndex(int idx)
{
if (_expandableNodeList.Count == 0) return;
_expandableNodeList.RemoveAt(idx);
Destroy(_expandableNodeList[idx]);
}
public void removeLastExpandNode()
{
if (_expandableNodeList.Count == 0) return;
_expandableNodeList.RemoveAt(_expandableNodeList.Count - 1);
Destroy(_expandableNodeList[_expandableNodeList.Count - 1]);
}
public void removeFrontExpandNode()
{
if (_expandableNodeList.Count == 0) return;
_expandableNodeList.RemoveAt(0);
Destroy(_expandableNodeList[0]);
}
public void removeAllExpandNodes()
{
if (_expandableNodeList.Count == 0) return;
int len = _expandableNodeList.Count;
for(int i=0;i<len; i++)
{
Destroy(_expandableNodeList[i].gameObject);
}
_expandableNodeList.Clear();
}
public List<LExpandNode> getExpandableNodes()
{
return _expandableNodeList;
}
public int getExpandableNodeCount()
{
return _expandableNodeList.Count;
}
public LExpandNode getExpandableNodeAtIndex(int idx)
{
return _expandableNodeList[idx];
}
public void updateNodesPosition()
{
if (_expandableNodeList.Count == 0) return;
float allNodesHeight = 0.0f;
int nodeLen = _expandableNodeList.Count;
for(int i=0;i< nodeLen; i++)
{
LExpandNode node = _expandableNodeList[i];
allNodesHeight += node.gameObject.GetComponent<RectTransform>().rect.height;
if (node.isExpanded())
{
List<GameObject> nodeItems = node.getExpandableNodeItemList();
int len = nodeItems.Count;
if (len > 0)
{
for(int _i=0;_i<len;_i++)
{
GameObject obj = nodeItems[_i];
obj.SetActive(true);
allNodesHeight += obj.GetComponent<RectTransform>().rect.height;
}
}
}
else
{
List<GameObject> nodeItems = node.getExpandableNodeItemList();
int len = nodeItems.Count;
if (len > 0)
{
for(int _i=0;_i<len;_i++)
{
nodeItems[_i].SetActive(false);
}
}
}
}
Rect rect = GetComponent<RectTransform>().rect;
allNodesHeight = Mathf.Max(allNodesHeight, rect.height);
setContainerSize(new Vector2(rect.width, allNodesHeight));
for (int i = 0; i < nodeLen; i++)
{
LExpandNode node = _expandableNodeList[i];
RectTransform rtran = node.gameObject.GetComponent<RectTransform>();
allNodesHeight = allNodesHeight - rtran.rect.height;
rtran.pivot = Vector2.zero;
rtran.anchorMax = new Vector2(0, 0);
rtran.anchorMin = new Vector2(0, 0);
node.transform.SetParent(container.transform);
node.transform.localPosition = new Vector2(0, allNodesHeight);
node.transform.localScale = new Vector3(1, 1, 1);
if (node.isExpanded())
{
List<GameObject> itemLists = node.getExpandableNodeItemList();
for(int j = 0; j < itemLists.Count; j++)
{
RectTransform _rtran = itemLists[j].GetComponent<RectTransform>();
allNodesHeight = allNodesHeight - _rtran.rect.height;
_rtran.pivot = Vector2.zero;
_rtran.anchorMax = new Vector2(0, 0);
_rtran.anchorMin = new Vector2(0, 0);
itemLists[j].transform.SetParent(container.transform);
itemLists[j].transform.localPosition = new Vector2(0, allNodesHeight);
itemLists[j].transform.localScale = new Vector3(1, 1, 1);
}
}
}
}
public void prepare()
{
if (nodeNum > 0)
{
if (cell_tpl == null) {
cell_tpl = transform.Find("container/cell_tpl").gameObject;
}
if (cell_sub_tpl == null){
cell_sub_tpl = transform.Find("container/cell_sub_tpl").gameObject;
}
cell_tpl.SetActive(false);
cell_sub_tpl.SetActive(false);
for (int i = 0; i < nodeNum; i++)
{
GameObject nodeObj = Instantiate(cell_tpl);
nodeObj.SetActive(true);
nodeObj.transform.SetParent(container.transform);
LExpandNode node = nodeObj.AddComponent<LExpandNode>();
node.tpl = cell_sub_tpl;
node.prepare(nodeItemNum);
insertExpandableNodeAtLast(node);
}
}
}
public void reloadData()
{
if(direction != ScrollDirection.VERTICAL)
{
Debug.LogWarning("LExpandListView should be Vertical");
return;
}
float oldHeight = container.GetComponent<RectTransform>().rect.height;
updateNodesPosition();
float newHeight = container.GetComponent<RectTransform>().rect.height - oldHeight;
setContentOffset(getContentOffset() - new Vector2(0, newHeight));
relocateContainer();
}
}
} |
using System;
using System.Diagnostics;
using ProjBobcat.Class.Model.YggdrasilAuth;
namespace ProjBobcat.Class.Model
{
public class LaunchResult
{
public LaunchErrorType ErrorType { get; set; }
public LaunchSettings LaunchSettings { get; set; }
public ErrorModel Error { get; set; }
public TimeSpan RunTime { get; set; }
public Process GameProcess { get; set; }
}
} |
using System;
namespace BinaryMesh.OpenXml.Internal
{
internal interface IOpenXmlDocument
{
IOpenXmlTextStyle DefaultTextStyle { get; }
IOpenXmlTheme Theme { get; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using Conway;
using Johnson;
using UnityEngine;
public class MinimalExample : MonoBehaviour
{
void Start()
{
// 1. Create a starting shape
ConwayPoly poly1 = JohnsonPoly.Build(PolyHydraEnums.JohnsonPolyTypes.Prism, 4);
// 2. Apply an operator to the starting shape
poly1 = poly1.ApplyOp(Ops.Chamfer, new OpParams(.3f));
// 3. Create a second shape
ConwayPoly poly2 = JohnsonPoly.Build(PolyHydraEnums.JohnsonPolyTypes.Pyramid, 4);
// 4. Move our second shape down by 0.5
poly2 = poly1.Transform(new Vector3(0, .5f, 0));
// 5. Join the two shapes
poly1.Append(poly2);
// 6. Build and apply the mesh
var mesh = PolyMeshBuilder.BuildMeshFromConwayPoly(poly1);
GetComponent<MeshFilter>().mesh = mesh;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Synnduit.Events;
using Synnduit.Mappings;
using Synnduit.Persistence;
namespace Synnduit
{
/// <summary>
/// Runs individual run segments of the <see cref="SegmentType.GarbageCollection" />
/// type.
/// </summary>
/// <typeparam name="TEntity">The type representing the entity.</typeparam>
[Export(typeof(IGarbageCollectionSegmentRunner<>))]
internal class GarbageCollectionSegmentRunner<TEntity> :
IGarbageCollectionSegmentRunner<TEntity>
where TEntity : class
{
private readonly IContext context;
private readonly IParameterProvider parameterProvider;
private readonly IOperationExecutive operationExecutive;
private readonly IGateway<TEntity> gateway;
private readonly ISafeRepository safeRepository;
private readonly IEventDispatcher<TEntity> eventDispatcher;
private EntityIdentifier[] idsOfEntitiesToDelete;
[ImportingConstructor]
public GarbageCollectionSegmentRunner(
IContext context,
IParameterProvider parameterProvider,
IOperationExecutive operationExecutive,
IGateway<TEntity> gateway,
ISafeRepository safeRepository,
IEventDispatcher<TEntity> eventDispatcher,
IInitializer initializer)
{
this.context = context;
this.parameterProvider = parameterProvider;
this.operationExecutive = operationExecutive;
this.gateway = gateway;
this.safeRepository = safeRepository;
this.eventDispatcher = eventDispatcher;
this.idsOfEntitiesToDelete = null;
initializer.Register(
new Initializer(this),
suppressEvents: true);
}
/// <summary>
/// Performs the current run segment run.
/// </summary>
public void Run()
{
foreach(EntityIdentifier id in this.idsOfEntitiesToDelete)
{
using(IOperationScope scope = this.operationExecutive.CreateOperation())
{
this.DeleteEntity(id);
scope.Complete();
}
}
}
private void DeleteEntity(EntityIdentifier id)
{
EntityDeletionOutcome outcome;
Exception exceptionThrown = null;
try
{
this.RaiseDeletionProcessing(id);
TEntity entity = this.gateway.Get(id);
if(entity != null)
{
this.RaiseDeletionEntityLoaded(id, entity);
this.gateway.Delete(entity);
outcome = EntityDeletionOutcome.Deleted;
}
else
{
outcome = EntityDeletionOutcome.NotFound;
}
}
catch(DestinationSystemException exception)
{
outcome = EntityDeletionOutcome.ExceptionThrown;
exceptionThrown = exception.InnerException;
}
this.RaiseDeletionProcessed(id, outcome, exceptionThrown);
}
private void RaiseDeletionProcessing(EntityIdentifier entityId)
{
this.eventDispatcher.DeletionProcessing(
new DeletionProcessingArgs(
this.operationExecutive.CurrentOperation.TimeStamp,
entityId));
}
private void RaiseDeletionEntityLoaded(EntityIdentifier entityId, TEntity entity)
{
this.eventDispatcher.DeletionEntityLoaded(
new DeletionEntityLoadedArgs(
this.operationExecutive.CurrentOperation.TimeStamp,
entityId,
entity));
}
private void RaiseDeletionProcessed(
EntityIdentifier entityId,
EntityDeletionOutcome outcome,
Exception exception)
{
this.eventDispatcher.DeletionProcessed(
new DeletionProcessedArgs(
this.operationExecutive.CurrentOperation.TimeStamp,
this.operationExecutive.CurrentOperation.LogMessages,
exception,
entityId,
outcome));
}
private class Initializer : IInitializable
{
private readonly GarbageCollectionSegmentRunner<TEntity> parent;
public Initializer(GarbageCollectionSegmentRunner<TEntity> parent)
{
this.parent = parent;
}
public void Initialize(IInitializationContext context)
{
this.parent
.eventDispatcher
.GarbageCollectionInitializing(
new GarbageCollectionInitializingArgs());
this.parent.idsOfEntitiesToDelete = this.GetIdsOfEntitiesToDelete();
this.parent
.eventDispatcher
.GarbageCollectionInitialized(
new GarbageCollectionInitializedArgs(
this.parent.idsOfEntitiesToDelete.Length));
}
private EntityIdentifier[] GetIdsOfEntitiesToDelete()
{
IEnumerable<EntityIdentifier> idsOfEntitiesToDelete;
IEnumerable<EntityIdentifier>
destinationSystemIds = this.parent.gateway.GetEntityIdentifiers();
MappingEntityIdentifiers mappingEntityIdentifiers
= this.GetMappingEntityIdentifiers();
switch(this.parent.parameterProvider.GarbageCollectionBehavior)
{
case GarbageCollectionBehavior.DeleteCreated:
idsOfEntitiesToDelete =
destinationSystemIds
.Intersect(mappingEntityIdentifiers.InactiveCreated);
break;
case GarbageCollectionBehavior.DeleteMapped:
idsOfEntitiesToDelete =
destinationSystemIds
.Intersect(mappingEntityIdentifiers.Inactive);
break;
case GarbageCollectionBehavior.DeleteAll:
idsOfEntitiesToDelete =
destinationSystemIds
.Except(mappingEntityIdentifiers.Active);
break;
default:
idsOfEntitiesToDelete = new EntityIdentifier[0];
break;
}
return idsOfEntitiesToDelete.ToArray();
}
private MappingEntityIdentifiers GetMappingEntityIdentifiers()
{
var active = new HashSet<EntityIdentifier>();
var inactiveCreated = new HashSet<EntityIdentifier>();
var inactiveNotCreated = new HashSet<EntityIdentifier>();
foreach(IMappedEntityIdentifier mappedEntityIdentifier in
this
.parent
.safeRepository
.GetMappedEntityIdentifiers(this.parent.context.EntityType.Id))
{
var state = (MappingState) mappedEntityIdentifier.State;
var origin = (MappingOrigin) mappedEntityIdentifier.Origin;
if(state == MappingState.Active)
{
active.Add(mappedEntityIdentifier.DestinationSystemEntityId);
}
else if(
state == MappingState.Deactivated ||
state == MappingState.Removed)
{
if(origin == MappingOrigin.NewEntity)
{
inactiveCreated.Add(
mappedEntityIdentifier.DestinationSystemEntityId);
}
else if(origin == MappingOrigin.Deduplication)
{
inactiveNotCreated.Add(
mappedEntityIdentifier.DestinationSystemEntityId);
}
}
}
return new MappingEntityIdentifiers(
active,
inactiveCreated.Union(inactiveNotCreated).Except(active),
inactiveCreated.Except(active));
}
private class MappingEntityIdentifiers
{
public MappingEntityIdentifiers(
IEnumerable<EntityIdentifier> active,
IEnumerable<EntityIdentifier> inactive,
IEnumerable<EntityIdentifier> inactiveCreated)
{
this.Active = active;
this.Inactive = inactive;
this.InactiveCreated = inactiveCreated;
}
public IEnumerable<EntityIdentifier> Active { get; }
public IEnumerable<EntityIdentifier> Inactive { get; }
public IEnumerable<EntityIdentifier> InactiveCreated { get; }
}
}
private class GarbageCollectionInitializingArgs :
IGarbageCollectionInitializingArgs
{
}
private class GarbageCollectionInitializedArgs : IGarbageCollectionInitializedArgs
{
private readonly int count;
public GarbageCollectionInitializedArgs(int count)
{
this.count = count;
}
public int Count
{
get { return this.count; }
}
}
private abstract class DeletionArgs : OperationArgs, IDeletionArgs
{
private readonly EntityIdentifier entityId;
public DeletionArgs(DateTimeOffset timeStamp, EntityIdentifier entityId)
: base(timeStamp)
{
this.entityId = entityId;
}
public EntityIdentifier EntityId
{
get { return this.entityId; }
}
}
private class DeletionProcessingArgs : DeletionArgs, IDeletionProcessingArgs
{
public DeletionProcessingArgs(
DateTimeOffset timeStamp, EntityIdentifier entityId)
: base(timeStamp, entityId)
{ }
}
private class DeletionEntityLoadedArgs :
DeletionArgs, IDeletionEntityLoadedArgs<TEntity>
{
private readonly TEntity entity;
public DeletionEntityLoadedArgs(
DateTimeOffset timeStamp,
EntityIdentifier entityId,
TEntity entity)
: base(timeStamp, entityId)
{
this.entity = entity;
}
public TEntity Entity
{
get { return this.entity; }
}
}
private class DeletionProcessedArgs :
OperationCompletedArgs, IDeletionProcessedArgs
{
private readonly EntityIdentifier entityId;
private readonly EntityDeletionOutcome outcome;
public DeletionProcessedArgs(
DateTimeOffset timeStamp,
IEnumerable<ILogMessage> logMessages,
Exception exception,
EntityIdentifier entityId,
EntityDeletionOutcome outcome)
: base(timeStamp, logMessages, exception)
{
this.entityId = entityId;
this.outcome = outcome;
}
public EntityIdentifier EntityId
{
get { return this.entityId; }
}
public EntityDeletionOutcome Outcome
{
get { return this.outcome; }
}
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace auth
{
[Route("/")]
public class HomeController : ControllerBase
{
public IActionResult Home()
{
return Redirect("https://github.com/AppBegin/OAuth2Webapi");
}
}
}
|
using System.Globalization;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
namespace IM.Identity.Web
{
public class FilterConfig
{
private bool _useHttps;
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
#region Https filter
bool useHttps;
var useHttpsString = WebConfigurationManager.AppSettings["UseHttps"] != null
? WebConfigurationManager.AppSettings["UseHttps"].ToString(CultureInfo.InvariantCulture)
: string.Empty;
bool.TryParse(useHttpsString, out useHttps);
if (useHttps)
{
filters.Add(new RequireHttpsAttribute());
}
#endregion
}
}
}
|
using System.Diagnostics.CodeAnalysis;
namespace KIP_server_Auth.Constants
{
/// <summary>
/// Custom name constants.
/// </summary>
[ExcludeFromCodeCoverage]
public static class CustomNames
{
/// <summary>
/// Cabinet url.
/// </summary>
public const string StudentCabinetUrl = @"http://schedule.kpi.kharkov.ua/json/kabinet?";
/// <summary>
/// PersonalInformationPage.
/// </summary>
public const string PersonalInformationPage = "page=1";
/// <summary>
/// SemesterMarksListPage.
/// </summary>
public const string SemesterMarksListPage = "page=2";
/// <summary>
/// DebtListPage.
/// </summary>
public const string DebtListPage = "page=3";
/// <summary>
/// SemesterStudyingPlanPage.
/// </summary>
public const string SemesterStudyingPlanPage = "page=4";
/// <summary>
/// CurrentRankPage.
/// </summary>
public const string CurrentRankPage = "page=5";
}
}
|
namespace GDO.Areas.HelpPage.ModelDescriptions
{
public class KeyValuePairModelDescription : ModelDescription
{
public ModelDescription KeyModelDescription { get; set; }
public ModelDescription ValueModelDescription { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using PostSharp.Patterns.Contracts;
using ThreatsManager.Extensions.Panels.Roadmap;
using ThreatsManager.Extensions.Schemas;
using ThreatsManager.Interfaces.ObjectModel;
using ThreatsManager.Interfaces.ObjectModel.ThreatsMitigations;
using ThreatsManager.Utilities;
namespace ThreatsManager.Extensions.Panels
{
public partial class RoadmapThreatTypesCharts : UserControl
{
private RoadmapStatus _currentStatus = RoadmapStatus.NotAssessed;
private IThreatModel _model;
public RoadmapThreatTypesCharts()
{
InitializeComponent();
}
public void Initialize([NotNull] IThreatModel model)
{
_model = model;
ShowRoadmapStatus(RoadmapStatus.ShortTerm);
}
private void _previous_Click(object sender, EventArgs e)
{
switch (_currentStatus)
{
case RoadmapStatus.ShortTerm:
ShowRoadmapStatus(RoadmapStatus.LongTerm);
break;
case RoadmapStatus.MidTerm:
ShowRoadmapStatus(RoadmapStatus.ShortTerm);
break;
case RoadmapStatus.LongTerm:
ShowRoadmapStatus(RoadmapStatus.MidTerm);
break;
}
}
private void _next_Click(object sender, EventArgs e)
{
switch (_currentStatus)
{
case RoadmapStatus.ShortTerm:
ShowRoadmapStatus(RoadmapStatus.MidTerm);
break;
case RoadmapStatus.MidTerm:
ShowRoadmapStatus(RoadmapStatus.LongTerm);
break;
case RoadmapStatus.LongTerm:
ShowRoadmapStatus(RoadmapStatus.ShortTerm);
break;
}
}
private void ShowRoadmapStatus(RoadmapStatus status)
{
bool ok = false;
var mitigations = _model.Mitigations?.ToArray();
if (mitigations?.Any() ?? false)
{
var selectedMitigations = new List<Guid>();
switch (status)
{
case RoadmapStatus.ShortTerm:
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.ShortTerm);
break;
case RoadmapStatus.MidTerm:
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.ShortTerm);
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.MidTerm);
break;
case RoadmapStatus.LongTerm:
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.ShortTerm);
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.MidTerm);
UpdateSelectedMitigations(selectedMitigations, mitigations, RoadmapStatus.LongTerm);
break;
}
var schemaManager = new ResidualRiskEstimatorPropertySchemaManager(_model);
var projected =
schemaManager.SelectedEstimator?.GetProjectedThreatTypesResidualRisk(_model, selectedMitigations);
if (projected?.Any() ?? false)
{
_chart.RefreshChart(_model, projected);
_currentStatus = status;
_chartName.Text = status.GetEnumLabel();
ok = true;
}
}
_previous.Visible = ok;
_next.Visible = ok;
_chartName.Visible = ok;
}
private static void UpdateSelectedMitigations(List<Guid> selectedMitigations,
[NotNull] IEnumerable<IMitigation> mitigations, RoadmapStatus status)
{
var toBeAdded = mitigations
.Where(x => x.GetStatus() == status)
.Select(x => x.Id)
.ToArray();
if (toBeAdded.Any())
selectedMitigations.AddRange(toBeAdded);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class WinningScript : MonoBehaviour
{
GameObject[] nextGameObjects;
bool pass = false;
public int sceneNumber;
public GameObject go;
public Slider slider;
public AudioClip aclip;
public Text scoreText;
private int scoreInt;
private float scoreS;
AudioSource aSource;
// Use this for initialization
void Start ()
{
aSource = GetComponent<AudioSource>();
go = GameObject.FindGameObjectWithTag("Finish");
nextGameObjects = GameObject.FindGameObjectsWithTag("NextStage");
Hide();
}
public void Hide()
{
foreach(GameObject g in nextGameObjects)
{
g.SetActive(false);
}
}
public void Show()
{
foreach (GameObject g in nextGameObjects)
{
g.SetActive(true);
}
}
public void OnTriggerEnter2D()
{
slider.enabled = false;
scoreInt = ScoreScript.score;
scoreS = (float)scoreInt;
scoreS *= 100f;
aSource.PlayOneShot(aclip);
pass = true;
scoreText.text = scoreInt.ToString();
Destroy(go.gameObject);
}
public void NewScene()
{
SceneManager.LoadScene(sceneNumber);
}
public void MainScene()
{
SceneManager.LoadScene(0);
}
// Update is called once per frame
void Update ()
{
if(pass)
{
Show();
}
}
}
|
using System;
using System.Collections.Generic;
using DotNetMessenger.Model;
namespace DotNetMessenger.DataLayer.SqlServer.ModelProxies
{
public class MessageSqlProxy : Message
{
private bool _areAttachmentsFetched;
private IEnumerable<Attachment> _attachments;
private bool _isExpirationDateFetched;
private DateTime? _expirationDate;
public override DateTime? ExpirationDate
{
get
{
if (_isExpirationDateFetched)
return _expirationDate;
_expirationDate = RepositoryBuilder.MessagesRepository.GetMessageExpirationDate(Id);
_isExpirationDateFetched = true;
return _expirationDate;
}
}
public override IEnumerable<Attachment> Attachments
{
get
{
if (_areAttachmentsFetched)
return _attachments;
_attachments = RepositoryBuilder.MessagesRepository.GetMessageAttachments(Id);
_areAttachmentsFetched = true;
return _attachments;
}
}
}
} |
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Restaurant.Server.Api.Abstraction.Facades;
using Restaurant.Server.Api.Abstraction.Providers;
using Restaurant.Server.Api.Abstraction.Repositories;
using Restaurant.Server.Api.Data;
using Restaurant.Server.Api.Facades;
using Restaurant.Server.Api.IdentityServer;
using Restaurant.Server.Api.Mappers;
using Restaurant.Server.Api.Models;
using Restaurant.Server.Api.Providers;
using Restaurant.Server.Api.Repositories;
using Swashbuckle.AspNetCore.Swagger;
namespace Restaurant.Server.Api
{
[ExcludeFromCodeCoverage]
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = _configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<RestaurantDbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<IRepository<DailyEating>, DailyEatingRepository>();
services.AddScoped<IRepository<Food>, FoodRepository>();
services.AddScoped<IRepository<Category>, CategoryRepository>();
services.AddScoped<IRepository<Order>, OrderRepository>();
services.AddScoped<IMapperFacade, MapperFacade>();
services.AddScoped<IUserManagerFacade, UserManagerFacade>();
services.AddSingleton<IFileInfoFacade, FileInfoFacade>();
services.AddSingleton<IFileUploadProvider, FileUploadProvider>();
services.AddLogging();
services.AddCors(o => o.AddPolicy("ServerPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("WWW-Authenticate");
}));
services.AddMvc();
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<RestaurantDbContext>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(DefaultUsers.Get())
.AddAspNetIdentity<User>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Restaurant HTTP API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app,
ILoggerFactory loggerFactory,
IConfiguration configuration,
IHostingEnvironment env)
{
loggerFactory.AddConsole(configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Restaurant API");
c.RoutePrefix = string.Empty;
});
app.UseCors("ServerPolicy");
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
app.UseStaticFiles();
new AutoMapperConfiguration().Configure();
}
}
} |
// Copyright(c) 2018 Jeff Hotchkiss
// Licensed under the MIT License. See License.md in the project root for license information.
using System;
using System.Diagnostics;
using System.Linq;
using AspNetCore.DataProtection.Aws.TestCoreWebApp.Models;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCore.DataProtection.Aws.TestCoreWebApp.Controllers
{
public class HomeController : Controller
{
private readonly IDataProtectionProvider protectionProvider;
public HomeController(IDataProtectionProvider protectionProvider)
{
this.protectionProvider = protectionProvider ?? throw new ArgumentNullException(nameof(protectionProvider));
}
public IActionResult Index()
{
var protector = protectionProvider.CreateProtector("testing");
var plaintext = new byte[] { 1, 2, 3, 4, 5, 6 };
var ciphertext = protector.Protect(plaintext);
var resultText = protector.Unprotect(ciphertext);
ViewData["Message"] = resultText.SequenceEqual(plaintext) ? "Protection round trip succeeded" : "Protection round trip mismatch";
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using Domain.Entities;
using System.Collections.Generic;
namespace Domain.Repositories
{
public interface ICartaoVirtualRepository
{
void AdicionarCartaoVirtual(CartaoVirtual cartaoVirtual);
IEnumerable<CartaoVirtual> ListarCartaoVirtual(string email);
}
}
|
//
// Copyright (c) 2017 Ricoh Company, Ltd. All Rights Reserved.
// See LICENSE for more information.
//
using System;
namespace MtpHelper
{
public class MtpHelperRuntimeException: Exception
{
public MtpHelperRuntimeException() {}
public MtpHelperRuntimeException(String message): base(message) {}
public MtpHelperRuntimeException(String message, Exception inner): base(message, inner) {}
}
}
|
using Qowaiv.Globalization;
namespace Qowaiv.Validation.DataAnnotations.UnitTests.Models
{
public class ModelWithAllowedValues
{
[AllowedValues("", "BE", "NL", "LU")]
public Country Country { get; set; }
}
}
|
namespace AbstractIO.Netduino3
{
#region Info
// PWM on Netduino will be available for the following, if not conflicting with other use of the timers.
// The Arduiino pins D0 - D13 are connected to MCU pins using timer x for PWM
// D0 = PC7 = TIM8, channel 1
// D1 = PC6 = TIM8, channel 0
// D2 = PA3 = TIM2, channel 3 or TIM5, channel 3
// D3 = PA2 = TIM2, channel 2 or TIM5, channel 2
// D4 = PB12
// D5 = PB8 = TIM4, channel 2
// D6 = PB9 = TIM4, channel 3
// D7 = PA1 = TIM2, channel 1 or TIM5, channel 1
// D8 = PA0 = TIM2, channel 0 or TIM5, channel 0
// D9 = PE5
// D10 = PB10 = TIM2, channel 2
// D11 = PB15
// D12 = PB14
// D13 = PB13
// D14 = GND
// D15 = intentionally left blank
// D16 = PB7 = I2C1 SDA = Data
// D17 = PB6 = I2C1 SCL = Clock
// Onboard button = PB5 (= PD11)
//
// A0 = PC0 = ADC1 channel 0/1
// A1 = PC1 = ADC1 channel 0/1
// A2 = PC2 = ADC2 channel 0/1
// A3 = PC3 = ADC2 channel 0/1
// A4 = PC4 = ADC3 channel 0/1
// A5 = PC5 = ADC3 channel 0/1
// Furthermore some LEDs available on the board:
//
// On board LED = Blue = PA10 = TIM1 channel 2
// Go port 1 LED = Blue = PE9 = TIM1 channel 0
// Go port 2 LED = Blue = PE11 = TIM1 channel 1
// Go port 3 LED = Blue = PE14 = TIM1 channel 3
// Power on LED = White = PC13 = No timer, so no PWM
// Wifi State LED = Yellow = PA8 = TIM1 channel 0
// Wifi link LED = Green = PC9 = TIM8 channel 3
#endregion
/// <summary>
/// The digital input pins of a Netduino 3 board.
/// </summary>
public enum DigitalInputPin
{
// The Arduino/Netduino pins D0 - D13 are connected to the following MCU pins, and using timer x for PWM:
// D0 = PC7 = TIM8, channel 1
// D1 = PC6 = TIM8, channel 0
// D2 = PA3 = TIM2, channel 3 or TIM5, channel 3
// D3 = PA2 = TIM2, channel 2 or TIM5, channel 2
// D4 = PB12
// D5 = PB8 = TIM4, channel 2
// D6 = PB9 = TIM4, channel 3
// D7 = PA1 = TIM2, channel 1 or TIM5, channel 1
// D8 = PA0 = TIM2, channel 0 or TIM5, channel 0
// D9 = PE5
// D10 = PB10 = TIM2, channel 2
// D11 = PB15
// D12 = PB14
// D13 = PB13
D0 = 2 * 16 + 7,
D1 = 2 * 16 + 6,
D2 = 0 * 16 + 3,
D3 = 0 * 16 + 2,
D4 = 1 * 16 + 12,
D5 = 1 * 16 + 8,
D6 = 1 * 16 + 9,
D7 = 0 * 16 + 1,
D8 = 0 * 16 + 0,
D9 = 4 * 16 + 5,
D10 = 1 * 16 + 10,
D11 = 1 * 16 + 15,
D12 = 1 * 16 + 14,
D13 = 1 * 16 + 13,
OnboardButton = 1 * 16 + 5
}
/// <summary>
/// The digital output pins of a Netduino 3 board.
/// </summary>
/// <remarks>
/// This is just the <see cref="DigitalInputPin"/> enumeration, but without the onboard button and extended with
/// members for the onboard-LEDs.
/// </remarks>
public enum DigitalOutputPin
{
// Plain copies of the DigitalInputPin members:
D0 = 2 * 16 + 7,
D1 = 2 * 16 + 6,
D2 = 0 * 16 + 3,
D3 = 0 * 16 + 2,
D4 = 1 * 16 + 12,
D5 = 1 * 16 + 8,
D6 = 1 * 16 + 9,
D7 = 0 * 16 + 1,
D8 = 0 * 16 + 0,
D9 = 4 * 16 + 5,
D10 = 1 * 16 + 10,
D11 = 1 * 16 + 15,
D12 = 1 * 16 + 14,
D13 = 1 * 16 + 13,
// The onboard LED:
OnboardLedBlue = 0 * 16 + 10,
// The LEDs next to the 3 GoBus ports:
GoPort1Led = 4 * 16 + 9,
GoPort2Led = 4 * 16 + 11,
GoPort3Led = 4 * 16 + 14,
// The Power LED:
PowerLed = 2 * 16 + 13
}
/// <summary>
/// The digital output pins of a Netduino 3 board which can be used with PWM.
/// </summary>
/// <remarks>
/// This is a subset of the the <see cref="DigitalOutputPin"/> enumeration.
/// </remarks>
public enum DigitalPwmOutputPin
{
// Plain copies of the DigitalInputPin members, but commented out the ones not usable for PWM:
D0 = 2 * 16 + 7,
D1 = 2 * 16 + 6,
D2 = 0 * 16 + 3,
D3 = 0 * 16 + 2,
// D4 = 1 * 16 + 12, // no PWM
D5 = 1 * 16 + 8,
D6 = 1 * 16 + 9,
D7 = 0 * 16 + 1,
D8 = 0 * 16 + 0,
// D9 = 4 * 16 + 5, // no PWM
// D10 = 1 * 16 + 10, // D10 would always be the same percentage as D3.
// D11 = 1 * 16 + 15, // no PWM
// D12 = 1 * 16 + 14, // no PWM
// D13 = 1 * 16 + 13, // no PWM
// The onboard LED:
OnboardLedBlue = 0 * 16 + 10,
// The LEDs next to the 3 GoBus ports:
GoPort1Led = 4 * 16 + 9,
GoPort2Led = 4 * 16 + 11,
GoPort3Led = 4 * 16 + 14
// The Power LED:
// PowerLed = 2 * 16 + 13 // no PWM
}
/// <summary>
/// The 6 analog ADC inputs of a Netduino 3 board.
/// </summary>
public enum AnalogInputPin
{
// DO NOT CHANGE THE ORDER OF THESE MEMBERS!
// DO NOT CHANGE THE VALUES OF THESE MEMBERS!
// They must correspond to the channel numbers to pass to AdcController.OpenChannel().
// Otherwise, don't forget to adapt the Netduino3.AdcInput constructor.
A0,
A1,
A2,
A3,
A4,
A5,
// SENSOR
InternalTemperatureSensor,
// VREFINT
InternalReferenceVoltage,
// VBAT
Battery
}
} |
using Panosen.CodeDom.Css;
using System;
using System.Collections.Generic;
namespace Panosen.CodeDom.Less
{
/// <summary>
/// less 样式
/// </summary>
public class CodeLess : CodeCss
{
/// <summary>
/// 子 less 样式
/// </summary>
public List<CodeLess> Children { get; set; }
}
/// <summary>
/// 扩展
/// </summary>
public static class CodeLessExtension
{
/// <summary>
/// 添加子节点
/// </summary>
/// <param name="codeLess"></param>
/// <param name="less"></param>
public static void AddChild(this CodeLess codeLess, CodeLess less)
{
if (codeLess.Children == null)
{
codeLess.Children = new List<CodeLess>();
}
codeLess.Children.Add(less);
}
/// <summary>
/// 添加子节点
/// </summary>
/// <param name="codeLess"></param>
/// <param name="name"></param>
public static CodeLess AddChild(this CodeLess codeLess, string name)
{
if (codeLess.Children == null)
{
codeLess.Children = new List<CodeLess>();
}
CodeLess less = new CodeLess();
less.Name = name;
codeLess.Children.Add(less);
return less;
}
}
}
|
using ValveMultitool.Models.Formats.Lump;
namespace ValveMultitool.Models.Formats.GameStats.Legacy.Custom
{
public interface IVersion : ILumpElement
{
byte Version { get; set; }
byte Magic { get; set; }
}
}
|
<div class="text-left">
<h2>Multi-Scale Structural SIMilarity (MS-SSIM)</h2>
<div>
<p>
<a href="https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf">Multi-Scale Structural SIMilarity</a>
(MS-SSIM) is layered on SSIM. The algorithm calculates multiple SSIM
values at multiple image scales (resolutions). By running the algorithm at different scales,
the quality of the image is evaluated for different viewing distances. MS-SSIM also puts less
emphasis on the luminance component compared to the contrast and structure components. In
total, MS-SSIM has been shown to increase the correlation between the MS-SSIM index and
subjective quality tests. However, the trade-off is that MS-SSIM takes a few times longer
to run than the straight SSIM algorithm. The detailed information you can refer to <a href="#ref">here</a> or this
<a href="http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=1292216&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D1292216">
paper</a> directly.
</p>
</div>
</div>
|
using System.Collections.ObjectModel;
using System.Linq;
using UtilitiesBills.Models;
using UtilitiesBills.Reports;
using UtilitiesBills.Services;
using UtilitiesBills.ViewModels.Base;
using Xamarin.Forms;
namespace UtilitiesBills.ViewModels
{
public class BillsViewModel : BaseViewModel
{
public ObservableCollection<BillItem> BillsItems { get; private set; } =
new ObservableCollection<BillItem>();
public Command AddBillCommand { get; private set; }
public Command<int> GenerateSmsReportCommand { get; private set; }
public BillsViewModel()
{
SubscribeToModifyBillRepository();
RefreshBillsItems();
InitializeCommands();
}
public void OnBillTapped(object sender, ItemTappedEventArgs e)
{
var bill = e.Item as BillItem;
var args = new BillEditorArgs
{
Bill = bill.Clone() as BillItem,
PreviousBill = GetPreviousBill(bill)
};
NavigationService.NavigateTo<BillEditorViewModel>(args);
}
private void InitializeCommands()
{
AddBillCommand = new Command(AddBill);
GenerateSmsReportCommand = new Command<int>(GenerateSmsReport);
}
private void AddBill()
{
var args = new BillEditorArgs
{
PreviousBill = GetLastBill()
};
NavigationService.NavigateTo<BillEditorViewModel>(args);
}
private async void GenerateSmsReport(int billId)
{
BillItem bill = BillsItems.First(b => b.Id == billId);
var smsReport = new SmsSimpleReport(DialogService, bill);
smsReport.Generate();
await smsReport.CopyToBuffer();
}
private BillItem GetLastBill()
{
BillItem lastBill = BillsItems
.OrderByDescending(b => b.DateOfReading)
.FirstOrDefault();
// Если нет платежей, то значения берем из настроек.
if (lastBill == null)
{
lastBill = GetInitBulks();
}
return lastBill.Clone() as BillItem;
}
private BillItem GetPreviousBill(BillItem bill)
{
BillItem prevBill = BillsItems
.Where(b => b.DateOfReading < bill.DateOfReading)
.OrderByDescending(b => b.DateOfReading)
.FirstOrDefault();
// Если нет платежей, то значения берем из настроек.
if (prevBill == null)
{
prevBill = GetInitBulks();
}
return prevBill.Clone() as BillItem;
}
private BillItem GetInitBulks()
{
return new BillItem()
{
HotWaterCounterBulkRounded = SettingsService.InitHotWaterBulk,
ColdWaterCounterBulkRounded = SettingsService.InitColdWaterBulk,
ElectricityCounterBulkRounded = SettingsService.InitElectricityBulk
};
}
private void SubscribeToModifyBillRepository()
{
MessagingCenter
.Subscribe<IRepository<BillItem>>(this, MessageKeys.AddBillItem, (s) => RefreshBillsItems());
MessagingCenter
.Subscribe<IRepository<BillItem>>(this, MessageKeys.DeleteBillItem, (s) => RefreshBillsItems());
MessagingCenter
.Subscribe<IRepository<BillItem>>(this, MessageKeys.UpdateBillItem, (s) => RefreshBillsItems());
MessagingCenter
.Subscribe<BackupInfoViewModel>(this, MessageKeys.DatabaseRestored, (s) => RefreshBillsItems());
}
private void RefreshBillsItems()
{
BillsItems.Clear();
IOrderedEnumerable<BillItem> bills = BillRepository.GetItems()
.OrderByDescending(b => b.DateOfReading);
foreach (BillItem bill in bills)
{
BillsItems.Add(bill);
}
}
}
}
|
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace CSharp9Sample
{
internal static class AwaitableExtensions
{
private static ValueTaskAwaiter<int> GetAwaiter(this int t)
{
return ValueTask.FromResult(t).GetAwaiter();
}
public static async void MainTest()
{
await 1;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using Microsoft.CodeAnalysis;
namespace System.Text.Json.Reflection
{
internal class ParameterInfoWrapper : ParameterInfo
{
private readonly IParameterSymbol _parameter;
private readonly MetadataLoadContextInternal _metadataLoadContext;
public ParameterInfoWrapper(IParameterSymbol parameter, MetadataLoadContextInternal metadataLoadContext)
{
_parameter = parameter;
_metadataLoadContext = metadataLoadContext;
}
public override Type ParameterType => _parameter.Type.AsType(_metadataLoadContext);
public override string Name => _parameter.Name;
public override IList<CustomAttributeData> GetCustomAttributesData()
{
var attributes = new List<CustomAttributeData>();
foreach (AttributeData a in _parameter.GetAttributes())
{
attributes.Add(new CustomAttributeDataWrapper(a, _metadataLoadContext));
}
return attributes;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
namespace Bot.Builder.Community.Cards.Management.Tree
{
internal class RichCardTreeNode<T> : TreeNode<T, IEnumerable<CardAction>>
where T : class
{
public RichCardTreeNode(Func<T, IEnumerable<CardAction>> buttonFactory)
: base((card, next) =>
{
// The nextAsync return value is not needed here because the Buttons property reference will remain unchanged
next(buttonFactory(card), TreeNodeType.CardActionList);
return card;
})
{
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
namespace Google.MaterialDesign.Icons
{
public class MaterialIconUGUI : Text
{
[SerializeField] MDTextIcon icon;
protected override void Start()
{
base.Start();
if (string.IsNullOrEmpty(base.text))
{
Init();
}
base.font = icon.Font.Font;
}
/// <summary> Properly initializes base Text class. </summary>
public void Init()
{
base.text = icon.Text;
base.font = icon.Font.Font;
base.color = new Color(0.196f, 0.196f, 0.196f, 1.000f);
base.material = null;
base.alignment = TextAnchor.MiddleCenter;
base.supportRichText = false;
base.horizontalOverflow = HorizontalWrapMode.Overflow;
base.verticalOverflow = VerticalWrapMode.Overflow;
base.fontSize = Mathf.FloorToInt(Mathf.Min(base.rectTransform.rect.width, base.rectTransform.rect.height));
}
protected override void OnRectTransformDimensionsChange()
{
base.OnRectTransformDimensionsChange();
base.fontSize = Mathf.FloorToInt(Mathf.Min(base.rectTransform.rect.width, base.rectTransform.rect.height));
}
public void UpdateIcon(MDTextIcon icon)
{
this.icon = icon;
base.font = icon.Font.Font;
base.text = icon.Text;
}
#if UNITY_EDITOR
protected override void Reset()
{
base.Reset();
Init();
}
protected override void OnValidate()
{
base.font = icon.Font.Font;
base.text = icon.Text;
base.OnValidate();
base.SetLayoutDirty();
}
#endif
}
}
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Data.Entity.Design.Refactoring
{
internal class CodeElementRenameData
{
internal RefactorTargetType RefactorTargetType { get; private set; }
internal string NewName { get; private set; }
internal string NewEntitySetName { get; private set; }
internal string OldName { get; private set; }
internal string OldEntitySetName { get; private set; }
internal string ParentEntityTypeName { get; private set; }
internal CodeElementRenameData(string newName, string newEntitySetName, string oldName, string oldEntitySetName)
{
NewName = newName;
NewEntitySetName = newEntitySetName;
OldName = oldName;
OldEntitySetName = oldEntitySetName;
RefactorTargetType = RefactorTargetType.Class;
}
internal CodeElementRenameData(string newName, string oldName, string parentEntityTypeName)
{
NewName = newName;
OldName = oldName;
ParentEntityTypeName = parentEntityTypeName;
RefactorTargetType = RefactorTargetType.Property;
}
}
}
|
using System;
namespace DAPNet
{
/// <summary>
/// Represents a naive declicker.
/// </summary>
public class NDeclicker : Declicker
{
/// <summary>
/// Holds the default order.
/// </summary>
public const int DefaultOrder = 5;
/// <summary>
/// Holds the derivative filter.
/// </summary>
private DerivativeFilter filter;
/// <summary>
/// Creates a new naive declicker with default settings.
/// </summary>
public NDeclicker() : this(DefaultOrder)
{
}
/// <summary>
/// Creates a new naive declicker.
/// </summary>
/// <param name="order">Order of the new naive declicker.</param>
public NDeclicker(int order)
{
filter = new DerivativeFilter(order);
}
/// <summary>
/// Gets excitations out of specified samples.
/// </summary>
/// <param name="samples">Samples to get excitations of.</param>
/// <returns>Excitations of specified samples.</returns>
public override SampleVector GetExcitations(SampleVector samples)
{
SampleVector f = samples.Clone();
filter.Process(f);
return f;
}
/// <summary>
/// Corrects specified degraded samples.
/// </summary>
/// <param name="samples">Degraded samples to correct.</param>
/// <param name="detection">Detection of degraded samples to correct.</param>
public override void Correct(SampleVector samples, DetectionVector detection)
{
int[] g = GetG(detection);
int[] o = GetO(detection);
for (int i = 0; i < samples.Count; i++)
{
if (detection[i])
{
double p_i = samples[i - o[i]];
double s_i = samples[i + g[i] - o[i] + 1];
double v_i = (double)o[i] / (g[i] + 1);
samples[i] = (1 - v_i) * p_i + v_i * s_i;
}
}
}
}
}
|
using EvernoteClone.ViewModels.Commands;
namespace EvernoteClone.ViewModels
{
public class SwitchLoginRegisterCommand : BaseCommand
{
private LoginViewModel _loginViewModel;
public SwitchLoginRegisterCommand(LoginViewModel loginViewModel)
=> _loginViewModel = loginViewModel;
public override bool CanExecute(object? parameter) => true;
public override void Execute(object? parameter) => _loginViewModel.SwitchLoginRegister();
}
} |
using System.Collections.Generic;
using CosmosApi.Serialization;
using Newtonsoft.Json;
namespace CosmosApi.Models
{
public class Deposit
{
/// <summary>
/// Initializes a new instance of the Deposit class.
/// </summary>
public Deposit()
{
}
/// <summary>
/// Initializes a new instance of the Deposit class.
/// </summary>
public Deposit(IList<Coin> amount, ulong proposalId, string depositor)
{
Amount = amount;
ProposalId = proposalId;
Depositor = depositor;
}
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "amount")]
public IList<Coin> Amount { get; set; } = null!;
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "proposal_id")]
[JsonConverter(typeof(StringNumberConverter))]
public ulong ProposalId { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "depositor")]
public string Depositor { get; set; } = null!;
}
}
|
using Ryujinx.Graphics.GAL.Multithreading.Commands.Sampler;
using Ryujinx.Graphics.GAL.Multithreading.Model;
namespace Ryujinx.Graphics.GAL.Multithreading.Resources
{
class ThreadedSampler : ISampler
{
private ThreadedRenderer _renderer;
public ISampler Base;
public ThreadedSampler(ThreadedRenderer renderer)
{
_renderer = renderer;
}
public void Dispose()
{
_renderer.New<SamplerDisposeCommand>().Set(new TableRef<ThreadedSampler>(_renderer, this));
_renderer.QueueCommand();
}
}
}
|
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage,
* (C) 2022 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using Minio.DataModel;
using Minio.Exceptions;
/*
* Certificate Identity Credential provider.
* This is a MinIO Extension to AssumeRole STS APIs on
* AWS, purely based on client certificates mTLS authentication.
*/
namespace Minio.Credentials;
[Serializable]
[XmlRoot(ElementName = "AssumeRoleWithCertificateResponse", Namespace = "https://sts.amazonaws.com/doc/2011-06-15/")]
public class CertificateResponse
{
[XmlElement(ElementName = "AssumeRoleWithCertificateResult")]
public CertificateResult cr { get; set; }
public string ToXML()
{
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
using (var ms = new MemoryStream())
{
var xmlWriter = XmlWriter.Create(ms, settings);
var names = new XmlSerializerNamespaces();
names.Add(string.Empty, "https://sts.amazonaws.com/doc/2011-06-15/");
var cs = new XmlSerializer(typeof(CertificateResponse));
cs.Serialize(xmlWriter, this, names);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(ms);
var xml = streamReader.ReadToEnd();
return xml;
}
}
[Serializable]
[XmlRoot(ElementName = "AssumeRoleWithCertificateResult")]
public class CertificateResult
{
[XmlElement(ElementName = "Credentials")]
public AccessCredentials Credentials { get; set; }
public AccessCredentials GetAccessCredentials()
{
return Credentials;
}
}
}
public class CertificateIdentityProvider : ClientProvider
{
private readonly int DEFAULT_DURATION_IN_SECONDS = 3600;
public CertificateIdentityProvider()
{
durationInSeconds = DEFAULT_DURATION_IN_SECONDS;
}
internal string stsEndpoint { get; set; }
internal int durationInSeconds { get; set; }
internal X509Certificate2 clientCertificate { get; set; }
internal string postEndpoint { get; set; }
internal HttpClient httpClient { get; set; }
internal AccessCredentials credentials { get; set; }
public CertificateIdentityProvider WithStsEndpoint(string stsEndpoint)
{
if (string.IsNullOrEmpty(stsEndpoint))
throw new InvalidEndpointException("Missing mandatory argument: stsEndpoint");
if (!stsEndpoint.StartsWith("https", StringComparison.OrdinalIgnoreCase))
throw new InvalidEndpointException(
$"stsEndpoint {stsEndpoint} is invalid." +
" The scheme must be https");
this.stsEndpoint = stsEndpoint;
return this;
}
public CertificateIdentityProvider WithHttpClient(HttpClient httpClient = null)
{
this.httpClient = httpClient;
return this;
}
public CertificateIdentityProvider WithCertificate(X509Certificate2 cert = null)
{
clientCertificate = cert;
return this;
}
public override AccessCredentials GetCredentials()
{
if (credentials != null && !credentials.AreExpired()) return credentials;
if (httpClient == null) throw new ArgumentException("httpClient cannot be null or empty");
if (clientCertificate == null) throw new ArgumentException("clientCertificate cannot be null or empty");
var t = Task.Run(async () => await httpClient.PostAsync(postEndpoint, null));
t.Wait();
var response = t.Result;
var certResponse = new CertificateResponse();
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var contentBytes = Encoding.UTF8.GetBytes(content);
using (var stream = new MemoryStream(contentBytes))
{
certResponse =
(CertificateResponse)new XmlSerializer(typeof(CertificateResponse)).Deserialize(stream);
}
}
if (credentials == null &&
certResponse != null &&
certResponse.cr != null)
credentials = certResponse.cr.Credentials;
return credentials;
}
public override async Task<AccessCredentials> GetCredentialsAsync()
{
var credentials = GetCredentials();
await Task.Yield();
return credentials;
}
public CertificateIdentityProvider Build()
{
if (string.IsNullOrEmpty(durationInSeconds.ToString())) durationInSeconds = DEFAULT_DURATION_IN_SECONDS;
var builder = new UriBuilder(stsEndpoint);
var query = HttpUtility.ParseQueryString(builder.Query);
query["Action"] = "AssumeRoleWithCertificate";
query["Version"] = "2011-06-15";
query["DurationInSeconds"] = durationInSeconds.ToString();
builder.Query = query.ToString();
postEndpoint = builder.ToString();
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(clientCertificate);
httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(stsEndpoint)
};
credentials = GetCredentials();
return this;
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using PuroBot.Discord.Services;
namespace PuroBot.Discord.Modules
{
public class MusicModule : ModuleBase<SocketCommandContext>
{
public MusicModule(VoiceConnectionService voice)
{
_voice = voice;
}
private static CancellationTokenSource _ctsPlaylist = new();
private static CancellationTokenSource _ctsSingle = new();
// [Command("play")]
// [Summary("play music from a link")]
// public async Task Play([Remainder] [Summary("the link to play")] Url target)
// {
// await PlayInternal(target.Value);
// }
[Command("play")]
[Summary("play music from a youtube search")]
public async Task Play([Remainder] [Summary("the youtube search")] string query)
{
await Stop();
_ctsPlaylist.Dispose();
_ctsPlaylist = new CancellationTokenSource();
string target = Uri.TryCreate(query, UriKind.Absolute, out _) ? query : $"ytsearch:{query}";
try
{
await foreach (var url in GetUrls(target, _ctsPlaylist.Token))
{
_ctsSingle.Dispose();
_ctsSingle = new CancellationTokenSource();
try
{
await PlayUrl(url, _ctsSingle.Token);
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException) { }
}
}
catch (Exception ex) when (ex is TaskCanceledException or OperationCanceledException) { }
}
[Command("skip")]
[Summary("skip one playlist entry")]
public Task Skip()
{
_ctsSingle.Cancel(false);
return Task.CompletedTask;
}
[Command("stop")]
[Summary("stops music playback")]
public Task Stop()
{
_ctsPlaylist.Cancel(false);
_ctsSingle.Cancel(false);
return Task.CompletedTask;
}
private readonly VoiceConnectionService _voice;
private async IAsyncEnumerable<string> GetUrls(string query, [EnumeratorCancellation] CancellationToken ct)
{
const string ytdlPath = "/usr/bin/youtube-dl";
const string ytdlpPath = "/usr/bin/youtube-dlp";
string downloaderPath = File.Exists(ytdlpPath) ? ytdlpPath : ytdlPath;
var ytdlInfo = new ProcessStartInfo
{
FileName = downloaderPath,
Arguments = $"-gf bestaudio \"{query}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using Process? ytdl = Process.Start(ytdlInfo);
if (ytdl is null)
{
await Context.Message.ReplyAsync("ytdl process could not be started");
yield break;
}
while (!ct.IsCancellationRequested && !ytdl.HasExited)
{
string? line = await ytdl.StandardOutput.ReadLineAsync();
if (line is not null)
yield return line;
}
await ytdl.WaitForExitAsync(ct);
if (ytdl.ExitCode <= 0)
yield break;
await Context.Message.ReplyAsync(await ytdl.StandardError.ReadToEndAsync());
}
private async Task PlayUrl(string target, CancellationToken ct)
{
const string ffmpegPath = "/usr/bin/ffmpeg";
var ffmpegInfo = new ProcessStartInfo
{
FileName = ffmpegPath,
Arguments = $"-i {target} -ac 2 -ar 48000 -f s16le -",
RedirectStandardOutput = true,
UseShellExecute = false
};
using Process? ffmpeg = Process.Start(ffmpegInfo);
if (ffmpeg is null)
{
await Context.Message.ReplyAsync("ffmpeg process could not be started");
return;
}
using var channelAcquirer = await VoiceConnectionService.ChannelHandle.Create(_voice, Context);
VoiceConnectionService.VoiceInfo? voiceInfo = channelAcquirer.VoiceInfo;
if (voiceInfo is null) //failed to connect
return;
await ffmpeg.StandardOutput.BaseStream.CopyToAsync(voiceInfo.AudioStream, ct);
}
}
}
|
using System;
namespace SFA.DAS.Authorization
{
public class UserContext : IUserContext
{
public long Id { get; set; }
public Guid Ref { get; set; }
public string Email { get; set; }
}
} |
namespace Lasm.UAlive
{
/// <summary>
/// A representation of X Y and Z axis. Used for selecting a single axis.
/// </summary>
public enum Axis
{
X, Y, Z
}
} |
using Codegen.CodegenAttributes;
using Codegen.CodegenAttributes.Bounds;
using UnityEngine;
namespace Sources.CommandSchemes.Common
{
[CommandToClient]
[CommandToServer]
public class TestScheme
{
[BoundedVector3(-1,1,0.01f,-1,1,0.01f,-1,-1,0.01f)]
public Vector3 Value;
public bool BoolValue;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp6.Controllers;
using WindowsFormsApp6.Models;
using WindowsFormsApp6.Providers;
namespace WindowsFormsApp6.Views
{
public partial class SpecialtiesForm : Form
{
public DataGridView SpecialtiesGridView
{
get => this.specialtiesGridView;
set { this.specialtiesGridView = value; }
}
public SpecialtiesForm(StorageContext context)
{
InitializeComponent();
SpecialtiesController specialtiesController = new SpecialtiesController(context, this);
this.addButtonSpecialtiesForm.Click += specialtiesController.AddButton_Click;
this.updateButtonSpecialtiesForm.Click += specialtiesController.UpdateButton_Click;
this.editButtonSpecialtiesForm.Click += specialtiesController.EditButton_Click;
}
public DialogResult ShowDialog(List<Specialty> specialties)
{
this.specialtiesGridView.DataSource = specialties;
return base.ShowDialog();
}
}
}
|
using System.IO;
using System.Net.Http;
using IntegrationTests.Helpers;
using Xunit;
using Xunit.Abstractions;
namespace IntegrationTests.AspNet
{
public class AspNetTests : TestHelper
{
private static readonly string SampleDir = Path.Combine("test", "test-applications", "integrations", "aspnet");
public AspNetTests(ITestOutputHelper output)
: base(new EnvironmentHelper("AspNet", typeof(TestHelper), output, samplesDirectory: SampleDir), output)
{
}
[Fact]
[Trait("Category", "EndToEnd")]
[Trait("WindowsOnly", "True")]
public void SubmitsTraces()
{
int agentPort = TcpPortProvider.GetOpenPort();
int webPort = TcpPortProvider.GetOpenPort();
using (var fwPort = FirewallHelper.OpenWinPort(agentPort, Output))
using (var agent = new MockZipkinCollector(Output, agentPort))
using (var container = StartContainer(agentPort, webPort))
{
HttpClient client = new HttpClient();
var response = client.GetAsync($"http://localhost:{webPort}").Result;
var content = response.Content.ReadAsStringAsync().Result;
Output.WriteLine("Sample response:");
Output.WriteLine(content);
var spans = agent.WaitForSpans(1);
Assert.True(spans.Count >= 1, $"Expecting at least 1 span, only received {spans.Count}");
}
}
}
}
|
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
namespace Messenger.Webhook.DotNet.Sample.Services
{
/// <summary>
/// https://developers.facebook.com/docs/messenger-platform/reference/send-api/
/// </summary>
public class FacebookApi
{
private const string BASE_API_URL = "https://graph.facebook.com/v2.6/me/messages";
private string AccessToken { get; set; }
public FacebookApi()
{
LoadConfiguration();
}
public async Task<bool> SendMessage(string recipientId, string text)
{
string url = $"{BASE_API_URL}?access_token={AccessToken}";
bool isSuccessful = false;
using(HttpClient http = new HttpClient())
{
object requestBody = new
{
messaging_type = "RESPONSE",
recipient = new
{
id = recipientId
},
message = new
{
text = text
}
};
HttpResponseMessage apiResponse = await http.PostAsJsonAsync(url, requestBody);
isSuccessful = apiResponse.IsSuccessStatusCode;
}
return isSuccessful;
}
private void LoadConfiguration()
{
AccessToken = ConfigurationManager.AppSettings["FbPageAccessToken"];
}
}
} |
namespace FirebaseCoreSDK.Logging
{
/// <summary>
/// FirebaseNullLogger which does not log.
/// </summary>
/// <seealso cref="FirebaseConsoleLogger" />
public class FirebaseNullLogger : FirebaseConsoleLogger
{
public FirebaseNullLogger()
: this(LogLevel.None) {}
public FirebaseNullLogger(LogLevel logLevel)
: base(logLevel) {}
}
} |
// Copyright and license at: https://github.com/MatthewMWR/MeasureTraceAutomation/blob/master/LICENSE
using System.Diagnostics;
using MeasureTraceAutomation.Logging;
namespace MeasureTraceAutomation
{
public static class Automate
{
public static void InvokeProcessingOnce(ProcessingConfig processingConfig, MeasurementStoreConfig storeConfig)
{
RichLog.Log.StartProcessEndToEnd(0);
ForwardMeasureTraceLogging.AddListenerAsNeeded();
AutomationTasks.DiscoverOneBatch(processingConfig, storeConfig);
var moved = AutomationTasks.MoveOneBatch(processingConfig, storeConfig);
var measured = AutomationTasks.MeasureOneBatch(processingConfig, storeConfig);
RichLog.Log.StopProcessEndToEnd(moved, measured);
}
}
} |
using MongoDB.Driver;
namespace JobOfferBackend.ApplicationServices.Test.Base
{
public class SetupIntegrationTest
{
private readonly static MongoClient _mongoClient = new MongoClient();
private const string TestDataBaseName = "JobOfferIntegrationTests";
public static IMongoDatabase DatabaseTest
{
get
{
return _mongoClient.GetDatabase(TestDataBaseName);
}
}
public static void OneTimeSetUp()
{
_mongoClient.GetDatabase(TestDataBaseName);
}
public static void OneTimeTearDown()
{
_mongoClient.DropDatabase(TestDataBaseName);
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace WickedSick.Thea.VisualStudioInterop
{
public class ComMessageFilter : IOleMessageFilter
{
const int SERVERCALL_ISHANDLED = 0;
const int SERVERCALL_RETRYLATER = 2;
const int PENDINGMSG_WAITDEFPROCESS = 2;
public static void Register()
{
IOleMessageFilter newFilter = new ComMessageFilter();
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(newFilter, out oldFilter);
}
public static void Revoke()
{
IOleMessageFilter oldFilter = null;
CoRegisterMessageFilter(null, out oldFilter);
}
public int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
{
return SERVERCALL_ISHANDLED;
}
public int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
{
if (dwRejectType == SERVERCALL_RETRYLATER)
{
// Retry the thread call immediately if return >=0 & <100.
return 99;
}
return -1; // Too busy; cancel call.
}
public int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
{
return PENDINGMSG_WAITDEFPROCESS;
}
[DllImport("Ole32.dll")]
private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter);
}
[ComImport(), Guid("00000016-0000-0000-C000-000000000046"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
interface IOleMessageFilter
{
[PreserveSig]
int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
[PreserveSig]
int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
[PreserveSig]
int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
}
} |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using CookBook.Model;
namespace CookBook.ViewModel
{
public class RecipeDetailsViewModel : BaseViewModel
{
#region Properties
private Recipe recipe;
public Recipe Recipe
{
get => recipe;
set
{
if (recipe == value)
return;
recipe = value;
OnPropertyChanged();
}
}
#endregion
#region Commands
public Command OpenMapCommand { get; }
#endregion
#region Constructors
public RecipeDetailsViewModel() : base(title: "Details")
{
OpenMapCommand = new Command(async () => await OpenMapAsync());
}
public RecipeDetailsViewModel(Recipe recipe) : base(title: $"{recipe.Name}")
{
Recipe = recipe;
OpenMapCommand = new Command(async () => await OpenMapAsync());
}
#endregion
#region Methods
private async Task OpenMapAsync()
{
try
{
await Maps.OpenAsync(Recipe.Latitude, Recipe.Longitude);
}
catch (Exception ex)
{
Debug.WriteLine($"Unable to launch maps: {ex.Message}");
await Application.Current.MainPage.DisplayAlert("Error, no Maps app!", ex.Message, "OK");
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ERP.DAL
{
public class Parameters
{
public System.Collections.Hashtable collection = new System.Collections.Hashtable();
public void Add(MySql.Data.MySqlClient.MySqlParameter param)
{
collection.Add(param.ParameterName, param);
}
public MySqlParameter Get(string paramName)
{
return (MySqlParameter)collection[paramName];
}
}
}
|
namespace NL.HNOGames.Domoticz.Models
{
/// <summary>
/// Defines the <see cref="SunRiseModel" />
/// </summary>
public class SunRiseModel
{
#region Properties
/// <summary>
/// Gets or sets the AstrTwilightEnd
/// </summary>
public string AstrTwilightEnd { get; set; }
/// <summary>
/// Gets or sets the AstrTwilightStart
/// </summary>
public string AstrTwilightStart { get; set; }
/// <summary>
/// Gets or sets the CivTwilightEnd
/// </summary>
public string CivTwilightEnd { get; set; }
/// <summary>
/// Gets or sets the CivTwilightStart
/// </summary>
public string CivTwilightStart { get; set; }
/// <summary>
/// Gets or sets the DayLength
/// </summary>
public string DayLength { get; set; }
/// <summary>
/// Gets or sets the NautTwilightEnd
/// </summary>
public string NautTwilightEnd { get; set; }
/// <summary>
/// Gets or sets the NautTwilightStart
/// </summary>
public string NautTwilightStart { get; set; }
/// <summary>
/// Gets or sets the ServerTime
/// </summary>
public string ServerTime { get; set; }
/// <summary>
/// Gets or sets the SunAtSouth
/// </summary>
public string SunAtSouth { get; set; }
/// <summary>
/// Gets or sets the Sunrise
/// </summary>
public string Sunrise { get; set; }
/// <summary>
/// Gets or sets the Sunset
/// </summary>
public string Sunset { get; set; }
/// <summary>
/// Gets or sets the status
/// </summary>
public string status { get; set; }
/// <summary>
/// Gets or sets the title
/// </summary>
public string title { get; set; }
#endregion
}
}
|
namespace Nyancat
{
partial struct AnsiConsole
{
private const string HIDE_CURSOR = "\x1b[?25l";
private const string RESET_CURSOR = "\x1b[H";
private const string SHOW_CURSOR = "\x1b[?25h";
private const string CLEAR_SCREEN = "\x1b[2J";
private const string RESET_ALL_ATTRIBUTES = "\x1b[0m";
public AnsiConsole HideCursor()
{
if (_hasAnsiSupport) Write(HIDE_CURSOR);
return this;
}
public AnsiConsole ResetCursor()
{
if (_hasAnsiSupport)
{
Write(RESET_CURSOR);
}
else
{
System.Console.CursorTop = 0;
System.Console.CursorLeft = 0;
}
return this;
}
public AnsiConsole ResetAll()
{
if (_hasAnsiSupport)
{
Write($"{SHOW_CURSOR}{RESET_ALL_ATTRIBUTES}{RESET_CURSOR}{CLEAR_SCREEN}");
WriteLine();
Flush();
}
else
{
System.Console.Clear();
}
return this;
}
}
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type Dep Enrollment Base Profile.
/// </summary>
[JsonConverter(typeof(DerivedTypeConverter<DepEnrollmentBaseProfile>))]
public partial class DepEnrollmentBaseProfile : EnrollmentProfile
{
///<summary>
/// The internal DepEnrollmentBaseProfile constructor
///</summary>
protected internal DepEnrollmentBaseProfile()
{
// Don't allow initialization of abstract entity types
}
/// <summary>
/// Gets or sets apple id disabled.
/// Indicates if Apple id setup pane is disabled
/// </summary>
[JsonPropertyName("appleIdDisabled")]
public bool? AppleIdDisabled { get; set; }
/// <summary>
/// Gets or sets apple pay disabled.
/// Indicates if Apple pay setup pane is disabled
/// </summary>
[JsonPropertyName("applePayDisabled")]
public bool? ApplePayDisabled { get; set; }
/// <summary>
/// Gets or sets configuration web url.
/// URL for setup assistant login
/// </summary>
[JsonPropertyName("configurationWebUrl")]
public bool? ConfigurationWebUrl { get; set; }
/// <summary>
/// Gets or sets device name template.
/// Sets a literal or name pattern.
/// </summary>
[JsonPropertyName("deviceNameTemplate")]
public string DeviceNameTemplate { get; set; }
/// <summary>
/// Gets or sets diagnostics disabled.
/// Indicates if diagnostics setup pane is disabled
/// </summary>
[JsonPropertyName("diagnosticsDisabled")]
public bool? DiagnosticsDisabled { get; set; }
/// <summary>
/// Gets or sets display tone setup disabled.
/// Indicates if displaytone setup screen is disabled
/// </summary>
[JsonPropertyName("displayToneSetupDisabled")]
public bool? DisplayToneSetupDisabled { get; set; }
/// <summary>
/// Gets or sets is default.
/// Indicates if this is the default profile
/// </summary>
[JsonPropertyName("isDefault")]
public bool? IsDefault { get; set; }
/// <summary>
/// Gets or sets is mandatory.
/// Indicates if the profile is mandatory
/// </summary>
[JsonPropertyName("isMandatory")]
public bool? IsMandatory { get; set; }
/// <summary>
/// Gets or sets location disabled.
/// Indicates if Location service setup pane is disabled
/// </summary>
[JsonPropertyName("locationDisabled")]
public bool? LocationDisabled { get; set; }
/// <summary>
/// Gets or sets privacy pane disabled.
/// Indicates if privacy screen is disabled
/// </summary>
[JsonPropertyName("privacyPaneDisabled")]
public bool? PrivacyPaneDisabled { get; set; }
/// <summary>
/// Gets or sets profile removal disabled.
/// Indicates if the profile removal option is disabled
/// </summary>
[JsonPropertyName("profileRemovalDisabled")]
public bool? ProfileRemovalDisabled { get; set; }
/// <summary>
/// Gets or sets restore blocked.
/// Indicates if Restore setup pane is blocked
/// </summary>
[JsonPropertyName("restoreBlocked")]
public bool? RestoreBlocked { get; set; }
/// <summary>
/// Gets or sets screen time screen disabled.
/// Indicates if screen timeout setup is disabled
/// </summary>
[JsonPropertyName("screenTimeScreenDisabled")]
public bool? ScreenTimeScreenDisabled { get; set; }
/// <summary>
/// Gets or sets siri disabled.
/// Indicates if siri setup pane is disabled
/// </summary>
[JsonPropertyName("siriDisabled")]
public bool? SiriDisabled { get; set; }
/// <summary>
/// Gets or sets supervised mode enabled.
/// Supervised mode, True to enable, false otherwise. See https://docs.microsoft.com/intune/deploy-use/enroll-devices-in-microsoft-intune for additional information.
/// </summary>
[JsonPropertyName("supervisedModeEnabled")]
public bool? SupervisedModeEnabled { get; set; }
/// <summary>
/// Gets or sets support department.
/// Support department information
/// </summary>
[JsonPropertyName("supportDepartment")]
public string SupportDepartment { get; set; }
/// <summary>
/// Gets or sets support phone number.
/// Support phone number
/// </summary>
[JsonPropertyName("supportPhoneNumber")]
public string SupportPhoneNumber { get; set; }
/// <summary>
/// Gets or sets terms and conditions disabled.
/// Indicates if 'Terms and Conditions' setup pane is disabled
/// </summary>
[JsonPropertyName("termsAndConditionsDisabled")]
public bool? TermsAndConditionsDisabled { get; set; }
/// <summary>
/// Gets or sets touch id disabled.
/// Indicates if touch id setup pane is disabled
/// </summary>
[JsonPropertyName("touchIdDisabled")]
public bool? TouchIdDisabled { get; set; }
}
}
|
using System;
using Netezos.Keys.Utils.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using BcEd25519 = Org.BouncyCastle.Math.EC.Rfc8032.Ed25519;
namespace Netezos.Keys.Crypto
{
class Ed25519 : ICurve
{
#region static
static readonly byte[] _AddressPrefix = { 6, 161, 159 };
static readonly byte[] _PublicKeyPrefix = { 13, 15, 37, 217 };
static readonly byte[] _PrivateKeyPrefix = { 43, 246, 78, 7 };
static readonly byte[] _SignaturePrefix = { 9, 245, 205, 134, 18 };
#endregion
public ECKind Kind => ECKind.Ed25519;
public byte[] AddressPrefix => _AddressPrefix;
public byte[] PublicKeyPrefix => _PublicKeyPrefix;
public byte[] PrivateKeyPrefix => _PrivateKeyPrefix;
public byte[] SignaturePrefix => _SignaturePrefix;
public byte[] GetPrivateKey(byte[] bytes)
{
var result = new byte[64];
Buffer.BlockCopy(bytes, 0, result, 0, 32);
BcEd25519.GeneratePublicKey(result, 0, result, 32);
return result;
}
public byte[] GetPublicKey(byte[] privateKey)
{
var publicKey = new byte[32];
BcEd25519.GeneratePublicKey(privateKey, 0, publicKey, 0);
return publicKey;
}
public Signature Sign(byte[] msg, byte[] prvKey)
{
var digest = Blake2b.GetDigest(msg);
var privateKey = new Ed25519PrivateKeyParameters(prvKey, 0);
var signer = new Ed25519Signer();
signer.Init(true, privateKey);
signer.BlockUpdate(digest, 0, digest.Length);
return new Signature(signer.GenerateSignature(), _SignaturePrefix);
}
public bool Verify(byte[] msg, byte[] sig, byte[] pubKey)
{
var keyedHash = Blake2b.GetDigest(msg);
var publicKey = new Ed25519PublicKeyParameters(pubKey, 0);
var verifier = new Ed25519Signer();
verifier.Init(false, publicKey);
verifier.BlockUpdate(keyedHash, 0, keyedHash.Length);
return verifier.VerifySignature(sig);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Bakery.Models;
using System;
namespace Bakery.Tests
{
[TestClass]
public class OrderTests : IDisposable
{
public void Dispose()
{
Order.ClearAll();
}
[TestMethod]
public void OrderConstructor_CreatesInstanceOfOrder_Order()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
Order testOrder = new Order(title, description, date, price);
Assert.AreEqual(typeof(Order), testOrder.GetType());
}
[TestMethod]
public void GetDescription_ReturnsDescription_String()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
Order testOrder = new Order(title, description, date, price);
string result = testOrder.Description;
Assert.AreEqual(description, result);
}
[TestMethod]
public void SetDescription_SetDescription_String()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
Order testOrder = new Order(title, description, date, price);
string updatedDescription = "updated test";
testOrder.Description = updatedDescription;
string result = testOrder.Description;
Assert.AreEqual(updatedDescription, result);
}
[TestMethod]
public void GetAll_ReturnsEmptyList_OrderList()
{
List<Order> testList = new List<Order> { };
List<Order> result = Order.GetAll();
CollectionAssert.AreEqual(testList, result);
}
[TestMethod]
public void GetAll_ReturnsOrders_OrderList()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
string title0 = "Coffee shop wants cookies";
string description0 = "cookies";
string date0 = "02/04/1999";
int price0 = 50;
Order testOrder = new Order(title, description, date, price);
Order testOrder0 = new Order(title0, description0, date0, price0);
List<Order> testList = new List<Order> { testOrder, testOrder0 };
List<Order> result = Order.GetAll();
CollectionAssert.AreEqual(testList, result);
}
[TestMethod]
public void GetId_OrdersInstantiateWithAnIdAndGetterReturns_Int()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
Order testOrder = new Order(title, description, date, price);
int result = testOrder.Id;
Assert.AreEqual(1, result);
}
[TestMethod]
public void Find_ReturnsCorrectOrder_Order()
{
string title = "test title";
string description = "test description";
string date = "02/04/2022";
int price = 250;
string title0 = "Coffee shop wants cookies";
string description0 = "cookies";
string date0 = "02/04/1999";
int price0 = 50;
Order testOrder = new Order(title, description, date, price);
Order testOrder0 = new Order(title0, description0, date0, price0);
Order result = Order.Find(2);
Assert.AreEqual(testOrder0, result);
}
}
} |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.Data.Entity.Metadata;
namespace Microsoft.Data.Entity.ChangeTracking.Internal
{
public class StoreGeneratedValuesFactory : IStoreGeneratedValuesFactory
{
public virtual StoreGeneratedValues Create(InternalEntityEntry entry, IEnumerable<IProperty> properties)
=> new StoreGeneratedValues(entry, properties);
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LogentriesCore
{
internal class LogEntryEncoder : ILogEntryEncoder
{
public LogEntryEncoder(Encoding encoding)
{
Debug.Assert(encoding != null, $"{nameof(encoding)} != null");
this.Encoding = encoding;
}
public Encoding Encoding { get; }
public byte[] EncodeEntry(ILogEntry entry)
{
return this.Encoding.GetBytes(entry.Line);
}
}
}
|
namespace Yoba.Bot.RegularExpressions;
public class Exept : Re
{
public override string ToString()
{
throw new NotImplementedException();
}
} |
namespace Sample.Functional.Migrations
{
using FluentMigrator;
[Migration(201712261133)]
public class M201712261133_SchemaInicial : Migration
{
public override void Up()
{
Create.Table("Usuario").WithDescription("Tabela de usuários")
.WithColumn("Id").AsInt32().Identity().PrimaryKey("PK_Usuario")
.WithColumn("Nome").AsString(256).NotNullable()
.WithColumn("Idade").AsInt16().NotNullable();
Create.Table("TipoDeTelefone").WithDescription("Tabela de tipos de telefones")
.WithColumn("Id").AsInt32().PrimaryKey("PK_TipoDeTelefone")
.WithColumn("Tipo").AsString().NotNullable();
Create.Table("Telefone").WithDescription("Tabela de telefones")
.WithColumn("Id").AsInt32().Identity().PrimaryKey("PK_Telefone")
.WithColumn("IdUsuario").AsInt32()
.ForeignKey("FK_Telefone_Usuario", "Usuario", "Id")
.WithColumn("IdTipoDeTelefone").AsInt32().NotNullable()
.ForeignKey("FK_Telefone_TipoDeTelefone", "TipoDeTelefone", "Id")
.WithColumn("DDD").AsInt16().NotNullable()
.WithColumn("Numero").AsInt32().NotNullable();
Insert.IntoTable("TipoDeTelefone")
.Row(new { Id = 1, Tipo = "Residencial" })
.Row(new { Id = 2, Tipo = "Celular" })
.Row(new { Id = 3, Tipo = "Comercial" });
}
public override void Down()
{
Delete.FromTable("TipoDeTelefone");
Delete.ForeignKey("FK_Telefone_TipoDeTelefone");
Delete.ForeignKey("FK_Telefone_Usuario");
Delete.PrimaryKey("PK_Telefone");
Delete.PrimaryKey("PK_TipoDeTelefone");
Delete.PrimaryKey("PK_Usuario");
}
}
}
|
namespace Shinden.Models
{
public enum MangaStatus
{
NotSpecified,
NotYetPublished,
Publishing,
Finished,
}
}
|
// 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.
#if DEBUG
#endif
internal static partial class Interop
{
internal static partial class Gdi32
{
/// <summary>
/// Helper to scope selecting a given background mix mode into a HDC. Restores the original
/// mix mode into the HDC when disposed.
/// </summary>
/// <remarks>
/// Use in a <see langword="using" /> statement. If you must pass this around, always pass by
/// <see langword="ref" /> to avoid duplicating the handle and resetting multiple times.
/// </remarks>
#if DEBUG
internal class SetBkModeScope : DisposalTracking.Tracker, IDisposable
#else
internal readonly ref struct SetBkModeScope
#endif
{
private readonly BKMODE _previousMode;
private readonly HDC _hdc;
/// <summary>
/// Selects <paramref name="bkmode"/> into the given <paramref name="hdc"/>.
/// </summary>
public SetBkModeScope(HDC hdc, BKMODE bkmode)
{
_previousMode = SetBkMode(hdc, bkmode);
// If we didn't actually change the mode, don't keep the HDC so we skip putting back the same state.
_hdc = _previousMode == bkmode ? default : hdc;
}
public void Dispose()
{
if (!_hdc.IsNull)
{
SetBkMode(_hdc, _previousMode);
}
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
}
}
}
|
namespace Modular.Abstractions.Messaging
{
public interface IMessageContextProvider
{
IMessageContext Get(IMessage message);
}
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using LRS.Business;
namespace LRS.Mvc.Models
{
public class ArtifactModel
{
#region Properties
public int MainId { get; set; }
public string Status => Main?.Status;
public StatusEnum? StatusEnum => Main?.StatusEnum;
public MainObject Main { get; set; } = new MainObject();
public ReviewObject Reviewer => Main?.ActiveReviewer;
public bool IsActiveReviewer => Main?.IsActiveReviewer ?? false;
public int? ReviewId => Reviewer?.ReviewId;
public ReviewerTypeEnum? ReviewerType => Reviewer?.ReviewerTypeEnum;
//Selected Tab
public string SelectedTab { get; set; }
//Selected Tab End
#endregion
#region Extended Properties
[Display(Name = "Intellectual Property")]
public List<IntellectualPropertyObject> Intellectuals => Main?.Intellectuals;
[Display(Name = "Subject Category Codes")]
public List<MetaDataObject> SubjectCategories => Main?.SubjectCategories;
[Display(Name = "Core Capabilities")]
public List<MetaDataObject> CoreCapabilities => Main?.CoreCapabilities;
[Display(Name = "Keyword(s)")]
public List<MetaDataObject> KeywordList => Main?.KeyWordList;
[Display(Name = "Attachment(s)")]
public List<AttachmentObject> Attachments => Main?.Attachments;
public string OwnerName => Main?.OwnerName;
public int? ChildId => (Main != null && Main.ChildId.HasValue) ? Main.ChildId : null;
public int? ParentId => (Main != null && Main.ParentId.HasValue) ? Main.ParentId : null;
public string SortUrl
{
get
{
if (Main != null && Main.SortId.HasValue)
{
return $"{Config.SortUrl.TrailingSlash()}Artifact/Index/{Main.SortId}";
}
return string.Empty;
}
}
public bool Ouo3 { get; set; }
public bool Ouo7 { get; set; }
[Display(Name = "Derivative Classifier")]
public string Ouo7EmployeeId { get; set; }
public bool ShowAdminControls => IsReleaseOfficer || (Main?.IsSpecialReviewer ?? false);
public bool IsReleaseOfficer => Current.IsReleaseOfficer;
#endregion
#region Constructor
public ArtifactModel() { }
public ArtifactModel(int id, string selectedTab)
{
MainId = id;
SelectedTab = selectedTab;
HydrateData();
}
#endregion
#region Functions
public void HydrateData()
{
Main = MainObject.GetMain(MainId);
Ouo3 = Main?.Ouo3 ?? false;
Ouo7 = Main?.Ouo7 ?? false;
Ouo7EmployeeId = Main?.Ouo7EmployeeId ?? UserObject.CurrentUser.EmployeeId;
Main?.CheckForMissingData();
}
#endregion
}
} |
using System;
namespace FakeFx.Runtime
{
// used for tracking request invocation history for deadlock detection.
[Serializable]
[Hagar.GenerateSerializer]
internal sealed class RequestInvocationHistory
{
[Hagar.Id(1)]
public GrainId GrainId { get; private set; }
[Hagar.Id(2)]
public ActivationId ActivationId { get; private set; }
[Obsolete("Removed and unused. This member is retained only for serialization compatibility purposes.")]
[Hagar.Id(3)]
public string DebugContext { get; private set; }
public RequestInvocationHistory(GrainId grainId, ActivationId activationId)
{
this.GrainId = grainId;
this.ActivationId = activationId;
}
public override string ToString() => $"RequestInvocationHistory {GrainId}:{ActivationId}";
}
}
|
using System;
using System.Globalization;
using System.Windows.Data;
using MahApps.Metro.IconPacks;
namespace IconPacksValueConverterSample
{
public class BatteryValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// the value is in this case a double (comes from the Slider)
var percentage = (value as double?).GetValueOrDefault(0);
if (percentage < 10)
{
return PackIconMaterialKind.BatteryOutline;
}
else if (percentage < 20)
{
return PackIconMaterialKind.Battery10;
}
else if (percentage < 30)
{
return PackIconMaterialKind.Battery20;
}
else if (percentage < 40)
{
return PackIconMaterialKind.Battery30;
}
else if (percentage < 50)
{
return PackIconMaterialKind.Battery40;
}
else if (percentage < 60)
{
return PackIconMaterialKind.Battery50;
}
else if (percentage < 70)
{
return PackIconMaterialKind.Battery60;
}
else if (percentage < 80)
{
return PackIconMaterialKind.Battery70;
}
else if (percentage < 90)
{
return PackIconMaterialKind.Battery80;
}
else if (percentage < 100)
{
return PackIconMaterialKind.Battery90;
}
return PackIconMaterialKind.Battery;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// nothing here
throw new NotImplementedException();
}
}
} |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
using Microsoft.Practices.EnterpriseLibrary.Logging.Instrumentation;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Practices.EnterpriseLibrary.Logging.Tests
{
[TestClass]
public class TracerManagerFixture
{
[TestMethod]
public void GetTracerFromTraceManagerWithNoInstrumentation()
{
MockTraceListener.Reset();
LogSource source = new LogSource("tracesource", SourceLevels.All);
source.Listeners.Add(new MockTraceListener());
List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
LogWriter lg = new LogWriter(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);
TraceManager tm = new TraceManager(lg);
Assert.IsNotNull(tm);
using (tm.StartTrace("testoperation"))
{
Assert.AreEqual(1, MockTraceListener.Entries.Count);
}
Assert.AreEqual(2, MockTraceListener.Entries.Count);
}
[TestMethod]
public void GetTracerFromTraceManagerWithInstrumentationEnabled()
{
MockTraceListener.Reset();
LogSource source = new LogSource("tracesource", SourceLevels.All);
source.Listeners.Add(new MockTraceListener());
List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
LogWriter lg = new LogWriter(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);
TracerInstrumentationListener instrumentationListener = new TracerInstrumentationListener(true);
TraceManager tm = new TraceManager(lg, instrumentationListener);
Assert.IsNotNull(tm);
using (tm.StartTrace("testoperation"))
{
Assert.AreEqual(1, MockTraceListener.Entries.Count);
}
Assert.AreEqual(2, MockTraceListener.Entries.Count);
}
}
}
|
using System;
using System.Collections;
using System.Windows.Forms;
namespace ImageScraper.Utilities
{
/// <summary>
/// ListViewの項目の並び替えに使用するクラス
/// </summary>
public class ListViewItemComparer : IComparer
{
private int _column;
private SortOrder _order;
/// <summary>
/// 並び替えるListView列の番号
/// </summary>
public int Column
{
set
{
//現在と同じ列の時は、昇順降順を切り替える
if (_column == value)
{
if (_order == SortOrder.Ascending)
_order = SortOrder.Descending;
else if (_order == SortOrder.Descending)
_order = SortOrder.Ascending;
}
_column = value;
}
get
{
return _column;
}
}
/// <summary>
/// 昇順か降順か
/// </summary>
public SortOrder Order
{
set
{
_order = value;
}
get
{
return _order;
}
}
/// <summary>
/// ListViewItemComparerクラスのコンストラクタ
/// </summary>
/// <param name="col">並び替える列番号</param>
public ListViewItemComparer(int col, SortOrder ord)
{
_column = col;
_order = ord;
}
public ListViewItemComparer()
{
_column = 2;
_order = SortOrder.Descending;
}
// xがyより小さいときはマイナスの数、大きいときはプラスの数、
// 同じときは0を返す
public int Compare(object x, object y)
{
// ListViewItemの取得
ListViewItem itemx = (ListViewItem)x;
ListViewItem itemy = (ListViewItem)y;
// xとyを文字列として比較する
int result = String.Compare(itemx.SubItems[_column].Text, itemy.SubItems[_column].Text);
if (_order == SortOrder.Descending)
result = -result;
return result;
}
}
}
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.1
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace Vixen {
using System;
using System.Runtime.InteropServices;
public class Evaluator : Engine {
private HandleRef swigCPtr;
internal Evaluator(IntPtr cPtr, bool cMemoryOwn) : base(VixenLibPINVOKE.Evaluator_SWIGUpcast(cPtr), cMemoryOwn) {
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(Evaluator obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
~Evaluator() {
Dispose();
}
public override void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
VixenLibPINVOKE.delete_Evaluator(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
base.Dispose();
}
}
public Evaluator() : this(VixenLibPINVOKE.new_Evaluator(), true) {
}
public virtual void ClearDest() {
VixenLibPINVOKE.Evaluator_ClearDest(swigCPtr);
}
public int DestType {
set {
VixenLibPINVOKE.Evaluator_DestType_set(swigCPtr, value);
}
get {
int ret = VixenLibPINVOKE.Evaluator_DestType_get(swigCPtr);
return ret;
}
}
public int ValSize {
set {
VixenLibPINVOKE.Evaluator_ValSize_set(swigCPtr, value);
}
get {
int ret = VixenLibPINVOKE.Evaluator_ValSize_get(swigCPtr);
return ret;
}
}
public float Alpha {
set {
VixenLibPINVOKE.Evaluator_Alpha_set(swigCPtr, value);
}
get {
float ret = VixenLibPINVOKE.Evaluator_Alpha_get(swigCPtr);
return ret;
}
}
public static readonly int UNKNOWN = VixenLibPINVOKE.Evaluator_UNKNOWN_get();
public static readonly int POSITION = VixenLibPINVOKE.Evaluator_POSITION_get();
public static readonly int ROTATION = VixenLibPINVOKE.Evaluator_ROTATION_get();
public static readonly int SCALE = VixenLibPINVOKE.Evaluator_SCALE_get();
public static readonly int LOOK_ROTATION = VixenLibPINVOKE.Evaluator_LOOK_ROTATION_get();
public static readonly int LOCAL_POSITION = VixenLibPINVOKE.Evaluator_LOCAL_POSITION_get();
public static readonly int ALPHA = VixenLibPINVOKE.Evaluator_ALPHA_get();
public static readonly int XPOS = VixenLibPINVOKE.Evaluator_XPOS_get();
public static readonly int YPOS = VixenLibPINVOKE.Evaluator_YPOS_get();
public static readonly int ZPOS = VixenLibPINVOKE.Evaluator_ZPOS_get();
public static readonly int COLOR = VixenLibPINVOKE.Evaluator_COLOR_get();
public static readonly int FACE = VixenLibPINVOKE.Evaluator_FACE_get();
public static readonly int LAST_DEST_TYPE = VixenLibPINVOKE.Evaluator_LAST_DEST_TYPE_get();
public static readonly int STEP = VixenLibPINVOKE.Evaluator_STEP_get();
public static readonly int LINEAR = VixenLibPINVOKE.Evaluator_LINEAR_get();
public static readonly int QSTEP = VixenLibPINVOKE.Evaluator_QSTEP_get();
public static readonly int SLERP = VixenLibPINVOKE.Evaluator_SLERP_get();
public static readonly int MAX_KEY_SIZE = VixenLibPINVOKE.Evaluator_MAX_KEY_SIZE_get();
}
}
|
using System;
namespace EntidadesGeneral
{
public class Cliente
{
public int Id { get; set; }
public string Apellido { get; set; }
public string Nombre { get; set; }
public int Dni { get; set; }
public string Domicilio { get; set; }
public string Localidad { get; set; }
public long Cuit { get; set; }
public string Email { get; set; }
public string Telefono { get; set; }
}
}
|
namespace NEP.Paranoia.Managers
{
public class TickTemplate
{
public int id { get; set; }
public string name { get; set; }
public float tick { get; set; }
public float[] minMaxTime { get; set; }
public int[] minMaxRNG { get; set; }
public float insanity { get; set; }
public string runOnMaps { get; set; }
public string pEvent { get; set; }
}
}
|
using System;
using Captura.Base.Notification;
using Captura.Base.Services;
using Captura.Loc;
namespace Captura.Fakes
{
// ReSharper disable once ClassNeverInstantiated.Global
class FakeSystemTray : ISystemTray
{
readonly LanguageManager _loc;
public FakeSystemTray(LanguageManager loc)
{
_loc = loc;
}
public void HideNotification() { }
public void ShowScreenShotNotification(string filePath)
{
// ReSharper disable once LocalizableElement
Console.WriteLine($"{_loc.ScreenShotSaved}: {filePath}");
}
public void ShowNotification(INotification notification) { }
}
}
|
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* TradeSharp is a C# based data feed and broker neutral Algorithmic
* Trading Platform that lets trading firms or individuals automate
* any rules based trading strategies in stocks, forex and ETFs.
* TradeSharp allows users to connect to providers like Tradier Brokerage,
* IQFeed, FXCM, Blackwood, Forexware, Integral, HotSpot, Currenex,
* Interactive Brokers and more.
* Key features: Place and Manage Orders, Risk Management,
* Generate Customized Reports etc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using TraceSourceLogger;
using TradeHub.Common.Core.DomainModels.OrderDomain;
using TradeHub.Common.Core.Repositories.Parameters;
using TradeHub.ReportingEngine.CommunicationManager.Service;
namespace TradeHub.ReportingEngine.Client.Service
{
/// <summary>
/// Provides communication medium with Reporting Engine Server
/// </summary>
public class ReportingEngineClient : ICommunicator
{
private Type _type = typeof (ReportingEngineClient);
/// <summary>
/// Provides direct access to Reporting Engine Server
/// </summary>
private readonly Communicator _serverCommunicator;
/// <summary>
/// Raised when Order Report is received from Reporting Engine
/// </summary>
public event Action<IList<object[]>> OrderReportReceivedEvent;
/// <summary>
/// Raised when Profit Loss Report is received from Reporting Engine
/// </summary>
public event Action<ProfitLossStats> ProfitLossReportReceivedEvent;
/// <summary>
/// Argument Constructor
/// </summary>
/// <param name="serverCommunicator"></param>
public ReportingEngineClient(Communicator serverCommunicator)
{
// Save Instance
_serverCommunicator = serverCommunicator;
// Register Server Events
SubscribeServerEvents();
}
/// <summary>
/// Subscribes Server events to received reporting data
/// </summary>
private void SubscribeServerEvents()
{
// Makes sure that events are not hooked multiple times
UnSubscribeServerEvents();
// Register Events
_serverCommunicator.OrderReportReceivedEvent += OrderReportReceived;
_serverCommunicator.ProfitLossReportReceivedEvent += ProfitLossReportReceived;
}
/// <summary>
/// Un-Subscribes Server events to received reporting data
/// </summary>
private void UnSubscribeServerEvents()
{
// Un-Subscribe Events
_serverCommunicator.OrderReportReceivedEvent -= OrderReportReceived;
_serverCommunicator.ProfitLossReportReceivedEvent -= ProfitLossReportReceived;
}
/// <summary>
/// Indicates if the communication medium is open or not
/// </summary>
/// <returns></returns>
public bool IsConnected()
{
if (_serverCommunicator != null)
{
return true;
}
return false;
}
#region Start/Stop
/// <summary>
/// Opens necessary connections to start communication
/// </summary>
public void Connect()
{
try
{
if (Logger.IsInfoEnabled)
{
Logger.Info(IsConnected() ? "Connection established" : "Connection failed", _type.FullName,
"Connect");
}
}
catch (Exception exception)
{
Logger.Error(exception, _type.FullName, "Connect");
}
}
/// <summary>
/// Closes communication channels
/// </summary>
public void Disconnect()
{
// NOTE: No operation needed as direct access to Server is used.
}
#endregion
#region Request Messages
/// <summary>
/// Send Order Report request to Reporting Engine
/// </summary>
/// <param name="parameters">Search parameters to be used for report</param>
public void RequestOrderReport(Dictionary<OrderParameters, string> parameters)
{
try
{
if (Logger.IsDebugEnabled)
{
Logger.Debug("New order report request received.", _type.FullName, "RequestOrderReport");
}
// Send Request to Reporting Engine
_serverCommunicator.RequestOrderReport(parameters);
}
catch (Exception exception)
{
Logger.Error(exception, _type.FullName, "RequestOrderReport");
}
}
/// <summary>
/// Send Profit Loss Report request to Reporting Engine
/// </summary>
/// <param name="parameters">Search parameters to be used for report</param>
public void RequestProfitLossReport(Dictionary<TradeParameters, string> parameters)
{
try
{
if (Logger.IsDebugEnabled)
{
Logger.Debug("New profit loss report request received.", _type.FullName, "RequestProfitLossReport");
}
// Send Request to Reporting Engine
_serverCommunicator.RequestProfitLossReport(parameters);
}
catch (Exception exception)
{
Logger.Error(exception, _type.FullName, "RequestProfitLossReport");
}
}
#endregion
#region
/// <summary>
/// Called when Order report is received
/// </summary>
/// <param name="report">Contains requested report information</param>
private void OrderReportReceived(IList<object[]> report)
{
try
{
if (Logger.IsDebugEnabled)
{
Logger.Debug("Order report received", _type.FullName, "OrderReportReceived");
}
// Raise event to notify listeners
if (OrderReportReceivedEvent!=null)
{
OrderReportReceivedEvent(report);
}
}
catch (Exception exception)
{
Logger.Error(exception, _type.FullName, "OrderReportReceived");
}
}
/// <summary>
/// Called when Profit Loss report is received
/// </summary>
/// <param name="report">Contains requested report information</param>
private void ProfitLossReportReceived(ProfitLossStats report)
{
try
{
if (Logger.IsDebugEnabled)
{
Logger.Debug("Profit Loss report received", _type.FullName, "ProfitLossReportReceived");
}
// Raise event to notify listeners
if (ProfitLossReportReceivedEvent != null)
{
ProfitLossReportReceivedEvent(report);
}
}
catch (Exception exception)
{
Logger.Error(exception, _type.FullName, "ProfitLossReportReceived");
}
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.