content stringlengths 23 1.05M |
|---|
using System.Threading.Tasks;
using TreniniDotNet.Common.Data;
using TreniniDotNet.Common.Data.Pagination;
using TreniniDotNet.SharedKernel.Slugs;
namespace TreniniDotNet.Domain.Catalog.Scales
{
public interface IScalesRepository : IRepository<ScaleId, Scale>
{
Task<bool> ExistsAsync(Slug slug);
Task<Scale?> GetBySlugAsync(Slug slug);
Task<PaginatedResult<Scale>> GetScalesAsync(Page page);
}
}
|
using System;
using System.Collections.Generic;
using Confluent.Kafka;
namespace InsideOut.Consumer
{
public interface IKafkaConsumer : IDisposable
{
string TopicName { get; }
}
public interface IKafkaConsumer<TKey, TValue> : IKafkaConsumer
{
IEnumerable<ConsumeResult<TKey, TValue>> ConnectToTopic();
IEnumerable<ConsumeResult<TKey, TValue>> ConnectToTopic(TimeSpan timeout);
}
} |
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
namespace HanoiCollab
{
public class NameUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
return connection.User?.FindFirst(ClaimTypes.Name)?.Value!;
}
}
}
|
// Licensed to Sky Blue Software under one or more agreements.
// Sky Blue Software licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SkyBlueSoftware.Events
{
public class EventStream : IEventStream
{
private IEnumerable<ISubscription> subscriptions;
private readonly IDependencyContainer container;
public EventStream(IDependencyContainer container = null)
{
subscriptions = new ISubscription[] { };
this.container = container ?? new DefaultDependencyContainer();
}
public EventStream Initialize(params ISubscribeTo[] subscribers) => Initialize(subscribers.AsEnumerable());
public EventStream Initialize(IEnumerable<ISubscribeTo> subscribers)
{
subscriptions = subscribers.CreateSubscriptions();
return this;
}
public async Task Publish<T>(params object[] args)
{
var e = await container.Create<T>(args);
if (e == null) return;
foreach (var o in subscriptions) await o.On(e);
}
#region IEnumerable
public IEnumerator<ISubscription> GetEnumerator() => subscriptions.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
}
} |
namespace EngagementBreeze.Models
{
/// <summary>
/// Enum of supported settings for user configuration
/// </summary>
public enum ConfigurableSettings
{
ApiKey,
City,
SunnyThreshold,
RainyThreshold
}
} |
//
// Copyright (c) 2020 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
using System;
using System.Collections;
using System.Runtime.CompilerServices;
namespace nanoFramework.Hardware.Esp32.Rmt
{
class RmtChannelcs
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SFXController : MonoBehaviour {
public AudioSource RoarWalkSFX;
public AudioSource RoarAirSFX;
public AudioSource Roar3SFX;
public AudioSource DrawSwordSFX;
public AudioSource Attack3SFX;
public void Roar1()
{
Roar3SFX.Play();
}
public void WalkRoar()
{
RoarWalkSFX.Play();
}
public void RoarAir()
{
if(!RoarAirSFX.isPlaying)
RoarAirSFX.Play();
}
public void DrawSword()
{
if (GetComponent<MasterMode>().enabled)
GetComponent<MasterMode>().BiggerSword.SetActive(true);
}
public void SheathSword()
{
if (GetComponent<MasterMode>().enabled)
GetComponent<MasterMode>().BiggerSword.SetActive(false);
}
public void Attack3()
{
Attack3SFX.Play();
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.Tye.ConfigModel
{
internal static class NameInferer
{
public static string? InferApplicationName(FileInfo fileInfo)
{
if (fileInfo == null)
{
return null;
}
var extension = fileInfo.Extension;
if (extension == ".sln" || extension == ".csproj" || extension == ".fsproj")
{
return Path.GetFileNameWithoutExtension(fileInfo.Name).ToLowerInvariant();
}
return fileInfo.Directory.Parent.Name.ToLowerInvariant();
}
}
}
|
using ETModel;
using UnityEngine;
namespace MyEditor
{
[Event(EventIdType.BehaviorTreeReplaceClick)]
public class BehaviorTreeReplaceClickEvent_ReplaceNode: AEvent<string, Vector2>
{
public override void Run(string name, Vector2 pos)
{
BTEditorWindow.Instance.onChangeNodeType(name, pos);
}
}
} |
using BioEngine.Core.DB;
namespace BioEngine.Core.Entities.Blocks
{
[Entity("cutblock")]
public class CutBlock : ContentBlock<CutBlockData>
{
public override string TypeTitle { get; set; } = "Кат";
public override string ToString()
{
return "";
}
}
public class CutBlockData : ContentBlockData
{
public string ButtonText { get; set; } = "Читать дальше";
}
}
|
using System;
using System.Collections.Generic;
using DataAccessLayer.Models;
using DataAccessLayer.Database;
using DataAccessLayer.Repositories;
namespace ServiceLayer.Services
{
public class OperationService : IOperationService
{
private readonly OperationRepository _OperationRepo;
public OperationService()
{
_OperationRepo = new OperationRepository();
}
public int CreateService(DatabaseContext _db, Service service)
{
return _OperationRepo.CreateService(_db, service);
}
public int CreateService(DatabaseContext _db, string serviceName)
{
return _OperationRepo.CreateService(_db, serviceName);
}
public int DisableService(DatabaseContext _db, Guid serviceId)
{
return _OperationRepo.DisableService(_db, serviceId);
}
public int EnableService(DatabaseContext _db, Guid serviceId)
{
return _OperationRepo.EnableService(_db, serviceId);
}
public int DeleteService(DatabaseContext _db, Guid serviceId)
{
return _OperationRepo.DeleteService(_db, serviceId);
}
public bool IsServiceDisabled(DatabaseContext _db, Guid serviceId)
{
return _OperationRepo.IsServiceDisabled(_db, serviceId);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.IO;
namespace VisualRust.ProjectSystem.FileSystemMirroring.IO {
public interface IMsBuildFileSystemFilter {
bool IsFileAllowed(string relativePath, FileAttributes attributes);
bool IsDirectoryAllowed(string relativePath, FileAttributes attributes);
void Seal();
}
} |
@model IEnumerable<TabViewModel>
@{
var tabs = Model.ToArray();
}
<div class="tabs">
<ul class="nav nav-tabs">
@for (var index = 0; index < tabs.Length; index++) {
var tab = tabs[index];
<li class="@(index == 0 ? Html.Raw("active") : Html.Raw(""))">
<a href="#@tab.Id" data-toggle="tab">@tab.Title</a>
</li>
}
</ul>
<div class="tab-content">
@for (var index = 0; index < tabs.Length; index++) {
var tab = tabs[index];
<div class="tab-data-content tab-pane @(index == 0 ? Html.Raw("active") : Html.Raw(""))" id="@tab.Id">
@if (tab.Editable)
{
// TODO: make it height automatically adjust
<textarea class="form-control" style="max-height: 350px; min-height: 350px; overflow: scroll; font-family: monospace; margin-bottom: 20px" wrap="off">@(tab.Content ?? "")</textarea>
}
else
{
<div class="well" style="max-height: 350px; min-height: 350px; overflow: scroll; font-family: monospace;
white-space: pre; text-align: left;">@(tab.Content ?? "No data available.")</div>
}
</div>
}
</div>
</div> |
using System;
using System.ComponentModel.DataAnnotations;
namespace EntityFrameworkCore.Jet.IntegrationTests.Model54_MemoryLeakageTest
{
public class Student
{
public int StudentId { get; set; }
[Required]
[MaxLength(50)]
// Index are supported only in fluent API
/*
[Index]
*/
public string StudentName { get; set; }
public string Notes { get; set; }
public virtual Standard Standard { get; set; }
public override string ToString()
{
return string.Format("{2}: {0} - {1}", StudentId, StudentName, base.ToString());
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ReverseGeocodeResourceTest.cs" company="Mapbox">
// Copyright (c) 2016 Mapbox. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Mapbox.UnitTest
{
using System;
using Mapbox.Utils;
using NUnit.Framework;
[TestFixture]
internal class ReverseGeocodeResourceTest
{
private const string Base = "https://api.mapbox.com/geocoding/v5/mapbox.places/";
private Vector2d query = new Vector2d(10, 10);
private string expectedQueryString = "10.00000,10.00000";
private Geocoding.ReverseGeocodeResource rgr;
[SetUp]
public void SetUp()
{
this.rgr = new Geocoding.ReverseGeocodeResource(this.query);
}
public void BadType()
{
this.rgr.Types = new string[] { "fake" };
}
public void BadTypeWithGoodType()
{
this.rgr.Types = new string[] { "place", "fake" };
}
[Test]
public void SetInvalidTypes()
{
Assert.Throws<Exception>(this.BadType);
Assert.Throws<Exception>(this.BadTypeWithGoodType);
}
[Test]
public void GetUrl()
{
// With only constructor
Assert.AreEqual(Base + this.expectedQueryString + ".json", this.rgr.GetUrl());
// With one types
this.rgr.Types = new string[] { "country" };
Assert.AreEqual(Base + this.expectedQueryString + ".json?types=country", this.rgr.GetUrl());
// With multiple types
this.rgr.Types = new string[] { "country", "region" };
Assert.AreEqual(Base + this.expectedQueryString + ".json?types=country%2Cregion", this.rgr.GetUrl());
// Set all to null
this.rgr.Types = null;
Assert.AreEqual(Base + this.expectedQueryString + ".json", this.rgr.GetUrl());
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Runtime;
using System.Reflection;
namespace Dotmim.Sync.Serialization.Converters
{
public class ObjectTypeConverter : ObjectConverter
{
public override string ConvertToString(Object obj)
{
var typeObj = (Type)obj;
var typeCode = typeObj.GetAssemblyQualifiedName();
return typeCode;
}
public override object ConvertFromString(string s)
{
return DmUtils.GetTypeFromAssemblyQualifiedName(s);
}
}
}
|
using System;
public abstract class Human : IComparable
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
protected Human(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
Human otherHuman = obj as Human;
if (otherHuman != null)
{
if (this.FirstName.CompareTo(otherHuman.FirstName) == 0)
{
return this.LastName.CompareTo(otherHuman.LastName);
}
return this.FirstName.CompareTo(otherHuman.FirstName);
}
else
{
throw new ArgumentException("Object is not a Human.");
}
}
public override string ToString()
{
return String.Format("{0} {1}", this.FirstName, this.LastName);
}
}
|
using UnityEngine;
using UnityEngine.Assertions;
namespace ShuHai.DebugInspector.Editor
{
public sealed class GameObjectDrawer<TOwner> : UnityObjectDrawer<TOwner, GameObject>
{
public override void ClearChildren()
{
base.ClearChildren();
ComponentGroup = null;
}
protected override void ChildrenUpdateImpl()
{
base.ChildrenUpdateImpl();
UpdateComponentGroupDrawer(TypedDrawingValue);
}
#region Component Group
/// <summary>
/// Group drawer that contains all child component drawers.
/// </summary>
public ComponentGroupDrawer ComponentGroup { get; private set; }
private void UpdateComponentGroupDrawer(GameObject value)
{
if (value != null)
{
if (ComponentGroup == null)
ComponentGroup = Create<ComponentGroupDrawer>(null, this);
ComponentGroup.UpdateChildren(value);
//ComponentGroup.ClearChildren();
//var components = value.GetComponents<Component>();
//foreach (var c in components)
//{
// var entry = new FixedValueEntry<GameObject, Component>(value, c);
// Create(entry, ComponentGroup, c.GetType().Name);
//}
}
else
{
if (ComponentGroup == null)
return;
ComponentGroup.Parent = null;
ComponentGroup = null;
}
}
#endregion
}
} |
namespace Lloyds.Market.Claims.Payments.Ui.Models;
public class SlipDto
{
public string UniqueMarketReference { get; set; }
public decimal SumInsured { get; set; }
public string Currency { get; set; }
} |
using System;
namespace Haven
{
public struct ResourceRef : IEquatable<ResourceRef>
{
public ResourceRef(string name, ushort version)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Name = name;
Version = version;
}
public string Name { get; }
public ushort Version { get; }
public override int GetHashCode()
{
return Name.GetHashCode() ^ Version.GetHashCode();
}
public bool Equals(ResourceRef other)
{
return string.Equals(Name, other.Name) && Version == other.Version;
}
public override bool Equals(object obj)
{
return (obj is ResourceRef) && Equals((ResourceRef)obj);
}
public bool IsEmpty()
{
return string.IsNullOrEmpty(Name);
}
}
}
|
using System;
using System.Numerics;
using System.Linq;
namespace c
{
class Program
{
static void Main(string[] args)
{
var s = Console.ReadLine().Split();
var a = long.Parse(s[0]);
var b = long.Parse(string.Join("",s[1].Where(c => c != '.')));
var x = new BigInteger(1);
x = a * b / 100;
Console.WriteLine(x);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bot.Clockify.Client;
using Bot.Clockify.Fill;
using Bot.Clockify.Models;
using Bot.Common;
using Bot.Common.ChannelData.Telegram;
using Bot.Common.Recognizer;
using Bot.Data;
using Bot.States;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Bot.Clockify.User
{
public class UserSettingsDialog : ComponentDialog
{
private readonly ITokenRepository _tokenRepository;
private readonly ITimeEntryStoreService _timeEntryStoreService;
private readonly UserState _userState;
private readonly IClockifyMessageSource _messageSource;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly ILogger<UserSettingsDialog> _logger;
private const string TaskWaterfall = "TaskWaterfall";
private const string Telegram = "telegram";
public UserSettingsDialog(ITimeEntryStoreService timeEntryStoreService,
UserState userState, ITokenRepository tokenRepository,
IClockifyMessageSource messageSource, IDateTimeProvider dateTimeProvider,
ILogger<UserSettingsDialog> logger)
{
_timeEntryStoreService = timeEntryStoreService;
_userState = userState;
_tokenRepository = tokenRepository;
_messageSource = messageSource;
_dateTimeProvider = dateTimeProvider;
_logger = logger;
AddDialog(new WaterfallDialog(TaskWaterfall, new List<WaterfallStep>
{
PromptForTaskAsync
}));
Id = nameof(UserSettingsDialog);
}
private async Task<DialogTurnResult> PromptForTaskAsync(WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
string messageText = "";
var userProfile =
await StaticUserProfileHelper.GetUserProfileAsync(_userState, stepContext.Context, cancellationToken);
var tokenData = await _tokenRepository.ReadAsync(userProfile.ClockifyTokenId!);
string clockifyToken = tokenData.Value;
stepContext.Values["ClockifyTokenId"] = userProfile.ClockifyTokenId;
var luisResult = (TimeSurveyBotLuis)stepContext.Options;
var workingMinutes = luisResult.WorkedDurationInMinutes();
var workingHours = workingMinutes / 60;
//Default messageText
messageText = string.Format(_messageSource.SetWorkingHoursFeedback, workingHours);
//Check if there is a need for a change
if (userProfile.WorkingHours != null)
{
if (userProfile.WorkingHours == workingHours)
messageText = string.Format(_messageSource.SetWorkingHoursUnchangedFeedback, workingHours);
}
//Store the working hours within the userProfile
userProfile.WorkingHours = workingHours;
//Inform user and exit the conversation.
return await InformAndExit(stepContext, cancellationToken, messageText);
}
private async Task<DialogTurnResult> InformAndExit(DialogContext stepContext,
CancellationToken cancellationToken, string messageText)
{
string platform = stepContext.Context.Activity.ChannelId;
var ma = GetExitMessageActivity(messageText, platform);
await stepContext.Context.SendActivityAsync(ma, cancellationToken);
return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}
private static IMessageActivity GetExitMessageActivity(string messageText, string platform)
{
IMessageActivity ma;
switch (platform.ToLower())
{
case Telegram:
ma = Activity.CreateMessageActivity();
var sendMessageParams = new SendMessageParameters(messageText, new ReplyKeyboardRemove());
var channelData = new SendMessage(sendMessageParams);
ma.ChannelData = JsonConvert.SerializeObject(channelData);
return ma;
default:
ma = MessageFactory.Text(messageText);
ma.SuggestedActions = new SuggestedActions { Actions = new List<CardAction>() };
return ma;
}
;
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Samhammer.Mongo.Abstractions
{
public interface IBaseRepositoryMongo<T> where T : BaseModelMongo
{
Task<T> GetById(string id);
Task<List<T>> GetAll();
Task Save(T model);
Task Delete(T model);
Task DeleteById(string id);
Task DeleteAll();
}
}
|
using System;
namespace CRoute.Base.Core.Services
{
public interface IDateTimeService : IService
{
DateTime MaxValue { get; }
DateTime MinValue { get; }
DateTime Now { get; }
DateTime UtcNow { get; }
DateTime Today { get; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectableObject : MonoBehaviour
{
[SerializeField] AudioClip CollectItemAudioClip;
CollectableItem ItemData;
bool roomHasEnemys;
public void Setup(CollectableItem itemData, bool roomHasEnemys)
{
ItemData = itemData;
transform.position = new Vector3(ItemData.Postion.x, ItemData.Postion.y, 0);
gameObject.SetActive(ItemData.IsCollectAble && !roomHasEnemys);
}
public virtual bool PickUp(Vector3 playerPos)
{
var collected = gameObject.activeSelf &&
transform.position == playerPos &&
ItemData.IsCollectAble &&
!roomHasEnemys;
if(collected)
{
ItemData.PickUp();
AudioSource.PlayClipAtPoint(CollectItemAudioClip, transform.position);
gameObject.SetActive(false);
}
return collected;
}
} |
using JT1078.FMp4.MessagePack;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using JT1078.Protocol.Extensions;
using JT1078.FMp4.Enums;
namespace JT1078.FMp4.Test.Boxs
{
public class DataReferenceBox_Test
{
/// <summary>
/// 使用doc/video/demo.mp4
/// </summary>
[Fact]
public void Test1()
{
// 00 00 00 1c--box size 28
// 64 72 65 66--box type dref
// 00--version
// 00 00 00--flags
// 00 00 00 01--entry_count
//----------------
// 00 00 00 0c--box size 12
// 75 72 6c 20--box type "url " 有个空格
// 00--version
// 00 00 01--flags
DataReferenceBox dataReferenceBox = new DataReferenceBox();
dataReferenceBox.DataEntryBoxes.Add(new DataEntryUrlBox(version:0,flags:1));
FMp4MessagePackWriter writer = new MessagePack.FMp4MessagePackWriter(new byte[48]);
dataReferenceBox.ToBuffer(ref writer);
var hex = writer.FlushAndGetArray().ToHexString();
Assert.Equal("0000001c6472656600000000000000010000000c75726c2000000001".ToUpper(), hex);
}
}
}
|
using System;
using Dapper.FastCrud;
using DataQI.Commons.Query.Support;
using DataQI.Dapper.FastCrud.Query;
using DataQI.Dapper.FastCrud.Query.Extensions;
using DataQI.Dapper.FastCrud.Query.Support;
using DataQI.Dapper.FastCrud.Test.Fixtures;
using Xunit;
namespace DataQI.Dapper.FastCrud.Test.Query
{
public class DapperJunctionExpressionTest : DapperExpressionTestBase, IClassFixture<QueryFixture>
{
private readonly IDapperCommandBuilder commandBuilder;
public DapperJunctionExpressionTest(QueryFixture fixture)
{
commandBuilder = fixture.GetCommandBuilder();
}
[Fact]
public void TestRejectsNullJunction()
{
var exception = Assert.Throws<ArgumentException>(() =>
new DapperJunctionExpression(null));
var exceptionMessage = exception.GetBaseException().Message;
Assert.IsType<ArgumentException>(exception.GetBaseException());
Assert.Equal("Junction must not be null", exceptionMessage);
}
[Fact]
public void TestBuildConjunctionSimpleExpressionCorrectly()
{
var junction = Restrictions.Conjunction();
junction.Add(Restrictions.Equal("FirstName", "Fake Name"));
FormattableString expression = $"{Sql.Column("FirstName")} = @{"0"}";
AssertExpression(
$"({expression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
[Fact]
public void TestBuildConjunctionComposedExpressionsCorrectly()
{
var junction = Restrictions.Conjunction();
junction
.Add(Restrictions.Equal("FirstName", "Fake Name"))
.Add(Restrictions.Equal("LastName", "Fake Name"));
FormattableString firstExpression = $"{Sql.Column("FirstName")} = @{"0"}";
FormattableString secondExpression = $"{Sql.Column("LastName")} = @{"1"}";
AssertExpression(
$"({firstExpression} AND {secondExpression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
[Fact]
public void TestBuildConjunctionsSimpleExpressionCorrectly()
{
var junction = Restrictions.Conjunction();
junction
.Add(Restrictions
.Conjunction()
.Add(Restrictions.Equal("FirstName", "Fake Name")))
.Add(Restrictions
.Conjunction()
.Add(Restrictions.Equal("LastName", "Fake Name")));
FormattableString firstExpression = $"{Sql.Column("FirstName")} = @{"0"}";
FormattableString firstJunctionExpression = $"({firstExpression})";
FormattableString secondExpression = $"{Sql.Column("LastName")} = @{"1"}";
FormattableString secondJunctionExpression = $"({secondExpression})";
AssertExpression(
$"({firstJunctionExpression} AND {secondJunctionExpression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
[Fact]
public void TestBuildDisjunctionSimpleExpressionCorrectly()
{
var junction = Restrictions.Disjunction();
junction.Add(Restrictions.Equal("FirstName", "Fake Name"));
FormattableString expression = $"{Sql.Column("FirstName")} = @{"0"}";
AssertExpression(
$"({expression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
[Fact]
public void TestBuildDisjunctionComposedExpressionsCorrectly()
{
var junction = Restrictions.Disjunction();
junction
.Add(Restrictions.Equal("FirstName", "Fake Name"))
.Add(Restrictions.Equal("LastName", "Fake Name"));
FormattableString firstExpression = $"{Sql.Column("FirstName")} = @{"0"}";
FormattableString secondExpression = $"{Sql.Column("LastName")} = @{"1"}";
AssertExpression(
$"({firstExpression} OR {secondExpression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
[Fact]
public void TestBuildDisjunctionsSimpleExpressionCorrectly()
{
var junction = Restrictions.Disjunction();
junction
.Add(Restrictions
.Disjunction()
.Add(Restrictions.Equal("FirstName", "Fake Name")))
.Add(Restrictions
.Disjunction()
.Add(Restrictions.Equal("LastName", "Fake Name")));
FormattableString firstExpression = $"{Sql.Column("FirstName")} = @{"0"}";
FormattableString firstJunctionExpression = $"({firstExpression})";
FormattableString secondExpression = $"{Sql.Column("LastName")} = @{"1"}";
FormattableString secondJunctionExpression = $"({secondExpression})";
AssertExpression(
$"({firstJunctionExpression} OR {secondJunctionExpression})",
junction.GetExpressionBuilder().Build(commandBuilder));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Mavplus.RovioDriver
{
public partial interface IRovio : IRovioManualDriver
{
void Execute(params IAction[] actions);
/// <summary>
/// The basic command for acquiring Image.
/// </summary>
/// <returns>Bitmap</returns>
Bitmap GetImage();
HeadLightState HeadLight { get; set; }
RovioLocation GetLocation();
void Emergency();
}
}
|
using System;
using System.Collections.Generic;
using System.ServiceModel;
using DAL.Models;
// ReSharper disable InconsistentNaming
namespace DAL
{
[ServiceContract]
public interface IServiceDAL
{
[OperationContract]
List<Person> GetPeople();
[OperationContract]
Person Find(string username, string password);
[OperationContract]
bool AddPerson(Person person);
[OperationContract]
bool EditPerson(Person person);
[OperationContract]
bool RemovePerson(Guid id);
}
} |
using RoboRyanTron.SceneReference;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace GrowGame
{
public class MainMenuController : MonoBehaviour
{
[SerializeField] private Button quitButton;
[SerializeField] private Button playButton;
[SerializeField] private SceneReference gameScene;
private void Awake()
{
Time.timeScale = 1;
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
quitButton.gameObject.SetActive(false);
}
}
private void OnEnable()
{
quitButton.onClick.AddListener(OnQuitApplication);
playButton.onClick.AddListener(OnPlay);
}
private void OnDisable()
{
quitButton.onClick.RemoveListener(OnQuitApplication);
playButton.onClick.RemoveListener(OnPlay);
}
private void OnPlay()
{
SceneManager.LoadScene(gameScene.SceneName);
}
private void OnQuitApplication()
{
Application.Quit();
}
}
} |
namespace Dashing.IntegrationTests.Tests {
using System.Threading.Tasks;
using Dashing.IntegrationTests.Setup;
using Dashing.IntegrationTests.TestDomain;
using Xunit;
public class AnyTests {
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public async Task AnyAsyncTrueWorks(TestSessionWrapper wrapper) {
Assert.True(await wrapper.Session.Query<User>().Where(u => u.UserId == 8).AnyAsync());
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public async Task AnyAsyncFalseWorks(TestSessionWrapper wrapper) {
Assert.False(await wrapper.Session.Query<User>().Where(u => u.UserId == 2000).AnyAsync());
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public async Task AnyAsyncWhereTrueWorks(TestSessionWrapper wrapper) {
Assert.True(await wrapper.Session.Query<User>().AnyAsync(u => u.UserId == 8));
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public async Task AnyAsyncWhereFalseWorks(TestSessionWrapper wrapper) {
Assert.False(await wrapper.Session.Query<User>().AnyAsync(u => u.UserId == 2000));
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public void AnyTrueWorks(TestSessionWrapper wrapper) {
Assert.True(wrapper.Session.Query<User>().Where(u => u.UserId == 8).Any());
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public void AnyFalseWorks(TestSessionWrapper wrapper) {
Assert.False(wrapper.Session.Query<User>().Where(u => u.UserId == 2000).Any());
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public void AnyWhereTrueWorks(TestSessionWrapper wrapper) {
Assert.True(wrapper.Session.Query<User>().Any(u => u.UserId == 8));
}
[Theory]
[MemberData(nameof(SessionDataGenerator.GetSessions), MemberType = typeof(SessionDataGenerator))]
public void AnyWhereFalseWorks(TestSessionWrapper wrapper) {
Assert.False(wrapper.Session.Query<User>().Any(u => u.UserId == 2000));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "GameSettings/PlayerSetting")]
public class playerSettings : ScriptableObject
{
[SerializeField]
private float _movementSpeed;
[SerializeField]
private float _backwardSpeed;
[SerializeField]
private float _rotationSpeed;
[SerializeField]
private float _jumpPower;
public float MovementSpeed { get => _movementSpeed; }
public float JumpPower { get => _jumpPower; }
public float RotationSpeed { get => _rotationSpeed; }
public float BackwardSpeed { get => _backwardSpeed; }
}
|
@{
ViewData["Title"] = "Error";
}
<h2>Sorry, something went wrong!</h2>
<div>
<img src="~/images/mominos-mama-sad.png" width="500" height="500" />
</div>
@if (TempData["ErrorMessage"] != null)
{
var errorMessage = TempData["ErrorMessage"].ToString();
<p>@errorMessage</p>
}
else
{
<p>An unexpected error occurred!</p>
}
<div>
<a asp-area="" asp-controller="Home" asp-action="Login">Click here to try again!</a>
</div> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Threading;
using DotNetNuke.Web.Api;
using DotNetNuclear.Modules.LogAnalyzer.Components;
using DotNetNuclear.Modules.LogAnalyzer.Models;
using DotNetNuclear.Modules.LogAnalyzer.Components.Settings;
namespace DotNetNuclear.Modules.LogAnalyzer.Services.Controllers
{
//[baseURL]=/desktopmodules/dotnetnuclear.loganalyzer/api
public class LogSvcController : DnnApiController
{
ISettingsRepository _settingsRepo;
public LogSvcController()
{
}
/// <summary>
/// API that starts the log analyzer process
/// </summary>
/// <returns></returns>
[HttpPost] //[baseURL]/logsvc/analyze
[ActionName("analyze")]
[ValidateAntiForgeryToken]
[SupportedModules(FeatureController.DESKTOPMODULE_NAME)]
public HttpResponseMessage Analyze(LogServiceRequest req)
{
_settingsRepo = new SettingsRepository(ActiveModule.ModuleID);
long logItemCount = 0;
string taskId = req.taskId;
string logPath = FileUtils.GetDnnLogPath() + "\\";
var p = new LogAnalyzerHub();
p.NotifyStart(taskId);
LogViewModel vm = new LogViewModel();
ILogItemRepository repo = new LogItemRepository();
long totalLogLines = 0, lineIncrement = 0;
repo.DeleteAllItems(ActiveModule.ModuleID);
foreach (string logFile in req.files)
{
totalLogLines += LogFileParser.GetLineCount(logPath + logFile);
}
lineIncrement = Convert.ToInt64(totalLogLines / 100);
IAnalyzerNotifyer progressNotifyer = new AnalyzerNotifyer(totalLogLines, lineIncrement, taskId, p);
try
{
var analyzer = new LogFileParser(progressNotifyer);
foreach (string logFile in req.files)
{
var logItems = analyzer.GetEntries(logPath + logFile, "log4net", _settingsRepo.LogAnalyzerRegex);
foreach (var li in logItems)
{
logItemCount++;
li.ModuleId = ActiveModule.ModuleID;
li.Count = 1;
repo.InsertItem(li);
}
}
if (logItemCount > 0)
{
// Rollup results and produce report object
var reportItems = repo.GetRollupItems(ActiveModule.ModuleID).ToList();
vm.ReportedItems = reportItems.GroupBy(r => r.Level, r => r,
(key, g) => new LogItemCollection {
Level = key,
Items = g.Take(100).ToList()
}
).ToList();
p.NotifyProgress(taskId, 100, string.Empty);
}
else
{
p.NotifyProgress(taskId, -1, "Log files analyzed contain no entries.");
}
}
catch (Exception ex)
{
p.NotifyProgress(taskId, -1, "An error occurred analyzing the log: " + ex.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
finally
{
p.NotifyEnd(taskId);
}
return Request.CreateResponse(HttpStatusCode.OK, vm);
}
}
public class LogServiceRequest
{
public List<string> files { get; set; }
public string taskId { get; set; }
}
} |
using System;
using GBAEmulator.Video;
namespace GBAEmulator.Memory.Sections
{
public class OAMSection : MirroredMemorySection
{
private PPU ppu;
public OAMSection() : base(0x400) { }
public void Init(PPU ppu)
{
this.ppu = ppu;
}
public override void SetByteAt(uint address, byte value)
{
/*
GBATek:
Writing 8bit Data to Video Memory
Video Memory (BG, OBJ, OAM, Palette) can be written to in 16bit and 32bit units only.
Attempts to write 8bit data (by STRB opcode) won't work:
Writes ...
to OAM (7000000h-70003FFh) are ignored, the memory content remains unchanged.
*/
}
public override void SetHalfWordAt(uint address, ushort value)
{
#if !UNSAFE_RENDERING
if (this.GetHalfWordAt(address) != value) this.ppu.BusyWait();
#endif
base.SetHalfWordAt(address, value);
}
public override void SetWordAt(uint address, uint value)
{
#if !UNSAFE_RENDERING
if (this.GetWordAt(address) != value) this.ppu.BusyWait();
#endif
base.SetWordAt(address, value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GUC.Network;
using GUC.WorldObjects.Instances;
using GUC.WorldObjects;
using GUC.Models;
namespace GUC.Scripting
{
public partial interface ScriptInterface
{
/// <summary>
/// Is called each frame.
/// </summary>
/// <param name="ticks"> Current DateTime.UtcNow.Ticks </param>
void Update(long ticks);
/// <summary>
/// Is called once when the outgame menu usually starts up.
/// </summary>
void StartOutgame();
/// <summary>
/// Is called once when Gothic is ingame for the first time.
/// </summary>
void StartIngame();
/// <summary>
/// Is called once when Gothic is finished loading and renders the first world frame.
/// </summary>
void FirstWorldRender();
}
}
|
using System;
using System.Threading.Tasks;
using Application.IntegrationTests.Common;
using CoolWebsite.Application.Common.Exceptions;
using CoolWebsite.Application.DatabaseAccess.Financials.FinancialProjects.Commands.DeleteFinancialProject;
using FluentAssertions;
using NUnit.Framework;
using CoolWebsite.Domain.Entities.Financial;
namespace Application.IntegrationTests.Financial.FinancialProject.Commands
{
using static Testing;
public class DeleteFinancialProjectTests : FinancialTestBase
{
[Test]
public async Task Handle_ValidId_ShouldDelete()
{
var id = await CreateFinancialProject();
var command = new DeleteFinancialProjectCommand
{
Id = id
};
var notDeleted = await FindAsync<CoolWebsite.Domain.Entities.Financial.FinancialProject>(id);
notDeleted.Deleted.Should().BeNull();
await SendAsync(command);
var entity = await FindAsync<CoolWebsite.Domain.Entities.Financial.FinancialProject>(id);
entity.Deleted.Should().BeCloseTo(DateTime.Now, 1000);
entity.DeletedByUserId.Should().Be(User.Id);
}
[Test]
public void Handle_InvalidId_ShouldThrowNotFoundException()
{
var command = new DeleteFinancialProjectCommand
{
Id = "asdasd"
};
FluentActions.Invoking(async () => await SendAsync(command)).Should().Throw<NotFoundException>();
}
[Test]
public void Handle_EmptyId_ShouldThrowValidationException()
{
var command = new DeleteFinancialProjectCommand();
FluentActions.Invoking(async () => await SendAsync(command)).Should().Throw<ValidationException>();
}
}
} |
using Lopla.Language.Binary;
using Lopla.Language.Compiler.Mnemonics;
using Lopla.Language.Processing;
using Xunit;
namespace Lopla.Tests
{
public class ExpressionSpecs
{
[InlineData(12, 12, OperatorType.Equals, 1)]
[InlineData(12, 4, OperatorType.GreaterThen, 1)]
[InlineData(12, 4, OperatorType.GreaterThenOrEqual, 1)]
[InlineData(12, 4, OperatorType.LessThen, 0)]
[InlineData(4, 12, OperatorType.LessThenOrEqual, 1)]
[InlineData(1, 0, OperatorType.NotEquals, 1)]
[Theory]
public void EvaluationOfBoelanLogic(int a, int b, OperatorType kind, int expected)
{
var r = Expression.ArgumentCalcualte<Number, decimal>
(new Number(a), new Number(b), kind);
Assert.True(r.HasResult(), "Incorrect arguments for this operation.");
var resultValue = r.Get(new Runtime(new Processors())) as Number;
Assert.Equal(resultValue?.Value, expected);
}
[InlineData(12, 12, OperatorType.Add, 24)]
[InlineData(12, 12, OperatorType.Multiply, 144)]
[InlineData(12, 12, OperatorType.Subtract, 0)]
[InlineData(24, 12, OperatorType.Divide, 2)]
[InlineData(12, 12, OperatorType.Equals, 1)]
[InlineData(12, 4, OperatorType.GreaterThen, 1)]
[InlineData(12, 4, OperatorType.GreaterThenOrEqual, 1)]
[InlineData(12, 4, OperatorType.LessThen, 0)]
[InlineData(4, 12, OperatorType.LessThenOrEqual, 1)]
[InlineData(1, 0, OperatorType.And, 0)]
[InlineData(1, 0, OperatorType.Or, 1)]
[InlineData(1, 0, OperatorType.NotEquals, 1)]
[Theory]
public void EvaluationOfMathFormula(int a, int b, OperatorType kind, int expected)
{
var r = Expression.ArgumentCalculate
(new Number(a), new Number(b), kind, new Runtime(new Processors()), new Nop(null));
Assert.True(r.HasResult(), "Incorrect arguments for this operation.");
var resultValue = r.Get(new Runtime(new Processors())) as Number;
Assert.Equal(resultValue?.Value, expected);
}
}
} |
using Controllers;
using Server.Http.Route;
using System;
using System.Threading.Tasks;
using System.Net;
using System.Reflection;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
using Server.Tcp.Server;
using Server.Http.Server;
using Server.Http.Decoration;
using Server.Http.Interface;
namespace git
{
class Program
{
static void Main(string[] args)
{
WebServer ws = new WebServer("http://*:8080/");
GitController c = new GitController();
ws.Add(c);
StreamServer d = new StreamServer();
while (true) { }
}
}
} |
namespace LearnPotentialDisposable
{
public class ItemFactory
{
public ISomething CreateSomething()
{
if (DateTime.Now.Second % 2 == 0)
{
return new Phone();
}
return new Paper();
}
}
} |
using Newtonsoft.Json;
using System;
namespace WolfLive.Api.Models.Welcome
{
public class EndpointConfig
{
[JsonProperty("avatarEndpoint")]
public Uri AvatarEndpoint { get; set; }
[JsonProperty("mmsUploadEndpoint")]
public Uri MmsUploadEndpoint { get; set; }
[JsonProperty("banner")]
public Banner Banner { get; set; }
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Vivet.AspNetCore.RequestTimeZone.Providers;
namespace Vivet.AspNetCore.RequestTimeZone.Interfaces
{
/// <summary>
/// Request TimeZone Provider interface.
/// </summary>
public interface IRequestTimeZoneProvider
{
/// <summary>
/// Determines the provider timezone result from the <see cref="HttpContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/>.</param>
/// <returns>The <see cref="ProviderTimeZoneResult"/>.</returns>
Task<ProviderTimeZoneResult> DetermineProviderTimeZoneResult(HttpContext httpContext);
}
} |
using System;
namespace FeedReaders.Models
{
/// <summary>
/// This represents the feed item entity.
/// </summary>
public class FeedItem
{
/// <summary>
/// Gets or sets the feed item title.
/// </summary>
public virtual string Title { get; set; }
/// <summary>
/// Gets or sets the feed item description.
/// </summary>
public virtual string Description { get; set; }
/// <summary>
/// Gets or sets the feed item link URL.
/// </summary>
public virtual string Link { get; set; }
/// <summary>
/// Gets or sets the feed item thumbnail URL.
/// </summary>
public virtual string ThumbnailLink { get; set; }
/// <summary>
/// Gets or sets the date/time when the feed item was published.
/// </summary>
public virtual DateTimeOffset DatePublished { get; set; }
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ActionMethodStepTests.cs">
// SPDX-License-Identifier: MIT
// Copyright © 2019-2020 Esbjörn Redmo and contributors. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Mocklis.Steps.Lambda
{
#region Using Directives
using System;
using Mocklis.Interfaces;
using Mocklis.Mocks;
using Xunit;
#endregion
public class ActionMethodStepTests
{
public MockMembers MockMembers { get; } = new MockMembers();
public IMethods Sut => MockMembers;
[Fact]
public void RequireNonNullAction()
{
Assert.Throws<ArgumentNullException>(() => MockMembers.SimpleAction.Action((Action)null!));
Assert.Throws<ArgumentNullException>(() => MockMembers.ActionWithParameter.Action(null!));
}
[Fact]
public void CallActionWithNoParameters()
{
bool isCalled = false;
MockMembers.SimpleAction.Action(() => { isCalled = true; });
Sut.SimpleAction();
Assert.True(isCalled);
}
[Fact]
public void CallActionWithParameters()
{
int callParameter = 0;
MockMembers.ActionWithParameter.Action(i => callParameter = i);
Sut.ActionWithParameter(99);
Assert.Equal(99, callParameter);
}
}
}
|
using System;
using System.Windows.Forms;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using CefSharp;
using SvnToGit.FrontEnd.BrowserForm;
using SvnToGit.FrontEnd.Controllers;
namespace SvnToGit.FrontEnd {
static class Program {
private static IWindsorContainer container;
[STAThread]
static void Main() {
container = new WindsorContainer(new XmlInterpreter());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
StartChromiumBrowser();
container.Resolve<IndexController>().Index();
Application.Run(container.Resolve<INavigator>().WinForm());
}
private static void StartChromiumBrowser() {
Cef.EnableHighDPISupport();
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme {
SchemeName = LocalSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new LocalSchemeHandlerFactory()
});
Cef.Initialize(settings);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml.Linq;
namespace ReClassNET.Util
{
/// <summary>
/// A class which stores custom config items from plugins.
/// The id of an item should consist of "a-zA-z0-9.,;_-+".
/// The naming convention is "Plugin.[ConfigGroup.]ConfigItem".
/// </summary>
public class CustomConfig
{
private readonly Dictionary<string, string> data = new Dictionary<string, string>();
internal XElement Serialize(string name)
{
return XElementSerializer.ToXml(name, data);
}
internal void Deserialize(XElement element)
{
foreach (var kv in XElementSerializer.ToDictionary(element))
{
data[kv.Key] = kv.Value;
}
}
/// <summary>
/// Sets a configuration item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="value">
/// The value of the item.
/// If the value is null the item gets removed.
/// </param>
public void SetString(string id, string value)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0)
{
throw new ArgumentException();
}
if (value == null)
{
data.Remove(id);
}
else
{
data[id] = value;
}
}
/// <summary>
/// Sets a configuration item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="value">The value of the item.</param>
public void SetBool(string id, bool value)
{
SetString(id, Convert.ToString(value));
}
/// <summary>
/// Sets a configuration item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="value">The value of the item.</param>
public void SetLong(string id, long value)
{
SetString(id, value.ToString(NumberFormatInfo.InvariantInfo));
}
/// <summary>
/// Sets a configuration item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="value">The value of the item.</param>
public void SetULong(string id, ulong value)
{
SetString(id, value.ToString(NumberFormatInfo.InvariantInfo));
}
public void SetXElement(string id, XElement value)
{
SetString(id, value.ToString());
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <returns>The value of the config item or null if the id does not exists.</returns>
public string GetString(string id)
{
return GetString(id, null);
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="def">The default value if the id does not exists.</param>
/// <returns>The value of the config item or <paramref name="def"/> if the id does not exists.</returns>
public string GetString(string id, string def)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0)
{
throw new ArgumentException();
}
if (data.TryGetValue(id, out var value))
{
return value;
}
return def;
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="def">The default value if the id does not exists.</param>
/// <returns>The value of the config item or <paramref name="def"/> if the id does not exists.</returns>
public bool GetBool(string id, bool def)
{
var value = GetString(id, null);
if (string.IsNullOrEmpty(value))
{
return def;
}
return Convert.ToBoolean(value);
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="def">The default value if the id does not exists.</param>
/// <returns>The value of the config item or <paramref name="def"/> if the id does not exists.</returns>
public long GetLong(string id, long def)
{
var str = GetString(id, null);
if (string.IsNullOrEmpty(str))
{
return def;
}
if (long.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out var value))
{
return value;
}
return def;
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="def">The default value if the id does not exists.</param>
/// <returns>The value of the config item or <paramref name="def"/> if the id does not exists.</returns>
public ulong GetULong(string id, ulong def)
{
var str = GetString(id, null);
if (string.IsNullOrEmpty(str))
{
return def;
}
if (ulong.TryParse(str, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out var value))
{
return value;
}
return def;
}
/// <summary>
/// Gets the value of the config item.
/// </summary>
/// <param name="id">The id of the item.</param>
/// <param name="def">The default value if the id does not exists.</param>
/// <returns>The value of the config item or <paramref name="def"/> if the id does not exists.</returns>
public XElement GetXElement(string id, XElement def)
{
var str = GetString(id, null);
if (string.IsNullOrEmpty(str))
{
return def;
}
return XElement.Parse(str);
}
}
}
|
namespace Catalog.Application.Contracts.Queries
{
using Catalog.Application.Contracts.Queries.DTOs;
using Services.Common;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IVideoGameQueryService
{
Task<DataCollection<VideoGameDto>> GetVideoGames(int page, int take, IEnumerable<Guid> videogames = null);
Task<VideoGameDto> GetVideoGame(Guid id);
Task<IEnumerable<VideoGameDto>> GetVideoGameByName(string name);
Task<IEnumerable<VideoGameDto>> GetVideoGameByConsole(string consoleName);
Task CreateVideoGame(VideoGameDto videoGame);
Task<bool> UpdateVideoGame(VideoGameDto videoGame);
Task<bool> DeleteVideoGame(string id);
}
}
|
using System;
using System.Text;
using Effort;
//
using NSG.Identity;
using WebSrv.Models;
//
namespace WebSrv_Tests
{
public static class Effort_Helper
{
//
private static string _connectionStringKey = "NetworkIncidentConnection";
//
public static string CSV_FullPath =
@"C:\Dat\Nsg\L\Web\Ng\NetIncidents3\WebSrv_Tests\App_Data\Effort";
//
public static string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings[_connectionStringKey]
.ConnectionString;
}
//
public static ApplicationDbContext GetEffortEntity( string connectionString, string fullPath )
{
Effort.DataLoaders.IDataLoader _loader = new Effort.DataLoaders.CsvDataLoader(fullPath);
// The 'data source' keyword is not supported.
System.Data.Common.DbConnection _connection =
Effort.DbConnectionFactory.CreateTransient( _loader );
// System.Data.Entity.Core.Objects.ObjectContext
return new ApplicationDbContext( _connection );
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebApplication1
{
/// <summary>
/// Summary description for SimpleCalculator
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class SimpleCalculator : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public double doTheMath(double fn, double sn, SharedProject.operators operat)
{
double res;
string sign;
switch (operat)
{
case SharedProject.operators.Add:
res = fn + sn;
sign = "+";
break;
case SharedProject.operators.Subtract:
res = fn - sn;
sign = "-";
break;
case SharedProject.operators.Multiply:
res = fn * sn;
sign = "*";
break;
case SharedProject.operators.Divide:
res = fn / sn;
sign = "/";
break;
case SharedProject.operators.None:
default:
res = 0;
sign = "unknown sign";
break;
}
List<string> calculations;
if (Session["CALCULATIONS"] == null)
calculations = new List<string>();
else
calculations = (List<string>)Session["CALCULATIONS"];
string strRecentCalculation = fn.ToString() + " "+ sign +" " + sn.ToString() + " = " + res.ToString();
calculations.Add(strRecentCalculation);
Session["CALCULATIONS"] = calculations;
return res;
}
[WebMethod(EnableSession = true)]
public List<string> getCalculations()
{
if (Session["CALCULATIONS"] == null)
{
List<string> calculations = new List<string>();
calculations.Add("There are no calculations yet.");
return calculations;
}
else
return ((List<string>)Session["CALCULATIONS"]);
}
}
}
|
namespace Our.Umbraco.Checklist.Constants
{
internal class RuntimeCacheConstants
{
public const int DefaultExpiration = 1440;
public const string RuntimeCacheKeyPrefix = "checklist_";
}
}
|
namespace Lachain.ConsensusTest
{
public enum DeliveryServiceMode
{
TAKE_FIRST,
TAKE_LAST,
TAKE_RANDOM
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Protogame.ATFLevelEditor;
using Protoinject;
namespace Protogame
{
public class EntityGroup : IContainsEntities, IEventListener<IGameContext>, IEventListener<INetworkEventContext>, IEventListener<IPhysicsEventContext>, IHasLights, IEntity, IServerEntity, INetworkIdentifiable, ISynchronisedObject, IPrerenderableEntity, IQueryableComponent
{
private readonly INode _node;
private readonly IFinalTransform _finalTransform;
private INode<IEntity>[] _entityCache = new INode<IEntity>[0];
private INode<IServerEntity>[] _serverEntityCache = new INode<IServerEntity>[0];
private readonly HashSet<Type> _enabledInterfaces = new HashSet<Type>();
private bool _hasRenderableComponentDescendants;
private bool _hasPrerenderableComponentDescendants;
private bool _hasUpdatableComponentDescendants;
private bool _hasServerUpdatableComponentDescendants;
private bool _hasLightableComponentDescendants;
public EntityGroup(INode node, IEditorQuery<EntityGroup> editorQuery)
{
_node = node;
_finalTransform = new DefaultFinalTransform(this, node);
Transform = new DefaultTransform();
// EditorGroup is used to represent game groups in the editor
// and we need to map the transform to this object.
if (editorQuery.Mode == EditorQueryMode.LoadingConfiguration)
{
editorQuery.MapTransform(this, x => this.Transform.Assign(x));
_node.ChildrenChanged += ChildrenChanged;
_node.DescendantsChanged += DescendantsChanged;
ChildrenChanged(null, null);
DescendantsChanged(null, null);
}
}
private void DescendantsChanged(object sender, EventArgs e)
{
_enabledInterfaces.Clear();
var children = _node.Children.Select(x => x.UntypedValue).ToArray();
for (var i = 0; i < children.Length; i++)
{
var queryableComponent = children[i] as IQueryableComponent;
if (queryableComponent != null)
{
_enabledInterfaces.UnionWith(queryableComponent.EnabledInterfaces);
}
else if (children[i] != null)
{
_enabledInterfaces.UnionWith(children[i].GetType().GetInterfaces());
}
}
_hasRenderableComponentDescendants = _enabledInterfaces.Contains(typeof(IRenderableComponent));
_hasPrerenderableComponentDescendants = _enabledInterfaces.Contains(typeof(IPrerenderableComponent));
_hasUpdatableComponentDescendants = _enabledInterfaces.Contains(typeof(IUpdatableComponent));
_hasServerUpdatableComponentDescendants = _enabledInterfaces.Contains(typeof(IServerUpdatableComponent));
_hasLightableComponentDescendants = _enabledInterfaces.Contains(typeof(ILightableComponent));
}
private void ChildrenChanged(object sender, EventArgs e)
{
_entityCache = _node.Children.Where(x => typeof(IEntity).IsAssignableFrom(x.Type)).Cast<INode<IEntity>>().ToArray();
_serverEntityCache = _node.Children.Where(x => typeof(IServerEntity).IsAssignableFrom(x.Type)).Cast<INode<IServerEntity>>().ToArray();
}
public ITransform Transform { get; }
public IFinalTransform FinalTransform => _finalTransform;
public void Update(IServerContext serverContext, IUpdateContext updateContext)
{
if (_hasServerUpdatableComponentDescendants)
{
for (var i = 0; i < _entityCache.Length; i++)
{
_serverEntityCache[i].Value.Update(serverContext, updateContext);
}
}
}
public void Render(IGameContext gameContext, IRenderContext renderContext)
{
if (_hasRenderableComponentDescendants)
{
for (var i = 0; i < _entityCache.Length; i++)
{
_entityCache[i].Value.Render(gameContext, renderContext);
}
}
}
public void Prerender(IGameContext gameContext, IRenderContext renderContext)
{
if (_hasPrerenderableComponentDescendants)
{
foreach (var child in _node.Children.Select(x => x.UntypedValue).OfType<IPrerenderableEntity>())
{
child.Prerender(gameContext, renderContext);
}
}
}
public void Update(IGameContext gameContext, IUpdateContext updateContext)
{
if (_hasUpdatableComponentDescendants)
{
for (var i = 0; i < _entityCache.Length; i++)
{
_entityCache[i].Value.Update(gameContext, updateContext);
}
}
}
public bool Handle(IGameContext context, IEventEngine<IGameContext> eventEngine, Event @event)
{
if (EnabledInterfaces.Contains(typeof(IEventListener<IGameContext>)))
{
foreach (var child in _node.Children.Select(x => x.UntypedValue).OfType<IEventListener<IGameContext>>())
{
if (child.Handle(context, eventEngine, @event))
{
return true;
}
}
}
return false;
}
public bool Handle(IPhysicsEventContext context, IEventEngine<IPhysicsEventContext> eventEngine, Event @event)
{
foreach (var child in _node.Children.Select(x => x.UntypedValue).OfType<IEventListener<IPhysicsEventContext>>())
{
if (child.Handle(context, eventEngine, @event))
{
return true;
}
}
return false;
}
public bool Handle(INetworkEventContext context, IEventEngine<INetworkEventContext> eventEngine, Event @event)
{
foreach (var child in _node.Children.Select(x => x.UntypedValue).OfType<IEventListener<INetworkEventContext>>())
{
if (child.Handle(context, eventEngine, @event))
{
return true;
}
}
return false;
}
public IEnumerable<ILight> GetLights()
{
if (_hasLightableComponentDescendants)
{
foreach (var child in _node.Children.Select(x => x.UntypedValue).OfType<IHasLights>())
{
foreach (var light in child.GetLights())
{
yield return light;
}
}
}
}
public void ReceiveNetworkIDFromServer(IGameContext gameContext, IUpdateContext updateContext, int identifier, int initialFrameTick)
{
throw new InvalidOperationException(
"Entity groups can not receive network IDs. This indicates an error in the code.");
}
public void ReceivePredictedNetworkIDFromClient(IServerContext serverContext, IUpdateContext updateContext, MxClient client,
int predictedIdentifier)
{
throw new InvalidOperationException(
"Entity groups can not receive predicted network IDs. This indicates an error in the code.");
}
public void DeclareSynchronisedProperties(ISynchronisationApi synchronisationApi)
{
throw new InvalidOperationException(
"Entity groups can not declare synchronised properties. Do not attach a network synchronisation component to an entity group.");
}
public HashSet<Type> EnabledInterfaces => _enabledInterfaces;
}
}
|
using System.Collections.Generic;
using System;
using System.IO;
using PathLib;
namespace Blossom.Operations
{
/// <summary>
/// Operations tha interact with a remote host.
/// </summary>
public interface IRemoteOperations : IDisposable
{
/// <summary>
/// A stream enabling access to the shell's input and output.
/// </summary>
Stream ShellStream { get; }
/// <summary>
/// Run a shell command on the remote host.
/// </summary>
/// <param name="command"></param>
string RunCommand(string command);
/// <summary>
/// Copy a file from the remote host to a stream.
/// </summary>
/// <param name="sourcePath">Path and filename of the file to copy on the remote server.</param>
/// <param name="destination">Destination stream.</param>
/// <param name="handler">Display file transfer information.</param>
void GetFile(string sourcePath, Stream destination, IFileTransferHandler handler);
/// <summary>
/// Copy a file from the remote host to the local host.
/// </summary>
/// <param name="sourcePath">Path and filename of the file to copy on the remote server.</param>
/// <param name="destinationPath">Destination for the file on the local machine.</param>
/// <param name="handler">Display file transfer information.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
/// <returns>True if the file was copied, false otherwise.</returns>
bool GetFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer);
/// <summary>
/// Copy a file from the local host to the remote host.
/// </summary>
/// <param name="source"></param>
/// <param name="destinationPath"></param>
/// <param name="handler"></param>
[Obsolete("Use the version with IPurePath parameters instead.")]
void PutFile(Stream source, string destinationPath, IFileTransferHandler handler);
/// <summary>
/// Copy a file from the local host to the remote host.
/// </summary>
/// <param name="source"></param>
/// <param name="destinationPath"></param>
/// <param name="handler"></param>
void PutFile(Stream source, IPurePath destinationPath, IFileTransferHandler handler);
/// <summary>
/// Copy a file from the local host to the remote host.
/// </summary>
/// <param name="sourcePath">Path and filename of the file to copy on the local machine.</param>
/// <param name="destinationPath">Destination for the file on the remote server.</param>
/// <param name="handler">Display file transfer information.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
[Obsolete("Use the version with IPurePath parameters instead.")]
bool PutFile(string sourcePath, string destinationPath, IFileTransferHandler handler, bool ifNewer);
/// <summary>
/// Copy a file from the local host to the remote host.
/// </summary>
/// <param name="sourcePath">Path and filename of the file to copy on the local machine.</param>
/// <param name="destinationPath">Destination for the file on the remote server.</param>
/// <param name="handler">Display file transfer information.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
bool PutFile(IPurePath sourcePath, IPurePath destinationPath, IFileTransferHandler handler, bool ifNewer);
/// <summary>
/// Copy a directory (and all files, recursively)
/// from the local host to the remote host.
///
/// Will create the destination directory and any
/// parents, if necessary.
/// </summary>
/// <param name="sourceDir">Directory to copy.</param>
/// <param name="destinationDir">Destination directory where contents are copied.</param>
/// <param name="handlerFactory">Produces <see cref="IFileTransferHandler"/>s for each copied file.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
[Obsolete("Use the version with IPurePath parameters instead.")]
void PutDir(string sourceDir, string destinationDir,
Func<IFileTransferHandler> handlerFactory, bool ifNewer);
/// <summary>
/// Copy a directory (and all files, recursively)
/// from the local host to the remote host.
///
/// Will create the destination directory and any
/// parents, if necessary.
/// </summary>
/// <param name="sourceDir">Directory to copy.</param>
/// <param name="destinationDir">Destination directory where contents are copied.</param>
/// <param name="handlerFactory">Produces <see cref="IFileTransferHandler"/>s for each copied file.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
void PutDir(IPurePath sourceDir, IPurePath destinationDir,
Func<IFileTransferHandler> handlerFactory, bool ifNewer);
/// <summary>
/// Copy a directory (and all files, recursively)
/// from the local host to the remote host.
///
/// Will create the destination directory and any
/// parents, if necessary.
/// </summary>
/// <param name="sourceDir">Directory to copy.</param>
/// <param name="destinationDir">Destination directory where contents are copied.</param>
/// <param name="handlerFactory">Produces <see cref="IFileTransferHandler"/>s for each copied file.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
/// <param name="fileFilters">
/// List of filenames or globbed filenames that are allowed to be copied.
/// Glob characters allowed are * for any number of characters and
/// ? for one arbitrary character.
/// </param>
[Obsolete("Use the version with IPurePath parameters instead.")]
void PutDir(string sourceDir, string destinationDir,
Func<IFileTransferHandler> handlerFactory, bool ifNewer, IEnumerable<string> fileFilters);
/// <summary>
/// Copy a directory (and all files, recursively)
/// from the local host to the remote host.
///
/// Will create the destination directory and any
/// parents, if necessary.
/// </summary>
/// <param name="sourceDir">Directory to copy.</param>
/// <param name="destinationDir">Destination directory where contents are copied.</param>
/// <param name="handlerFactory">Produces <see cref="IFileTransferHandler"/>s for each copied file.</param>
/// <param name="ifNewer">
/// If file exists on destination, only copy if that file is
/// older than the one being copied.
/// </param>
/// <param name="fileFilters">
/// List of filenames or globbed filenames that are allowed to be copied.
/// Glob characters allowed are * for any number of characters and
/// ? for one arbitrary character.
/// </param>
void PutDir(IPurePath sourceDir, IPurePath destinationDir,
Func<IFileTransferHandler> handlerFactory, bool ifNewer, IEnumerable<string> fileFilters);
/// <summary>
/// Creates a directory on the remote computer.
/// </summary>
/// <param name="path">
/// Directory path to create.
/// </param>
/// <param name="makeParents">
/// If true, go through each parent dir and make sure each
/// child directory exists before creating the final directory.
/// </param>
[Obsolete("Use the version with IPurePath parameters instead.")]
void MkDir(string path, bool makeParents = false);
/// <summary>
/// Creates a directory on the remote computer.
/// </summary>
/// <param name="path">
/// Directory path to create.
/// </param>
/// <param name="makeParents">
/// If true, go through each parent dir and make sure each
/// child directory exists before creating the final directory.
/// </param>
void MkDir(IPurePath path, bool makeParents = false);
/// <summary>
/// Remove a directory on the remote computer. Fails if
/// <paramref name="recursive"/> is false and the directory is not
/// empty.
/// </summary>
/// <param name="path">Directory to remove.</param>
/// <param name="recursive">
/// Whether to remove files and folders inside recursively.
/// </param>
[Obsolete("Use the version with IPurePath parameters instead.")]
void RmDir(string path, bool recursive = false);
/// <summary>
/// Remove a directory on the remote computer. Fails if
/// <paramref name="recursive"/> is false and the directory is not
/// empty.
/// </summary>
/// <param name="path">Directory to remove.</param>
/// <param name="recursive">
/// Whether to remove files and folders inside recursively.
/// </param>
void RmDir(IPurePath path, bool recursive = false);
}
}
|
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Threading;
using SixLabors.ImageSharp.Drawing.Utilities;
using SixLabors.ImageSharp.PixelFormats;
using Xunit;
namespace SixLabors.ImageSharp.Drawing.Tests.Drawing.Utils
{
public class ThreadLocalBlenderBuffersTests
{
private readonly TestMemoryAllocator memoryAllocator = new TestMemoryAllocator();
[Fact]
public void CreatesPerThreadUniqueInstances()
{
using var buffers = new ThreadLocalBlenderBuffers<Rgb24>(this.memoryAllocator, 100);
var allSetSemaphore = new SemaphoreSlim(2);
var thread1 = new Thread(() =>
{
Span<float> ams = buffers.AmountSpan;
Span<Rgb24> overlays = buffers.OverlaySpan;
ams[0] = 10;
overlays[0] = new Rgb24(10, 10, 10);
allSetSemaphore.Release(1);
allSetSemaphore.Wait();
Assert.Equal(10, buffers.AmountSpan[0]);
Assert.Equal(10, buffers.OverlaySpan[0].R);
});
var thread2 = new Thread(() =>
{
Span<float> ams = buffers.AmountSpan;
Span<Rgb24> overlays = buffers.OverlaySpan;
ams[0] = 20;
overlays[0] = new Rgb24(20, 20, 20);
allSetSemaphore.Release(1);
allSetSemaphore.Wait();
Assert.Equal(20, buffers.AmountSpan[0]);
Assert.Equal(20, buffers.OverlaySpan[0].R);
});
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
[Theory]
[InlineData(false, 1)]
[InlineData(false, 3)]
[InlineData(true, 1)]
[InlineData(true, 3)]
public void Dispose_ReturnsAllBuffers(bool amountBufferOnly, int threadCount)
{
var buffers = new ThreadLocalBlenderBuffers<Rgb24>(this.memoryAllocator, 100, amountBufferOnly);
void RunThread()
{
buffers.AmountSpan[0] = 42;
}
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(RunThread);
threads[i].Start();
}
foreach (Thread thread in threads)
{
thread.Join();
}
buffers.Dispose();
int expectedReturnCount = amountBufferOnly ? threadCount : 2 * threadCount;
Assert.Equal(expectedReturnCount, this.memoryAllocator.ReturnLog.Count);
}
}
}
|
using System.Linq;
namespace LateNightStupidities.XorPersist.Example
{
class Program
{
static void Main(string[] args)
{
RootClass root = new RootClass(true);
LeafClass leaf1 = new LeafClass(root, "leaf1");
root.MainLeaf = leaf1;
LeafClass leaf2 = new LeafClass(root, "leaf2");
LeafClass leaf11 = new LeafClass(leaf1, "leaf11");
leaf1.Leaf = leaf11;
LeafClass leaf111 = new LeafClass(leaf11, "leaf111");
leaf11.Leaf = leaf111;
var controller = XorController.Get();
controller.Save(root, @"C:\Users\Sebastian\Desktop\temp\xor\test.xml");
root = controller.Load<RootClass>(@"C:\Users\Sebastian\Desktop\temp\xor\test.xml");
controller = XorController.Get();
controller.Save(root, @"C:\Users\Sebastian\Desktop\temp\xor\test2.xml");
}
}
}
|
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using EnsureThat;
using Microsoft.ApplicationInsights;
namespace Microsoft.Health.Logging.Telemetry
{
public class IomtTelemetryLogger : ITelemetryLogger
{
private readonly TelemetryClient _telemetryClient;
public IomtTelemetryLogger(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
EnsureArg.IsNotNull(_telemetryClient);
}
public virtual void LogMetric(Common.Telemetry.Metric metric, double metricValue)
{
EnsureArg.IsNotNull(metric);
LogMetricWithDimensions(metric, metricValue);
}
public virtual void LogError(Exception ex)
{
if (ex is AggregateException e)
{
// Address bug https://github.com/microsoft/iomt-fhir/pull/120
LogAggregateException(e);
}
else
{
LogExceptionWithProperties(ex);
LogInnerException(ex);
}
}
public virtual void LogTrace(string message)
{
_telemetryClient.TrackTrace(message);
}
public void LogMetricWithDimensions(Common.Telemetry.Metric metric, double metricValue)
{
EnsureArg.IsNotNull(metric);
_telemetryClient.LogMetric(metric, metricValue);
}
private void LogExceptionWithProperties(Exception ex)
{
EnsureArg.IsNotNull(ex, nameof(ex));
_telemetryClient.LogException(ex);
}
private void LogAggregateException(AggregateException e)
{
LogInnerException(e);
foreach (var exception in e.InnerExceptions)
{
LogExceptionWithProperties(exception);
}
}
private void LogInnerException(Exception ex)
{
EnsureArg.IsNotNull(ex, nameof(ex));
var innerException = ex.InnerException;
if (innerException != null)
{
LogExceptionWithProperties(innerException);
}
}
}
}
|
using SFA.DAS.ApiSubstitute.WebAPI;
namespace SFA.DAS.CommitmentsApiSubstitute.WebAPI
{
public class CommitmentsApi : WebApiSubstitute
{
public string BaseAddress { get; private set; }
public CommitmentsApiMessageHandler CommitmentsApiMessageHandler { get; private set; }
public CommitmentsApi(CommitmentsApiMessageHandler apiMessageHandler) : base(apiMessageHandler)
{
BaseAddress = apiMessageHandler.BaseAddress;
CommitmentsApiMessageHandler = apiMessageHandler;
}
}
}
|
using System.Text;
namespace MFT.Attributes
{
public class VolumeName : Attribute
{
public VolumeName(byte[] rawBytes) : base(rawBytes)
{
var residentData = new ResidentData(rawBytes);
VolName = string.Empty;
if (residentData.Data.Length > 0)
{
VolName = Encoding.Unicode
.GetString(residentData.Data, ContentOffset, residentData.Data.Length - ContentOffset)
.TrimEnd('\0');
}
}
public string VolName { get; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine("**** VOLUME NAME ****");
sb.AppendLine(base.ToString());
sb.AppendLine();
sb.AppendLine($"Volume Name: {VolName}");
return sb.ToString();
}
}
} |
using System.Threading.Tasks;
using Microsoft.Owin;
namespace DbLocalizationProvider.MvcSample
{
public class AuthenticationMiddleware : OwinMiddleware
{
private OwinMiddleware next;
public AuthenticationMiddleware(OwinMiddleware next)
: base(next)
{
this.next = next;
}
public override async Task Invoke(IOwinContext context)
{
if(context.Request.Path.Value == "/localization-admin/" && !UserAuthenticated(context))
{
context.Response.StatusCode = 303;
context.Response.Headers.Add("location", new []{ context.Request.PathBase.Value });
return;
}
await next.Invoke(context);
}
private bool UserAuthenticated(IOwinContext context)
{
// Implement authentication logic here
return true;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.PholioObjectsTest
{
[TestClass]
public class UnitTest
{
[TestMethod]
public void TestShouldSerializeShowLabelOnLeftOfValue()
{
Assert.IsTrue(new Unit{ShowLabelOnLeftOfValue = true}.ShowLabelOnLeftOfValue);
Assert.IsFalse(new Unit { ShowLabelOnLeftOfValue = false }.ShowLabelOnLeftOfValue);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeepLearningWithCNTK;
using CC = CNTK.CNTKLib;
using C = CNTK;
namespace Capsules {
class MNISTExample {
C.Function network;
C.Function loss_function;
C.Function eval_function;
C.Learner learner;
C.Trainer trainer;
C.Evaluator evaluator;
C.Variable imageVariable;
C.Variable categoricalVariable;
C.DeviceDescriptor computeDevice = Util.get_compute_device();
public void run() {
create_network();
train_network();
}
const int batch_size = 64;
void create_network() {
Console.WriteLine("Compute Device: " + computeDevice.AsString());
imageVariable = Util.inputVariable(new int[] { 28, 28, 1 }, "image_tensor");
categoricalVariable = Util.inputVariable(new int[] { 10 }, "label_tensor");
network = imageVariable;
network = Layers.Convolution2D(network, 32, new int[] { 3, 3 }, computeDevice, CC.ReLU);
network = CC.Pooling(network, C.PoolingType.Max, new int[] { 2, 2 }, new int[] { 2 });
network = Layers.Convolution2D(network, 64, new int[] { 3, 3 }, computeDevice, CC.ReLU);
network = CC.Pooling(network, C.PoolingType.Max, new int[] { 2, 2 }, new int[] { 2 });
network = Layers.Convolution2D(network, 64, new int[] { 3, 3 }, computeDevice, CC.ReLU);
network = Layers.Dense(network, 64, computeDevice, activation: CC.ReLU);
network = Layers.Dense(network, 10, computeDevice);
Logging.detailed_summary(network);
Logging.log_number_of_parameters(network);
loss_function = CC.CrossEntropyWithSoftmax(network, categoricalVariable);
eval_function = CC.ClassificationError(network, categoricalVariable);
learner = CC.AdamLearner(
new C.ParameterVector(network.Parameters().ToArray()),
new C.TrainingParameterScheduleDouble(0.001 * batch_size, (uint)batch_size),
new C.TrainingParameterScheduleDouble(0.9),
true,
new C.TrainingParameterScheduleDouble(0.99));
trainer = CC.CreateTrainer(network, loss_function, eval_function, new C.LearnerVector(new C.Learner[] { learner }));
evaluator = CC.CreateEvaluator(eval_function);
}
void train_network() {
var mnist = new Datasets.MNIST();
var trainSteps = mnist.train_images.Length / batch_size;
var validationSteps = mnist.test_images.Length / batch_size;
var wrapped_trainGenerator = new InMemoryMiniBatchGenerator(
new float[][][] { mnist.train_images, mnist.train_labels },
new C.Variable[] { imageVariable, categoricalVariable },
batch_size, true, false, "training");
var trainGenerator = new MultiThreadedGenerator(4, wrapped_trainGenerator);
var wrapped_testGenerator = new InMemoryMiniBatchGenerator(
new float[][][] { mnist.test_images, mnist.test_labels },
new C.Variable[] { imageVariable, categoricalVariable },
batch_size, true, false, "testing");
var validationGenerator = new MultiThreadedGenerator(4, wrapped_testGenerator);
var epochs = 6;
Model.fit_generator(
network,
learner,
trainer,
evaluator,
batch_size,
epochs,
trainGenerator, trainSteps,
validationGenerator, validationSteps,
computeDevice, "mnist_");
trainGenerator.Dispose(); trainGenerator = null;
validationGenerator.Dispose(); validationGenerator = null;
}
}
class Capsules {
static void Main(string[] args) {
//new MNISTExample().run();
new Capsules().run();
}
void run() {
Console.Title = "Capsules";
Console.WriteLine($"Using {computeDevice.AsString()}");
create_network();
train_network();
}
void train_network() {
var mnist = new Datasets.MNIST();
var trainSteps = mnist.train_images.Length / batch_size;
var validationSteps = mnist.test_images.Length / batch_size;
var trainGenerator = new InMemoryMiniBatchGenerator(
new float[][][] { mnist.train_images, mnist.train_labels },
new C.Variable[] { imageVariable, categoricalLabel },
batch_size, shuffle: true, only_once: false, name: "train");
var mtTrainGenerator = new MultiThreadedGenerator(workers: 4, generator: trainGenerator);
var validationGenerator = new InMemoryMiniBatchGenerator(
new float[][][] { mnist.test_images, mnist.test_labels },
new C.Variable[] { imageVariable, categoricalLabel },
batch_size, shuffle: false, only_once: false, name: "validation");
var mtValidationGenerator = new MultiThreadedGenerator(workers: 4, generator: validationGenerator);
var epochs = 6;
Model.fit_generator(
network,
learner,
trainer,
evaluator,
batch_size,
epochs,
mtTrainGenerator, trainSteps,
mtValidationGenerator, validationSteps,
computeDevice,
prefix: "capsules_",
trainingLossMetricName: "Training Loss",
trainingEvaluationMetricName: "Training Error",
validationMetricName: "Validation Error");
mtTrainGenerator.Dispose();
mtValidationGenerator.Dispose();
}
C.Function create_primary_cap(C.Function inputs, int dim_capsule, int n_channels, int[] kernel_size, int[] strides, bool pad) {
var output = Layers.Convolution2D(
inputs,
dim_capsule * n_channels,
kernel_size,
computeDevice,
strides: strides,
use_padding: pad,
name: "primarycap_conv2d");
var outputShape = output.Output.Shape.Dimensions;
System.Diagnostics.Debug.Assert((outputShape[2] == 256) && (outputShape[1] == 6) && (outputShape[0] == 6));
var num_rows = (int)(Util.np_prod(outputShape.ToArray()) / dim_capsule);
var target_shape = new int[] { num_rows, dim_capsule };
var outputs = CC.Reshape(output, target_shape, name: "primarycap_reshape");
var rtrn = squash(outputs, name: "primarycap_squash", axis: 1);
return rtrn;
}
C.Function squash(C.Function vectors, string name, int axis) {
var squared_values = CC.Square(vectors);
var s_squared_sum = CC.ReduceSum(squared_values, new C.AxisVector(new C.Axis[] { new C.Axis(axis) }), keepDims: true);
var epsilon = C.Constant.Scalar(C.DataType.Float, 1e-7, computeDevice);
var one = C.Constant.Scalar(C.DataType.Float, 1.0, computeDevice);
var normalize_factor = CC.Plus(CC.Sqrt(s_squared_sum), epsilon);
var one_plus_s_squared_sum = CC.Plus(s_squared_sum, one);
var scale = CC.ElementDivide(s_squared_sum, one_plus_s_squared_sum);
scale = CC.ElementDivide(scale, normalize_factor);
var result = CC.ElementTimes(scale, vectors, name);
return result;
}
C.Function create_capsule_layer(C.Function inputs, int num_capsule, int dim_capsule, int routings, string name) {
var inputs_shape = inputs.Output.Shape.Dimensions;
var input_num_capsule = inputs_shape[0];
var input_dim_capsule = inputs_shape[1];
var W = new C.Parameter(
new int[] { num_capsule, dim_capsule, input_num_capsule, input_dim_capsule },
C.DataType.Float,
CC.GlorotUniformInitializer(),
computeDevice,
name: "W");
inputs = CC.Reshape(inputs, new int[] { 1, 1, input_num_capsule, input_dim_capsule }); // [1, 1, 1152, 8])
var inputs_hat = CC.ElementTimes(W, inputs);
inputs_hat = CC.ReduceSum(inputs_hat, new C.Axis(3));
inputs_hat = CC.Squeeze(inputs_hat);
C.Function outputs = null;
var zeros = new C.Constant(new int[] { num_capsule, 1, input_num_capsule }, C.DataType.Float, 0, computeDevice);
var b = CC.Combine(new C.VariableVector() { zeros });
for (int i = 0; i < routings; i++) {
var c = CC.Softmax(b, new C.Axis(0));
var batch_dot_result = CC.ElementTimes(c, inputs_hat);
batch_dot_result = CC.ReduceSum(batch_dot_result, new C.Axis(2));
batch_dot_result = CC.Squeeze(batch_dot_result);
outputs = squash(batch_dot_result, name: $"squashed_{i}", axis: 1);
if (i < (routings - 1)) {
outputs = CC.Reshape(outputs, new int[] { num_capsule, dim_capsule, 1 });
batch_dot_result = CC.ElementTimes(outputs, inputs_hat);
batch_dot_result = CC.ReduceSum(batch_dot_result, new C.Axis(1));
b = CC.Plus(b, batch_dot_result);
}
}
outputs = CC.Combine(new C.VariableVector() { outputs }, name);
return outputs;
}
C.Function get_length_and_remove_last_dimension(C.Function x, string name) {
var number_dimensions = x.Output.Shape.Dimensions.Count;
x = CC.Square(x);
var sum_entries = CC.ReduceSum(x, new C.Axis(number_dimensions - 1));
var epsilon = C.Constant.Scalar(C.DataType.Float, 1e-7, computeDevice);
x = CC.Sqrt(CC.Plus(sum_entries, epsilon));
x = CC.Squeeze(x);
return x;
}
C.Function get_mask_and_infer_from_last_dimension(C.Function inputs, C.Function mask) {
if (mask == null) {
var inputs_shape = inputs.Output.Shape.Dimensions.ToArray();
var ndims = inputs_shape.Length - 1;
var x = CC.Sqrt(CC.ReduceSum(CC.Square(inputs), new C.Axis(ndims - 1)));
x = CC.Squeeze(x);
System.Diagnostics.Debug.Assert(x.Output.Shape.Dimensions.Count == 1);
x = CC.Argmax(x, new C.Axis(0));
mask = CC.OneHotOp(x, numClass: (uint)inputs_shape[0], outputSparse: false, axis: new C.Axis(0));
}
mask = CC.Reshape(mask, mask.Output.Shape.AppendShape(new int[] { 1 }));
var masked = CC.ElementTimes(inputs, mask);
masked = CC.Flatten(masked);
masked = CC.Squeeze(masked);
return masked;
}
C.Function create_decoder(int[] digits_capsules_output_shape) {
var decoder_input = Util.inputVariable(digits_capsules_output_shape);
var decoder = Layers.Dense(decoder_input, 512, computeDevice, activation: CC.ReLU);
decoder = Layers.Dense(decoder, 1024, computeDevice, activation: CC.ReLU);
decoder = Layers.Dense(decoder, Util.np_prod(input_shape), computeDevice, activation: CC.Sigmoid);
decoder = CC.Reshape(decoder, input_shape, name: "out_recon");
return decoder;
}
void create_network() {
imageVariable = Util.inputVariable(input_shape, "image");
var conv1 = Layers.Convolution2D(
imageVariable, 256, new int[] { 9, 9 }, computeDevice,
use_padding: false, activation: CC.ReLU, name: "conv1");
var primarycaps = create_primary_cap(
conv1, dim_capsule: 8, n_channels: 32,
kernel_size: new int[] { 9, 9 }, strides: new int[] { 2, 2 }, pad: false);
var digitcaps = create_capsule_layer(
primarycaps, num_capsule: 10, dim_capsule: 16,
routings: routings, name: "digitcaps");
var out_caps = get_length_and_remove_last_dimension(digitcaps, name: "capsnet");
categoricalLabel = Util.inputVariable(new int[] { 10 }, "label");
var masked_by_y = get_mask_and_infer_from_last_dimension(digitcaps, CC.Combine(new C.VariableVector() { categoricalLabel }));
var masked = get_mask_and_infer_from_last_dimension(digitcaps, null);
var decoder = create_decoder(masked.Output.Shape.Dimensions.ToArray());
var decoder_output_training = Model.invoke_model(decoder, new C.Variable[] { masked_by_y });
var decoder_output_evaluation = Model.invoke_model(decoder, new C.Variable[] { masked });
network = CC.Combine(new C.VariableVector() { out_caps, decoder_output_training }, "overall_training_network");
Logging.log_number_of_parameters(network);
// first component of the loss
var y_true = categoricalLabel;
var y_pred = out_caps;
var digit_loss = CC.Plus(
CC.ElementTimes(y_true, CC.Square(CC.ElementMax(DC(0), CC.Minus(DC(0.9), y_pred), ""))),
CC.ElementTimes(DC(0.5),
CC.ElementTimes(CC.Minus(DC(1), y_true), CC.Square(CC.ElementMax(DC(0), CC.Minus(y_pred, DC(0.1)), "")))));
digit_loss = CC.ReduceSum(digit_loss, C.Axis.AllStaticAxes());
// second component of the loss
var num_pixels_at_output = Util.np_prod(decoder_output_training.Output.Shape.Dimensions.ToArray());
var squared_error = CC.SquaredError(decoder_output_training, imageVariable);
var image_mse = CC.ElementDivide(squared_error, DC(num_pixels_at_output));
loss_function = CC.Plus(digit_loss, CC.ElementTimes(DC(0.35), image_mse));
eval_function = CC.ClassificationError(y_pred, y_true);
learner = CC.AdamLearner(
new C.ParameterVector(network.Parameters().ToArray()),
new C.TrainingParameterScheduleDouble(0.001 * batch_size, (uint)batch_size),
new C.TrainingParameterScheduleDouble(0.9),
true,
new C.TrainingParameterScheduleDouble(0.99));
trainer = CC.CreateTrainer(network, loss_function, eval_function, new C.LearnerVector(new C.Learner[] { learner }));
evaluator = CC.CreateEvaluator(eval_function);
}
C.Constant DC(double value) {
// DC: device constant
return C.Constant.Scalar(C.DataType.Float, value, computeDevice);
}
readonly int[] input_shape = new int[] { 28, 28, 1 };
readonly int routings = 3;
readonly int batch_size = 64;
readonly C.DeviceDescriptor computeDevice = Util.get_compute_device();
C.Variable imageVariable;
C.Variable categoricalLabel;
C.Function network;
C.Function loss_function;
C.Function eval_function;
C.Learner learner;
C.Trainer trainer;
C.Evaluator evaluator;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace unitTest_Engine_cs.IO
{
class StaticFile_LoadAsyncFromPackage : EngineTest
{
List<asd.StaticFile> files;
bool finished = false;
public StaticFile_LoadAsyncFromPackage()
: base(60)
{
}
protected override void OnStart()
{
asd.Engine.File.AddRootPackage("Data/Texture/SamplePackage.pack");
files = new List<asd.StaticFile>();
for (int i = 0; i < 9; i++)
{
var f = asd.Engine.File.CreateStaticFile("Cloud" + i + ".png");
files.Add(f);
}
var block = asd.Engine.File.CreateStaticFile("Cloud9.png");
files.Add(block);
}
protected override void OnUpdated()
{
if (!finished && files.All(x => x.LoadState == asd.LoadState.Loaded))
{
Console.WriteLine("読み込み完了");
finished = true;
}
}
}
}
|
using System;
namespace IglooCastle.Samples
{
/// <summary>
/// A sample class for test purposes.
/// </summary>
public sealed class Sample : IEquatable<Sample>
{
/// <summary>
/// Initializes an instance of the <see cref="Sample"/> class.
/// </summary>
public Sample()
{
}
public bool Equals(Sample other)
{
throw new NotImplementedException();
}
public sealed class NestedSample
{
public sealed class SecondLevelNest
{
}
}
}
}
|
using System.Text;
public class Cat : Animal
{
public Cat(string name, string favouriteFood)
: base(name, favouriteFood)
{ }
public override string ExplainMyself()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine($"I am {base.Name} and my fovourite food is {base.FavouriteFood}");
sb.Append("MEEOW");
return sb.ToString();
}
}
|
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CKAN
{
public abstract class JsonPropertyNamesChangedConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType.GetTypeInfo().IsClass;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = Activator.CreateInstance(objectType);
var props = objectType.GetTypeInfo().DeclaredProperties.ToList();
JObject jo = JObject.Load(reader);
var changes = mapping;
foreach (JProperty jp in jo.Properties())
{
string name;
if (!changes.TryGetValue(jp.Name, out name))
{
name = jp.Name;
}
PropertyInfo prop = props.FirstOrDefault(pi => pi.CanWrite && (
pi.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName == name
|| pi.Name == name));
prop?.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
// This is what you need to override in the child class
protected abstract Dictionary<string, string> mapping
{
get;
}
}
}
|
namespace Faforever.Qai.Core.Commands.Arguments
{
public interface IBotUserCapsule
{
string Username { get; }
}
}
|
using System;
using System.Runtime.InteropServices;
namespace MK.MobileDevice.XEDevice
{
// Token: 0x02000018 RID: 24
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct AMDeviceNotificationCallbackInfo
{
// Token: 0x1700002E RID: 46
public unsafe void* dev
{
// Token: 0x060000D9 RID: 217 RVA: 0x00006388 File Offset: 0x00004588
get
{
return this.dev_ptr;
}
}
// Token: 0x04000075 RID: 117
public unsafe void* dev_ptr;
// Token: 0x04000076 RID: 118
public NotificationMessage msg;
}
}
|
using AlphaDev.EntityFramework.Unit.Testing.Support;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using NSubstitute;
namespace AlphaDev.EntityFramework.Unit.Testing.Extensions
{
public static class ObjectExtensions
{
public static EntityEntry<T> ToMockEntityEntry<T>(this T target) where T : class
{
var stateManager = Substitute.For<StateManagerStub>();
#pragma warning disable EF1001
var entityType = new EntityType(typeof(T), new Model(), ConfigurationSource.Convention);
var internalClrEntityEntry = new InternalClrEntityEntry(stateManager, entityType, target);
#pragma warning restore EF1001
var mockEntry = Substitute.For<EntityEntry<T>>(internalClrEntityEntry);
mockEntry.Entity.Returns(target);
return mockEntry;
}
}
} |
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using AspNetApiMonolithSample.Api.Models;
using AspNetApiMonolithSample.Api.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using AspNetApiMonolithSample.Api.Mvc;
namespace AspNetApiMonolithSample.Api.Controllers.Frontend
{
[Authorize]
[Route("Frontend/[controller]")]
public class ThingiesController
{
private readonly IThingieStore thingies;
public ThingiesController(IThingieStore thingies)
{
this.thingies = thingies;
}
public class GetByNameAction
{
public string Name { get; set; } = "";
}
[HttpPost("[action]")]
public int GetOwnedThingie([RequestClaim(AspNetApiMonolithSampleConstants.Claims.OwnsThingie)] int thingieId)
{
return thingieId;
}
[HttpPost("[action]")]
public async Task<Thingie> GetByName([FromBody] GetByNameAction a)
{
return await thingies.FindByNameAsync(a.Name);
}
public class GetByIdAction
{
public int Id { get; set; } = 0;
}
[HttpPost("[action]")]
public async Task<Thingie> GetById([FromBody] GetByIdAction byId)
{
return await thingies.FindByIdAsync(byId.Id);
}
public class StoreThingie
{
[Required]
public Thingie Thingie { get; set; }
}
[HttpPost("[action]")]
public Thingie Store([FromBody] StoreThingie store)
{
return store.Thingie;
}
}
} |
using Newtonsoft.Json;
#pragma warning disable CS8618
namespace Andreal.Data.Json.Pjsk.PjskProfile;
public class UserMusicDifficultyStatusesItem
{
[JsonProperty("musicId")] public int MusicID { get; set; }
[JsonProperty("musicDifficulty")] public string MusicDifficulty { get; set; }
[JsonProperty("userMusicResults")] public List<UserMusicResultsItem> UserMusicResults { get; set; }
}
|
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
namespace Gallio.Common.Reflection
{
/// <summary>
/// Provides basic information about an Assembly derived from its metadata.
/// </summary>
public class AssemblyMetadata
{
private readonly ushort majorRuntimeVersion;
private readonly ushort minorRuntimeVersion;
private readonly CorFlags corflags;
private readonly PEFormat peFormat;
private readonly AssemblyName assemblyName;
private readonly IList<AssemblyName> assemblyReferences;
private readonly string runtimeVersion;
private AssemblyMetadata(ushort majorRuntimeVersion, ushort minorRuntimeVersion, CorFlags corflags, PEFormat peFormat,
AssemblyName assemblyName, IList<AssemblyName> assemblyReferences, string runtimeVersion)
{
this.majorRuntimeVersion = majorRuntimeVersion;
this.minorRuntimeVersion = minorRuntimeVersion;
this.corflags = corflags;
this.peFormat = peFormat;
this.assemblyName = assemblyName;
this.assemblyReferences = assemblyReferences;
this.runtimeVersion = runtimeVersion;
}
/// <summary>
/// Gets the major version of the CLI runtime required for the assembly.
/// </summary>
/// <remarks>
/// <para>
/// Typical runtime versions:
/// <list type="bullet">
/// <item>2.0: .Net 1.0 / .Net 1.1</item>
/// <item>2.5: .Net 2.0 / .Net 3.0 / .Net 3.5 / .Net 4.0</item>
/// </list>
/// </para>
/// </remarks>
public int MajorRuntimeVersion
{
get { return majorRuntimeVersion; }
}
/// <summary>
/// Gets the minor version of the CLI runtime required for the assembly.
/// </summary>
/// <remarks>
/// <para>
/// Typical runtime versions:
/// <list type="bullet">
/// <item>2.0: .Net 1.0 / .Net 1.1</item>
/// <item>2.5: .Net 2.0 / .Net 3.0 / .Net 3.5 / .Net 4.0</item>
/// </list>
/// </para>
/// </remarks>
public int MinorRuntimeVersion
{
get { return minorRuntimeVersion; }
}
/// <summary>
/// Gets the processor architecture required for the assembly.
/// </summary>
public ProcessorArchitecture ProcessorArchitecture
{
get
{
if (peFormat == PEFormat.PE32Plus)
return ProcessorArchitecture.Amd64;
// Issue 704 - If ILOnly is false, we must run x86
if ((corflags & CorFlags.F32BitsRequired) != 0 || (corflags & CorFlags.ILOnly) == 0)
return ProcessorArchitecture.X86;
return ProcessorArchitecture.MSIL;
}
}
/// <summary>
/// Gets the assembly references.
/// </summary>
/// <remarks>
/// <para>
/// This field is only populated when the <see cref="AssemblyMetadataFields.AssemblyName"/> flag is specified.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if the assembly name was not populated.</exception>
public AssemblyName AssemblyName
{
get
{
if (assemblyName == null)
throw new InvalidOperationException("The assembly name was not populated.");
return assemblyName;
}
}
/// <summary>
/// Gets the assembly references.
/// </summary>
/// <remarks>
/// <para>
/// This field is only populated when the <see cref="AssemblyMetadataFields.AssemblyReferences"/> flag is specified.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if the assembly references were not populated.</exception>
public IList<AssemblyName> AssemblyReferences
{
get
{
if (assemblyReferences == null)
throw new InvalidOperationException("The assembly references were not populated.");
return assemblyReferences;
}
}
/// <summary>
/// Gets the runtime version in the form "vX.Y.ZZZZ".
/// </summary>
/// <remarks>
/// <para>
/// This field is only populated when the <see cref="AssemblyMetadataFields.RuntimeVersion"/> flag is specified.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if the runtime version were not populated.</exception>
public string RuntimeVersion
{
get
{
if (runtimeVersion == null)
throw new InvalidOperationException("The runtime version was not populated.");
return runtimeVersion;
}
}
internal static AssemblyMetadata ReadAssemblyMetadata(Stream stream, AssemblyMetadataFields fields)
{
long length = stream.Length;
if (length < 0x40)
return null;
BinaryReader reader = new BinaryReader(stream);
// Read the pointer to the PE header.
stream.Position = 0x3c;
uint peHeaderPtr = reader.ReadUInt32();
if (peHeaderPtr == 0)
peHeaderPtr = 0x80;
// Ensure there is at least enough room for the following structures:
// 24 byte PE Signature & Header
// 28 byte Standard Fields (24 bytes for PE32+)
// 68 byte NT Fields (88 bytes for PE32+)
// >= 128 byte Data Dictionary Table
if (peHeaderPtr > length - 256)
return null;
// Check the PE signature. Should equal 'PE\0\0'.
stream.Position = peHeaderPtr;
uint peSignature = reader.ReadUInt32();
if (peSignature != 0x00004550)
return null;
// Read PE header fields.
ushort machine = reader.ReadUInt16();
ushort numberOfSections = reader.ReadUInt16();
uint timeStamp = reader.ReadUInt32();
uint symbolTablePtr = reader.ReadUInt32();
uint numberOfSymbols = reader.ReadUInt32();
ushort optionalHeaderSize = reader.ReadUInt16();
ushort characteristics = reader.ReadUInt16();
// Read PE magic number from Standard Fields to determine format.
PEFormat peFormat = (PEFormat)reader.ReadUInt16();
if (peFormat != PEFormat.PE32 && peFormat != PEFormat.PE32Plus)
return null;
// Read the 15th Data Dictionary RVA field which contains the CLI header RVA.
// When this is non-zero then the file contains CLI data otherwise not.
stream.Position = peHeaderPtr + (peFormat == PEFormat.PE32 ? 232 : 248);
uint cliHeaderRva = reader.ReadUInt32();
if (cliHeaderRva == 0)
return null;
// Read section headers. Each one is 40 bytes.
// 8 byte Name
// 4 byte Virtual Size
// 4 byte Virtual Address
// 4 byte Data Size
// 4 byte Data Pointer
// ... total of 40 bytes
uint sectionTablePtr = peHeaderPtr + 24 + optionalHeaderSize;
Section[] sections = new Section[numberOfSections];
for (int i = 0; i < numberOfSections; i++)
{
stream.Position = sectionTablePtr + i * 40 + 8;
Section section = new Section();
section.VirtualSize = reader.ReadUInt32();
section.VirtualAddress = reader.ReadUInt32();
reader.ReadUInt32();
section.Pointer = reader.ReadUInt32();
sections[i] = section;
}
// Read parts of the CLI header.
uint cliHeaderPtr = ResolveRva(sections, cliHeaderRva);
if (cliHeaderPtr == 0)
return null;
stream.Position = cliHeaderPtr + 4;
ushort majorRuntimeVersion = reader.ReadUInt16();
ushort minorRuntimeVersion = reader.ReadUInt16();
uint metadataRva = reader.ReadUInt32();
uint metadataSize = reader.ReadUInt32();
CorFlags corflags = (CorFlags)reader.ReadUInt32();
// Read optional fields.
AssemblyName assemblyName = null;
IList<AssemblyName> assemblyReferences = null;
string runtimeVersion = null;
if ((fields & AssemblyMetadataFields.RuntimeVersion) != 0)
{
uint metadataPtr = ResolveRva(sections, metadataRva);
stream.Position = metadataPtr + 12;
int paddedRuntimeVersionLength = reader.ReadInt32();
byte[] runtimeVersionBytes = reader.ReadBytes(paddedRuntimeVersionLength);
int runtimeVersionLength = 0;
while (runtimeVersionLength < paddedRuntimeVersionLength
&& runtimeVersionBytes[runtimeVersionLength] != 0)
runtimeVersionLength += 1;
runtimeVersion = Encoding.UTF8.GetString(runtimeVersionBytes, 0, runtimeVersionLength);
}
if ((fields & (AssemblyMetadataFields.AssemblyName | AssemblyMetadataFields.AssemblyReferences)) != 0)
{
// Using Cecil.
stream.Position = 0;
var imageReader = new ImageReader(stream);
if ((fields & AssemblyMetadataFields.AssemblyName) != 0)
assemblyName = imageReader.GetAssemblyName();
if ((fields & AssemblyMetadataFields.AssemblyReferences) != 0)
assemblyReferences = imageReader.GetAssemblyReferences();
}
// Done.
return new AssemblyMetadata(majorRuntimeVersion, minorRuntimeVersion, corflags, peFormat,
assemblyName, assemblyReferences, runtimeVersion);
}
private static uint ResolveRva(IEnumerable<Section> sections, uint rva)
{
foreach (Section section in sections)
{
if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.VirtualSize)
return rva - section.VirtualAddress + section.Pointer;
}
return 0;
}
private sealed class ImageReader
{
private readonly AssemblyDefinition assemblyDefinition;
public ImageReader(Stream stream)
{
assemblyDefinition = AssemblyDefinition.ReadAssembly(stream);
}
public AssemblyName GetAssemblyName()
{
var assemblyName = new AssemblyName
{
Name = assemblyDefinition.Name.Name,
Version = assemblyDefinition.Name.Version,
CultureInfo = new CultureInfo(assemblyDefinition.Name.Culture)
};
if (assemblyDefinition.Name.PublicKey.Length > 0)
assemblyName.SetPublicKey(assemblyDefinition.Name.PublicKey);
return assemblyName;
}
public IList<AssemblyName> GetAssemblyReferences()
{
var assemblyReferences = new List<AssemblyName>();
foreach (var reference in assemblyDefinition.MainModule.AssemblyReferences)
{
var assemblyName = new AssemblyName
{
Name = reference.Name,
Version = reference.Version,
CultureInfo = new CultureInfo(reference.Culture)
};
if (reference.HasPublicKey)
assemblyName.SetPublicKey(reference.PublicKey);
if (reference.PublicKeyToken != null)
assemblyName.SetPublicKeyToken(reference.PublicKeyToken);
assemblyReferences.Add(assemblyName);
}
return assemblyReferences;
}
}
private enum PEFormat : ushort
{
PE32 = 0x10b,
PE32Plus = 0x20b
}
[Flags]
private enum CorFlags : uint
{
F32BitsRequired = 2,
ILOnly = 1,
StrongNameSigned = 8,
TrackDebugData = 0x10000
}
private class Section
{
public uint VirtualAddress;
public uint VirtualSize;
public uint Pointer;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using AllenCopeland.Abstraction.Slf.Abstract;
using AllenCopeland.Abstraction.Slf.Cli.Metadata.Tables;
using AllenCopeland.Abstraction.Slf.Cli.Modules;
using AllenCopeland.Abstraction.Slf.Platforms.WindowsNT;
using AllenCopeland.Abstraction.Slf.Cli.Metadata.Blobs;
namespace AllenCopeland.Abstraction.Slf.Cli
{
/// <summary>
/// Defines properties and methods for resolving the identities
/// of entities from the Common Language Infrastructure.
/// </summary>
public interface ICliManager :
IIdentityManager<Type, Assembly>,
IIdentityManager<string, string>,
IIdentityManager<ICliMetadataTypeDefinitionTableRow, ICliMetadataAssemblyTableRow>,
IIdentityManager<ICliMetadataTypeRefTableRow, ICliMetadataAssemblyRefTableRow>,
ITypeIdentityManager<ICliMetadataTypeSpecificationTableRow>,
ITypeIdentityManager<ICliMetadataTypeDefOrRefRow>,
IDisposable
{
event EventHandler Disposed;
/// <summary>
/// Obtains a <see cref="ICopmiledAssembly"/> reference by the filename.
/// </summary>
/// <param name="filename">The <see cref="String"/> value
/// which denotes the location of the assembly image.</param>
/// <returns>A <see cref="IAssembly"/> which denotes the assembly in
/// question.</returns>
/// <exception cref="System.IO.FileNotFoundException">thrown when
/// <paramref name="filename"/> was not found.</exception>
IAssembly ObtainAssemblyReference(string filename);
/// <summary>
/// Returns the <see cref="ICliRuntimeEnvironmentInfo"/> the
/// which details the framework version and platform
/// <see cref="ICliManager"/> is targeting.
/// </summary>
new ICliRuntimeEnvironmentInfo RuntimeEnvironment { get; }
/// <summary>
/// Returns the <see cref="IType"/> from the <paramref name="coreType"/> provided.
/// </summary>
/// <param name="coreType">The <see cref="CliRuntimeCoreType"/> which denotes the
/// core type to obtain a type reference of.</param>
/// <param name="relativeSource">The <see cref="IAssembly"/> which represents
/// the lookup scope for the type to retrieve.</param>
/// <returns>A <see cref="IType"/> relative to the <paramref name="coreType"/>
/// within the scope of <paramref name="relativeSource"/>.</returns>
IType ObtainTypeReference(CliRuntimeCoreType coreType, IAssembly relativeSource);
/// <summary>
/// Returns the <see cref="IType"/> from the <paramref name="uniqueIdentifier"/> provided.
/// </summary>
/// <param name="uniqueIdentifier">The <see cref="IGeneralTypeUniqueIdentifier"/> of
/// to the type to retrieve relative to the scope of
/// <paramref name="relativeScope"/>.</param>
/// <param name="relativeSource">The <see cref="IAssembly"/> which represents
/// the lookup scope for the type to retrieve.</param>
/// <returns>A <see cref="IType"/> relative to the <paramref name="uniqueIdentifier"/>
/// within the scope of <paramref name="relativeSource"/>.</returns>
IType ObtainTypeReference(IGeneralTypeUniqueIdentifier uniqueIdentifier, IAssembly relativeSource);
event EventHandler<CliAssemblyLoadedEventArgs> AssemblyLoaded;
}
}
|
/****************************************************
文件:SoldierCamp.cs
作者:zhyStay
邮箱: zhy18125@163.com
日期:2021/2/19 23:13:08
功能:Nothing
*****************************************************/
using System;
using System.Collections.Generic;
using UnityEngine;
public class SoldierCamp : ICamp
{
private const int MAX_LV = 4; // 兵营最大等级
private int mLv = 1; // 兵营等级
private WeaponType mWeaponType = WeaponType.Gun;
public SoldierCamp(GameObject gameObject, string name, string iconSprite,
SoldierType soldierType, Vector3 position, float trainTime,
WeaponType weaponType = WeaponType.Gun, int lv = 1)
: base(gameObject, name, iconSprite, soldierType, position, trainTime)
{
mLv = lv;
mWeaponType = weaponType;
energyCostStrategy = new SoldierEnergyCostStrategy();
UpdateEnergyCost();
}
public override int Lv
{
get { return mLv; }
}
public override WeaponType WeaponType
{
get { return mWeaponType; }
}
public override void Train()
{
// 添加训练命令
TrainSoldierCommand cmd = new TrainSoldierCommand(mSoldierType, mWeaponType, mPosition, mLv);
mCommands.Add(cmd);
}
public override void Update()
{
base.Update();
}
public override void UpgradeCamp()
{
// 兵营升级处理
mLv++;
UpdateEnergyCost(); // 更新策略
}
public override void UpgradeWeapon()
{
// 武器升级处理
mWeaponType += 1;
UpdateEnergyCost(); // 更新策略
}
protected override void UpdateEnergyCost()
{
mEnergyCostCampUpgrade = energyCostStrategy.GetCampUpgradeCost(mSoldierType, mLv);
mEnergyCostWeaponUpgrade = energyCostStrategy.GetWeaponUpgradeCost(mWeaponType);
mEnergyCostTrain = energyCostStrategy.GetSoldierTrainCost(mSoldierType, mLv);
}
public override int EnergyCostCampUpgrade
{
get
{
if (mLv == MAX_LV)
return -1;
else
return mEnergyCostCampUpgrade;
}
}
public override int EnergyCostWeaponUpgrade
{
get
{
if (mWeaponType + 1 == WeaponType.MAX_LV)
return -1;
else
return mEnergyCostWeaponUpgrade;
}
}
public override int EnergyCostTrain
{
get
{
return mEnergyCostTrain;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Crews.API.Data.Entities;
public class Crew
{
[Key]
public int Id { get; set; }
public Guid UniqueId { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string ShortName { get; set; }
// żółta, niebieska, czerwona, podstawowa, średnio-zaawansowana, zaawansowana etc.
[Required]
[MaxLength(50)]
public string Group { get; set; }
[Required]
[Range(1990, 2999)]
public int Year { get; set; }
// Na serwerze w DB trzymany jest Id do loga. Na podstawie Id możemy ściągnąć Resource (byte[]) z serwera bądź
// też z cache, który jest lokalnie
public Guid LogoId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
// Województwo - gdyby ktoś chciał wylistować wszystkie zespoły z danego województwa
public string Region { get; set; }
// Powiat - gdyby ktoś chciał wylistować wszystkie zespoły z powiatu np. Trzebnicki
public string Subregion { get; set; }
public bool Archived { get; set; }
[Required]
public DateTime DateTimeAdd { get; set; }
public ICollection<Training> Trainings { get; set; }
public User User { get; set; }
} |
using Xunit;
using MetadataExtractor.Util;
namespace MetadataExtractor.Tests.Util
{
public class ByteArrayUtilTest
{
[Fact]
public void StartsWith()
{
var bytes = new byte[] { 0, 1, 2, 3 };
Assert.True(bytes.StartsWith(new byte[] { }));
Assert.True(bytes.StartsWith(new byte[] { 0 }));
Assert.True(bytes.StartsWith(new byte[] { 0, 1 }));
Assert.True(bytes.StartsWith(new byte[] { 0, 1, 2 }));
Assert.True(bytes.StartsWith(new byte[] { 0, 1, 2, 3 }));
Assert.False(bytes.StartsWith(new byte[] { 0, 1, 2, 3, 4 }));
Assert.False(bytes.StartsWith(new byte[] { 1 }));
Assert.False(bytes.StartsWith(new byte[] { 1, 2 }));
}
}
} |
using Eaf.Domain.Services;
namespace Eaf.ProjectName
{
public abstract class ProjectNameDomainServiceBase : DomainService
{
/* ADD YOUR COMMON MEMBERS FOR ALL YOUR DOMAIN SERVICES. */
protected ProjectNameDomainServiceBase()
{
LocalizationSourceName = ProjectNameConsts.LocalizationSourceName;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeviceAuthentication : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine (DelayAuthenticateRoutine ());
}
IEnumerator DelayAuthenticateRoutine(){
yield return new WaitForSeconds (1f);
new GameSparks.Api.Requests.DeviceAuthenticationRequest().Send((response) => {
if (!response.HasErrors) {
Debug.Log("Device Authenticated...");
//set X active once we are authenticated
//
} else {
Debug.Log("Error Authenticating Device...");
}
});
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Threading.RateLimiting.Test
{
public class ConcurrencyLimiterTests
{
[Fact]
public void CanAcquireResource()
{
var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(1, QueueProcessingOrder.NewestFirst, 1));
var lease = limiter.Acquire();
Assert.True(lease.IsAcquired);
Assert.False(limiter.Acquire().IsAcquired);
lease.Dispose();
Assert.True(limiter.Acquire().IsAcquired);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Sherlock.Core
{
internal class ItemCollection : List<IItem>, IItemCollection
{
}
}
|
namespace GoDaddy.Asherah.Crypto.CipherSuites
{
public enum AeadCipherSuite
{
Aes256Gcm,
}
}
|
using System.Security.Claims;
namespace SchoolBusAPI.Extensions
{
public static class ClaimsPrincipalExtensions
{
public static (string username, string userGuid, string directory) GetUserInfo(this ClaimsPrincipal principal)
{
var preferredUsername = principal.FindFirstValue("preferred_username");
var usernames = preferredUsername?.Split("@");
var username = usernames?[0].ToUpperInvariant();
var directory = usernames?[1].ToUpperInvariant();
var userGuidClaim = directory?.ToUpperInvariant() == "IDIR" ? "idir_userid" : "bceid_userid";
var userGuid = principal.FindFirstValue(userGuidClaim)?.ToUpperInvariant();
return (username, userGuid, directory);
}
}
}
|
using ReactiveUI;
using System.Collections.ObjectModel;
using PurpleExplorer.Models;
using Splat;
namespace PurpleExplorer.ViewModels
{
public class ConnectionStringWindowViewModel : DialogViewModelBase
{
private string _connectionString;
private readonly IAppState _appState;
public ObservableCollection<string> SavedConnectionStrings { get; set; }
public string ConnectionString
{
get => _connectionString;
set => this.RaiseAndSetIfChanged(ref _connectionString, value);
}
public ConnectionStringWindowViewModel(IAppState appState = null)
{
_appState = appState ?? Locator.Current.GetService<IAppState>();
SavedConnectionStrings = _appState.SavedConnectionStrings;
}
}
} |
using Chess.Core;
namespace Chess.Engine
{
interface IGameInitializer
{
Square[][] Initialize();
}
} |
using System.Collections.Generic;
namespace ReactiveUIUnoSample.Interfaces.Testing
{
public interface ITwoLineTestResults
{
string Title { get; set; }
IList<ITwoLineTestItem> UserWasCorrect { get; set; }
IList<ITwoLineTestWrongAnswer> UserWasWrong { get; set; }
IList<ITwoLineTestItem> TestItems { get; set; }
bool HasRightAnswers { get; }
bool AllWrong { get; }
bool HasWrongAnswers { get; }
string PercentCorrect { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PCAxis.Sql.Pxs {
/// <summary>
/// This class is used be the FlatFileReader-method to store some temp-values.
/// </summary>
class FlatFileReaderHelper{
internal int no_vars = -1;
internal int no_vars_before_heading = -1;
internal int no_vars_before_time = -1;
internal int var_counter = -1;
internal String langInFile = null;
//The [] determin which variable ( VAR0, VAR1 ...)
// the list conatins the values for a variable
internal PQVariable[] tmpVariable;
internal List<ValueTypeWithGroup>[] variableValues;
//The [] determin which variable ( VAR0, VAR1 ...)
// the dictionary use the molecule code as key for list of atom codes
internal Dictionary<string, List<GroupValueType>>[] groupsValuesByValueCode;
//The [] determin which variable ( VAR0, VAR1 ...)
// the dictionary use the value sortorder as key for text
internal Dictionary<int, string>[] groupTextByValueSortOrder;
internal List<BasicValueType> timeValues = new List<BasicValueType>();
internal List<BasicValueType> contentValues = new List<BasicValueType>();
internal List<MenuSelType> menuSelList = new List<MenuSelType>();
internal FlatFileReaderHelper() { }
}
}
|
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
namespace Microsoft.VisualStudio.Text
{
using System;
/// <summary>
/// Describes a version of an <see cref="ITextBuffer"/>. Each application of an <see cref="ITextEdit"/> to a text buffer
/// generates a new ITextVersion.
/// </summary>
public interface ITextVersion
{
/// <summary>
/// Gets the next <see cref="ITextVersion"/>. Returns null if and only if this is the most recent version of its text buffer.
/// </summary>
ITextVersion Next { get; }
/// <summary>
/// Gets the length in characters of this <see cref="ITextVersion"/>.
/// </summary>
int Length { get; }
/// <summary>
/// Gets the text changes that produce the next version. Returns null if and only if this is the most recent version of its text buffer.
/// </summary>
INormalizedTextChangeCollection Changes { get; }
/// <summary>
/// Creates a <see cref="ITrackingPoint"/> against this version.
/// </summary>
/// <param name="position">The position of the point.</param>
/// <param name="trackingMode">The tracking mode of the point.</param>
/// <returns>A non-null <see cref="ITrackingPoint"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="position"/> is less than zero or greater than the length of this version.</exception>
ITrackingPoint CreateTrackingPoint(int position, PointTrackingMode trackingMode);
/// <summary>
/// Creates a <see cref="ITrackingPoint"/> against this version.
/// </summary>
/// <param name="position">The position of the point.</param>
/// <param name="trackingMode">The tracking mode of the point.</param>
/// <param name="trackingFidelity">The tracking fidelity of the point.</param>
/// <returns>A non-null <see cref="ITrackingPoint"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="position"/> is less than zero or greater than the length of the snapshot.</exception>
/// <remarks>This text point reprises its previous position when visiting a version that was created by undo or redo.</remarks>
ITrackingPoint CreateTrackingPoint(int position, PointTrackingMode trackingMode, TrackingFidelityMode trackingFidelity);
/// <summary>
/// Creates a <see cref="ITrackingSpan"/> against this version.
/// </summary>
/// <param name="span">The span of text in this snapshot that the <see cref="ITrackingSpan"/> should represent.</param>
/// <param name="trackingMode">How the <see cref="ITrackingSpan"/> will react to changes at its boundaries.</param>
/// <returns>A non-null <see cref="ITrackingSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="span"/>.End is greater than the length of this version, or
/// <paramref name="trackingMode"/> is equal to <see cref="SpanTrackingMode.Custom"/>.</exception>
ITrackingSpan CreateTrackingSpan(Span span, SpanTrackingMode trackingMode);
/// <summary>
/// Creates a <see cref="ITrackingSpan"/> against this version.
/// </summary>
/// <param name="span">The span of text in this snapshot that the <see cref="ITrackingSpan"/> should represent.</param>
/// <param name="trackingMode">How the <see cref="ITrackingSpan"/> will react to changes at its boundaries.</param>
/// <param name="trackingFidelity">The tracking fidelity of the span.</param>
/// <returns>A non-null <see cref="ITrackingSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="span"/>.End is greater than <see cref="Length"/>, or
/// <paramref name="trackingMode"/> is equal to <see cref="SpanTrackingMode.Custom"/>.</exception>
ITrackingSpan CreateTrackingSpan(Span span, SpanTrackingMode trackingMode, TrackingFidelityMode trackingFidelity);
/// <summary>
/// Creates a <see cref="ITrackingSpan"/> against this version.
/// </summary>
/// <param name="start">The starting position of the <see cref="ITrackingSpan"/> in this version.</param>
/// <param name="length">The length of the <see cref="ITrackingSpan"/> in this version.</param>
/// <param name="trackingMode">How the <see cref="ITrackingSpan"/> will react to changes at its boundaries.</param>
/// <returns>A non-null <see cref="ITrackingSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> is negative or greater than the length of this version, or
/// <paramref name="length"/> is negative, or <paramref name="start"/> + <paramref name="length"/>
/// is less than <paramref name="start"/>, or
/// <paramref name="trackingMode"/> is equal to <see cref="SpanTrackingMode.Custom"/>.</exception>
ITrackingSpan CreateTrackingSpan(int start, int length, SpanTrackingMode trackingMode);
/// <summary>
/// Creates a <see cref="ITrackingSpan"/> against this version.
/// </summary>
/// <param name="start">The starting position of the <see cref="ITrackingSpan"/> in this snapshot.</param>
/// <param name="length">The length of the <see cref="ITrackingSpan"/> in this snapshot.</param>
/// <param name="trackingMode">How the <see cref="ITrackingSpan"/> will react to changes at its boundaries.</param>
/// <param name="trackingFidelity">The tracking fidelity mode.</param>
/// <returns>A non-null <see cref="ITrackingSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> is negative or greater than <see cref="Length"/>, or
/// <paramref name="length"/> is negative, or <paramref name="start"/> + <paramref name="length"/>
/// is less than <paramref name="start"/>, or
/// <paramref name="trackingMode"/> is equal to <see cref="SpanTrackingMode.Custom"/>.</exception>
ITrackingSpan CreateTrackingSpan(int start, int length, SpanTrackingMode trackingMode, TrackingFidelityMode trackingFidelity);
/// <summary>
/// Creates a custom <see cref="ITrackingSpan"/> against this version.
/// </summary>
/// <param name="span">The span of text in this snapshot that the <see cref="ITrackingSpan"/> should represent.</param>
/// <param name="trackingFidelity">The tracking fidelity of the span.</param>
/// <param name="customState">Client-defined state associated with the span.</param>
/// <param name="behavior">The custom tracking behavior.</param>
/// <returns>A non-null <see cref="ITrackingSpan"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="span"/>.End is greater than <see cref="Length"/>.</exception>
ITrackingSpan CreateCustomTrackingSpan(Span span, TrackingFidelityMode trackingFidelity, object customState, CustomTrackToVersion behavior);
/// <summary>
/// The <see cref="ITextBuffer"/> to which this <see cref="ITextVersion"/> applies.
/// </summary>
ITextBuffer TextBuffer { get; }
/// <summary>
/// The version number for this version. It is used for comparisons between versions of the same buffer.
/// </summary>
int VersionNumber { get; }
/// <summary>
/// Gets the oldest version number for which all text changes between that version and this version have
/// been canceled out by corresponding undo/redo operations.
/// </summary>
/// <remarks>
/// If ReiteratedVersionNumber is not equal to <see cref="VersionNumber" />, then for every
/// <see cref="ITextChange" /> not originated by an undo operation between ReiteratedVersionNumber and VersionNumber, there is a
/// corresponding <see cref="ITextChange"/> originated by an undo operation that cancels it out. So the contents of the two
/// versions are necessarily identical.
///<para>
/// Setting this property correctly is the responsibility of the undo system; aside from this
/// property, the text buffer and related classes are unaware of undo and redo.
/// </para>
/// <para>
/// Note that the <see cref="ITextVersion"/> objects created through <see cref="ITextBuffer.ChangeContentType"/>
/// have no text changes and will therefore keep the ReiteratedVersionNumber of the
/// previous version.
/// </para>
/// </remarks>
int ReiteratedVersionNumber { get; }
}
}
|
using System;
using Calculator.Lexing;
using Calculator.Parsing;
using GParse;
using GParse.Parsing;
using GParse.Parsing.Parselets;
using Tsu;
namespace Calculator.Parsing.Parselets
{
/// <summary>
/// Represents an exponentiation through superscript expression
/// </summary>
public class SuperscriptExponentiationExpressionParselet : IInfixParselet<CalculatorTokenType, CalculatorTreeNode>
{
/// <summary>
/// Initializes this <see cref="SuperscriptExponentiationExpressionParselet"/>
/// </summary>
/// <param name="precedence"></param>
public SuperscriptExponentiationExpressionParselet(int precedence) =>
Precedence = precedence;
/// <inheritdoc />
public int Precedence { get; }
/// <inheritdoc />
public Option<CalculatorTreeNode> Parse(
IPrattParser<CalculatorTokenType, CalculatorTreeNode> parser,
CalculatorTreeNode @base,
DiagnosticList diagnostics)
{
if (parser is null)
throw new ArgumentNullException(nameof(parser));
if (@base is null)
throw new ArgumentNullException(nameof(@base));
if (diagnostics is null)
throw new ArgumentNullException(nameof(diagnostics));
var reader = parser.TokenReader;
if (reader.Accept(CalculatorTokenType.Superscript, out var exponent))
return new SuperscriptExponentiationExpression(@base, exponent);
return Option.None<CalculatorTreeNode>();
}
}
} |
using SetsProcessor.Domain;
using System;
using System.Linq;
using System.Text;
namespace SetsProcessor.API
{
public class Functions
{
private SetsCollection Collection { get; }
public Functions()
{
Collection = new SetsCollection();
}
/// <summary>
/// Permite añadir un set
/// </summary>
/// <param name="set"></param>
/// <returns></returns>
public bool AddSet(string set)
{
return Collection.Add(set);
}
/// <summary>
/// Devuelve la cantidad de set correctos que se han añadido y cuántos se han añadidos múltiples veces
/// </summary>
/// <returns></returns>
public string Resume()
{
var repeated = Collection.ValidateSets.Count(x => x.Value > 1);
var notRepeated = Collection.ValidateSets.Count(x => x.Value == 1);
return String.Format(Resources.ResumeMessage, repeated, notRepeated);
}
/// <summary>
/// Devuelve el listado de strings que no tenían un formato correcto
/// </summary>
/// <returns></returns>
public string GetIncorrectSets()
{
StringBuilder sb = new StringBuilder();
foreach (var set in Collection.UnvalidSets)
sb.Append(set.Key + Environment.NewLine);
return String.Format(Resources.UnvalidateMessage, sb.ToString());
}
/// <summary>
/// Devuelve el set más frecuentemente insertado
/// </summary>
/// <returns></returns>
public string GetMoreFrequentSet()
{
return Collection.MoreRepeatSet.ToString();
}
}
}
|
using System;
namespace FTX.Net.Objects.Futures
{
/// <summary>
/// Funding rate info
/// </summary>
public class FTXFundingRate
{
/// <summary>
/// Future name
/// </summary>
public string Future { get; set; } = string.Empty;
/// <summary>
/// Funding rate
/// </summary>
public decimal Rate { get; set; }
/// <summary>
/// Time
/// </summary>
public DateTime Time { get; set; }
}
}
|
using System.Web;
using System.Web.Http;
namespace BlueGreenTest.Controllers
{
public class SessionController : ApiController
{
[HttpGet]
public string Test()
{
HttpContext.Current.Session["TEST"] = 123;
return "HELLO";
}
}
} |
using System;
namespace De.Osthus.Ambeth.Service
{
public interface ICacheRetrieverExtendable
{
void RegisterCacheRetriever(ICacheRetriever cacheRetriever, Type handledType);
void UnregisterCacheRetriever(ICacheRetriever cacheRetriever, Type handledType);
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FallThroughBehavior : AgentBehavior
{
private List<AgentBehavior> behaviorList = new List<AgentBehavior>();
public void addBehavior(AgentBehavior newBehavior)
{
behaviorList.Add(newBehavior);
newBehavior.setAgent(_myself);
}
public AgentBehavior getBehaviorAt(int index)
{
return behaviorList[index];
}
public void removeBehaviorAt(int index)
{
behaviorList.RemoveAt(index);
}
public override void setAgent(Agent newAgent)
{
_myself = newAgent;
for(int i=0; i<this.behaviorList.Count; i++)
{
behaviorList[i].setAgent(_myself);
}
}
public override bool executePlanUpdate()
{
bool planCleared = false;
for(int i=0; i<this.behaviorList.Count; i++)
{
if(behaviorList[i].updatePlan(null, 0.0f))
{
if(!planCleared)
{
currentPlans.Clear();
planCleared = true;
}
List<Action> tempPlans = behaviorList[i].getCurrentPlans();
for(int planIdx=0; planIdx<tempPlans.Count; planIdx++)
{
currentPlans.Add(tempPlans[planIdx]);
_myself.LookInUse = (_myself.LookInUse || tempPlans[planIdx].getUsingLook());
_myself.MoveInUse = (_myself.MoveInUse || tempPlans[planIdx].getUsingMove());
}
}
}
return false;
}
}
|
/*
* Copyright (c) 1989 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Robert Paul Corbett.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Yacc
{
public class Reader : Grammar<string>
{
#if !lint
static readonly string sccsid = "@(#)reader.c 5.7 (Berkeley) 1/20/91";
#endif // not lint
/* The line size must be a positive integer. One hundred was chosen */
/* because few lines in Yacc input grammars exceed 100 characters. */
/* Note that if a line exceeds LINESIZE characters, the line buffer */
/* will be expanded to accomodate it. */
private List<string> m_TagTable = new List<string>();
private int m_ColumnNo;
private string m_Line;
private string m_InputFileName;
private TextReader m_InputFile; /* the input file */
private Output m_Output;
private Rules m_CurrentRule;
private bool m_ZeroBase;
public Reader(Yacc<string> yacc, Output output)
: base(yacc)
{
m_Output = output;
}
private static bool IsOctal(int c) { return ((c) >= '0' && (c) <= '7'); }
public string InputFileName {
get { return m_InputFileName; }
set { m_InputFileName = value; }
}
public TextReader InputFile {
get { return m_InputFile; }
set { m_InputFile = value; }
}
public bool ZeroBase {
get { return m_ZeroBase; }
set { m_ZeroBase = value; }
}
void GetLine()
{
string temp = m_InputFile.ReadLine();
if (temp != null)
m_Line = temp + "\n";
m_ColumnNo = 0;
++Error.LineNo;
}
string DupLine()
{
int s;
if (m_Line == null)
return null;
s = m_Line.IndexOf('\n');
if (s < 0)
return null;
return m_Line.Substring(0, s + 1);
}
void SkipComment()
{
int s;
int st_lineno = Error.LineNo;
string st_line = DupLine();
int st_cptr = m_ColumnNo;
s = m_ColumnNo + 2;
for (;;) {
if (m_Line[s] == '*' && m_Line[s + 1] == '/') {
m_ColumnNo = s + 2;
return;
}
if (m_Line[s] == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedComment(st_lineno, st_line, st_cptr);
s = m_ColumnNo;
}
else
++s;
}
}
int Nextc()
{
int s;
if (m_Line == null) {
GetLine();
if (m_Line == null)
return Defs.EOF;
}
s = m_ColumnNo;
for (;;) {
switch (m_Line[s]) {
case '\n':
GetLine();
if (m_Line == null) return Defs.EOF;
s = m_ColumnNo;
break;
case ' ':
case '\t':
case '\f':
case '\r':
case '\v':
case ',':
case ';':
++s;
break;
case '\\':
m_ColumnNo = s;
return '%';
case '/':
if (m_Line[s + 1] == '*') {
m_ColumnNo = s;
SkipComment();
s = m_ColumnNo;
break;
}
else if (m_Line[s + 1] == '/') {
GetLine();
if (m_Line == null) return Defs.EOF;
s = m_ColumnNo;
break;
}
goto default;/* fall through */
default:
m_ColumnNo = s;
return m_Line[s];
}
}
}
KeywordCode Keyword()
{
char c;
int t_cptr = m_ColumnNo;
c = m_Line[++m_ColumnNo];
if (Char.IsLetter(c)) {
StringBuilder cache = new StringBuilder();
for (;;) {
if (Char.IsLetter(c)) {
if (Char.IsUpper(c)) c = Char.ToLower(c);
cache.Append((char)c);
}
else if (Char.IsDigit(c) || c == '_' || c == '.' || c == '$')
cache.Append((char)c);
else
break;
c = m_Line[++m_ColumnNo];
}
if (String.Compare(cache.ToString(), "token") == 0 || String.Compare(cache.ToString(), "term") == 0)
return KeywordCode.TOKEN;
if (String.Compare(cache.ToString(), "type") == 0)
return KeywordCode.TYPE;
if (String.Compare(cache.ToString(), "left") == 0)
return KeywordCode.LEFT;
if (String.Compare(cache.ToString(), "right") == 0)
return KeywordCode.RIGHT;
if (String.Compare(cache.ToString(), "nonassoc") == 0 || String.Compare(cache.ToString(), "binary") == 0)
return KeywordCode.NONASSOC;
if (String.Compare(cache.ToString(), "start") == 0)
return KeywordCode.START;
}
else {
m_ColumnNo++;
if (c == '{')
return KeywordCode.TEXT;
if (c == '%' || c == '\\')
return KeywordCode.MARK;
if (c == '<')
return KeywordCode.LEFT;
if (c == '>')
return KeywordCode.RIGHT;
if (c == '0')
return KeywordCode.TOKEN;
if (c == '2')
return KeywordCode.NONASSOC;
}
Error.SyntaxError(Error.LineNo, m_Line, t_cptr);
/*NOTREACHED*/
return (KeywordCode)(-1);
}
void CopyText(TextWriter f)
{
int c;
int quote;
bool need_newline = false;
int t_lineno = Error.LineNo;
string t_line = DupLine();
int t_cptr = m_ColumnNo - 2;
if (m_Line[m_ColumnNo] == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedText(t_lineno, t_line, t_cptr);
}
f.Write(m_Output.LineFormat, Error.LineNo, Error.InputFileName);
loop:
c = m_Line[m_ColumnNo++];
switch (c) {
case '\n':
next_line:
f.Write('\n');
need_newline = false;
GetLine();
if (m_Line != null) goto loop;
Error.UnterminatedText(t_lineno, t_line, t_cptr);
break;
case '\'':
case '"': {
int s_lineno = Error.LineNo;
string s_line = DupLine();
int s_cptr = m_ColumnNo - 1;
quote = c;
f.Write((char)c);
for (;;) {
c = m_Line[m_ColumnNo++];
f.Write((char)c);
if (c == quote) {
need_newline = true;
goto loop;
}
if (c == '\n')
Error.UnterminatedString(s_lineno, s_line, s_cptr);
if (c == '\\') {
c = m_Line[m_ColumnNo++];
f.Write((char)c);
if (c == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedString(s_lineno, s_line, s_cptr);
}
}
}
}
break;
case '/':
f.Write((char)c);
need_newline = true;
c = m_Line[m_ColumnNo];
if (c == '/') {
do f.Write((char)c); while ((c = m_Line[++m_ColumnNo]) != '\n');
goto next_line;
}
if (c == '*') {
int c_lineno = Error.LineNo;
string c_line = DupLine();
int c_cptr = m_ColumnNo - 1;
f.Write('*');
m_ColumnNo++;
for (;;) {
c = m_Line[m_ColumnNo++];
f.Write((char)c);
if (c == '*' && m_Line[m_ColumnNo] == '/') {
f.Write('/');
m_ColumnNo++;
goto loop;
}
if (c == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedComment(c_lineno, c_line, c_cptr);
}
}
}
need_newline = true;
goto loop;
case '%':
case '\\':
if (m_Line[m_ColumnNo] == '}') {
if (need_newline) f.Write('\n');
m_ColumnNo++;
return;
}
goto default; /* fall through */
default:
f.Write((char)c);
need_newline = true;
goto loop;
}
}
int HexVal(int c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
return -1;
}
Symbol GetLiteral()
{
char c, quote;
int i;
int n;
Symbol bp;
int s_lineno = Error.LineNo;
string s_line = DupLine();
int s_cptr = m_ColumnNo;
quote = m_Line[m_ColumnNo++];
StringBuilder cache = new StringBuilder();
for (;;) {
c = m_Line[m_ColumnNo++];
if (c == quote) break;
if (c == '\n') Error.UnterminatedString(s_lineno, s_line, s_cptr);
if (c == '\\') {
int c_cptr = m_ColumnNo - 1;
c = m_Line[m_ColumnNo++];
switch (c) {
case '\n':
GetLine();
if (m_Line == null) Error.UnterminatedString(s_lineno, s_line, s_cptr);
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
n = c - '0';
c = m_Line[m_ColumnNo];
if (IsOctal(c)) {
n = (n << 3) + (c - '0');
c = m_Line[++m_ColumnNo];
if (IsOctal(c)) {
n = (n << 3) + (c - '0');
m_ColumnNo++;
}
}
if (n > Defs.MAXCHAR) Error.IllegalCharacter(m_Line, c_cptr);
c = (char)n;
break;
case 'x':
c = m_Line[m_ColumnNo++];
n = HexVal(c);
if (n < 0 || n >= 16)
Error.IllegalCharacter(m_Line, c_cptr);
for (;;) {
c = m_Line[m_ColumnNo];
i = HexVal(c);
if (i < 0 || i >= 16) break;
m_ColumnNo++;
n = (n << 4) + i;
if (n > Defs.MAXCHAR) Error.IllegalCharacter(m_Line, c_cptr);
}
c = (char)n;
break;
case 'a': c = '\x7'; break;
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'v': c = '\v'; break;
}
}
cache.Append((char)c);
}
bp = LookupLiteralSymbol(cache.ToString());
return bp;
}
Symbol GetName()
{
int c;
StringBuilder cache = new StringBuilder();
for (c = m_Line[m_ColumnNo]; IsIdent(c); c = m_Line[++m_ColumnNo])
cache.Append((char)c);
if (IsReserved(cache.ToString())) Error.UsedReserved(cache.ToString());
return LookupSymbol(cache.ToString());
}
int GetNumber()
{
char c;
int n;
n = 0;
for (c = m_Line[m_ColumnNo]; Char.IsDigit(c); c = m_Line[++m_ColumnNo])
n = 10 * n + (c - '0');
if (m_ZeroBase)
return n + 1;
else
return n;
}
/** ats:
maintains tag_table with contents of < tag >.
extended to allow nested <> on the same line for use with Java/C# generics.
*/
string GetTag(bool emptyOk)
{
int c;
int i;
string s;
int t_lineno = Error.LineNo;
string t_line = DupLine();
int t_cptr = m_ColumnNo;
m_ColumnNo++;
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (emptyOk && c == '>') {
m_ColumnNo++; return null; // 0 indicates empty tag if emptyOk
}
if (!Char.IsLetter((char)c) && c != '_' && c != '$') // << or <. are not allowed
Error.IllegalTag(t_lineno, t_line, t_cptr);
StringBuilder cache = new StringBuilder();
/** ats: was
do { cachec(c); c = line[++cptr]; } while (Defs.IS_IDENT(c)); */
for (i = 0; ;) { // count <> nests
cache.Append((char)c);
switch (c = m_Line[++m_ColumnNo]) {
case '<': // nest
++i;
continue;
case '>': // unnest or exit loop
if (--i < 0) break;
continue;
case ' ':
case '?':
case '[':
case ']':
case ',': // extra characters for generics
if (i == 0) break; // but not at outer level
continue;
default: // alnum and . _ $ are ok.
if (!IsIdent(c)) break;
continue;
}
break;
}
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (c != '>')
Error.IllegalTag(t_lineno, t_line, t_cptr);
m_ColumnNo++;
for (i = 0; i < m_TagTable.Count; ++i) {
if (String.Compare(cache.ToString(), m_TagTable[i]) == 0)
return m_TagTable[i];
}
s = cache.ToString();
m_TagTable.Add(s);
return s;
}
void DeclareTokens(KeywordCode assoc)
{
int c;
Symbol bp;
int value;
string tag = null;
List<Symbol> symbols = new List<Symbol>();
List<int> values = new List<int>();
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (c == '<') {
tag = GetTag(false);
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
}
for (;;) {
if (Char.IsLetter((char)c) || c == '_' || c == '.' || c == '$')
bp = GetName();
else if (c == '\'' || c == '"')
bp = GetLiteral();
else
break;
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
value = bp.Value;
if (Char.IsDigit((char)c)) {
value = GetNumber();
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
}
symbols.Add(bp);
values.Add(value);
}
DeclareTokens(assoc, tag, symbols.ToArray(), values.ToArray());
}
void DeclareTypes()
{
int c;
Symbol bp;
string tag;
List<Symbol> symbols = new List<Symbol>();
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (c != '<') Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
tag = GetTag(false);
for (;;) {
c = Nextc();
if (Char.IsLetter((char)c) || c == '_' || c == '.' || c == '$')
bp = GetName();
else if (c == '\'' || c == '"')
bp = GetLiteral();
else
break;
symbols.Add(bp);
}
DeclareTypes(tag, symbols.ToArray());
}
void DeclareStart()
{
int c;
Symbol bp;
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (!Char.IsLetter((char)c) && c != '_' && c != '.' && c != '$')
Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
bp = GetName();
DeclareStart(bp);
}
protected override void DeclareTokens()
{
int c;
KeywordCode k;
StringBuilder cache = new StringBuilder();
for (;;) {
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (c != '%') Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
switch (k = Keyword()) {
case KeywordCode.MARK:
return;
case KeywordCode.TEXT:
CopyText(m_Output.PrologWriter);
break;
case KeywordCode.TOKEN:
case KeywordCode.LEFT:
case KeywordCode.RIGHT:
case KeywordCode.NONASSOC:
DeclareTokens(k);
break;
case KeywordCode.TYPE:
DeclareTypes();
break;
case KeywordCode.START:
DeclareStart();
break;
}
}
}
void AdvanceToStart()
{
int c;
Symbol bp;
int s_cptr;
int s_lineno;
for (;;) {
c = Nextc();
if (c != '%') break;
s_cptr = m_ColumnNo;
switch (Keyword()) {
case KeywordCode.MARK:
Error.NoGrammar();
break;
case KeywordCode.TEXT:
CopyText(m_Output.LocalWriter);
break;
case KeywordCode.START:
DeclareStart();
break;
default:
Error.SyntaxError(Error.LineNo, m_Line, s_cptr);
break;
}
}
c = Nextc();
if (!Char.IsLetter((char)c) && c != '_' && c != '.' && c != '_')
Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
bp = GetName();
s_lineno = Error.LineNo;
c = Nextc();
if (c == Defs.EOF) Error.UnexpectedEOF();
if (c != ':') Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
m_CurrentRule = DeclareRule(bp);
if (m_CurrentRule.Error)
Error.TerminalLhs(s_lineno);
m_ColumnNo++;
}
void AddSymbol()
{
int c;
Symbol bp;
int s_lineno = Error.LineNo;
c = m_Line[m_ColumnNo];
if (c == '\'' || c == '"')
bp = GetLiteral();
else
bp = GetName();
c = Nextc();
if (c == ':') {
m_CurrentRule.EndRule();
m_CurrentRule = DeclareRule(bp);
m_ColumnNo++;
return;
}
m_CurrentRule.AddSymbol(bp);
}
void CopyAction()
{
int c;
int i, n;
int depth;
int quote;
string tag;
int a_lineno = Error.LineNo;
string a_line = DupLine();
int a_cptr = m_ColumnNo;
StringBuilder f = new StringBuilder();
#if !OUTPUT_CODE
f.AppendFormat("case {0}:\n", Yacc.m_Rules.Count - (m_CurrentRule.LastWasAction ? 1 : 2));
f.AppendFormat(m_Output.LineFormat, Error.LineNo, Error.InputFileName);
#endif
f.Append(' '); f.Append(' ');
if (m_Line[m_ColumnNo] == '=') m_ColumnNo++;
n = 0;
for (i = Items.Count - 1; Items[i] != null; --i) ++n;
depth = 0;
loop:
c = m_Line[m_ColumnNo];
if (c == '$') {
if (m_Line[m_ColumnNo + 1] == '<') {
int d_lineno = Error.LineNo;
string d_line = DupLine();
int d_cptr = m_ColumnNo;
m_ColumnNo++;
tag = GetTag(true);
c = m_Line[m_ColumnNo];
if (c == '$') {
if (tag != null && String.Compare(tag, "Object") != 0)
#if !OUTPUT_CODE
f.AppendFormat("(({0})yyVal)", tag);
else f.Append("yyVal");
#else
f.AppendFormat("(({0})val)", tag);
else f.Append("val");
#endif
m_ColumnNo++;
goto loop;
}
else if (Char.IsDigit((char)c)) {
i = GetNumber();
if (i > n) Error.DollarWarning(d_lineno, i);
if (tag != null && String.Compare(tag, "Object") != 0)
#if !OUTPUT_CODE
f.AppendFormat("(({0})yyVals[{1}+yyTop])", tag, i - n);
else f.AppendFormat("yyVals[{0}+yyTop]", i - n);
#else
f.AppendFormat("(({0})vals[{1}])", tag, i - 1/* - n*/);
else f.AppendFormat("vals[{0}]", i - 1/* - n*/);
#endif
goto loop;
}
else if (c == '-' && Char.IsDigit(m_Line[m_ColumnNo + 1])) {
m_ColumnNo++;
#if !OUTPUT_CODE
i = -GetNumber() - n;
if (tag != null && String.Compare(tag, "Object") != 0)
f.AppendFormat("(({0})yyVals[{1}+yyTop])", tag, i);
else f.AppendFormat("yyVals[{0}+yyTop]", i); // etienne.cochard@ciel.com 3/5/04
#else
i = -GetNumber() - 1/* - n*/;
if (tag != null && String.Compare(tag, "Object") != 0)
f.AppendFormat("(({0})vals[{1}])", tag, i);
else f.AppendFormat("vals[{0}]", i); // etienne.cochard@ciel.com 3/5/04
#endif
goto loop;
}
else
Error.DollarError(d_lineno, d_line, d_cptr);
}
else if (m_Line[m_ColumnNo + 1] == '$') {
if (m_TagTable.Count != 0 && m_CurrentRule.Rule.Lhs.Tag == null)
Error.UntypedLhs();
#if !OUTPUT_CODE
f.Append("yyVal");
#else
f.Append("val");
#endif
m_ColumnNo += 2;
goto loop;
}
else if (Char.IsDigit(m_Line[m_ColumnNo + 1])) {
m_ColumnNo++;
i = GetNumber();
if (m_TagTable.Count != 0) {
if (i <= 0 || i > n)
Error.UnknownRhs(i);
tag = Items[Items.Count + i - n - 1].Tag;
if (tag == null) {
Error.UntypedRhs(i, Items[Items.Count + i - n - 1].Name);
#if !OUTPUT_CODE
f.AppendFormat("yyVals[{0}+yyTop]", i - n);
#else
f.AppendFormat("vals[{0}]", i - 1/* - n*/);
#endif
}
else if (String.Compare(tag, "Object") != 0)
#if !OUTPUT_CODE
f.AppendFormat("(({0})yyVals[{1}+yyTop])", tag, i - n);
#else
f.AppendFormat("(({0})vals[{1}])", tag, i - 1/* - n*/);
#endif
else
#if !OUTPUT_CODE
f.AppendFormat("yyVals[{0}+yyTop]", i - n);
#else
f.AppendFormat("vals[{0}]", i - 1/* - n*/);
#endif
}
else {
if (i > n)
Error.DollarWarning(Error.LineNo, i);
#if !OUTPUT_CODE
f.AppendFormat("yyVals[{0}+yyTop]", i - n);
#else
f.AppendFormat("vals[{0}]", i - 1/* - n*/);
#endif
}
goto loop;
}
else if (m_Line[m_ColumnNo + 1] == '-') {
m_ColumnNo += 2;
i = GetNumber();
if (m_TagTable.Count != 0)
Error.UnknownRhs(-i);
#if !OUTPUT_CODE
f.AppendFormat("yyVals[{0}+yyTop]", -i - n);
#else
f.AppendFormat("vals[{0}]", -i - 1/* - n*/);
#endif
goto loop;
}
}
if (Char.IsLetter((char)c) || c == '_' || c == '$') {
do {
f.Append((char)c);
c = m_Line[++m_ColumnNo];
} while (Char.IsLetterOrDigit((char)c) || c == '_' || c == '$');
goto loop;
}
f.Append((char)c);
m_ColumnNo++;
switch (c) {
case '\n':
next_line:
GetLine();
if (m_Line != null) goto loop;
Error.UnterminatedAction(a_lineno, a_line, a_cptr);
break;
case ';':
if (depth > 0) goto loop;
#if !OUTPUT_CODE
f.Append("\nbreak;\n");
#endif
goto epilog;
case '{':
++depth;
goto loop;
case '}':
if (--depth > 0) goto loop;
#if !OUTPUT_CODE
f.Append("\n break;\n");
#endif
goto epilog;
case '\'':
case '"': {
int s_lineno = Error.LineNo;
string s_line = DupLine();
int s_cptr = m_ColumnNo - 1;
quote = c;
for (;;) {
c = m_Line[m_ColumnNo++];
f.Append((char)c);
if (c == quote) {
goto loop;
}
if (c == '\n')
Error.UnterminatedString(s_lineno, s_line, s_cptr);
if (c == '\\') {
c = m_Line[m_ColumnNo++];
f.Append((char)c);
if (c == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedString(s_lineno, s_line, s_cptr);
}
}
}
}
case '/':
c = m_Line[m_ColumnNo];
if (c == '/') {
f.Append('*');
while ((c = m_Line[++m_ColumnNo]) != '\n') {
if (c == '*' && m_Line[m_ColumnNo + 1] == '/')
f.Append("* ");
else
f.Append((char)c);
}
f.Append("*/\n");
goto next_line;
}
if (c == '*') {
int c_lineno = Error.LineNo;
string c_line = DupLine();
int c_cptr = m_ColumnNo - 1;
f.Append('*');
m_ColumnNo++;
for (;;) {
c = m_Line[m_ColumnNo++];
f.Append((char)c);
if (c == '*' && m_Line[m_ColumnNo] == '/') {
f.Append('/');
m_ColumnNo++;
goto loop;
}
if (c == '\n') {
GetLine();
if (m_Line == null)
Error.UnterminatedComment(c_lineno, c_line, c_cptr);
}
}
}
goto loop;
default:
goto loop;
}
epilog:
m_CurrentRule.AddAction(f.ToString());
}
bool MarkSymbol()
{
int c;
Symbol bp;
c = m_Line[m_ColumnNo + 1];
if (c == '%' || c == '\\') {
m_ColumnNo += 2;
return true;
}
if (c == '=')
m_ColumnNo += 2;
else if ((c == 'p' || c == 'P') &&
((c = m_Line[m_ColumnNo + 2]) == 'r' || c == 'R') &&
((c = m_Line[m_ColumnNo + 3]) == 'e' || c == 'E') &&
((c = m_Line[m_ColumnNo + 4]) == 'c' || c == 'C')) {
if (!IsIdent(c = m_Line[m_ColumnNo + 5]))
m_ColumnNo += 5;
}
else
Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
c = Nextc();
if (Char.IsLetter((char)c) || c == '_' || c == '.' || c == '$')
bp = GetName();
else if (c == '\'' || c == '"')
bp = GetLiteral();
else {
Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
/*NOTREACHED*/
bp = null;
}
m_CurrentRule.MarkSymbol(bp);
return false;
}
protected override void DeclareGrammar()
{
int c;
AdvanceToStart();
for (;;) {
c = Nextc();
if (c == Defs.EOF) break;
if (Char.IsLetter((char)c) || c == '_' || c == '.' || c == '$' || c == '\'' ||
c == '"')
AddSymbol();
else if (c == '{' || c == '=')
CopyAction();
else if (c == '|') {
m_CurrentRule.EndRule();
m_CurrentRule.StartRule();
m_ColumnNo++;
}
else if (c == '%') {
if (MarkSymbol()) break;
}
else
Error.SyntaxError(Error.LineNo, m_Line, m_ColumnNo);
}
m_CurrentRule.EndRule();
CopyEpilog(m_Output.EpilogWriter);
}
void CopyEpilog(TextWriter f)
{
int c, last;
TextReader In;
if (m_Line == null)
return;
In = m_InputFile;
c = m_Line[m_ColumnNo];
if (c == '\n') {
++Error.LineNo;
if ((c = In.Read()) == Defs.EOF)
return;
f.Write(m_Output.LineFormat, Error.LineNo, Error.InputFileName);
f.Write((char)c);
last = c;
}
else {
f.Write(m_Output.LineFormat, Error.LineNo, Error.InputFileName);
do { f.Write((char)c); } while ((c = m_Line[++m_ColumnNo]) != '\n');
f.Write("\n ");
last = '\n';
}
while ((c = In.Read()) != Defs.EOF) {
f.Write((char)c);
last = c;
}
if (last != '\n') {
f.Write("\n ");
}
}
}
}
|
namespace Sys.Workflow.Engine.Impl.Bpmn.Helper
{
using Sys.Workflow.Engine.Impl.Persistence.Entity;
///
public class SubProcessVariableSnapshotter
{
public virtual void SetVariablesSnapshots(IExecutionEntity sourceExecution, IExecutionEntity snapshotHolder)
{
snapshotHolder.VariablesLocal = sourceExecution.VariablesLocal;
IExecutionEntity parentExecution = sourceExecution.Parent;
if (parentExecution != null && parentExecution.IsMultiInstanceRoot)
{
snapshotHolder.VariablesLocal = parentExecution.VariablesLocal;
}
}
}
} |
#region
using LoESoft.GameServer.realm;
using log4net;
using System;
#endregion
namespace LoESoft.GameServer.logic
{
public abstract class Behavior : IStateChildren
{
public static ILog log = LogManager.GetLogger(nameof(Behavior));
/// <summary>
/// Enable debug log
/// </summary>
public static readonly bool debug = false;
[ThreadStatic]
private static Random rand;
protected static Random Random
{
get
{
if (rand == null)
rand = new Random();
return rand;
}
}
public void Tick(Entity host, RealmTime time)
{
if (!host.StoredBehaviors.TryGetValue(this, out object state))
state = null;
try
{
TickCore(host, time, ref state);
if (state == null)
host.StoredBehaviors.Remove(this);
else
host.StoredBehaviors[this] = state;
}
catch (Exception) { }
}
protected abstract void TickCore(Entity host, RealmTime time, ref object state);
public void OnStateEntry(Entity host, RealmTime time)
{
if (!host.StoredBehaviors.TryGetValue(this, out object state))
state = null;
OnStateEntry(host, time, ref state);
if (state == null)
host.StoredBehaviors.Remove(this);
else
host.StoredBehaviors[this] = state;
}
protected virtual void OnStateEntry(Entity host, RealmTime time, ref object state)
{
}
public void OnStateExit(Entity host, RealmTime time)
{
if (!host.StoredBehaviors.TryGetValue(this, out object state))
state = null;
OnStateExit(host, time, ref state);
if (state == null)
host.StoredBehaviors.Remove(this);
else
host.StoredBehaviors[this] = state;
}
protected virtual void OnStateExit(Entity host, RealmTime time, ref object state)
{
}
protected internal virtual void Resolve(State parent)
{
}
}
} |
using System.Runtime.Serialization;
namespace EzTextingApiClient.Api.Inbox.Model
{
public enum MessageType
{
[EnumMember(Value = "SMS")] Sms,
[EnumMember(Value = "MMS")] Mms
}
} |
@model IEnumerable<DapperSampleWeb.Models.UserFavoriteBookEntity>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Sample1</title>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>ユーザID</th>
<th>ユーザ名</th>
<th>書籍ID</th>
<th>書籍名</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.ID)</td>
<td>@Html.DisplayFor(modelItem => item.User.ID)</td>
<td>@Html.DisplayFor(modelItem => item.User.FirstName)</td>
<td>@Html.DisplayFor(modelItem => item.InterstBook.ID)</td>
<td>@Html.DisplayFor(modelItem => item.InterstBook.Name)</td>
</tr>
}
</table>
</body>
</html>
|
#Thu Jul 11 13:34:37 BST 2019
lib/com.ibm.ws.cdi.security_1.0.30.jar=16c784dbd801c18ff55f2447c7a0fcfe
lib/features/com.ibm.websphere.appserver.cdi1.2-appSecurity1.0.mf=080e420b6f1b0456414adcb5f34f5251
|
using Kaiyuanshe.OpenHackathon.Server.K8S.Models;
using Kaiyuanshe.OpenHackathon.Server.Storage.Entities;
using NUnit.Framework;
namespace Kaiyuanshe.OpenHackathon.ServerTests.K8S
{
class ExperimentContextTests
{
[Test]
public void BuildCustomResource()
{
var context = new ExperimentContext
{
ExperimentEntity = new ExperimentEntity
{
PartitionKey = "pk",
RowKey = "rk",
Paused = true,
TemplateName = "tpl",
UserId = "uid"
}
};
var cr = context.BuildCustomResource();
Assert.AreEqual("hackathon.kaiyuanshe.cn/v1", cr.ApiVersion);
Assert.AreEqual("Experiment", cr.Kind);
Assert.AreEqual("tpl-uid", cr.Metadata.Name);
Assert.AreEqual("default", cr.Metadata.NamespaceProperty);
Assert.AreEqual(3, cr.Metadata.Labels.Count);
Assert.AreEqual("pk", cr.Metadata.Labels["hackathonName"]);
Assert.AreEqual("uid", cr.Metadata.Labels["userId"]);
Assert.AreEqual("tpl", cr.Metadata.Labels["templateName"]);
Assert.AreEqual("meta-cluster", cr.Spec.ClusterName);
Assert.AreEqual("pk-tpl", cr.Spec.Template);
Assert.AreEqual(true, cr.Spec.Pause);
}
}
}
|
@{
ViewData["Title"] = "Password Reset";
}
@model ResetPasswordModel
<h1>Password Reset</h1>
@Html.ValidationSummary()
<form method="post">
<input type="hidden" asp-for="Code" />
<section class="myaccount-grid">
<div>
<label asp-for="EmailOrUsername"></label>
</div>
<div>
<input type="text" data-required data-email asp-for="EmailOrUsername" />
<div class="error-message"></div>
</div>
<div>
<label asp-for="Password"></label>
</div>
<div>
<input type="password" data-required asp-for="Password" />
<div class="error-message"></div>
</div>
<div>
<label asp-for="ConfirmPassword"></label>
</div>
<div>
<input type="password" data-required asp-for="ConfirmPassword" />
<div class="error-message"></div>
</div>
<div class="width-two">
<button type="submit">Reset Password</button>
</div>
</section>
</form>
@section Scripts {
<script src="~/js/dist/runtime.min.js"></script>
<script src="~/js/dist/aspnetcore_formvalidation.min.js"></script>
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.