content stringlengths 23 1.05M |
|---|
using System;
using System.Runtime.InteropServices;
namespace Windows.Win32.Interop
{
public class NativeArrayInfoAttribute : Attribute
{
//
// Summary:
// Indicates the number of elements in the fixed-length array or the number of characters
// (not bytes) in a string to import.
public int CountConst;
//
// Summary:
// Indicates the zero-based parameter that contains the count of array elements,
// similar to size_is in COM.
public short CountParamIndex;
public NativeArrayInfoAttribute()
{
}
}
}
|
using UnityEngine;
namespace tezcat.Framework.Game
{
public interface ITezHoverable
{
void onEnter(ref RaycastHit hit);
void onExit();
void onHovering(ref RaycastHit hit);
}
} |
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using LightDirectory.Asn1.Serialization;
using LightDirectory.Asn1.Suport;
namespace LightDirectory.Asn1.Universal.Serializers
{
public class Asn1BooleanSerializer : Asn1ObjectSerializer<Asn1Boolean>
{
public Asn1BooleanSerializer() : base(TagClass.Universal, (int) UniversalTags.Boolean){}
public override async Task<(Asn1Object, int)> Read(IAsn1Serializer serializer, Identifier id, int length,
Stream stream, CancellationToken cancellationToken)
{
var b = await stream.ReadBERByte(cancellationToken);
var val = (b != 0x00);
return (new Asn1Boolean(val),1);
}
public override async Task<int> Write(IAsn1Serializer serializer, Asn1Boolean item, Stream stream,
CancellationToken cancellationToken)
{
var boolean = (Asn1Boolean)item;
var identBytes = await SerializerUtility.WriteIdentifier(item.Id, stream, cancellationToken);
var buffer = new byte[] {1, boolean.Value?(byte)0xff :(byte) 0x00};
await stream.WriteBERBytes(buffer, cancellationToken: cancellationToken);
return identBytes + buffer.Length;
}
}
}
|
// Copyright (c) 2012, Joshua Burke
// All rights reserved.
//
// See LICENSE for more information.
using System;
using System.IO;
using System.Diagnostics.Contracts;
using Frost.Surfacing.Contracts;
namespace Frost.Surfacing
{
namespace Contracts
{
[ContractClassFor(typeof(ISurface2D))]
internal abstract class ISurface2DContract : ISurface2D
{
public Device2D Device2D
{
get
{
Contract.Ensures(Contract.Result<Device2D>() != null);
throw new NotSupportedException();
}
}
public abstract SurfaceUsage Usage { get; }
public abstract Rectangle Region { get; }
public void DumpToPNG(Stream stream)
{
Contract.Requires(stream != null);
}
public void CopyTo(
Rectangle srcRegion, ISurface2D destination, Point dstLocation)
{
Contract.Requires(destination != null);
}
public abstract void AcquireLock();
public abstract void ReleaseLock();
public abstract Guid Id { get; }
}
}
[ContractClass(typeof(ISurface2DContract))]
public interface ISurface2D
{
Device2D Device2D { get; }
SurfaceUsage Usage { get; }
Rectangle Region { get; }
Guid Id { get; }
void DumpToPNG(Stream stream);
void CopyTo(Rectangle srcRegion, ISurface2D destination, Point dstLocation);
void AcquireLock();
void ReleaseLock();
}
} |
using System;
namespace HackerRank
{
/// <summary>
/// Problem link: https://www.hackerrank.com/challenges/sock-merchant
/// </summary>
class SockMerchant
{
public static void Main()
{
Console.ReadLine();
int[] c = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
var result = CalculateNumberOfMatchingPairs(c);
Console.WriteLine(result);
}
static int CalculateNumberOfMatchingPairs(int[] socks)
{
var colors = new int[100];
foreach (var sock in socks)
{
colors[sock-1]++;
}
var totalOfPairs = 0;
foreach (var item in colors)
{
totalOfPairs += item / 2;
}
return totalOfPairs;
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using Paramore.Darker.Builder;
namespace Paramore.Darker.AspNetCore
{
public interface IQueryProcessorAspNetExtensionBuilder : IQueryProcessorExtensionBuilder
{
IServiceCollection Services { get; }
}
} |
namespace DanubeJourney.Web.ViewModels.Employees
{
using System;
using DanubeJourney.Data.Models;
using DanubeJourney.Services.Mapping;
public class EmployeeViewModel : IMapFrom<Employee>
{
public string Id { get; set; }
public string Avatar { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBird { get; set; }
public string Profession { get; set; }
public int Experience { get; set; }
public decimal Salary { get; set; }
}
}
|
using Computer.Bus.RabbitMq.Contracts;
namespace Computer.Bus.ProtobuffNet.Model;
internal class SerializationResult<T> : ISerializationResult<T>
{
public T? Param { get; }
public bool Success { get; }
public string? Reason { get; }
private SerializationResult(T? param, bool success, string? reason = null)
{
Param = param;
Success = success;
Reason = reason;
}
public static SerializationResult<T> CreateSuccess(T param)
{
return new SerializationResult<T>(param, true);
}
public static SerializationResult<T> CreateError(string reason)
{
return new SerializationResult<T>(default, false, reason);
}
} |
using System;
using System.Collections.Generic;
using OfficeRibbonXEditor.Helpers;
namespace OfficeRibbonXEditor.Events
{
public class ReplaceResultsEventArgs : EventArgs
{
public ReplaceResultsEventArgs(FindReplace findReplace, List<CharacterRange> replaceAllResults)
{
this.FindReplace = findReplace;
this.ReplaceAllResults = replaceAllResults ?? new List<CharacterRange>();
}
public FindReplace FindReplace { get; set; }
public List<CharacterRange> ReplaceAllResults { get; }
}
}
|
using System;
using System.Collections.Generic;
public class ListTabsModule : global::UIModule
{
public void Setup(global::System.Action<int> tabChanged, int current)
{
this.tabChangedCallback = tabChanged;
for (int i = 0; i < this.tabs.Count; i++)
{
int index = i;
this.tabs[i].onAction.AddListener(delegate()
{
this.OnTabChanged(index);
});
}
this.OnTabChanged(current);
}
private void OnTabChanged(int index)
{
this.currentTab = index;
this.tabChangedCallback(index);
}
public void Next()
{
this.currentTab = ((this.currentTab + 1 < this.tabs.Count) ? (this.currentTab + 1) : 0);
if (!this.tabs[this.currentTab].isActiveAndEnabled)
{
this.Next();
}
else
{
this.tabs[this.currentTab].SetOn();
this.tabChangedCallback(this.currentTab);
}
}
public void Prev()
{
this.currentTab = ((this.currentTab - 1 < 0) ? (this.tabs.Count - 1) : (this.currentTab - 1));
if (!this.tabs[this.currentTab].isActiveAndEnabled)
{
this.Prev();
}
else
{
this.tabs[this.currentTab].SetOn();
this.tabChangedCallback(this.currentTab);
}
}
public global::System.Collections.Generic.List<global::ToggleEffects> tabs;
private global::System.Action<int> tabChangedCallback;
public int currentTab;
}
|
using GenderPayGap.Database;
using GovUkDesignSystem;
using GovUkDesignSystem.Attributes;
using GovUkDesignSystem.Attributes.ValidationAttributes;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace GenderPayGap.WebUI.Models.Admin
{
public class ChangeOrganisationAddressViewModel : GovUkViewModel
{
[BindNever /* Output Only - only used for sending data from the Controller to the View */]
public Database.Organisation Organisation { get; set; }
public ManuallyChangeOrganisationAddressViewModelActions Action { get; set; }
#region Used by Manual Change page
public string PoBox { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string TownCity { get; set; }
public string County { get; set; }
public string Country { get; set; }
public string PostCode { get; set; }
[GovUkValidateRequired(ErrorMessageIfMissing = "Select whether or not this is a UK address")]
public ManuallyChangeOrganisationAddressIsUkAddress? IsUkAddress { get; set; }
public void PopulateFromOrganisationAddress(OrganisationAddress address)
{
PoBox = address?.PoBox;
Address1 = address?.Address1;
Address2 = address?.Address2;
Address3 = address?.Address3;
TownCity = address?.TownCity;
County = address?.County;
Country = address?.Country;
PostCode = address?.GetPostCodeInAllCaps();
if (address?.IsUkAddress != null)
{
IsUkAddress = address.IsUkAddress.Value
? ManuallyChangeOrganisationAddressIsUkAddress.Yes
: ManuallyChangeOrganisationAddressIsUkAddress.No;
}
}
#endregion
[GovUkValidateRequired(ErrorMessageIfMissing =
"Select whether you want to use this address from Companies House or to enter an address manually")]
public AcceptCompaniesHouseAddress? AcceptCompaniesHouseAddress { get; set; }
[GovUkValidateRequired(ErrorMessageIfMissing = "Please enter a reason for this change.")]
public string Reason { get; set; }
}
public enum ManuallyChangeOrganisationAddressIsUkAddress
{
Yes,
No
}
public enum AcceptCompaniesHouseAddress
{
[GovUkRadioCheckboxLabelText(Text = "Yes, use this address from Companies House")]
Accept,
[GovUkRadioCheckboxLabelText(Text = "No, enter an address manually")]
Reject
}
public enum ManuallyChangeOrganisationAddressViewModelActions
{
Unknown = 0,
OfferNewCompaniesHouseAddress = 1,
ManualChange = 2,
CheckChangesManual = 3,
CheckChangesCoHo = 4
}
}
|
namespace BonusCalcListener
{
public static class EventTypes
{
// Define the event types this service will be interested in here.
public const string DoSomethingEvent = "DoSomethingEvent";
}
}
|
using System.IO;
using Microsoft.Xna.Framework.Audio;
using StardewModdingAPI;
using StardewValley;
namespace SimpleSoundManager
{
public class XACTMusicPair
{
public WaveBank waveBank;
public ISoundBank soundBank;
/// <summary>Create a xwb and xsb music pack pair.</summary>
/// <param name="helper">The mod helper from the mod that will handle loading in the file.</param>
/// <param name="wavBankPath">A relative path to the .xwb file in the mod helper's mod directory.</param>
/// <param name="soundBankPath">A relative path to the .xsb file in the mod helper's mod directory.</param>
public XACTMusicPair(IModHelper helper, string wavBankPath, string soundBankPath)
{
wavBankPath = Path.Combine(helper.DirectoryPath, wavBankPath);
soundBankPath = Path.Combine(helper.DirectoryPath, soundBankPath);
this.waveBank = new WaveBank(Game1.audioEngine.Engine, wavBankPath);
this.soundBank = new SoundBankWrapper(new SoundBank(Game1.audioEngine.Engine, soundBankPath));
}
}
}
|
namespace XnaFlash.Swf.Structures.Filters
{
public class BlurFilter : Filter
{
public override Filter.ID FilterID { get { return ID.Blur; } }
public decimal BlurX { get; private set; }
public decimal BlurY { get; private set; }
public byte Passes { get; private set; }
public BlurFilter(SwfStream stream)
{
BlurX = stream.ReadFixed();
BlurY = stream.ReadFixed();
Passes = (byte)(stream.ReadByte() >> 3);
}
}
}
|
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
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.Diagnostics;
using System.Linq;
namespace Tensorflow.Contexts
{
/// <summary>
/// Environment in which eager operations execute.
/// </summary>
public sealed partial class Context
{
public ConfigProto Config { get; set; } = new ConfigProto
{
GpuOptions = new GPUOptions
{
}
};
ConfigProto MergeConfig()
{
Config.LogDevicePlacement = _log_device_placement;
// var gpu_options = _compute_gpu_options();
// Config.GpuOptions.AllowGrowth = gpu_options.AllowGrowth;
return Config;
}
GPUOptions _compute_gpu_options()
{
// By default, TensorFlow maps nearly all of the GPU memory of all GPUs
// https://www.tensorflow.org/guide/gpu
return new GPUOptions()
{
AllowGrowth = get_memory_growth("GPU")
};
}
}
}
|
using System;
using Humanizer.Localisation;
using Xunit;
using Xunit.Extensions;
namespace Humanizer.Tests.Localisation.it
{
public class DateHumanizeTests : AmbientCulture
{
public DateHumanizeTests()
: base("it")
{
}
[Theory]
[InlineData(-2, "2 giorni fa")]
[InlineData(-1, "ieri")]
public void DaysAgo(int days, string expected)
{
DateHumanize.Verify(expected, days, TimeUnit.Day, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 giorni")]
[InlineData(1, "domani")]
public void DaysFromNow(int days, string expected)
{
DateHumanize.Verify(expected, days, TimeUnit.Day, Tense.Future);
}
[Theory]
[InlineData(-2, "2 ore fa")]
[InlineData(-1, "un'ora fa")]
public void HoursAgo(int hours, string expected)
{
DateHumanize.Verify(expected, hours, TimeUnit.Hour, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 ore")]
[InlineData(1, "tra un'ora")]
public void HoursFromNow(int hours, string expected)
{
DateHumanize.Verify(expected, hours, TimeUnit.Hour, Tense.Future);
}
[Theory]
[InlineData(-2, "2 minuti fa")]
[InlineData(-1, "un minuto fa")]
[InlineData(60, "un'ora fa")]
public void MinutesAgo(int minutes, string expected)
{
DateHumanize.Verify(expected, minutes, TimeUnit.Minute, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 minuti")]
[InlineData(1, "tra un minuto")]
public void MinutesFromNow(int minutes, string expected)
{
DateHumanize.Verify(expected, minutes, TimeUnit.Minute, Tense.Future);
}
[Theory]
[InlineData(-2, "2 mesi fa")]
[InlineData(-1, "un mese fa")]
public void MonthsAgo(int months, string expected)
{
DateHumanize.Verify(expected, months, TimeUnit.Month, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 mesi")]
[InlineData(1, "tra un mese")]
public void MonthsFromNow(int months, string expected)
{
DateHumanize.Verify(expected, months, TimeUnit.Month, Tense.Future);
}
[Theory]
[InlineData(-2, "2 secondi fa")]
[InlineData(-1, "un secondo fa")]
public void SecondsAgo(int seconds, string expected)
{
DateHumanize.Verify(expected, seconds, TimeUnit.Second, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 secondi")]
[InlineData(1, "tra un secondo")]
public void SecondsFromNow(int seconds, string expected)
{
DateHumanize.Verify(expected, seconds, TimeUnit.Second, Tense.Future);
}
[Theory]
[InlineData(-2, "2 anni fa")]
[InlineData(-1, "un anno fa")]
public void YearsAgo(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Past);
}
[Theory]
[InlineData(2, "tra 2 anni")]
[InlineData(1, "tra un anno")]
public void YearsFromNow(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Future);
}
[Theory]
[InlineData(0, "adesso")]
public void Now(int years, string expected)
{
DateHumanize.Verify(expected, years, TimeUnit.Year, Tense.Future);
}
}
}
|
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.ComponentModel.Composition;
namespace Sce.Atf
{
/// <summary>
/// A service to log unhandled exceptions (crashes) to a remote server, by listening
/// to the AppDomain.CurrentDomain.UnhandledException event</summary>
/// <remarks>Default server's web UI: https://sd-cdump-dev002.share.scea.com/recap/.
/// If used with Sce.Atf.Applications.UnhandledExceptionService, put CrashLogger before
/// UnhandledExceptionService in the TypeCatalog, because otherwise UnhandledExceptionService
/// can prevent CrashLogger from receiving events, but CrashLogger does not prevent
/// UnhandledExceptionService from receiving events.</remarks>
[Export(typeof(IInitializable))]
[Export(typeof(ICrashLogger))]
[Export(typeof(CrashLogger))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class CrashLogger : ServerLogger, ICrashLogger, IInitializable
{
#region IInitializable Members
/// <summary>
/// Finishes initializing component by creating CrashReporter</summary>
public void Initialize()
{
m_crashHandler = new Scea.CrashReporter(GetConnection());
m_crashHandler.Enable();
}
#endregion
#region ICrashLogger Members
/// <summary>
/// Logs the given exception to the remote server</summary>
/// <param name="e">Exception</param>
public virtual void LogException(Exception e)
{
m_crashHandler.CrashHandler(e);
}
#endregion
private Scea.CrashReporter m_crashHandler;
}
}
|
using System;
using System.ComponentModel;
namespace PublishingUtility
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class SRDescriptionAttribute : DescriptionAttribute
{
private bool _localized;
public override string Description
{
get
{
if (!_localized)
{
_localized = true;
base.DescriptionValue = SR.GetString(base.DescriptionValue);
}
return base.Description;
}
}
public SRDescriptionAttribute(string text)
: base(text)
{
_localized = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ITVComponents.UserInterface
{
/// <summary>
/// Provides Methods to control the main-application of an ITVUserInterface - App
/// </summary>
public interface IUIApp
{
/// <summary>
/// Gets or sets a value indicating whether to automatically exit an application
/// </summary>
bool AutoShutdown { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to currently display the main-ui
/// </summary>
bool ShowMainWindow { get; set; }
/// <summary>
/// Shuts down the application
/// </summary>
void ExitApplication();
}
}
|
/////////////////////////////////////////////////////////////////////////
// Server.cs - CommService server //
// ver 2.4 //
// Author: Ayush Khemka, 538044584, aykhemka@syr.edu //
// Source: Jim Fawcett, CSE681 - Software Modeling and Analysis, Project #4 //
/////////////////////////////////////////////////////////////////////////
/*
* Additions to C# Console Wizard generated code:
* - Added reference to ICommService, Sender, Receiver, Utilities
*
* Note:
* - This server now receives and then sends back received messages.
*/
/*
* Plans:
* - Add message decoding and NoSqlDb calls in performanceServiceAction.
* - Provide requirements testing in requirementsServiceAction, perhaps
* used in a console client application separate from Performance
* Testing GUI.
*/
/*
* Maintenance History:
* --------------------
* ver 2.4 : 23 Nov 2015
* - added the functionalities to take requests from clients and
* pass it on to the correct parser based on where it came from
* - record the times to process each type of request, required
* for stress testing the server
* - send performance results to WPF client when requested
* - final release
* ver 2.3 : 29 Oct 2015
* - added handling of special messages:
* "connection start message", "done", "closeServer"
* ver 2.2 : 25 Oct 2015
* - minor changes to display
* ver 2.1 : 24 Oct 2015
* - added Sender so Server can echo back messages it receives
* - added verbose mode to support debugging and learning
* - to see more detail about what is going on in Sender and Receiver
* set Utilities.verbose = true
* ver 2.0 : 20 Oct 2015
* - Defined Receiver and used that to replace almost all of the
* original Server's functionality.
* ver 1.0 : 18 Oct 2015
* - first release
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Project2;
namespace Project4
{
using Util = Utilities;
class Server
{
string address { get; set; } = "localhost";
string port { get; set; } = "8080";
//----< quick way to grab ports and addresses from commandline >-----
public void ProcessCommandLine(string[] args)
{
if (args.Length > 0)
{
port = args[0];
}
if (args.Length > 1)
{
address = args[1];
}
}
static void Main(string[] args)
{
RequestEngine re = new RequestEngine();
QueryRequestEngine qre = new QueryRequestEngine();
DBEngine<string, DBElement<string, List<string>>> db = new DBEngine<string, DBElement<string, List<string>>>();
Util.verbose = false;
Server srvr = new Server();
srvr.ProcessCommandLine(args);
Console.Title = "Server";
Console.Write(String.Format("\n Starting CommService server listening on port {0}", srvr.port));
Console.Write("\n ====================================================\n");
Sender sndr = new Sender(Util.makeUrl(srvr.address, srvr.port));
//Sender sndr = new Sender();
Receiver rcvr = new Receiver(srvr.port, srvr.address);
// - serviceAction defines what the server does with received messages
// - This serviceAction just announces incoming messages and echos them
// back to the sender.
// - Note that demonstrates sender routing works if you run more than
// one client.
HiResTimer hrt = new HiResTimer();
PerfTest pt = new PerfTest();
Action serviceAction = () =>
{
Message msg = null;
while (true)
{
msg = rcvr.getMessage(); // note use of non-service method to deQ messages
//insert();
int length = msg.content.IndexOf(",") + 1;
string from = "";
if (msg.content != "connection start message")
from = msg.content.Substring(0, length); //figure out where the request came from
string[] msgList=msg.content.Split(',');
Console.Write("\n Received message:");
Console.Write("\n Request type is: {0}", from); //denotes where the request came from
Console.Write("\n sender is {0}", msg.fromUrl);
Console.Write("\n content is {0}\n", msg.content);
string reply="";
//------------< do processing based on the request type >------------
if (from == "write,")
{
hrt.Start();
re.parseRequest(msg.content, out reply);
hrt.Stop();
pt.add(msgList[1], hrt.ElapsedMicroseconds);
msg.content=reply;
}
else if (from == "read,")
{
hrt.Start();
db = re.getDB();
qre.parseRequest(db, msg.content, out reply);
hrt.Stop();
pt.add(msgList[1], hrt.ElapsedMicroseconds);
msg.content = reply;
}
else if (from == "perf,")
{
reply = pt.printTimesWpf(msgList[1]);
msg.content = reply;
}
if (msg.content == "connection start message")
{
continue; // don't send back start message
}
if (msg.content == "done")
{
Console.Write("\n client has finished\n");
Console.WriteLine(pt.printTimes());
continue;
}
if (msg.content == "closeServer")
{
Console.Write("received closeServer");
break;
}
// swap urls for outgoing message
Util.swapUrls(ref msg);
#if (TEST_WPFCLIENT)
/////////////////////////////////////////////////
// The statements below support testing the
// WpfClient as it receives a stream of messages
// - for each message received the Server
// sends back 1000 messages
// Use the code to test the server
/*int count = 0;
for (int i = 0; i < 1000; ++i)
{
Message testMsg = new Message();
testMsg.toUrl = msg.toUrl;
testMsg.fromUrl = msg.fromUrl;
testMsg.content = String.Format("test message #{0}", ++count);
Console.Write("\n sending testMsg: {0}", testMsg.content);
sndr.sendMessage(testMsg);
}*/
Message testMsg = new Message();
testMsg.toUrl = msg.toUrl;
testMsg.fromUrl = msg.fromUrl;
testMsg.content = String.Format("test message");
Console.Write("\n sending testMsg: {0}", testMsg.content);
sndr.sendMessage(testMsg);
#else
/////////////////////////////////////////////////
// Use the statement below for normal operation
sndr.sendMessage(msg);
//re.db.show<string, DBElement<string, List<string>>, List<string>, string>();
#endif
}
};
if (rcvr.StartService())
{
rcvr.doService(serviceAction); // This serviceAction is asynchronous,
} // so the call doesn't block.
Util.waitForUser();
}
}
} |
using System.Linq;
using CqrsPattern.Actions;
using CqrsPattern.Domain;
using CqrsPattern.Infrastructure;
namespace CqrsPattern.Handlers
{
public class CommandHandler
{
private Db _db;
public CommandHandler(Db db)
{
_db = db;
}
public void Handle(AddCustomerCommand cmd)
{
// Does not account for duplicates
_db.Customers.Add(new Customer { Id = cmd.Id, Name = cmd.Name });
}
public void Handle(RemoveCustomerCommand cmd)
{
var customer = _db.Customers.FirstOrDefault(c => c.Id == cmd.Id);
if (customer != null)
{
_db.Customers.Remove(customer);
}
}
}
}
|
using Microsoft.Xna.Framework.Graphics;
namespace Pong.Objects
{
public class GameCage
{
public Wall UpperWall { get; set; }
public Wall LowerWall { get; set; }
public Wall LeftWall { get; set; }
public Wall RightWall { get; set; }
public void Draw(SpriteBatch spriteBatch)
{
UpperWall?.Draw(spriteBatch);
LowerWall?.Draw(spriteBatch);
LeftWall?.Draw(spriteBatch);
RightWall?.Draw(spriteBatch);
}
}
} |
using Newtonsoft.Json;
namespace LocaHealthLog.Plotly
{
[JsonConverter(typeof(AxisTypeJsonConverter))]
enum AxisType
{
Category,
Date,
Linear,
Log,
None
}
}
|
using System;
namespace Scenario.Domain.Services.ScenarioManagement
{
public class ScenarioCreateService : IScenarioCreateService
{
public ScenarioCreateService()
{
}
}
}
|
using WarHub.ArmouryModel.Concrete;
using WarHub.ArmouryModel.Source;
namespace WarHub.ArmouryModel.EditorServices;
/// <summary>
/// Represents a point-in-time roster together with dataset used to create the roster and roster diagnostics.
/// Diagnostics will contain warnings and errors to show to the user.
/// </summary>
public record RosterState(Compilation Compilation)
{
public GamesystemNode Gamesystem => Compilation.GlobalNamespace.RootCatalogue.GetGamesystemDeclaration()
?? throw new InvalidOperationException();
public ImmutableArray<CatalogueNode> Catalogues =>
Compilation.GlobalNamespace.Catalogues.Where(x => !x.IsGamesystem)
.Select(x => x.GetCatalogueDeclaration() ?? throw new InvalidOperationException())
.ToImmutableArray();
public RosterNode? Roster => Compilation.GlobalNamespace.Rosters.SingleOrDefault()?.GetDeclaration();
public RosterNode RosterRequired => Roster ?? throw new InvalidOperationException();
public static RosterState CreateFromNodes(params SourceNode[] rootNodes)
=> new(WhamCompilation.Create(rootNodes.Select(SourceTree.CreateForRoot).ToImmutableArray()));
public static RosterState CreateFromNodes(IEnumerable<SourceNode> rootNodes)
=> new(WhamCompilation.Create(rootNodes.Select(SourceTree.CreateForRoot).ToImmutableArray()));
public RosterState ReplaceRoster(RosterNode node)
{
var oldTree = RosterRequired.GetSourceTree(Compilation);
var newTree = oldTree.WithRoot(node);
return new(Compilation.ReplaceSourceTree(oldTree, newTree));
}
}
|
using System;
using SimpleCommandParser.Core.Initializer;
using SimpleCommandParser.Core.Settings;
using SimpleCommandParser.Core.StageResults;
namespace SimpleCommandParser.Examples.ExtendParser
{
public class CustomCommandInitializer : ICommandInitializer
{
private readonly ICommandInitializer _sourceInitializer;
public CustomCommandInitializer(Func<ICommandParserSettings> settingsProvider)
{
_sourceInitializer = new ParameterAttributeBasedCommandInitializer(settingsProvider);
}
public CommandInitializationStageResult Initialize(ICommandInitializationRequest request)
{
return _sourceInitializer.Initialize(request);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _08.GreaterOfTwoValues
{
class GreaterOfTwoValues
{
static void Main()
{
string input = Console.ReadLine().ToLower();
string first = Console.ReadLine();
string second = Console.ReadLine();
if (input == "int")
{
int firstNum = int.Parse(first);
int secondNum = int.Parse(second);
int result = GetMaxInt(firstNum, secondNum);
Console.WriteLine(result);
}
else if (input == "char")
{
char firstChar = char.Parse(first);
char secondChar = char.Parse(second);
char result = GetMaxChar(firstChar, secondChar);
Console.WriteLine(result);
}
else
{
string result = GetMaxString(first, second);
Console.WriteLine(result);
}
}
private static int GetMaxInt(int firstNum, int secondNum)
{
if (firstNum >= secondNum)
{
return firstNum;
}
return secondNum;
}
private static char GetMaxChar(char firstChar, char secondChar)
{
if (firstChar >= secondChar)
{
return firstChar;
}
return secondChar;
}
private static string GetMaxString(string first, string second)
{
if (first.CompareTo(second) >= 0)
{
return first;
}
return second;
}
}
}
|
using VA = VisioAutomation;
using SMA = System.Management.Automation;
using IVisio = Microsoft.Office.Interop.Visio;
namespace VisioPowerShell.Commands
{
[SMA.Cmdlet(SMA.VerbsCommon.Set, "VisioDocument")]
public class Set_VisioDocument : VisioCmdlet
{
[SMA.Parameter(Position = 0, Mandatory = true, ParameterSetName = "Name")]
[SMA.ValidateNotNullOrEmpty]
public string Name { get; set; }
[SMA.Parameter(Position = 0, Mandatory = true, ParameterSetName = "Doc")]
[SMA.ValidateNotNull]
public IVisio.Document Document { get; set; }
protected override void ProcessRecord()
{
if (this.Name != null)
{
this.client.Document.Activate(this.Name);
}
else if (this.Document != null)
{
this.client.Document.Activate(this.Document);
}
}
}
} |
using BannerKings.Managers.Titles;
using TaleWorlds.CampaignSystem;
using TaleWorlds.SaveSystem;
using static BannerKings.Managers.TitleManager;
namespace BannerKings.Managers.Duties
{
public abstract class BannerKingsDuty
{
[SaveableProperty(1)]
public float Completion { get; private set; }
[SaveableProperty(2)]
public CampaignTime DueTime { get; protected set; }
[SaveableProperty(3)]
public FeudalDuties Type { get; private set; }
public BannerKingsDuty(CampaignTime dueTime, FeudalDuties type, float completion = 0f)
{
this.Completion = completion;
this.DueTime = dueTime;
this.Type = type;
}
public abstract void Tick();
public abstract void Finish();
}
}
|
using System;
namespace AltLib
{
/// <summary>
/// Property access helper for an instance of <see cref="CmdData"/>
/// where <see cref="CmdData.CmdName"/> has a value of "ICreateStore".
/// </summary>
public partial class CmdData : ICreateStore
{
/// <summary>
/// The unique ID that should be used to identify the store.
/// </summary>
Guid ICreateStore.StoreId => this.GetGuid(nameof(ICreateStore.StoreId));
/// <summary>
/// The user-perceived name for the store.
/// </summary>
string ICreateStore.Name => this.GetValue<string>(nameof(ICreateStore.Name));
/// <summary>
/// The persistence mechanism to be used for saving command data.
/// </summary>
StoreType ICreateStore.Type => this.GetEnum<StoreType>(nameof(ICreateStore.Type));
}
}
|
using System;
namespace ITA.Common.Host
{
internal class AdjustPrivileges
{
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
public static void AdjustSEShutdownPrivilege()
{
WinInterops.TokPriv1Luid tp;
IntPtr hproc = WinInterops.GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
if (!WinInterops.OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok))
{
throw new Exception("Unable to open process token");
}
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
if (!WinInterops.LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid))
{
throw new Exception("Unable to find privilege");
}
if (!WinInterops.AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero))
{
throw new Exception("Unable to adjust process token");
}
}
}
} |
using System;
using UnityEngine;
namespace TheBunniesOfVegetaria
{
[RequireComponent(typeof(AudioSource))]
public class BattleMusicPlayer : MonoBehaviour
{
[SerializeField] private AudioClip regularBattleMusic;
[SerializeField] private AudioClip finalAreaBattleMusic;
[SerializeField] private AudioClip bossBattleMusic;
[SerializeField] private AudioClip finalBossBattleMusic;
[SerializeField] private AudioClip victoryMusic;
private bool bossReached = false;
private AudioSource audioSource;
private void Awake()
{
audioSource = GetComponent<AudioSource>();
}
private void OnEnable()
{
BattleHandler.OnEnemiesInitialized += BattleHandler_OnEnemiesInitialized;
EnemyActor.OnDefeat += EnemyActor_OnDefeat;
}
private void OnDisable()
{
BattleHandler.OnEnemiesInitialized -= BattleHandler_OnEnemiesInitialized;
EnemyActor.OnDefeat -= EnemyActor_OnDefeat;
}
private void BattleHandler_OnEnemiesInitialized(object sender, BattleEventArgs e)
{
if (e.isFinalWave)
{
// Start boss battle music
bossReached = true;
bool isFinalBattle = GameManager.Instance.BattleArea == Globals.Area.Final2;
PlayMusic(isFinalBattle ? finalBossBattleMusic : bossBattleMusic);
}
else if (!audioSource.isPlaying)
{
// Start regular enemy battle music
bool isFinalArea = GameManager.Instance.BattleArea == Globals.Area.CarrotTop;
PlayMusic(isFinalArea ? finalAreaBattleMusic : regularBattleMusic);
}
}
private void EnemyActor_OnDefeat(object sender, EventArgs e)
{
if (bossReached)
PlayMusic(victoryMusic, false);
}
/// <summary>
/// Set and play the current music track.
/// </summary>
/// <param name="audioClip">The music track to play.</param>
/// <param name="loop">Whether to loop the music when it finishes playing.</param>
private void PlayMusic(AudioClip audioClip, bool loop = true)
{
audioSource.clip = audioClip;
audioSource.loop = loop;
audioSource.Play();
}
}
} |
using ProtoBuf;
namespace Abc.Zebus.Tests.Messages
{
[ProtoContract]
public class FakeCommandResult : IMessage
{
[ProtoMember(1, IsRequired = true)]
public readonly string StringValue;
[ProtoMember(2, IsRequired = true)]
public readonly int IntegerValue;
public FakeCommandResult(string stringValue, int integerValue)
{
StringValue = stringValue;
IntegerValue = integerValue;
}
}
} |
namespace SubmissionEvaluation.Client.Services
{
public class MaintenanceService
{
public delegate void MaintenanceChange();
public event MaintenanceChange OnMaintenanceChange;
public void InvokeEvent()
{
OnMaintenanceChange?.Invoke();
}
}
}
|
namespace MultilayerPerceptron.Core
{
public struct Neuron
{
public float Error;
public float Value;
}
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WorkbookTableColumnItemAtRequestBuilder.
/// </summary>
public partial class WorkbookTableColumnItemAtRequestBuilder : BaseFunctionMethodRequestBuilder<IWorkbookTableColumnItemAtRequest>, IWorkbookTableColumnItemAtRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="WorkbookTableColumnItemAtRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="index">A index parameter for the OData method call.</param>
public WorkbookTableColumnItemAtRequestBuilder(
string requestUrl,
IBaseClient client,
Int32 index)
: base(requestUrl, client)
{
this.SetParameter("index", index, false);
this.SetFunctionParameters();
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IWorkbookTableColumnItemAtRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new WorkbookTableColumnItemAtRequest(functionUrl, this.Client, options);
return request;
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnAddRequestBuilder.
/// </summary>
/// <param name="index">A index parameter for the OData method call.</param>
/// <param name="values">A values parameter for the OData method call.</param>
/// <param name="name">A name parameter for the OData method call.</param>
/// <returns>The <see cref="IWorkbookTableColumnAddRequestBuilder"/>.</returns>
public IWorkbookTableColumnAddRequestBuilder Add(
Int32? index,
System.Text.Json.JsonDocument values,
string name)
{
return new WorkbookTableColumnAddRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.add"),
this.Client,
index,
values,
name);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnCountRequestBuilder.
/// </summary>
/// <returns>The <see cref="IWorkbookTableColumnCountRequestBuilder"/>.</returns>
public IWorkbookTableColumnCountRequestBuilder Count()
{
return new WorkbookTableColumnCountRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.count"),
this.Client);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnDataBodyRangeRequestBuilder.
/// </summary>
/// <returns>The <see cref="IWorkbookTableColumnDataBodyRangeRequestBuilder"/>.</returns>
public IWorkbookTableColumnDataBodyRangeRequestBuilder DataBodyRange()
{
return new WorkbookTableColumnDataBodyRangeRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.dataBodyRange"),
this.Client);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnHeaderRowRangeRequestBuilder.
/// </summary>
/// <returns>The <see cref="IWorkbookTableColumnHeaderRowRangeRequestBuilder"/>.</returns>
public IWorkbookTableColumnHeaderRowRangeRequestBuilder HeaderRowRange()
{
return new WorkbookTableColumnHeaderRowRangeRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.headerRowRange"),
this.Client);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnItemAtRequestBuilder.
/// </summary>
/// <param name="index">A index parameter for the OData method call.</param>
/// <returns>The <see cref="IWorkbookTableColumnItemAtRequestBuilder"/>.</returns>
public IWorkbookTableColumnItemAtRequestBuilder ItemAt(
Int32 index)
{
return new WorkbookTableColumnItemAtRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.itemAt"),
this.Client,
index);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnRangeRequestBuilder.
/// </summary>
/// <returns>The <see cref="IWorkbookTableColumnRangeRequestBuilder"/>.</returns>
public IWorkbookTableColumnRangeRequestBuilder Range()
{
return new WorkbookTableColumnRangeRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.range"),
this.Client);
}
/// <summary>
/// Gets the request builder for WorkbookTableColumnTotalRowRangeRequestBuilder.
/// </summary>
/// <returns>The <see cref="IWorkbookTableColumnTotalRowRangeRequestBuilder"/>.</returns>
public IWorkbookTableColumnTotalRowRangeRequestBuilder TotalRowRange()
{
return new WorkbookTableColumnTotalRowRangeRequestBuilder(
this.AppendSegmentToRequestUrl("microsoft.graph.totalRowRange"),
this.Client);
}
/// <summary>
/// Gets the request builder for Filter.
/// Retrieve the filter applied to the column. Read-only.
/// </summary>
/// <returns>The <see cref="IWorkbookFilterRequestBuilder"/>.</returns>
public IWorkbookFilterRequestBuilder Filter
{
get
{
return new WorkbookFilterRequestBuilder(this.AppendSegmentToRequestUrl("filter"), this.Client);
}
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using JetBrains.Annotations;
// from https://stackoverflow.com/a/3729877
namespace Soddi.Services
{
public class BlockingStream : Stream
{
private readonly BlockingCollection<byte[]> _blocks;
private byte[]? _currentBlock;
private int _currentBlockIndex;
public BlockingStream(int streamWriteCountCache)
{
_blocks = new BlockingCollection<byte[]>(streamWriteCountCache);
}
public override bool CanTimeout { get { return false; } }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { throw new NotSupportedException(); } }
public override void Flush() { }
public long TotalBytesWritten { get; private set; }
public int TotalBytesRead { get; set; }
public int WriteCount { get; private set; }
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
ValidateBufferArgs(buffer, offset, count);
var bytesRead = 0;
while (true)
{
if (_currentBlock != null)
{
var copy = Math.Min(count - bytesRead, _currentBlock.Length - _currentBlockIndex);
Array.Copy(_currentBlock, _currentBlockIndex, buffer, offset + bytesRead, copy);
_currentBlockIndex += copy;
bytesRead += copy;
if (_currentBlock.Length <= _currentBlockIndex)
{
_currentBlock = null;
_currentBlockIndex = 0;
}
if (bytesRead == count)
{
TotalBytesRead += bytesRead;
return bytesRead;
}
}
if (!_blocks.TryTake(out _currentBlock, Timeout.Infinite))
return bytesRead;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBufferArgs(buffer, offset, count);
var newBuf = new byte[count];
Array.Copy(buffer, offset, newBuf, 0, count);
_blocks.Add(newBuf);
TotalBytesWritten += count;
WriteCount++;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_blocks.Dispose();
}
}
public override void Close()
{
CompleteWriting();
base.Close();
}
public void CompleteWriting()
{
_blocks.CompleteAdding();
}
[AssertionMethod]
private static void ValidateBufferArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - offset < count)
throw new ArgumentException("buffer.Length - offset < count");
}
}
}
|
namespace MarkdownSnippets
{
[ObsoleteEx(
TreatAsErrorFromVersion = "10.0",
RemoveInVersion = "11.0",
ReplacementTypeOrMember = nameof(DirectoryMarkdownProcessor))]
public class GitHubMarkdownProcessor
{
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Vuforia;
public class VBloadsceneEventHandler : MonoBehaviour, IVirtualButtonEventHandler {
private GameObject vbButtonObject;
// Use this for initialization
void Start () {
vbButtonObject = GameObject.Find ("btn");
vbButtonObject.GetComponent<VirtualButtonBehaviour> ().RegisterEventHandler (this);
}
public void OnButtonPressed (VirtualButtonAbstractBehaviour vb) {
Debug.Log ("downbtn1");
English ();
}
public void OnButtonReleased(VirtualButtonAbstractBehaviour vb)
{
Debug.Log("OnButtonReleased");
}
// Update is called once per frame
void Update () {
}
public void English()
{
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
SceneManager.LoadScene ("English");
#else
Application.LoadLevel ("English");
#endif
}
}
|
namespace ZWaveControllerClient.CommandClasses
{
public class CommandParameterDescLoc
{
public byte Key { get; internal set; }
public int Param { get; internal set; }
public int ParamDesc { get; internal set; }
public int ParamStart { get; internal set; }
}
}
|
using System;
public class CustomDateTime : IDatetime
{
public void AddDays(DateTime date, double daysToAdd) => date.AddDays(daysToAdd);
public DateTime Now() => DateTime.Now;
public TimeSpan SubstractDays(DateTime date, int daysToSybstract)
=> date.Subtract(DateTime.Parse($"{daysToSybstract}", System.Globalization.CultureInfo.InvariantCulture));
}
|
using System.Threading.Tasks;
namespace Abc.Zebus.Tests.Dispatch.DispatchMessages
{
public class AsyncDoNotStartTaskCommandHandler : IAsyncMessageHandler<AsyncDoNotStartTaskCommand>
{
public Task Handle(AsyncDoNotStartTaskCommand message)
{
return new Task(() => {});
}
}
} |
// Copyright (c) 2021 Carpe Diem Software Developing by Alex Versetty.
// http://carpediem.0fees.us/
// License: MIT
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace CDSD.Data
{
class Serialization
{
public static string XmlSerialize<T>(T value)
{
if (value == null) {
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false);
settings.Indent = true;
settings.IndentChars = " ";
settings.OmitXmlDeclaration = false;
using (StringWriter textWriter = new StringWriter()) {
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
public static T XmlDeserialize<T>(string xml)
{
if (string.IsNullOrEmpty(xml)) {
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
using (StringReader textReader = new StringReader(xml)) {
using (XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
return (T)serializer.Deserialize(xmlReader);
}
}
}
public static byte[] BinSerialize(object value)
{
if (value == null) {
return null;
}
byte[] bytes;
var formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream()) {
formatter.Serialize(stream, value);
bytes = stream.ToArray();
}
return bytes;
}
public static object BinDeserialize(byte[] bytes)
{
var formatter = new BinaryFormatter();
return formatter.Deserialize(new MemoryStream(bytes));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESC.Infrastructure;
using ESC.Core;
using ESC.Infrastructure.DomainObjects;
using ESC.Infrastructure.Repository;
namespace ESC.Service
{
/// <summary>
/// 组织结构
/// </summary>
public class SOrganizationService
{
protected SOrganizationRepository oRepository;
protected SUserRepository uRepository;
public SOrganizationService()
{
oRepository = new SOrganizationRepository();
uRepository = new SUserRepository(oRepository.DbCondext);
}
/// <summary>
/// 添加
/// </summary>
/// <param name="users"></param>
/// <param name="orgID"></param>
public int AddOrganization(SOrganization org)
{
//插入组织
object orgID = oRepository.Insert(org);
return Convert.ToInt32(orgID);
}
/// <summary>
/// 通过ID删除库存组织
/// </summary>
/// <param name="orgId"></param>
public bool RemoveOrganization(int orgId)
{
SOrganization org = oRepository.SingleOrDefault(orgId);
if (org == null)
{
return false;
}
uRepository.RemoveOrg(orgId);
return oRepository.Delete(org);
}
/// <summary>
/// 判断是否存在子组织结构
/// </summary>
/// <param name="orgId"></param>
/// <returns></returns>
public bool HasChildrenOrg(int orgId)
{
List<SOrganization> children = oRepository.GetChildOrganization(orgId);
return children.Count > 0;
}
/// <summary>
/// 获取库存组织树
/// </summary>
/// <returns></returns>
public List<SOrganization> GetOrganizationTree()
{
List<SOrganization> orgs = oRepository.QueryAll();
List<SOrganization> parents = orgs.Select(t => t).Where(o => o.ParentID == 0).ToList();
foreach (SOrganization parent in parents)
{
GetOrganizationChild(parent, orgs);
}
return parents;
}
/// <summary>
/// 递归
/// </summary>
/// <param name="parent"></param>
/// <param name="orgs"></param>
/// <returns></returns>
private void GetOrganizationChild(SOrganization parent, List<SOrganization> orgs)
{
List<SOrganization> children = orgs.Select(t => t).Where(o => o.ParentID == parent.ID).ToList();
if (children.Count > 0)
{
parent.Children.AddRange(children);
foreach (SOrganization child in children)
{
GetOrganizationChild(child, orgs);
}
}
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="org"></param>
/// <param name="isAdd"></param>
/// <returns></returns>
public bool IsNotExits(SOrganization org, bool isAdd)
{
if (org == null) return true;
if (string.IsNullOrWhiteSpace(org.OrgCode)) return true;
return oRepository.IsNotExits(org, isAdd);
}
/// <summary>
/// 验证
/// </summary>
/// <param name="org"></param>
/// <returns></returns>
public string CheckOrganization(SOrganization org)
{
string msg = string.Empty;
if (string.IsNullOrWhiteSpace(org.OrgCode))
{
return "组织编码不能为空.";
}
if (string.IsNullOrWhiteSpace(org.OrgName))
{
return "组织名称不能为空.";
}
if (org.ID > 0)
{
if (org.ID == org.ParentID)
{
return "上级组织不能选择自身.";
}
}
return msg;
}
/// <summary>
/// 更新组织
/// </summary>
/// <param name="org"></param>
/// <returns></returns>
public bool UpdateOrganization(SOrganization org)
{
return oRepository.Update(org);
}
/// <summary>
/// 根据ID获取
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public SOrganization GetOrganizationById(int Id)
{
return oRepository.GetOrganizationById(Id);
}
/// <summary>
/// 根据编码或名称查询
/// </summary>
/// <param name="codeName"></param>
/// <returns></returns>
public List<SOrganization> GetOrganizationCodeName(string codeName)
{
return oRepository.GetOrganizationCodeName(codeName);
}
}
}
|
using System;
using MattsWorld.Stations.Domain.Models.Views;
using MattsWorld.Stations.Domain.Ports;
namespace MattsWorld.Stations.Domain
{
public class ViewFacade : IViewFacade
{
private readonly IViewStore _viewStore;
public ViewFacade(IViewStore viewStore)
{
_viewStore = viewStore ?? throw new ArgumentNullException(nameof(viewStore));
}
public StationDetailView GetStation(Guid id)
{
return _viewStore.Get<StationDetailView>(id);
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ServiceCenterWeb.Models.Database;
namespace ServiceCenterWeb.Controllers.WebAPI
{
[Route("api/[controller]")]
[ApiController]
[Authorize(Roles = "Админ, Клиент")]
public class TechnicsController : ControllerBase
{
private readonly ApplicationDbContext _db;
public TechnicsController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public async Task<IEnumerable<Technic>> Get() =>
await _db.Technics
.Include(t => t.TypeTechnic)
.Include(m => m.Manufacturer)
.ToListAsync();
// GET api/technics/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var technic = await _db.Technics.FindAsync(id);
if (technic == null)
return NotFound();
return new ObjectResult(technic);
}
// POST api/technics
[HttpPost]
public async Task<IActionResult> Post([FromBody]Technic technic)
{
if (technic == null) {
return BadRequest();
} // if
var typeTechnic = await _db.TypeTechnics
.FirstAsync(c => c.Id == technic.TypeTechnicId);
var manufacturer = await _db.Manufacturers
.FirstAsync(c => c.Id == technic.ManufacturerId);
if (typeTechnic != null && manufacturer != null) {
technic.TypeTechnic = typeTechnic;
technic.Manufacturer = manufacturer;
await _db.Technics.AddAsync(technic);
await _db.SaveChangesAsync();
} else
return BadRequest();
return Ok(technic);
}
// PUT api/technics/
[HttpPut]
public async Task<IActionResult> Put([FromBody]Technic technic)
{
if (technic == null) {
return BadRequest();
} // if
if (!await _db.Technics.AnyAsync(x => x.Id == technic.Id)) {
return NotFound();
} // if
var typeTechnic = await _db.TypeTechnics
.FirstAsync(c => c.Id == technic.TypeTechnicId);
var manufacturer = await _db.Manufacturers
.FirstAsync(c => c.Id == technic.ManufacturerId);
if (typeTechnic != null && manufacturer != null) {
technic.TypeTechnic = typeTechnic;
technic.Manufacturer = manufacturer;
_db.Update(technic);
await _db.SaveChangesAsync();
} else
return BadRequest();
return Ok(technic);
}
// DELETE api/technics/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var technic = await _db.Technics.FindAsync(id);
if (technic == null) {
return NotFound();
} // if
_db.Technics.Remove(technic);
await _db.SaveChangesAsync();
return Ok(technic);
}
}
} |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Azmoon.Core.Quiz.Entities;
using System;
namespace Azmoon.Application.Shared.Quiz.Questions.Dto
{
[AutoMap(typeof(MatchSet))]
public class MatchSetDto : EntityDto<Guid>
{
public MatchSetDto()
{
}
public Guid QuestionId { get; set; }
public string Value { get; set; }
public bool IsPublic { get; set; }
public bool? IsApproved { get; set; }
}
}
|
using Firebase;
using Firebase.Database;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using Newtonsoft.Json;
public class FirebaseManager : MonoBehaviour
{
[SerializeField]
private List<Level> levels = new List<Level>();
[SerializeField] TMPro.TMP_InputField username;
[HideInInspector]
public DatabaseReference reference;
public UserManager userManager;
private void Start()
{
Debug.Log("HELLO!");
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
reference = FirebaseDatabase.DefaultInstance.RootReference;
// Set a flag here to indicate whether Firebase is ready to use by your app.
}
else
{
UnityEngine.Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
}
public async void AddUserToDatabase(string username)
{
var UserInDatabase = await IsUserInDatabase(username);
if (!UserInDatabase)
{
User user = userManager.initializeUser(username);
string json = JsonUtility.ToJson(user);
try
{
await reference.Child("users").Child(user.username).SetRawJsonValueAsync(json);
Debug.Log("Added " + username + " to the database");
}
catch (Exception e)
{
Debug.Log("Error: " + e);
}
}
}
public async Task<User> GetUser(string username)
{
var task = await reference.Child("users").Child(username).GetValueAsync();
DataSnapshot snapshot = task;
var UserExist = await IsUserInDatabase(username);
if(UserExist)
{
var user = JsonUtility.FromJson<User>(snapshot.GetRawJsonValue());
return user;
} else
{
Debug.Log("User is null!");
return null;
}
}
private async Task<bool> IsUserInDatabase(string username)
{
var task = await reference.Child("users").Child(username).GetValueAsync();
DataSnapshot snapshot = task;
Debug.Log(snapshot);
return snapshot.Child("username").Value != null;
}
public async void UpdateUser(string username, string path, string json)
{
await reference.Child("users").Child(username).Child(path).SetRawJsonValueAsync(json);
Debug.Log("Updated user!");
}
public async Task<DataSnapshot> GetUsers()
{
var task = await reference.Child("users").GetValueAsync();
return task;
}
public async void UpdateUserLevelAttempt(string username, string currentLevel)
{
var user = await GetUser(username);
List<Level> levelList = user.levels;
for (int i = 0; i < levelList.Count; i++)
{
Level level = levelList[i];
if(level.levelname.Contains(currentLevel))
{
levels.Add(level);
Debug.Log("OLD: " + level.attempts);
level.attempts++;
Debug.Log("NEW: " + level.attempts);
string json = JsonConvert.SerializeObject(levelList);
Debug.Log("--------------------");
Debug.Log(json);
Debug.Log("--------------------");
UpdateUser(username, "levels", json);
}
}
}
}
|
using RN.Network;
using UnityEngine;
namespace RN.Network.SpaceWar.Fx
{
public class ExplosionFx : ActorFx<ExplosionSpawner>
{
public override void onCreateFx(ExplosionSpawner actorSpawner)
{
Debug.Assert(actorSpawner.isClient == true, "isClient == true", this);
foreach (var ps in GetComponentsInChildren<ParticleSystem>())
{
if (ps.name == "_")
continue;
var shape = ps.shape;
shape.radius = actorSpawner.radius;
}
var explosionParticleTrigger = GetComponentInChildren<ExplosionParticleTrigger>();
if (explosionParticleTrigger != null)
explosionParticleTrigger.radius = 5f + actorSpawner.radius;
}
public override void onDestroyFx(ExplosionSpawner actorSpawner)
{
Debug.Assert(actorSpawner.isClient == true, "isClient == true", this);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace FisherYates
{
class Program
{
static void Main()
{
var nums = Enumerable.Range(0, 10);
var numsShuffled = nums.Shuffle<int>();
foreach (var item in numsShuffled)
Console.Write("{0} ", item);
Console.WriteLine();
var list = new List<string> { "fisher", "yates", "havel", "hakimi" };
var listShuffled = list.Shuffle<string>();
foreach (var item in listShuffled)
Console.Write("{0} ", item);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace api_worker.Models
{
[Table("Parcari")]
public class ParcariTableModel
{
[Key]
public int ID_PARCARE { get; set; }
public string LOCATIE { get; set; }
public int LOCURI_TOTALE { get; set; }
public string STARE_PARCARE { get; set; }
}
} |
using System;
using Microsoft.SPOT;
using System.Runtime.CompilerServices;
namespace Microsoft.SPOT.Hardware
{
/// <summary>Base class for access to a memory address space</summary>
/// <remarks>
/// An Address space consists of a base address, bit width and length
/// for some Memory or I/O Mapped region. Derived classes provide
/// access to the memory with type safe accessors that overload the
/// index (this[]) operator.
/// </remarks>
public class AddressSpace
{
/// <summary>Per instance Address Space ID stored by Native code</summary>
protected UIntPtr ASID;
/// <summary>Creates a new AddressSpace instance</summary>
/// <param name="Name">Name of the address space</param>
/// <param name="Width">Expected bit width of the address space</param>
/// <remarks>
/// The HAL defines the address space
/// </remarks>
[MethodImpl(MethodImplOptions.InternalCall)]
protected extern AddressSpace(string Name, int Width);
/// <summary>Bit width for the address space</summary>
/// <value>number of bits per word for the address space</value>
/// <remarks>
/// The number of bits is determined by the HAL and cannot
/// be changed from managed code.
/// </remarks>
public extern int BitWdith
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
/// <summary>Word Length for the address space</summary>
/// <value>Number of address space words (BitWidth Wide) in the address space</value>
/// <remarks>
/// The length is a word length and not a byte length. This is done to support
/// indexing in derived classes like an array. The byte length can be computed
/// as follows: int byteLength = ( this.Length * this.BitWidth ) / 8;
/// </remarks>
public extern UInt32 Length
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
}
/// <summary>8 bit wide address space</summary>
public class AddressSpaceUInt8 : AddressSpace
{
public AddressSpaceUInt8(string Name)
: base(Name, 8)
{
}
/// <summary>Accesses a byte in the address space</summary>
/// <param name="Offset">byte offset from the base of the address space (e.g. 0 based index)</param>
/// <value>New Value for the byte at the specified offset</value>
/// <returns>Value of the byte at the offset</returns>
public extern byte this[UInt32 Offset]
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
}
/// <summary>16 bit address space</summary>
public class AddressSpaceUInt16 : AddressSpace
{
public AddressSpaceUInt16(string Name)
: base(Name, 16)
{
}
/// <summary>Accesses a 16 bit value in the address space</summary>
/// <param name="Offset">16 bit word offset from the base of the address space (e.g. 0 based index)</param>
/// <value>New Value for word at the specified offset</value>
/// <returns>Value of the word at the specified offset</returns>
public extern UInt16 this[UInt32 Offset]
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
}
/// <summary>32 bit address space</summary>
public class AddressSpaceUInt32 : AddressSpace
{
public AddressSpaceUInt32(string Name)
: base(Name, 32)
{
}
/// <summary>Accesses a 32 bit value in the address space</summary>
/// <param name="Offset">32 bit word offset from the base of the address space (e.g. 0 based index)</param>
/// <value>New Value for word at the specified offset</value>
/// <returns>Value of the word at the specified offset</returns>
public extern UInt32 this[UInt32 Offset]
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
}
}
|
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Justgrow.Engine.Containers.Hexgrid;
using Justgrow.Engine.Utilities.LSystem;
using Justgrow.Engine.Services.Core;
using Justgrow.Engine.Services.Resources;
using Justgrow.Gameplays.Core;
using Justgrow.Gameplays.Background;
using Justgrow.Gameplays.Wind;
namespace Justgrow.Gameplays.Tree
{
public class UndergroundCell : Cell
{
public int Size { get; set; }
public bool Visited { get; set; }
public UndergroundCell() : base()
{
Size = 0;
Visited = false;
}
}
} |
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Components;
using System;
using Xunit;
namespace Blazored.Toast.Tests.ToastServiceTests
{
public class ShowToastComponent
{
private readonly ToastService _sut;
public ShowToastComponent()
{
_sut = new ToastService();
}
[Fact]
public void OnShowComponentInvoked_When_ShowToastCalled()
{
// arrange
var OnShowCalled = false;
_sut.OnShowComponent += (_, _, _) => OnShowCalled = true;
// act
_sut.ShowToast<MyTestComponent>();
// assert
Assert.True(OnShowCalled);
}
[Fact]
public void OnShowComponentEventContainsNoParameters_When_ShowToastCalled()
{
// arrange
ToastParameters parameters = null;
_sut.OnShowComponent += (_, argParameters, _) => parameters = argParameters;
// act
_sut.ShowToast<MyTestComponent>();
// assert
Assert.NotNull(parameters);
}
[Fact]
public void OnShowComponentEventContainsNoSettings_When_ShowToastCalled()
{
// arrange
ToastInstanceSettings settings = null;
_sut.OnShowComponent += (_, _, argSettings) => settings = argSettings;
// act
_sut.ShowToast<MyTestComponent>();
// assert
Assert.Null(settings);
}
[Fact]
public void OnShowComponentInvoked_When_ShowToastCalledWithParameters()
{
// arrange
var OnShowCalled = false;
_sut.OnShowComponent += (_, _, _) => OnShowCalled = true;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters());
// assert
Assert.True(OnShowCalled);
}
[Fact]
public void OnShowComponentEventContainsParameters_When_ShowToastCalledWithParameters()
{
// arrange
ToastParameters parameters = null;
_sut.OnShowComponent += (_, argParameters, _) => parameters = argParameters;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters());
// assert
Assert.NotNull(parameters);
}
[Fact]
public void OnShowComponentEventContainsNoSettings_When_ShowToastCalledWithParameters()
{
// arrange
ToastInstanceSettings settings = null;
_sut.OnShowComponent += (_, _, argSettings) => settings = argSettings;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters());
// assert
Assert.Null(settings);
}
[Fact]
public void OnShowComponentInvoked_When_ShowToastCalledWithSettings()
{
// arrange
var OnShowCalled = false;
_sut.OnShowComponent += (_, _, _) => OnShowCalled = true;
// act
_sut.ShowToast<MyTestComponent>(new ToastInstanceSettings(10, true));
// assert
Assert.True(OnShowCalled);
}
[Fact]
public void OnShowComponentEventContainsNoParameters_When_ShowToastCalledWithSettings()
{
// arrange
ToastParameters parameters = null;
_sut.OnShowComponent += (_, argParameters, _) => parameters = argParameters;
// act
_sut.ShowToast<MyTestComponent>(new ToastInstanceSettings(10, true));
// assert
Assert.Null(parameters);
}
[Fact]
public void OnShowComponentEventContainsSettings_When_ShowToastCalledWithSettings()
{
// arrange
ToastInstanceSettings settings = null;
_sut.OnShowComponent += (_, _, argSettings) => settings = argSettings;
// act
_sut.ShowToast<MyTestComponent>(new ToastInstanceSettings(2, true));
// assert
Assert.NotNull(settings);
Assert.Equal(2, settings.Timeout);
Assert.True(settings.ShowProgressBar);
}
[Fact]
public void OnShowComponentInvoked_When_ShowToastCalledWithParametersAndSettings()
{
// arrange
var OnShowCalled = false;
_sut.OnShowComponent += (_, _, _) => OnShowCalled = true;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters(), new ToastInstanceSettings(10, true));
// assert
Assert.True(OnShowCalled);
}
[Fact]
public void OnShowComponentEventContainsParameters_When_ShowToastCalledWithParametersAndSettings()
{
// arrange
ToastParameters parameters = null;
_sut.OnShowComponent += (_, argParameters, _) => parameters = argParameters;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters(), new ToastInstanceSettings(10, true));
// assert
Assert.NotNull(parameters);
}
[Fact]
public void OnShowComponentEventContainsSettings_When_ShowToastCalledWithParametersAndSettings()
{
// arrange
ToastInstanceSettings settings = null;
_sut.OnShowComponent += (_, _, argSettings) => settings = argSettings;
// act
_sut.ShowToast<MyTestComponent>(new ToastParameters(), new ToastInstanceSettings(2, true));
// assert
Assert.NotNull(settings);
Assert.Equal(2, settings.Timeout);
Assert.True(settings.ShowProgressBar);
}
[Fact]
public void ArgumentExceptionIsThrown_When_ShowToastCalledPassingIncorrectType()
{
// arrange / act
Action action = () => _sut.ShowToast(typeof(int), null, null);
// assert
Assert.Throws<ArgumentException>(action);
}
[Fact]
public void OnShowComponentInvoked_When_ShowToastCalledWithCorrectTypeAndParametersAndSettings()
{
// arrange
var OnShowCalled = false;
_sut.OnShowComponent += (_, _, _) => OnShowCalled = true;
// act
_sut.ShowToast(typeof(IComponent), new ToastParameters(), new ToastInstanceSettings(10, true));
// assert
Assert.True(OnShowCalled);
}
[Fact]
public void OnShowComponentEventContainsParameters_When_ShowToastCalledWithCorrectTypeAndParametersAndSettings()
{
// arrange
ToastParameters parameters = null;
_sut.OnShowComponent += (_, argParameters, _) => parameters = argParameters;
// act
_sut.ShowToast(typeof(IComponent), new ToastParameters(), new ToastInstanceSettings(10, true));
// assert
Assert.NotNull(parameters);
}
[Fact]
public void OnShowComponentEventContainsSettings_When_ShowToastCalledWithCorrectTypeAndParametersAndSettings()
{
// arrange
ToastInstanceSettings settings = null;
_sut.OnShowComponent += (_, _, argSettings) => settings = argSettings;
// act
_sut.ShowToast(typeof(IComponent), new ToastParameters(), new ToastInstanceSettings(2, true));
// assert
Assert.NotNull(settings);
Assert.Equal(2, settings.Timeout);
Assert.True(settings.ShowProgressBar);
}
}
}
|
namespace CoreWCF.IdentityModel.Claims
{
internal static class XsiConstants
{
public const string Namespace = "http://schemas.xmlsoap.org/ws/2005/05/identity";
public const string System = "System";
}
} |
namespace openECAClient.Model
{
public class SchemaVersion
{
public int VersionNumber { get; set; }
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Loly.Kafka.Producer;
namespace Loly.Agent.Kafka
{
public interface IProducerService<TKey, TValue> : IDisposable
{
IProducerQueue<TKey, TValue> Queue { get; set; }
Task Start(CancellationToken cancellationToken);
Task Stop(CancellationToken cancellationToken);
}
} |
using System;
using Newtonsoft.Json;
namespace Warframe.World.Models
{
public class SortieVariant
{
[Obsolete("This property isn't used anymore and will most likely always return \"Deprecated\"")]
[JsonProperty]
public string Boss { get; private set; }
[Obsolete("This property isn't used anymore and will most likely always return \"Deprecated\"")]
[JsonProperty]
public string Planet { get; private set; }
[JsonProperty]
public string MissionType { get; private set; }
[JsonProperty]
public string Modifier { get; private set; }
[JsonProperty]
public string ModifierDescription { get; private set; }
[JsonProperty]
public string Node { get; private set; }
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Cognitive Services: http://www.microsoft.com/cognitive
//
// Microsoft Cognitive Services Github:
// https://github.com/Microsoft/Cognitive
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using ServiceHelpers;
using ServiceHelpers.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
namespace IntelligentKioskSample.Views.AnomalyDetector
{
public sealed partial class AnomalyChartControl : UserControl
{
private static readonly int MaxVolumeValue = 120;
private static readonly int TooltipBottomMargin = 15;
private static readonly int BaseVolume = 50;
private static readonly int DefaultDurationOfLiveDemoInSecond = 480;
private static readonly string StopDetectButton = "Stop Processing";
private static readonly string StartDetectButton = "Detect Anomalies";
private static readonly string ShortDateFormat = "MM/dd";
private static readonly string ShortDateWithTimeFormat = "MM/dd HH:mm";
private Visual xamlRoot;
private Compositor compositor;
private ContainerVisual containerRoot;
private SpriteVisual progressIndicator;
private bool isProcessing = false;
private bool shouldStopCurrentRun = false;
private float maxVolumeInSampleBuffer = 0;
private AnomalyDetectionScenario curScenario;
private AnomalyEntireDetectResult anomalyEntireDetectResult;
private List<Tuple<SpriteVisual, AnomalyInfo>> allAnomalyIndicators = new List<Tuple<SpriteVisual, AnomalyInfo>>();
public AnomalyDetectorServiceType SelectedDetectionMode { get; private set; }
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title",
typeof(string),
typeof(ScenarioInfoControl),
new PropertyMetadata(string.Empty));
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public event EventHandler StartLiveAudio;
public event EventHandler StopLiveAudio;
public AnomalyChartControl()
{
this.InitializeComponent();
PrepareUIElements();
}
public void InitializeChart(AnomalyDetectionScenarioType scenarioType, AnomalyDetectorServiceType detectionMode, double sensitivy)
{
if (AnomalyDetectorScenarioLoader.AllModelData.ContainsKey(scenarioType))
{
curScenario = AnomalyDetectorScenarioLoader.AllModelData[scenarioType];
if (scenarioType == AnomalyDetectionScenarioType.Live)
{
curScenario.AllData.Clear();
}
DisplayBasicData(curScenario);
// set default value: slider and radio buttons
this.sensitivitySlider.Value = sensitivy;
SelectedDetectionMode = detectionMode;
}
}
public void SetVolumeValue(float value)
{
maxVolumeInSampleBuffer = value;
}
private void OnChartGridSizeChanged(object sender, SizeChangedEventArgs e)
{
if (curScenario == null)
{
return;
}
ResetState();
DisplayBasicData(curScenario);
shouldStopCurrentRun = true;
// update anomaly data
if (allAnomalyIndicators != null && allAnomalyIndicators.Count > 0)
{
if (curScenario.ScenarioType == AnomalyDetectionScenarioType.Live)
{
ClearAnomalyPoints();
}
}
}
private void PrepareUIElements()
{
xamlRoot = ElementCompositionPreview.GetElementVisual(ResultPanel);
compositor = xamlRoot.Compositor;
containerRoot = compositor.CreateContainerVisual();
ElementCompositionPreview.SetElementChildVisual(resultGrid, containerRoot);
progressIndicator = compositor.CreateSpriteVisual();
progressIndicator.Size = new Vector2(10, 10);
progressIndicator.AnchorPoint = new Vector2(0.5f, 0.5f);
progressIndicator.Brush = compositor.CreateColorBrush(Color.FromArgb(179, 0, 120, 215));
containerRoot.Children.InsertAtTop(progressIndicator);
progressIndicator.Offset = new Vector3(0, (float)resultGrid.ActualHeight, resultGrid.CenterPoint.Z);
progressLine.X1 = progressIndicator.CenterPoint.X;
progressLine.X2 = progressIndicator.CenterPoint.X;
// pointer moved event for tooltip
resultGrid.PointerMoved += OnChartPointer;
detectWindowPolyline.PointerMoved += OnChartPointer;
}
private void OnChartPointer(object sender, PointerRoutedEventArgs e)
{
Point point = e.GetCurrentPoint(resultGrid).Position;
var anomaly = allAnomalyIndicators.FirstOrDefault(x => Util.IsPointInsideVisualElement(x.Item1, point) &&
(e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse || e.Pointer.IsInContact)); // test for touch exit event);
if (anomaly != null)
{
Visual visualElement = anomaly.Item1;
AnomalyInfo anomalyInfo = anomaly.Item2;
double popupWidth = this.tooltipPopup.ActualWidth;
double popupHeight = this.tooltipPopup.ActualHeight;
Point absolutePoint = e.GetCurrentPoint(Window.Current.Content).Position;
double pageWidth = ((AppShell)Window.Current.Content)?.ActualWidth ?? 0;
double xOffset = absolutePoint.X + popupWidth / 2.0 >= pageWidth ? visualElement.Offset.X - popupWidth : visualElement.Offset.X - popupWidth / 2.0;
double yOffset = visualElement.Offset.Y - popupHeight - TooltipBottomMargin;
// set tooltip offset
this.tooltipPopup.HorizontalOffset = xOffset;
this.tooltipPopup.VerticalOffset = yOffset;
// set tooltip data
this.timestampTextBlock.Text = anomalyInfo.Text;
this.delayValueTextBlock.Text = anomalyInfo.Value;
this.expectedTextBlock.Text = anomalyInfo.ExpectedValue;
// show tooltip
this.tooltipPopup.IsOpen = true;
}
else
{
// hide tooltip
this.tooltipPopup.IsOpen = false;
}
}
private async void OnStartDetectionButtonClicked(object sender, RoutedEventArgs e)
{
if (curScenario == null)
{
return;
}
try
{
if (isProcessing)
{
shouldStopCurrentRun = true;
detectingAnomalyBtn.Content = StartDetectButton;
}
else
{
ResetState();
isProcessing = true;
shouldStopCurrentRun = false;
detectingAnomalyBtn.Content = StopDetectButton;
switch (curScenario.ScenarioType)
{
case AnomalyDetectionScenarioType.Live:
this.StartLiveAudio?.Invoke(this, EventArgs.Empty);
await StartLiveDemoProcessAsync();
break;
default:
await StartStreamingModeProcessAsync();
break;
}
}
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure after click Anomaly Detect button.");
}
finally
{
isProcessing = false;
detectingAnomalyBtn.Content = StartDetectButton;
}
}
private async Task StartLiveDemoProcessAsync()
{
try
{
double yScale = resultGrid.ActualHeight / MaxVolumeValue;
double xOffset = resultGrid.ActualWidth / DefaultDurationOfLiveDemoInSecond;
DateTime currentTime = DateTime.Now;
DateTime startTime = currentTime.AddMinutes((double)DefaultDurationOfLiveDemoInSecond * -1);
progressLine.X1 = progressIndicator.CenterPoint.X;
progressLine.X2 = progressIndicator.CenterPoint.X;
dataPolyline.Points.Clear();
int startIndex = AnomalyDetectionScenario.DefaultRequiredPoints;
for (int i = 0; i < startIndex; i++)
{
float volume = GetCurrentVolumeValue();
curScenario.AllData.Insert(i, new TimeSeriesData(startTime.ToString(), volume));
startTime = startTime.AddMinutes(AnomalyDetectorScenarioLoader.GetTimeOffsetInMinute(curScenario.Granularity));
double yOffset = yScale * (curScenario.AllData[i].Value - BaseVolume);
Point point = new Point(xOffset * i, resultGrid.ActualHeight - yOffset);
dataPolyline.Points.Add(point);
Point newUpperPoint = new Point(dataPolyline.Points[i].X, 0);
Point newLowerPoint = new Point(dataPolyline.Points[i].X, resultGrid.ActualHeight);
int endOfUpper = detectWindowPolyline.Points.Count / 2;
int endOfLower = detectWindowPolyline.Points.Count / 2 + 1;
detectWindowPolyline.Points.Insert(endOfUpper, newUpperPoint);
detectWindowPolyline.Points.Insert(endOfLower, newLowerPoint);
}
for (int i = startIndex; i < DefaultDurationOfLiveDemoInSecond; i++)
{
if (shouldStopCurrentRun)
{
break;
}
float volume = GetCurrentVolumeValue();
curScenario.AllData.Insert(i, new TimeSeriesData(startTime.ToString(), volume));
startTime = startTime.AddMinutes(AnomalyDetectorScenarioLoader.GetTimeOffsetInMinute(curScenario.Granularity));
double yOffset = yScale * (curScenario.AllData[i].Value - BaseVolume);
Point point = new Point(xOffset * i, resultGrid.ActualHeight - yOffset);
dataPolyline.Points.Add(point);
AnomalyLastDetectResult result = await GetLiveDemoAnomalyDetectionResultAsync(i);
if (result != null)
{
result.ExpectedValue -= BaseVolume;
AnomalyInfo anomalyInfo = new AnomalyInfo
{
Text = i.ToString(),
Value = (volume - BaseVolume).ToString("F2"),
ExpectedValue = result.ExpectedValue.ToString("F2")
};
DrawProgressByDetectionResult(dataPolyline.Points[i], result, anomalyInfo, yScale);
}
}
this.StopLiveAudio?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure during streaming detection.");
}
}
private async Task StartBatchModeProcessAsync()
{
try
{
detectingAnomalyBtn.IsEnabled = false;
string timestampFormat = curScenario.ScenarioType == AnomalyDetectionScenarioType.Telecom ? ShortDateFormat : ShortDateWithTimeFormat;
double dataRange = curScenario.MaxValue - curScenario.MinValue;
double yScale = (resultGrid.ActualHeight / dataRange);
double yZeroLine = yScale * curScenario.MinValue;
for (int i = 0; i < dataPolyline.Points.Count; i++)
{
progressIndicator.Offset = new Vector3(float.Parse(dataPolyline.Points[i].X.ToString()), float.Parse(resultGrid.ActualHeight.ToString()), resultGrid.CenterPoint.Z);
progressLine.X1 = dataPolyline.Points[i].X;
progressLine.X2 = dataPolyline.Points[i].X;
if (anomalyEntireDetectResult != null)
{
Point newUpperPoint = new Point(dataPolyline.Points[i].X, yZeroLine + resultGrid.ActualHeight - (yScale * (anomalyEntireDetectResult.ExpectedValues[i] + anomalyEntireDetectResult.UpperMargins[i])));
Point newLowerPoint = new Point(dataPolyline.Points[i].X, yZeroLine + resultGrid.ActualHeight - (yScale * (anomalyEntireDetectResult.ExpectedValues[i] - anomalyEntireDetectResult.LowerMargins[i])));
if (anomalyEntireDetectResult.IsAnomaly[i])
{
SpriteVisual anomalyIndicator = GetNewAnomalyIndicator(dataPolyline.Points[i]);
TimeSeriesData timeSeriesData = curScenario.AllData[i];
AnomalyInfo anomalyInfo = new AnomalyInfo
{
Text = Util.StringToDateFormat(timeSeriesData.Timestamp, timestampFormat),
Value = timeSeriesData.Value.ToString("F2"),
ExpectedValue = anomalyEntireDetectResult.ExpectedValues[i].ToString("F2")
};
containerRoot.Children.InsertAtTop(anomalyIndicator);
allAnomalyIndicators.Add(new Tuple<SpriteVisual, AnomalyInfo>(anomalyIndicator, anomalyInfo));
}
int endOfUpper = progressPolyline.Points.Count / 2;
int endOfLower = progressPolyline.Points.Count / 2 + 1;
progressPolyline.Points.Insert(endOfUpper, newUpperPoint);
progressPolyline.Points.Insert(endOfLower, newLowerPoint);
}
}
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure during batch detection.");
}
finally
{
detectingAnomalyBtn.IsEnabled = true;
}
}
private async Task StartStreamingModeProcessAsync()
{
try
{
if (dataPolyline.Points != null)
{
dataPolyline.Points.Clear();
}
else
{
dataPolyline.Points = new PointCollection();
}
double dataRange = curScenario.MaxValue - curScenario.MinValue;
double yScale = resultGrid.ActualHeight / dataRange;
double xOffset = resultGrid.ActualWidth / (curScenario.AllData.Count - 1);
double yZeroLine = yScale * curScenario.MinValue;
string timestampFormat = curScenario.ScenarioType == AnomalyDetectionScenarioType.Telecom ? ShortDateFormat : ShortDateWithTimeFormat;
int startIndex = curScenario.MinIndexOfRequiredPoints;
for (int i = 0; i < startIndex; i++)
{
Point point = new Point(xOffset * i, yZeroLine + resultGrid.ActualHeight - (yScale * curScenario.AllData[i].Value));
dataPolyline.Points.Add(point);
Point newUpperPoint = new Point(dataPolyline.Points[i].X, 0);
Point newLowerPoint = new Point(dataPolyline.Points[i].X, resultGrid.ActualHeight);
int endOfUpper = detectWindowPolyline.Points.Count / 2;
int endOfLower = detectWindowPolyline.Points.Count / 2 + 1;
detectWindowPolyline.Points.Insert(endOfUpper, newUpperPoint);
detectWindowPolyline.Points.Insert(endOfLower, newLowerPoint);
}
for (int i = startIndex; i < curScenario.AllData.Count; i++)
{
if (shouldStopCurrentRun)
{
break;
}
AnomalyLastDetectResult result = await GetStreamingAnomalyDetectionResultAsync(i);
Point point = new Point(xOffset * i, yZeroLine + resultGrid.ActualHeight - (yScale * curScenario.AllData[i].Value));
dataPolyline.Points.Add(point);
if (result != null)
{
TimeSeriesData timeSeriesData = curScenario.AllData[i];
AnomalyInfo anomalyInfo = new AnomalyInfo
{
Text = Util.StringToDateFormat(timeSeriesData.Timestamp, timestampFormat),
Value = timeSeriesData.Value.ToString("F2"),
ExpectedValue = result.ExpectedValue.ToString("F2")
};
DrawProgressByDetectionResult(dataPolyline.Points[i], result, anomalyInfo, yScale, yZeroLine);
}
}
}
catch (Exception ex)
{
await Util.GenericApiCallExceptionHandler(ex, "Failure during streaming detection.");
}
}
private async Task<AnomalyLastDetectResult> GetLiveDemoAnomalyDetectionResultAsync(int dataPointIndex)
{
int requiredPoints = Math.Min(AnomalyDetectionScenario.DefaultRequiredPoints, curScenario.MinIndexOfRequiredPoints);
if (dataPointIndex >= requiredPoints)
{
AnomalyDetectionRequest dataRequest = new AnomalyDetectionRequest
{
Sensitivity = (int)sensitivitySlider.Value,
MaxAnomalyRatio = curScenario.MaxAnomalyRatio,
Granularity = curScenario.Granularity.ToString(),
CustomInterval = curScenario.CustomInterval,
Period = curScenario.Period,
Series = curScenario.AllData.GetRange(dataPointIndex - requiredPoints, (requiredPoints + 1))
};
return await AnomalyDetectorHelper.GetStreamingDetectionResult(dataRequest);
}
return null;
}
private async Task<AnomalyLastDetectResult> GetStreamingAnomalyDetectionResultAsync(int dataPointIndex)
{
if (dataPointIndex >= curScenario.MinIndexOfRequiredPoints)
{
AnomalyDetectionRequest dataRequest = new AnomalyDetectionRequest
{
Sensitivity = (int)sensitivitySlider.Value,
MaxAnomalyRatio = curScenario.MaxAnomalyRatio,
Granularity = curScenario.Granularity.ToString(),
CustomInterval = curScenario.CustomInterval,
Period = curScenario.Period,
Series = curScenario.AllData.GetRange(dataPointIndex - curScenario.MinIndexOfRequiredPoints, (curScenario.MinIndexOfRequiredPoints + 1))
};
return await AnomalyDetectorHelper.GetStreamingDetectionResult(dataRequest);
}
return null;
}
private async Task<AnomalyEntireDetectResult> GetBatchAnomalyDetectionResultAsync()
{
AnomalyDetectionRequest dataRequest = new AnomalyDetectionRequest
{
Sensitivity = (int)sensitivitySlider.Value,
MaxAnomalyRatio = curScenario.MaxAnomalyRatio,
Granularity = curScenario.Granularity.ToString(),
CustomInterval = curScenario.CustomInterval,
Period = curScenario.Period,
Series = curScenario.AllData
};
return await AnomalyDetectorHelper.GetBatchDetectionResult(dataRequest);
}
private SpriteVisual GetNewAnomalyIndicator(Point anomalyPoint)
{
SpriteVisual anomaly;
anomaly = compositor.CreateSpriteVisual();
anomaly.Brush = compositor.CreateColorBrush(Colors.Yellow);
anomaly.Size = new Vector2(10, 10);
anomaly.Offset = new Vector3((float)(anomalyPoint.X), (float)(anomalyPoint.Y), resultGrid.CenterPoint.Z);
anomaly.AnchorPoint = new Vector2()
{
X = 0.5f,
Y = anomaly.Offset.Y + anomaly.Size.Y > resultGrid.ActualHeight ? 1f :
anomaly.Offset.Y - anomaly.Size.Y < 0 ? 0f : 0.5f
};
return anomaly;
}
private void SetYAxisLabels(double max, double min, AnomalyDetectionScenarioType scenarioType)
{
string format = "F2";
if (scenarioType == AnomalyDetectionScenarioType.Live)
{
min = 0;
max = MaxVolumeValue;
format = "F0";
}
double step = (max - min) / 4;
this.y1_Lbl.Text = min.ToString(format);
this.y2_Lbl.Text = (min + step).ToString(format);
this.y3_Lbl.Text = (min + 2 * step).ToString(format);
this.y4_Lbl.Text = (min + 3 * step).ToString(format);
this.y5_Lbl.Text = max.ToString(format);
}
private void SetXAxisLabels(AnomalyDetectionScenario scenario)
{
if (scenario != null)
{
int step = 0;
List<TimeSeriesData> data = scenario.AllData;
switch (scenario.ScenarioType)
{
case AnomalyDetectionScenarioType.Live:
step = DefaultDurationOfLiveDemoInSecond / 4;
this.x1_Lbl.Text = $"{0 * step}";
this.x2_Lbl.Text = $"{1 * step}";
this.x3_Lbl.Text = $"{2 * step}";
this.x4_Lbl.Text = $"{3 * step}";
this.x5_Lbl.Text = $"{4 * step}";
break;
default:
if (data.Any())
{
step = data.Count % 4 != 0 ? (int)Math.Floor(data.Count / 4.0) : data.Count / 4;
this.x1_Lbl.Text = Util.StringToDateFormat(data[0 * step].Timestamp, ShortDateFormat);
this.x2_Lbl.Text = Util.StringToDateFormat(data[1 * step].Timestamp, ShortDateFormat);
this.x3_Lbl.Text = Util.StringToDateFormat(data[2 * step].Timestamp, ShortDateFormat);
this.x4_Lbl.Text = Util.StringToDateFormat(data[3 * step].Timestamp, ShortDateFormat);
this.x5_Lbl.Text = Util.StringToDateFormat(data[data.Count - 1].Timestamp, ShortDateFormat);
}
break;
}
}
}
private void DrawProgressByDetectionResult(Point detectionPoint, AnomalyLastDetectResult detectionResult, AnomalyInfo anomalyInfo, double yScale, double yZeroLine = 0)
{
double upperMarginOnUI = detectionResult.ExpectedValue + detectionResult.UpperMargin;
double lowerMarginOnUI = detectionResult.ExpectedValue - detectionResult.LowerMargin;
double offsetY1 = yScale * upperMarginOnUI;
double offsetY2 = lowerMarginOnUI > 0 ? yScale * lowerMarginOnUI : 0;
int indexOfFirstValidPoint = curScenario.MinIndexOfRequiredPoints;
Point newUpperPoint = new Point(detectionPoint.X, (yZeroLine + resultGrid.ActualHeight - offsetY1) > 0 ? (yZeroLine + resultGrid.ActualHeight - offsetY1) : 0);
Point newLowerPoint = new Point(detectionPoint.X, yZeroLine + resultGrid.ActualHeight - offsetY2);
if (detectionResult.IsAnomaly)
{
SpriteVisual anomalyIndicator = GetNewAnomalyIndicator(detectionPoint);
containerRoot.Children.InsertAtTop(anomalyIndicator);
allAnomalyIndicators.Add(new Tuple<SpriteVisual, AnomalyInfo>(anomalyIndicator, anomalyInfo));
}
int endOfUpper = progressPolyline.Points.Count / 2;
int endOfLower = progressPolyline.Points.Count / 2 + 1;
progressPolyline.Points.Insert(endOfUpper, newUpperPoint);
progressPolyline.Points.Insert(endOfLower, newLowerPoint);
detectWindowPolyline.Points.Insert((detectWindowPolyline.Points.Count / 2), new Point(detectionPoint.X, 0));
detectWindowPolyline.Points.Insert((detectWindowPolyline.Points.Count / 2 + 1), new Point(detectionPoint.X, resultGrid.ActualHeight));
if ((detectWindowPolyline.Points.Count / 2) >= indexOfFirstValidPoint)
{
detectWindowPolyline.Points.RemoveAt(0);
detectWindowPolyline.Points.RemoveAt(detectWindowPolyline.Points.Count - 1);
}
progressIndicator.Offset = new Vector3((float)(detectionPoint.X), (float)(resultGrid.ActualHeight), resultGrid.CenterPoint.Z);
progressLine.X1 = detectionPoint.X;
progressLine.X2 = detectionPoint.X;
}
private float GetCurrentVolumeValue()
{
return maxVolumeInSampleBuffer * 100 + BaseVolume;
}
public void ResetState()
{
shouldStopCurrentRun = true;
anomalyEntireDetectResult = null;
this.StopLiveAudio?.Invoke(this, EventArgs.Empty);
ClearAnomalyPoints();
}
private void DisplayBasicData(AnomalyDetectionScenario scenario)
{
// update axis lines
SetXAxisLabels(scenario);
SetYAxisLabels(scenario.MaxValue, scenario.MinValue, scenario.ScenarioType);
// update progress line
if (progressIndicator != null)
{
progressIndicator.Offset = new Vector3(0, (int)resultGrid.ActualHeight, resultGrid.CenterPoint.Z);
progressLine.X1 = progressIndicator.CenterPoint.X;
progressLine.X2 = progressIndicator.CenterPoint.X;
progressLine.Y1 = 0;
progressLine.Y2 = resultGrid.ActualHeight;
}
// update data points
dataPolyline.Points?.Clear();
}
private PointCollection GetPointCollectionByScenarioData(AnomalyDetectionScenario scenario)
{
PointCollection dataPoints = new PointCollection();
if (scenario.AllData != null && scenario.AllData.Any())
{
double dataRange = scenario.MaxValue - scenario.MinValue;
double yScale = (resultGrid.ActualHeight / dataRange);
double xOffset = resultGrid.ActualWidth / (scenario.AllData.Count - 1);
double yZeroLine = yScale * scenario.MinValue;
for (int i = 0; i < scenario.AllData.Count; i++)
{
Point point = new Point(xOffset * i, yZeroLine + resultGrid.ActualHeight - (yScale * scenario.AllData[i].Value));
dataPoints.Add(point);
}
}
return dataPoints;
}
private void ClearAnomalyPoints()
{
progressPolyline.Points?.Clear();
detectWindowPolyline.Points?.Clear();
if (allAnomalyIndicators != null && allAnomalyIndicators.Count > 0)
{
foreach (SpriteVisual anomaly in allAnomalyIndicators.Select(x => x.Item1))
{
if (containerRoot.Children.Contains(anomaly))
{
containerRoot.Children.Remove(anomaly);
}
}
allAnomalyIndicators.Clear();
}
}
}
}
|
using System;
using essentialMix.Data.Model;
namespace MongoPOC.Model;
public interface IEntity<T> : IEntity
where T : IComparable<T>, IEquatable<T>
{
T Id { get; set; }
} |
using MaoDeVaca.Domain.Commands;
using MaoDeVaca.Domain.Dto;
using MaoDeVaca.Domain.Query;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MaoDeVaca.Domain.Interfaces
{
public interface IUserService
{
Task CreateAsync(CreateUserCommand request);
Task UpdateAsync(UpdateUserCommand request);
void Delete(Guid id);
Task<IList<UserDto>> GetAsync(UserQuery query);
}
}
|
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace TextProcessingExercise
{
class Program
{
static void Main(string[] args)
{
string[] words = Console.ReadLine().Split(", ");
Regex regex1 = new Regex(@"^[a-zA-Z0-9_-]+$");
foreach (var word in words)
{
if (regex1.IsMatch(word) && word.Length >= 3 && word.Length <= 16)
{
Console.WriteLine(word);
}
}
}
}
}
|
using Microsoft.Xna.Framework;
using System.Collections.Generic;
namespace OpenVIII
{
public abstract partial class SP2
{
#region Classes
public class TexProps
{
#region Fields
/// <summary>
/// For big textures.
/// </summary>
public List<BigTexProps> Big;
/// <summary>
/// Override palette of texture to this and don't load other palettes. If null ignore.
/// </summary>
public Color[] Colors;
/// <summary>
/// Number of Textures
/// </summary>
public uint Count;
/// Filename. To match more than one number use {0:00} or {00:00} for ones with leading
/// zeros. </summary>
public string Filename;
#endregion Fields
#region Properties
/// <summary>
/// Position in Filename of texture
/// </summary>
public uint Offset { get; set; }
#endregion Properties
//public TexProps(string filename, uint Count, params BigTexProps[] big)
//{
// Filename = filename;
// Count = Count;
// if (big != null && Count != big.Length && big.Length > 0)
// throw new Exception($"Count of big textures should match small ones {Count} != {big.Length}");
// Big = big.ToList();
// Colors = null;
//}
//public TexProps(string filename, uint Count, Color[] colors, params BigTexProps[] big)
//{
// Filename = filename;
// Count = Count;
// if (big != null && Count != big.Length && big.Length > 0)
// throw new Exception($"Count of big textures should match small ones {Count} != {big.Length}");
// Big = big.ToList();
// Colors = colors;
//}
//Texture_Base.TextureType TextureType;
}
#endregion Classes
}
} |
using System;
namespace Jord.Core.Items
{
public class ItemPile
{
private int _quantity = 0;
public Item Item
{
get; set;
}
public int Quantity
{
get
{
return _quantity;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_quantity = value;
}
}
public ItemPile Clone()
{
return new ItemPile
{
Item = Item,
Quantity = Quantity
};
}
public override string ToString()
{
if (Quantity == 1)
{
return Item.Info.Name;
}
return string.Format("{0} ({1})", Item.Info.Name, Quantity);
}
}
}
|
using ScrapyCore.Core.Platform.Commands;
namespace ScrapyCore.Core.Platform.MessageOperation
{
public interface IMessageOperationManager
{
IMessageRawOperation GetRawOperation(CommandTransfer transfer);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
label1.Text = openFileDialog1.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Form4", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
sw.Write(richTextBox1.Text);
sw.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Form4", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button3_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
cd.ShowHelp = true;
if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
button3.BackColor = cd.Color;
button2.BackColor = cd.Color;
button1.BackColor = cd.Color;
}
}
}
}
|
//
// Copyright (c) 2019-2022 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//
using AngouriMath.Core.Exceptions;
namespace AngouriMath
{
using SortLevel = Functions.TreeAnalyzer.SortLevel;
partial record Entity
{
/// <summary>
/// Returns the correct way for sort string
/// </summary>
/// <param name="level">The level at which we are sorting</param>
/// <param name="highLevel">The most general way (that is, the least uniqueness of the string)</param>
/// <param name="middleLevel">The one in between (for example, for grouping some functions)</param>
/// <param name="lowLevel">The most unique string id</param>
private static string Choice(SortLevel level, string highLevel, string middleLevel, string lowLevel)
=> level switch
{
SortLevel.HIGH_LEVEL => highLevel,
SortLevel.MIDDLE_LEVEL => middleLevel,
SortLevel.LOW_LEVEL => lowLevel,
_ => throw new AngouriBugException($"Unrecognized SortLevel: {level}")
};
/// <summary>
/// Returns the correct way for sort string
/// </summary>
/// <param name="level">The level at which we are sorting</param>
/// <param name="highLevel">The most general way (that is, the least uniqueness of the string)</param>
/// <param name="lowLevel">The most unique string id</param>
private static string Choice(SortLevel level, string highLevel, string lowLevel)
=> Choice(level, highLevel, lowLevel, lowLevel);
public partial record Number
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", Stringize(), Stringize() + " ");
}
// TODO: reorder all those names to make similar functions appear closer
public partial record Variable
{
private protected override string SortHashName(SortLevel level) => "v_" + Name;
}
partial record Matrix
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "tensort_");
}
// Each function and operator processing
public partial record Sumf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "summinus_", "sum_");
}
public partial record Minusf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "summinus_", "min_");
}
public partial record Mulf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "divmul_", "mul_");
}
public partial record Divf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "divmul_", "div_");
}
public partial record Powf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "logpow_", "pow_");
}
public partial record Logf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "", "logpow_", "log_");
}
public partial record Sinf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "sincoss_", "sin_", "sin_");
}
public partial record Cosf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "sincosc_", "cos_", "cos_");
}
public partial record Secantf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "seccsc_", "sec_", "sec_");
}
public partial record Cosecantf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "seccsc_", "csc_", "csc_");
}
public partial record Tanf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "tancot_", "tan_", "tan_");
}
public partial record Cotanf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "tancot_", "cot_", "cot_");
}
public partial record Arcsecantf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arcseccsc_", "arcseccsc_", "arcsec_");
}
public partial record Arccosecantf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arcseccsc_", "arcseccsc_", "arccsc_");
}
public partial record Arcsinf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arcsincos_", "arcsincos_", "arcsin_");
}
public partial record Arccosf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arcsincos_", "arcsincos_", "arccos_");
}
public partial record Arctanf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arctancot_", "arctancot_", "arctan_");
}
public partial record Arccotanf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "arctancot_", "arctancot_", "arccot_");
}
public partial record Factorialf
{
private protected override string SortHashName(SortLevel level) => "factorialf_";
}
public partial record Derivativef
{
private protected override string SortHashName(SortLevel level) => "derivativef_";
}
public partial record Integralf
{
private protected override string SortHashName(SortLevel level) => "integralf_";
}
public partial record Limitf
{
private protected override string SortHashName(SortLevel level) => "limitf_";
}
public partial record Signumf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "sgnabs_", "sgn_", "sgn_");
}
public partial record Absf
{
private protected override string SortHashName(SortLevel level)
=> Choice(level, "sgnabs_", "abs_", "abs_");
}
partial record Boolean
{
private protected override string SortHashName(SortLevel level)
=> level switch
{
SortLevel.HIGH_LEVEL => "",
SortLevel.MIDDLE_LEVEL => Stringize(),
_ => Stringize() + " "
};
}
partial record Notf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "not_" : "";
}
partial record Andf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "and_" : "";
}
partial record Orf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "or_" : "";
}
partial record Xorf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "xor_" : "";
}
partial record Impliesf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "impl_" : "";
}
partial record Equalsf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "equals_" : "";
}
partial record Greaterf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "greater_" : "";
}
partial record GreaterOrEqualf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "greaterequal_" : "";
}
partial record Lessf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "less_" : "";
}
partial record LessOrEqualf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "lessequal_" : "";
}
partial record Set
{
partial record FiniteSet
{
private protected override string SortHashName(SortLevel level)
=> level switch
{
SortLevel.HIGH_LEVEL => "",
SortLevel.MIDDLE_LEVEL => Stringize(),
_ => Stringize() + " "
};
}
partial record Interval
{
private protected override string SortHashName(SortLevel level)
=> level switch
{
SortLevel.HIGH_LEVEL => "",
SortLevel.MIDDLE_LEVEL => Stringize(),
_ => Stringize() + " "
};
}
partial record ConditionalSet
{
private protected override string SortHashName(SortLevel level)
=> level switch
{
SortLevel.HIGH_LEVEL => "",
SortLevel.MIDDLE_LEVEL => Stringize(),
_ => Stringize() + " "
};
}
partial record SpecialSet
{
private protected override string SortHashName(SortLevel level)
=> level switch
{
SortLevel.HIGH_LEVEL => "",
SortLevel.MIDDLE_LEVEL => Stringize(),
_ => Stringize() + " "
};
}
partial record Unionf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "union_" : "";
}
partial record Intersectionf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "intersection_" : "";
}
partial record SetMinusf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "setminus_" : "";
}
partial record Inf
{
private protected override string SortHashName(SortLevel level)
=> level == SortLevel.LOW_LEVEL ? "in_" : "";
}
}
partial record Phif
{
private protected override string SortHashName(SortLevel level) => "phi_";
}
partial record Providedf
{
private protected override string SortHashName(SortLevel level) => "provided_";
}
partial record Piecewise
{
private protected override string SortHashName(SortLevel level) => "__";
}
partial record Application
{
private protected override string SortHashName(SortLevel level) => "___";
}
partial record Lambda
{
private protected override string SortHashName(SortLevel level) => "___";
}
}
}
|
using System;
using Microsoft.Extensions.DependencyInjection;
using GraphQL.Types;
namespace GraphQL.Relay.StarWars.Types
{
public class StarWarsSchema : Schema
{
public StarWarsSchema(IServiceProvider provider) : base(provider)
{
Query = provider.GetService<StarWarsQuery>();
RegisterType(typeof(FilmGraphType));
RegisterType(typeof(PeopleGraphType));
RegisterType(typeof(PlanetGraphType));
RegisterType(typeof(SpeciesGraphType));
RegisterType(typeof(StarshipGraphType));
RegisterType(typeof(VehicleGraphType));
}
}
} |
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using Autofac;
namespace ModulesMvc.Infrastructure
{
public static class AutofacExtension
{
public static void RegisterModules(this ContainerBuilder builder, string pluginsPath)
{
var mapPath = HttpContext.Current.Server.MapPath(string.Concat("~/", pluginsPath));
var dir = new DirectoryInfo(mapPath);
var dlls = dir.GetFiles("*.dll");
if (dlls != null && dlls.Any())
{
foreach (var item in dlls)
{
if (item.Name.Contains("Module"))
{
var asmb = Assembly.LoadFile(Path.Combine(mapPath, item.Name));
builder.RegisterAssemblyTypes(asmb).AsImplementedInterfaces();
}
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
namespace EjemplosTasks
{
class CLConexionDestino
{
//Conexion para mi BulkSqlCopy
public static SqlConnection getConnection()
{
// Conexion
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MiBasedeDatosDestino"];
string connectionString = conSettings.ConnectionString;
return new SqlConnection(connectionString);
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using JuloUtil;
public interface IFocusTarget {
bool isFocused();
Vector3 getFocusPosition();
}
public interface IFocusable {
void focusObject(Component obj);
void focusAny<T>(IList<T> objects) where T : Component;
void focusPosition(Vector3 position);
void blur();
}
public class FocusTarget : IFocusable, IFocusTarget {
private enum Type { NONE, OBJECT, POSITION }
private Type focusType;
private Transform targetObject;
private Vector3 targetPosition;
public FocusTarget() {
focusType = Type.NONE;
}
public bool isFocused() {
return focusType != Type.NONE;
}
public Vector3 getFocusPosition() {
if(focusType == Type.OBJECT) {
if(!targetObject.gameObject.activeSelf)
blur();
return targetObject.position;
} else if(focusType == Type.POSITION) {
return targetPosition;
} else {
throw new ApplicationException("No target");
}
}
public void focusObject(Component obj) {
focusType = Type.OBJECT;
targetObject = obj.transform;
}
public void focusAny<T>(IList<T> objects) where T : Component {
int numCandidates = objects.Count;
if(numCandidates == 0) {
Debug.Log("Focusing zero objects");
return;
}
bool alreadyFocused = false;
if(focusType == Type.OBJECT) {
foreach(Component c in objects) {
if(c.gameObject == targetObject.gameObject) {
alreadyFocused = true;
break;
}
}
}
if(!alreadyFocused) {
focusObject(objects[JuloMath.randomInt(0, numCandidates - 1)]);
}
}
public void focusPosition(Vector3 position) {
focusType = Type.POSITION;
targetPosition = position;
}
public void blur() {
focusType = Type.NONE;
}
}
|
using Quasar.Common.Messages;
using Quasar.Common.Networking;
using Quasar.Server.Networking;
using System;
using System.Collections.Generic;
namespace Quasar.Server.Messages
{
public class SayHelloHandler : MessageProcessorBase<List<string>>
{
private readonly Client _client;
public SayHelloHandler(Client client) : base(true)
{
_client = client;
}
public override bool CanExecute(IMessage message) => message is GetSayHelloResponse;
public override bool CanExecuteFrom(ISender client) => _client.Equals(client);
public override void Execute(ISender sender, IMessage message)
{
switch (message)
{
case GetSayHelloResponse info:
Execute(sender, info);
break;
}
}
public void RefreshSystemInformation(string inputMsg)
{
if (string.IsNullOrEmpty(inputMsg))
{
inputMsg = "msg == null";
}
GetSayHello sayHello = new GetSayHello();
sayHello.msg = inputMsg;
_client.Send(sayHello);
}
private void Execute(ISender client, GetSayHelloResponse message)
{
OnReport(message.msgs);
}
}
}
|
namespace ExperimentFramework.Evaluation
{
/// <summary>
/// 公式运算,用于检测某些数值是否合理
/// </summary>
public interface IFormula
{
FormulaMessage Formula(string[] args,params string[] anwser);
}
} |
using FluentAssertions;
using NUnit.Framework;
using Sanchez.Processing.Models;
using Sanchez.Processing.Services;
using Sanchez.Test.Common;
namespace Sanchez.Processing.Test.Services
{
[TestFixture(TestOf = typeof(VisibleRangeService))]
public class VisibleRangeServiceTests : AbstractTests
{
private IVisibleRangeService VisibleRangeService => GetService<IVisibleRangeService>();
[Test]
public void GetVisibleRangeGoes17()
{
const double longitude = -137.2;
var range = VisibleRangeService.GetVisibleRange(Angle.FromDegrees(longitude));
range.Start.Should().BeApproximately(Angle.FromDegrees(142.088718).Radians, Precision);
range.End.Should().BeApproximately(Angle.FromDegrees(-56.48871).Radians, Precision);
}
}
} |
using Cerber.Models;
using Cerber.ViewModels;
using Xamarin.Forms;
namespace Cerber.Views
{
public partial class ServiceDetailsPage : ContentPage
{
private ServiceDetailsViewModel _viewModel => BindingContext as ServiceDetailsViewModel;
public ServiceDetailsPage(ServiceModel serviceModel)
{
InitializeComponent();
BindingContext = new ServiceDetailsViewModel(serviceModel);
_viewModel.LoadServiceDetails.Execute(null);
}
}
}
|
using System.IO;
using System.Drawing;
using Aspose.Cells;
using Aspose.Cells.Rendering;
namespace Aspose.Cells.Examples.CSharp.Files.Utility
{
public class WorksheetToImage
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Open a template Excel file.
Workbook book = new Workbook(dataDir + "MyTestBook1.xls");
// Get the first worksheet.
Worksheet sheet = book.Worksheets[0];
// Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
// Specify the image format
imgOptions.ImageType = Drawing.ImageType.Jpeg;
// Only one page for the whole sheet would be rendered
imgOptions.OnePagePerSheet = true;
// Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
// Render the image for the sheet
Bitmap bitmap = sr.ToImage(0);
// Save the image file specifying its image format.
bitmap.Save(dataDir + "SheetImage.out.jpg");
// Display result, so that user knows the processing has finished.
System.Console.WriteLine("Conversion to Image(s) completed.");
// ExEnd:1
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;
//using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Mvc;
//using Evol.TMovie.Domain.QueryEntries;
//using Evol.Domain.Messaging;
//using Evol.TMovie.Domain.QueryEntries.Parameters;
//using Evol.TMovie.Domain.Dto;
//using Evol.TMovie.Manage.Models;
//using Evol.TMovie.Domain.Commands.Dto;
//using Evol.TMovie.Domain.Commands;
//namespace Evol.TMovie.Manage.Controllers
//{
// [Produces("application/json")]
// [Route("api/Role")]
// public class RoleController : Controller
// {
// private IRoleQueryEntry _roleQueryEntry { get; set; }
// private ICommandBus _commandBus { get; set; }
// public RoleController(IRoleQueryEntry roleQueryEntry, ICommandBus commandBus)
// {
// _roleQueryEntry = roleQueryEntry;
// _commandBus = commandBus;
// }
// // GET: Cinema
// [HttpGet]
// public async Task<IActionResult> Index(RoleQueryParameter param = null, int pageIndex = 1, int pageSize = 10)
// {
// var paged = await _roleQueryEntry.PagedAsync(param, pageIndex, pageSize);
// var result = paged.MapPaged<RoleViewModel>();
// return View(result);
// }
// // GET: Cinema/Details/5
// [HttpGet]
// public async Task<IActionResult> Details(Guid id)
// {
// var item = await _roleQueryEntry.FindAsync(id);
// return View(item);
// }
// // GET: Cinema/Create
// [HttpGet]
// public IActionResult Create()
// {
// return View();
// }
// // POST: Cinema/Create
// [HttpPost]
// [ValidateAntiForgeryToken]
// public async Task<IActionResult> Create(RoleCreateOrUpdateDto dto)
// {
// if (!await TryUpdateModelAsync(dto))
// {
// return View(dto);
// }
// await _commandBus.SendAsync(new RoleCreateCommand() { Input = dto });
// return RedirectToAction("Index");
// }
// // GET: Cinema/Edit/5
// [HttpGet]
// public async Task<IActionResult> Edit(Guid id)
// {
// var item = await _roleQueryEntry.FindAsync(id);
// return View(item);
// }
// // POST: Cinema/Edit/5
// [ValidateAntiForgeryToken]
// [HttpPut]
// public async Task<IActionResult> Edit(int id, RoleCreateOrUpdateDto dto)
// {
// if (!await TryUpdateModelAsync(dto))
// {
// return View(dto);
// }
// await _commandBus.SendAsync(new RoleUpdateCommand() { Input = dto });
// this.ModelState.AddModelError(string.Empty, "Success!");
// return View(dto);
// }
// // GET: Cinema/Delete/5
// [HttpDelete]
// public async Task<bool> Delete(Guid id)
// {
// await _commandBus.SendAsync(new RoleDeleteCommand() { Input = new ItemDeleteDto() { Id = id } });
// return true;
// }
// }
//}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using SecureApp.Utilities.Model.Enum;
using SecureApp.Utilities.Model.Interface;
using SecureApp.Utilities.Network.Callbacks;
using SecureApp.Utilities.Network.Packets;
using SecureApp.Utilities.Network.RemoteCalls;
using SecureApp.Utilities.Network.Server.RemoteCalls;
namespace SecureApp.Utilities.Network.Server
{
public delegate void OnClientConnectDelegate(SecureSocketServer sender, SecureSocketConnectedClient client);
public class SecureSocketServer : IEnumerable<SecureSocket>
{
public event OnClientConnectDelegate OnClientConnect;
public TransportProtocol Protocol { get; }
public ClientManager Clients { get; private set; }
private readonly Packager _packager;
private readonly CallbackManager<SecureSocketConnectedClient> _callbacks;
private readonly RemoteCallServerManager _remoteFuncs;
private Func<Guid> _guidGenerator = Guid.NewGuid;
private readonly List<SecureSocket> _openSockets = new List<SecureSocket>();
private SecureSocketServer(TransportProtocol protocol, Packager packager)
{
Protocol = protocol;
_packager = packager;
_callbacks = new CallbackManager<SecureSocketConnectedClient>();
Clients = new ClientManager();
_remoteFuncs = new RemoteCallServerManager(_packager);
SetHandler<RemoteCallRequest>((cl, att) => _remoteFuncs.HandleClientFunctionCall(cl, att));
}
public SecureSocketServer() : this(TransportProtocol.IPv4, new Packager())
{
}
public SecureSocket StartServer(int port)
{
BaseServerSocket baseSock = new BaseServerSocket(Protocol);
baseSock.OnClientConnect += TcpSock_OnClientConnect;
if (!baseSock.BeginAccept(port))
return null;
_openSockets.Add(baseSock);
baseSock.OnClose += (s, err) => {
_openSockets.Remove(s);
};
return baseSock;
}
private void TcpSock_OnClientConnect(BaseServerSocket sender, Socket s)
{
InternalSecureSocketConnectedClient client = new InternalSecureSocketConnectedClient(s, _packager);
client.SetId(_guidGenerator());
client.BeginReceive(ReceiveHandler);
client.Send(cl => {
Clients.Add(cl);
client.OnDisconnect += (c, err) => {
Clients.Remove(c);
};
OnClientConnect?.Invoke(this, cl);
}, new HandshakePacket(true, client.Id));
}
private void ReceiveHandler(InternalSecureSocketConnectedClient client, IPacket data)
{
_callbacks.Handle(client, data);
}
public void SetGuidGenerator(Func<Guid> call)
{
if (call == null)
return;
_guidGenerator = call;
}
public void SetHandler(Action<SecureSocketConnectedClient, object[]> callback)
{
_callbacks.SetArrayHandler(callback);
}
public void SetHandler<T>(Action<SecureSocketConnectedClient, T> callback) where T : class, IPacket
{
_callbacks.SetHandler(callback);
}
public void SetHandler(Action<SecureSocketConnectedClient, IPacket> callback)
{
_callbacks.SetPacketHandler(callback);
}
public RemoteFunctionBind RegisterRemoteFunction(string name, Delegate func)
{
return _remoteFuncs.BindRemoteCall(name, func);
}
public void SetDefaultRemoteFunctionAuthCallback(RemoteFunctionCallAuth defaultAuthCallback)
{
_remoteFuncs.SetDefaultAuthCallback(defaultAuthCallback);
}
public IEnumerator<SecureSocket> GetEnumerator()
{
return _openSockets.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _openSockets.GetEnumerator();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ZChatSystem
{
internal static class errorLogging
{
private static string errorLogFile = "d:\\errorLog.txt";
internal static void LogError(Exception ex)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(errorLogFile, true);
sw.WriteLine("============================================================================");
sw.WriteLine(DateTime.Now.ToString());
sw.WriteLine("Error: " + ex.Message);
sw.WriteLine("Source: " + ex.Source);
sw.WriteLine("Stack: " + ex.StackTrace);
if (ex.InnerException != null)
{
sw.WriteLine("Inner: " + ex.InnerException.Message);
sw.WriteLine("Inner Stack: " + ex.InnerException.StackTrace);
}
sw.WriteLine("============================================================================");
sw.WriteLine("");
sw.Close();
}
}
} |
using System.Text.RegularExpressions;
using Xunit;
namespace MR.QueryBuilder
{
public class QueryBuilderTest
{
[Fact]
public void Works()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.Where("UserName = 'root'")
.Skip(1).Take(10)
.Select("AspNetUsers u", null, c => c.Exclude("Name"));
Assert.NotNull(query);
}
[Fact]
public void Select()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.WhereNotNull("f.Name")
.Select("Foo f");
var expected = @"
SELECT f.Id, f.Name
FROM Foo f
WHERE f.Name IS NOT NULL";
AssertEqual(expected, query);
}
[Fact]
public void Select_SkipTake()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.Skip(2).Take(3)
.Select("Foo f");
var expected = @"
SELECT f.Id, f.Name
FROM Foo f
OFFSET 2 ROWS FETCH NEXT 3 ROWS ONLY";
AssertEqual(expected, query);
}
[Fact]
public void Select_WithoutPrefix()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.WhereNotNull("Name")
.Select("Foo");
var expected = @"
SELECT Id, Name
FROM Foo
WHERE Name IS NOT NULL";
AssertEqual(expected, query);
}
[Fact]
public void Select_Order()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.OrderBy("Name")
.Select("Foo");
var expected = @"
SELECT Id, Name
FROM Foo
ORDER BY Name";
AssertEqual(expected, query);
}
[Fact]
public void Select_OrderDesc()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.OrderBy("Name").Desc()
.Select("Foo");
var expected = @"
SELECT Id, Name
FROM Foo
ORDER BY Name DESC";
AssertEqual(expected, query);
}
[Fact]
public void Select_IncludeProps()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.Select("Foo", null, c =>
{
c.Include("Id");
});
var expected = @"
SELECT Id
FROM Foo";
AssertEqual(expected, query);
}
[Fact]
public void Select_ExcludeProps()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.Select("Foo", null, c =>
{
c.Exclude("Name");
});
var expected = @"
SELECT Id
FROM Foo";
AssertEqual(expected, query);
}
[Fact]
public void Select_ExcludeAll()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.Select("Foo", null, c =>
{
c.ExcludeAll();
c.Include("Id, Name");
});
var expected = @"
SELECT Id
FROM Foo";
AssertEqual(expected, query);
}
[Fact]
public void Select_Join()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.InnerJoin<Model2>("Bar b on b.Id = f.BarId")
.Select("Foo f");
var expected = @"
SELECT f.Id, f.Name, b.Id, b.Peer
FROM Foo f
INNER JOIN Bar b on b.Id = f.BarId";
AssertEqual(expected, query);
}
[Fact]
public void Select_Join_Exclude()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.InnerJoin<Model2>("Bar b on b.Id = f.BarId", c =>
{
c.Exclude("Peer");
})
.Select("Foo f");
var expected = @"
SELECT f.Id, f.Name, b.Id
FROM Foo f
INNER JOIN Bar b on b.Id = f.BarId";
AssertEqual(expected, query);
}
[Fact]
public void Select_CaseInsensetive()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.InnerJoin<Model2>("Bar b on b.Id = f.BarId", c =>
{
c.Exclude("peer");
})
.Select("Foo f");
var expected = @"
SELECT f.Id, f.Name, b.Id
FROM Foo f
INNER JOIN Bar b on b.Id = f.BarId";
AssertEqual(expected, query);
}
[Fact]
public void Select_WithSelector()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.WhereNotNull("Name")
.Select("Foo", "Id, Name");
var expected = @"
SELECT Id, Name
FROM Foo
WHERE Name IS NOT NULL";
AssertEqual(expected, query);
}
[Fact]
public void Select_Count()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.WhereNotNull("Name")
.Count("Foo");
var expected = @"
SELECT COUNT(*)
FROM Foo
WHERE Name IS NOT NULL";
AssertEqual(expected, query);
}
[Fact]
public void Delete()
{
var qb = new QueryBuilder<Model1>();
var query = qb
.WhereNull("Name")
.Delete("Foo");
var expected = @"
DELETE FROM Foo
WHERE Name IS NULL";
AssertEqual(expected, query);
}
private class Model1
{
public int Id { get; set; }
public string Name { get; set; }
}
private class Model2
{
public int Id { get; set; }
public string Peer { get; set; }
}
private string Collapse(string value)
{
value = value.Trim();
var regex = new Regex("[\r\n\t ]+");
value = regex.Replace(value, " ");
return value;
}
private void AssertEqual(string expected, string actual)
{
Assert.Equal(Collapse(expected), Collapse(actual));
}
}
}
|
using Contoso.DigitalGoods.DigitalLocker.Service.Models;
using Contoso.DigitalGoods.TokenService.Models;
using Microsoft.Azure.TokenService.Proxy;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Contoso.DigitalGoods.TokenService.Interfaces
{
public interface ITokenServiceAgent
{
Task<TokenMeta> CreateToken(string TokenName, string TokenSymbol, string CallerID);
Task DeleteAccount(string ABTUserID);
Task<User> GetAccountInfo(string ABTUserID);
Task<IEnumerable<User>> GetAllAccounts();
Asset GetDigitalGoodFromDigitalLocker(string ABTUserID, long TokenNumber);
Task<DigitalKickToken> GetDigitalGoodfromToken(string ABTUserID, long TokenNumber);
Task<TokenMeta> GetTokenInfo(string TokenId, string CallerID);
List<Asset> GetUserDigitalLocker(string ABTUserID);
Task<bool> GiftDigitalGoods(string Recipient, long TokenNumber);
Task<bool> IsitMyToken(long? TokenNumber, string CallerID);
Task<DigitalKickToken> MakeDigitalGoods(DigitalKickToken digitalGoodToken);
Task<string> ProvisionUser(string ContosoUserIdentifier);
Task<bool> TransferDigitalGoods(string Sender, string Recipient, long TokenNumber);
}
} |
@model IList<MyShop.ViewModels.CategoryVm>
<ul class="navbar-nav" style="margin: 0 auto">
@foreach (var cat in Model)
{
<li class="nav-item"><a class="nav-link" href="/categories/@cat.Id">@cat.Name</a></li>
}
</ul> |
/* Copyright (c) 2021, John Lenz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of John Lenz, Black Maple Software, SeedTactics,
nor the names of other contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
namespace MazakMachineInterface
{
public enum MazakDbType
{
MazakVersionE,
MazakWeb,
MazakSmooth
}
public enum MazakWriteCommand
{
ForceUnlockEdit = 3,
Add = 4,
Delete = 5,
Edit = 6,
ScheduleSafeEdit = 7,
ScheduleMaterialEdit = 8,
Error = 9,
}
public record MazakPartRow
{
public string PartName { get; init; }
public string Comment { get; init; }
public double Price { get; init; }
public int TotalProcess { get; init; }
// these columns are new on smooth
private string _matName;
public string MaterialName
{
get => _matName ?? "";
init => _matName = value;
}
public int Part_1 { get; init; }
public int Part_2 { get; init; }
private string _part3;
public string Part_3
{
get => _part3 ?? "";
init => _part3 = value;
}
public int Part_4 { get; init; }
public int Part_5 { get; init; }
public int CheckCount { get; init; }
public int ProductCount { get; init; }
public IList<MazakPartProcessRow> Processes { get; init; } = new List<MazakPartProcessRow>();
public MazakWriteCommand Command { get; init; } // only for transaction DB
}
public record MazakPartProcessRow
{
public string PartName { get; init; }
public int ProcessNumber { get; init; }
public int FixQuantity { get; init; }
public int ContinueCut { get; init; }
public string CutMc { get; init; }
public string FixLDS { get; init; }
public string FixPhoto { get; init; }
public string Fixture { get; init; }
public string MainProgram { get; init; }
public string RemoveLDS { get; init; }
public string RemovePhoto { get; init; }
public int WashType { get; init; }
// these are new on smooth
public int PartProcess_1 { get; init; }
public int PartProcess_2 { get; init; }
public int PartProcess_3 { get; init; }
public int PartProcess_4 { get; init; }
public int FixTime { get; init; }
public int RemoveTime { get; init; }
public int CreateToolList_RA { get; init; }
}
public record MazakScheduleRow
{
public int Id { get; init; }
public string Comment { get; init; }
public string PartName { get; init; }
public int PlanQuantity { get; init; }
public int CompleteQuantity { get; init; }
public int Priority { get; init; }
public DateTime? DueDate { get; init; }
public int FixForMachine { get; init; }
public int HoldMode { get; init; }
public int MissingFixture { get; init; }
public int MissingProgram { get; init; }
public int MissingTool { get; init; }
public int MixScheduleID { get; init; }
public int ProcessingPriority { get; init; }
//these are only on Smooth
public int Schedule_1 { get; init; }
public int Schedule_2 { get; init; }
public int Schedule_3 { get; init; }
public int Schedule_4 { get; init; }
public int Schedule_5 { get; init; }
public int Schedule_6 { get; init; }
public DateTime? StartDate { get; init; }
public int SetNumber { get; init; }
public int SetQuantity { get; init; }
public int SetNumberSets { get; init; }
public IList<MazakScheduleProcessRow> Processes { get; init; } = new List<MazakScheduleProcessRow>();
public MazakWriteCommand Command { get; init; } // only for transaction DB
}
public record MazakScheduleProcessRow
{
public int MazakScheduleRowId { get; init; }
public int FixQuantity { get; init; }
public int ProcessNumber { get; init; }
public int ProcessMaterialQuantity { get; init; }
public int ProcessExecuteQuantity { get; init; }
public int ProcessBadQuantity { get; init; }
public int ProcessMachine { get; init; }
// these are only on Smooth
public int FixedMachineFlag { get; init; }
public int FixedMachineNumber { get; init; }
public int ScheduleProcess_1 { get; init; }
public int ScheduleProcess_2 { get; init; }
public int ScheduleProcess_3 { get; init; }
public int ScheduleProcess_4 { get; init; }
public int ScheduleProcess_5 { get; init; }
}
public record MazakPalletRow
{
public int PalletNumber { get; init; }
public string Fixture { get; init; }
public int RecordID { get; init; }
public int AngleV1 { get; init; }
public int FixtureGroupV2 { get; init; }
public MazakWriteCommand Command { get; init; } // only for transaction DB
public int FixtureGroup
{
get
{
if (AngleV1 > 1000)
{
return AngleV1 % 1000;
}
else
{
return FixtureGroupV2;
}
}
}
}
public record MazakPalletSubStatusRow
{
public int PalletNumber { get; init; }
public string FixtureName { get; init; }
public int ScheduleID { get; init; }
public string PartName { get; init; }
public int PartProcessNumber { get; init; }
public int FixQuantity { get; init; }
}
public record MazakPalletPositionRow
{
public int PalletNumber { get; init; }
public string PalletPosition { get; init; }
}
public record MazakFixtureRow
{
public string FixtureName { get; init; }
public string Comment { get; init; }
public MazakWriteCommand Command { get; init; } // only for transaction DB
}
public record MazakAlarmRow
{
public int? AlarmNumber { get; init; }
public string AlarmMessage { get; init; }
}
public record ToolPocketRow
{
public int? MachineNumber { get; init; }
public int? PocketNumber { get; init; }
public int? PocketType { get; init; }
public int? ToolID { get; init; }
public int? ToolNameCode { get; init; }
public int? ToolNumber { get; init; }
public bool? IsLengthMeasured { get; init; }
public bool? IsToolDataValid { get; init; }
public bool? IsToolLifeOver { get; init; }
public bool? IsToolLifeBroken { get; init; }
public bool? IsDataAccessed { get; init; }
public bool? IsBeingUsed { get; init; }
public bool? UsableNow { get; init; }
public bool? WillBrokenInform { get; init; }
public int? InterferenceType { get; init; }
public int? LifeSpan { get; init; }
public int? LifeUsed { get; init; }
public string NominalDiameter { get; init; }
public int? SuffixCode { get; init; }
public int? ToolDiameter { get; init; }
public string GroupNo { get; init; }
}
public record LoadAction
{
public int LoadStation { get; init; }
public bool LoadEvent { get; init; }
public string Unique { get; init; }
public string Part { get; init; }
public int Process { get; init; }
public int Path { get; init; }
public int Qty { get; init; }
public LoadAction(bool l, int stat, string p, string comment, int proc, int q)
{
LoadStation = stat;
LoadEvent = l;
Part = p;
Process = proc;
Qty = q;
if (string.IsNullOrEmpty(comment))
{
Unique = "";
Path = 1;
}
else
{
MazakPart.ParseComment(comment, out string uniq, out var procToPath, out bool manual);
Unique = uniq;
Path = procToPath.PathForProc(proc);
}
}
[Newtonsoft.Json.JsonConstructor] public LoadAction() { }
}
public record MazakCurrentStatus
{
public IEnumerable<MazakScheduleRow> Schedules { get; init; }
public IEnumerable<LoadAction> LoadActions { get; init; }
public IEnumerable<MazakPalletSubStatusRow> PalletSubStatuses { get; init; }
public IEnumerable<MazakPalletPositionRow> PalletPositions { get; init; }
public IEnumerable<MazakAlarmRow> Alarms { get; init; }
public IEnumerable<MazakPartRow> Parts { get; init; }
public void FindSchedule(string mazakPartName, int proc, out string unique, out int path, out int numProc)
{
unique = "";
numProc = proc;
path = 1;
foreach (var schRow in Schedules)
{
if (schRow.PartName == mazakPartName && !string.IsNullOrEmpty(schRow.Comment))
{
bool manual;
MazakPart.ParseComment(schRow.Comment, out unique, out var procToPath, out manual);
numProc = schRow.Processes.Count;
if (numProc < proc) numProc = proc;
path = procToPath.PathForProc(proc);
return;
}
}
}
}
public record MazakCurrentStatusAndTools : MazakCurrentStatus
{
public IEnumerable<ToolPocketRow> Tools { get; init; }
}
public record MazakProgramRow
{
public string MainProgram { get; init; }
public string Comment { get; init; }
}
public record MazakAllData : MazakCurrentStatus
{
public IEnumerable<MazakPalletRow> Pallets { get; init; }
public IEnumerable<MazakProgramRow> MainPrograms { get; init; }
public IEnumerable<MazakFixtureRow> Fixtures { get; init; }
}
public interface ICurrentLoadActions : IDisposable
{
IEnumerable<LoadAction> CurrentLoadActions();
}
public interface IReadDataAccess
{
MazakDbType MazakType { get; }
MazakCurrentStatusAndTools LoadStatusAndTools();
MazakAllData LoadAllData();
IEnumerable<MazakProgramRow> LoadPrograms();
IEnumerable<ToolPocketRow> LoadTools();
bool CheckPartExists(string part);
bool CheckProgramExists(string mainProgram);
TResult WithReadDBConnection<TResult>(Func<IDbConnection, TResult> action);
}
public record NewMazakProgram
{
public string ProgramName { get; init; }
public long ProgramRevision { get; init; }
public string MainProgram { get; init; }
public string Comment { get; init; }
public MazakWriteCommand Command { get; init; }
public string ProgramContent { get; init; }
}
public record MazakWriteData
{
public IReadOnlyList<MazakScheduleRow> Schedules { get; init; } = new List<MazakScheduleRow>();
public IReadOnlyList<MazakPartRow> Parts { get; init; } = new List<MazakPartRow>();
public IReadOnlyList<MazakPalletRow> Pallets { get; init; } = new List<MazakPalletRow>();
public IReadOnlyList<MazakFixtureRow> Fixtures { get; init; } = new List<MazakFixtureRow>();
public IReadOnlyList<NewMazakProgram> Programs { get; init; } = new List<NewMazakProgram>();
}
public interface IWriteData
{
MazakDbType MazakType { get; }
void Save(MazakWriteData data, string prefix);
}
} |
using Bridge.Contract;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem;
using System.Linq;
namespace Bridge.Translator.Lua
{
public class VisitorMethodBlock : AbstractMethodBlock
{
public VisitorMethodBlock(IEmitter emitter, MethodDeclaration methodDeclaration)
: base(emitter, methodDeclaration)
{
this.Emitter = emitter;
this.MethodDeclaration = methodDeclaration;
}
public MethodDeclaration MethodDeclaration
{
get;
set;
}
protected override void DoEmit()
{
this.VisitMethodDeclaration(this.MethodDeclaration);
}
protected void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
foreach (var attrSection in methodDeclaration.Attributes)
{
foreach (var attr in attrSection.Attributes)
{
var rr = this.Emitter.Resolver.ResolveNode(attr.Type, this.Emitter);
if (rr.Type.FullName == "Bridge.ExternalAttribute" || rr.Type.FullName == "Bridge.IgnoreAttribute")
{
return;
}
else if (rr.Type.FullName == "Bridge.InitAttribute")
{
int initPosition = 0;
if (attr.HasArgumentList)
{
if (attr.Arguments.Any())
{
var argExpr = attr.Arguments.First();
var argrr = this.Emitter.Resolver.ResolveNode(argExpr, this.Emitter);
if (argrr.ConstantValue is int)
{
initPosition = (int)argrr.ConstantValue;
}
}
}
if (initPosition > 0)
{
return;
}
}
}
}
//this.EnsureComma();
this.EnsureNewLine();
this.ResetLocals();
var prevMap = this.BuildLocalsMap();
var prevNamesMap = this.BuildLocalsNamesMap();
this.AddLocals(methodDeclaration.Parameters, methodDeclaration.Body);
var typeDef = this.Emitter.GetTypeDefinition();
var overloads = OverloadsCollection.Create(this.Emitter, methodDeclaration);
XmlToJsDoc.EmitComment(this, this.MethodDeclaration);
string name = overloads.GetOverloadName();
TransformCtx.CurClassMethodNames.Add(new TransformCtx.MethodInfo() {
Name = name,
IsPrivate = methodDeclaration.HasModifier(Modifiers.Private),
});
this.Write(name);
this.WriteEqualsSign();
/*
if (methodDeclaration.TypeParameters.Count > 0)
{
this.WriteFunction();
this.EmitTypeParameters(methodDeclaration.TypeParameters, methodDeclaration);
this.WriteSpace();
this.BeginBlock();
this.WriteReturn(true);
this.Write("Bridge.fn.bind(this, ");
}*/
this.WriteFunction();
this.EmitMethodParameters(methodDeclaration.Parameters, methodDeclaration, true);
if(methodDeclaration.TypeParameters.Count > 0) {
if(methodDeclaration.Parameters.Count > 0 || !methodDeclaration.HasModifier(Modifiers.Static)) {
this.WriteComma();
}
this.EmitTypeParameters(methodDeclaration.TypeParameters, methodDeclaration);
}
this.WriteCloseParentheses();
this.WriteSpace();
if(methodDeclaration.HasModifier(Modifiers.Async)) {
new AsyncBlock(this.Emitter, methodDeclaration).Emit();
}
else {
this.BeginFunctionBlock();
bool isYieldExists = YieldBlock.HasYield(methodDeclaration.Body);
IType yieldReturnType = null;
if(isYieldExists) {
var returnResolveResult = this.Emitter.Resolver.ResolveNode(methodDeclaration.ReturnType, this.Emitter);
yieldReturnType = returnResolveResult.Type;
YieldBlock.EmitYield(this, yieldReturnType, methodDeclaration);
}
else {
this.ConvertParamsToReferences(methodDeclaration.Parameters);
}
MarkTempVars();
methodDeclaration.Body.AcceptVisitor(this.Emitter);
EmitTempVars();
if(isYieldExists) {
YieldBlock.EmitYieldReturn(this, yieldReturnType, methodDeclaration);
}
else {
PrimitiveType returnType = methodDeclaration.ReturnType as PrimitiveType;
if(returnType != null) {
if(returnType.KnownTypeCode == ICSharpCode.NRefactory.TypeSystem.KnownTypeCode.Void) {
string refArgsString = GetRefArgsString(this.Emitter, methodDeclaration);
if(refArgsString != null) {
this.WriteReturn(true);
this.Write(refArgsString);
this.WriteNewLine();
}
}
}
}
this.EndFunctionBlock();
}
/*
if (methodDeclaration.TypeParameters.Count > 0)
{
this.Write(");");
this.WriteNewLine();
this.EndBlock();
}*/
this.ClearLocalsMap(prevMap);
this.ClearLocalsNamesMap(prevNamesMap);
this.Emitter.Comma = true;
}
public static string GetRefArgsString(IEmitter Emitter, MethodDeclaration methodDeclaration) {
var sb = new System.Text.StringBuilder();
bool isFirst = true;
foreach(var item in methodDeclaration.Parameters) {
if(item.ParameterModifier == ParameterModifier.Out || item.ParameterModifier == ParameterModifier.Ref) {
if(isFirst) {
isFirst = false;
}
else {
sb.Append(", ");
}
string itemName = Emitter.LocalsMap[item.Name];
sb.Append(itemName);
}
}
return sb.Length > 0 ? sb.ToString(): null;
}
}
}
|
namespace Nest.Linq.Internals
{
public enum JoinOperation
{
AndAlso,
OrElse
}
}
|
using System.CodeDom;
using System.Web.Compilation;
namespace System.Web.WebPages.Razor
{
internal sealed class AssemblyBuilderWrapper : IAssemblyBuilder
{
public AssemblyBuilderWrapper(AssemblyBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
InnerBuilder = builder;
}
internal AssemblyBuilder InnerBuilder { get; set; }
public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)
{
InnerBuilder.AddCodeCompileUnit(buildProvider, compileUnit);
}
public void GenerateTypeFactory(string typeName)
{
InnerBuilder.GenerateTypeFactory(typeName);
}
}
}
|
// Needed for NET40
#pragma warning disable CA1812 // Avoid uninstantiated internal classes
// ReSharper disable ImplicitlyCapturedClosure
using System;
namespace Theraot.Collections
{
internal sealed class ProgressorProxy
{
private readonly IClosable _node;
public ProgressorProxy(IClosable node)
{
_node = node ?? throw new ArgumentNullException(nameof(node));
}
public bool IsClosed => _node.IsClosed;
}
} |
using Microsoft.VisualStudio.ConnectedServices;
namespace Contoso.Samples.ConnectedServices.UITemplates.SinglePage.ViewModels
{
internal class AuthenticatorViewModel : ConnectedServiceAuthenticator
{
public AuthenticatorViewModel()
{
this.View = new Views.AuthenticatorView();
this.View.DataContext = this;
}
}
}
|
//Copyright (c) 2018 Yardi Technology Limited. Http://www.kooboo.com
//All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kooboo.IndexedDB
{
public interface IObjectStore
{
string Name { get; set; }
string ObjectFolder { get; set; }
int Count();
void Close();
void DelSelf();
void Flush();
Database OwnerDatabase { get; set; }
bool add(object key, object value);
bool update(object key, object value);
void delete(object key);
object get(object key);
List<object> List(int count = 9999, int skip = 0);
void RollBack(LogEntry log);
void RollBack(List<LogEntry> loglist);
void RollBack(Int64 LastVersionId, bool SelfIncluded = true);
void RollBackTimeTick(Int64 TimeTick, bool SelfIncluded = true);
void CheckOut(Int64 VersionId, IObjectStore DestinationStore, bool SelfIncluded = true);
void CheckOut(List<LogEntry> logs, IObjectStore DestinationStore);
int getLength(long blockposition);
}
}
|
using System.Collections.Generic;
using HotChocolate.Resolvers;
namespace HotChocolate.Data.Sorting
{
public interface ISortProvider
{
IReadOnlyCollection<ISortFieldHandler> FieldHandlers { get; }
IReadOnlyCollection<ISortOperationHandler> OperationHandlers { get; }
FieldMiddleware CreateExecutor<TEntityType>(NameString argumentName);
}
}
|
using System.Diagnostics.CodeAnalysis;
#nullable enable
namespace EFT.Trainer.Extensions
{
public static class ThrowableExtensions
{
public static bool IsValid([NotNullWhen(true)] this Throwable? throwable)
{
return throwable != null
&& throwable.transform != null;
}
}
}
|
using System;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Wcf.Demonstration.WcfService;
using Wcf.Tracker;
namespace Wcf.Demonstration
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
// TODO MVVM
public partial class MainWindow
{
private IService _service;
private readonly Uri _hostUri = new Uri("net.tcp://127.0.0.1:60000");
private int _sumValue;
public MainWindow()
{
InitializeComponent();
Init();
}
private void Init()
{
ValueBefore.Content = _sumValue;
// Simple Server
var serviceHost = new ServiceHost(typeof(Service));
serviceHost.AddServiceEndpoint(typeof(IService), new NetTcpBinding(), _hostUri);
serviceHost.Open();
// Simple client
var factory = new ChannelFactory<IService>(new NetTcpBinding()).AttachTracker();
_service = factory.CreateChannel(new EndpointAddress(_hostUri));
}
private void button_Click(object sender, RoutedEventArgs e)
{
ValueBefore.Content = _sumValue;
SummResult.Content = _sumValue = _service.Sum(_sumValue, 5);
}
private void MainWindow_OnKeyDown(object sender, KeyEventArgs args)
{
if (args.IsRepeat)
{
return;
}
var keyboard = args.KeyboardDevice;
if ((keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Alt)) != ModifierKeys.None &&
keyboard.IsKeyDown(Key.L))
{
LogService.ShowWindow();
}
}
private void button_Click_1(object sender, RoutedEventArgs e)
{
LogService.ShowWindow();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var r = new Random();
var size = r.Next(64, 1024);
var preparedArray = new byte[size];
for (int i = 0; i < preparedArray.Length; i++)
{
preparedArray[i] = (byte)r.Next(0, 128);
}
RandomByteSize.Content = $"Sent {_service.SendBytes(preparedArray)} bytes";
}
}
} |
using System.ComponentModel;
namespace NMockaroo.Attributes
{
/// <summary>
/// Represents the Mockaroo Formula type
/// <see cref="https://www.mockaroo.com/api/docs#type_formula" />
/// </summary>
public class MockarooFormulaAttribute : MockarooInfoAttribute
{
/// <summary>
/// The string value representing the formula
/// </summary>
public string Value { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Solutions.Skills;
namespace PointOfInterestSkill
{
public class FindPointOfInterestDialog : PointOfInterestSkillDialog
{
public FindPointOfInterestDialog(
SkillConfiguration services,
IStatePropertyAccessor<PointOfInterestSkillState> accessor,
IServiceManager serviceManager)
: base(nameof(FindPointOfInterestDialog), services, accessor, serviceManager)
{
var findPointOfInterest = new WaterfallStep[]
{
GetPointOfInterestLocations,
ResponseToGetRoutePrompt,
};
// Define the conversation flow using a waterfall model.
AddDialog(new WaterfallDialog(Action.FindPointOfInterest, findPointOfInterest));
AddDialog(new RouteDialog(services, Accessor, ServiceManager));
// Set starting dialog for component
InitialDialogId = Action.FindPointOfInterest;
}
}
}
|
namespace DeviceIOControlLib.Objects.FileSystem
{
public class FileExtentInfo
{
/// <summary>
/// Position in file
/// </summary>
public ulong Vcn { get; set; }
/// <summary>
/// Position on disk
/// </summary>
public ulong Lcn { get; set; }
/// <summary>
/// Size in # of clusters
/// </summary>
public ulong Size { get; set; }
}
} |
using System;
using Newtonsoft.Json.Linq;
namespace WebAPI.JsonTranslation
{
public interface IJsonTranslatorStrategy
{
Type TargetType { get; }
string[] SupportedProperties { get; }
void WriteObjectToJson(object target, JObject output);
void VerifyJsonUpdate(object target, JObject input);
void UpdateObjectFromJson(object target, JObject input);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NuGet.Packaging;
namespace NuGetPe
{
public static class PackageBuilderExtensions
{
public static IPackage Build(this PackageBuilder builder)
{
return new SimplePackage(builder);
}
}
}
|
using Xunit.Abstractions;
namespace ExRam.Gremlinq.Core.Tests
{
public sealed class InlinedGroovyGremlinQuerySerializationTest : QuerySerializationTest
{
public InlinedGroovyGremlinQuerySerializationTest(ITestOutputHelper testOutputHelper) : base(
GremlinQuerySource.g.ConfigureEnvironment(_ => _
.UseSerializer(GremlinQuerySerializer.Default.ToGroovy(GroovyFormatting.AllowInlining))),
testOutputHelper)
{
}
}
} |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.WordApi
{
/// <summary>
/// DispatchInterface ContentControl
/// SupportByVersion Word, 12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff821215.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
[TypeId("EE95AFE3-3026-4172-B078-0E79DAB5CC3D")]
public interface ContentControl : ICOMObject
{
#region Properties
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff845327.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Application Application { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193736.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
Int32 Creator { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840017.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16), ProxyResult]
object Parent { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839788.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Range Range { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff835775.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
bool LockContentControl { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822956.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
bool LockContents { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193642.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.XMLMapping XMLMapping { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff192401.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Enums.WdContentControlType Type { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194660.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.ContentControlListEntries DropdownListEntries { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194687.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.BuildingBlock PlaceholderText { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194027.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
string Title { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff845679.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
string DateDisplayFormat { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195729.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
bool MultiLine { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822193.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.ContentControl ParentContentControl { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197494.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
bool Temporary { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff192748.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
string ID { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff191954.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
bool ShowingPlaceholderText { get; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838048.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Enums.WdContentControlDateStorageFormat DateStorageFormat { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff198199.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Enums.WdBuildingBlockTypes BuildingBlockType { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838162.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
string BuildingBlockCategory { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193973.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Enums.WdLanguageID DateDisplayLocale { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff820775.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
object DefaultTextStyle { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196651.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
NetOffice.WordApi.Enums.WdCalendarType DateCalendarType { get; set; }
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195293.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
string Tag { get; set; }
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194593.aspx </remarks>
[SupportByVersion("Word", 14,15,16)]
bool Checked { get; set; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj227730.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
NetOffice.WordApi.Enums.WdColor Color { get; set; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj227646.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
NetOffice.WordApi.Enums.WdContentControlAppearance Appearance { get; set; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj229832.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
NetOffice.WordApi.Enums.WdContentControlLevel Level { get; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj231663.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
NetOffice.WordApi.RepeatingSectionItemColl RepeatingSectionItems { get; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj230582.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
string RepeatingSectionItemTitle { get; set; }
/// <summary>
/// SupportByVersion Word 15,16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/jj229741.aspx </remarks>
[SupportByVersion("Word", 15, 16)]
bool AllowInsertDeleteSection { get; set; }
#endregion
#region Methods
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838347.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
void Copy();
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836258.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
void Cut();
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194849.aspx </remarks>
/// <param name="deleteContents">optional bool DeleteContents = false</param>
[SupportByVersion("Word", 12,14,15,16)]
void Delete(object deleteContents);
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194849.aspx </remarks>
[CustomMethod]
[SupportByVersion("Word", 12,14,15,16)]
void Delete();
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838691.aspx </remarks>
/// <param name="buildingBlock">optional NetOffice.WordApi.BuildingBlock BuildingBlock = 0</param>
/// <param name="range">optional NetOffice.WordApi.Range Range = 0</param>
/// <param name="text">optional string Text = </param>
[SupportByVersion("Word", 12,14,15,16)]
[KnownIssue]
void SetPlaceholderText(object buildingBlock, object range, object text);
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838691.aspx </remarks>
[CustomMethod]
[SupportByVersion("Word", 12,14,15,16)]
[KnownIssue]
void SetPlaceholderText();
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838691.aspx </remarks>
/// <param name="buildingBlock">optional NetOffice.WordApi.BuildingBlock BuildingBlock = 0</param>
[CustomMethod]
[SupportByVersion("Word", 12,14,15,16)]
[KnownIssue]
void SetPlaceholderText(object buildingBlock);
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff838691.aspx </remarks>
/// <param name="buildingBlock">optional NetOffice.WordApi.BuildingBlock BuildingBlock = 0</param>
/// <param name="range">optional NetOffice.WordApi.Range Range = 0</param>
[CustomMethod]
[SupportByVersion("Word", 12,14,15,16)]
[KnownIssue]
void SetPlaceholderText(object buildingBlock, object range);
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195895.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
void Ungroup();
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197558.aspx </remarks>
/// <param name="characterNumber">Int32 characterNumber</param>
/// <param name="font">optional string Font = </param>
[SupportByVersion("Word", 14,15,16)]
void SetCheckedSymbol(Int32 characterNumber, object font);
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197558.aspx </remarks>
/// <param name="characterNumber">Int32 characterNumber</param>
[CustomMethod]
[SupportByVersion("Word", 14,15,16)]
void SetCheckedSymbol(Int32 characterNumber);
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836974.aspx </remarks>
/// <param name="characterNumber">Int32 characterNumber</param>
/// <param name="font">optional string Font = </param>
[SupportByVersion("Word", 14,15,16)]
void SetUncheckedSymbol(Int32 characterNumber, object font);
/// <summary>
/// SupportByVersion Word 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836974.aspx </remarks>
/// <param name="characterNumber">Int32 characterNumber</param>
[CustomMethod]
[SupportByVersion("Word", 14,15,16)]
void SetUncheckedSymbol(Int32 characterNumber);
#endregion
}
}
|
using System;
public class Hanoi
{
public class Stack
{
public int size;
public int top;
public int[] array;
}
Stack createStack(int size)
{
Stack stack = new Stack();
stack.size = size;
stack.top = -1;
stack.array = new int[size];
return stack;
}
Boolean isFull(Stack stack)
{
return (stack.top == stack.size - 1);
}
Boolean isEmpty(Stack stack)
{
return (stack.top == -1);
}
void push(Stack stack, int item)
{
if (isFull(stack))
return;
stack.array[++stack.top] = item;
}
int pop(Stack stack)
{
if (isEmpty(stack))
return int.MinValue;
return stack.array[stack.top--];
}
void move_disk(Stack src, Stack dest, int from, int to)
{
int home_top = pop(src);
int center_top = pop(dest);
if (home_top == int.MinValue)
{
push(src, center_top);
print_move(to, from, center_top);
}
else if (center_top == int.MinValue)
{
push(dest, home_top);
print_move(from, to, home_top);
}
else if (home_top > center_top)
{
push(src, home_top);
push(src, center_top);
print_move(to, from, center_top);
}
else
{
push(dest, center_top);
push(dest, home_top);
print_move(from, to, home_top);
}
}
void print_move(int src, int dest, int disk)
{
Console.WriteLine("Move disk " + disk + " from post " + src + " to " + dest);
return;
}
void solve(int n, Stack src, Stack dest, Stack aux)
{
int i, num_moves;
int home = 1, center = 2, end = 3;
num_moves = (int)(Math.Pow(2, n) - 1);
for (i = n; i >= 1; i--)
push(src, i);
for (i = 1; i <= num_moves; i++)
{
if (i % 3 == 0)
move_disk(aux, dest, end, center);
else if (i % 3 == 1)
move_disk(src, dest, home, center);
else if (i % 3 == 2)
move_disk(src, aux, home, end);
}
}
public static void Main(String[] args)
{
int n = 3;
Console.WriteLine("Enter number of rings: ");
n = Convert.ToInt32(Console.ReadLine());
Hanoi tower = new Hanoi();
Stack src, dest, aux;
src = tower.createStack(n);
dest = tower.createStack(n);
aux = tower.createStack(n);
tower.solve(n, src, dest, aux);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.