text stringlengths 13 6.01M |
|---|
using System;
namespace SymbolicMath
{
class Program
{
static void Main(string[] args)
{
Expression a = new Constant(MathUtil.degreeToRadian(90));
Expression b = new Constant(MathUtil.degreeToRadian(45));
Expression e = new Constant(Math.E);
Expression sin = new Sin(a);
Expression cos = new Cos(b);
Expression tg = new Tg(b);
Expression ln = new Ln(e);
Expression exp = new Exp(e);
Expression ctg = new Ctg(b);
Expression p = new Constant(2);
Expression q = new Constant(5);
Expression add = new Add(ln, q);
Expression sub = new Subsctract(p, q);
Expression mult = new Mult(p, q);
Expression div = new Div(p, q);
Expression pow = new Pow(q, p);
double[] coef = new double[] {2, 3, 0, 0.5};
Expression polinomial = new Polynomial(q, coef);
print(sin);
print(cos);
print(tg);
print(ln);
print(exp);
print(ctg);
print(add);
print(sub);
print(mult);
print(div);
print(pow);
print(polinomial);
}
static void print(Expression exp) {
Console.Write($"{exp.toString()} = {exp.calc()}\n");
}
}
}
|
using Xunit;
using Prime.Services;
namespace Tests
{
public class PrimeService_IsPrimeShould
{
private readonly PrimeService _primeService;
public PrimeService_IsPrimeShould()
{
_primeService = new PrimeService();
}
[Fact]
public void ReturnFalseGivenValueOf1()
{
var result = _primeService.IsPrime(1);
Assert.False(result, "1 not a prime");
}
[Fact]
public void ReturnFalseGivenValueOf87()
{
var result = _primeService.IsPrime(87);
Assert.False(result, "87 is not a prime");
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(1)]
public void ReturnFalseGivenValuesLessThan2(int value)
{
var result = _primeService.IsPrime(value);
Assert.False(result, $"{value} should not be prime");
}
[InlineData(11)]
[InlineData(13)]
[InlineData(17)]
[InlineData(19)]
[InlineData(23)]
[InlineData(29)]
[InlineData(31)]
[InlineData(37)]
[InlineData(83)]
[InlineData(997)]
[InlineData(991)]
[InlineData(983)]
[InlineData(977)]
[InlineData(971)]
[InlineData(967)]
public void ReturnTrueGivenValuesIsPrime(int value)
{
var result = _primeService.IsPrime(value);
Assert.True(result, $"{value} should BE prime");
}
}
} |
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using DataAccess;
namespace Business {
[PropertyChanged.ImplementPropertyChanged]
[Serializable()]
public class MediaEncoderSettings : ICloneable {
public bool ConvertToAvi { get; set; }
public string FileName { get; set; }
[DefaultValue(null)]
public double? Position { get; set; }
[DefaultValue(null)]
public int? SourceHeight { get; set; }
[DefaultValue(null)]
public int? SourceWidth { get; set; }
public double SourceAspectRatio { get; set; }
[DefaultValue(null)]
public double? SourceFrameRate { get; set; }
private bool audioRequiresMkv;
public bool AudioRequiresMkv {
get { return audioRequiresMkv; }
set {
audioRequiresMkv = value;
if (value && !ignoreAudio)
EncodeMp4 = false;
}
}
public bool FixColors { get; set; }
public bool DoubleNNEDI3Before { get; set; }
public bool DoubleEEDI3 { get; set; }
public bool DoubleNNEDI3 { get; set; }
public bool Resize { get; set; }
public int ResizeHeight { get; set; }
public bool Denoise { get; set; }
public int DenoiseStrength { get; set; }
public int DenoiseSharpen { get; set; }
public bool SharpenAfterDouble { get; set; }
public int SharpenAfterDoubleStrength { get; set; }
public bool SharpenFinal { get; set; }
public int SharpenFinalStrength { get; set; }
public bool IncreaseFrameRate { get; set; }
public FrameRateModeEnum IncreaseFrameRateValue { get; set; }
public int EncodeQuality { get; set; }
public bool Crop { get; set; }
public int CropLeft { get; set; }
public int CropTop { get; set; }
public int CropRight { get; set; }
public int CropBottom { get; set; }
private bool trim = false;
public bool Trim {
get { return trim; }
set {
trim = value;
if (value)
IgnoreAudio = true;
}
}
[DefaultValue(null)]
public int? TrimStart { get; set; }
[DefaultValue(null)]
public int? TrimEnd { get; set; }
private bool changeSpeed;
public bool ChangeSpeed {
get { return changeSpeed; }
set {
changeSpeed = value;
if (value)
IgnoreAudio = true;
}
}
public int ChangeSpeedValue { get; set; }
private bool ignoreAudio;
public bool IgnoreAudio {
get { return ignoreAudio; }
set {
ignoreAudio = value;
if (!ignoreAudio) {
Trim = false;
ChangeSpeed = false;
if (audioRequiresMkv)
EncodeMp4 = false;
}
}
}
public bool EncodeMp4 { get; set; }
public string CustomScript { get; set; }
public int JobIndex { get; set; }
public MediaEncoderSettings() {
ConvertToAvi = true;
SourceAspectRatio = 1;
ResizeHeight = 720;
EncodeQuality = 25;
DenoiseStrength = 20;
SharpenFinalStrength = 3;
ChangeSpeedValue = 100;
}
public bool CanEncodeMp4 {
get {
return !AudioRequiresMkv || ignoreAudio;
}
}
public bool HasFileName {
get { return !string.IsNullOrEmpty(FileName); }
}
public string ScriptFile {
get { return Settings.TempFilesPath + string.Format("Job{0}_Script.avs", JobIndex); }
}
public string SettingsFile {
get { return Settings.TempFilesPath + string.Format("Job{0}_Settings.xml", JobIndex); }
}
public string InputFile {
get {
if (ConvertToAvi)
return Settings.TempFilesPath + string.Format("Job{0}_Input.avi", JobIndex);
else
return Settings.NaturalGroundingFolder + FileName;
}
}
public string OutputFile {
get { return Settings.TempFilesPath + string.Format("Job{0}_Output.mp4", JobIndex); }
}
public string FinalFile {
get { return Settings.TempFilesPath + string.Format("Job{0}_Final.{1}", JobIndex, EncodeMp4 ? "mp4" : "mkv"); }
}
public object Clone() {
return (MediaEncoderSettings)DataHelper.DeepClone(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameIsOn.Classes
{
public class Player
{
/// <summary>
/// Luokan sisällä toimivat ominaisuudet
/// </summary>
private string player_name;
private static string player_static_name;
private int player_points;
/// <summary>
/// Julkinen ominaisuus Player_name, jonka get - aksessori palauttaa string - tyyppisen arvon ja set - aksessori sijoittaa sille annetun arvon muuttujaan.
/// </summary>
public string Player_name
{
get
{
return player_name;
}
set
{
player_name = value;
}
}
/// <summary>
/// Julkinen ominaisuus Player_points, jonka get - aksessori palauttaa int - tyyppisen arvon ja set - aksessori sijoittaa sille annetun arvon muuttujaan.
/// </summary>
public int Player_points
{
get
{
return player_points;
}
set
{
player_points = value;
}
}
/// <summary>
/// Julkinen Set_player_static_name - metodi, joka sijoittaa metodille tuotavan string - tyyppisen arvon muuttujaan.
/// </summary>
/// <param name="value"></param>
public void Set_player_static_name(string value)
{
player_static_name = value;
}
/// <summary>
/// Julkinen Return_player_static_name - metodi, joka palauttaa string - tyyppisen arvon.
/// </summary>
/// <returns></returns>
public string Return_player_static_name()
{
return player_static_name;
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Org.Common.Web.HealthChecks
{
public class ApiHealthCheck : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
{
return HealthCheckResult.Healthy("Ping HealthCheck passed");
}
}
}
|
using System.Collections.Generic;
namespace Algorithms.Lib.Interfaces
{
public interface ITwoPartsWeighedGraph : IPrintable
{
IEnumerable<IPairNode> NodeXs { get; }
IEnumerable<IPairNode> NodeYs { get; }
IEnumerable<IPairNode> Nodes { get; }
IWeighedEdge GetEdge(IPairNode nodeX, IPairNode nodeY);
IEnumerable<IWeighedEdge> GetEdges(IPairNode node);
void AddEdge(IWeighedEdge edge);
}
} |
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace SampleUWP
{
public sealed partial class B01 : Page
{
public B01()
{
InitializeComponent();
//mainPage.HideDebugBar();
//mainPage.dM1 = "Testing debug message";
//mainPage.ShowDebugBar();
}
// Top Reset button
private void TopReset_Click(object sender, RoutedEventArgs e)
{
_ = sender; // Discard unused parameter.
_ = e; // Discard unused parameter.
sliderValueConverter.Value = 70;
}
// Bottom Reset button
private void BottomReset_Click(object sender, RoutedEventArgs e)
{
_ = sender; // Discard unused parameter.
_ = e; // Discard unused parameter.
sliderOneWayDataSource.Value = 10;
sliderTwoWayDataSource.Value = 50;
sliderOneTimeDataSource.Value = 100;
}
}
// For more information on Value Converters, see http://go.microsoft.com/fwlink/?LinkId=254639#data_conversions
public class S2Formatter : IValueConverter
{
//Convert the slider value into Grades
public object Convert(object value, System.Type type, object parameter, string language)
{
string _grade = string.Empty;
//try parsing the value to int
if (int.TryParse(value.ToString(), out int _value))
{
if (_value < 50)
_grade = "F";
else if (_value < 60)
_grade = "D";
else if (_value < 70)
_grade = "C";
else if (_value < 80)
_grade = "B";
else if (_value < 90)
_grade = "A";
else if (_value < 100)
_grade = "A+";
else if (_value == 100)
_grade = "SUPER STAR!";
}
return _grade;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, System.Type type, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
|
using System.Reflection;
using System.Xml;
using AutoFixture.Kernel;
namespace Leprechaun.Tests.Test.SpecimenBuilders
{
public class XmlNodeBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (!(request is ParameterInfo pi) || pi.ParameterType != typeof(XmlNode)) return new NoSpecimen();
var xmlDocument = new XmlDocument();
xmlDocument.Load(@"Leprechaun.config");
return xmlDocument;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Run
{
public partial class FrmRun : Form
{
public FrmRun()
{
InitializeComponent();
}
Thread hiloCarro01;
Thread hiloCarro02;
Thread hiloCarro03;
Int32 iPosicion = 0;
private void btnRun_Click(object sender, EventArgs e)
{
hiloCarro01 = new Thread(new ThreadStart(this.RunCarro01));
hiloCarro01.Start();
hiloCarro02 = new Thread(new ThreadStart(this.RunCarro02));
hiloCarro02.Start();
hiloCarro03 = new Thread(new ThreadStart(this.RunCarro03));
hiloCarro03.Start();
}
public void RunCarro01()
{
while (picCarro01.Left <= 950)
{
Random _random = new Random();
int x = _random.Next(0, 10);
this.Invoke((MethodInvoker)delegate
{
this.picCarro01.Left += x;
});
Thread.Sleep(50);
}
this.Invoke((MethodInvoker)delegate
{
iPosicion += 1;
lblPosicion01.Text = iPosicion.ToString();
this.picCarro01.Left = 950;
});
hiloCarro01.Abort();
}
public void RunCarro02()
{
while (picCarro02.Left <= 950)
{
Random _random = new Random();
int x = _random.Next(0, 10);
this.Invoke((MethodInvoker)delegate
{
this.picCarro02.Left += x;
});
Thread.Sleep(50);
}
this.Invoke((MethodInvoker)delegate
{
iPosicion += 1;
lblPosicion02.Text = iPosicion.ToString();
this.picCarro02.Left = 950;
});
hiloCarro02.Abort();
}
public void RunCarro03()
{
while (picCarro03.Left <= 950)
{
Random _random = new Random();
int x = _random.Next(0, 10);
this.Invoke((MethodInvoker)delegate
{
this.picCarro03.Left += x;
});
Thread.Sleep(50);
}
this.Invoke((MethodInvoker)delegate
{
iPosicion += 1;
lblPosicion03.Text = iPosicion.ToString();
this.picCarro03.Left = 950;
});
hiloCarro03.Abort();
}
}
}
|
namespace MvcApp.Web.Views.Home
{
using System.IO;
using System.Text;
using SimpleMVC.Interfaces.Generic;
using ViewModels;
public class Index : IRenderable<SignedViewModel>
{
public SignedViewModel Model { get; set; }
public string Render()
{
StringBuilder builder = new StringBuilder();
builder.Append(File.ReadAllText(Constants.ContentPath + "header.html"));
if (string.IsNullOrEmpty(this.Model.Username))
{
builder.Append(File.ReadAllText(Constants.ContentPath + "menu.html"));
}
else
{
builder.Append(string.Format(File.ReadAllText(Constants.ContentPath + "menu-logged.html"),
this.Model.ToString()));
}
builder.Append(File.ReadAllText(Constants.ContentPath + "home.html"));
builder.Append(File.ReadAllText(Constants.ContentPath + "footer.html"));
return builder.ToString();
}
}
}
|
/* The MIT License (MIT)
*
* Copyright (c) 2018 Marc Clifton
*
* 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.
*/
/* Code Project Open License (CPOL) 1.02
* https://www.codeproject.com/info/cpol10.aspx
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Clifton.Core.ExtensionMethods;
namespace Clifton.Meaning
{
public class ContextNode
{
// Must be explicitly marked as JsonProperty because we are using a protected/private setter.
[JsonProperty] public Guid InstanceId { get; protected set; }
[JsonProperty] public Type Type { get; protected set; }
[JsonProperty(TypeNameHandling = TypeNameHandling.Objects)] public ContextNode Parent { get; protected set; }
public ContextValue ContextValue { get; set; } // setter should probably only be used internally.
public IReadOnlyList<ContextNode> Children { get { return children; } }
public List<string> DebugChidrenTypeNames { get { return children.Select(c => c.Type.Name).ToList(); } }
public static ContextNode Root { get { return new ContextNode(); } }
protected List<ContextNode> children = new List<ContextNode>();
protected ContextNode()
{
}
public ContextNode(Guid instanceId, Type t)
{
InstanceId = instanceId;
Type = t;
}
public void Clear()
{
children.Clear();
}
public void AddChild(ContextNode node)
{
children.Add(node);
node.Parent = this;
}
public bool HasChild(Guid id)
{
return children.Any(child => child.InstanceId == id);
}
/// <summary>
/// The parent instance chain from this child, including this child's ID.
/// </summary>
public List<Guid> GetParentInstancePath()
{
List<Guid> path = new List<Guid>();
path.Add(InstanceId);
ContextNode parentNode = Parent;
while (parentNode != null)
{
path.Insert(0, parentNode.InstanceId);
parentNode = parentNode.Parent;
}
return path.Skip(1).ToList(); // Exclude the Guid.Empty root.
}
/// <summary>
/// Walk the child instance graph.
/// </summary>
public List<List<Guid>> ChildInstancePaths()
{
// There's probably a way to do this with iterators and yield return, but it's too complicated for me to figure out!
List<List<Guid>> allPaths = new List<List<Guid>>();
List<Guid> idpath = new List<Guid>();
idpath.Add(InstanceId);
Walk(children, idpath, allPaths);
return allPaths;
}
protected void Walk(List<ContextNode> children, List<Guid> idpath, List<List<Guid>> allPaths)
{
if (children.Count == 0)
{
// Make a copy as we're manipulating the original!
allPaths.Add(idpath.ToList());
}
else
{
foreach (var cn in children)
{
idpath.Add(cn.InstanceId);
Walk(cn.children, idpath, allPaths);
idpath.RemoveLast();
}
}
}
}
}
|
using System.Linq;
using System.Collections.Generic;
using System;
namespace StringReplicator.Core.Infrastructure
{
public enum DataBaseType
{
SqlServer=1,
NotSqlServer=2
}
} |
namespace CheckIt.Syntax
{
public interface IReference
{
string Name { get; }
}
} |
using System;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog;
using NLog.StructuredLogging.Json;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Org.Common.Web.Logging
{
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly LoggingOptions _options;
private readonly ILoggerFactory _loggerFactory;
public const string ResponseIdHeaderName = "X-Request-Id";
public RequestLoggingMiddleware(RequestDelegate next, IOptions<LoggingOptions> options, ILoggerFactory loggerFactory)
{
_options = options.Value;
_next = next;
_loggerFactory = loggerFactory;
}
public async Task Invoke(HttpContext context)
{
var requestId = Guid.NewGuid();
context.Response.Headers.Append(ResponseIdHeaderName, requestId.ToString());
var startTime = DateTime.UtcNow;
var originalBody = context.Response.Body;
await using var responseRewindStream = new MemoryStream();
await using var requestRewindStream = new MemoryStream();
try
{
if (context.Request.Body != null && context.Request.Body.CanRead)
{
await context.Request.Body?.CopyToAsync(requestRewindStream);
requestRewindStream.Seek(0, SeekOrigin.Begin);
context.Request.Body = requestRewindStream;
}
context.Response.Body = responseRewindStream;
await _next(context);
responseRewindStream.Position = 0;
await responseRewindStream.CopyToAsync(originalBody);
}
finally
{
context.Response.Body = originalBody;
}
var logModel = new RequestLogModel(context)
{
AppZone = _options.AppZone,
StartTime = startTime,
EndTime = DateTime.UtcNow,
};
MediaTypeHeaderValue.TryParse(context.Response.ContentType, out var responseType);
if (responseType?.MediaType == "application/json")
{
responseRewindStream.Seek(0, SeekOrigin.Begin);
using var reader = new StreamReader(responseRewindStream);
logModel.ResponseBody = await reader.ReadToEndAsync();
}
if (context.Request.ContentType?.Equals("application/json", StringComparison.InvariantCultureIgnoreCase) ?? false)
{
requestRewindStream.Seek(0, SeekOrigin.Begin);
using var reader = new StreamReader(requestRewindStream);
logModel.RequestBody = await reader.ReadToEndAsync();
}
_loggerFactory.CreateLogger<RequestLoggingMiddleware>().LogInformation("{@request}", logModel);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HotelReservationSystem.Models
{
public class CommanClass
{
public Room room { get; set; }
public RoomFacility roomfacility { get; set; }
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Ideal.Ipos.RealTime.Skat.Model {
public class Spieler {
public Spieler(string id, string name) {
this.ID = id;
this.Name = name;
}
[JsonProperty(PropertyName = "id")]
public string ID {
get;
private set;
}
[JsonProperty(PropertyName = "name")]
public string Name {
get;
private set;
}
[JsonIgnore]
public string ConnectionID {
get;
set;
}
}
} |
using Dwjk.Dtp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using trade.client.Trade;
using trade.client.UIUtils;
using static Dwjk.Dtp.QueryPositionResponse.Types;
namespace trade.client
{
public partial class FrmQueryPositions : Form
{
private DefaultGridView<PositionDetail> _Grid;
private QueryPagination _NextPage;
public string Code { set; get; }
public Exchange Exchange { set; get; }
public FrmQueryPositions()
{
InitializeComponent();
_Grid = new DefaultGridView<PositionDetail>(Grid);
_NextPage = new QueryPagination
{
Size = (uint)PageSize.Value,
Offset = 0,
};
}
private void BtnQuery_Click(object sender, EventArgs e)
{
RefreshQuery();
}
private void RefreshQuery()
{
InitQueryParams();
QueryAsync();
}
private void InitQueryParams()
{
_NextPage.Size = (uint)PageSize.Value;
_NextPage.Offset = 0;
Exchange = TradeDict.Exchange[cboExchange.Text];
Code = txtCode.Text;
_Grid.Clear();
}
private void QueryAsync()
{
Thread thread = new Thread(new ThreadStart(Query));
thread.Start();
}
private void Query()
{
var positions = accountToolbar.Current?.QueryPositions(
exchange: Exchange,
code: Code,
pagination: _NextPage
);
if (positions == null || positions.PositionList.Count() == 0)
{
MessageBox.Show("没有了!");
return;
};
if (positions.Pagination.Offset <= _NextPage.Offset) return;
_NextPage.Offset = positions.Pagination.Offset;
Invoke(
new MethodInvoker(() =>
{
_Grid.Add(positions.PositionList.ToList());
}));
}
private void FrmQueryPositions_Shown(object sender, EventArgs e)
{
RefreshQuery();
}
private void NextPage_Click(object sender, EventArgs e)
{
QueryAsync();
}
}
}
|
using EduHome.Models.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.Models.Entity
{
public class Contact:BaseEntity
{
public List<PostMessage> PostMessages { get; set; }
public List<Address> Addresses { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace VandelayIndustries.ViewModels
{
public class TransactionAddModel
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int Seller { get; set; }
public int Buyer { get; set; }
public int SalesPerson { get; set; }
public List<int> Items { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vlc.DotNet.Core
{
public interface IChapterManagement
{
int Count { get; }
void Previous();
void Next();
int Current { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Bank_collections
{
public partial class LogInForm : Form
{
public LogInForm()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
if (e.KeyChar == (char)Keys.Enter)
textBox2.Focus();
return;
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
if (e.KeyChar == (char)Keys.Enter)
button1.Focus();
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using UnityEngine;
using System.Collections;
public enum GAME_SCENE{
TITLE,
STAGE_SELECT,
PLAY_GAME,
RESULT
};
public class GameMain : MonoBehaviour {
public static GAME_SCENE NowScene;
private GAME_SCENE BeforeScene;
// 各シーン
public GameObject Title;
public GameObject StageSelect;
public GameObject PlayGame;
public GameObject PlayGameUI;
public GameObject Result;
// ガイド
public GameObject GameGuide;
public static bool GuideFlag;
// 各パーティクル
public GameObject StageSelectParticle;
public GameObject PlayGameParticle;
public GameObject ResultParticle;
// Use this for initialization
void Start () {
NowScene = GAME_SCENE.TITLE;
}
// Update is called once per frame
void Update () {
switch (NowScene) {
case GAME_SCENE.TITLE:
PlayBGM.isPlayOpening = true;
Title.SetActive(true);
StageSelect.SetActive(false);
StageSelectParticle.SetActive(false);
PlayGame.SetActive(false);
PlayGameUI.SetActive(false);
PlayGameParticle.SetActive(false);
Result.SetActive(false);
ResultParticle.SetActive(false);
break;
case GAME_SCENE.STAGE_SELECT:
PlayBGM.isPlayOpening = true;
Title.SetActive(false);
StageSelect.SetActive(true);
StageSelectParticle.SetActive(true);
PlayGame.SetActive(false);
PlayGameUI.SetActive(false);
PlayGameParticle.SetActive(false);
Result.SetActive(false);
ResultParticle.SetActive(false);
break;
case GAME_SCENE.PLAY_GAME:
PlayBGM.isPlayGamePlay = true;
Title.SetActive(false);
StageSelect.SetActive(false);
StageSelectParticle.SetActive(false);
PlayGame.SetActive(true);
PlayGameUI.SetActive(true);
PlayGameParticle.SetActive(true);
Result.SetActive(false);
ResultParticle.SetActive(false);
break;
case GAME_SCENE.RESULT:
PlayBGM.isPlayGamePlay = true;
Title.SetActive(false);
StageSelect.SetActive(false);
StageSelectParticle.SetActive(false);
PlayGame.SetActive(false);
PlayGameUI.SetActive(false);
PlayGameParticle.SetActive(false);
Result.SetActive(true);
ResultParticle.SetActive(true);
break;
}
if (BeforeScene != NowScene) {
init ();
BackgroundDraw.DrawFlag = true;
}
BeforeScene = NowScene;
GameGuide.SetActive (GuideFlag);
}
void init(){
switch (NowScene) {
case GAME_SCENE.TITLE:
break;
case GAME_SCENE.STAGE_SELECT:
StageAction.isStart = true;
RollPage.isStart = true;
RollStage.isStart = true;
StageInfo.isStart = true;
break;
case GAME_SCENE.PLAY_GAME:
MapAction.isStart = true;
Player.isStart = true;
PlayerMove.isStart = true;
CameraAction.isStart = true;
break;
case GAME_SCENE.RESULT:
result.isStart = true;
break;
}
}
}
|
namespace Hanaby
{
using System;
using System.Collections.Generic;
using System.Linq;
enum ColorCard { White, Red, Green, Blue, Yellow}
internal class Card
{
internal ColorCard Color
{
get { return _color; }
}
ColorCard _color;
internal int Rank
{
get { return _rank; }
}
int _rank;
public bool VisibleColor
{
get { return _visibleColor; }
set { _visibleColor = value; }
}
bool _visibleColor;
public bool VisibleRank
{
get { return _visibleRank; }
set { _visibleRank = value; }
}
bool _visibleRank;
public Card(ColorCard color, int rank)
{
_color = color;
_rank = rank;
}
public bool IsNextAfter(Card currentCard)
{
return this.Rank - currentCard.Rank == 1;
}
public string ToStringForPlayer()
{
return (_visibleColor ? Color.ToString()[0] : '#') + (_visibleRank ? Rank.ToString() : "#");
}
public override string ToString()
{
return Color.ToString()[0]+Rank.ToString();
}
}
internal class Player
{
internal List<Card> CardsPlayer
{
get
{
if (_cardsPlayer == null)
throw new Exception("Колода игрока не существует");
return _cardsPlayer;
}
set { _cardsPlayer = value; }
}
List<Card> _cardsPlayer;
public int CountCardsPlayed
{
get { return _countCardsPlayed; }
set { _countCardsPlayed = value; }
}
int _countCardsPlayed;
public int CountRiskCardsPlayed
{
get { return _countRiskCardsPlayed; }
set { _countRiskCardsPlayed = value; }
}
int _countRiskCardsPlayed;
int _countCard;
public Player(int countCard,List<Card> deck)
{
if (deck.Count < countCard + 1)
throw new Exception("В колоде не хватает карт для раздачи");
_cardsPlayer = new List<Card>();
for (int i = 0; i < countCard; i++)
{
Card selectCard=deck[deck.Count-1];
_cardsPlayer.Add(selectCard);
deck.Remove(selectCard);
}
_countCard = countCard;
}
public bool DropCard(int numDropCart,List<Card> deck)
{
if (deck.Count < 2 || _cardsPlayer.Count<numDropCart || numDropCart<1)
return false;
_cardsPlayer.RemoveAt(numDropCart-1);
Card newCard = deck[deck.Count - 1];
_cardsPlayer.Add(newCard);
deck.Remove(newCard);
return true;
}
public bool AddCardFromDeck(List<Card> deck)
{
if (deck.Count < 2 || _cardsPlayer.Count==_countCard)
return false;
Card newCard = deck[deck.Count - 1];
_cardsPlayer.Add(newCard);
deck.Remove(newCard);
return true;
}
//Проверям, есть ли карта по такому номеру
public bool IsCardExist(int numCard)
{
return _cardsPlayer.Count >= numCard && numCard>0;
}
public override string ToString()
{
return "Кол-во успешно разыгранных карт: "+CountCardsPlayed.ToString()+'\n'+"Кол-во рискованных ходов: "+CountRiskCardsPlayed.ToString();
}
}
class Program
{
const int constCardInHand = 5;
const int constCardInDeck = 56;
static void NewGame()
{
//initialization
List<Card> deck = CreateCardDeck(constCardInDeck);
Player playerOne = new Player(constCardInHand, deck);
Player playerTwo = new Player(constCardInHand, deck);
Dictionary<char, List<Card>> table = new Dictionary<char, List<Card>>();
#region initializationDictionary
for (int indexColor = 0; indexColor < 5; indexColor++)
table[((ColorCard)indexColor).ToString()[0]] = new List<Card>();
#endregion
//очерёдность хода, если false, то ходит первый игрок
bool turnPlayer=false;
//если false, то gameover
bool statGame=false;
//если отличен от truePlayer, то ход прошёл успешно и следует сменить игрока
bool turnPlayerAfterCourse=false;
do
{
//вывод игрового поля на экран
ViewGameField(table, playerOne, playerTwo, deck.Count, turnPlayer);
if(table.All(p=>p.Value.Count==5))
{
Console.WriteLine("Больше нельзя сделать ход");
Console.ReadKey(true);
break;
}
//выбор действия игрока
Console.WriteLine("Выберете действие");
Console.WriteLine("1. Разыграть карту");
Console.WriteLine("2. Сбросить карту");
Console.WriteLine("3. Подсказать цвет");
Console.WriteLine("4. Подсказать наименование");
//Сохранение очерёдности хода до самого хода
turnPlayerAfterCourse = turnPlayer;
#region SwitchForSelectGameVariantCorse
switch (Console.ReadKey(true).KeyChar)
{
case '1':
ViewGameField(table, playerOne, playerTwo, deck.Count, turnPlayer);
ConsoleRunPlayCard(ref statGame, ref turnPlayer, turnPlayer ? playerTwo : playerOne, deck, table);
break;
case '2':
ViewGameField(table, playerOne, playerTwo, deck.Count, turnPlayer);
ConsoleRunDropCard(ref statGame, ref turnPlayer,turnPlayer ? playerTwo: playerOne, deck);
break;
case '3':
ViewGameField(table, playerOne, playerTwo, deck.Count, turnPlayer);
ConsoleRunPromtColor(ref statGame, ref turnPlayer, playerOne, playerTwo);
break;
case '4':
ViewGameField(table, playerOne, playerTwo, deck.Count, turnPlayer);
ConsoleRunPromtRank(ref statGame, ref turnPlayer, playerOne, playerTwo);
break;
default:
statGame = true;
break;
}
#endregion
if (deck.Count <= 1)
break;
//Запрос клавиши при смене игрока
if(statGame&&(turnPlayer!=turnPlayerAfterCourse))
{
Console.WriteLine("Для смены игрока нажмите любую клавишу");
Console.ReadKey(true);
}
} while (statGame);
ViewGameOver(playerOne,playerTwo);
}
static void About()
{
Console.Clear();
Console.WriteLine("Нумерация карт начинается с единицы");
Console.ReadKey(true);
Console.Clear();
}
#region NewGameSubMethods
#region IOConsoleGameVariantCourse
static void ConsoleRunPlayCard(ref bool statGame, ref bool turnPlayer, Player player, List<Card> deck, Dictionary<char, List<Card>> table)
{
int selectedNumCard;
Console.WriteLine("Введите номер карты: ");
try
{
selectedNumCard = int.Parse(Console.ReadKey(true).KeyChar.ToString());
}
catch
{
statGame = true;
return;
}
if (player.IsCardExist(selectedNumCard))
{
statGame = PlayCard(player.CardsPlayer[selectedNumCard - 1], player, deck, table);
turnPlayer = !turnPlayer;
}
else
{
Console.WriteLine("Карты с таким номером не существует у вас в руке");
statGame = true;
}
}
static void ConsoleRunDropCard(ref bool statGame, ref bool turnPlayer, Player player, List<Card> deck)
{
int selectedNumCard;
Console.WriteLine("Введите номер карты: ");
try
{
selectedNumCard = int.Parse(Console.ReadKey(true).KeyChar.ToString());
}
catch
{
// selectedNumCard = -1;
statGame = true;
return;
}
if (player.IsCardExist(selectedNumCard))
{
statGame = player.DropCard(selectedNumCard, deck);
turnPlayer = !turnPlayer;
}
else
{
Console.WriteLine("Карты с таким номером не существует у вас в руке");
statGame = true;
}
}
static void ConsoleRunPromtColor(ref bool statGame, ref bool turnPlayer, Player playerOne, Player playerTwo)
{
int numColorOrRank;
int[] selectedNumsCard;
Console.WriteLine("Введите номер цвета карты : ");
Console.WriteLine("1. White");
Console.WriteLine("2. Red");
Console.WriteLine("3. Green");
Console.WriteLine("4. Blue");
Console.WriteLine("5. Yellow");
try
{
numColorOrRank = int.Parse(Console.ReadKey(true).KeyChar.ToString());
if (numColorOrRank > 5)
{
statGame = true;
return;
}
}
catch
{
statGame = true;
return;
}
Console.WriteLine("Введите номера карт с {0} цветом (можно использовать пробел как разделитель)", ((ColorCard)numColorOrRank - 1).ToString());
string inputString = Console.ReadLine();
try
{
inputString = inputString.Replace(" ", "");
selectedNumsCard = new int[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
selectedNumsCard[i] = int.Parse(inputString[i].ToString());
}
catch
{
statGame = true;
return;
}
if (statGame = PromtColorPlayer(((ColorCard)numColorOrRank - 1),turnPlayer? playerOne:playerTwo, selectedNumsCard))
{
turnPlayer = !turnPlayer;
}
else
{
Console.WriteLine("Вы назвали не верные карты");
Console.ReadKey(true);
statGame = false;
return;
}
}
static void ConsoleRunPromtRank(ref bool statGame, ref bool turnPlayer, Player playerOne, Player playerTwo)
{
//номер цвета или достоинсва карты
int numColorOrRank;
//номера карт подсказки цвета или достоинсва карты
int[] selectedNumsCard;
Console.WriteLine("Введите номер достоинсва карты карты : ");
Console.WriteLine("1. 1");
Console.WriteLine("2. 2");
Console.WriteLine("3. 3");
Console.WriteLine("4. 4");
Console.WriteLine("5. 5");
try
{
numColorOrRank = int.Parse(Console.ReadKey(true).KeyChar.ToString());
if (numColorOrRank > 5)
{
statGame = true;
return;
}
}
catch
{
// numColorOrRank = -1;
statGame = true;
return;
}
Console.WriteLine("Введите номера карт с достоиством в {0} (можно использовать пробел как разделитель)", numColorOrRank.ToString());
string inputString = Console.ReadLine();
try
{
inputString = inputString.Replace(" ", "");
selectedNumsCard = new int[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
selectedNumsCard[i] = int.Parse(inputString[i].ToString());
}
catch
{
statGame = true;
return;
}
if (statGame = PromtRankPlayer(numColorOrRank,turnPlayer ? playerOne:playerTwo, selectedNumsCard))
{
turnPlayer = !turnPlayer;
}
else
{
Console.WriteLine("Вы назвали не верные карты");
Console.ReadKey(true);
statGame = false;
return;
}
}
#endregion
#region ViewConsoleGameFieldAndGameOver
static void ViewGameField(Dictionary<char, List<Card>> table, Player playerOne, Player playerTwo, int countCardInDeck, bool turnPlayer)
{
Console.Clear();
if (turnPlayer)
{
Console.Write("PlayerOne: ");
foreach (Card selectCard in playerOne.CardsPlayer)
Console.Write(selectCard + " ");
ViewTable(table);
Console.Write("PlayerTwo: ");
foreach (Card selectCard in playerTwo.CardsPlayer)
Console.Write(selectCard.ToStringForPlayer() + " ");
}
else
{
Console.Write("PlayerTwo: ");
foreach (Card selectCard in playerTwo.CardsPlayer)
Console.Write(selectCard + " ");
ViewTable(table);
Console.Write("PlayerOne: ");
foreach (Card selectCard in playerOne.CardsPlayer)
Console.Write(selectCard.ToStringForPlayer() + " ");
}
Console.WriteLine('\n');
}
static void ViewTable(Dictionary<char, List<Card>> table)
{
Console.WriteLine();
Console.WriteLine("---------------------------------------------------------------");
Console.WriteLine("W\tR\tG\tB\tY");
Console.WriteLine();
for (int numRank = 1; numRank < 6; numRank++)
{
for(int indexColor = 0; indexColor < 5; indexColor++)
Console.Write("{0}\t", table[((ColorCard)indexColor).ToString()[0]].Any(p=>p.Rank==numRank)?((ColorCard)indexColor).ToString()[0]+numRank.ToString():" ");
Console.WriteLine();
}
Console.WriteLine("---------------------------------------------------------------");
Console.WriteLine();
}
static void ViewGameOver(Player playerOne, Player playerTwo)
{
Console.Clear();
Console.WriteLine(" GameOver");
Console.WriteLine("========================================");
Console.WriteLine("PlayerOne: ");
Console.WriteLine(playerOne.ToString());
Console.WriteLine('\n');
Console.WriteLine("PlayerTwo: ");
Console.WriteLine(playerTwo.ToString());
Console.ReadKey(true);
Console.Clear();
}
#endregion
#region ModelGameVarintСourse
static bool PlayCard(Card playCard,Player player,List<Card> deck, Dictionary<char,List<Card>> table)
{
//Если на столе не сущесвует карты такого цвета, то проверяем достоинство карты
if (table[playCard.Color.ToString()[0]].Count==0)
{
if (playCard.Rank == 1)
{
player.CountRiskCardsPlayed += playCard.VisibleColor && playCard.VisibleRank ? 0 : 1;
player.CountCardsPlayed++;
// table[playCard.Color.ToString()[0]] = new List<Card>();
table[playCard.Color.ToString()[0]].Add(playCard);
player.CardsPlayer.Remove(playCard);
//добор из колоды в руку
player.AddCardFromDeck(deck);
return true;
}
return false;
}
else
{
if (table[playCard.Color.ToString()[0]].Any(p => p.ToString() == playCard.ToString()))
return false;
foreach (Card selectCard in table[playCard.Color.ToString()[0]])
{
if (playCard.IsNextAfter(selectCard))
{
player.CountRiskCardsPlayed += playCard.VisibleColor && playCard.VisibleRank ? 0 : 1;
player.CountCardsPlayed++;
table[playCard.Color.ToString()[0]].Add(playCard);
player.CardsPlayer.Remove(playCard);
//добор из колоды в руку
player.AddCardFromDeck(deck);
return true;
}
}
return false;
}
}
static bool DropCardFromCardsSelectPlayer(int numDropCart, List<Card> deck, Player selectPlayer)
{
return selectPlayer.DropCard(numDropCart, deck);
}
static bool PromtColorPlayer(ColorCard color,Player player, params int[] numbersCards)
{
if (numbersCards.Length == 0)
if (player.CardsPlayer.Any(p => p.Color == color))
return false;
for(int i=1;i<=player.CardsPlayer.Count;i++)
{
if (player.CardsPlayer[i - 1].Color == color)
//проверяет, правильно ли подсказаны карты
if (numbersCards.Any(p => p == i))
{
player.CardsPlayer[i - 1].VisibleColor = true;
}
else
return false;
}
return true;
}
static bool PromtRankPlayer(int rank, Player player, params int[] numbersCards)
{
if (numbersCards.Length == 0)
if (player.CardsPlayer.Any(p => p.Rank == rank))
return false;
for (int i = 1; i <= player.CardsPlayer.Count; i++)
{
if (player.CardsPlayer[i - 1].Rank == rank)
//проверяет, правильно ли подсказаны карты
if (numbersCards.Any(p => p == i))
{
player.CardsPlayer[i - 1].VisibleRank = true;
}
else
return false;
}
return true;
}
#endregion
static List<Card> CreateCardDeck(int countCard = 11)
{
Random rand = new Random();
List<Card> cardDeck = new List<Card>();
for (int i = 0; i < countCard; i++)
cardDeck.Add(new Card((ColorCard)rand.Next(0, 5), rand.Next(1, 6)));
return cardDeck;
}
#endregion
static void Main(string[] args)
{
char selectKey;
do
{
#region MajorMenu
Console.Clear();
Console.WriteLine("1. Новая игра");
Console.WriteLine("2. Справка");
Console.WriteLine("3. Выход");
selectKey = Console.ReadKey(true).KeyChar;
Console.Clear();
if (selectKey == '3')
break;
switch (selectKey)
{
case '1':
NewGame();
break;
case '2':
About();
break;
}
#endregion
} while (true);
}
}
}
|
#define TRACE
namespace Sentry.Infrastructure;
/// <summary>
/// Trace logger used by the SDK to report its internal logging.
/// </summary>
/// <remarks>
/// Logger available when hooked to an IDE. It's useful when debugging apps running under IIS which have no output to Console logger.
/// </remarks>
public class TraceDiagnosticLogger : DiagnosticLogger
{
/// <summary>
/// Creates a new instance of <see cref="TraceDiagnosticLogger"/>.
/// </summary>
public TraceDiagnosticLogger(SentryLevel minimalLevel) : base(minimalLevel)
{
}
/// <inheritdoc />
protected override void LogMessage(string message) => Trace.WriteLine(message);
}
|
using System.Windows;
using System.Windows.Controls;
namespace Unchase.OpenAPI.ConnectedService.Views
{
public partial class ConfigOpenApiEndpoint : UserControl
{
private readonly Wizard _wizard;
internal ConfigOpenApiEndpoint(Wizard wizard)
{
InitializeComponent();
_wizard = wizard;
}
#region Events
private void GenerateCSharpClient_OnUnchecked(object sender, RoutedEventArgs e)
{
this._wizard.RemoveCSharpClientSettingsPage();
}
private void GenerateCSharpClient_OnChecked(object sender, RoutedEventArgs e)
{
this._wizard.AddCSharpClientSettingsPage();
}
private void GenerateCSharpController_OnChecked(object sender, RoutedEventArgs e)
{
this._wizard.AddCSharpControllerSettingsPage();
}
private void GenerateCSharpController_OnUnchecked(object sender, RoutedEventArgs e)
{
this._wizard.RemoveCSharpControllerSettingsPage();
}
private void GenerateTypeScriptClient_OnChecked(object sender, RoutedEventArgs e)
{
this._wizard.AddTypeScriptClientSettingsPage();
}
private void GenerateTypeScriptClient_OnUnchecked(object sender, RoutedEventArgs e)
{
this._wizard.RemoveTypeScriptClientSettingsPage();
}
#endregion
}
}
|
// See https://aka.ms/new-console-template for more information
public class Configuration
{
static Lazy<Configuration> s_default => new(() => {
var fitnessComparer = new SolutionValueAndWeightComparer();
return new Configuration(populationSize: 20,
maxGenerations: 100,
crossoverRate: 0.8,
initialMutationRate: 0.1,
initialSolutionRate: 0.5,
fitnessComparer,
parentSelectionStrategy: new TournamentSelectionStrategy(5, fitnessComparer),
crossoverStrategy: new UniformCrossoverStrategy(),
mutationStrategy: new SimpleMutationStrategy());
});
public Configuration(
int populationSize,
int maxGenerations,
double crossoverRate,
double initialMutationRate,
double initialSolutionRate,
IComparer<Solution> fitnessComparer,
IParentSelectionStrategy parentSelectionStrategy,
UniformCrossoverStrategy crossoverStrategy,
SimpleMutationStrategy mutationStrategy)
{
PopulationSize = populationSize;
MaxGenerations = maxGenerations;
CrossoverRate = crossoverRate;
MutationRate = initialMutationRate;
InitialSolutionRate = initialSolutionRate;
FitnessComparer = fitnessComparer;
ParentSelectionStrategy = parentSelectionStrategy;
CrossoverStrategy = crossoverStrategy;
MutationStrategy = mutationStrategy;
}
public static Configuration Default => s_default.Value;
public double MutationRate { get; internal set; }
public int MaxGenerations { get; internal set; }
public double CrossoverRate { get; }
public IComparer<Solution> FitnessComparer { get; internal set; }
public IParentSelectionStrategy ParentSelectionStrategy { get; }
public UniformCrossoverStrategy CrossoverStrategy { get; }
public SimpleMutationStrategy MutationStrategy { get; }
public int PopulationSize { get; internal set; }
public double InitialSolutionRate { get; internal set; }
} |
using AutoMapper;
using Uintra.Features.Comments.Models;
using Uintra.Features.Comments.Sql;
using Uintra.Infrastructure.Extensions;
namespace Uintra.Features.Comments.AutoMapperProfiles
{
public class CommentAutoMapperProfile : Profile
{
public CommentAutoMapperProfile()
{
CreateMap<Comment, CommentModel>()
.ForMember(dst => dst.LinkPreview, o => o.Ignore());
CreateMap<CommentModel, CommentViewModel>()
.ForMember(dst => dst.LinkPreview, o => o.Ignore())
.ForMember(dst => dst.CanEdit, o => o.Ignore())
.ForMember(dst => dst.CreatorProfileUrl, o => o.Ignore())
.ForMember(dst => dst.CanDelete, o => o.Ignore())
.ForMember(dst => dst.ModifyDate, o => o.Ignore())
.ForMember(dst => dst.Creator, o => o.Ignore())
.ForMember(dst => dst.ElementOverviewId, o => o.Ignore())
.ForMember(dst => dst.CommentViewId, o => o.Ignore())
.ForMember(dst => dst.Replies, o => o.Ignore())
.ForMember(dst => dst.LikeModel, o => o.Ignore())
.ForMember(dst => dst.CreatedDate, o => o.MapFrom(src => src.CreatedDate.ToDateTimeFormat()))
.ForMember(dst => dst.IsReply, o => o.MapFrom(el => !el.ParentId.HasValue))
.ForMember(dst => dst.Likes, o => o.Ignore())
.ForMember(dst=>dst.LikedByCurrentUser, o=> o.Ignore());
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace Marten.Linq
{
public interface IMartenQueryProvider : IQueryProvider
{
Task<IEnumerable<TResult>> ExecuteCollectionAsync<TResult>(Expression expression, CancellationToken token);
Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken token);
}
} |
using System;
using BikeDistributor.Data.Entities;
using BikeDistributor.Interfaces;
using BikeDistributor.Interfaces.CommonServices;
using BikeDistributor.Interfaces.Services;
using BikeDistributor.Models;
using BikeDistributor.Services.Common;
namespace BikeDistributor.Services.Receipt
{
public class HtmlReceiptService: BaseService, IHtmlReceiptService
{
private readonly IDataRepositoryService _dataRepositoryService;
private readonly IReceiptContentService _receiptContentService;
public HtmlReceiptService(IDataRepositoryService dataRepositoryService, IReceiptContentService receiptContentService)
{
_dataRepositoryService = dataRepositoryService;
_receiptContentService = receiptContentService;
}
public string Output(int orderId, int templateId, string token)
{
var result = "";
try
{
var templateModel = _dataRepositoryService.GetOne<HtmlTemplateModel, HtmlTemplate>(t => t.Id == templateId);
var content = _receiptContentService.Generate(orderId, "order-line-container", "order-line", "sub-total-container",
"sub-total-line");
result = templateModel.Content.Replace(token, content);
}
catch (Exception e)
{
LogService.Error(e);
throw;
}
return result;
}
}
}
|
using System.Collections.Generic;
using SuperMario.Collision;
using static SuperMario.Entities.MovementDirectionsEnum;
namespace SuperMario.Entities.Mario
{
public class MarioCollider : IEntityCollider
{
readonly MovingEntity mario;
readonly ICollider rectangleCollider;
public MarioCollider(Entity mario)
{
this.mario = (MovingEntity)mario;
rectangleCollider = new RectangleCollider();
}
private IList<Direction> EntityPastLevelBoundsRestrictDirection()
{
List<Direction> restrictMovementDirections = new List<Direction>();
if (mario.BoundingBox.Left <= 0)
restrictMovementDirections.Add(Direction.Left);
else if (mario.BoundingBox.Right >= 3600)
restrictMovementDirections.Add(Direction.Right);
return restrictMovementDirections;
}
public IList<Direction> RunCollision()
{
List<Direction> restrictMovementDirections = new List<Direction>();
mario.Grounded = false;
for (int i = 0; i < EntityStorage.EntityList.Count; i++)
{
var entity = EntityStorage.EntityList[i];
if (!entity.Equals(mario))
{
RectangleCollisions collisions = (RectangleCollisions)rectangleCollider.Collide(mario.BoundingBox, entity.BoundingBox);
if (collisions.Collisions.Count > 0)
restrictMovementDirections.AddRange(entity.Collide(mario, collisions));
}
}
restrictMovementDirections.AddRange(EntityPastLevelBoundsRestrictDirection());
return restrictMovementDirections;
}
}
}
|
using System;
namespace Decorador
{
class Program
{
static void Main(string[] args)
{
GuardarCxP guardarCxP = new GuardarCxP();
Console.WriteLine("Se guarda CxP");
guardarCxP.EjecutarAccion();
Console.WriteLine("Modificacion 1");
GuardarHistorialCxp guardarHistorialCxp = new GuardarHistorialCxp(guardarCxP);
guardarHistorialCxp.EjecutarAccion();
Console.WriteLine("Modificacion 2");
EnviarCorreoUsuario enviarCorreoUsuario = new EnviarCorreoUsuario(guardarCxP);
enviarCorreoUsuario.EjecutarAccion();
Console.WriteLine("Modificacion 3");
enviarCorreoUsuario = new EnviarCorreoUsuario(guardarHistorialCxp);
enviarCorreoUsuario.EjecutarAccion();
}
}
}
|
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("IzBone.SimpleRig.Editor")]
|
using System;
using System.Web.Mvc;
using IBLLService;
using ShengUI.Helper;
using Common;
namespace ShengUI.Logic
{
[HandleError]
public class HelpController : BaseController
{
ITokenConfig_MANAGER token = OperateContext.Current.BLLSession.ITokenConfig_MANAGER;
IYX_sysConfigs_MANAGER sysConfigs = OperateContext.Current.BLLSession.IYX_sysConfigs_MANAGER;
public string JssdkSignature = "";
public string noncestr = "";
public string shareInfo = "";
public string timestamp = "";
public string openid = "";
public string userid = "";
//
public string isok = "NO";
public ActionResult Index()
{
ViewBag.isok = "OK";
ViewBag.Appid = sysConfigs.GetKeyValue("appid");
ViewBag.Uri = sysConfigs.GetKeyValue("shareurl");
noncestr = CommonMethod.GetCode(16);
string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token());
timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ;
string url = Request.Url.ToString().Replace("#", "");
JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url);
ViewBag.noncestr = noncestr;
ViewBag.jsapi_ticket = jsapi_ticket;
ViewBag.timestamp = timestamp;
userid = Request.QueryString["userid"];
ViewBag.userid = userid;
ViewBag.openid = openid;
//根据授权 获取openid //根据授权 获取用户的openid
string code = Request.QueryString["code"];//获取授权code
LogHelper.WriteLog("//////////////////////////////////////////////////////////////////////////////////");
LogHelper.WriteLog("code:" + code);
if (!string.IsNullOrEmpty(code))
{
string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + sysConfigs.GetKeyValue("appid") + "&secret=" + sysConfigs.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code";
// LogHelper.WriteLog("openIdUrl:" + openIdUrl);
string content = Tools.GetPage(openIdUrl, "");
LogHelper.WriteLog("content:" + content);
openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid
Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(token.IsExistAccess_Token(), openid);
LogHelper.WriteLog("XXXXXXXXXXX:" + openid);
if (dic != null)
{
ViewBag.nickname = dic.nickname;
ViewBag.headimgurl = dic.headimgurl;
}
}
else
{
string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5affe01247a2482c&redirect_uri=http://qxw2062640039.my3w.com/help/index/&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
Response.Redirect(codeurl);
}
return View();
}
public ActionResult About()
{
ViewBag.PageFlag = "About";
return View();
}
public ActionResult Login()
{
return View();
}
}
}
|
using System;
namespace Practice
{
class MainClass
{
public static void Main(string[] args)
{
string[] stateName = new string[4];
int[] statePop = new int[4];
int maxPop = 0;
int index = 0;
for (int i = 0; i < 4; i++){
Console.WriteLine("What is the state name?");
stateName[i] = Console.ReadLine();
Console.WriteLine("What is the population?");
statePop[i] = int.Parse(Console.ReadLine());
if (statePop[i] > maxPop)
{
maxPop = statePop[i];
index = i;
}
Console.WriteLine("The state with the highest population is {0} with a population of {1}", stateName[index], statePop[index]);
Console.ReadLine();
Console.Clear();
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Ada.Framework.Expressions.Entities
{
public abstract class Evaluador<T>
{
public IList<string> Parametros { get; set; }
protected string codigo;
protected Func<T, Condicion, bool> delegado;
public string Codigo { get { return codigo; } }
public Func<T, Condicion, bool> Delegado { get { return delegado; } }
public Evaluador()
{
Parametros = new List<string>();
}
protected virtual object ObtenerValorExpresion(object objeto, string expresion)
{
if (expresion == "this")
{
return objeto;
}
if (expresion.Contains("."))
{
foreach (string prop in expresion.Split('.'))
{
objeto = objeto.GetType().GetProperty(prop).GetValue(objeto, null);
}
return objeto;
}
return objeto.GetType().GetProperty(expresion).GetValue(objeto, null);
}
}
public abstract class Evaluador : Evaluador<object>{ }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Contracts
{
public interface ISiteContextProvider
{
Uri RootDomain { get; }
Claim RootClaim { get; }
}
}
|
using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
using pjank.BossaAPI.Fixml;
namespace pjank.BossaAPI.DemoConsole.Modules
{
class NolCustomOrders : IDemoModule
{
public char MenuKey { get { return '3'; } }
public string Description { get { return "NolClient usage, sending orders directly with Fixml classes"; } }
/// <summary>
/// Przykład wysyłki zleceń, korzystając bezpośrednio z klas NewOrderSingleMsg i spółki...
/// Test ten wrzuca na giełdę zlecenie kupna 1 x FW20 po 1000zł (*raczej* nie ma szans się zrealizować :)),
/// następnie je modyfikuje ustawiając limit ceny oczko wyżej... aż ostatecznie całe zlecenie anuluje.
/// </summary>
public void Execute()
{
var accountNumber = "00-22-..."; // <- wpisz tu swój numer, żeby program nie musiał o niego pytać
if (accountNumber.EndsWith("..."))
{
Console.Write("Podaj numer rachunku (końcówkę z " + accountNumber + "): ");
var str = Console.ReadLine();
accountNumber = accountNumber.Replace("...", str);
Trace.WriteLine("Wybrany rachunek: " + accountNumber);
}
// nawiązanie połączenia z NOL3 i zalogowanie użytkownika
using (var nol = new NolClient())
{
Thread.Sleep(2000);
var tmp = FixmlMsg.DebugFormattedXml.Enabled;
try
{
ExecutionReportMsg execReport;
// --- wysyłka nowego zlecenia ---
Console.WriteLine("\nPress any key... to send NEW order request [Esc - exit]\n");
if (Console.ReadKey(true).Key == ConsoleKey.Escape) return;
var newRequest = new NewOrderSingleMsg();
newRequest.Account = accountNumber;
newRequest.Side = OrderSide.Buy;
newRequest.Instrument = FixmlInstrument.FindBySym("FW20H12");
newRequest.Quantity = 1;
newRequest.Price = 1000;
using (var socket = NolClient.GetSyncSocket())
{
FixmlMsg.DebugFormattedXml.Enabled = true; // <- wyświetli nam dokładną treść komunikatów
newRequest.Send(socket);
execReport = new ExecutionReportMsg(socket);
FixmlMsg.DebugFormattedXml.Enabled = tmp;
}
Thread.Sleep(3000);
// --- modyfikacja tego zlecenia ---
Console.WriteLine("\nPress any key... to MODIFY this order request [Esc - exit]\n");
if (Console.ReadKey(true).Key == ConsoleKey.Escape) return;
var replaceRequest = new OrderReplaceRequestMsg();
replaceRequest.BrokerOrderId2 = execReport.BrokerOrderId2;
replaceRequest.Account = accountNumber;
replaceRequest.Side = OrderSide.Buy;
replaceRequest.Instrument = newRequest.Instrument;
replaceRequest.Quantity = 1;
replaceRequest.Price = 1001;
using (var socket = NolClient.GetSyncSocket())
{
FixmlMsg.DebugFormattedXml.Enabled = true;
replaceRequest.Send(socket);
execReport = new ExecutionReportMsg(socket);
FixmlMsg.DebugFormattedXml.Enabled = tmp;
}
Thread.Sleep(3000);
// --- anulowanie tego zlecenia ---
Console.WriteLine("\nPress any key... to CANCEL this order request [Esc - exit]\n");
if (Console.ReadKey(true).Key == ConsoleKey.Escape) return;
var cancelRequest = new OrderCancelRequestMsg();
cancelRequest.BrokerOrderId2 = replaceRequest.BrokerOrderId2;
cancelRequest.Account = accountNumber;
cancelRequest.Side = newRequest.Side;
cancelRequest.Instrument = newRequest.Instrument;
cancelRequest.Quantity = newRequest.Quantity;
using (var socket = NolClient.GetSyncSocket())
{
FixmlMsg.DebugFormattedXml.Enabled = true;
cancelRequest.Send(socket);
execReport = new ExecutionReportMsg(socket);
FixmlMsg.DebugFormattedXml.Enabled = false;
}
Thread.Sleep(3000);
Console.WriteLine("\nPress any key... to exit\n");
Console.ReadKey(true);
Console.WriteLine("\n\nThank you :)\n");
}
catch (Exception e)
{
MyUtil.PrintError(e);
}
FixmlMsg.DebugFormattedXml.Enabled = tmp;
} // tu następuje wylogowanie
}
}
}
|
using System;
namespace interfaces
{
public class JetSki : IVehicle, IWater
{
public int Doors { get; set; }
public int PassengerCapacity { get; set; }
public double EngineVolume { get; set; }
public double MaxWaterSpeed { get; set; }
public void Drive()
{
Console.WriteLine("The jetski zips through the waves with the greatest of ease");
}
}
} |
namespace Taggart.ITunes
{
public class Track
{
public Track()
{
Album = new Album();
}
#region Properties
public Album Album { get; set; }
public int TrackNumber { get; set; }
public string Name { get; set; }
public string Artist { get; set; }
public int TotalTime { get; set; }
public int BitRate { get; set; }
public int SampleRate { get; set; }
#endregion
public bool Equals(Track obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj.Album, Album) && obj.TrackNumber == TrackNumber && Equals(obj.Name, Name) && Equals(obj.Artist, Artist) && obj.TotalTime == TotalTime && obj.BitRate == BitRate && obj.SampleRate == SampleRate;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Track)) return false;
return Equals((Track)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (Album != null ? Album.GetHashCode() : 0);
result = (result * 397) ^ TrackNumber;
result = (result * 397) ^ (Name != null ? Name.GetHashCode() : 0);
result = (result * 397) ^ (Artist != null ? Artist.GetHashCode() : 0);
result = (result * 397) ^ TotalTime.GetHashCode();
result = (result * 397) ^ BitRate;
result = (result * 397) ^ SampleRate;
return result;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace lsc.Model.Enume
{
/// <summary>
/// 热度
/// </summary>
public enum DegreeOfHeatEnume
{
/// <summary>
/// 高
/// </summary>
Senior = 1,
/// <summary>
/// 中
/// </summary>
Intermediate = 2,
/// <summary>
/// 低
/// </summary>
Lower = 3
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Tile : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
//Script is attached to all tile gameObjects
//Explanation of variables are found on the Tactics Movement tutorial: https://www.youtube.com/watch?v=cX_KrK8RQ2o
public bool walkable = true;
public bool current = false;
public bool target = false;
public bool selectable = false;
public bool pathable = false;
public bool inRange = false;
public bool inAffect = false;
public bool shieldable = false;
public bool shielded = false;
public List<Tile> adjecencyList = new List<Tile>();
//Needed BFS algorithm (Breadth First Search)
public bool visited = false;
public Tile parent = null;
[HideInInspector] public int distance = 0;
//For A*
[HideInInspector] public float f = 0; //g + h
[HideInInspector] public float g = 0; //cost from parent to current tile
[HideInInspector] public float h = 0; //heuristic cost (cost from processed tile to destination)
[HideInInspector] public Color selectableColor = Color.red;
[HideInInspector] public Color pathableColor = Color.red;
[HideInInspector] public Color targetColor = Color.gray;
[HideInInspector] public Color currentColor = Color.magenta;
[HideInInspector] public Color inRangeColor = Color.black;
[HideInInspector] public Color baseColor = Color.white;
[HideInInspector] public Color emptyAffectColor = Color.grey;
[HideInInspector] public Color attackableColor = Color.blue;
[HideInInspector] public List<Tile> tilesInRange = new List<Tile>();
BattleStateMachine BSM;
Pattern pattern = new Pattern();
Transform cursor;
void Start()
{
BSM = GameObject.Find("BattleManager").GetComponent<BattleStateMachine>();
UpdateShieldable(this);
cursor = GameObject.Find("GridMap/TileCursor").transform;
}
void Update()
{
if (inRange && !inAffect)
{
GetComponent<SpriteRenderer>().material.color = inRangeColor;
}
//else if (inRange && inAffect)
//{
// GetComponent<SpriteRenderer>().material.color = attackableColor;
//}
else if (inAffect)
{
GetComponent<SpriteRenderer>().material.color = attackableColor; //set back to emptyAffectColor if needed
}
else if (current)
{
GetComponent<SpriteRenderer>().material.color = currentColor;
}
else if (target)
{
GetComponent<SpriteRenderer>().material.color = targetColor;
}
else if (pathable)
{
GetComponent<SpriteRenderer>().material.color = pathableColor;
}
//else if (selectable)
//{
// GetComponent<SpriteRenderer>().material.color = selectableColor;
//}
else
{
GetComponent<SpriteRenderer>().material.color = baseColor;
}
}
/// <summary>
/// Sets attached tile's variables to false and clears the adjency list for it
/// Implemented here: https://youtu.be/cK2wzBCh9cg?t=1038
/// </summary>
public void Reset()
{
adjecencyList.Clear();
walkable = false;
current = false;
target = false;
selectable = false;
inAffect = false;
inRange = false;
shielded = false;
visited = false;
parent = null;
distance = 0;
f = g = h = 0;
}
/// <summary>
/// Sets pathable to false for attached tile
/// </summary>
public void ClearPathable()
{
pathable = false;
}
/// <summary>
/// Calls CheckTile for tiles (up, down, left, and right) surrounding the attached tile
/// Explanation found on tutorial: https://youtu.be/cK2wzBCh9cg?t=1076
/// </summary>
/// <param name="target">Target tile to check neighbor details</param>
public void FindNeighbors(Tile target)
{
Reset();
CheckTile(Vector2.up, target);
CheckTile(Vector2.down, target);
CheckTile(Vector2.right, target);
CheckTile(Vector2.left, target);
}
/// <summary>
/// Checks if tile should be walkable or if it is adjacent to attached tile
/// Explanation found on tutorial: https://youtu.be/cK2wzBCh9cg?t=1115
/// </summary>
/// <param name="direction">Position of tile to check</param>
/// <param name="target">Tile to check if it should be added to adjency list</param>
public void CheckTile(Vector2 direction, Tile target)
{
Collider2D[] colliders = Physics2D.OverlapBoxAll((Vector2)transform.position + direction, new Vector2(.5f, .5f), 0);
foreach (Collider2D item in colliders)
{
Tile tile = item.GetComponent<Tile>();
if (tile != null)
{
//Make these blockable when incorporating tiles that block movement. Then it will not add these to adjency list.
//Really I just need to add a new tag for "unwalkable" or "blockable" objects, and use the new tag below.
RaycastHit2D[] tileHits = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D checkIfWalkable in tileHits)
{
if (checkIfWalkable.collider.gameObject.tag == "Enemy" && BSM.HeroesToManage.Count > 0)
{
tile.walkable = false;
}
else
{
tile.walkable = true;
}
}
foreach (RaycastHit2D checkIfShieldable in tileHits)
{
if (checkIfShieldable.collider.gameObject.tag == "Shieldable" && BSM.HeroesToManage.Count > 0)
{
//Debug.Log("Shieldable: " + checkIfShieldable.collider.gameObject.name);
tile.walkable = false;
}
else
{
tile.walkable = true;
}
}
if (tile.walkable)
{
RaycastHit hit;
if (!Physics.Raycast(tile.transform.position, Vector3.forward, out hit, 1) || (tile == target))
{
adjecencyList.Add(tile);
}
}
}
}
}
/// <summary>
/// Test method
/// </summary>
public void CheckStuff()
{
foreach (Tile tile in adjecencyList)
{
Debug.Log(tile.gameObject.name);
}
}
/// <summary>
/// Processes methods when cusor enters attached tile
/// </summary>
public void OnPointerEnter(PointerEventData eventData)
{/*
if (BSM.centerTile == null)
{
BSM.centerTile = this.gameObject;
}
RaycastHit2D[] hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
//shows enemy name on hover
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(hit.collider.gameObject.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if (target.collider.gameObject.tag == "Enemy" && !BSM.targets.Contains(target.collider.gameObject))
{
GameObject.Find("BattleCanvas/BattleUI/BattleDetailsPanel/BattleDetailsText").GetComponent<Text>().text = target.collider.gameObject.GetComponent<EnemyStateMachine>().enemy.name;
}
}
}
}
}
//shows hero border and name on hover
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(hit.collider.gameObject.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if (target.collider.gameObject.tag == "Hero" && !BSM.targets.Contains(target.collider.gameObject))
{
GameObject.Find("BattleCanvas/BattleUI/BattleDetailsPanel/BattleDetailsText").GetComponent<Text>().text = target.collider.gameObject.GetComponent<HeroStateMachine>().hero.name;
foreach (Transform child in GameObject.Find("BattleCanvas/BattleUI/HeroPanel/HeroPanelSpacer").transform)
{
string ID = target.collider.gameObject.name.Replace("BattleHero - ID ", "");
if (child.name.Replace("BattleHeroPanel - ID ","") == ID)
{
HeroStateMachine HSM = target.collider.gameObject.GetComponent<HeroStateMachine>();
HSM.HeroPanel.transform.Find("BorderCanvas").GetComponent<CanvasGroup>().alpha = 1.0f;
}
}
}
}
}
}
}
if (BSM.choosingTarget)
{
//facilitates display of if the tile can be selected (if it is in the attack pattern and is in range)
if (BSM.HeroChoice.chosenItem != null)
{
pattern.GetAffectPattern(this, 0); //gets pattern for 1 tile for item use
}
else
{
pattern.GetAffectPattern(this, BSM.HeroChoice.chosenAttack.patternIndex); //gets attack pattern
}
tilesInRange = pattern.pattern;
foreach (Tile tile in tilesInRange)
{
//Debug.Log(tile.gameObject.name + " is in affect");
RaycastHit2D[] shieldableTiles = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in shieldableTiles)
{
if (target.collider.gameObject.tag != "Shieldable" && !tile.shielded)
{
tile.inAffect = true;
}
else
{
tile.inAffect = false;
}
}
CheckIfTileIsShielded(tile);
}
//Debug.Log(gameObject.name + " entered");
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
if (hit.collider.gameObject.GetComponent<Tile>().inRange)
{
foreach (Tile tile in tilesInRange)
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if ((target.collider.gameObject.tag == "Enemy" || target.collider.gameObject.tag == "Hero") && tile.inAffect)
{
BSM.ShowSelector(target.collider.gameObject.transform.Find("Selector").gameObject);
}
}
}
}
}
}
}
}*/
}
public void UpdateTilesInRange()
{
BSM.centerTile = this.gameObject;
RaycastHit2D[] hits = Physics2D.RaycastAll(cursor.position, Vector2.zero);
//facilitates display of if the tile can be selected (if it is in the attack pattern and is in range)
if (BSM.HeroChoice.chosenItem != null)
{
pattern.GetAffectPattern(this, 0); //gets pattern for 1 tile for item use
}
else
{
pattern.GetAffectPattern(this, BSM.HeroChoice.chosenAttack.patternIndex); //gets attack pattern
}
tilesInRange = pattern.pattern;
foreach (Tile tile in tilesInRange)
{
//Debug.Log(tile.gameObject.name + " is in affect");
RaycastHit2D[] shieldableTiles = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in shieldableTiles)
{
if (target.collider.gameObject.tag != "Shieldable" && !tile.shielded)
{
tile.inAffect = true;
}
else
{
tile.inAffect = false;
}
}
CheckIfTileIsShielded(tile);
}
//Debug.Log(gameObject.name + " entered");
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
if (hit.collider.gameObject.GetComponent<Tile>().inRange)
{
foreach (Tile tile in tilesInRange)
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if ((target.collider.gameObject.tag == "Enemy" || target.collider.gameObject.tag == "Hero") && tile.inAffect)
{
//BSM.ShowSelector(target.collider.gameObject.transform.Find("Selector").gameObject);
}
}
}
}
}
}
}
}
public void ResetTilesInRange()
{
foreach (Tile tile in tilesInRange)
{
tile.inAffect = false;
tile.shielded = false;
}
}
/// <summary>
/// Processes methods when cusor exits attached tile
/// </summary>
public void OnPointerExit(PointerEventData eventData)
{/*
//resets enemy name on hover to blank when exiting tile
GameObject.Find("BattleCanvas/BattleUI/BattleDetailsPanel/BattleDetailsText").GetComponent<Text>().text = "";
foreach (Transform child in GameObject.Find("BattleCanvas/BattleUI/HeroPanel/HeroPanelSpacer").transform)
{
child.transform.Find("BorderCanvas").GetComponent<CanvasGroup>().alpha = 0.0f;
}
if (BSM.choosingTarget)
{
GameObject[] heroes = GameObject.FindGameObjectsWithTag("Hero");
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject heroObj in heroes)
{
BSM.HideSelector(heroObj.transform.Find("Selector").gameObject);
}
foreach (GameObject enemyObj in enemies)
{
BSM.HideSelector(enemyObj.transform.Find("Selector").gameObject);
}
foreach (Tile tile in tilesInRange)
{
tile.inAffect = false;
tile.shielded = false;
}
//tilesInRange.Clear();
//Debug.Log(gameObject.name + " exited");
}*/
}
/// <summary>
/// Processes methods when cusor clicks on attached tile
/// </summary>
public void OnPointerClick(PointerEventData eventData)
{/*
if (BSM.choosingTarget)
{
//this.inAffect = false;
RaycastHit2D[] hits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
if (hit.collider.gameObject.GetComponent<Tile>().inRange)
{
BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().ActionTarget = hit.collider.gameObject; //sets the primary target for animation to occur on the tile clicked
BattleCameraManager.instance.parentTile = hit.collider.gameObject;
foreach (Tile tile in tilesInRange)
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if ((target.collider.gameObject.tag == "Enemy" || target.collider.gameObject.tag == "Hero") && !BSM.targets.Contains(target.collider.gameObject) && tile.inAffect)
{
//Debug.Log("adding " + target.collider.gameObject + " to targets");
//BSM.targets.Add(target.collider.gameObject); //adds all objects inside target range to targets list to be affected
BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().targets.Add(target.collider.gameObject);
}
}
}
if (BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().targets.Count > 0)
{
tilesInRange.Clear();
ClearTiles();
}
}
}
}
}
}*/
}
public void SelectMoveTile(PlayerMove playerMove)
{
RaycastHit2D[] hits = Physics2D.RaycastAll(cursor.position, Vector3.zero);
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.tag == "Tile")
{
Tile t = hit.collider.GetComponent<Tile>();
if (t.selectable)
{
Debug.Log("moving to: " + hit.collider.gameObject.name);
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
playerMove.MoveToTile(t);
}
}
}
}
}
public void SelectActionTile()
{
if (BSM.choosingTarget)
{
//this.inAffect = false;
RaycastHit2D[] hits = Physics2D.RaycastAll(cursor.position, Vector3.zero);
//Debug.Log(cursor.position);
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
//Debug.Log("SelectActionTile hit: " + hit.collider.gameObject.name + ", is in range: " + hit.collider.gameObject.GetComponent<Tile>().inRange);
if (hit.collider.gameObject.GetComponent<Tile>().inRange)
{
BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().ActionTarget = hit.collider.gameObject; //sets the primary target for animation to occur on the tile clicked
BattleCameraManager.instance.parentTile = hit.collider.gameObject;
//Debug.Log("parent tile: " + BattleCameraManager.instance.parentTile.name);
foreach (Tile tile in tilesInRange)
{
//Debug.Log("tile in range: " + tile.gameObject.name);
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
//Debug.Log("Tile hit: " + target.collider.gameObject.name);
if ((target.collider.gameObject.tag == "Enemy" || target.collider.gameObject.tag == "Hero") && !BSM.targets.Contains(target.collider.gameObject) && tile.inAffect)
{
//Debug.Log("adding " + target.collider.gameObject + " to targets");
//BSM.targets.Add(target.collider.gameObject); //adds all objects inside target range to targets list to be affected
BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().targets.Add(target.collider.gameObject);
}
}
}
if (BSM.HeroesToManage[0].GetComponent<HeroStateMachine>().targets.Count > 0)
{
//Debug.Log("clearing tiles and stuff");
tilesInRange.Clear();
ClearTiles();
}
}
}
}
}
}
}
public bool IfTargetsInRange()
{
if (BSM.choosingTarget)
{
//this.inAffect = false;
RaycastHit2D[] hits = Physics2D.RaycastAll(cursor.position, Vector3.zero);
//Debug.Log(cursor.position);
foreach (RaycastHit2D hit in hits)
{
if (hit.collider != null)
{
if (hit.collider.gameObject.tag == "Tile")
{
//Debug.Log("SelectActionTile hit: " + hit.collider.gameObject.name + ", is in range: " + hit.collider.gameObject.GetComponent<Tile>().inRange);
if (hit.collider.gameObject.GetComponent<Tile>().inRange)
{
foreach (Tile tile in tilesInRange)
{
//Debug.Log("tile in range: " + tile.gameObject.name);
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
//Debug.Log("Tile hit: " + target.collider.gameObject.name);
if ((target.collider.gameObject.tag == "Enemy" || target.collider.gameObject.tag == "Hero") && !BSM.targets.Contains(target.collider.gameObject) && tile.inAffect)
{
return true;
}
}
}
}
}
}
}
}
return false;
}
/// <summary>
/// Sets all tiles inAffect and inRange to false
/// </summary>
void ClearTiles()
{
GameObject[] tiles = GameObject.FindGameObjectsWithTag("Tile");
foreach (GameObject tileObj in tiles)
{
Tile tile = tileObj.GetComponent<Tile>();
tile.inAffect = false;
tile.inRange = false;
}
}
/// <summary>
/// Returns the hero by given ID based on HeroDB
/// </summary>
/// <param name="ID">ID of hero needing to be returned</param>
BaseHero GetHeroByID(int ID)
{
foreach (BaseHero hero in GameManager.instance.activeHeroes)
{
if (hero.ID == ID)
{
return hero;
}
}
foreach (BaseHero hero in GameManager.instance.inactiveHeroes)
{
if (hero.ID == ID)
{
return hero;
}
}
return null;
}
public void CheckIfTileIsShielded(Tile tile)
{
StartCoroutine(GetShieldableTiles(tile));
}
public IEnumerator GetShieldableTiles(Tile tile)
{
//check each tile in each direction 1 tile - done
//if tile is shieldable or shielded - done
//get direction of that tile from center tile - done
//check tile 1 over in that direction - done
//if in affect - done
//mark tile as shielded - done
yield return new WaitForEndOfFrame();
string dir = "null";
Tile tileToCheck = null;
//Debug.Log(BSM.centerTile.name);
//Debug.Log("checking for shieldable tiles from: " + BSM.centerTile.name + " to: " + tile.gameObject.name);
//up
RaycastHit2D[] upHits = Physics2D.RaycastAll(tile.transform.position, Vector3.up, 1);
foreach (RaycastHit2D target in upHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>() != tile && BSM.centerTile.GetComponent<Tile>().inRange)
{
if (target.collider.gameObject.GetComponent<Tile>().shieldable || target.collider.gameObject.GetComponent<Tile>().shielded)
{
if (DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) != "null")
{
//Debug.Log(target.collider.gameObject.name + " is shieldable/shielded and is " + DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) + " from center tile");
tileToCheck = target.collider.gameObject.GetComponent<Tile>();
dir = DirectionFromCenterTile(tileToCheck);
}
}
}
}
//down
RaycastHit2D[] downHits = Physics2D.RaycastAll(tile.transform.position, Vector3.down, 1);
foreach (RaycastHit2D target in downHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>() != tile && BSM.centerTile.GetComponent<Tile>().inRange)
{
if (target.collider.gameObject.GetComponent<Tile>().shieldable || target.collider.gameObject.GetComponent<Tile>().shielded)
{
if (DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) != "null")
{
//Debug.Log(target.collider.gameObject.name + " is shieldable/shielded and is " + DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) + " from center tile");
tileToCheck = target.collider.gameObject.GetComponent<Tile>();
dir = DirectionFromCenterTile(tileToCheck);
}
}
}
}
//left
RaycastHit2D[] leftHits = Physics2D.RaycastAll(tile.transform.position, Vector3.left, 1);
foreach (RaycastHit2D target in leftHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>() != tile && BSM.centerTile.GetComponent<Tile>().inRange)
{
if (target.collider.gameObject.GetComponent<Tile>().shieldable || target.collider.gameObject.GetComponent<Tile>().shielded)
{
if (DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) != "null")
{
//Debug.Log(target.collider.gameObject.name + " is shieldable/shielded and is " + DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) + " from center tile");
tileToCheck = target.collider.gameObject.GetComponent<Tile>();
dir = DirectionFromCenterTile(tileToCheck);
}
}
}
}
//right
RaycastHit2D[] rightHits = Physics2D.RaycastAll(tile.transform.position, Vector3.right, 1);
foreach (RaycastHit2D target in rightHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>() != tile && BSM.centerTile.GetComponent<Tile>().inRange)
{
if (target.collider.gameObject.GetComponent<Tile>().shieldable || target.collider.gameObject.GetComponent<Tile>().shielded)
{
if (DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) != "null")
{
//Debug.Log(target.collider.gameObject.name + " is shieldable/shielded and is " + DirectionFromCenterTile(target.collider.gameObject.GetComponent<Tile>()) + " from center tile");
tileToCheck = target.collider.gameObject.GetComponent<Tile>();
dir = DirectionFromCenterTile(tileToCheck);
}
}
}
}
if (dir != "null" && tileToCheck != null)
{
if (dir == "up" && tileToCheck.gameObject != BSM.centerTile)
{
//Debug.Log("checking 1 tile up from " + tileToCheck.gameObject.name);
RaycastHit2D[] dirHits = Physics2D.RaycastAll(tileToCheck.transform.position, Vector3.up, 1);
foreach (RaycastHit2D target in dirHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>().inAffect)
{
//Debug.Log("shielding " + target.collider.gameObject.name);
SetShielded(target.collider.gameObject);
}
}
}
if (dir == "down" && tileToCheck.gameObject != BSM.centerTile)
{
//Debug.Log("checking 1 tile down from " + tileToCheck.gameObject.name);
RaycastHit2D[] dirHits = Physics2D.RaycastAll(tileToCheck.transform.position, Vector3.down, 1);
foreach (RaycastHit2D target in dirHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>().inAffect)
{
SetShielded(target.collider.gameObject);
}
}
}
if (dir == "left" && tileToCheck.gameObject != BSM.centerTile)
{
//Debug.Log("checking 1 tile left from " + tileToCheck.gameObject.name);
RaycastHit2D[] dirHits = Physics2D.RaycastAll(tileToCheck.transform.position, Vector3.left, 1);
foreach (RaycastHit2D target in dirHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>().inAffect)
{
SetShielded(target.collider.gameObject);
}
}
}
if (dir == "right" && tileToCheck.gameObject != BSM.centerTile)
{
//Debug.Log("checking 1 tile right from " + tileToCheck.gameObject.name);
RaycastHit2D[] dirHits = Physics2D.RaycastAll(tileToCheck.transform.position, Vector3.right, 1);
foreach (RaycastHit2D target in dirHits)
{
if (target.collider.gameObject.tag == "Tile" && target.collider.gameObject.GetComponent<Tile>().inAffect)
{
SetShielded(target.collider.gameObject);
}
}
}
}
}
void SetShielded(GameObject tileObj)
{
Debug.Log("shielding " + tileObj.name);
tileObj.GetComponent<Tile>().shielded = true;
tileObj.GetComponent<Tile>().inAffect = false;
}
string DirectionFromCenterTile(Tile tileToCheck)
{
Vector3 centerTilePos = BSM.centerTile.gameObject.transform.position;
Vector3 tileToCheckPos = tileToCheck.gameObject.transform.position;
//Debug.Log(centerTilePos + " - " + tileToCheckPos);
if (centerTilePos.x != tileToCheckPos.x && centerTilePos.y != tileToCheckPos.y)
{
return "null";
}
else
{
if (centerTilePos.x > tileToCheckPos.x)
{
//Debug.Log(BSM.centerTile.gameObject.name + " is right of " + tileToCheck.gameObject.name);
return "left";
}
if (centerTilePos.x < tileToCheckPos.x)
{
//Debug.Log(BSM.centerTile.gameObject.name + " is left of " + tileToCheck.gameObject.name);
return "right";
}
if (centerTilePos.y > tileToCheckPos.y)
{
//Debug.Log(BSM.centerTile.gameObject.name + " is up of " + tileToCheck.gameObject.name);
return "down";
}
if (centerTilePos.y < tileToCheckPos.y)
{
//Debug.Log(BSM.centerTile.gameObject.name + " is down of " + tileToCheck.gameObject.name);
return "up";
}
}
return "null";
}
void UpdateShieldable(Tile tile)
{
RaycastHit2D[] tilesHit = Physics2D.RaycastAll(tile.transform.position, Vector3.forward, 1);
foreach (RaycastHit2D target in tilesHit)
{
if (target.collider.gameObject.tag == "Shieldable")
{
Debug.Log("Setting " + tile.gameObject.name + " as shieldable");
tile.shieldable = true;
}
}
}
}
|
using gView.Framework.Geometry;
using gView.Framework.Symbology;
using gView.Framework.system;
using System.Collections.Generic;
namespace gView.Framework.Carto
{
public interface ILabelEngine
{
void Init(IDisplay display, bool directDraw);
LabelAppendResult TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, bool chechForOverlap);
LabelAppendResult TryAppend(IDisplay display, List<IAnnotationPolygonCollision> aPolygons, IGeometry geometry, bool checkForOverlap);
void Draw(IDisplay display, ICancelTracker cancelTracker);
void Release();
GraphicsEngine.Abstraction.ICanvas LabelCanvas { get; }
}
} |
using LauncherLib.Download;
using LauncherLib.Utilities;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LauncherLib.Upgrader
{
//public static class PackageMaker
//{
// public static Package MakePackage(string GamePath)
// {
// //TODO
// return null;
// }
// //public static Package GenerateInfoFromZIP(string )
// //TODO
//}
public static class PackageDownloader
{
static string RESOURCESURL = "https://resources.eod.moe";
static List<string> sha1List;
public static void InitializePackageDownloader()
{
sha1List = new List<string>();
}
public static void moveCache(string Des,bool willDelete,bool willOverwrite)
{
if (willDelete)
{
Utils.DeleteFolder(Des);
Directory.CreateDirectory(Des);
Utils.CopyFile(@".\HikazeLauncher\temp", Des, true);
}
Utils.CopyFile(@".\HikazeLauncher\temp", Des, willOverwrite);
}
//public static void moveCache(string Des,List<string> DeleteList)
//{
//}
//TODO
public static void Unpackage(string sha1)
{
if (sha1List != null)
{
foreach(string element in sha1List)
{
Unzipper.UnZip(@"\HikazeLauncher\download\" + sha1 + ".zip", @".\HikazeLauncher\temp");
}
}
else
{
throw new NullReferenceException("sha1List Empty");
}
}
public static void PackageDownload(Index index)
{
string url;
string localPath;
Queue<DownloadTask> tasks = new Queue<DownloadTask>();
if (!Directory.Exists(@".\HikazeLauncher\download"))
{
Utils.CreateDir(@".\HikazeLauncher\download");
}
if (!Directory.Exists(@".\HikazeLauncher\temp"))
{
Utils.CreateDir(@".\HikazeLauncher\temp");
}
foreach (JFiles files in index.files)
{
url = RESOURCESURL + "/objects/" + files.sha1.Substring(0, 2) + "/" + files.sha1 + ".zip";
localPath = @".\HikazeLauncher\temp\"+ files.sha1 + ".zip";
tasks.Enqueue(new DownloadTask(url, localPath, files.sha1, files.size));
sha1List.Add(files.sha1);
}
MultiDownloader multiDownloader = new MultiDownloader(tasks, 3, false);
}
}
public class Package
{
public static readonly string HikazeResources = "https://resources.eod.moe";
public string Name { get; }
public string sha1 { get; }
public int size { get; }
public string mainVersion { get; }
public int subVersion { get; }
public string localPath { get; }
public string Url { get; }
}
public class Version
{
public string mainVersion{get;}=null;
public string subVersion{get;}=null;
public string projectName{get;}=null;
public string releaseTime{get;}=null;
public Version(JToken versionJson)
{
mainVersion = versionJson["mainVersion"] !=null? versionJson["mainVersion"].ToString():null;
subVersion = versionJson["subVersion"] !=null? versionJson["subVersion"].ToString():null;
projectName = versionJson["projectName"] !=null? versionJson["projectName"].ToString():null;
releaseTime = versionJson["releaseTime"] !=null? versionJson["releaseTime"].ToString():null;
}
}
public class JFiles
{
public string sha1 {get;}
public int size { get; }
public JFiles(JToken fileJson)
{
sha1 = fileJson["sha1"].ToString();
size = Convert.ToInt32(fileJson["size"].ToString());
}
}
public class Index
{
public string Name{get;}
public List<JFiles> files{get;}
Version version{get;}
public bool enabled{get;}
public Index(JToken indexJson)
{
version = new Version(indexJson["version"]);
Name = version.projectName+"-"+version.mainVersion+"-"+version.subVersion;
files = new List<JFiles>();
foreach(JToken element in indexJson["files"])
{
files.Add(new JFiles(element));
}
enabled = Convert.ToBoolean(indexJson["enabled"].ToString());//TODO:convert to boolean
}
}
public class rootIndex
{
List<Index> indexes{get;}
public rootIndex(JObject rootJson)
{
indexes = new List<Index>();
foreach(JToken element in rootJson["Indexes"])
{
indexes.Add(new Index(element));
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameScript : MonoBehaviour
{
public static System.Action<Beetle, Beetle> OnReadyToFight = null;
[System.Serializable]
public class Visuals
{
public GameObject P1Turnlights = null;
public GameObject P2Turnlights = null;
public List<GameObject> P1Points = null;
public List<GameObject> P2Points = null;
}
[SerializeField]
private Visuals m_visuals = null;
[SerializeField]
private TextMeshProUGUI m_winnerText = null;
[SerializeField]
private float m_turnLength = GameConstants.START_TURN_LENGTH;
[SerializeField]
private DeckGenerator m_generator = null;
[SerializeField]
private Beetle m_player1 = null;
[SerializeField]
private Beetle m_player2 = null;
[SerializeField]
private Carriage m_carriagePrefab = null;
[SerializeField]
private Transform m_carriageContainer = null;
[SerializeField]
private Text m_timerText = null;
private List<CarriageDefinition> m_currentHand = null;
private List<Carriage> m_currentAvailableCarriages = null;
public bool ReadyToFight
{
get
{
return (
m_player1.CarriageCount >= GameConstants.MAX_CARRIAGE_CAPACITY &&
m_player2.CarriageCount >= GameConstants.MAX_CARRIAGE_CAPACITY
);
}
}
// If false, it's player 2's turn
private bool m_player1Turn = true;
private float m_currentTurnTimer = 0;
private bool m_gameplayActive = false;
private bool m_doubleDip = false;
private void OnCarriageSelected(Carriage c)
{
if (ReadyToFight)
{
Debug.Log("READY TO FIGHT");
OnReadyToFight?.Invoke(m_player1, m_player2);
return;
}
CarriageDefinition.Color color = c.CarriageDefinition.GetColor();
if (color == CarriageDefinition.Color.Wild)
{
int rand = UnityEngine.Random.Range(0, 3);
color = (CarriageDefinition.Color) rand;
}
CarriageDefinition.Ability ability = c.CarriageDefinition.GetAbility();
Beetle player = GetCurrentPlayer();
Beetle otherPlayer = GetOtherPlayer();
switch (ability)
{
case CarriageDefinition.Ability.None:
player.AddCarriage(color);
break;
case CarriageDefinition.Ability.Copy:
if (player.CarriageCount == 0)
{
return;
}
Carriage lastCarriage = player.GetLastCarriage();
color = lastCarriage.CarriageDefinition.GetColor();
player.AddCarriage(color);
break;
case CarriageDefinition.Ability.Send:
if (otherPlayer.CarriageCount == GameConstants.MAX_CARRIAGE_CAPACITY)
{
player.AddCarriage(color);
}
else
{
otherPlayer.AddCarriage(color);
}
break;
case CarriageDefinition.Ability.Swap:
if (player.CarriageCount > 0 && otherPlayer.CarriageCount > 0)
{
Carriage c1 = player.RemoveLastCarriage();
Carriage c2 = otherPlayer.RemoveLastCarriage();
player.AddCarriage(c2.CarriageDefinition.GetColor());
otherPlayer.AddCarriage(c1.CarriageDefinition.GetColor());
Destroy(c1.gameObject);
Destroy(c2.gameObject);
}
player.AddCarriage(color);
break;
case CarriageDefinition.Ability.DoubleDip:
m_doubleDip = true;
player.AddCarriage(color);
break;
case CarriageDefinition.Ability.Shuffle:
player.AddCarriage(color);
m_carriageContainer.GetComponent<CarriageMenu>().Reset();
m_currentHand.Clear();
DrawHand();
m_carriageContainer.GetComponent<CarriageMenu>().Init();
break;
}
c.gameObject.SetActive(false);
if (m_doubleDip)
{
m_doubleDip = false;
}
else
{
NextTurn();
}
if (ReadyToFight)
{
OnReadyToFight?.Invoke(m_player1, m_player2);
}
}
private Carriage CreateCarriage(CarriageDefinition def)
{
Carriage carriage = Instantiate(m_carriagePrefab, Vector3.zero, Quaternion.identity);
carriage.Init(def);
return carriage;
}
private void OnEnable()
{
MatchOutcomeController.OnMatchOutcomeDecided += OnMatchOutcomeDecided;
}
private void OnMatchOutcomeDecided(bool p1wins)
{
Debug.LogFormat("Beetle {0} wins", p1wins ? m_player1.name : m_player2.name);
if (p1wins)
{
m_player1.GainPoint();
}
else
{
m_player2.GainPoint();
}
// Fill all points for player 1
for (int i = 0; i < m_player1.Points; ++i)
{
m_visuals.P1Points[i].SetActive(true);
}
// Fill all points for player 2
for (int i = 0; i < m_player2.Points; ++i)
{
m_visuals.P2Points[i].SetActive(true);
}
// Handle the match/game winner
string text = string.Format("Player {0}", p1wins ? "1" : "2");
bool matchEnded = false;
if (
m_player1.Points >= GameConstants.POINTS_TO_WIN ||
m_player2.Points >= GameConstants.POINTS_TO_WIN)
{
matchEnded = true;
text += " is the winner!";
}
else
{
text += " won this round!";
}
m_winnerText.text = text;
m_winnerText.DOFade(1, 0.35f);
m_winnerText.rectTransform.DOScale(Vector3.zero, 2).From().SetEase(Ease.OutBack).OnComplete(() =>
{
FMODUnity.RuntimeManager.PlayOneShot("event:/Character/AttackWhistle");
m_winnerText.DOFade(0, 0.15f).SetDelay(1f).OnComplete(() =>
{
if (matchEnded)
{
MusicController.MC.GameStartedMusic();
SceneManager.LoadScene("TitleScreen", LoadSceneMode.Single);
}
else
{
RestartRound();
}
});
});
}
private void RestartRound()
{
m_carriageContainer.GetComponent<CarriageMenu>().Reset();
m_currentHand.Clear();
m_player1.Reset();
m_player2.Reset();
m_generator.ConstructDeck();
InitializeRound(false);
}
private void Start()
{
foreach (GameObject go in m_visuals.P1Points)
{
go.SetActive(false);
}
foreach (GameObject go in m_visuals.P2Points)
{
go.SetActive(false);
}
m_winnerText.text = "Get ready to choo!";
m_generator.ConstructDeck();
InitializeRound(true);
}
private void Update()
{
m_currentTurnTimer -= Time.deltaTime;
m_timerText.text = Mathf.CeilToInt(m_currentTurnTimer).ToString();
if (m_currentTurnTimer <= 0)
{
NextTurn();
}
}
private void InitializeRound(bool animate)
{
DrawHand();
m_gameplayActive = true;
TurnStart();
if (!animate)
return;
m_winnerText.DOFade(1, 0.35f);
m_winnerText.rectTransform.DOScale(Vector3.zero, 1).From().SetEase(Ease.OutBack).OnComplete(() =>
{
m_winnerText.DOFade(0, 0.15f).SetDelay(1f);
});
}
private void DrawHand()
{
m_generator.Generate();
m_currentHand = m_generator.GetHand();
m_currentAvailableCarriages = new List<Carriage>();
for (int i = 0; i < m_currentHand.Count; i++)
{
Carriage carriage = CreateCarriage(m_currentHand[i]);
carriage.OnSelect += OnCarriageSelected;
carriage.transform.SetParent(m_carriageContainer);
m_currentAvailableCarriages.Add(carriage);
}
m_carriageContainer.GetComponent<CarriageMenu>().Init();
}
private void NextTurn()
{
if (m_player1.CarriageCount == 3 && m_player1.CarriageCount == m_player2.CarriageCount)
{
return;
}
if (m_player1.CarriageCount == 3)
{
m_player1Turn = false;
}
else if (m_player2.CarriageCount == 3)
{
m_player1Turn = true;
}
else
{
m_player1Turn = !m_player1Turn;
}
TurnStart();
}
private void TurnStart()
{
m_currentTurnTimer = m_turnLength;
m_visuals.P1Turnlights.SetActive(m_player1Turn);
m_visuals.P2Turnlights.SetActive(!m_player1Turn);
}
private Beetle GetCurrentPlayer()
{
if (m_player1Turn)
{
return m_player1;
}
else
{
return m_player2;
}
}
private Beetle GetOtherPlayer()
{
if (m_player1Turn)
{
return m_player2;
}
else
{
return m_player1;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VictoryManager : MonoBehaviour
{
[SerializeField]
private Texture[] images;
private ScreenFader fader;
private RawImage rawImage;
private int currentIdx;
protected void Awake()
{
Cursor.lockState = CursorLockMode.None;
fader = FindObjectOfType<ScreenFader>();
rawImage = GetComponent<RawImage>();
fader.FadeIn(1f, null);
StartCoroutine(ImageSwapCoroutine());
}
protected void Update()
{
rawImage.rectTransform.localScale += 0.01f * Time.deltaTime * Vector3.one;
}
private IEnumerator ImageSwapCoroutine()
{
float t = 0f;
currentIdx = Random.Range(0, images.Length);
while (t < 12f)
{
float wait = 1 - 1 / (1 + Mathf.Exp(-0.5f * t + 3));
yield return new WaitForSeconds(wait);
int newIdx = Random.Range(0, images.Length);
while (newIdx == currentIdx)
{
newIdx = Random.Range(0, images.Length);
}
currentIdx = newIdx;
rawImage.texture = images[currentIdx];
t += wait;
}
rawImage.texture = null;
rawImage.color = Color.black;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace VJBatangas.LomiHouse.Common
{
public class VJHelper
{
public string GetConnectionString (String key)
{
return ConfigurationManager.ConnectionStrings[key].ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntSys_Lab2._1.Model
{
public class MiniMaxSolver
{
public double[,] Values { get; set; }
public double[] MinA { get; set; }
public double[] MaxB { get; set; }
public double MaxA { get; set; }
public double MinB { get; set; }
public bool CanSolve { get; set; }
public MiniMaxSolver(double[,] values)
{
Values = values;
CanSolve = false;
Solve();
}
public void Solve()
{
MinA = new double[Values.GetLength(0)];
MaxB = new double[Values.GetLength(1)];
for (int i = 0; i < MinA.Length; i++)
MinA[i] = Values.GetRow(i).Min();
for (int i = 0; i < MaxB.Length; i++)
MaxB[i] = Values.GetCol(i).Max();
MaxA = MinA.Max();
MinB = MaxB.Min();
CanSolve = (MinB == MaxA);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
/*******************************
* Created By franco
* Description: log type
*******************************/
namespace Kingdee.CAPP.Common.Logger
{
class LogHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, System.Xml.XmlNode section)
{
if (section == null)
{
System.Diagnostics.Debug.WriteLine("<section name='Test' type='Test.ConfigHandler,Test'/>");
}
return section;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MySingleton
{
class EagerSingleton
{
private static EagerSingleton instance = new EagerSingleton();
private EagerSingleton()
{
}
public static EagerSingleton getInstance()
{
return EagerSingleton.instance;
}
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace YFVIC.DMS.Model.Models.FileInfo
{
public class BigFileEntity
{
/// <summary>
///编号
/// </summary>
[DataMember]
public int Id;
/// <summary>
/// 文档名称
/// </summary>
[DataMember]
public string FileName;
/// <summary>
/// 当前版本号
/// </summary>
[DataMember]
public string VersionNum;
/// <summary>
///文件内容
/// </summary>
[DataMember]
public byte[] FileContent;
/// <summary>
///发起人
/// </summary>
[DataMember]
public string Creater;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPSMouseLook : MonoBehaviour
{
public enum RotationAxis {MouseX, MouseY}
public RotationAxis axex = RotationAxis.MouseY;
private float CurrentSensitity_X = 1.5f;
private float CurrentSensitity_Y = 1.5f;
private float Sensitity_X = 1.5f;
private float Sensitity_Y = 1.5f;
private float Rotation_X, Rotation_Y;
private float Minimum_X = -360f;
private float Max_X = 360f;
private float Minimum_Y = -60f;
private float Max_Y = 60f;
private Quaternion originalRotation;
private float mouseSens = 1.7f;
// Start is called before the first frame update
void Start()
{
originalRotation = transform.rotation;
}
void Update()
{
}
void FixedUpdate()
{
}
// Update is called once per frame
void LateUpdate()
{
HandleRotation();
}
float ClampAngle(float angle, float min, float max)
{
if(angle < -360f)
{
angle += 360;
}
if(angle > 360f)
{
angle -= 360f;
}
return Mathf.Clamp(angle, min, max);
void HandleRotation()
{
if(CurrentSensitity_X != mouseSens || CurrentSensitity_Y != mouseSens)
{
CurrentSensitity_X = CurrentSensitity_Y = mouseSens;
}
}
Sensitity_X = CurrentSensitity_X;
Sensitity_Y = CurrentSensitity_Y;
if(axex == RotationAxis.MouseX)
{
Rotation_X += Input.GetAxis("Mouse X") * Sensitity_X;
Rotation_X = ClampAngle(Rotation_X, Minimum_X, Max_X);
Quaterion xQuaterion = Quaterion.AngleAxis(Rotation_X, Vector3.up);
transform.localRotation = originalRotation * xQuaterion;
}
if(axex == RotationAxis.MouseY)
{
Rotation_Y += Input.GetAxis("Mouse Y") * Sensitity_Y;
Rotation_Y = ClampAngle(Rotation_Y, Minimum_Y, Max_Y);
Quaterion yQuaterion = Quaterion.AngleAxis(Rotation_Y, Vector3.right);
transform.localRotation = originalRotation * yQuaterion;
}
}
}
|
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Docller.Core.Models;
using Docller.Core.Services;
namespace Docller.Core.Images
{
public interface IPreviewImageProvider
{
void GeneratePreviews(long customerId, BlobBase blobBase);
void DeletePreviews(long customerId, BlobBase blobBase);
string GetPreview(long customerId, BlobBase blobBase, PreviewType previewType);
string GetZoomablePreview(long customerId, BlobBase blobBase);
string GetTile(long customerId, BlobBase blobBase, string tile);
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MoulaCodingChallenge.Controllers
{
/// <summary>
/// This is a dummy login api to generate JWT token, based on an assumption that account info is private and need AA
/// </summary>
[ApiController]
[Produces("application/json")]
[Route("api/v1/dummyAuth")]
[ExcludeFromCodeCoverage]
public class DummyLoginController : ControllerBase
{
[HttpPost]
[Route("{userName}")]
public async Task<IActionResult> Login([FromRoute] string userName)
{
var handler = new JsonWebTokenHandler();
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Issuer = "moula",
Audience = "account",
IssuedAt = now,
NotBefore = now,
Expires = now.AddMinutes(30),
Subject = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, userName) }),
SigningCredentials = new SigningCredentials(DummyKV.Key, SecurityAlgorithms.RsaSha256Signature)
};
string jwt = handler.CreateToken(descriptor);
return Ok( new { accessToken = jwt});
}
}
}
|
using Asnapper.Hal101.Data;
using Asnapper.Hal101.Models;
using Microsoft.AspNetCore.Mvc;
namespace Asnapper.Hal101.Controllers
{
[Route("[controller]")]
[ApiController]
public class AddressesController : ControllerBase
{
private readonly AddressRepository _repository;
public AddressesController(AddressRepository repository)
{
_repository = repository;
}
[HttpGet]
public ActionResult<PagedList<Address>> List([FromQuery] Paging paging)
{
return _repository.List(paging);
}
[HttpGet]
[Route("{id}")]
public ActionResult<Address> Get(int id)
{
return _repository.Get(id);
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class RacingGameController : MonoBehaviour {
public int score1;
public int score2;
public Text score1Text;
public Text score2Text;
public int time;
public static RacingGameController instance = null;
private bool onlyOnce;
private GameController gc;
void Awake(){
if (instance == null)
instance = this;
else if (instance != this)
Destroy (gameObject);
}
void Start () {
gc = GameController.gc;
gc.startGame (time);
gc.timeBeforeTransition = 2;
}
// Update is called once per frame
void Update () {
if(gc.gameTime <= 0 && !onlyOnce){
onlyOnce = true;
if (score1 > score2)
gc.gameOver (1);
else if (score1 < score2)
gc.gameOver (2);
else if (score1 == score2)
gc.gameOver (0);
}
}
public void updateText(){
score1Text.text = "Player 1 Score: " + score1;
score2Text.text = "Player 2 Score: " + score2;
}
}
|
using System;
using System.Windows.Forms;
namespace Claudia
{
/// <summary>
///
/// </summary>
public partial class MiniForm : Form
{
private MainForm _Parent { get; set; }
private string _ArtworkUrl { get; set; }
private string _Title { get; set; }
private string _Artist { get; set; }
private string _Duration { get; set; }
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="artworkUrl"></param>
/// <param name="title"></param>
/// <param name="artist"></param>
/// <param name="duration"></param>
public MiniForm(MainForm parent, string artworkUrl, string title, string artist, string duration)
{
InitializeComponent();
this._Parent = parent;
this._ArtworkUrl = artworkUrl;
this._Title = title;
this._Artist = artist;
this._Duration = duration;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MiniWindow_Load(object sender, EventArgs e)
{
this.SizeChanged += (s, ev) =>
{
if (this.WindowState == FormWindowState.Minimized)
this._Parent.WindowState = FormWindowState.Normal;
this.Close();
};
this.Artwork.ImageLocation = this._ArtworkUrl;
this.Title.Text = this._Title;
this.Artist.Text = this._Artist;
this.Duration.Text = this._Duration;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Construction_Project
{
public partial class Cus_profile : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataBind();
}
//go button
protected void Button2_Click(object sender, EventArgs e)
{
getMember();
}
//active button
protected void LinkButton1_Click(object sender, EventArgs e)
{
UpdateMemberStatus("active");
}
//pause button
protected void LinkButton2_Click(object sender, EventArgs e)
{
UpdateMemberStatus("pending");
}
//deactive button
protected void LinkButton3_Click(object sender, EventArgs e)
{
UpdateMemberStatus("deactive");
}
//user define function
void getMember()
{
try
{
//perform the connection and pass the connection in the constructor
SqlConnection con = new SqlConnection(strcon);
//check whether the connection is closed
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Customer WHERE NIC = '" + TextBox9.Text.Trim() + "'", con);
//execute above query
SqlDataReader dr = cmd.ExecuteReader();
//finding record
if (dr.HasRows)
{
while (dr.Read())
{
TextBox1.Text = dr.GetValue(0).ToString();
TextBox2.Text = dr.GetValue(1).ToString();
TextBox3.Text = dr.GetValue(2).ToString();
TextBox6.Text = dr.GetValue(3).ToString();
TextBox9.Text = dr.GetValue(4).ToString();
TextBox8.Text = dr.GetValue(5).ToString();
TextBox4.Text = dr.GetValue(6).ToString();
TextBox5.Text = dr.GetValue(7).ToString();
TextBox7.Text = dr.GetValue(8).ToString();
}
}
else
{
Response.Write("<script>alert('Invalid Credentials');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
void UpdateMemberStatus(string status)
{
try
{
//perform the connection and pass the connection in the constructor
SqlConnection con = new SqlConnection(strcon);
//check whether the connection is closed
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("UPDATE Customer SET Account_status='" + status + "' WHERE NIC='" + TextBox9.Text.Trim() + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
Response.Write("<script>alert('Account status successfully updated!!!');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}
} |
using System;
namespace week05a
{
class MainClass
{
public static void Main (string[] args)
{
/*A switch statement can be used like a nested if/else statement
* The idea is you have cases to match text, characters or numbers
* when a case is found that matches the input (selection in this case)
* then it will jump to that code.
* it will continue in that section until it finds a break or return statement.
*/
Console.WriteLine ("Please enter a number from 0 to 3");
int selection = int.Parse(Console.ReadLine());
switch (selection) {
case 0:
Console.WriteLine ("Bad selection");
break;
case 1:
Console.WriteLine ("You selected to add");
break;
case 2:
Console.WriteLine ("You selected to remove");
break;
case 3:
Console.WriteLine ("You selected to repeat");
break;
}
Console.WriteLine ("Please enter a number from 0 to 3");
selection = int.Parse(Console.ReadLine());
switch (selection) {
case 10:
Console.WriteLine ("Some Text");
break;
case 11:
case 12:
case 13:
Console.WriteLine ("You've entered 11, 12 or 13");
break;
case 14:
case 15:
Console.WriteLine ("You've entered 14 or 15");
break;
default:
Console.WriteLine ("Invalid selection");
break;
}
do {
Console.WriteLine ("For internet banking press 1");
Console.WriteLine ("For accounts press 2");
Console.WriteLine ("For fraud support press 3");
Console.WriteLine ("To hear the options again press 0");
selection = int.Parse (Console.ReadLine ());
switch (selection) {
case 0:
continue;
case 1:
Console.WriteLine ("You are now speaking to internet banking");
break;
case 2:
Console.WriteLine ("You are now speaking to accounts department");
break;
case 3:
Console.WriteLine ("You are now speaking to fraud support");
break;
default:
Console.WriteLine ("Invalid input");
continue;
}
} while (selection == 0);
}
}
}
|
using System;
using System.Collections.Generic;
using App.Core.Interfaces.Dto;
using App.Core.Interfaces.Dto.Responses;
using App.Core.Interfaces.Extensions;
using Newtonsoft.Json;
namespace App.Core.Interfaces.Json
{
public class FlatListsJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<Type, ListDto>);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var tValue = (Dictionary<Type, ListDto>) value;
var dict = new Dictionary<string, ListDto>();
foreach (var pair in tValue)
{
dict[pair.Key.GetEntityListName()] = pair.Value;
}
serializer.Serialize(writer, dict);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var dict = (Dictionary<string, ListDto>) serializer.Deserialize(reader,
typeof(Dictionary<string, ListDto>));
var result = new Dictionary<Type, ListDto>();
foreach (var pair in dict)
{
pair.Value.PrimaryKey = pair.Key.GetEntityTypeByListName().GetEntityPrimaryKeyName();
result[pair.Key.GetEntityTypeByListName()] = pair.Value;
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Sales.Common.Models;
using Sales.Domain.Models;
namespace Sales.API.Controllers
{
public class AssistantsController : ApiController
{
private DataContext db = new DataContext();
// GET: api/Assistants
public IQueryable<Assistant> GetAssistants()
{
return db.Assistants;
}
// GET: api/Assistants/5
[ResponseType(typeof(Assistant))]
public async Task<IHttpActionResult> GetAssistant(int id)
{
Assistant assistant = await db.Assistants.FindAsync(id);
if (assistant == null)
{
return NotFound();
}
return Ok(assistant);
}
// PUT: api/Assistants/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutAssistant(int id, Assistant assistant)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != assistant.AssistantId)
{
return BadRequest();
}
db.Entry(assistant).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AssistantExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Assistants
[ResponseType(typeof(Assistant))]
public async Task<IHttpActionResult> PostAssistant(Assistant assistant)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Assistants.Add(assistant);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = assistant.AssistantId }, assistant);
}
// DELETE: api/Assistants/5
[ResponseType(typeof(Assistant))]
public async Task<IHttpActionResult> DeleteAssistant(int id)
{
Assistant assistant = await db.Assistants.FindAsync(id);
if (assistant == null)
{
return NotFound();
}
db.Assistants.Remove(assistant);
await db.SaveChangesAsync();
return Ok(assistant);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool AssistantExists(int id)
{
return db.Assistants.Count(e => e.AssistantId == id) > 0;
}
}
} |
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using MongoDB.Driver;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Alabo.Datas.Stores.Count.Mongo {
public abstract class CountMongoStore<TEntity, TKey> : CountAsyncMongoStore<TEntity, TKey>,
ICountStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected CountMongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public long Count(Expression<Func<TEntity, bool>> predicate) {
if (predicate == null) {
return Collection.AsQueryable().LongCount();
}
return Collection.AsQueryable().LongCount(predicate);
}
public long Count() {
return Collection.Count(FilterDefinition<TEntity>.Empty);
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TestType.cs">
// Copyright (c) 2021 Johannes Deml. All rights reserved.
// </copyright>
// <author>
// Johannes Deml
// public@deml.io
// </author>
// --------------------------------------------------------------------------------------------------------------------
namespace NetworkBenchmark
{
public enum TestType
{
/// <summary>
/// 1. Client sends <see cref="Configuration.ParallelMessages"/> to the server (Ping)
/// 2. Server sends each messages it receives back to the sending client (Pong)
/// 3. Client again sends each message it receives back to the server and so on.
/// Also known as Echo. Great for testing round trip if just one parallel message is used.
/// </summary>
PingPong,
/// <summary>
/// Messages are sent manually by clients or server
/// Helps to understand data by sniffing the traffic or to debug libraries
/// Can also be used in conjunction with a ping-pong server process to get direct responses from the server
/// <example>
/// <code>
/// c 1 // sends one message for each client
/// s 5 // send five messages to each client the server is connected to
/// q // quit
/// </code>
/// </example>
/// </summary>
Manual
}
}
|
using Allyn.Domain.Models.Basic;
using Allyn.Domain.Repositories;
using Allyn.Domain.Repositories.Basic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Allyn.Infrastructure.EfRepositories.Basic
{
public class RoleRepository : IRoleRepository
{
private readonly IRepository<Role> _repository;
public RoleRepository(IRepository<Role> repository)
{
_repository = repository;
}
}
}
|
namespace Xamarin.Forms.PlatformConfiguration.WindowsSpecific
{
using FormsElement = Forms.VisualElement;
public static class VisualElement
{
#region IsLegacyColorModeEnabled
public static readonly BindableProperty IsLegacyColorModeEnabledProperty =
BindableProperty.CreateAttached("IsLegacyColorModeEnabled", typeof(bool),
typeof(FormsElement), true);
public static bool GetIsLegacyColorModeEnabled(BindableObject element)
{
return (bool)element.GetValue(IsLegacyColorModeEnabledProperty);
}
public static void SetIsLegacyColorModeEnabled(BindableObject element, bool value)
{
element.SetValue(IsLegacyColorModeEnabledProperty, value);
}
public static bool GetIsLegacyColorModeEnabled(this IPlatformElementConfiguration<Windows, FormsElement> config)
{
return (bool)config.Element.GetValue(IsLegacyColorModeEnabledProperty);
}
public static IPlatformElementConfiguration<Windows, FormsElement> SetIsLegacyColorModeEnabled(
this IPlatformElementConfiguration<Windows, FormsElement> config, bool value)
{
config.Element.SetValue(IsLegacyColorModeEnabledProperty, value);
return config;
}
#endregion
}
}
|
using System;
namespace method
{
class Caculator // 계산하는 클래스를 선행하여 만들겠다.
{
public static int Plus(int a, int b) // Plus라는 이름의 int형 매개변수를 선언하겠다.
{
return a + b; // Caculator안에 Plus라는 매개변수를 사용하면 두 변수 a와 b를 더하겠다.
}
public static int Minus(int a, int b) // Minus라는 이름의 int형 매개변수를 선언한다.
{
return a - b; // Caculator안에 Minus라는 매개변수를 사용하여 입력된 두 변수 a와 b를 빼준 값을 반환한다.
}
}
class MainApp // 메인 클래스를 선언한다. 실제로 함수들이 돌아가는 곳이다.
{
static void Main() // 왜냐하면 여기에 메인이 선언되었기 때문.
{
int result = Caculator.Plus(3, 4); // result라는 int형 변수를 선언하고 Caculator의 Plus매개변수에 3,4를 대입한 값을 다시 result에 대입한다.
Console.WriteLine(result); // result값을 출력한다.
result = Caculator.Minus(5, 2);
Console.WriteLine(result);
}
}
}
|
using SwordAndFather.Contracts;
using SwordAndFather.Models;
namespace SwordAndFather.Validators
{
public class CreateAssassinRequestValidator : IValidator<CreateAssassinRequest>
{
public bool Validate(CreateAssassinRequest request)
{
return !(string.IsNullOrEmpty(request.CatchPhrase) ||
string.IsNullOrEmpty(request.CodeName) ||
string.IsNullOrEmpty(request.PreferredWeapon));
}
}
} |
using MongoDB.Driver.Builders;
using mvcMongoDB.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcMongoDB.Controllers
{
public class BrandController : Controller
{
private readonly CountryDB Context = new CountryDB();
// GET: Rep
public ActionResult Index()
{
var Models = Context.Brands.FindAll().SetSortOrder(SortBy<Brand>.Ascending(r => r.brandName));
return View(Models);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Brand _brand)
{
if (ModelState.IsValid)
{
Context.Brands.Insert(_brand);
return RedirectToAction("Index");
}
return View();
}
}
} |
using SMG.Common.Algebra;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMG.Common.Gates
{
/// <summary>
/// Logical OR combination gate.
/// </summary>
class ORGate : CompositeGate
{
#region Properties
public override GateType Type
{
get { return GateType.OR; }
}
public override string SeparatorOperator
{
get { return " + "; }
}
public override string SeparatorCode
{
get { return " || "; }
}
#endregion
#region Public Methods
public override IGate Simplify()
{
IGate gate = this;
SimplifyConstants(ref gate);
SimplifyRule2(ref gate);
while(SimplifyRule1(ref gate))
{
SimplifyRule2(ref gate);
}
Gate.TraceSimplify(this, gate, "simplify OR (0)");
return gate;
}
#endregion
#region Private Methods
private bool SimplifyRule1(ref IGate gate)
{
var original = gate;
var garg = gate as ORGate;
if(null == garg) return false;
// handle the rules:
// A + !A B = A + B
// A + A B = A
var gset = garg.GetSOP();
int changes = 0;
var gplan = gset.OrderBy(e => e.Inputs.Count()).ToList();
for (int j = 0; j < gplan.Count; ++j)
{
var glist = gplan[j];
if (glist.IsEmpty) continue;
TraceSimplify(" product [{0}] : {1}", glist.Signature, glist.ToGate());
for (int k = j + 1; k < gplan.Count; ++k)
{
var olist = gplan[k];
switch (olist.ContainsFactor(glist))
{
case 1:
// contains the sequence => eliminate entry?
TraceSimplify(" is contained in {0} ...", olist.ToGate());
olist.Clear();
changes++;
break;
case 2:
// contains negation => remove negations
TraceSimplify(" negation is contained in {0} ...", olist.ToGate());
olist.Remove(glist);
if(olist.IsEmpty)
{
// full negation ==> ALL
glist.Clear();
gset.Fixed = new TrueGate();
}
changes++;
break;
}
}
}
gset.Purge();
if (gset.Fixed != null)
{
gate = gset.Fixed;
}
else
{
// construct an OR expression containing the ordered factors
var or = new ORGate();
foreach (var glist in gset.OrderBy(e => e.Signature, StringComparer.Ordinal))
{
or.AddInput(glist.ToGate().Simplify());
}
if (or.Inputs.Count() == 0)
{
gate = new FalseGate();
}
else if (or.Inputs.Count() == 1)
{
gate = or.Inputs.First();
}
else
{
gate = or;
}
}
if (changes > 0)
{
TraceSimplify(original, gate, "simplify OR (1)");
}
return changes > 0;
}
/// <summary>
/// Looks for common subfactors.
/// </summary>
/// <param name="gate"></param>
private bool SimplifyRule2(ref IGate gate)
{
var originalgate = gate;
var gset = gate.GetSOP();
// try all elementary factors ...
foreach (var elementaryfactor in gset.GetPrimitiveFactors().ToArray())
{
// Trace("trying factor {0}", elementaryfactor);
// collect all products that contain the factor as candidates
var candidates = new List<Product>();
foreach (var p in gset)
{
if (1 == p.ContainsFactor(elementaryfactor))
{
candidates.Add(p);
}
}
// need at least two
if (candidates.Count < 2)
{
continue;
}
TraceSimplify("common factor {0} found in {1} ...", elementaryfactor, candidates.ToSeparatorList());
// construct a new gate consisting of the sum of remaining products
var reducedsum = new ORGate();
Gate newgate = reducedsum;
foreach (var involvedproduct in candidates)
{
var reducedproduct = involvedproduct.Clone();
reducedproduct.Remove(elementaryfactor);
if (reducedproduct.Factors.Any())
{
reducedsum.AddInput(reducedproduct.ToGate());
}
else
{
// candidate equals elementary factor => TRUE
newgate = new TrueGate();
break;
}
}
// remove original elements from the set
foreach (var x in candidates)
{
gset.Remove(x);
}
// simplify the resulting gate recursively
var partialsum = newgate.Simplify();
var factor = elementaryfactor.ToGate();
TraceSimplify(" is ({0}) AND {1}", partialsum, factor);
if (partialsum.Type == GateType.Fixed)
{
if (partialsum is TrueGate)
{
// factor only
gate = factor;
}
else
{
// simplification yields FALSE
gate = partialsum;
}
}
else if (partialsum.Type == GateType.AND)
{
// multiply with factor
gate = Gate.Multiply(factor.GetInputs(), partialsum);
}
else if (partialsum.Type == GateType.OR)
{
// multiply with all factors
gate = Gate.Multiply(factor.GetInputs(), partialsum.GetInputs());
}
else
{
// multiply with factor
gate = Gate.Multiply(factor.GetInputs(), partialsum);
}
// compose with the remaining terms
foreach (var term in gset.Select(e => e.ToGate()))
{
gate = Gate.ComposeOR(gate, term, ComposeOptions.NoSimplify);
}
break;
}
if (gate != originalgate)
{
Gate.TraceSimplify(originalgate, gate, "simplify OR (2)");
}
return gate != originalgate;
}
private static void SimplifyConstants(ref IGate gate)
{
var inputs = gate.GetInputs();
var list = new List<IGate>();
foreach (var i in inputs)
{
if (i is TrueGate)
{
// sum is constant => TRUE
gate = new TrueGate();
return;
}
else if (i is FalseGate)
{
// remove any FALSE gates ...
}
else if (i.GetNestingLevel() > 1)
{
var r = i.Simplify();
if (r.Type == GateType.OR)
{
list.AddRange(r.GetInputs());
}
else
{
list.Add(r);
}
}
else
{
var r = i.Simplify();
list.Add(r);
}
}
gate = ConsolidateList(list);
}
private static IGate ConsolidateList(List<IGate> list)
{
IGate gate;
if (!list.Any())
{
// empty sum => FALSE
gate = new FalseGate();
}
else if (list.Count == 1)
{
gate = list.First();
}
else
{
var or = new ORGate();
or.AddInputRange(list);
gate = or;
}
return gate;
}
#endregion
}
}
|
using System;
using TiledMax;
namespace USMS_Source
{
public class Level
{
private Map map;
public Level (String fileName)
{
this.map = Map.Open(fileName);
if(map.Loaded.Successful)
{
drawMap(map);
}
}
public void drawMap(Map map)
{
Console.WriteLine("Map Loaded!");
}
}
}
|
using MMSEApp.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using Xamarin.Forms;
namespace MMSEApp.ViewModels
{
public class RegisterViewModel : INotifyPropertyChanged
{
public INavigation navigation;
public event PropertyChangedEventHandler PropertyChanged;
public RegisterViewModel() { }
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
}
}
private string lastName;
public string LastName
{
get { return lastName; }
set
{
lastName = value;
PropertyChanged(this, new PropertyChangedEventArgs("LastName"));
}
}
private string username;
public string Username
{
get { return username; }
set
{
username = value;
PropertyChanged(this, new PropertyChangedEventArgs("Username"));
}
}
private string password;
public string Password
{
get { return password; }
set
{
password = value;
PropertyChanged(this, new PropertyChangedEventArgs("Password"));
}
}
private string confirmPassword;
public string ConfirmPassword
{
get { return confirmPassword; }
set
{
confirmPassword = value;
PropertyChanged(this, new PropertyChangedEventArgs("ConfirmPassword"));
}
}
public Command RegisterCommand
{
get
{
return new Command(Register);
}
}
private void Register() {
if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(ConfirmPassword))
{
App.Current.MainPage.DisplayAlert("Empty Values", "Please enter Username and Password", "OK");
}
else
{
if (Password != ConfirmPassword)
{
App.Current.MainPage.DisplayAlert("Passwords do not match", "Please retry", "OK");
}
else
{
DbResult reg = RegisterUser();
App.Current.MainPage.DisplayAlert(reg.msg, "", "OK");
if (reg.success)
{
navigation.PopAsync();
}
}
}
}
private DbResult RegisterUser()
{
DbResult res = new DbResult();
string cs = @"server=oharam29-nolanm45-mmse-app.c4zhfzwco8qq.eu-west-1.rds.amazonaws.com;Port=3306;database=patient_info;user id=oharam29;password=f1sfo9mu;Persist Security Info=True;charset=utf8;";
MySqlConnection con = new MySqlConnection(cs);
try
{
if (con.State == ConnectionState.Closed)
{
//// add to user table
con.Open(); // open connection
MySqlCommand init_check = new MySqlCommand("SELECT UserName FROM TBL_USER WHERE UserName=@user;", con); // sql query string
init_check.Parameters.AddWithValue("@user", Username); // add parameters
MySqlDataReader init_reader = init_check.ExecuteReader();
if (!init_reader.HasRows)
{
init_reader.Close();
MySqlCommand cmd = new MySqlCommand("INSERT INTO TBL_USER(UserName, PassWord) VALUES(@user, @pass)", con); // sql query string
cmd.Parameters.AddWithValue("@user", Username); // add parameters
cmd.Parameters.AddWithValue("@pass", Password);
cmd.ExecuteNonQuery(); // execute the query
res.msg = "User added successfully";
res.success = true;
MySqlCommand cmd2 = new MySqlCommand("SELECT UserID FROM TBL_USER WHERE UserName=@user;", con); // sql query string
cmd2.Parameters.AddWithValue("@user", Username); // add parameters
User u = new User();
using (MySqlDataReader reader = cmd2.ExecuteReader())
{
while (reader.Read()) // read in query results
{
u.UserId = reader.GetInt32(0);
};
}
// add to doctor table
MySqlCommand cmd3 = new MySqlCommand("INSERT INTO TBL_DOCTOR(LastName, FirstName,UserID) VALUES(@user, @pass,@userid)", con); // sql query string
cmd3.Parameters.AddWithValue("@user", Username); // add parameters
cmd3.Parameters.AddWithValue("@pass", Password);
cmd3.Parameters.AddWithValue("@userid", u.UserId);
cmd3.ExecuteNonQuery(); // execute the query
}
else
{
App.Current.MainPage.DisplayAlert("User already exists", "Please choose another username", "Ok");
}
}
}
catch (MySqlException ex)
{
res.msg = "Error occured, please try again";
res.success = false;
throw (ex);
}
finally
{
con.Close(); // close connection
}
return res;
}
}
}
|
using System;
using System.Windows.Forms;
namespace twpx.VIew
{
public partial class LoginForm : Form
{
Common Lcommon = new Common();
public LoginForm()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
if (Lcommon.GetCount() == 0)
{
MessageBox.Show("没有设备在线!");
Lcommon.AddLog("没有设备在线!");
return;
}
new FullScreen().Show();
Hide();
}
private void button1_Click(object sender, EventArgs e)
{
new Form1().Show();
Hide();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.SYS;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.TRANS
{
public partial class MrpExPlanItemRate
{
[Display(Name = "MrpExPlanItemRate_SectionDesc", ResourceType = typeof(Resources.MRP.MrpExPlanItemRate))]
public string SectionDesc { get; set; }
[Display(Name = "MrpExPlanItemRate_ItemDesc", ResourceType = typeof(Resources.MRP.MrpExPlanItemRate))]
public string ItemDesc { get; set; }
public bool IsNew { get; set; }
public bool IsDeleted { get; set; }
}
} |
using UnityEngine;
public class TaskRandomFly : TaskMovement<EntityBat> {
[SerializeField]
private int _minMoveDistance = 2;
[SerializeField]
private int _maxMoveDistance = 5;
[SerializeField, MinMaxSlider(0.01f, 60)]
private Vector2 _randomFlyTry = new Vector2(1, 1.5f);
private float timer;
public override void onTaskStart() {
base.onTaskStart();
this.timer = this.getRndTime();
}
public override bool shouldExecute() {
this.timer -= Time.deltaTime;
if(this.timer <= 0) {
this.timer = this.getRndTime();
int x = this.func();
int y = this.func();
Position dest = this.owner.position.add(x, y);
if(!this.owner.world.isOutOfBounds(dest) && this.owner.world.getCellState(dest).data.isWalkable) {
if(this.calculateAndSetPath(dest)) {
return true;
}
}
}
return false;
}
public override void onDestinationArive() {
base.onDestinationArive();
this.navPath = null;
}
public override bool continueExecuting() {
return this.navPath != null;
}
private int func() {
return Random.Range(this._minMoveDistance, this._maxMoveDistance + 1) * (Random.value > 0.5 ? 1 : -1);
}
private float getRndTime() {
return Random.Range(this._randomFlyTry.x, this._randomFlyTry.y);
}
}
|
using System.Collections.Generic;
using System.Web.Http;
using ILogging;
using ServiceDeskSVC.Domain.Entities.ViewModels.AssetManager;
using ServiceDeskSVC.Managers;
namespace ServiceDeskSVC.Controllers.API.AssetManager
{
public class SoftwareController : ApiController
{
private readonly IAssetManagerSoftwareManager _assetSoftwareManager;
private readonly ILogger _logger;
public SoftwareController(IAssetManagerSoftwareManager assetSoftwareManager, ILogger logger)
{
_assetSoftwareManager = assetSoftwareManager;
_logger = logger;
}
/// <summary>
/// Gets this instance.
/// </summary>
/// <returns></returns>
public IEnumerable<AssetManager_Software_View_vm> Get()
{
_logger.Info("Getting all Software assets.");
return _assetSoftwareManager.GetAllSoftwareAssets();
}
/// <summary>
/// Gets this instance.
/// </summary>
/// <returns></returns>
public AssetManager_Software_vm Get(int id)
{
_logger.Info("Getting single Software Asset with ID of " + id);
return _assetSoftwareManager.GetSoftwareAssetByID(id);
}
/// <summary>
/// Posts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Post([FromBody]AssetManager_Software_vm value)
{
_logger.Info("Creating a new software asset.");
return _assetSoftwareManager.CreateSoftwareAsset(value);
}
/// <summary>
/// Puts the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Put(int id, [FromBody]AssetManager_Software_vm value)
{
_logger.Info("Editing the software asset with id "+ id);
return _assetSoftwareManager.EditSoftwareAssetById(id, value);
}
/// <summary>
/// Deletes the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public bool Delete(int id)
{
_logger.Info("Deleting the software asset with id "+id);
return _assetSoftwareManager.DeleteSoftwareAssetById(id);
}
}
}
|
using System.Globalization;
using System.Text;
/// <summary>
/// ZPL 語言封裝類別
/// </summary>
namespace ZebraUDP
{
public class ZplCmdBuilder
{
private static readonly string START_ZPL = "^XA";
private static readonly string END_ZPL = "^XZ";
public static string ORI_NORMAL = "N"; //orientation Normal 旋轉參數,正常
public static string ORI_90 = "R"; //orientation 90 degrees 旋轉參數,90度 (順時針)
public static string ORI_180 = "I"; //orientation 180 degrees
public static string ORI_270 = "B"; //orientation 270 degrees
private readonly StringBuilder _zplCode = new StringBuilder(); //內置 Zpl 碼組合字串
private readonly CultureInfo _format = new CultureInfo("zh-TW");
/** 取得目前組合的 zpl 碼 */
public string GetZplCode() { return _zplCode.ToString(); }
/** 清空目前組合的 zpl 碼 */
public ZplCmdBuilder ClrZplCode()
{
_zplCode.Clear();
return this;
}
#region 一般通用函式
/** 取得完整的 zpl 段,自動包含 ZPL 開頭和結尾 */
public string GetZpl(params string[] strings)
{
if (strings != null)
{
StringBuilder result = new StringBuilder();
result.Append(START_ZPL);
for (int i = 0; i < strings.Length; i++)
{
result.Append(strings[i]);
}
result.Append(END_ZPL);
return result.ToString();
}
else
return null;
}
/** ZPL 區段起始標號 (放在 ZPL 語言開頭) */
public ZplCmdBuilder StartZPL()
{
_zplCode.Append(START_ZPL);
return this;
}
/** ZPL 區段終止標號 (放在 ZPL 語言結尾) */
public ZplCmdBuilder EndZPL()
{
_zplCode.Append(END_ZPL);
return this;
}
#endregion
#region 編碼指定
/**
* Select Encoding Table (選擇編碼) - 選擇編碼檔作為目前列印文字的編碼
* @param deviceAndCodename 編碼檔存放的裝置識別字元 與 編碼檔名,格式 : E:BIG5.DAT
* @return
*/
public ZplCmdBuilder SelectEncoding(string deviceAndCodename)
{
_zplCode.Append(string.Format(_format, "^SE{0}", deviceAndCodename));
return this;
}
/**
* Change International Font/Encoding (改變編碼) - 選擇目前列印文字的編碼
* @param encodingCode 編碼代號
* @return
*/
public ZplCmdBuilder ChgEncoding(int encodingCode)
{
_zplCode.Append(string.Format(_format, "^CI{0}", encodingCode));
return this;
}
#endregion
#region 字型設定
/**
* Font Identifier (設定預備字型) - 預先設定會使用到的字型的代號
* @param fontLetter 字型的代號字串,從 A-Z, 0-9
* @param deviceAndFontname 字型存放的裝置識別字元 與 字型檔名,格式 : E:BIG5.TTF
* @return
*/
public ZplCmdBuilder FontIdentifier(string fontLetter, string deviceAndFontname)
{
_zplCode.Append(string.Format(_format, "^CW{0},{1}", fontLetter, deviceAndFontname));
return this;
}
/**
* Change Alphanumeric Default Font (指定字母/數字預設字型) - 指定印表機預設字型的大小, 與 ^CW 配合使用
* @param fontLetter iMZ320 預設有 0-7 共八種字型
* @param width 電源開啟時預設 5
* @param height 電源開啟時預設 9
* @return
*/
public ZplCmdBuilder ChangeAlphanumericFont(string fontLetter, int width, int height)
{
_zplCode.Append(string.Format(_format, "^CF{0},{1},{2}", fontLetter, height, width));
return this;
}
/**
* Use Font Name to Call Font (使用字型) - 在接下來的列印中使用某個預備字型
* @param fontLetter 字型代號
* @param width 字寬 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @param height 字高 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @return
*/
public ZplCmdBuilder UseFontN(string fontLetter, int width, int height)
{
_zplCode.Append(string.Format(_format, "^A{0}N,{1},{2}", fontLetter, height, width));
return this;
}
/**
* Use Font Name to Call Font (使用字型) - 在接下來的列印中使用某個預備字型
* @param fontLetter 字型代號
* @param width 字寬 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @param height 字高 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @return
*/
public ZplCmdBuilder UseFont(string fontLetter, int width, int height)
{
_zplCode.Append(string.Format(_format, "^A{0},{1},{2}", fontLetter, height, width));
return this;
}
/**
* Use Font Name to Call Font (帶入字型檔名來使用字型)
* @param fontName 字型存放的裝置識別字元 與 字型檔名,格式 : E:BIG5.TTF
* @param width 字寬 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @param height 字高 (10 to 32000),沒設定的話,會以最後一次呼叫 ^CF 的設定值為主
* @return
*/
public ZplCmdBuilder UseFontByName(string fontName, int width, int height)
{
_zplCode.Append(string.Format(_format, "^A@N,{0},{1},{2}", height, width, fontName));
return this;
}
#endregion
#region Label 設定
/**
* Label Length (設定標籤長度)
* @param y 長度 (dots, 1 - 32000)
* @return
*/
public ZplCmdBuilder LabelLength(int y)
{
_zplCode.Append(string.Format(_format, "^LL{0}", y));
return this;
}
/**
* Label Home (設定標籤起點座標)
* @param x 標籤 x 起點
* @param y 標籤 y 起點
* @return
*/
public ZplCmdBuilder LabelHome(int x, int y)
{
_zplCode.Append(string.Format(_format, "^LH{0},{1}", x, y));
return this;
}
#endregion
#region Field 設定
/**
* Field Parameter (Field參數設定) - 設定列印的方向以及字距
* align H: horizontal printing, V: vertical printing, R: reverse printing
* gap 字距
* */
public ZplCmdBuilder FieldParam(int gap)
{
_zplCode.Append(string.Format(_format, "^FP{0},{1}", "H", gap));
return this;
}
/**
* Field Origin (Field初始設定) - 設定 ^LH 後的第一個 field (最左上角)
* align 0: left , 1: right, 2: auto
* */
public ZplCmdBuilder FieldOrigin(int x, int y, int align)
{
_zplCode.Append(string.Format(_format, "^FO{0},{1},{2}", x, y, align));
return this;
}
/**
* Field Typeset (Field格式設定) - 與 ^FO 相似,但是針對後續要列印的欄位做設定
* align 0: left , 1: right, 2: auto
* */
public ZplCmdBuilder FieldType(int x, int y, int align)
{
_zplCode.Append(string.Format(_format, "^FT{0},{1},{2}", x, y, align));
return this;
}
/**
* Field Block (Field區塊設定),主要用來做文字對齊用
* align: L: left , R: right, C:center, J:justified
* */
public ZplCmdBuilder FieldBlock(string align)
{
_zplCode.Append(string.Format(_format, "^FB576,1,0,{0},0", align));
return this;
}
/**
* Field Data (欄位資料)
* data: 要印出的資料
* */
public ZplCmdBuilder FieldData(string data)
{
_zplCode.Append(string.Format(_format, "^FD{0}", data));
return this;
}
/**
* Field Separator (換行)
* */
public ZplCmdBuilder FieldSeparator()
{
_zplCode.Append(string.Format(_format, "^FS"));
return this;
}
/**
* Field Orientation (選轉)
* @param rotation : N:normal, R:rotation 90, I:Inverted 180, B:Bottom-Up 270(read from bottom up)
* @return
*/
public ZplCmdBuilder FieldOrientation(string rotation)
{
_zplCode.Append(string.Format(_format, "^FW{0}", rotation));
return this;
}
#endregion
/**
* 印出 BarCode 128 (包含換行)
* ^FO20,10 ^FO 設定條碼左上角的位置 , 0, 0代表完全不留邊距
* ^BCN,,Y,N ^BC 印 code128 的指令
* ^FD01008D004Q-0^FS ^FD 設定要印的内容, ^FS表示換行
* @param start_x 起始 x 座標
* @param start_y 起始 y 座標
* @param height 條碼高度
* @param code 條碼字串
* @return
*/
public ZplCmdBuilder BarCode128(int start_x, int start_y, int height, string code)
{
_zplCode.Append(string.Format(_format, "^FO{0},{1},2^BCN,{2},N,N,N^FD{3}^FS", start_x, start_y, height, code));
return this;
}
/** 印出 BarCode 39 (包含換行) */
public ZplCmdBuilder BarCode39(int start_x, int start_y, int height, string code)
{
_zplCode.Append(string.Format(_format, "^FO{0},{1},2^B3N,N,{2},N,N^FD{3}^FS", start_x, start_y, height, code));
return this;
}
/**
* 印出 QRCode (包含換行)
* @param start_x 起點 x
* @param start_y 起點 y
* @param size 大小 ( 1 to 10, 共10種等級)
* @param code 要編碼的文字 (注意,zebra 的 QRcode有附加設定,可在 FD 欄位中另外設定,故底下在 FD 後帶的 QA 即是附加設定)
* @return
*/
public ZplCmdBuilder QrCode(int start_x, int start_y, int size, string code)
{
_zplCode.Append($"^FO{start_x},{start_y},2^BQN,2,{size}^FDMA,{code}^FS");
return this;
}
/// <summary>
/// 打印英文
/// </summary>
/// <param name="EnText">待打印文本</param>
/// <param name="ZebraFont">打印機字體 A-Z</param>
/// <param name="px">終點X坐標</param>
/// <param name="py">終點Y坐標</param>
/// <param name="Orient">扭轉角度N = normal,R = rotated 90 degrees (clockwise),I = inverted 180 degrees,B = read from bottom up, 270 degrees</param>
/// <param name="Height">字體高度</param>
/// <param name="Width">字體寬度</param>
/// <returns>前往ZPL敕令</returns>
public ZplCmdBuilder Text(string EnText, string ZebraFont, int px, int py, string Orient, int Height, int Width)
{
//ZPL打印英文敕令:^FO50,50^A0N,32,25^FDZEBRA^FS
_zplCode.Append($"^FO{px},{py}^A { ZebraFont} {Orient},{Height},{Width}^FD{EnText}^FS");
return this;
}
/**
* Graphic Box 畫框框
* @param width 寬 (邊框寬度 to 32000)
* @param height 高 (邊框寬度 to 32000)
* @param border 邊框寬度 ( 1 to 32000)
* @param degree 圓角
* @return
*/
public ZplCmdBuilder GraphicBox(int width, int height, int border, int degree)
{
_zplCode.Append(string.Format(_format, "^GB{0},{1}, {2}, B, {3}", width, height, border, degree));
return this;
}
}
}
|
using MyBlog.WebApi.Framework.DTOs;
namespace MyBlog.WebApi.DTOs.Blogs
{
public class BlogPostForFilteringDto : BasePagingQueryStringParameters
{
public string Tag { get; set; }
}
}
|
using System;
using System.Windows.Data;
namespace DameGUI.Data
{
public class PlayerConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int idx = (int)value;
if (idx % 2 == 0) { return "Bílý"; }
return "Černý";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return "";
}
}
} |
using System;
using System.Linq;
using Xunit;
namespace NStandard.Test
{
public class ArrayExtensionsTests
{
private class Class { }
[Fact]
public void LetTest1()
{
var arr = new int[5].Let(i => i * 2 + 1);
Assert.Equal(new[] { 1, 3, 5, 7, 9 }, arr);
}
[Fact]
public void LetTest2()
{
var arr = new int[2, 3].Let((i0, i1) => i0 * 3 + i1);
Assert.Equal(new[,] { { 0, 1, 2 }, { 3, 4, 5 } }, arr);
}
[Fact]
public void LetTest3()
{
var arr = new int[2, 3, 2].Let((i0, i1, i2) => i0 * 6 + i1 * 2 + i2);
Assert.Equal(new[, ,]
{
{ { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } },
}, arr);
}
[Fact]
public void LetTest4()
{
var arr = new int[2, 2, 3, 2].Let(indices => indices[0] * 12 + indices[1] * 6 + indices[2] * 2 + indices[3]) as int[,,,];
Assert.Equal(new[, , ,]
{
{
{
{ 0, 1 }, { 2, 3 }, { 4, 5 }
},
{
{ 6, 7 }, { 8, 9 }, { 10, 11 }
},
},
{
{
{ 12, 13 }, { 14, 15 }, { 16, 17 }
},
{
{ 18, 19 }, { 20, 21 }, { 22, 23 }
},
}
}, arr);
}
[Fact]
public void LetClassTest()
{
var classes = new Class[2].Let(i => new Class());
Assert.NotNull(classes[0]);
Assert.NotNull(classes[1]);
}
[Fact]
public void ShuffleTest()
{
var random = new Random();
var arr = new int[100].Let(i => i);
arr.Shuffle();
}
[Fact]
public void JaggedArrayTest()
{
var arr = new string[2, 3]
{
{ "0,0", "0,1", "0,2" },
{ "1,0", "1,1", "1,2" },
};
arr.Each((v, i1, i2) =>
{
Assert.Equal($"{i1},{i2}", v);
Assert.Equal($"{i1},{i2}", arr[i1, i2]);
});
}
[Fact]
public void DeconstructTest()
{
var arr = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var (i1, i2, i3, i4, i5, i6, i7, (i8, _)) = arr;
Assert.Equal(1, i1);
Assert.Equal(2, i2);
Assert.Equal(3, i3);
Assert.Equal(4, i4);
Assert.Equal(5, i5);
Assert.Equal(6, i6);
Assert.Equal(7, i7);
Assert.Equal(8, i8);
}
[Fact]
public void LocateTest()
{
Assert.Equal(15, "BBC ABCDAB ABCDABCDABDE".ToCharArray().Locate("ABCDABD".ToCharArray()));
Assert.Equal(0, "AAAA".ToCharArray().Locate("AA".ToCharArray()));
Assert.Equal(0, "A".ToCharArray().Locate("A".ToCharArray()));
Assert.ThrowsAny<ArgumentException>(() => "A".ToCharArray().Locate("".ToCharArray()));
}
[Fact]
public void LocatesTest()
{
Assert.Single("BBC ABCDAB ABCDABCDABDE".ToCharArray().Locates("ABCDABD".ToCharArray()));
Assert.Equal(3, "AAAA".ToCharArray().Locates("AA".ToCharArray()).Count());
Assert.Single("A".ToCharArray().Locates("A".ToCharArray()));
Assert.ThrowsAny<ArgumentException>(() => "A".ToCharArray().Locates("".ToCharArray()));
}
}
}
|
using System;
using System.Collections.Generic;
namespace Cradiator.Config
{
// ReSharper disable UnusedMemberInSuper.Global
public interface IConfigSettings : IViewSettings
{
int PollFrequency { get; set; }
bool ShowCountdown { get; set; }
TimeSpan PollFrequencyTimeSpan { get; }
string BrokenBuildSound { get; set; }
string FixedBuildSound { get; set; }
string BrokenBuildText { get; set; }
string FixedBuildText { get; set; }
bool PlaySounds { get; set; }
bool PlaySpeech { get; set; }
string SpeechVoiceName { get; set; }
bool ShowProgress { get; set; }
IDictionary<string, string> UsernameMap { get; }
GuiltStrategyType BreakerGuiltStrategy { get; }
void AddObserver(IConfigObserver observer);
void Load();
void NotifyObservers();
void Save();
void RotateView();
void Log();
}
// ReSharper restore UnusedMemberInSuper.Global
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Embraer_Backend.Models;
using Microsoft.Extensions.Configuration;
using System;
using Microsoft.AspNetCore.Cors;
using System.Linq;
namespace Embraer_Backend.Controllers
{
[Route("api/[controller]/[action]")]
[EnableCors("CorsPolicy")]
public class ParametrosController : Controller
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ParametrosController));
private readonly IConfiguration _configuration;
ParametrosModel _prtmModel = new ParametrosModel();
IEnumerable <Parametros> prtm;
public ParametrosController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
public IActionResult Index()
{
return Ok(_prtmModel.SelectParametros(_configuration,0,null));
}
//Get api/GetParametros
[HttpGet]
public IActionResult GetParametros(long IdLocalMedicao, string DescParam)
{
log.Debug("Get Dos parametros pelo IdLocalMedicao "+ IdLocalMedicao + "E descrição:"+ DescParam);
prtm=_prtmModel.SelectParametros(_configuration,IdLocalMedicao,DescParam);
return Json(prtm);
}
[HttpPut]
public IActionResult PutParametros([FromBody]Parametros _parametros)
{
if (ModelState.IsValid)
{
var insert = _prtmModel.UpdateParametros(_configuration,_parametros);
if(insert==true)
{
log.Debug("Post do Apontamento com sucesso:" + _parametros);
return Json(_parametros);
}
return StatusCode(500,"Houve um erro, verifique o Log do sistema!");
}
else
log.Debug("Post não efetuado, Bad Request" + ModelState.ToString());
return BadRequest(ModelState);
}
}
} |
namespace MyQueue
{
using System;
using System.Collections.Generic;
/// <summary>
/// This is a queue that holds 5 integers.
/// </summary>
public class MyQueue : MyQueueBase, IMyQueue
{
public MyQueue()
{
Values = new List<int>();
}
public const int MaximumNumberOfQueueItems = 100;
public const int MaximumIntegerValue = 99;
public List<int> Values { get; set; }
public int Count
{
get
{
return Values.Count;
}
}
public void Add(int newIntegerValue)
{
if (!MaximumQueueLimitReached() && IsPositiveInteger(newIntegerValue) && !IsMaximumIntegerValue(newIntegerValue))
{
Values.Add(newIntegerValue);
}
}
private bool IsMaximumIntegerValue(int value)
{
if (value > MaximumIntegerValue)
{
throw new ArgumentOutOfRangeException();
}
return false;
}
public int GetValue(int position)
{
return Values[position];
}
public void Remove(int position)
{
Values.RemoveAt(position);
}
private bool MaximumQueueLimitReached()
{
if (Values.Count >= MaximumNumberOfQueueItems)
{
throw new ArgumentException(string.Format("Maximum number of queue items reached: {0}", MaximumNumberOfQueueItems));
}
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using Plugin.FileUploader;
using Plugin.FileUploader.Abstractions;
using Plugin.Media;
using Plugin.Media.Abstractions;
using Xamarin.Forms;
namespace LorikeetMApp
{
public partial class TakePicture : ContentPage
{
private string memberIDGUID = null;
private string fileToUpload = string.Empty;
private Queue<string> paths = new Queue<string>();
private bool isBusy = false;
public static Data.MemberManager memberManager { get; private set; }
public TakePicture()
{
InitializeComponent();
}
public TakePicture(String memberIDGUID)
{
InitializeComponent();
this.memberIDGUID = memberIDGUID;
memberManager = new Data.MemberManager(new Data.RestService());
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
SaveToAlbum = false,
CompressionQuality = 75,
CustomPhotoSize = 50,
PhotoSize = PhotoSize.MaxWidthHeight,
MaxWidthHeight = 1000,
DefaultCamera = CameraDevice.Front,
Name = this.memberIDGUID + ".jpg"
});
if (file == null)
return;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
string fileToCopyTo = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), memberIDGUID + ".jpg");
File.Copy(file.Path, fileToCopyTo, true);
fileToUpload = fileToCopyTo;
uploadPhoto.IsVisible = true;
};
pickPhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (file == null)
return;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
string fileToCopyTo = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), memberIDGUID + ".jpg");
File.Copy(file.Path, fileToCopyTo, true);
fileToUpload = fileToCopyTo;
uploadPhoto.IsVisible = true;
};
uploadPhoto.Clicked += async (sender, args) =>
{
if (fileToUpload != null)
{
if (isBusy)
return;
isBusy = true;
progress.IsVisible = true;
//Uploading multiple images at once
/*List<FilePathItem> pathItems = new List<FilePathItem>();
while (paths.Count > 0)
{
pathItems.Add(new FilePathItem("image",paths.Dequeue()));
}*/
await CrossFileUploader.Current.UploadFileAsync(Constants.UPLOAD_URL, new FilePathItem("file", fileToUpload));
}
};
okButton.Clicked += (sender, args) =>
{
this.Navigation.PopAsync();
};
downloadPhoto.Clicked += async (sender, args) =>
{
try
{
var fileToDownloadTo = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), memberIDGUID + ".jpg");
var worked = await memberManager.DownloadImageFileAsync(memberIDGUID + ".jpg", fileToDownloadTo);
if ((image != null) && worked.Equals("worked"))
{
image.Source = ImageSource.FromFile(fileToDownloadTo);
}
else
{
await DisplayAlert("File Download Error", worked, "Ok");
}
}
catch (Exception ex)
{
await DisplayAlert("File Download Error", ex.Message, "Ok");
}
};
CrossFileUploader.Current.FileUploadCompleted += Current_FileUploadCompleted;
CrossFileUploader.Current.FileUploadError += Current_FileUploadError;
CrossFileUploader.Current.FileUploadProgress += Current_FileUploadProgress;
}
private void Current_FileUploadProgress(object sender, FileUploadProgress e)
{
Device.BeginInvokeOnMainThread(() =>
{
progress.Progress = e.Percentage / 100.0f;
});
}
private void Current_FileUploadError(object sender, FileUploadResponse e)
{
isBusy = false;
System.Diagnostics.Debug.WriteLine($"{e.StatusCode} - {e.Message}");
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("File Upload", "Upload Failed", "Ok");
progress.IsVisible = false;
progress.Progress = 0.0f;
});
}
private void Current_FileUploadCompleted(object sender, FileUploadResponse e)
{
isBusy = false;
System.Diagnostics.Debug.WriteLine($"{e.StatusCode} - {e.Message}");
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("File Upload", "Upload Completed", "Ok");
progress.IsVisible = false;
progress.Progress = 0.0f;
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace Allyn.Application.Dto.Manage.Front
{
/// <summary>
/// 表示产品类别实体的修改数据传输对象.
/// </summary>
[DataContractAttribute(Namespace = "http://www.allyn.com.cn/category-edit-dto")]
public class CategoryEditDto
{
/// <summary>
/// 获取或设置类别标识.
/// </summary>
[DataMemberAttribute(Order = 0)]
public Guid Id { get; set; }
/// <summary>
/// 获取或设置标题
/// </summary>
[DataMemberAttribute(Order = 1)]
public string Title { get; set; }
/// <summary>
/// 获取或设置备注信息.
/// </summary>
[DataMemberAttribute(Order = 2)]
public string Description { get; set; }
/// <summary>
/// 获取或设置启用标识.
/// </summary>
[DataMemberAttribute(Order = 3)]
public bool Disabled { get; set; }
/// <summary>
/// 获取或设置修改者.
/// </summary>
[DataMemberAttribute(Order = 4)]
public Guid? Modifier { get; set; }
/// <summary>
/// 获取或设置更新时间.
/// </summary>
[DataMemberAttribute(Order = 5)]
public DateTime? UpdateDate { get; set; }
}
}
|
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace net_tech_cource {
public class SimpleClient {
public readonly string uuid;
public readonly string Name;
private string ipAdress;
private int port;
private Socket socket;
private Action<String> logger;
private Func<string> input;
public SimpleClient (string uuid, string ipAdress, int port, Action<String> logger, Func<string> input) {
this.uuid = uuid;
this.Name = $"Client<{uuid}>";
this.ipAdress = ipAdress;
this.port = port;
this.logger = logger;
this.input = input;
IPAddress address = IPAddress.Parse (ipAdress);
this.socket = new Socket (
address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
}
public void Connect () {
this.socket.ConnectAsync (ipAdress, port)
.ContinueWith (handleConnection);
}
private bool handleConnection (Task task) {
try {
logger ($"{Name} connected...");
while (Messaging());
return true;
} catch (Exception e) {
logger ($"{Name} exception: {e}");
return false;
} finally {
logger($"{Name} Shutdown");
socket.Shutdown (SocketShutdown.Both);
socket.Close ();
}
}
private bool Messaging() {
var message = input();
SocketHelper.SendMessage (socket, message);
if (message == ".exit") {
return false;
} else {
var text = SocketHelper.ReadMessage (socket);
logger ($"{Name} recieved: {text}");
return true;
}
}
}
} |
using System;
namespace Reactive.Flowable
{
public interface IFlowable<out T> : IPublisher<T>
{
}
} |
using Alabo.Domains.Entities;
using System.Collections.Generic;
namespace Alabo.UI.Design.AutoTables {
/// <summary>
/// 自动表单,可以构建前台自动列表
/// </summary>
public interface IAutoTable {
/// <summary>
/// 操作链接
/// </summary>
/// <returns></returns>
List<TableAction> Actions();
}
/// <summary>
/// 自动表单,可以构建前台自动列表
/// </summary>
public interface IAutoTable<T> : IAutoTable {
/// <summary>
/// 通用分页查询列表
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
PageResult<T> PageTable(object query, AutoBaseModel autoModel);
}
} |
using UnityEngine;
using System.Collections;
public class TutorialGradient : MonoBehaviour
{
private MeshRenderer gradientRenderer;
private Color alphaZero;
private Color alphaOne;
public float tweenDuration;
public float tweenCount;
private bool hasStarted;
void Start()
{
hasStarted = false;
gradientRenderer = GetComponent<MeshRenderer>();
alphaZero = new Color(gradientRenderer.material.color.r, gradientRenderer.material.color.g, gradientRenderer.material.color.b, 0f);
alphaOne = new Color(gradientRenderer.material.color.r, gradientRenderer.material.color.g, gradientRenderer.material.color.b, 1f);
gameObject.SetActive(false);
}
void OnEnable()
{
/*
if (!hasStarted)
{
hasStarted = true;
return;
}
*/
//FlickerCo();
}
public void Flip()
{
float value = transform.localPosition.x;
transform.localPosition = new Vector3(-value, transform.localPosition.y, transform.localPosition.z);
}
public void Flicker()
{
StartCoroutine(FlickerCo());
}
IEnumerator FlickerCo()
{
Debug.Log("Hongyeol3");
float t = 0f;
float count = 0f;
Color fromColor = alphaZero;
Color toColor = alphaOne;
while (count < tweenCount)
{
gradientRenderer.material.color = Color.Lerp(fromColor, toColor, t);
if (t > 1)
{
t = 0f;
count++;
if (count % 2 == 0)
{
fromColor = alphaZero;
toColor = alphaOne;
}
else
{
fromColor = alphaOne;
toColor = alphaZero;
}
}
else
{
t += Time.deltaTime / tweenDuration;
}
yield return null;
}
gameObject.SetActive(false);
}
}
|
using System.Text;
using EqualExperts.Core.Interfaces;
namespace EqualExperts.Core
{
public class NumberProcessor : INumberProcessor
{
private readonly IMathUtilities _mathUtilities;
public NumberProcessor(IMathUtilities mathUtilities)
{
_mathUtilities = mathUtilities;
}
public string ProcessNumber(int input)
{
if (_mathUtilities.ContainsNumberThree(input))
{
return Constants.ContainsNumberThree;
}
var sb = new StringBuilder();
if (_mathUtilities.IsDividibleByThree(input))
{
sb.Append(Constants.DivisibleBy3Prefix);
}
if (_mathUtilities.IsDividibleByFive(input))
{
sb.Append(Constants.DivisibleBy5Prefix);
}
var result = sb.ToString();
if (string.IsNullOrWhiteSpace(result))
{
return input.ToString();
}
return result;
}
}
} |
using BankAppCore.Data.Converters;
using BankAppCore.Data.EFContext;
using BankAppCore.Data.Repositories;
using BankAppCore.DataTranferObjects;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using static BankAppCore.Data.EFContext.EFContext;
namespace BankAppCore.Services
{
public class EmployeeService : IEmployeeService
{
private ApplicationUserRepository employeeRepository;
public EmployeeService(ShopContext context,UserManager<ApplicationUser> userManager)
{
this.employeeRepository = new ApplicationUserRepository(context,userManager);
}
public IEnumerable<EmployeeDTO> getAllEmployees()
{
return EmployeeConverter.toDtos(employeeRepository.Get());
}
public EmployeeDTO getEmployeeById(string accountId)
{
ApplicationUser user = employeeRepository.GetByID(accountId);
if (user == null) throw new InvalidOperationException("No Employee found with that Id");
return EmployeeConverter.toDto(user);
}
public EmployeeDTO createEmployee(EmployeeDTO employeeDTO)
{
ApplicationUser user = employeeRepository.GetByID(employeeDTO.Id);
if (user == null)
{
ApplicationUser newUser = new ApplicationUser()
{
Email = employeeDTO.Username,
SecurityStamp = Guid.NewGuid().ToString(),
UserName = employeeDTO.Username,
RegisterDate = DateTime.Now
};
return EmployeeConverter.toDto(employeeRepository.GetByID(employeeDTO.Id));
}
else
{
throw new InvalidOperationException("User already exists");
}
}
public void updateEmployee(PasswordChangeModel passwordChangeModel)
{
employeeRepository.Update(passwordChangeModel);
}
public void deleteEmployee(string employeeId)
{
}
}
}
|
using SpeedSlidingTrainer.Core.Model;
namespace SpeedSlidingTrainer.Application.Events
{
public sealed class SlideHappened
{
public SlideHappened(Step step, bool boardSolved)
{
this.Step = step;
this.BoardSolved = boardSolved;
}
public Step Step { get; }
public bool BoardSolved { get; }
}
}
|
using System;
using Matrix = System.Numerics.Matrix4x4;
namespace Jypeli
{
/// <summary>
/// Kirjaimen valitsin.
/// </summary>
public class LetterPicker : Label
{
private int _selectedIndex;
private char _selectedCharacter;
private readonly SynchronousList<Listener> _controls = new SynchronousList<Listener>();
private Touch _touch = null;
private double _touchStart = 0;
private double _indexDelta = 0;
private double _indexVelocity = 0;
/// <summary>
/// Tapahtuu kun kirjainta muutetaan.
/// </summary>
public event Action<LetterPicker> LetterChanged;
/// <summary>
/// Merkit joita käytetään.
/// </summary>
public string Charset { get; set; }
/// <inheritdoc/>
public override Font Font
{
get { return base.Font; }
set { base.Font = value; UpdateSize(); }
}
/// <summary>
/// Koko
/// </summary>
public override Vector Size
{
get { return base.Size; }
set { base.Size = value; UpdateSize(); }
}
/// <summary>
/// Valitun merkin indeksi.
/// </summary>
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = AdvMod(value, Charset.Length);
_selectedCharacter = Charset[_selectedIndex];
Text = _selectedCharacter.ToString();
OnLetterChanged();
}
}
/// <summary>
/// Valittu merkki.
/// </summary>
public char SelectedCharacter
{
get { return _selectedCharacter; }
set
{
SelectedIndex = Charset.IndexOf(value);
_selectedCharacter = value;
Text = value.ToString();
OnLetterChanged();
}
}
/// <summary>
/// Nuoli ylöspäin.
/// </summary>
public Widget UpArrow { get; set; }
/// <summary>
/// Nuoli alaspäin.
/// </summary>
public Widget DownArrow { get; set; }
/// <summary>
/// Alustaa uuden kirjainvalitsimen.
/// </summary>
/// <param name="width">Leveys.</param>
/// <param name="height">Korkeus.</param>
/// <param name="charset">Käytettävät merkit.</param>
/// <param name="initialCharacter">Oletusmerkki</param>
public LetterPicker(double width, double height, string charset = "", char initialCharacter = 'a')
: base(width, height)
{
Charset = (charset.Length > 0) ? charset : Jypeli.Charset.Alphanumeric + " ";
base.Font = new Font(40);
SelectedCharacter = initialCharacter;
YMargin = 10;
UpArrow = new Widget(this.Width, 10, Shape.Triangle);
UpArrow.Top = this.Height / 2;
UpArrow.Color = Color.Red;
Add(UpArrow);
DownArrow = new Widget(this.Width, 10, Shape.Triangle);
DownArrow.Bottom = -this.Height / 2;
DownArrow.Angle = Angle.StraightAngle;
DownArrow.Color = Color.Red;
Add(DownArrow);
AddedToGame += AddControls;
Removed += RemoveControls;
}
internal LetterPicker Clone()
{
// TODO: make a better clone method, maybe using the DataStorage load / save system
var lpClone = new LetterPicker(this.Width, this.Height, this.Charset, this.SelectedCharacter);
lpClone.Font = this.Font;
lpClone.Color = this.Color;
lpClone.BorderColor = this.BorderColor;
lpClone.TextColor = this.TextColor;
lpClone.TextScale = this.TextScale;
lpClone.SizeMode = this.SizeMode;
lpClone.UpArrow.Color = this.UpArrow.Color;
lpClone.DownArrow.Color = this.DownArrow.Color;
lpClone.UpArrow.Animation = this.UpArrow.Animation;
lpClone.DownArrow.Animation = this.DownArrow.Animation;
lpClone.UpArrow.Angle = this.UpArrow.Angle;
lpClone.DownArrow.Angle = this.DownArrow.Angle;
return lpClone;
}
private void UpdateSize()
{
UpArrow.Width = this.Width;
DownArrow.Width = this.Width;
UpArrow.Top = this.Height / 2;
DownArrow.Bottom = -this.Height / 2;
}
private void OnLetterChanged()
{
if (LetterChanged != null)
LetterChanged(this);
}
private void AddControls()
{
_controls.Add(Game.TouchPanel.ListenOn(this, ButtonState.Pressed, StartDrag, null).InContext(this));
_controls.Add(Game.TouchPanel.Listen(ButtonState.Released, EndDrag, null).InContext(this));
}
private void RemoveControls()
{
// SynchronousList removes every destroyed object automatically
_controls.ForEach(c => c.Destroy());
}
private void StartDrag(Touch touch)
{
if (_touch != null)
return;
_touch = touch;
_touchStart = touch.PositionOnScreen.Y;
}
private void EndDrag(Touch touch)
{
if (_touch != touch)
return;
double delta = _touch != null ? (_touch.PositionOnScreen.Y - _touchStart) / TextSize.Y : 0;
_touch = null;
if (touch.MovementOnScreen.Y < 1)
{
// Set the index now
SelectedIndex += (int)Math.Round(delta);
_indexDelta = 0;
}
else
{
// Continue scrolling
_indexDelta = delta;
_indexVelocity = 100 * touch.MovementOnScreen.Y / TextSize.Y;
}
}
private int AdvMod(int x, int n)
{
if (n <= 0)
return -1;
while (x < 0)
x += n;
while (x >= n)
x -= n;
return x;
}
/// <inheritdoc/>
public override void Update(Time time)
{
if (_touch != null)
{
_indexDelta = (_touch.PositionOnScreen.Y - _touchStart) / TextSize.Y;
}
else if (_indexVelocity > 0)
{
_indexDelta += Math.Sign(_indexDelta) * _indexVelocity * time.SinceLastUpdate.TotalSeconds;
_indexVelocity *= 0.95;
if (_indexVelocity < 1.5)
{
SelectedIndex += (int)Math.Round(_indexDelta);
_indexDelta = 0;
_indexVelocity = 0;
}
}
_controls.UpdateChanges();
base.Update(time);
}
/// <inheritdoc/>
public override void Draw(Matrix parentTransformation, Matrix transformation)
{
if (_indexDelta == 0)
{
base.Draw(parentTransformation, transformation);
return;
}
int indexDeltaInt = (int)Math.Round(_indexDelta);
double yDelta = _indexDelta - indexDeltaInt; // for smooth scrolling
for (int i = -1; i <= 1; i++)
{
Matrix m = Matrix.CreateScale((float)TextScale.X, (float)TextScale.Y, 1)
* Matrix.CreateRotationZ((float)Angle.Radians)
* Matrix.CreateTranslation((float)Position.X, (float)(Position.Y - (i - yDelta) * TextSize.Y), 0)
* parentTransformation;
int ci = AdvMod(this.SelectedIndex + indexDeltaInt + i, this.Charset.Length);
//Renderer.DrawText( Charset[ci].ToString(), ref m, Font, TextColor );
}
}
}
}
|
//==============================================================================
// Copyright (c) 2012-2020 Fiats Inc. All rights reserved.
// https://www.fiats.asia/
//
namespace Financial.Extensions
{
// Based on ISO4217
public enum CurrencyCode
{
AUD = 36, // Australian dollar
CNY = 156, // Yuan Renminbi
HKD = 344, // Hong Kong dollar
JPY = 392, // Japanese yen
KRW = 410, // Source Korean won
SGD = 702, // Singapore dollar
ZAR = 710, // South african Rand
THB = 764, // Thai baht
RUR = 810, // Russian Ruble
GBP = 826, // Pound sterling
USD = 840, // United States dollar
EUR = 978, // Euro
}
}
|
namespace Cs_Notas.Infra.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AlterarEscritura : DbMigration
{
public override void Up()
{
AddColumn("dbo.Escrituras", "TipoAtoCesdi", c => c.Int());
AlterColumn("dbo.Escrituras", "NaturezaCensec", c => c.Int());
DropColumn("dbo.Escrituras", "TipoAtoCensec");
}
public override void Down()
{
AddColumn("dbo.Escrituras", "TipoAtoCensec", c => c.String(maxLength: 100, unicode: false));
AlterColumn("dbo.Escrituras", "NaturezaCensec", c => c.String(maxLength: 100, unicode: false));
DropColumn("dbo.Escrituras", "TipoAtoCesdi");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
[HideInInspector]
//public string itemToDrop, itemToPick;
GameObject itemHeld;
GameObject itemToPick, itemToDrop;
GameObject itemOnHotspot;
PlayerStates playerStates;
// Use this for initialization
void Start()
{
playerStates = gameObject.GetComponent<PlayerStates>();
}
public void HotSpotItemHandler(GameObject hotspot)
{
ItemHeld(); //what do I have in hand?
ItemOnHotspot(hotspot);
HotspotHandler hotspotScript= hotspot.GetComponent<HotspotHandler>();
if (itemOnHotspot != null)
{
playerStates.ItemInHand = itemOnHotspot;
/*itemToPick = itemOnHotspot;
itemOnHotspot = null;
print("Neco jsem sebral! A je to" + itemToPick.tag);
*/
//itemToPick.SetActive(false);
//itemToPick.transform.SetParent(gameObject.transform); //hang it to a Player but invisible
}
if (itemHeld != null)
{
itemToDrop = itemHeld;
itemHeld = null;
itemToDrop.SetActive(true);
hotspotScript.itemOnHotspot = itemToDrop;
hotspotScript.SpawnObject();
Destroy(itemToDrop);
//itemToDrop.transform.SetParent(hotspot.transform);
}
}
public void ItemOnHotspot(GameObject hotspot)
{
Transform[] ts = hotspot.GetComponentsInChildren<Transform>();
foreach (Transform t in ts) //is there any item on the hotspot?
{
if (t.tag=="Item")
{
itemOnHotspot = t.gameObject;
}
}
}
public void ItemHeld()
{
foreach (Transform child in transform)
if (child.CompareTag("Item"))
{
itemHeld = child.gameObject;
}
/*
Transform[] th = gameObject.
itemHeld= gameObject.transform.GetComponentsInChildren<PickableItem>().;
foreach (Transform t in th) //is there any item held by Player?
{
print("Sem nasel:"+ t.tag);
if (t.tag == "Item")
{
print("co maaaa hobitek v rusissce???");
itemHeld = t.gameObject;
print("Item v ruce" + itemHeld);
}
}
*/
}
}
|
using System;
using System.Windows.Forms;
namespace StockTracking
{
public class isGeneral
{
internal static bool isNumber(KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
return true;
else
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using X1PL_Backend.Interpretations;
using X1PL_Backend.IO;
using X1PL_Backend.Structures;
namespace X1PL_Backend
{
public class X1PL_Easy
{
public X1PL_Easy(string conrsPath)
{
StructureComprehender.Work(conrsPath, out FileLayout[] files);
CommandLayout[] commandLayouts = new CommandLayout[files.Length - 1];
for (int line = 0; line < files.Length; line++)
{
for (int word = 0; word < files[line].lines.Length; word++)
{
var sp = files[0].lines[line].Split(' ');
commandLayouts[line].Keyword = sp[0];
commandLayouts[line].Args = new Type[sp.Length - 2];
foreach (var i in sp)
{
if (commandLayouts[line].Keyword == i) { continue; }
try
{
double.Parse(i);
commandLayouts[line].Args[word] = typeof(double);
}
catch
{
commandLayouts[line].Args[word] = typeof(string);
}
}
commandLayouts[line].ArgsString = sp;
}
}
CompleteCommand[] commands = Interpreter.GetCommands(commandLayouts);
foreach (var i in commands)
{
switch (i.command)
{
case Commands.Print:
{ Console.WriteLine(i.ComLay.ArgsString[1].ToString()); }
break;
default:
{ }
break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace League.Models
{
public class Dojo
{
[Key]
public long id { get; set; }
[Required]
[MinLength(3, ErrorMessage = "Name must be at least 3 characters")]
[Display(Name = "Name")]
public string name { get; set; }
[Required]
[MinLength(3, ErrorMessage = "Location must be at least 3 characters")]
[Display(Name = "Location")]
public string location { get; set; }
[Required]
[Display(Name = "Description")]
public string description { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public IEnumerable<Ninja> ninjas { get; set; }
public Dojo()
{
ninjas = new List<Ninja>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace UmbracoAarhus.ViewModels
{
public class ContactForm
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Waddup, invalid email, my friend")]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
[Required]
public string Message { get; set; }
}
} |
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float crouchSpeed = 2f;
[SerializeField] private float walkingSpeed = 4f;
[SerializeField] private float sprintingSpeed = 8f;
[SerializeField] private float turnSpeed = 5.0F;
[SerializeField] private float jumpHeight = 12.0F;
[SerializeField] private float gravityScale = 1f;
[SerializeField] private float DashDistance = 10f;
[SerializeField] private Vector3 Drag = new Vector3(5f, 0f, 5f);
private CharacterController m_Controller;
private Animator m_Animator;
private Rigidbody m_Rigidbody;
private float m_CapsuleRadius;
private Vector3 m_Move;
private float m_moveSpeed;
private float h;
private float v;
// Animator variables
private float m_InputForward;
private float m_InputTurn;
private bool m_Crouching;
private bool m_Sprint;
public bool m_Jump;
private bool m_Dash;
public bool allowCrouch;
public bool allowSprinting;
public bool allowAttack;
// Use this for initialization
private void Start()
{
m_Animator = GetComponentInChildren<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Controller = GetComponent<CharacterController>();
m_CapsuleRadius = m_Controller.radius;
m_Move = new Vector3(0f, 0f, 0f);
m_moveSpeed = walkingSpeed;
}
// Update is called once per frame
private void Update()
{
Move();
Jump();
Rotate();
if (allowSprinting)
{
Sprint();
}
if (allowCrouch)
{
Dash();
Crouch();
}
Gravity();
if (allowAttack)
{
Attack();
}
UpdateAnimator();
}
private void FixedUpdate()
{
m_Controller.Move(this.transform.forward * m_InputForward * Time.fixedDeltaTime * m_moveSpeed);
m_Controller.Move(m_Move * Time.fixedDeltaTime);
}
private void Move()
{
h = Input.GetAxisRaw("Horizontal");// setup h variable as our horizontal input axis
v = Input.GetAxisRaw("Vertical"); // setup v variables as our vertical input axis
h = h * Mathf.Sqrt(1f - 0.5f * v * v);
v = v * Mathf.Sqrt(1f - 0.5f * h * h);
m_InputForward = Mathf.Clamp(Mathf.Lerp(m_InputForward, v, Time.fixedDeltaTime * 5f), -5f, 5);
m_InputTurn = Mathf.Lerp(m_InputTurn, h, Time.fixedDeltaTime * 5f);
if (m_InputForward < -0.01f)
m_InputTurn = -m_InputTurn;
}
private void Jump()
{
if (Input.GetButtonDown("Jump") && !m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Jump"))
{
Debug.Log("Jump");
m_Move.y = jumpHeight;
m_Animator.SetTrigger("Jump");
}
}
private void Sprint()
{
if (!m_Crouching && Input.GetButtonDown("Sprint") && !m_Dash)
{
Debug.Log("Sprint");
m_Sprint = true;
m_moveSpeed = sprintingSpeed;
}
else if (Input.GetButtonUp("Sprint") && m_Sprint)
{
m_Sprint = false;
m_moveSpeed = walkingSpeed;
}
}
private void Dash()
{
if (m_Sprint && Input.GetButtonDown("Crouch") && !m_Crouching && !m_Dash)
{
Debug.Log("Dash");
m_Move += Vector3.Scale(transform.forward, DashDistance * new Vector3((Mathf.Log(1f / (Time.fixedDeltaTime * Drag.x + 1)) / -Time.fixedDeltaTime), 0,
(Mathf.Log(1f / (Time.fixedDeltaTime * Drag.z + 1)) / -Time.fixedDeltaTime)));
m_Sprint = false;
m_Dash = true;
m_moveSpeed = walkingSpeed;
}
m_Move.x /= 1 + Drag.x * Time.fixedDeltaTime;
m_Move.y /= 1 + Drag.y * Time.fixedDeltaTime;
m_Move.z /= 1 + Drag.z * Time.fixedDeltaTime;
}
private void Crouch()
{
if (Input.GetButtonDown("Crouch"))
{
Debug.Log("Crouch");
if (m_Crouching) return;
m_Controller.radius /= 2f;
//m_Controller.center /= 2f;
m_Crouching = true;
m_moveSpeed = crouchSpeed;
}
else if (Input.GetButtonUp("Crouch"))
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Controller.radius * 0.5f, Vector3.up);
float crouchRayLength = m_CapsuleRadius * 0.5f;
if (Physics.SphereCast(crouchRay, m_Controller.radius * 0.5f, crouchRayLength, Physics.AllLayers, QueryTriggerInteraction.Ignore) && m_Crouching)
{
Debug.Log("OOPS");
m_Crouching = true;
return;
}
else if (m_Controller.radius != m_CapsuleRadius && m_Crouching)
{
m_Controller.radius = m_CapsuleRadius;
m_Crouching = false;
m_moveSpeed = walkingSpeed;
m_Dash = false;
}
}
}
private void Gravity()
{
m_Move.y += (Physics.gravity.y * gravityScale * Time.fixedDeltaTime);
}
private void Rotate()
{
transform.Rotate(0f, m_InputTurn * turnSpeed * Time.fixedDeltaTime, 0f);
}
private void Attack()
{
if (Input.GetButtonDown("Fire1"))
{
Debug.Log("Attack");
m_Animator.SetTrigger("Attack");
}
}
void UpdateAnimator()
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_InputForward, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_InputTurn, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("Sprinting", m_Sprint);
m_Animator.SetBool("Dash", m_Dash);
}
public bool IsAttacking()
{
//change it to check animation instead
return m_Sprint || m_Dash || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Attack");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CAPCO.Infrastructure.Domain;
using CAPCO.Infrastructure.Data;
namespace CAPCO.Areas.Admin.Controllers
{
public class ProductStatusController : BaseAdminController
{
private readonly IRepository<ProductStatus> productstatusRepository;
public ProductStatusController(IRepository<ProductStatus> productstatusRepository)
{
this.productstatusRepository = productstatusRepository;
}
public ViewResult Index()
{
return View(productstatusRepository.All.ToList());
}
public ViewResult Show(int id)
{
return View(productstatusRepository.Find(id));
}
public ActionResult New()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
public ActionResult Create(ProductStatus productstatus)
{
if (ModelState.IsValid) {
productstatusRepository.InsertOrUpdate(productstatus);
productstatusRepository.Save();
this.FlashInfo("The status was successfully created.");
return RedirectToAction("Index");
} else {
this.FlashError("There was a problem creating the status.");
return View("New", productstatus);
}
}
public ActionResult Edit(int id)
{
return View(productstatusRepository.Find(id));
}
[HttpPut, ValidateAntiForgeryToken, ValidateInput(false)]
public ActionResult Update(ProductStatus productstatus)
{
if (ModelState.IsValid) {
var prop = productstatusRepository.Find(productstatus.Id);
prop.Name = productstatus.Name;
prop.Code = productstatus.Code;
productstatusRepository.InsertOrUpdate(prop);
productstatusRepository.Save();
this.FlashInfo("The status was successfully saved.");
return RedirectToAction("Index");
} else {
this.FlashError("There was a problem saving the status.");
return View("Edit", productstatus);
}
}
public ActionResult Delete(int id)
{
productstatusRepository.Delete(id);
productstatusRepository.Save();
this.FlashInfo("The status was successfully deleted.");
return RedirectToAction("Index");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.