text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.UI;
using XinputGamePad;
public class LogSampleNormal : MonoBehaviour {
public int DeviceNumber;
void Update()
{
DllConst.Capture();
int Buttons = DllConst.GetButtons(DeviceNumber);
// 方向(デジタル)
if((Buttons & InputConst.XINPUT_GAMEPAD_DPAD_LEFT) != 0){
Debug.Log("Left");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_DPAD_RIGHT) != 0){
Debug.Log("Right");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_DPAD_UP) != 0){
Debug.Log("Up");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_DPAD_DOWN) != 0){
Debug.Log("Down");
}
// ABXYボタン
if((Buttons & InputConst.XINPUT_GAMEPAD_A) != 0){
Debug.Log("A");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_B) != 0){
Debug.Log("B");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_X) != 0){
Debug.Log("X");
}
if((Buttons & InputConst.XINPUT_GAMEPAD_Y) != 0){
Debug.Log("Y");
}
// トリガー
if(DllConst.GetLeftTrigger(DeviceNumber) != 0){
Debug.Log("LeftTriger : " + DllConst.GetLeftTrigger(DeviceNumber));
}
if(DllConst.GetRightTrigger(DeviceNumber) != 0){
Debug.Log("RightTriger : " + DllConst.GetRightTrigger(DeviceNumber));
}
// 軸(アナログ)
if((DllConst.GetThumbLX(DeviceNumber)) != 0){
Debug.Log("ThumbLX : " + DllConst.GetThumbLX(DeviceNumber));
}
if((DllConst.GetThumbLY(DeviceNumber)) != 0){
Debug.Log("ThumbLY : " + DllConst.GetThumbLY(DeviceNumber));
}
if(DllConst.GetThumbRX(DeviceNumber) != 0){
Debug.Log("ThumbRX : " + DllConst.GetThumbRX(DeviceNumber));
}
if(DllConst.GetThumbRX(DeviceNumber) != 0){
Debug.Log("ThumbRY : " + DllConst.GetThumbRX(DeviceNumber));
}
}
}
|
using System;
using Xunit;
namespace OptionalTypes.Tests.Unit
{
public static class NullableValueTests
{
[Fact]
public static void VariousEquality_GivenEqualOptionals_ShouldBeEqual()
{
//Arrange
var subject1 = new Optional<int?>(5);
var subject2 = new Optional<int?>(5);
//Act & Assert
Assert.True(subject1 == subject2);
Assert.False(subject1 != subject2);
Assert.Equal(subject1, subject2);
Assert.True(subject1.Equals(subject2));
}
[Fact]
public static void VariousEquality_GivenEqualOptionalAndUnderlyingInt_ShouldBeEqual()
{
//Arrange
var subject1 = new Optional<int?>(5);
var subject2 = 5;
//Act & Assert
Assert.True(subject1 == subject2);
Assert.False(subject1 != subject2);
Assert.Equal(subject1, subject2);
Assert.True(subject1.Equals(subject2));
}
[Fact]
public static void VariousEquality_GivenEqualUnderlyingIntAndOptional_ShouldBeEqual()
{
//Arrange
var subject1 = 5;
var subject2 = new Optional<int?>(5);
//Act & Assert
Assert.False(subject1 != subject2);
Assert.True(subject1 == subject2);
Assert.Equal(subject1, subject2);
// Assert.True(subject1.Equals(subject2)); TODO: fix.
}
[Fact]
public static void VariousInequality_GivenNotEqualOptionals_ShouldBeNotEqual()
{
//Arrange
var subject1 = new Optional<int?>(5);
var subject2 = new Optional<int?>(10);
//Act & Assert
Assert.False(subject1 == subject2);
Assert.True(subject1 != subject2);
Assert.NotEqual(subject1, subject2);
Assert.False(subject1.Equals(subject2));
}
[Fact]
public static void VariousInequality_GivenNotEqualOptionalAndUnderlyingInt_ShouldBeNotEqual()
{
//Arrange
var subject1 = new Optional<int?>(10);
var subject2 = 5;
//Act & Assert
Assert.False(subject1 == subject2);
Assert.True(subject1 != subject2);
Assert.NotEqual(subject1, subject2);
Assert.False(subject1.Equals(subject2));
}
[Fact]
public static void VariousInequality_GivenNotEqualUnderlyingIntAndOptional_ShouldBeNotEqual()
{
//Arrange
var subject1 = 5;
var subject2 = new Optional<int?>(10);
//Act & Assert
Assert.False(subject1 == subject2);
Assert.True(subject1 != subject2);
Assert.NotEqual(subject1, subject2);
// Assert.True(subject1.Equals(subject2)); TODO: fix.
}
[Fact]
public static void Ctor_GivenNoArguments_ShouldBeUndefined()
{
//Act
var subject = new Optional<int?>();
//Assert
Assert.False(subject.IsDefined);
}
[Fact]
public static void ImplicitOperatorOnCreation_SettingValue_ShouldDefineValue()
{
//Act
Optional<int?> subject = 5;
Assert.True(subject.IsDefined);
Assert.Equal(5, subject.Value);
}
[Fact]
public static void ImplicitOperator_SettingValue_ShouldDefineValue()
{
//Arrange
var subject = new Optional<int?>();
//Act
subject = 5;
//Assert
Assert.True(subject.IsDefined);
Assert.Equal(5, subject.Value);
}
[Fact]
public static void VariousEquality_GivenUndefinedOptionals_ShouldBeEqual()
{
//Arrange
var subject1 = new Optional<int?>();
var subject2 = new Optional<int?>();
//Act & Assert
Assert.True(subject1 == subject2);
Assert.False(subject1 != subject2);
Assert.Equal(subject1, subject2);
Assert.True(subject1.Equals(subject2));
}
[Fact]
public static void VariousEquality_GivenUndefinedOptionalsOfDiffernetTypes_ShouldNotBeEqual()
{
//Arrange
var subject1 = new Optional<int?>();
var subject2 = new Optional<DateTime>();
//Act & Assert
Assert.False(subject1.Equals(subject2));
Assert.False(subject2.Equals(subject1));
}
[Fact]
public static void VariousEquality_GivenNullOptional_ShouldBeEqualToNull()
{
//Arrange
var subject1 = new Optional<int?>(null);
//Act & Assert
Assert.True(subject1 == null);
Assert.False(subject1 != null);
Assert.Equal(subject1, null);
Assert.True(subject1.Equals(null));
}
}
} |
using UnityEngine;
using System.Collections;
using GameFrame;
public class EnermyAnimation : GameBehaviour
{
Animator m_animator = null;
AnimatorStateSetting m_stateSetting = new AnimatorStateSetting();
float t = 0;
protected override void Init()
{
m_animator = GetComponent<Animator>();
m_stateSetting.SetAnimator(m_animator);
// Tools.AddAnimatorEvent(m_animator, "FlowerAttack", "EndAttackAnimation");
m_stateSetting.AddBoolState("stand");
m_stateSetting.AddBoolState("move");
m_stateSetting.AddBoolState("attack");
m_stateSetting.AddBoolState("beAttacked");
m_stateSetting.AddBoolState("die");
}
/// <summary>
/// 默认动画,其它动画执行完后,自动执行此动画
/// </summary>
public void StandAnimation()
{
m_stateSetting.SetBool("stand");
}
void TestAnimatorEvent()
{
Debug.Log("TestAnimatorEvent:" + gameObject.name);
}
public void MoveAnimation()
{
m_stateSetting.SetBool("move");
}
public void EndMoveAnimation()
{
StandAnimation();
}
public void AttackAnimation()
{
m_stateSetting.SetBool("attack");
}
public void EndAttackAnimation()
{
// Debug.Log(gameObject.name + ":end enermy attack");
// m_animator.SetBool("attack", false);
m_stateSetting.SetBool("");
}
public void BeAttackedAnimation()
{
m_stateSetting.SetBool("beAttacked");
}
public void DieAnimation()
{
m_stateSetting.SetBool("die");
}
public void Update()
{
//t += Time.deltaTime;
//if (t > 3)
//{
// AttackAnimation();
// t = 0;
//}
//else
//{
// StandAnimation();
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
namespace TT_ClientSocketLibrary
{
public enum Enum_ConnectionEventClient
{
RECEIVEDATA,
STARTCLIENT,
STOPCLIENT
}
public class ClientSocket
{
public bool Started = false;
byte[] m_DataBuffer = new byte[512];
IAsyncResult m_asynResult;
public AsyncCallback pfnCallBack;
public Socket client;
public string ip = "";
public Int32 port = 0;
public string ConnectString = "";
public string Subfix = "";
public string ReceiveString = "";
public delegate void EventHandler(Enum_ConnectionEventClient e, object obj);
public event EventHandler ConnectionEventCallBack;
public void StartClient()
{
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(ip);
if (reply.Status == IPStatus.Success)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress Ip = IPAddress.Parse(ip);
int iPortNo = System.Convert.ToInt32(port);
IPEndPoint ipEnd = new IPEndPoint(Ip, iPortNo);
client.Connect(ipEnd);
Send(ConnectString);
Started = true;
WaitForData();
if (ConnectionEventCallBack != null)
{
ConnectionEventCallBack.Invoke(Enum_ConnectionEventClient.STARTCLIENT, client.Connected);
}
}
}
catch (Exception)
{
Started = false;
}
}
public void WaitForData()
{
try
{
if (pfnCallBack == null)
{
pfnCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = client;
m_asynResult = client.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnCallBack, theSocPkt);
}
catch (Exception)
{
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[512];
}
public void StopClient()
{
if (client != null)
{
client.Disconnect(true);
client.Dispose();
//Started = false;
if (ConnectionEventCallBack != null)
{
ConnectionEventCallBack.Invoke(Enum_ConnectionEventClient.STOPCLIENT, true);
}
}
}
public void Send(string data)
{
if (client != null && data != null)
{
try
{
Object objData = data;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString() + Subfix);
client.Send(byData);
}
catch (SocketException)
{
client = null;
}
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
ReceiveString = szData;
if (ConnectionEventCallBack != null)
{
ConnectionEventCallBack.Invoke(Enum_ConnectionEventClient.RECEIVEDATA, szData);
}
Started = true;
WaitForData();
}
catch (ObjectDisposedException)
{
//Started = false;
}
catch (SocketException)
{
//Started = false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace VV_ProjetoLobosOvelhas
{
class SimuladorTela : Form
{
private static readonly Color COR_VAZIA = Color.FromArgb(0,255,255,255);
private static readonly Color COR_INDEFINIDA = Color.FromArgb(0,128,128,128);
private readonly String PREFIXO_ETAPA = "Etapa: ";
private readonly String PREFIXO_POPULACAO = "Populacao: ";
private Label rotuloEtapa, populacao;
private VisaoCampo visaoCampo;
private Dictionary<Type, Color> cores;
private CampoEstatistica estatisticas;
public SimuladorTela(int height, int width)
{
estatisticas = new CampoEstatistica();
cores = new LinkedHashMap<Type, Color>();
this.Text = "Simulacao Coelhos and Raposas";
rotuloEtapa.Text = PREFIXO_ETAPA;
rotuloEtapa.AutoSize = false;
rotuloEtapa.TextAlign = ContentAlignment.MiddleCenter;
rotuloEtapa.Dock = DockStyle.None;
populacao.Text = PREFIXO_POPULACAO;
populacao.AutoSize = false;
populacao.TextAlign = ContentAlignment.MiddleCenter;
populacao.Dock = DockStyle.None;
setLocation(100, 50);
visaoCampo = new VisaoCampo(height, width);
Container conteudos = getContentPane();
conteudos.add(rotuloEtapa, BorderLayout.NORTH);
conteudos.add(visaoCampo, BorderLayout.CENTER);
conteudos.add(populacao, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void SetCor(Type animalClass, Color color)
{
if(cores.ContainsKey(animalClass))
{
cores.Remove(animalClass);
cores.Add(animalClass, color);
}
}
private Color getCor(Type animalClass)
{
Color coluna = cores[animalClass];
if (coluna == null)
{
return COR_INDEFINIDA;
}
else
{
return coluna;
}
}
public void mostraStatus(int etapa, Campo campo)
{
if (!isVisible())
{
setVisible(true);
}
rotuloEtapa.setText(PREFIXO_ETAPA + etapa);
estatisticas.redefine();
visaoCampo.preparePaint();
for (int row = 0; row < campo.getProfundidade(); row++)
{
for (int col = 0; col < campo.getLargura(); col++)
{
Object animal = campo.getObjectAt(row, col);
if (animal != null)
{
estatisticas.incrementaContador(animal.GetType());
visaoCampo.drawMark(col, row, getCor(animal.GetType()));
}
else
{
visaoCampo.drawMark(col, row, COR_VAZIA);
}
}
}
estatisticas.contadorFinalizado();
populacao.setText(PREFIXO_POPULACAO + estatisticas.getPopulationDetails(campo));
visaoCampo.repaint();
}
public bool ehViavel(Campo campo)
{
return estatisticas.ehViavel(campo);
}
private class VisaoCampo
{
private readonly int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Point size;
private Graphics g;
private Image fieldImage;
public VisaoCampo(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Point(0, 0);
}
public Point getPreferredSize()
{
return new Point(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
public void preparePaint()
{
if (!size.Equals(getSize))
{
size = getSize();
fieldImage = visaoCampo.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if (xScale < 1)
{
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if (yScale < 1)
{
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale - 1, yScale - 1);
}
public void paintComponent(Graphics g)
{
if (fieldImage != null)
{
Dimension currentSize = getSize();
if (size.equals(currentSize))
{
g.drawImage(fieldImage, 0, 0, null);
}
else
{
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
}
|
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using System.Collections.Generic;
using System.Fabric;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.ServiceFabric.Services.Runtime
{
public class StatelessService
{
public StatelessService(StatelessServiceContext context)
{
}
public StatelessServiceContext Context { get; }
protected virtual IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return null;
}
protected virtual async Task RunAsync(CancellationToken cancellationToken)
{
await Task.Run(() =>
{
});
}
}
}
|
using System;
namespace CustomIterator
{
public class Demo1
{
public static void Run()
{
int[] intArray = { 10, 20, 30, 40, 50 };
foreach(int i in intArray)
{
Console.WriteLine(i);
}
/**********************************************************************************************
# Doing iteration on an Array is possible because Array type implemements GetEnumerator() method
# defined in IEnumerable interface.
# https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerable.getenumerator?view=netframework-4.8
# Not exclusive to an array, every type that implements GetEnumerator() method can be iterated using foreach loop
**********************************************************************************************/
intArray.GetEnumerator();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BugTracker.DataAccessLayer;
namespace BugTracker.BusinessLayer
{
class VentaService
{
VentaDao oVentaDao;
VentaService()
{
oVentaDao = new VentaDao();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MorseCode : MonoBehaviour
{
int x = 0;
Light morseLight;
private void Start()
{
morseLight = GetComponentInChildren<Light>();
StartCoroutine("ControlLight");
}
private IEnumerator ControlLight()
{
while (x == 0)
{
morseLight.enabled = false;
yield return new WaitForSeconds(2f);
//E: .
morseLight.enabled = true;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = false;
yield return new WaitForSeconds(1.2f);
//A: .-
morseLight.enabled = true;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = false;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = true;
yield return new WaitForSeconds(1.0f);
morseLight.enabled = false;
yield return new WaitForSeconds(1.2f);
//S: ...
morseLight.enabled = true;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = false;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = true;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = false;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = true;
yield return new WaitForSeconds(0.3f);
morseLight.enabled = false;
yield return new WaitForSeconds(1.2f);
//T: -
morseLight.enabled = true;
yield return new WaitForSeconds(1.0f);
morseLight.enabled = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolidPrinciples.OpenClose
{
class Violation
{
public double TotalArea(Object[] shapeObjects)
{
double area = 0;
foreach(var obj in shapeObjects)
{
if(obj is Rectangle)
{
var ObjRectangle = (Rectangle)obj;
area = ObjRectangle.Height * ObjRectangle.Width;
}
else if
{
var ObjCircle = (Circle)obj;
area = ObjCircle.Radius * ObjCircle.Radius * Math.PI;
}
else
{
var ObjTriangle = (Triangle)obj;
area = (ObjTriangle.Trianglebase * ObjTriangle.Triangleheight)/ 2;
}
}
return area;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
namespace MiNETDevTools.UI.Forms.Tools
{
public partial class ToolWindow : DockContent
{
protected UiContext Context { get; private set; }
public ToolWindow()
{
InitializeComponent();
AutoScaleMode = AutoScaleMode.Dpi;
}
internal void LoadUiContext(UiContext context)
{
Context = context;
OnLoadUiContext(context);
}
protected virtual void OnLoadUiContext(UiContext context) { }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneSoundManager : MonoBehaviour
{
private AudioSource planeSound;
void Start()
{
planeSound = this.GetComponent<AudioSource>();
}
void Update()
{
planeSound.pitch = Mathf.Clamp(1+ Mathf.Abs(this.transform.rotation.z)*2,1,2);
planeSound.volume = Mathf.Clamp(0.6f + Mathf.Abs(this.transform.rotation.z) * 0.5f,0,0.9f);
}
}
|
using Battleship.Logic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Battleship.Tests.UnitTests
{
[TestClass]
public class ShipRandomPlacerTests
{
[ExpectedException(typeof(ArgumentException))]
[TestMethod]
public void PlaceShips_ShipSizeBiggerThanNumberOfRowsAndColumns_ArgumentExpcetion()
{
//Arrange
var ships = new List<Ship>() { new Ship("Test", 8) };
var board = new Board(7, 7);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
}
[TestMethod]
public void PlaceShips_ShipSizeBiggerThanNumberOfColumnsButNotBiggerThenNumberOfRows_ShipIsPlacedOnBoard()
{
//Arrange
var ship = new Ship("Test", 8);
var ships = new List<Ship>() { ship };
var board = new Board(8, 1);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
//Assert
Assert.IsNotNull(ship.OccupiedCells);
Assert.IsTrue(ship.OccupiedCells.Any());
}
[ExpectedException(typeof(ArgumentException))]
[TestMethod]
public void PlaceShips_NMoreShipsInTheListThanNumberThanNumberOfColumnsAndRows_ArgumentExpcetion()
{
//Arrange
var ships = new List<Ship>() { new Ship("Test", 1), new Ship("Test", 1) };
var board = new Board(1, 1);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
}
[TestMethod]
public void PlaceShips_MoreShipsInTheListThanNumberOfColumnsButNotRows_AllShipsArePlaced()
{
//Arrange
var ships = new List<Ship>() { new Ship("Test", 1), new Ship("Test", 1) };
var board = new Board(2, 1);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
//Assert
Assert.IsTrue(ships.All(s => s.OccupiedCells != null));
Assert.IsTrue(ships.All(s => s.OccupiedCells.Any()));
}
[TestMethod]
public void PlaceShips_ShipSize1BoardSize1x1_ShipOccupiedCellsContainsSingleCell()
{
//Arrange
var ship = new Ship("Test", 1);
var ships = new List<Ship>() { ship };
var board = new Board(1, 1);
var cell = board.Cells.First();
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
//Assert
Assert.AreEqual(1, board.Cells.Count());
Assert.AreEqual(1, ship.Size);
Assert.AreEqual(cell, ship.OccupiedCells.First());
}
[TestMethod]
public void PlaceShips_ShipSize5NumberOfShips5BoardSize5x5_ShipOccupiedCellsAreNotEmpty()
{
//Arrange
var ships = new List<Ship>() { new Ship("Test", 5), new Ship("Test", 5), new Ship("Test", 5) , new Ship("Test", 5) , new Ship("Test", 5) };
var board = new Board(5, 5);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
//Assert
Assert.IsTrue(ships.All(s => s.OccupiedCells.Any()));
}
[TestMethod]
public void PlaceShips_DifferentShipSizesNumberOfShips5BoardSize5x5_ShipOccupiedCellsAreNotEmpty()
{
//Arrange
var ships = new List<Ship>() { new Ship("Test", 3), new Ship("Test", 2), new Ship("Test", 2), new Ship("Test", 1), new Ship("Test", 5) };
var board = new Board(5, 3);
var placer = new ShipRandomPlacer();
//Act
placer.PlaceShips(ships, board.Cells);
//Assert
Assert.IsTrue(ships.All(s => s.OccupiedCells.Any()));
}
}
}
|
using AutoMapper;
using WebApi.Services.Dto.MercadoLibre.Search;
namespace WebApi.ViewModel.Mappings
{
public class ResultMappingProfile : Profile
{
public ResultMappingProfile()
{
CreateMap<Result, ResultViewModel>()
.ForMember(x => x.seller_id, x => x.MapFrom(y => y.Seller.Id));
}
}
}
|
using UnityEngine;
public class ModelImport : MonoBehaviour {
[Tooltip("GameObject container for a newly imported geometry file.")]
public GameObject TargetObject;
public void ImportModel(string path) {
#if !UNITY_EDITOR
Geometry.Initialize(path, this.TargetObject);
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace AdminPanelIntegration.Models
{
public class DBconnect
{
SqlConnection con;
protected List<SqlParameter> sp;
public SqlConnection getconnection()
{
con = new SqlConnection("Data Source=Pratik ; Integrated Security=True ; Initial Catalog=VirtualShareMarket");
//con = new SqlConnection("Data Source=198.12.156.82\\SQLEXPRESS ; Initial Catalog=VirtualShareMarket; User id=*****; Password=*****");
//con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["VSMConnectionString"].ConnectionString);
con.Open();
return con;
}
public SqlCommand getcommand(string Query)
{
con = getconnection();
SqlCommand cmd = new SqlCommand(Query, con);
if (sp != null)
{
for (int i = 0; i < sp.Count; i++)
{
cmd.Parameters.Add(sp.ElementAt(i));
}
}
return cmd;
}
public int executenon(string Query)
{
SqlCommand cmd = getcommand(Query);
int res = cmd.ExecuteNonQuery();
return res;
}
public SqlDataReader executeread(string Query)
{
SqlCommand cmd = getcommand(Query);
SqlDataReader dr = cmd.ExecuteReader();
return dr;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using k8s;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace nemo_api_service.library
{
public class BaseController:Controller
{
public IKubernetes _client;
public BaseController(IHttpContextAccessor httpContextAccessor)
{
var kubeBase64Content=Environment.GetEnvironmentVariable("nemo-kube-config");
byte[] kubeConfigContentByte= Convert.FromBase64String(kubeBase64Content);
var kubeConfigContent = System.Text.Encoding.Default.GetString(kubeConfigContentByte);
Stream kubeConfig = Utilities.GenerateStreamFromString(kubeConfigContent);
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile(kubeConfig);
_client = new Kubernetes(config);
}
}
}
|
using E_ticaret.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace E_ticaret.Controllers
{
public class KargoController : Controller
{
// GET: Kargo
Model1 k = new Model1();
#region Kargo Liste
public ActionResult Kargolar()
{
List<kargo> Kargolar = k.kargoes.ToList();
return View(Kargolar);
}
#endregion
#region Kargo Ekle
public ActionResult KargoEkle()
{
ViewBag.kargo = k.kargoes.ToList();
return View();
}
[HttpPost]
public ActionResult KargoEkle(kargo u)
{
k.kargoes.Add(u);
k.SaveChanges();
return RedirectToAction("Kargolar");
}
#endregion
#region Kargo Güncelle
public ActionResult Guncelle(int? id)
{
if (id == null)
{
ViewBag.Uyari = "Güncellenecek hizmet bulunamadi..";
}
var f = k.kargoes.Where(x => x.kargo_id == id).FirstOrDefault();
if (f == null)
{
return HttpNotFound();
}
return View(f);
}
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Guncelle(int id, kargo f)
{
if (ModelState.IsValid)
{
var kargolar = k.kargoes.Where(x => x.kargo_id == id).SingleOrDefault();
kargolar.firma = f.firma;
kargolar.aciklama = f.aciklama;
kargolar.telefon = f.telefon;
kargolar.website = f.website;
kargolar.e_posta = f.e_posta;
k.SaveChanges();
return RedirectToAction("Kargolar");
}
return View(f);
}
#endregion
#region Silme
public ActionResult Delete(int id)
{
if (id == null)
{
return HttpNotFound();
}
var h = k.kargoes.Find(id);
if (h == null)
{
return HttpNotFound();
}
k.kargoes.Remove(h);
k.SaveChanges();
return RedirectToAction("Kampanyalar");
}
#endregion
}
} |
using ContosoUniversity.DAL;
using ContosoUniversity.Models;
using ContosoUniversity.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace ContosoUniversity.Controllers
{
public class AccountController : Controller
{
private SchoolContext db = new SchoolContext();
public SchoolContext DbContext
{
get { return db; }
set { db = value; }
}
// GET: Account
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(PersonVM model)
{
if (model.Password == model.ConfirmPassword)
{
bool boolImage = false;
string fileName = "";
string extension = "";
if (model.ImageFile != null)
{
boolImage = true;
fileName = model.FirstMidName + model.LastName.ToUpper();
extension = Path.GetExtension(model.ImageFile.FileName);
if (extension != ".jpg" && extension != ".jpeg" && extension != ".png")
{
TempData["ImageMessage"] = "Authorized extension are JPG, JPEG and PNG";
return View(model);
}
else if (model.ImageFile.ContentLength > 100000)
{
TempData["ImageMessage"] = "Maximum size is 100 KB";
return View(model);
}
else
{
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
model.ImagePath = "/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("/Image/"), fileName);
}
}
using (SchoolContext db = new SchoolContext())
{
if (!db.People.Any(u => u.Username == model.Username) && model.Role == "Student")
{
Student user = new Student
{
FirstMidName = model.FirstMidName,
LastName = model.LastName,
Username = model.Username,
Password = model.Password,
Email = model.Email,
EnrollmentDate = DateTime.Now,
ImagePath = model.ImagePath
};
db.Students.Add(user);
db.SaveChanges();
if (boolImage == true)
{
model.ImageFile.SaveAs(fileName);
}
ViewBag.Message = "Welcome " + user.Username;
return RedirectToAction("Login");
}
else if (!db.People.Any(u => u.Username == model.Username) && model.Role == "Instructor")
{
{
Instructor user = new Instructor
{
FirstMidName = model.FirstMidName,
LastName = model.LastName,
Username = model.Username,
Password = model.Password,
HireDate = DateTime.Now,
ImagePath = model.ImagePath
};
db.Instructors.Add(user);
db.SaveChanges();
if (boolImage == true)
{
model.ImageFile.SaveAs(fileName);
}
ViewBag.Message = "Welcome " + user.Username;
return RedirectToAction("Login");
}
}
else
{
TempData["UsernameMessage"] = "Username already exists";
return View();
}
}
}
TempData["PasswordMessage"] = "Password Not Conform";
return View();
}
//Login
public ActionResult Login()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult Login(string username, string password) //TODO : Ici ça serait bien de mettre un ViewModel ...
{
using (SchoolContext db = new SchoolContext())
{
if (db.People.FirstOrDefault(u => u.Username == username && u.Password == password) is Student)
{
Student user = new Student();
user.Username = username;
user.Password = password;
Session["UserID"] = user;
TempData["LoginMessage"] = "Welcome " + username;
return RedirectToAction("Index", "Student");
}
else if (db.People.FirstOrDefault(u => u.Username == username && u.Password == password) is Instructor)
{
Instructor user = new Instructor();
user.Username = username;
user.Password = password;
Session["UserID"] = user;
TempData["LoginMessage"] = "Welcome " + username;
return RedirectToAction("Index", "Instructor");
}
else { TempData["ErrorLoginMessage"] = "Username or Password is wrong"; }
}
return View();
}
public ActionResult Logout()
{
//if (Session["UserID"] != null)
//{
// FormsAuthentication.SignOut();
//}
Session["UserID"] = null;
return RedirectToAction("Index", "Home");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ShowHHeal : MonoBehaviour
{
private GameObject player;
private BoHealthController health;
public GameObject HtoHealText;
private void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
health = player.GetComponent<BoHealthController>();
}
private void Update()
{
if(health.currentHealth > 15)
{
HtoHealText.SetActive(false);
}
if(health.currentHealth < 15)
{
HtoHealText.SetActive(true);
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace testMonogame
{
class AquamentusEnemy : IEnemy, ISprite
{
Texture2D texture;
Rectangle destRect;
public int X { get; set; }
public int Y { get; set; }
int health;
int maxHealth = 12; //takes 12 hits to kill on easy and normal (by default), on hard this is increased to 24
//drawing stuff
const int width = 48;
const int height = 64;
Color color = Color.White;
LinkedList<Rectangle> frames = new LinkedList<Rectangle>();
LinkedList<Rectangle> hurtFrames = new LinkedList<Rectangle>();
LinkedListNode<Rectangle> currentFrame;
int frameDelay = 20;
int frameWait;
int hurtFlash;
/*
*Rectangle frame1 = new Rectangle(0, 0, 24, 32);
* Rectangle frame2 = new Rectangle(25, 0, 24, 32);
*Rectangle frame3 = new Rectangle(50, 0, 24, 32);
*Rectangle frame4 = new Rectangle(75, 0, 24, 32);
*
*
*
*/
//movement stuff
int xVel; //doesnt have y velocity
int directionWait;
int directionStall = 10; //how many updates until we change direction
int moveDelay = 6;
int moveDelayCount;
int fireDelay = 240;
int fireDelayCount;
public AquamentusEnemy(Texture2D inTexture, Vector2 position)
{
// Stuff for drawing
texture = inTexture;
X = (int)position.X;
Y = (int)position.Y;
frameWait = 0;
frames.AddLast(new Rectangle(0, 0, 24, 32));
frames.AddLast(new Rectangle(25, 0, 24, 32));
frames.AddLast(new Rectangle(50, 0, 24, 32));
frames.AddLast(new Rectangle(75, 0, 24, 32));
hurtFrames.AddLast(new Rectangle(0, 33, 24, 32));
hurtFrames.AddLast(new Rectangle(25, 33, 24, 32));
hurtFrames.AddLast(new Rectangle(50, 33, 24, 32));
currentFrame = frames.First;
hurtFlash = 0;
maxHealth = maxHealth * (int)GameplayConstants.ENEMY_SPEED_MODIFIER;
// Stuff for state
health = maxHealth;
xVel = 2;
directionWait = 0;
moveDelayCount = 0;
}
public Rectangle getDestRect()
{
return destRect;
}
public void Attack(IPlayer player)
{
//Deal damage if you make contact
player.TakeDamage(4);
}
public int getHealth() { return health; }
public void Draw(SpriteBatch spriteBatch)
{
destRect = new Rectangle(X, Y, width, height);
frameWait++;
if (frameWait >= frameDelay) {
if (hurtFlash == 0)
{
if (currentFrame.Next != null) currentFrame = currentFrame.Next;
else currentFrame = frames.First;
}
else
{
if (currentFrame.Next != null) currentFrame = currentFrame.Next;
else
{
//loop through hurt frames, hurtflash number of times
currentFrame = hurtFrames.First;
hurtFlash--;
}
}
frameWait = 0;
}
//source rectangle is the frame that we are currently on in the list
spriteBatch.Draw(texture, destRect, currentFrame.Value, color);
}
public void Move()
{
directionWait++;
if (directionWait > directionStall)
{
xVel *= -1;
directionWait = 0;
}
X += xVel * (int)GameplayConstants.ENEMY_SPEED_MODIFIER;
}
public void takeDamage(int dmg)
{
//if invulnerable during hurtflash then put all this inside if(hurtflash==0)
//boss only takes 1 damage from all sources to ensure that he cant be cheesed
if (hurtFlash == 0)
{
health -= 1;
hurtFlash = 3;
currentFrame = hurtFrames.First;
}
//flash colors
}
void spawnFireBalls(GameManager game)
{
game.AddEnemyProjectile(new FireBallEnemyProjectile(texture, new Vector2(X + width / 4, Y + height / 4), new Vector2(-1, 1)));
game.AddEnemyProjectile(new FireBallEnemyProjectile(texture, new Vector2(X + width / 4, Y + height / 4), new Vector2(-1, 0)));
game.AddEnemyProjectile(new FireBallEnemyProjectile(texture, new Vector2(X + width / 4, Y + height / 4), new Vector2(-1, -1)));
}
public void Update(GameManager game)
{
//slow movement since aquamentus rocks back and forth slowly
moveDelayCount++;
if (moveDelayCount > moveDelay)
{
Move();
moveDelayCount = 0;
}
fireDelayCount++;
if (fireDelayCount > fireDelay)
{
spawnFireBalls(game);
fireDelayCount = 0;
}
//add collision and projectile stuff
}
}
}
|
using System;
using System.Collections.Generic;
using Fingo.Auth.AuthServer.Client.Exceptions;
using Fingo.Auth.AuthServer.Client.Services.Interfaces;
using Fingo.Auth.Infrastructure.Logging;
using Fingo.Auth.JsonWrapper;
using Newtonsoft.Json;
namespace Fingo.Auth.AuthServer.Client.Services.Implementation
{
public class RemoteTokenService : IRemoteTokenService
{
private readonly ILogger<RemoteTokenService> _logger;
private readonly IPostService _postService;
public RemoteTokenService(IPostService postService)
{
_postService = postService;
_logger = new Logger<RemoteTokenService>();
}
public bool VerifyToken(string jwt)
{
var parameters = new Dictionary<string , string>
{
{"jwt" , jwt} ,
{"projectGuid" , Configuration.Guid}
};
JsonObject parsed;
try
{
var authServerAnswer = _postService.SendAndGetAnswer(Configuration.VerifyTokenAdress , parameters);
parsed = JsonConvert.DeserializeObject<JsonObject>(authServerAnswer);
}
catch (Exception e)
{
_logger.Log(LogLevel.Error ,
$"<VerifyToken> _postService.SendAndGetAnswer({Configuration.VerifyTokenAdress}, parameters) threw a exception: {e.Message}, stacktrace: {e.StackTrace}");
return false;
}
return (parsed != null) && (parsed.Result == JsonValues.TokenValid);
}
public string AcquireToken(string login , string password)
{
var parameters = new Dictionary<string , string>
{
{"login" , login} ,
{"password" , password} ,
{"projectGuid" , Configuration.Guid}
};
string authServerAnswer;
JsonObject parsed;
try
{
authServerAnswer = _postService.SendAndGetAnswer(Configuration.AcquireTokenAdress , parameters);
}
catch (Exception)
{
throw new ServerConnectionException();
}
try
{
parsed = JsonConvert.DeserializeObject<JsonObject>(authServerAnswer);
if (parsed == null)
throw new Exception();
}
catch
{
throw new ServerNotValidAnswerException();
}
if (parsed.Result == JsonValues.NotAuthenticated)
throw new NotAuthenticatedException();
if (parsed.Result == JsonValues.AccountExpired)
throw new AccountExpiredException();
if (parsed.Result == JsonValues.PasswordExpired)
throw new PasswordExpiredException();
if (parsed.Result == JsonValues.Authenticated)
return parsed.Jwt;
throw new Exception();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVC5Demo.Models
{
public class Individual
{
public int Id { get; set; }
public DateTime DateAdded { get; set; }
[Required(ErrorMessage="Please enter a full name.")]
[Display(Name="Full Name")]
public String FullName { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfDeath { get; set; }
public String HealthCard { get; set; }
public String SIN { get; set; }
public String Birthplace { get; set; }
public String StreetAddress { get; set; }
public String MailingAddress { get; set; }
public String Town { get; set; }
public String Province { get; set; }
[DataType(DataType.PostalCode)]
public String PostalCode { get; set; }
[DataType(DataType.PhoneNumber)]
public String PhoneNumber { get; set; }
[DataType(DataType.PhoneNumber)]
public String AltPhoneNumber { get; set; }
public String ContactName { get; set; }
public String ContactStreetAddress { get; set; }
public String ContactMailAddress { get; set; }
public String ContactTown { get; set; }
public String ContactProvince { get; set; }
[DataType(DataType.PostalCode)]
public String ContactPostalCode { get; set; }
[DataType(DataType.PhoneNumber)]
public String ContactPhoneNumber { get; set; }
[DataType(DataType.PhoneNumber)]
public String ContactAltPhoneNumber { get; set; }
public String PrearrangementStatus { get; set; }
public int TDCanadaTrustRef { get; set; }
public String LifeInsuranceCo { get; set; }
public int PolicyNumber { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OnlineShopping.Models;
namespace OnlineShopping.Controllers
{
public class MyOrdersController : ApiController
{
DbproonlineshoppingEntities db = new DbproonlineshoppingEntities();
#region PlaceOrder
[HttpPost]
public IHttpActionResult PlaceOrder(MyOrderModel myOrderModel)
{
try
{
if (myOrderModel.OrderID == 0)
{
MyOrder objcl = new MyOrder();
objcl.OrderID = myOrderModel.OrderID;
objcl.UserID = myOrderModel.UserID;
objcl.OrderTotal = myOrderModel.OrderTotal;
objcl.OrderDate = DateTime.Now;
db.MyOrders.Add(objcl);
db.SaveChanges();
int id = objcl.OrderID;
foreach (var item in myOrderModel.CartModel)
{
OrderDetail orderDetail = new OrderDetail();
orderDetail.OrderDate = DateTime.Now;
orderDetail.TotalPrice = (int)item.TotalPrice;
orderDetail.Quantity = item.Quantity;
orderDetail.OrderID = id;
orderDetail.ProductID = item.ProductID;
db.OrderDetails.Add(orderDetail);
db.SaveChanges();
try
{
var productData = db.Products.Where(p => p.ProductID == item.ProductID).FirstOrDefault();
{
// Product product = new Product();
productData.Quantity = productData.Quantity - item.Quantity;
if (productData.Quantity == 0)
{
productData.InStock = false;
}
else
{
productData.InStock = true;
}
productData.ModifiedDate = DateTime.Now;
db.Entry(productData).State = EntityState.Modified;
db.SaveChanges();
}
}
catch (Exception exp)
{
return Ok(exp);
}
var cart = db.Carts.Where(w => w.CartID == item.CartID).FirstOrDefault();
if (cart != null)
{
db.Carts.Remove(cart);
db.SaveChanges();
}
}
}
return Ok("Success");
}
catch (Exception e)
{
return Ok(e);
}
}
#endregion
#region DisplayOrderHistory
[HttpGet]
public IHttpActionResult GetMyOrders(int userId)
{
try
{
var orders =
from myOrder in db.MyOrders
join orderDetail in db.OrderDetails on myOrder.OrderID equals orderDetail.OrderID
where myOrder.UserID == userId
group myOrder by myOrder.OrderID into groupOrder
select new MyOrderModel()
{
OrderID = groupOrder.FirstOrDefault().OrderID,
UserID = groupOrder.FirstOrDefault().UserID,
OrderTotal = groupOrder.FirstOrDefault().OrderTotal,
OrderDate = groupOrder.FirstOrDefault().OrderDate,
CartModel = db.OrderDetails.Where(w => w.OrderID == groupOrder.FirstOrDefault().OrderID).Select(s => new CartModel()
{
ProductName = s.Product.ProductName,
ProductDescription = s.Product.ProductDescription,
ProductPrice = s.Product.ProductPrice,
Quantity = s.Quantity,
TotalPrice = s.TotalPrice,
ProductID = s.Product.ProductID,
Image = s.Product.Images.Where(w => w.ProductID == s.ProductID).Select(t => t.ProductImage).FirstOrDefault()
}).ToList()
};
return Ok(orders);
}
catch(Exception e)
{
return Ok(e);
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using LINQ101MVC.Controllers;
namespace LINQ101MVC.Models
{
[Table("Sales.Customer")]
public partial class Customer
{
public int CustomerID { get; set; }
public int? PersonID { get; set; }
public int? StoreID { get; set; }
public int? TerritoryID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[Required]
[StringLength(10)]
public string AccountNumber { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual Person Person { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage","CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; } = new HashSet<SalesOrderHeader>();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.BIZ;
using Core.DAL;
namespace WinForm.Views
{
public partial class frmThemNXB : Form
{
public frmThemNXB(Form parent)
{
InitializeComponent();
_frmParent = parent;
}
#region Private Properties
Form _frmParent;
#endregion
#region Form Control Listener
//Khi Load Form
private void frmThemNXB_Load(object sender, EventArgs e)
{
}
//Khi Chọn Thêm
private void btnThem_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Bạn có muốn thêm nhà xuất bản", "Thông báo", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
if (!txbTenNXB.Text.Equals("") && !txbDiaChi.Text.Equals("") && !txbSoDienThoai.Text.Equals("") && !txbSoTaiKhoan.Text.Equals(""))
{
NhaXuatBan nxb = new NhaXuatBan();
nxb.TenNXB = txbTenNXB.Text.ToString();
nxb.DiaChi = txbDiaChi.Text.ToString();
nxb.SoDienThoai = txbSoDienThoai.Text.ToString();
nxb.SoTaiKhoan = txbSoTaiKhoan.Text.ToString();
nxb.NganHang = txbNganHang.Text.ToString();
if (NhaXuatBanManager.add(nxb) != 0)
MessageBox.Show("Đã thêm nhà xuất bản thành công");
else
MessageBox.Show("Không thêm được");
}
else
MessageBox.Show("Bạn cần nhập đầy đủ thuông tin");
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
//Khi Hủy Thêm
private void btnThoat_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Bạn có muốn thoát", "Thông báo", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
this.Close();
if (_frmParent.GetType().Name == nameof(frmDanhMucNXB))
{
(_frmParent as frmDanhMucNXB).loadNXB();
}
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class PaymentType
{
public string Id { get; set; }
public string Description { get; set; }
public bool IsActive { get; set; }
public bool HasExtra { get; set; }
public string LaunchAppUrl { get; set; }
public int SortOrder { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class SimpleCallback : MonoBehaviour {
delegate void delegateCaller();
delegateCaller caller = FunctionToCall;
// Use this for initialization
void Start () {
caller();
}
static void FunctionToCall () {
Debug.Log("Function called.");
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Justa.Job.Backend.Api.Application.MediatR.Requests;
using Justa.Job.Backend.Api.Application.Services.DataValidation.Interfaces;
using Justa.Job.Backend.Api.Application.Services.DataValidation.Models;
using Microsoft.AspNetCore.Mvc;
namespace Justa.Job.Backend.Api.Application.MediatR.Handlers
{
public class QueryValidateCpfHandler : ActionResultRequestHandler<QueryValidateCpf>
{
private readonly ICpfValidator _cpfValidator;
public QueryValidateCpfHandler(ICpfValidator cpfValidator)
{
_cpfValidator = cpfValidator;
}
public override Task<IActionResult> Handle(QueryValidateCpf request, CancellationToken cancellationToken)
=> Task.Run(() =>
{
var isCpfValid = _cpfValidator.Validate(request.Cpf);
var response = new ValidatorResponse
{
Type = "cpf",
IsValid = isCpfValid,
Value = request.Cpf,
Formated = isCpfValid ? Convert.ToUInt64(request.Cpf).ToString(@"000\.000\.000\-00") : string.Empty
};
return Ok(response);
});
}
} |
using System.ComponentModel.DataAnnotations;
namespace Etherama.WebApplication.Models.API.v1.ViewModels
{
public class AddTokenRequestViewModel
{
[Required]
public string CompanyName { get; set; }
public string WebsiteUrl { get; set; }
[Required]
public string ContactEmail { get; set; }
[Required]
public string TokenTicker { get; set; }
public string TokenContractAddress { get; set; }
[Required]
public decimal StartPriceEth { get; set; }
[Required]
public long TotalSupply { get; set; }
}
}
|
//-----------------------------------------------------------------------
// <copyright file="RestrictSpecialCharactersAttribute.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace SmartLibrary.Infrastructure.DataAnnotations
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmartLibrary.Resources;
/// <summary>
/// Restrict Special Characters([,],<,>,{,},) Attribute
/// </summary>
public class RestrictSpecialCharactersAttribute : RegularExpressionAttribute, IClientValidatable
{
/// <summary>
/// error message constant
/// </summary>
private string eRRORMESSAGE = Messages.RestrictIllegalCharacters;
/// <summary>
/// Initializes a new instance of the <see cref="RestrictSpecialCharactersAttribute"/> class.
/// </summary>
public RestrictSpecialCharactersAttribute()
: base(@"^([^()<>\{\}\[\]\\\/]*)$")
{
this.ErrorMessage = this.eRRORMESSAGE;
}
/// <summary>
/// Get Client Validation Rules
/// </summary>
/// <param name="metadata">metadata object</param>
/// <param name="context">context Object</param>
/// <returns>Return ModelClientValidationRule List</returns>
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mvr = new ModelClientValidationRule();
mvr.ErrorMessage = this.eRRORMESSAGE;
mvr.ValidationType = "restrictspecialchar";
return new[] { mvr };
}
}
} |
using Alabo.Domains.Entities.Core;
using System;
using System.Linq.Expressions;
namespace Alabo.Domains.Query {
/// <summary>
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public interface IOrderQuery<TEntity> : IPredicateQuery<TEntity> where TEntity : class, IEntity {
IOrderQuery<TEntity> OrderByAscending<TKey>(Expression<Func<TEntity, TKey>> keySelector);
IOrderQuery<TEntity> OrderByDescending<TKey>(Expression<Func<TEntity, TKey>> keySelector);
IOrderQuery<TEntity> OrderBy<TKey>(Expression<Func<TEntity, TKey>> keySelector,
OrderType type = OrderType.Ascending);
}
} |
namespace Futbol5.DAL.Infrastructure
{
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private Futbol5Entities dataContext;
public Futbol5Entities Get()
{
return dataContext ?? (dataContext = new Futbol5Entities());
}
protected override void DisposeCore()
{
if (dataContext != null) dataContext.Dispose();
}
}
}
|
using SAAS.FrameWork.Module.SsApiDiscovery.ApiDesc.Attribute;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SAAS.FrameWork.Util.Common
{
public static class TransObj<TIn, TOut>
{
private static readonly Func<TIn, TOut> cache = GetFunc();
private static Func<TIn, TOut> GetFunc()
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
List<MemberBinding> memberBindingList = new List<MemberBinding>();
foreach (var item in typeof(TOut).GetProperties())
{
if (!item.CanWrite)
continue;
MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
return lambda.Compile();
}
public static TOut Trans(TIn tIn)
{
return cache(tIn);
}
}
public static class TransObj
{
public static DataSet ToDataSet<TSource>(this IList<TSource> list)
{
Type elementType = typeof(TSource);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
foreach (var pi in elementType.GetProperties())
{
Type colType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
var descobj= (SsDescriptionAttribute)Attribute.GetCustomAttribute(pi, typeof(SsDescriptionAttribute));
if (descobj == null)
{
dt.Columns.Add(pi.Name, colType);
}
else
{
dt.Columns.Add(descobj.Value, colType);
}
}
foreach (TSource item in list)
{
DataRow row = dt.NewRow();
foreach (var pi in elementType.GetProperties())
{
var descobj = (SsDescriptionAttribute)Attribute.GetCustomAttribute(pi, typeof(SsDescriptionAttribute));
var name = "";
if(descobj==null)
{
name = pi.Name;
}
else
{
name = descobj.Value;
}
row[name] = pi.GetValue(item, null) ?? DBNull.Value;
}
dt.Rows.Add(row);
}
return ds;
}
}
} |
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Journey.WebApp.Data
{
public partial class Traveler
{
public Traveler()
{
TravelerAlbum = new HashSet<TravelerAlbum>();
TravelerRelationshipsTravelerId1Navigation = new HashSet<TravelerRelationships>();
TravelerRelationshipsTravelerId2Navigation = new HashSet<TravelerRelationships>();
TravelersCities = new HashSet<TravelersCities>();
TravelersTrips = new HashSet<TravelersTrips>();
}
public long Id { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone Number")]
public string Phone { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date of Birth")]
public DateTime? Dob { get; set; }
public string Gender { get; set; }
[Display(Name = "Secondary Email")]
public string Email2 { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "About Me")]
public string AboutMe { get; set; }
[DataType(DataType.MultilineText)]
public string Occupation { get; set; }
[DataType(DataType.MultilineText)]
public string Hobbies { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = "Social Media")]
public string SocialMedia { get; set; }
public DateTime DateCreated { get; set; }
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public ICollection<TravelerAlbum> TravelerAlbum { get; set; }
public ICollection<TravelerRelationships> TravelerRelationshipsTravelerId1Navigation { get; set; }
public ICollection<TravelerRelationships> TravelerRelationshipsTravelerId2Navigation { get; set; }
public ICollection<TravelersCities> TravelersCities { get; set; }
public ICollection<TravelersTrips> TravelersTrips { get; set; }
}
}
|
using System;
using UnityEngine.Events;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// None generic Unity Event of type `QuaternionPair`. Inherits from `UnityEvent<QuaternionPair>`.
/// </summary>
[Serializable]
public sealed class QuaternionPairUnityEvent : UnityEvent<QuaternionPair> { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEMAPI.Models
{
public class CustomerDetails
{
public int ContactID { get; set; }
public string SAPCustomerID { get; set; }
public int ContextId { get; set; }
public string ContextType { get; set; }
public string CustomerName { get; set; }
public int ProjectID { get; set; }
public string ProjectName { get; set; }
public int TowerID { get; set; }
public string TowerName { get; set; }
public int UnitID { get; set; }
public string UnitNumber { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Uintra.Persistence;
using Uintra.Persistence.Sql;
namespace Uintra.Core.Updater.Sql
{
[UintraTable("MigrationHistory")]
public class MigrationHistory : SqlEntity<int>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override int Id { get; set; }
[StringLength(255)]
public string Name { get; set; }
public DateTime CreateDate { get; set; }
[StringLength(50)]
public string Version { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.ValuesObject
{
public class Conjuge
{
public int NumeroConjuge { get; set; }
public string Descricao { get; set; }
public List<Conjuge> ObterListaConjuge()
{
var retornoLista = new List<Conjuge>();
var conjuge = new Conjuge();
conjuge.NumeroConjuge = 1;
conjuge.Descricao = "PRIMEIRO CÔNJUGE LANÇADO (1)";
retornoLista.Add(conjuge);
conjuge = new Conjuge();
conjuge.NumeroConjuge = 2;
conjuge.Descricao = "SEGUNDO CÔNJUGE LANÇADO (2)";
retornoLista.Add(conjuge);
return retornoLista;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Web;
using ProjetoMVC.Repositorio;
namespace ProjetoMVC.Models
{
public class Aluno : Pessoa
{
private string cidade, numero, orgaoExpedidor, rg, rua, sexo, uf;
private DateTime dataNascimento;
//[Display(Name ="Codigo",Description ="Informe um número inteiro de 1 a 99999")]
//public int id { get; set; }
[Display(Name = "Informe o Nome da Sua cidade :")]
[Required(ErrorMessage = "O nome da sua cidade é obrigatório")]
public string Cidade { get => cidade; set => cidade = value; }
[Range(1, 99999)]
[Required(ErrorMessage = "O número deve ser entre 1 a 99999")]
public string Numero { get => numero; set => numero = value; }
[Display(Name = "Orgão Expedidor do Documento: ")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public string OrgaoExpedidor { get => orgaoExpedidor; set => orgaoExpedidor = value; }
[Display(Name = "RG:")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public string Rg { get => rg; set => rg = value; }
[Display(Name = "Rua:")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public string Rua { get => rua; set => rua = value; }
[Display(Name = "Sexo: ")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public string Sexo { get => sexo; set => sexo = value; }
[Display(Name = "Unidade da Federação :")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public string Uf { get => uf; set => uf = value; }
[Display(Name = "Data de Nascimento:")]
[Required(ErrorMessage = "Este campo é obrigatório")]
public DateTime DataNascimento { get => dataNascimento; set => dataNascimento = value; }
public Aluno BuscarAlunoPorID(int id)
{
return Banco.Alunos.First(x => x.Id == id);
}
public void Delete(Aluno id)
{
return;
}
public Aluno Update(Aluno emprestimo)
{
return new Aluno();
}
public void Inserir()
{
if (this.Id == 0)
{
Random r = new Random();
this.Id = r.Next(1, 9999);
Banco.Alunos.Add(this);
}
}
public IList<Aluno> BuscarTodos()
{
return Banco.Alunos;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApp3
{
/// <summary>
/// Логика взаимодействия для WindowSettShop.xaml
/// </summary>
public partial class WindowSettShop : Window
{
SettShopEntities context;
public WindowSettShop(SettShopEntities context, Shopinformation currentinformation)
{
InitializeComponent();
this.context = context;
FirstName.ItemsSource = context.Owner_s.ToList();
Name.ItemsSource = context.Shopinformation.ToList();
this.DataContext = currentinformation;
}
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
if (CheckEdit())
{
context.SaveChanges();
this.Close();
}
}
private bool CheckEdit()
{
var reg = this.DataContext as Shopinformation;
if (reg.Name == null)
{
MessageBox.Show("Владелец не выбран");
return false;
}
if (reg.Name == null)
{
MessageBox.Show("Название магазина не выбрано");
return false;
}
if (reg.Adress == null)
{
MessageBox.Show("Адресс не записан");
return false;
}
if (reg.Shopphone == null)
{
MessageBox.Show("Номер магазина не записан");
return false;
}
return true;
}
}
}
|
namespace Sentry;
/// <summary>
/// Sentry View Hierarchy attachment.
/// </summary>
public class ViewHierarchyAttachment : Attachment
{
/// <summary>
/// Initializes an instance of <see cref="ViewHierarchyAttachment"/>.
/// </summary>
/// /// <param name="content">The view hierarchy attachment</param>
public ViewHierarchyAttachment(IAttachmentContent content) :
base(AttachmentType.ViewHierarchy, content, "view-hierarchy.json", "application/json")
{ }
}
|
namespace AssessmentApp.Common
{
public static class GlobalConstants
{
public const string SystemName = "AssessmentApp";
public const string AdministratorRoleName = "Administrator";
}
}
|
using System;
using strange.framework.api;
using UnityEngine;
namespace strange.examples.strangerocks
{
public class ResourceInstanceProvider : IInstanceProvider
{
//The GameObject instantiated from the prefab
GameObject prototype;
private string resourceName;
private int layer;
private int id = 0;
public ResourceInstanceProvider(string name, int layer) {
resourceName = name;
this.layer = layer;
}
public T GetInstance<T> () {
object instance = GetInstance (typeof(T));
T retv = (T) instance;
return retv;
}
public object GetInstance (Type key) {
if (prototype == null) {
prototype = Resources.Load<GameObject> (resourceName);
prototype.transform.localScale = Vector3.one;
}
GameObject go = GameObject.Instantiate (prototype) as GameObject;
go.name = resourceName + "_" + id++;
return go;
}
}
}
|
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramFootballBot.Core.Services;
namespace TelegramFootballBot.Core.Models.Commands
{
public class StartCommand : Command
{
public override string Name => "/start";
private readonly IMessageService _messageService;
public StartCommand(IMessageService messageService)
{
_messageService = messageService;
}
public override async Task ExecuteAsync(Message message)
{
await _messageService.SendMessageAsync(message.Chat.Id, "Для регистрации введите /reg Фамилия Имя");
}
}
}
|
namespace Photobooth
{
public partial class PhotoboothApp
{
}
}
|
using Android.OS;
using Android.Views;
using Android.Widget;
using MvvmCross.Droid.Shared.Attributes;
using ResidentAppCross.Droid.Views.AwesomeSiniExtensions;
using ResidentAppCross.ViewModels;
namespace ResidentAppCross.Droid.Views
{
[MvxFragment(typeof (ApplicationViewModel), Resource.Id.application_host_container_primary)]
public class MaterialPlaygroundFragment1 : ViewFragment<DevelopmentViewModel1>
{
private Switch _toolbarToggle;
public override int LayoutId => Resource.Layout.material_playground_fragment_1;
public Switch ToolbarToggle
{
get { return _toolbarToggle ?? (_toolbarToggle = Layout.FindViewById<Switch>(Resource.Id.show_toolbar_switch)); }
set { _toolbarToggle = value; }
}
public override void OnViewModelSet()
{
base.OnViewModelSet();
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
ToolbarToggle.Checked = true;
ToolbarToggle.CheckedChange += (sender, args) =>
{
if (ToolbarToggle.Checked)
{
Toolbar.Show();
}
else
{
Toolbar.Hide();
}
};
for (int i = 0; i < 15; i++)
{
Layout.AddView(new TextView(Context)
{
Text = "Mega Trolololo"
}.WithWidthMatchParent().WithHeight(40));
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem417 : ProblemBase {
public override string ProblemName {
get { return "417: Reciprocal cycles II"; }
}
public override string GetAnswer() {
var x = Test(1000000);
return "";
}
private ulong Test(ulong max) {
ulong sum = 0;
for (ulong num = 3; num <= max; num += 3) {
if (num % 5 != 0 && num % 2 != 0) {
var result = GetChainSize(num);
sum += result;
}
}
return sum;
}
private ulong GetChainSize(ulong num) {
ulong count = 1;
var remainder = 10 % num;
while (remainder != 1) {
remainder = (remainder * 10) % num;
count++;
}
return count;
}
}
}
|
using Content.Client.Weapons.Ranged.Barrels.Components;
using Robust.Client.GameObjects;
namespace Content.Client.Weapons.Ranged.Barrels.EntitySystems;
public sealed class ClientBatteryBarrelSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ClientBatteryBarrelComponent, AppearanceChangeEvent>(OnAppearanceChange);
}
private void OnAppearanceChange(EntityUid uid, ClientBatteryBarrelComponent component, ref AppearanceChangeEvent args)
{
component.ItemStatus?.Update(args.Component);
}
}
|
using Centrifuge.Distance.Game;
using Centrifuge.Distance.GUI.Controls;
using Centrifuge.Distance.GUI.Data;
using Reactor.API.Attributes;
using Reactor.API.Interfaces.Systems;
using Reactor.API.Logging;
using Reactor.API.Runtime.Patching;
using UnityEngine;
namespace Distance.WheelieBoostFix
{
[ModEntryPoint("com.seekr.wbfix")]
public sealed class Mod : MonoBehaviour
{
public static Mod Instance { get; private set; }
public IManager Manager { get; private set; }
public Log Logger { get; private set; }
public ConfigurationLogic Configuration { get; private set; }
public void Initialize(IManager manager)
{
DontDestroyOnLoad(this);
Instance = this;
Manager = manager;
Logger = LogManager.GetForCurrentAssembly();
Configuration = gameObject.AddComponent<ConfigurationLogic>();
CreateSettingsMenu();
RuntimePatcher.AutoPatch();
}
private void CreateSettingsMenu()
{
MenuTree settingsMenu = new MenuTree("menu.mod.wbfix", "Wheelie Boost Fix Settings")
{
new CheckBox(MenuDisplayMode.Both, "setting:debug", "DEBUG MODE")
.WithGetter(() => Configuration.Debug)
.WithSetter((x) => Configuration.Debug = x)
.WithDescription("Output debugging information to the console and log file."),
new FloatSlider(MenuDisplayMode.Both, "settings:default_boost_multiplier", "DEFAULT BOOST MULTIPLIER")
.LimitedByRange(0, 10)
.WithDefaultValue(1.05f)
.WithGetter(() => Configuration.DefaultBoostMultiplier)
.WithSetter((x) => Configuration.DefaultBoostMultiplier = x)
.WithDescription("Default multiplier applied to the boost speed (lower values means a lower speed)."),
new FloatSlider(MenuDisplayMode.Both, "settings:jump_boost_multiplier", "JUMP BOOST MULTIPLIER")
.LimitedByRange(0, 10)
.WithDefaultValue(0.79f)
.WithGetter(() => Configuration.JumpBoostMultiplier)
.WithSetter((x) => Configuration.JumpBoostMultiplier = x)
.WithDescription("Boost multiplier applied after jumping (lower values means a lower speed)."),
new IntegerSlider(MenuDisplayMode.Both, "setting:jump_boost_mltiplier_frames", "JUMP BOOST MULTIPLIER FRAMES")
.LimitedByRange(0, 500)
.WithDefaultValue(60)
.WithGetter(() => Configuration.JumpBoostMultiplierFrames)
.WithSetter((x) => Configuration.JumpBoostMultiplierFrames = x)
.WithDescription("How long (in frames) should the jump boost multiplier be applied."),
new IntegerSlider(MenuDisplayMode.Both, "setting:wheel_threshold", "WHEEL THRESHOLD")
.LimitedByRange(0, 4)
.WithDefaultValue(1)
.WithGetter(() => Configuration.WheelThreshold)
.WithSetter((x) => Configuration.WheelThreshold = x)
.WithDescription("The numbers of wheels contacting a surface needed for the car to be considered 'grounded'.")
};
Menus.AddNew(MenuDisplayMode.Both, settingsMenu, "WHEELIE BOOST FIX", "Change settings of the Wheelie Boost Fix.");
}
public bool GameplayCheatsAllowed()
{
NetworkingManager networking = G.Sys.NetworkingManager_;
return networking?.IsOnline_ == false;
}
}
} |
using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Source.Code.MyPhoton
{
public class ConnectionToRoom : MonoBehaviourPunCallbacks
{
[SerializeField] private TextMeshProUGUI debugTMP;
[SerializeField] private Button[] buttons;
private void Awake()
{
foreach (var button in buttons) button.interactable = false;
debugTMP.text = "";
}
public void OnCreateNewRoomButtonClick()
{
PhotonNetwork.CreateRoom(null, new RoomOptions { MaxPlayers = 6});
}
public void OnJoinToRandomRoomClick()
{
PhotonNetwork.JoinRandomRoom();
}
public override void OnConnectedToMaster()
{
foreach (var button in buttons) button.interactable = true;
Hashtable props = new Hashtable { { GlobalConst.PLAYER_READY, false } };
PhotonNetwork.LocalPlayer.SetCustomProperties(props);
props = new Hashtable { { GlobalConst.PLAYER_LOADED_LEVEL, false } };
PhotonNetwork.LocalPlayer.SetCustomProperties(props);
}
public override void OnDisconnected(DisconnectCause cause)
{
foreach (var button in buttons) button.interactable = false;
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
string debugText = $"OnJoinRandomFailed() was called by PUN. No random room available. Short: {returnCode} Message: {message}";
Debug.LogError(debugText);
debugTMP.text = debugText;
debugTMP.color = Color.red;
}
public override void OnCreateRoomFailed(short returnCode, string message)
{
string debugText = $"OnCreateRoomFailed() was called by PUN. Short: {returnCode} Message: {message}";
Debug.LogError(debugText);
debugTMP.text = debugText;
debugTMP.color = Color.red;
}
public override void OnJoinedRoom()
{
SetCustomProperties();
PhotonNetwork.LoadLevel("Room");
}
private void SetCustomProperties()
{
}
}
} |
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL
{
/**
* Unit Of Work
* */
public class AppManager
{
public static LinkedInContext linkedInContext =
new LinkedInContext();
public PostsManager Post
{
get
{
return new PostsManager(linkedInContext);
}
}
public ExperienceManager User_Com_Experience
{
get
{
return new ExperienceManager(linkedInContext);
}
}
public UserActions userDetails
{
get
{
return new UserActions(linkedInContext);
}
}
public EducationManager EducationManager
{
get
{
return new EducationManager(linkedInContext);
}
}
public Education_OrganizationManager Education_Organization
{
get
{
return new Education_OrganizationManager(linkedInContext);
}
}
}
}
|
namespace Properties.Models
{
public class Area
{
public string PostcodePrefix { get; set; }
public string FriendlyName { get; set; }
}
} |
using System;
using System.Text;
namespace LAOffsetUpdater
{
public class MemoryReader
{
public int Handle { get; set; }
public MemoryReader()
{
}
public byte ReadByte(long address)
{
byte[] buffer = new byte[sizeof(byte)];
int bytesRead = 0;
Win32.ReadProcessMemory(Handle, address, buffer, buffer.Length, ref bytesRead);
return buffer[0];
}
public byte ReadByte(int index, byte[] data)
{
if (index >= data.Length || index < 0)
return 0;
return data[index];
}
public byte[] ReadByteArray(long address, int Size)
{
byte[] buffer = new byte[Size];
int bytesRead = 0;
Win32.ReadProcessMemory(Handle, address, buffer, buffer.Length, ref bytesRead);
return buffer;
}
public long ReadInt64(long address)
{
byte[] buffer = new byte[sizeof(long)];
int bytesRead = 0;
Win32.ReadProcessMemory(Handle, address, buffer, buffer.Length, ref bytesRead);
return BitConverter.ToInt64(buffer, 0);
}
public long ReadInt64(int index, byte[] data)
{
if (index + sizeof (long) > data.Length)
return 0;
return BitConverter.ToInt64(data, index);
}
public int ReadInt32(int index, byte[] data)
{
if (index + sizeof(int) > data.Length)
return 0;
return BitConverter.ToInt32(data, index);
}
public string ReadStringUnicode(long address)
{
string rtn = "";
byte[] buffer = new byte[512];
int bytesRead = 0;
byte[] b = new byte[1];
int count = 0;
int countB = 0;
for (int i = 0; i < 512; i++)
{
Win32.ReadProcessMemory(Handle, address + i, b, b.Length, ref bytesRead);
buffer[i] = b[0];
if (b[0] == 0)
count++;
if (b[0] != 0)
{
count--;
countB++;
}
if (count >= 2)
break;
if (count < -1)
return rtn;
}
byte[] bufferB = new byte[countB * 2];
Array.Copy(buffer, bufferB, countB * 2);
rtn = Encoding.Unicode.GetString(bufferB);
return rtn;
}
public string ReadStringUnicode(int index, byte[] data)
{
string rtn = "";
byte[] buffer = new byte[512];
int length = buffer.Length;
if (index + length > data.Length)
length = data.Length - index;
byte[] b = new byte[1];
int count = 0;
int countB = 0;
for (int i = 0; i < length; i++)
{
b[0] = data[index + i];
buffer[i] = b[0];
if (b[0] == 0)
count++;
if (b[0] != 0)
{
count--;
countB++;
}
if (count >= 2)
break;
if (count < -1)
return rtn;
}
byte[] bufferB = new byte[countB * 2];
Array.Copy(buffer, bufferB, countB * 2);
rtn = Encoding.Unicode.GetString(bufferB);
return rtn;
}
public string ReadStringASCII(long address)
{
byte[] buffer = new byte[512];
int bytesRead = 0;
Win32.ReadProcessMemory(Handle, address, buffer, buffer.Length, ref bytesRead);
int counter = 0;
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] == 0)
break;
counter++;
}
byte[] a = new byte[counter];
Array.Copy(buffer, 0, a, 0, counter);
string output = Encoding.ASCII.GetString(a);
return output;
}
public string ReadStringASCII(int index, byte[] data)
{
byte[] buffer = new byte[512];
int length = buffer.Length;
if (index + length > data.Length)
length = data.Length - index;
Array.Copy(data, index, buffer, 0, length);
int counter = 0;
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] == 0)
break;
counter++;
}
byte[] a = new byte[counter];
Array.Copy(buffer, 0, a, 0, counter);
string output = Encoding.ASCII.GetString(a);
return output;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SqlServerWebAdmin
{
public partial class FileProperties : System.Web.UI.UserControl
{
public object Properties
{
get
{
int growth = 0;
int maximumFileSize = 0;
try
{
growth = Convert.ToInt32(GrowthTextBox.Text);
}
catch
{
throw new Exception("Growth must be an integer");
}
try
{
maximumFileSize = Convert.ToInt32(MaximumFileSizeTextBox.Text);
}
catch
{
throw new Exception("Maximum file size must be an integer");
}
return null;
//return new FileProperties(
// /*(GrowthTypeDropDownList.SelectedIndex == 0) ? SqlFileGrowthType.MB : SqlFileGrowthType.Percent*/0,
// AutomaticallyGrowFileCheckBox.Checked ? growth : 0,
// UnrestrictedGrowthRadioButton.Checked ? -1 : maximumFileSize);
}
set
{
//Microsoft.SqlServer.Management.Smo.DatabaseFile
/*FileProperties props = value;
if (props.FileGrowth == 0)
AutomaticallyGrowFileCheckBox.Checked = false;
else
AutomaticallyGrowFileCheckBox.Checked = true;
if (props.FileGrowthType == 0) //SqlFileGrowthType.MB
GrowthTypeDropDownList.SelectedIndex = 0;
else
GrowthTypeDropDownList.SelectedIndex = 1;
GrowthTextBox.Text = props.FileGrowth.ToString();
if (props.MaximumSize == -1)
{
UnrestrictedGrowthRadioButton.Checked = true;
RestrictGrowthRadioButton.Checked = false;
}
else
{
UnrestrictedGrowthRadioButton.Checked = false;
RestrictGrowthRadioButton.Checked = true;
}
MaximumFileSizeTextBox.Text = props.MaximumSize.ToString();*/
}
}
}
} |
using Alabo.Cloud.People.UserRightss.Domain.Dtos;
using Alabo.Cloud.People.UserRightss.Domain.Entities;
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
using Alabo.Industry.Shop.Orders.Dtos;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Alabo.Cloud.People.UserRightss.Domain.Services
{
public interface IUserRightsService : IService<UserRights, long>
{
/// <summary>
/// 获取权益修改视图
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
UserRights GetEditView(object id);
/// <summary>
/// 添加或删除权益
/// </summary>
/// <param name="view"></param>
/// <returns></returns>
ServiceResult AddOrUpdate(UserRights view);
/// <summary>
/// 获取商家权益
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
IList<UserRightsOutput> GetView(long userId);
/// <summary>
/// 获取商家权益
/// </summary>
/// <param name="isAdmin"></param>
/// <returns></returns>
IList<UserRightsOutput> GetView(bool isAdmin);
/// <summary>
/// 商家服务订购
/// </summary>
/// <param name="orderBuyInput"></param>
/// <returns></returns>
Task<Tuple<ServiceResult, OrderBuyOutput>> Buy(UserRightsOrderInput orderBuyInput);
/// <summary>
/// 获取支付的价格
/// </summary>
/// <returns></returns>
Tuple<ServiceResult, decimal> GetPayPrice(UserRightsOrderInput orderBuyInput);
/// <summary>
/// 帮别人开通
/// </summary>
/// <param name="orderBuyInput"></param>
/// <returns></returns>
Task<Tuple<ServiceResult, OrderBuyOutput>> OpenToOther(UserRightsOrderInput orderBuyInput);
/// <summary>
/// 自己开通或自己升级
/// </summary>
/// <param name="orderBuyInput"></param>
/// <returns></returns>
Task<Tuple<ServiceResult, OrderBuyOutput>> OpenSelfOrUpgrade(UserRightsOrderInput orderBuyInput);
/// <summary>
/// 支付时调用执行的Sql脚本
/// </summary>
/// <param name="entityIdList"></param>
/// <returns></returns>
List<string> ExcecuteSqlList(List<object> entityIdList);
/// <summary>
/// 支付成功回调函数
/// </summary>
/// <param name="entityIdList"></param>
void AfterPaySuccess(List<object> entityIdList);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// Author: Corwin Belser
/// Attach to a GameObject to expand it until reaching a max distance
public class ScaleThenDestroy : MonoBehaviour {
public float MAX_DISTANCE = 15f; /* Max size the GameObject should reach before being destroyed */
public float EXPANSION_SPEED = 10f; /* Speed in m/s the GameObject should expand at */
/// <summary>
/// Called every frame. Destroys the GameObject if the size exceeds MAX_DISTANCE. Otherwise scales the GameObject
/// </summary>
void FixedUpdate () {
Vector3 scale = this.transform.localScale;
if (scale.magnitude > MAX_DISTANCE * 2)
GameObject.Destroy(this.gameObject);
else
{
//Debug.Log("Magnitude: " + this.transform.localScale.magnitude + ", scale.x: " + scale.x);
float increase = EXPANSION_SPEED * Time.deltaTime;
this.transform.localScale = new Vector3(scale.x + increase, scale.y + increase, scale.z + increase);
}
}
}
|
using Microsoft.Extensions.Logging;
namespace EntityFrameworkCoreGetSQL
{
public class LoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new Logger();
}
public void Dispose()
{
}
}
}
|
using ClearBank.DeveloperTest.Types;
namespace ClearBank.DeveloperTest.PaymentSchemeValidators
{
public interface IPaymentSchemeValidator
{
bool IsValid(Account account, MakePaymentRequest request);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CheckAvability.Common;
using CheckAvability.Service;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CheckAvability.Model;
using System.Collections;
using System.Data;
using System.Windows.Threading;
using CheckAvability.DAL;
namespace CheckAvability
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private IConfiguration config { get; set; }
//private IStoreService storeService { get; set; }
private ICheckIphoneService checkIphoneService { get; set; }
private IAuthService authService { get; set; }
private IIphonePlus PlusDAL { get; set; }
private DispatcherTimer dispatcherTimer { get; set; }
private int DefaultSecond { get; set; } = 15;
private bool isDBSave { get; set; } = false;
public MainWindow()
{
this.config = new Configuration();
//this.storeService = new StoreService(this.config);
this.checkIphoneService = new CheckIphoneService(this.config);
this.authService = new AuthService(this.config);
this.PlusDAL = new IphonePlus();
InitializeComponent();
}
private async void btn_Start_Click(object sender, RoutedEventArgs e)
{
try
{
if (string.IsNullOrEmpty(textBox.Text))
{
int second;
if (Int32.TryParse(textBox.Text, out second))
{
this.DefaultSecond = second;
}
}
this.dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, this.DefaultSecond);
dispatcherTimer.Start();
await CheckAvalibility();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private async void dispatcherTimer_Tick(object sender, EventArgs e)
{
await CheckAvalibility();
}
public async Task CheckAvalibility()
{
dynamic result = await checkIphoneService.GetIphoneTaskAsyn();
List<IphoneAvalibilityInStore> IphoneInStore = new List<IphoneAvalibilityInStore>();
List<IphonePlusAvalibilityInStore> IphonePlusInStore = new List<IphonePlusAvalibilityInStore>();
var jObj = (JObject)result;
foreach (JToken token in jObj.Children())
{
if (token is JProperty)
{
var prop = token as JProperty;
if (prop.Name == "R409" || prop.Name == "R428" || prop.Name == "R485" || prop.Name == "R499" || prop.Name == "R610")
{
IphoneAvalibilityInStore get_iphone_return = Mapper.IphoneMapping(prop.Name, prop.Value.ToString());
IphonePlusAvalibilityInStore get_iphone_plus_return = Mapper.IphonePlusMapping(prop.Name, prop.Value.ToString());
IphoneInStore.Add(get_iphone_return);
IphonePlusInStore.Add(get_iphone_plus_return);
}
}
}
IphonedataGrid.ItemsSource = IphoneInStore;
IphonePlusdataGrid.ItemsSource = IphonePlusInStore;
IphonedataGrid.Items.Refresh();
IphonePlusdataGrid.Items.Refresh();
if (isDBSave)
{
var plus_mapper_return = Common.IphonePlusMapper.IphonePlusMapToDbEntities(IphonePlusInStore).ToList();
if (plus_mapper_return.Count() > 0)
{
await PlusDAL.Create(plus_mapper_return);
}
}
}
private async void btnAuth_Click(object sender, RoutedEventArgs e)
{
await this.authService.GetLoginUrlTask();
}
//public void UpdateColor(DataGrid input)
//{
// var r= GetDataGridRows(input);
// foreach (DataGridColumn column in IphonedataGrid.Columns)
// {
// if (column.GetCellContent(r) is TextBlock)
// {
// TextBlock cellContent = column.GetCellContent(r) as TextBlock;
// if (cellContent.Text == "ALL")
// {
// cellContent.Background = Brushes.Pink;
// }
// }
// }
//}
//public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
//{
// var itemsSource = grid.ItemsSource as IEnumerable;
// if (null == itemsSource) yield return null;
// foreach (var item in itemsSource)
// {
// var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
// if (null != row) yield return row;
// }
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication42.Models;
namespace WebApplication42.Controllers
{
[Authorize]
public class RealVController : Controller
{
volunteer v = null;
public ActionResult loggedin(volunteerlogin v)
{
ViewData["name"] = v.UserName;
List<volunteer> x = new List<volunteer>();
using (DBModels db = new DBModels())
{
x = db.volunteers.ToList();
foreach (var y in x)
{
if (y.VID == v.ID)
return View();
}
}
return RedirectToAction("wrong", "Volunteer");
}
}
}
|
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace DemoF.Web.Extensions
{
using Core.Contracts;
using Core.Repositories;
using Persistence;
using Persistence.Repositories;
using Filters;
using Services;
using DemoF.Core.Domain;
public static class ServiceCollectionExtensions
{
// https://github.com/aspnet/JavaScriptServices/tree/dev/src/Microsoft.AspNetCore.SpaServices#debugging-your-javascripttypescript-code-when-it-runs-on-the-server
// Url to visit:
// chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
public static IServiceCollection AddPreRenderDebugging(this IServiceCollection services, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
services.AddNodeServices(options =>
{
options.LaunchWithDebugging = true;
options.DebuggingPort = 9229;
});
}
return services;
}
public static IServiceCollection AddCustomizedMvc(this IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(ModelValidationFilter));
})
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
return services;
}
public static IServiceCollection AddCustomDbContext(this IServiceCollection services)
{
// Add framework services.
services.AddDbContextPool<DemofContext>(options =>
{
options.UseSqlServer(Startup.Configuration["Data:DemoF:ConnectionString"], b => b.MigrationsAssembly("DemoF.Web"));
});
return services;
}
public static IServiceCollection RegisterCustomServices(this IServiceCollection services)
{
services.AddTransient<IUnitOfDemof, UnitOfDemof>();
services.AddTransient<DemofContext>();
services.AddScoped<ApiExceptionFilter>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IUserRepositoryDapper, UserRepositoryDapper>(provider => new UserRepositoryDapper(Startup.Configuration["Data:DemoF:ConnectionString"]));
services.AddTransient<IUserService, UserService>();
return services;
}
}
}
|
using System;
using PostSharp.Extensibility;
using PostSharp.Laos;
namespace DelftTools.Utils.Aop.EditableObject
{
[MulticastAttributeUsage(MulticastTargets.Class)]
public sealed class EditableObjectAttribute : CompoundAspect
{
/// <summary>
/// Method called at compile time to get individual aspects required by the current compound
/// aspect.
/// </summary>
/// <param name="element">Metadata element (<see cref="Type"/> in our case) to which
/// the current custom attribute instance is applied.</param>
/// <param name="collection">Collection of aspects to which individual aspects should be
/// added.</param>
public override void ProvideAspects(object element, LaosReflectionAspectCollection collection)
{
// Get the target type.
var targetType = (Type) element;
// On the type, add a Composition aspect to implement the INotifyPropertyChanged interface.
collection.AddAspect(targetType, new AddEditableObjectInterfaceSubAspect());
}
#region Nested type: AddEditableObjectInterfaceSubAspect
#endregion
}
} |
using StructureMap;
namespace Ajf.NugetWatcher
{
public static class ServiceIoC
{
/// <summary>
/// </summary>
public static IContainer Initialize()
{
return new Container(c =>
{
c.AddRegistry<ServiceRegistry>();
});
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using PingoSnake.Code.Engine;
using PingoSnake.Code.Entities;
using PingoSnake.Code.GUI;
using PingoSnake.Code.LoadingScreens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PingoSnake.Code.Scenes
{
class SnakeLevel : Scene
{
public override void LoadTextures()
{
base.LoadTextures();
this.AddTexture("ice_background_1", newName: "ice_background");
this.AddTexture("ice_tile_platform_1", newName: "ice_platform");
this.AddTexture("running_penguin_with_duck_1_cropped", newName: "penguin");
this.AddTexture("walrus_1", newName: "walrus");
this.AddTexture("seagule2", newName: "seagull");
this.AddTexture("good_neighbors_32", newName: "spritefont32");
this.AddTexture("good_neighbors_64", newName: "spritefont64");
//this.AddTexture("good_neighbors_128", newName: "spritefont128");
this.AddTexture("snake_v2", newName: "snake");
this.AddTexture("snake_v3", newName: "snake3");
this.AddTexture("snake_v4", newName: "snake4");
this.AddTexture("snake_v5", newName: "snake5");
this.AddTexture("snake_v6", newName: "snake6");
this.AddTexture("snake_v7", newName: "snake7");
this.AddTexture("food20", newName: "food");
//this.AddTexture("dirt_background", newName: "dirt_background");
this.AddTexture("dirt_background1", newName: "dirt_background");
}
public override void LoadSounds()
{
base.LoadSounds();
AddSoundEffect("eat1", "eat");
AddSoundEffect("dizzy", "dizzy");
}
public override LoadingScreen GetLoadingScreen(Scene scene)
{
return new MainLoadingScreen(scene);
}
public override void Initialize()
{
base.Initialize();
int floor_pos_y = this.GetWindowHeight() - 128;
SnakeBackground snakeBackground1 = new SnakeBackground(new Vector2(0, 0));
SnakeBackground snakeBackground2 = new SnakeBackground(new Vector2(1025, 0));
AddEntity(snakeBackground1);
AddEntity(snakeBackground2);
Snake snake = new Snake(new Vector2(400, floor_pos_y - 128), new Vector2(0, 0), new Rectangle(0, 0, GetWindowWidth(), GetWindowHeight()));
AddEntity(snake);
GameGUI gameGUI = new GameGUI();
AddEntity(gameGUI);
GameState.Instance.SetVar<bool>("game_over", false);
GameState.Instance.SetVar<double>("score", 0);
}
public void CheckKeyboard()
{
KeyboardState keyState = Keyboard.GetState();
KeyboardState prevKeyState = GameState.Instance.GetPrevKeyboardState();
if (keyState.IsKeyDown(Keys.P) && !prevKeyState.IsKeyDown(Keys.P))
{
if (!GameState.Instance.GetVar<bool>("game_over"))
TogglePause();
}
if (keyState.IsKeyDown(Keys.Enter) && !prevKeyState.IsKeyDown(Keys.Enter))
{
if (GameState.Instance.GetVar<bool>("game_over"))
GameState.Instance.SetScene(new SnakeLevel());
}
if (keyState.IsKeyDown(Keys.Escape) && !prevKeyState.IsKeyDown(Keys.Escape))
{
GameState.Instance.SetScene(new MainMenu());
}
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
CheckKeyboard();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using CsvHelper;
using DataProvider;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MimeKit;
using OrderLibrary;
using OrderLibrary.Models;
namespace Scheduler
{
public class OrdersScheduler : BackgroundService
{
private readonly ILogger<OrdersScheduler> _logger;
private readonly IConfiguration _config;
private readonly ISmtpClient _smtpClient;
private IReader Reader { get; set; }
private int _maxMailsAtOnce;
private int _cycleTimeMilisec;
private string _sender;
public OrdersScheduler(ILogger<OrdersScheduler> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_smtpClient = new SmtpClient();
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Reading application settings...");
var (host, port, from, password) = GetSmtpFromConfiguration();
this._maxMailsAtOnce = _config.GetValue<int>(key: "MaxMailsAtOnce");
this._cycleTimeMilisec = _config.GetValue<int>("CycleTimeMilisec");
this._sender = from;
_logger.LogInformation("Initializing data reader...");
InitializeDataReader();
_logger.LogInformation("Connecting to the smtp server...");
await ConnectToSmtpAsync(host, port, from, password, cancellationToken);
await base.StartAsync(cancellationToken);
}
#region StartAsync Methods
private void InitializeDataReader()
{
var filePath = _config.GetValue<string>("CsvFilePath");
var sr = new StreamReader(filePath);
Reader = new CsvReader(sr, CultureInfo.InvariantCulture);
Reader.Configuration.HasHeaderRecord = false;
}
private async Task ConnectToSmtpAsync(string host, int port, string from, string password, CancellationToken cancellationToken)
{
await _smtpClient.ConnectAsync(host, port, false, cancellationToken);
await _smtpClient.AuthenticateAsync(from, password, cancellationToken);
}
private (string host, int port, string from, string password) GetSmtpFromConfiguration()
{
var host = _config.GetValue<string>("Smtp:Server");
var port = _config.GetValue<int>("Smtp:Port");
var from = _config.GetValue<string>("Smtp:FromAddress");
var password = _config.GetValue<string>("Smtp:Password");
return (host, port, from, password);
}
#endregion
/// <summary>
/// Service running in cycle.
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation($"Starting cycle: {DateTimeOffset.Now}");
await ExecuteOrderProcessAsync(stoppingToken);
await WaitAsync(_cycleTimeMilisec, stoppingToken);
}
}
#region ExecuteAsync Methods
private async Task ExecuteOrderProcessAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Getting data from file...");
var ordersProvider = new OrdersProvider();
var orders = ordersProvider.GetOrdersFromCsv(Reader).Take(_maxMailsAtOnce).ToList();
if (!orders.Any()) return;
_logger.LogInformation($"Found {orders.Count} orders for send.");
_logger.LogInformation("Starting sending process...");
var orderMailService = new OrderMailService(_smtpClient, _logger);
await orderMailService.SendOrders(orders, stoppingToken);
}
#endregion
/// <summary>
/// Methods for end of
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Disconecting from smtp server...");
await _smtpClient.DisconnectAsync(false, cancellationToken);
await base.StopAsync(cancellationToken);
}
private async Task WaitAsync(int milisecondsDelay, CancellationToken stoppingToken)
{
_logger.LogInformation($"Waiting {milisecondsDelay} miliseconds for another cycle...");
await Task.Delay(milisecondsDelay, stoppingToken);
}
}
}
|
using BDTest.Maps;
namespace BDTest.NetCore.Razor.ReportMiddleware.Interfaces;
public interface IBDTestDataReceiver
{
public Task OnReceiveTestDataAsync(BDTestOutputModel bdTestOutputModel);
} |
using UnityEngine;
using System.Collections;
public class Constants : MonoBehaviour
{
// Tags
public const string PLAYER = "Player";
public const string ENEMY = "Enemy";
public const string MAIN_CAMRA = "MainCamera";
public const string GAME_CONTROLLER = "GameController";
public const string FOOTSTEP_MANAGER = "FootstepManager";
public const string AUDIO_MANAGER = "AudioManager";
public const string MUZZLEFLASH = "Muzzleflash";
public const string UI_INVENTORY_EQUIPPED = "UI_Inventory_Equipped";
public const string UI_INVENTORY_STACK = "UI_Inventory_Stack";
public const string UI_INVENTORY_IMAGE = "UI_Inventory_Image";
public const string UI_BULLET_COUNT = "UI_Bullet_Count";
// Input
public const string VERTICAL = "Vertical";
public const string HORIZONTAL = "Horizontal";
public const string RUN = "Run";
public const string CROUCH = "Crouch";
public const string PRONE = "Prone";
public const string INVENTORY = "Inventory";
public const string FIRE = "Fire1";
public const string RELOAD = "Reload";
// Animator Parameters
public const string IS_RUNNING = "IsRunning";
public const string IS_CROUCHING = "IsCrouching";
public const string IS_PRONING = "IsProning";
public const string WEAPON_ID = "Weapon_ID";
public const string SHOOT = "Shoot";
public const string IS_DUAL_WIELDING = "IsDualWielding";
// Footsteps
public const string SNOW = "Snow";
// Inventory
public const string LEFT_HAND = "Left_Hand";
public const string RIGHT_HAND = "Right_Hand";
}
|
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public enum BodyMovementType {
STILL = 0,
TURNING,
DRAGGING,
};
public float startCatAngle = 45f;
public GameObject rightPawGameObject;
public GameObject leftPawGameObject;
public HeadMovement headMovement;
public GameObject fartPuffPrototype;
public GameObject butthole;
public BodyMovementType bodyMovement { get; private set;}
private float targetTurnAngleDegrees;
private float currentTurnAngleDegrees;
// When I start dragging on cat butt, dragAnchor = cat coords of touched
// point on butt. Flatten y value to 0.
private Vector3 dragAnchorCat;
// When I start dragging on cat butt, dragAngleAngle = angle from
// cat fwd (0, 0, 1) to dragAnchorOnCat.
private float dragAnchorAngleCat;
public static PlayerController instance { get; private set; }
bool registeredForEvents;
public delegate void TurnedWithTapHandler();
public event TurnedWithTapHandler TurnedWithTap;
public delegate void TurnedWithDragHandler();
public event TurnedWithDragHandler TurnedWithDrag;
public delegate void SwattedHandler();
public event SwattedHandler Swatted;
float lastFartTime;
public float fartPause;
void Awake() {
instance = this;
bodyMovement = BodyMovementType.STILL;
}
// Use this for initialization
void Start () {
RegisterForEvents ();
Reset ();
}
void OnDestroy() {
UnregisterForEvents ();
}
void RegisterForEvents() {
if (registeredForEvents) {
return;
}
registeredForEvents = true;
GamePhaseState.instance.GameInstanceChanged +=
new GamePhaseState.GameInstanceChangedEventHandler (OnInstanceChanged);
BoostConfig.instance.BoostActive +=
new BoostConfig.BoostActiveEventHandler (OnBoostActive);
}
void UnregisterForEvents() {
if (registeredForEvents) {
GamePhaseState.instance.GameInstanceChanged -=
new GamePhaseState.GameInstanceChangedEventHandler (OnInstanceChanged);
BoostConfig.instance.BoostActive -=
new BoostConfig.BoostActiveEventHandler (OnBoostActive);
}
}
void OnInstanceChanged() {
Reset ();
}
void OnBoostActive(BoostConfig.BoostType newType,
BoostConfig.BoostType oldType) {
if (newType == BoostConfig.BoostType.BOOST_TYPE_FART) {
MakeFartPuff();
}
}
void Reset() {
bodyMovement = BodyMovementType.STILL;
currentTurnAngleDegrees = startCatAngle;
targetTurnAngleDegrees = currentTurnAngleDegrees;
transform.rotation = Quaternion.Euler (0, 0, currentTurnAngleDegrees);
}
// Update is called once per frame
void Update () {
MaybeMakeFartPuff ();
switch (bodyMovement) {
case BodyMovementType.DRAGGING:
UpdateDrag ();
break;
case BodyMovementType.TURNING:
UpdateTurn ();
break;
}
}
void UpdateTurn() {
if (currentTurnAngleDegrees < targetTurnAngleDegrees) {
currentTurnAngleDegrees += TweakableParams.turnVelocityDegrees * Time.deltaTime;
if (currentTurnAngleDegrees > targetTurnAngleDegrees) {
currentTurnAngleDegrees = targetTurnAngleDegrees;
bodyMovement = BodyMovementType.STILL;
}
} else {
currentTurnAngleDegrees -= TweakableParams.turnVelocityDegrees * Time.deltaTime;
if (currentTurnAngleDegrees < targetTurnAngleDegrees) {
currentTurnAngleDegrees = targetTurnAngleDegrees;
bodyMovement = BodyMovementType.STILL;
}
}
transform.rotation = Quaternion.Euler (0, 0, currentTurnAngleDegrees);
}
void UpdateDrag() {
Vector3 clickPositionScreen;
bool isClicked = InputHandler.instance.GetWorldClickPosition (out clickPositionScreen);
if (!isClicked) {
bodyMovement = BodyMovementType.STILL;
return;
}
Vector3 clickPositionWorld = Camera.main.ScreenToWorldPoint (clickPositionScreen);
Vector3 clickPositionCat = transform.InverseTransformPoint (clickPositionWorld);
float clickAngleCat = Utilities.GetZAngle (clickPositionCat);
transform.Rotate (new Vector3(0.0f, 0.0f, clickAngleCat - dragAnchorAngleCat));
}
public void HandleDragClickStart(Vector2 worldPoint2d) {
bodyMovement = BodyMovementType.DRAGGING;
dragAnchorCat = transform.InverseTransformPoint(worldPoint2d);
dragAnchorCat.z = 0.0f;
dragAnchorAngleCat = Utilities.GetZAngle (dragAnchorCat);
rightPawGameObject.GetComponent<PawController> ().CancelSwipe();
leftPawGameObject.GetComponent<PawController> ().CancelSwipe();
if (TurnedWithDrag != null) {
TurnedWithDrag();
}
}
public void HandleSlapClickStart(Vector2 worldPoint2d) {
Vector3 swipeLocationCat;
float angle;
GameObject paw = GetPawToHitWorldLocation (worldPoint2d,
out swipeLocationCat,
out angle);
if (paw) {
// If for a paw, do the slap.
paw.GetComponent<PawController> ().Swipe (swipeLocationCat);
if (Swatted != null) {
Swatted();
}
} else {
// Otherwise start turning to face this location.
currentTurnAngleDegrees = transform.rotation.eulerAngles.z;
targetTurnAngleDegrees = angle + currentTurnAngleDegrees;
bodyMovement = BodyMovementType.TURNING;
rightPawGameObject.GetComponent<PawController> ().CancelSwipe();
leftPawGameObject.GetComponent<PawController> ().CancelSwipe();
if (TurnedWithTap != null) {
TurnedWithTap();
}
}
headMovement.LookTowards (swipeLocationCat);
}
void OnApplicationFocus(bool focusStatus) {
if (!focusStatus) {
if (!DebugConfig.instance.useDebugValues) {
bodyMovement = BodyMovementType.STILL;
}
}
}
void MaybeMakeFartPuff() {
if (BoostConfig.instance.activeBoost == BoostConfig.BoostType.BOOST_TYPE_FART &&
Time.time > lastFartTime + fartPause) {
MakeFartPuff ();
}
}
void MakeFartPuff() {
GameObject fartPuffObject = Instantiate (fartPuffPrototype,
butthole.transform.position,
Quaternion.identity) as GameObject;
FartPuff fartPuff = fartPuffObject.GetComponent<FartPuff> ();
fartPuff.SetDirection (transform.rotation * Vector3.left);
lastFartTime = Time.time;
}
public GameObject GetPawToHitWorldLocation(Vector2 worldPoint2d,
out Vector3 swipeLocationCat,
out float angle) {
// Get this position in terms of cat position.
swipeLocationCat = transform.InverseTransformPoint (worldPoint2d);
angle = 0;
// If outside of reach radius, ignore altogether.
if (swipeLocationCat.magnitude > TweakableParams.swipeRadius) {
swipeLocationCat *= TweakableParams.swipeRadius/swipeLocationCat.magnitude;
}
// Is this a slap for right paw, left paw, or neither?
angle = Utilities.GetZAngle (swipeLocationCat);
if (angle >= 0 &&
angle <= ConeOfViewController.instance.actualAngleRange / 2) {
return leftPawGameObject;
} else if (angle < 0 &&
angle >= -ConeOfViewController.instance.actualAngleRange / 2) {
return rightPawGameObject;
} else {
return null;
}
}
}
|
using Data.Contracts;
using Data.Models;
using Data.Services.Contracts;
namespace Data.Services
{
public class UserDataService : DataService<User>, IUserDataService
{
public UserDataService(IUnitOfWork unitOfWork)
: base(unitOfWork)
{ }
#region IDisposable Members
private bool _disposed;
protected override void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
}
this._disposed = true;
}
base.Dispose(disposing);
}
#endregion IDisposable Members
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Voting
{
class Voting
{
int candidates, voters;
ArrayList persons;
int[] results;
public Voting(int n, int m)
{
candidates = n;
voters = m;
persons = new ArrayList();
results = new int[candidates];
InitVoters();
}
void InitVoters()
{
for (int i = 0; i < voters; i++)
{
persons.Add(new Person(candidates));
}
}
public int PerformVoting()
{
for (int i = 0; i < voters; i++)
{
results[((Person)persons[i]).Vote()]++;
}
int mx = 0, mn = 0, imx = 0, imn = 0;
for (int i = 0; i < candidates; i++)
{
if (results[i] >= voters / 2) return i + 1;
if (results[i] > mx)
{
mn = mx;
imn = imx;
mx = results[i];
imx = i;
}
else if (results[i] > mn)
{
imn = i;
mn = results[i];
}
}
results[imx] = results[imn] = 0;
for (int i = 0; i < voters; i++)
{
results[((Person)persons[i]).SecondVote(imn, imx)]++;
}
return (results[imx] > results[imn]) ? imx + 1 : imn + 1;
}
}
}
|
using System.Threading.Tasks;
using TeamCityChangeNotifier.Http;
namespace TeamCityChangeNotifier.Tests
{
public class FakeTeamCityReader : ITeamCityReader
{
private string _value;
public FakeTeamCityReader(string value)
{
_value = value;
}
public Task<string> ReadBuildList(string buildName)
{
return Task.FromResult(_value);
}
public Task<string> ReadBuild(int buildId)
{
return Task.FromResult(_value);
}
public Task<string> ReadBuildChanges(int buildId)
{
return Task.FromResult(_value);
}
public Task<string> ReadChange(int changeId)
{
return Task.FromResult(_value);
}
public Task<string> ReadRelativeUrl(string relativeUrl)
{
return Task.FromResult(_value);
}
}
} |
using System;
namespace DEV_3
{
class FibonacciNumber
{
static void Main()
{
try
{
Console.WriteLine("Enter a number: ");
int numberToCheck = int.Parse(Console.ReadLine());
if (numberToCheck < 0)
{
Console.Write("It's a negative number. Try again: ");
Main();
}
else
{
bool result = false;
FibonacciNumber numbersFibonacci = new FibonacciNumber();
result = numbersFibonacci.CheckForFibonacciNumber(numberToCheck);
if (result || numberToCheck == 0)
{
Console.WriteLine("This number is Fibonacci number.");
Console.ReadKey();
}
else
{
Console.WriteLine("This number is not Fibonacci number.");
Console.ReadKey();
}
}
}
catch (FormatException ex)
{
Console.WriteLine("It's not a number!!\n");
Console.WriteLine("Error: " + ex.Message + "\n\n");
Main();
}
catch (OverflowException ex)
{
Console.WriteLine("Invalid value: Please enter a lower number!\n");
Console.WriteLine("Error: " + ex.Message + "\n\n");
Main();
}
}
internal bool CheckForFibonacciNumber(int numberToCheck)
{
int previos1 = 0;
int previos2 = 0;
int subsequent = 1;
bool verificationForFibonacci = false;
for (int i = 0; i <= numberToCheck; i++)
{
previos1 = previos2;
previos2 = subsequent;
subsequent = previos1 + previos2;
if (numberToCheck == subsequent)
{
verificationForFibonacci = true;
}
}
return verificationForFibonacci;
}
}
}
|
using System;
using System.Linq;
using EnduroCalculator;
using EnduroLibrary;
using EnduroTrackReader;
namespace EnduroCalculator
{
class Program
{
static void Main(string[] args)
{
TrackReader trackReader = new TrackReader(args[0]);
var points = trackReader.GetAllPoints();
Track track = new Track(points.ToList());
var calculatorService = new CalculatorService(track)
.AddCalculator(new DistanceCalculator())
.AddCalculator(new ElevationCalculator())
.AddCalculator(new SpeedCalculator())
.AddCalculator(new TimeCalculator())
.SetSlope(2)
.AddTimeFilter(7200)
.CalculateAll();
calculatorService.PrintAllCalculations();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Meshop.Framework.Model;
using Meshop.Framework.Services;
namespace Meshop.Core.Models
{
public class CartViewModel
{
public List<CartItem> CartItems { get; set; }
public decimal CartTotal { get; set; }
public ICheckout CheckoutService { get; set; }
}
public class CartRemoveViewModel
{
public string Message { get; set; }
public decimal CartTotal { get; set; }
public int CartCount { get; set; }
public int ItemCount { get; set; }
public int DeleteId { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace ServiceQuotes.Application.Helpers
{
public class NullableStringLength : ValidationAttribute
{
public NullableStringLength(int minValue, int maxValue, string errorMessage) : base(errorMessage) { }
public override bool IsValid(object value)
{
if (value is null)
{
return true;
}
if (value is not string)
{
return false;
}
string stringValue = value as string;
if (stringValue.Length < int.MinValue || stringValue.Length > int.MaxValue)
{
return false;
}
return true;
}
}
}
|
using UnityEngine;
using Project.UI;
namespace Project.Interactables
{
public class Pickable : Interactable
{
public string itemName;
public Animator anim;
private int triggerHash = Animator.StringToHash("PickedUp");
public override void Interact()
{
base.Interact();
Debug.Log("Pick " + name);
//Add Coin to inventort
Inventory.Instance.AddItem(itemName);
//player anim for destroy
if (anim != null)
{
anim.SetTrigger(triggerHash);
}
else
{
PickedUp();
}
}
public void PickedUp()
{
//destroy coin
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace com.Sconit.Entity.SI.MES
{
public class MaterialIORequest
{
public string request_id { get; set; }
public List<MES_Interface_MaterialIO> data { get; set; }
public string requester { get; set; }
public DateTime request_date { get; set; }
}
}
|
namespace Sentry.Extensibility;
/// <summary>
/// The size allowed when extracting a request body in a web application.
/// </summary>
public enum RequestSize
{
/// <summary>
/// No request payload is extracted
/// </summary>
/// <remarks>This is the default value. Opt-in is required.</remarks>
None,
/// <summary>
/// A small payload is extracted.
/// </summary>
Small,
/// <summary>
/// A medium payload is extracted.
/// </summary>
Medium,
/// <summary>
/// The SDK will always capture the request body. Sentry might truncate or reject the event if too large.
/// </summary>
Always
} |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using DbConnector.Core;
using DbConnector.Core.Extensions;
namespace DbConnector.Example.Providers
{
public abstract class EntityProvider<TDbConnection, T> : IEntityProvider<T>
where T : new()
where TDbConnection : DbConnection
{
protected static IDbConnector<TDbConnection> _dbConnector;
public EntityProvider(IDbConnector<TDbConnection> dbConnector)
{
_dbConnector = dbConnector;
}
public virtual Task<IDbResult<List<T>>> GetAll()
{
return _dbConnector.Read<T>(
onInit: (settings) =>
{
settings.CommandType = System.Data.CommandType.Text;
settings.CommandText = "Select * from " + typeof(T).GetAttributeValue((TableAttribute ta) => ta.Name) ?? typeof(T).Name;
}).ExecuteContainedAsync();
}
public virtual Task<IDbResult<T>> Get()
{
return _dbConnector.ReadSingle<T>(
onInit: (settings) =>
{
settings.CommandType = System.Data.CommandType.Text;
settings.CommandText = "Select * from "
+ typeof(T).GetAttributeValue((TableAttribute ta) => ta.Name) ?? typeof(T).Name
+ " fetch first 1 rows only";
}).ExecuteContainedAsync();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Entity))]
public class DummyHeadtracker : MonoBehaviour {
public Entity entity;
public GameObject head;
public GameObject forwardDirector;
Rigidbody headRigidbody;
Quaternion headInitialRotation;
public float headTurnAngleMax;
float headTurnStrength = 1f;
void Start () {
entity = GetComponent<Entity>();
headRigidbody = head.GetComponent<Rigidbody>();
headInitialRotation = head.transform.localRotation;
}
void Update () {
if (entity.focusedMonobehaviour != null && entity.vitals.stunCurrent < entity.vitals.stunThreshold) {
HeadTrack();
}
}
void HeadTrack() {
Vector3 focusPosition = Vector3.zero;
if (entity.focusedMonobehaviour is Entity) {
focusPosition = (entity.focusedMonobehaviour as Entity).head.transform.position;
} else if (entity.focusedMonobehaviour is Item) {
focusPosition = entity.focusedMonobehaviour.transform.position;
}
Vector3 headToTrackingDirection = (focusPosition - head.transform.position).normalized;
Quaternion rotationDesired = Quaternion.LookRotation(headToTrackingDirection, Vector3.up) * headInitialRotation;
float rotationDistance = Vector3.Angle(forwardDirector.transform.forward, headToTrackingDirection);
rotationDistance = Mathf.Abs((rotationDistance / 180) - 1);
headTurnStrength = Mathf.Lerp(headTurnStrength, rotationDistance, 5f * Time.deltaTime);
if (rotationDistance >= headTurnAngleMax) {
Quaternion rotationDeltaItem = rotationDesired * Quaternion.Inverse(head.transform.rotation);
float angleItem;
Vector3 axisItem;
rotationDeltaItem.ToAngleAxis(out angleItem, out axisItem);
if (angleItem > 180) {
angleItem -= 360;
}
if (angleItem != float.NaN) {
//headRigidbody.maxAngularVelocity = Mathf.Infinity;
headRigidbody.angularVelocity = Vector3.Lerp(headRigidbody.angularVelocity, (angleItem * axisItem) * headTurnStrength * 0.5f, Mathf.Clamp01(50 * Time.deltaTime));
}
}
}
}
|
namespace Tutorial.LinqToEntities
{
#if EF
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Spatial;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
internal static partial class Translation
{
internal static void WhereAndSelect(AdventureWorks adventureWorks)
{
// IQueryable<string> products = AdventureWorks.Products
// .Where(product => product.Name.Length > 10).Select(product => product.Name);
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<Product> whereQueryable = sourceQueryable.Where(product => product.Name.Length > 10);
IQueryable<string> selectQueryable = whereQueryable.Select(product => product.Name); // Define query.
selectQueryable.WriteLines(); // Execute query.
}
}
internal static partial class Translation
{
internal static void WhereAndSelectLinqExpressions(AdventureWorks adventureWorks)
{
IQueryable<Product> sourceQueryable = adventureWorks.Products; // DbSet<Product>.
// MethodCallExpression sourceMergeAsCallExpression = (MethodCallExpression)sourceQuery.Expression;
ObjectQuery<Product> objectQuery = new ObjectQuery<Product>(
$"[{nameof(AdventureWorks)}].[{nameof(AdventureWorks.Products)}]",
((IObjectContextAdapter)adventureWorks).ObjectContext,
MergeOption.AppendOnly);
MethodInfo mergeAsMethod = typeof(ObjectQuery<Product>).GetTypeInfo()
.GetDeclaredMethods("MergeAs").Single();
MethodCallExpression sourceMergeAsCallExpression = Expression.Call(
instance: Expression.Constant(objectQuery),
method: mergeAsMethod,
arguments: Expression.Constant(MergeOption.AppendOnly, typeof(MergeOption)));
sourceQueryable.Expression.WriteLine();
// value(System.Data.Entity.Core.Objects.ObjectQuery`1[Product])
// .MergeAs(AppendOnly)
IQueryProvider sourceQueryProvider = sourceQueryable.Provider; // DbQueryProvider.
// Expression<Func<Product, bool>> predicateExpression = product => product.Name.Length > 10;
ParameterExpression productParameterExpression = Expression.Parameter(typeof(Product), "product");
Expression<Func<Product, bool>> predicateExpression = Expression.Lambda<Func<Product, bool>>(
body: Expression.GreaterThan(
left: Expression.Property(
expression: Expression.Property(
expression: productParameterExpression, propertyName: nameof(Product.Name)),
propertyName: nameof(string.Length)),
right: Expression.Constant(10)),
parameters: productParameterExpression);
// IQueryable<Product> whereQueryable = sourceQueryable.Where(predicateExpression);
Func<IQueryable<Product>, Expression<Func<Product, bool>>, IQueryable<Product>> whereMethod =
Queryable.Where;
MethodCallExpression whereCallExpression = Expression.Call(
method: whereMethod.Method,
arg0: sourceMergeAsCallExpression,
arg1: Expression.Quote(predicateExpression));
IQueryable<Product> whereQueryable = sourceQueryProvider
.CreateQuery<Product>(whereCallExpression); // DbQuery<Product>.
object.ReferenceEquals(whereCallExpression, whereQueryable.Expression).WriteLine(); // True.
IQueryProvider whereQueryProvider = whereQueryable.Provider; // DbQueryProvider.
// Expression<Func<Product, string>> selectorExpression = product => product.Name;
Expression<Func<Product, string>> selectorExpression = Expression.Lambda<Func<Product, string>>(
Expression.Property(productParameterExpression, nameof(Product.Name)),
productParameterExpression);
selectorExpression.WriteLine();
// product => product.Name
// IQueryable<string> selectQueryable = whereQueryable.Select(selectorExpression);
Func<IQueryable<Product>, Expression<Func<Product, string>>, IQueryable<string>> selectMethod =
Queryable.Select;
MethodCallExpression selectCallExpression = Expression.Call(
method: selectMethod.Method,
arg0: whereCallExpression,
arg1: Expression.Quote(selectorExpression));
IQueryable<string> selectQueryable = whereQueryProvider
.CreateQuery<string>(selectCallExpression); // DbQuery<Product>.
selectQueryable.WriteLines(); // Execute query.
}
internal static void CompileWhereAndSelectExpressions(AdventureWorks adventureWorks)
{
Expression linqExpression = adventureWorks.Products
.Where(product => product.Name.Length > 10).Select(product => product.Name).Expression;
DbQueryCommandTree result = adventureWorks.Compile(linqExpression);
result.WriteLine();
}
internal static DbQueryCommandTree WhereAndSelectDatabaseExpressions(AdventureWorks adventureWorks)
{
MetadataWorkspace metadata = ((IObjectContextAdapter)adventureWorks).ObjectContext.MetadataWorkspace;
TypeUsage stringTypeUsage = TypeUsage.CreateDefaultTypeUsage(metadata
.GetPrimitiveTypes(DataSpace.CSpace)
.Single(type => type.ClrEquivalentType == typeof(string)));
TypeUsage nameRowTypeUsage = TypeUsage.CreateDefaultTypeUsage(RowType.Create(
EnumerableEx.Return(EdmProperty.Create(nameof(Product.Name), stringTypeUsage)),
Enumerable.Empty<MetadataProperty>()));
TypeUsage productTypeUsage = TypeUsage.CreateDefaultTypeUsage(metadata
.GetType(nameof(Product), "CodeFirstDatabaseSchema", DataSpace.SSpace));
EntitySet productEntitySet = metadata
.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace)
.GetEntitySetByName(nameof(Product), false);
DbProjectExpression query = DbExpressionBuilder.Project(
DbExpressionBuilder.BindAs(
DbExpressionBuilder.Filter(
DbExpressionBuilder.BindAs(
DbExpressionBuilder.Scan(productEntitySet), "Extent1"),
DbExpressionBuilder.GreaterThan(
DbExpressionBuilder.Invoke(
((IObjectContextAdapter)adventureWorks).ObjectContext.MetadataWorkspace
.GetFunctions("LEN", "SqlServer", DataSpace.SSpace).First(),
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(productTypeUsage, "Extent1"), nameof(Product.Name))),
DbExpressionBuilder.Constant(10))),
"Filter1"),
DbExpressionBuilder.New(
nameRowTypeUsage,
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(productTypeUsage, "Filter1"), nameof(Product.Name))));
DbQueryCommandTree result = new DbQueryCommandTree(metadata, DataSpace.SSpace, query);
return result.WriteLine();
}
internal static void SelectAndFirst(AdventureWorks adventureWorks)
{
// string first = AdventureWorks.Products.Select(product => product.Name).First();
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<string> selectQueryable = sourceQueryable.Select(product => product.Name);
string first = selectQueryable.First().WriteLine();
}
internal static void SelectAndFirstLinqExpressions(AdventureWorks adventureWorks)
{
IQueryable<Product> sourceQueryable = adventureWorks.Products;
sourceQueryable.Expression.WriteLine();
// value(System.Data.Entity.Core.Objects.ObjectQuery`1[Product])
// .MergeAs(AppendOnly)
IQueryable<string> selectQueryable = sourceQueryable.Select(product => product.Name);
selectQueryable.Expression.WriteLine();
// value(System.Data.Entity.Core.Objects.ObjectQuery`1[Product])
// .MergeAs(AppendOnly)
// .Select(product => product.Name)
MethodCallExpression selectCallExpression = (MethodCallExpression)selectQueryable.Expression;
IQueryProvider selectQueryProvider = selectQueryable.Provider; // DbQueryProvider.
// string first = selectQueryable.First();
Func<IQueryable<string>, string> firstMethod = Queryable.First;
MethodCallExpression firstCallExpression = Expression.Call(firstMethod.Method, selectCallExpression);
firstCallExpression.WriteLine();
// value(System.Data.Entity.Core.Objects.ObjectQuery`1[Product])
// .MergeAs(AppendOnly)
// .Select(product => product.Name)
// .First()
string first = selectQueryProvider.Execute<string>(firstCallExpression).WriteLine(); // Execute query.
}
internal static void CompileSelectAndFirstExpressions(AdventureWorks adventureWorks)
{
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<string> selectQueryable = sourceQueryable.Select(product => product.Name);
Func<IQueryable<string>, string> firstMethod = Queryable.First;
MethodCallExpression firstCallExpression = Expression.Call(firstMethod.Method, selectQueryable.Expression);
// IQueryable<string> firstQueryable = selectQueryable.Provider._internalQuery.ObjectQueryProvider
// .CreateQuery<string>(firstCallExpression);
// Above _internalQuery, ObjectQueryProvider and CreateQuery are not public. Reflection is needed:
Assembly entityFrameworkAssembly = typeof(DbContext).Assembly;
Type dbQueryProviderType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Internal.Linq.DbQueryProvider");
FieldInfo internalQueryField = dbQueryProviderType.GetField(
"_internalQuery", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);
Type internalQueryType = entityFrameworkAssembly.GetType("System.Data.Entity.Internal.Linq.IInternalQuery");
PropertyInfo objectQueryProviderProperty = internalQueryType.GetProperty("ObjectQueryProvider");
Type objectQueryProviderType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider");
MethodInfo createQueryMethod = objectQueryProviderType
.GetMethod(
"CreateQuery",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,
null,
new Type[] { typeof(Expression) },
null)
.MakeGenericMethod(typeof(string));
object internalQuery = internalQueryField.GetValue(selectQueryable.Provider);
object objectProvider = objectQueryProviderProperty.GetValue(internalQuery);
IQueryable<string> firstQueryable = (IQueryable<string>)createQueryMethod.Invoke(
objectProvider, new object[] { firstCallExpression });
Func<IEnumerable<string>, string> firstMappingMethod = Enumerable.First;
string first = firstMappingMethod(firstQueryable).WriteLine(); // Execute query.
}
internal static DbQueryCommandTree SelectAndFirstDatabaseExpressions(AdventureWorks adventureWorks)
{
MetadataWorkspace metadata = ((IObjectContextAdapter)adventureWorks).ObjectContext.MetadataWorkspace;
TypeUsage stringTypeUsage = TypeUsage.CreateDefaultTypeUsage(metadata
.GetPrimitiveTypes(DataSpace.CSpace)
.Single(type => type.ClrEquivalentType == typeof(string)));
TypeUsage nameRowTypeUsage = TypeUsage.CreateDefaultTypeUsage(RowType.Create(
EnumerableEx.Return(EdmProperty.Create(nameof(Product.Name), stringTypeUsage)),
Enumerable.Empty<MetadataProperty>()));
TypeUsage productTypeUsage = TypeUsage.CreateDefaultTypeUsage(metadata
.GetType(nameof(Product), "CodeFirstDatabaseSchema", DataSpace.SSpace));
EntitySet productEntitySet = metadata
.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace)
.GetEntitySetByName(nameof(Product), false);
DbProjectExpression query = DbExpressionBuilder.Project(
DbExpressionBuilder.BindAs(
DbExpressionBuilder.Limit(
DbExpressionBuilder.Scan(productEntitySet),
DbExpressionBuilder.Constant(1)),
"Limit1"),
DbExpressionBuilder.New(
nameRowTypeUsage,
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(productTypeUsage, "Limit1"), nameof(Product.Name))));
DbQueryCommandTree commandTree = new DbQueryCommandTree(metadata, DataSpace.SSpace, query);
return commandTree.WriteLine();
}
}
public static partial class DbContextExtensions
{
public static DbQueryCommandTree Compile(this IObjectContextAdapter context, Expression linqExpression)
{
ObjectContext objectContext = context.ObjectContext;
// DbExpression dbExpression = new ExpressionConverter(
// Funcletizer.CreateQueryFuncletizer(objectContext), expression).Convert();
// DbQueryCommandTree commandTree = objectContext.MetadataWorkspace.CreateQueryCommandTree(dbExpression);
// List<ProviderCommandInfo> providerCommands;
// PlanCompiler.Compile(
// commandTree, out providerCommands, out columnMap, out columnCount, out entitySets);
// return (DbQueryCommandTree)providerCommands.Single().CommandTree;
// ExpressionConverter, Funcletizer and PlanCompiler are not public. Reflection is needed:
Assembly entityFrameworkAssembly = typeof(DbContext).Assembly;
Type funcletizerType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Core.Objects.ELinq.Funcletizer");
MethodInfo createQueryFuncletizerMethod = funcletizerType.GetMethod(
"CreateQueryFuncletizer", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod);
Type expressionConverterType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Core.Objects.ELinq.ExpressionConverter");
ConstructorInfo expressionConverterConstructor = expressionConverterType.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { funcletizerType, typeof(Expression) },
null);
MethodInfo convertMethod = expressionConverterType.GetMethod(
"Convert", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod);
object funcletizer = createQueryFuncletizerMethod.Invoke(null, new object[] { objectContext });
object expressionConverter = expressionConverterConstructor.Invoke(
new object[] { funcletizer, linqExpression });
DbExpression dbExpression = (DbExpression)convertMethod.Invoke(expressionConverter, new object[0]);
DbQueryCommandTree commandTree = objectContext.MetadataWorkspace.CreateQueryCommandTree(dbExpression);
Type planCompilerType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler");
MethodInfo compileMethod = planCompilerType.GetMethod(
"Compile", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod);
object[] arguments = new object[] { commandTree, null, null, null, null };
compileMethod.Invoke(null, arguments);
Type providerCommandInfoType = entityFrameworkAssembly.GetType(
"System.Data.Entity.Core.Query.PlanCompiler.ProviderCommandInfo");
PropertyInfo commandTreeProperty = providerCommandInfoType.GetProperty(
"CommandTree", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty);
object providerCommand = ((IEnumerable<object>)arguments[1]).Single();
return (DbQueryCommandTree)commandTreeProperty.GetValue(providerCommand);
}
}
public static partial class DbContextExtensions
{
public static DbCommand Generate(this IObjectContextAdapter context, DbQueryCommandTree compilation)
{
MetadataWorkspace metadataWorkspace = context.ObjectContext.MetadataWorkspace;
StoreItemCollection itemCollection = (StoreItemCollection)metadataWorkspace
.GetItemCollection(DataSpace.SSpace);
DbCommandDefinition commandDefinition = SqlProviderServices.Instance
.CreateCommandDefinition(itemCollection.ProviderManifest, compilation);
return commandDefinition.CreateCommand();
// SqlVersion sqlVersion = ((SqlProviderManifest)itemCollection.ProviderManifest).SqlVersion;
// SqlGenerator sqlGenerator = new SqlGenerator(sqlVersion);
// string sql = sqlGenerator.GenerateSql(commandTree, HashSet<string> out paramsToForceNonUnicode)
}
}
public partial class LogProviderServices : DbProviderServices
{
private static readonly SqlProviderServices Sql = SqlProviderServices.Instance;
private static object RedirectCall(
Type[] argumentTypes, object[] arguments, [CallerMemberName] string methodName = null)
=> typeof(SqlProviderServices)
.GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
null,
argumentTypes,
null)
.Invoke(Sql, arguments);
private static object RedirectCall<T>(T arg, [CallerMemberName] string methodName = null)
=> RedirectCall(new Type[] { typeof(T) }, new object[] { arg }, methodName);
private static object RedirectCall<T1, T2>(T1 arg1, T2 arg2, [CallerMemberName] string methodName = null)
=> RedirectCall(new Type[] { typeof(T1), typeof(T2) }, new object[] { arg1, arg2 }, methodName);
private static object RedirectCall<T1, T2, T3>(
T1 arg1, T2 arg2, T3 arg3, [CallerMemberName] string methodName = null) => RedirectCall(
new Type[] { typeof(T1), typeof(T2), typeof(T3) }, new object[] { arg1, arg2, arg3 }, methodName);
}
public partial class LogProviderServices
{
protected override DbCommandDefinition CreateDbCommandDefinition(
DbProviderManifest providerManifest, DbCommandTree commandTree) =>
(DbCommandDefinition)RedirectCall(providerManifest, commandTree.WriteLine());
}
public partial class LogProviderServices
{
public override void RegisterInfoMessageHandler(DbConnection connection, Action<string> handler) =>
Sql.RegisterInfoMessageHandler(connection, handler);
protected override DbCommand CloneDbCommand(DbCommand fromDbCommand) =>
(DbCommand)RedirectCall(fromDbCommand);
protected override void SetDbParameterValue(DbParameter parameter, TypeUsage parameterType, object value) =>
RedirectCall(parameter, parameterType, value);
protected override string GetDbProviderManifestToken(DbConnection connection) =>
(string)RedirectCall(connection);
protected override DbProviderManifest GetDbProviderManifest(string manifestToken) =>
(DbProviderManifest)RedirectCall(manifestToken);
protected override DbSpatialDataReader GetDbSpatialDataReader(DbDataReader fromReader, string manifestToken) =>
(DbSpatialDataReader)RedirectCall<DbDataReader, string>(fromReader, manifestToken);
[Obsolete("Return DbSpatialServices from the GetService method. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.")]
protected override DbSpatialServices DbGetSpatialServices(string manifestToken) =>
(DbSpatialServices)RedirectCall(manifestToken);
protected override string DbCreateDatabaseScript(
string providerManifestToken, StoreItemCollection storeItemCollection) =>
(string)RedirectCall(providerManifestToken, storeItemCollection);
protected override void DbCreateDatabase(
DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) =>
RedirectCall(connection, commandTimeout, storeItemCollection);
protected override bool DbDatabaseExists(
DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) =>
(bool)RedirectCall(connection, commandTimeout, storeItemCollection);
protected override bool DbDatabaseExists(
DbConnection connection, int? commandTimeout, Lazy<StoreItemCollection> storeItemCollection) =>
(bool)RedirectCall(connection, commandTimeout, storeItemCollection);
protected override void DbDeleteDatabase(
DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) =>
RedirectCall(connection, commandTimeout, storeItemCollection);
}
#else
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Query.Sql;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Parsing.ExpressionVisitors.Transformation;
using Remotion.Linq.Parsing.ExpressionVisitors.TreeEvaluation;
using Remotion.Linq.Parsing.Structure;
using Remotion.Linq.Parsing.Structure.ExpressionTreeProcessors;
using Remotion.Linq.Parsing.Structure.NodeTypeProviders;
internal static partial class Translation
{
internal static void WhereAndSelect(AdventureWorks adventureWorks)
{
// IQueryable<string> products = adventureWorks.Products
// .Where(product => product.Name.Length > 10)
// .Select(product => product.Name);
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<Product> whereQueryable = sourceQueryable.Where(product => product.Name.Length > 10);
IQueryable<string> selectQueryable = whereQueryable.Select(product => product.Name); // Define query.
foreach (string result in selectQueryable) // Execute query.
{
result.WriteLine();
}
}
}
internal static partial class Translation
{
internal static void WhereAndSelectLinqExpressions(AdventureWorks adventureWorks)
{
IQueryable<Product> sourceQueryable = adventureWorks.Products; // DbSet<Product>.
ConstantExpression sourceConstantExpression = (ConstantExpression)sourceQueryable.Expression;
IQueryProvider sourceQueryProvider = sourceQueryable.Provider; // EntityQueryProvider/DbQueryProvider.
// Expression<Func<Product, bool>> predicateExpression = product => product.Name.Length > 10;
ParameterExpression productParameterExpression = Expression.Parameter(typeof(Product), "product");
Expression<Func<Product, bool>> predicateExpression = Expression.Lambda<Func<Product, bool>>(
body: Expression.GreaterThan(
left: Expression.Property(
expression: Expression.Property(
expression: productParameterExpression, propertyName: nameof(Product.Name)),
propertyName: nameof(string.Length)),
right: Expression.Constant(10)),
parameters: productParameterExpression);
// IQueryable<Product> whereQueryable = sourceQueryable.Where(predicateExpression);
Func<IQueryable<Product>, Expression<Func<Product, bool>>, IQueryable<Product>> whereMethod =
Queryable.Where;
MethodCallExpression whereCallExpression = Expression.Call(
method: whereMethod.GetMethodInfo(),
arg0: sourceConstantExpression,
arg1: Expression.Quote(predicateExpression));
IQueryable<Product> whereQueryable = sourceQueryProvider
.CreateQuery<Product>(whereCallExpression); // EntityQueryable<Product>/DbQuery<Product>.
IQueryProvider whereQueryProvider = whereQueryable.Provider; // EntityQueryProvider/DbQueryProvider.
// Expression<Func<Product, string>> selectorExpression = product => product.Name;
Expression<Func<Product, string>> selectorExpression = Expression.Lambda<Func<Product, string>>(
body: Expression.Property(productParameterExpression, nameof(Product.Name)),
parameters: productParameterExpression);
// IQueryable<string> selectQueryable = whereQueryable.Select(selectorExpression);
Func<IQueryable<Product>, Expression<Func<Product, string>>, IQueryable<string>> selectMethod =
Queryable.Select;
MethodCallExpression selectCallExpression = Expression.Call(
method: selectMethod.GetMethodInfo(),
arg0: whereCallExpression,
arg1: Expression.Quote(selectorExpression));
IQueryable<string> selectQueryable = whereQueryProvider
.CreateQuery<string>(selectCallExpression); // EntityQueryable<Product>/DbQuery<Product>.
using (IEnumerator<string> iterator = selectQueryable.GetEnumerator()) // Execute query.
{
while (iterator.MoveNext())
{
iterator.Current.WriteLine();
}
}
}
internal static SelectExpression WhereAndSelectDatabaseExpressions(AdventureWorks adventureWorks)
{
QueryCompilationContext compilationContext = adventureWorks.GetService<IQueryCompilationContextFactory>()
.Create(async: false);
SelectExpression databaseExpression = new SelectExpression(
dependencies: new SelectExpressionDependencies(adventureWorks.GetService<IQuerySqlGeneratorFactory>()),
queryCompilationContext: (RelationalQueryCompilationContext)compilationContext);
MainFromClause querySource = new MainFromClause(
itemName: "product",
itemType: typeof(Product),
fromExpression: Expression.Constant(adventureWorks.ProductCategories));
TableExpression tableExpression = new TableExpression(
table: nameof(Product),
schema: AdventureWorks.Production,
alias: querySource.ItemName,
querySource: querySource);
databaseExpression.AddTable(tableExpression);
IEntityType productEntityType = adventureWorks.Model.FindEntityType(typeof(Product));
IProperty nameProperty = productEntityType.FindProperty(nameof(Product.Name));
ColumnExpression nameColumn = new ColumnExpression(
name: nameof(Product.Name), property: nameProperty, tableExpression: tableExpression);
databaseExpression.AddToProjection(nameColumn);
databaseExpression.AddToPredicate(Expression.GreaterThan(
left: new ExplicitCastExpression(
operand: new SqlFunctionExpression(
functionName: "LEN",
returnType: typeof(int),
arguments: new Expression[] { nameColumn }),
type: typeof(int)),
right: Expression.Constant(10)));
return databaseExpression.WriteLine();
}
internal static void WhereAndSelectQuery(AdventureWorks adventureWorks)
{
IQueryable<string> products = adventureWorks.Products
.Where(product => product.Name.Length > 10)
.Select(product => product.Name);
// Equivalent to:
// IQueryable<string> products =
// from product in adventureWorks.Products
// where product.Name.Length > 10
// select product.Name;
}
internal static void CompileWhereAndSelectExpressions(AdventureWorks adventureWorks)
{
Expression linqExpression = adventureWorks.Products
.Where(product => product.Name.Length > 10)
.Select(product => product.Name).Expression;
(SelectExpression DatabaseExpression, IReadOnlyDictionary<string, object> Parameters) result =
adventureWorks.Compile(linqExpression);
result.DatabaseExpression.WriteLine();
result.Parameters.WriteLines(parameter => $"{parameter.Key}: {parameter.Value}");
}
internal static void SelectAndFirst(AdventureWorks adventureWorks)
{
// string first = adventureWorks.Products.Select(product => product.Name).First();
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<string> selectQueryable = sourceQueryable.Select(product => product.Name);
string first = selectQueryable.First().WriteLine(); // Execute query.
}
internal static void SelectAndFirstLinqExpressions(AdventureWorks adventureWorks)
{
IQueryable<Product> sourceQueryable = adventureWorks.Products;
IQueryable<string> selectQueryable = sourceQueryable.Select(product => product.Name);
MethodCallExpression selectCallExpression = (MethodCallExpression)selectQueryable.Expression;
IQueryProvider selectQueryProvider = selectQueryable.Provider; // DbQueryProvider.
// string first = selectQueryable.First();
Func<IQueryable<string>, string> firstMethod = Queryable.First;
MethodCallExpression firstCallExpression = Expression.Call(
method: firstMethod.GetMethodInfo(), arg0: selectCallExpression);
string first = selectQueryProvider.Execute<string>(firstCallExpression).WriteLine(); // Execute query.
}
internal static void CompileSelectAndFirstExpressions(AdventureWorks adventureWorks)
{
var selectQueryable = adventureWorks.Products
.Select(product => product.Name).Expression;
Func<IQueryable<string>, string> firstMethod = Queryable.First;
MethodCallExpression linqExpression = Expression.Call(
method: firstMethod.GetMethodInfo(), arg0: selectQueryable);
(SelectExpression DatabaseExpression, IReadOnlyDictionary<string, object> Parameters) compilation =
adventureWorks.Compile(linqExpression);
compilation.DatabaseExpression.WriteLine();
compilation.Parameters.WriteLines(parameter => $"{parameter.Key}: {parameter.Value}");
}
internal static void SelectAndFirstQuery(AdventureWorks adventureWorks)
{
string first = adventureWorks.Products.Select(product => product.Name).First();
// Equivalent to:
// string first = (from product in adventureWorks.Products select product.Name).First();
}
internal static SelectExpression SelectAndFirstDatabaseExpressions(AdventureWorks adventureWorks)
{
QueryCompilationContext compilationContext = adventureWorks.GetService<IQueryCompilationContextFactory>()
.Create(async: false);
SelectExpression selectExpression = new SelectExpression(
dependencies: new SelectExpressionDependencies(adventureWorks.GetService<IQuerySqlGeneratorFactory>()),
queryCompilationContext: (RelationalQueryCompilationContext)compilationContext);
MainFromClause querySource = new MainFromClause(
itemName: "product",
itemType: typeof(Product),
fromExpression: Expression.Constant(adventureWorks.ProductCategories));
TableExpression tableExpression = new TableExpression(
table: nameof(Product),
schema: AdventureWorks.Production,
alias: querySource.ItemName,
querySource: querySource);
selectExpression.AddTable(tableExpression);
IEntityType productEntityType = adventureWorks.Model.FindEntityType(typeof(Product));
IProperty nameProperty = productEntityType.FindProperty(nameof(Product.Name));
selectExpression.AddToProjection(new ColumnExpression(
name: nameof(Product.Name), property: nameProperty, tableExpression: tableExpression));
selectExpression.Limit = Expression.Constant(1);
return selectExpression.WriteLine();
}
}
public static partial class DbContextExtensions
{
public static (SelectExpression, IReadOnlyDictionary<string, object>) Compile(
this DbContext dbContext, Expression linqExpression)
{
QueryContext queryContext = dbContext.GetService<IQueryContextFactory>().Create();
IEvaluatableExpressionFilter evaluatableExpressionFilter = dbContext.GetService<IEvaluatableExpressionFilter>();
linqExpression = new ParameterExtractingExpressionVisitor(
evaluatableExpressionFilter: evaluatableExpressionFilter,
parameterValues: queryContext,
logger: dbContext.GetService<IDiagnosticsLogger<DbLoggerCategory.Query>>(),
parameterize: true).ExtractParameters(linqExpression);
QueryParser queryParser = new QueryParser(new ExpressionTreeParser(
nodeTypeProvider: dbContext.GetService<INodeTypeProviderFactory>().Create(),
processor: new CompoundExpressionTreeProcessor(new IExpressionTreeProcessor[]
{
new PartialEvaluatingExpressionTreeProcessor(evaluatableExpressionFilter),
new TransformingExpressionTreeProcessor(ExpressionTransformerRegistry.CreateDefault())
})));
QueryModel queryModel = queryParser.GetParsedQuery(linqExpression);
Type resultType = queryModel.GetResultType();
if (resultType.IsConstructedGenericType && resultType.GetGenericTypeDefinition() == typeof(IQueryable<>))
{
resultType = resultType.GenericTypeArguments.Single();
}
QueryCompilationContext compilationContext = dbContext.GetService<IQueryCompilationContextFactory>()
.Create(async: false);
RelationalQueryModelVisitor queryModelVisitor = (RelationalQueryModelVisitor)compilationContext
.CreateQueryModelVisitor();
queryModelVisitor.GetType()
.GetMethod(nameof(RelationalQueryModelVisitor.CreateQueryExecutor))
.MakeGenericMethod(resultType)
.Invoke(queryModelVisitor, new object[] { queryModel });
SelectExpression databaseExpression = queryModelVisitor.TryGetQuery(queryModel.MainFromClause);
databaseExpression.QuerySource = queryModel.MainFromClause;
return (databaseExpression, queryContext.ParameterValues);
}
}
public static partial class DbContextExtensions
{
public partial class ApiCompilationFilter : EvaluatableExpressionFilterBase
{
private static readonly PropertyInfo dateTimeUtcNow = typeof(DateTime)
.GetProperty(nameof(DateTime.UtcNow));
public override bool IsEvaluatableMember(MemberExpression memberExpression) =>
memberExpression.Member != dateTimeUtcNow;
}
}
public static partial class DbContextExtensions
{
public static IRelationalCommand Generate(
this DbContext dbContext,
SelectExpression databaseExpression,
IReadOnlyDictionary<string, object> parameters = null)
{
IQuerySqlGeneratorFactory sqlGeneratorFactory = dbContext.GetService<IQuerySqlGeneratorFactory>();
IQuerySqlGenerator sqlGenerator = sqlGeneratorFactory.CreateDefault(databaseExpression);
return sqlGenerator.GenerateSql(parameters ?? new Dictionary<string, object>());
}
public static IEnumerable<TResult> Materialize<TResult>(
this DbContext dbContext,
SelectExpression databaseExpression,
IRelationalCommand sql,
IReadOnlyDictionary<string, object> parameters = null)
{
Func<DbDataReader, TResult> materializer = dbContext.GetMaterializer<TResult>(databaseExpression, parameters);
using (RelationalDataReader reader = sql.ExecuteReader(
connection: dbContext.GetService<IRelationalConnection>(), parameterValues: parameters))
{
while (reader.DbDataReader.Read())
{
yield return materializer(reader.DbDataReader);
}
}
}
public static Func<DbDataReader, TResult> GetMaterializer<TResult>(
this DbContext dbContext,
SelectExpression databaseExpression,
IReadOnlyDictionary<string, object> parameters = null)
{
IMaterializerFactory materializerFactory = dbContext.GetService<IMaterializerFactory>();
Func<ValueBuffer, object> materializee = materializerFactory
.CreateMaterializer(
entityType: dbContext.Model.FindEntityType(typeof(TResult)),
selectExpression: databaseExpression,
projectionAdder: (property, expression) => expression.AddToProjection(
property, databaseExpression.QuerySource),
querySource: databaseExpression.QuerySource,
typeIndexMap: out _)
.Compile();
IQuerySqlGeneratorFactory sqlGeneratorFactory = dbContext.GetService<IQuerySqlGeneratorFactory>();
IQuerySqlGenerator sqlGenerator = sqlGeneratorFactory.CreateDefault(databaseExpression);
IRelationalValueBufferFactoryFactory valueBufferFactory = dbContext.GetService<IRelationalValueBufferFactoryFactory>();
return dbReader => (TResult)materializee(sqlGenerator.CreateValueBufferFactory(valueBufferFactory, dbReader).Create(dbReader));
}
public static IEnumerable<TEntity> MaterializeEntity<TEntity>(
this DbContext dbContext,
IRelationalCommand sql,
IReadOnlyDictionary<string, object> parameters = null)
where TEntity : class
{
return dbContext.Set<TEntity>().FromSql(
sql: sql.CommandText,
parameters: parameters.Select(parameter => new SqlParameter(parameter.Key, parameter.Value)).ToArray());
}
}
#endif
internal static partial class Translation
{
private static bool FilterName(string name) => name.Length > 10;
internal static void WhereAndSelectWithCustomPredicate(AdventureWorks adventureWorks)
{
IQueryable<Product> source = adventureWorks.Products;
IQueryable<string> products = source
.Where(product => FilterName(product.Name))
.Select(product => product.Name); // Define query.
products.WriteLines(); // Execute query.
#if EF
// NotSupportedException: LINQ to Entities does not recognize the method 'Boolean FilterName(System.String)' method, and this method cannot be translated into a store expression.
#else
// SELECT [product].[Name]
// FROM [Production].[Product] AS [product]
#endif
}
internal static void WhereAndSelectWithLocalPredicate(AdventureWorks adventureWorks)
{
IQueryable<Product> source = adventureWorks.Products;
IEnumerable<string> products = source
.Select(product => product.Name) // LINQ to Entities.
.AsEnumerable() // LINQ to Objects.
.Where(name => FilterName(name)); // Define query, IEnumerable<string> instead of IQueryable<string>.
products.WriteLines(); // Execute query.
}
#if EF
internal static void DbFunction(AdventureWorks adventureWorks)
{
var photos = adventureWorks.ProductPhotos.Select(photo => new
{
LargePhotoFileName = photo.LargePhotoFileName,
UnmodifiedDays = DbFunctions.DiffDays(photo.ModifiedDate, DateTime.UtcNow)
});
adventureWorks.Compile(photos.Expression).WriteLine();
photos.WriteLines();
// SELECT
// 1 AS [C1],
// [Extent1].[LargePhotoFileName] AS [LargePhotoFileName],
// DATEDIFF (day, [Extent1].[ModifiedDate], SysUtcDateTime()) AS [C2]
// FROM [Production].[ProductPhoto] AS [Extent1]
}
internal static void SqlFunction(AdventureWorks adventureWorks)
{
IQueryable<string> products = adventureWorks.Products
.Select(product => product.Name)
.Where(name => SqlFunctions.PatIndex(name, "%Touring%50%") > 0); // Define query.
products.WriteLines(); // Execute query.
// SELECT
// [Extent1].[Name] AS [Name]
// FROM [Production].[Product] AS [Extent1]
// WHERE ( CAST(PATINDEX([Extent1].[Name], N'%Touring%50%') AS int)) > 0
}
internal static void DbFunctionSql(AdventureWorks adventureWorks)
{
var photos = adventureWorks.ProductPhotos.Select(photo => new
{
LargePhotoFileName = photo.LargePhotoFileName,
UnmodifiedDays = DbFunctions.DiffDays(photo.ModifiedDate, DateTime.Now)
});
adventureWorks.Generate(adventureWorks.Compile(photos.Expression).WriteLine()).CommandText.WriteLine();
// SELECT
// 1 AS [C1],
// [Extent1].[LargePhotoFileName] AS [LargePhotoFileName],
// DATEDIFF (day, [Extent1].[ModifiedDate], SysDateTime()) AS [C2]
// FROM [Production].[ProductPhoto] AS [Extent1]
}
internal static void SqlFunctionSql(AdventureWorks adventureWorks)
{
IQueryable<string> products = adventureWorks.Products
.Select(product => product.Name)
.Where(name => SqlFunctions.PatIndex(name, "%o%a%") > 0);
adventureWorks.Generate(adventureWorks.Compile(products.Expression).WriteLine()).CommandText.WriteLine();
// SELECT
// [Extent1].[Name] AS [Name]
// FROM [Production].[Product] AS [Extent1]
// WHERE ( CAST(PATINDEX([Extent1].[Name], N'%o%a%') AS int)) > 0
}
#endif
#if EF
internal static void WhereAndSelectSql(AdventureWorks adventureWorks)
{
DbQueryCommandTree databaseExpressionAndParameters = WhereAndSelectDatabaseExpressions(adventureWorks);
DbCommand sql = adventureWorks.Generate(databaseExpressionAndParameters);
sql.CommandText.WriteLine();
// SELECT
// [Extent1].[Name] AS [Name]
// FROM [Production].[Product] AS [Extent1]
// WHERE [Extent1].[Name] LIKE N'M%'
}
internal static void SelectAndFirstSql(AdventureWorks adventureWorks)
{
DbQueryCommandTree databaseExpressionAndParameters = SelectAndFirstDatabaseExpressions(adventureWorks);
DbCommand sql = adventureWorks.Generate(databaseExpressionAndParameters);
sql.CommandText.WriteLine();
// SELECT TOP (1)
// [c].[Name] AS [Name]
// FROM [Production].[Product] AS [c]
}
#else
internal static void WhereAndSelectSql(AdventureWorks adventureWorks)
{
SelectExpression databaseExpression = WhereAndSelectDatabaseExpressions(adventureWorks);
IRelationalCommand sql = adventureWorks.Generate(databaseExpression: databaseExpression, parameters: null);
sql.CommandText.WriteLine();
// SELECT [product].[Name]
// FROM [Production].[ProductCategory] AS [product]
// WHERE CAST(LEN([product].[Name]) AS int) > 10
}
internal static void SelectAndFirstSql(AdventureWorks adventureWorks)
{
SelectExpression databaseExpression = SelectAndFirstDatabaseExpressions(adventureWorks);
IRelationalCommand sql = adventureWorks.Generate(databaseExpression: databaseExpression, parameters: null);
sql.CommandText.WriteLine();
// SELECT TOP(1) [product].[Name]
// FROM [Production].[Product] AS [product]
}
#endif
}
#if DEMO
public class LogConfiguration : DbConfiguration
{
public LogConfiguration()
{
this.SetProviderServices(SqlProviderServices.ProviderInvariantName, new LogProviderServices());
}
}
#endif
}
#if DEMO
namespace Microsoft.EntityFrameworkCore.Query.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Remotion.Linq.Clauses;
public class SelectExpression : TableExpressionBase
{
public virtual IReadOnlyList<Expression> Projection { get; } // SELECT.
public virtual bool IsDistinct { get; set; } // DISTINCT.
public virtual Expression Limit { get; set; } // TOP.
public virtual IReadOnlyList<TableExpressionBase> Tables { get; } // FROM.
public virtual Expression Predicate { get; set; } // WHERE.
public virtual IReadOnlyList<Ordering> OrderBy { get; } // ORDER BY.
public virtual Expression Offset { get; set; } // OFFSET.
public override Type Type { get; }
// Other members.
}
}
namespace Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.Internal
{
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
public class SqlServerStringLengthTranslator : IMemberTranslator
{
public virtual Expression Translate(MemberExpression memberExpression) =>
memberExpression.Expression != null
&& memberExpression.Expression.Type == typeof(string)
&& memberExpression.Member.Name == nameof(string.Length)
? new SqlFunctionExpression("LEN", memberExpression.Type, new Expression[] { memberExpression.Expression })
: null;
}
}
namespace Microsoft.EntityFrameworkCore.Query.Sql
{
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Storage;
public interface IQuerySqlGenerator
{
IRelationalCommand GenerateSql(IReadOnlyDictionary<string, object> parameterValues);
// Other members.
}
}
namespace Microsoft.EntityFrameworkCore.Storage
{
using System.Collections.Generic;
public interface IRelationalCommand
{
string CommandText { get; }
IReadOnlyList<IRelationalParameter> Parameters { get; }
RelationalDataReader ExecuteReader(
IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues);
// Other members.
}
}
namespace System.Data.Common
{
public abstract class DbCommand : Component, IDbCommand, IDisposable
{
public abstract string CommandText { get; set; }
public DbParameterCollection Parameters { get; }
public DbDataReader ExecuteReader();
// Other members.
}
}
namespace System.Linq
{
using System.Collections;
using System.Collections.Generic;
public interface IQueryable<out T> : IEnumerable<T>, IEnumerable, IQueryable
{
// Expression Expression { get; } from IQueryable.
// Type ElementType { get; } from IQueryable.
// IQueryProvider Provider { get; } from IQueryable.
// IEnumerator<T> GetEnumerator(); from IEnumerable<T>.
}
}
namespace System.Linq
{
using System.Linq.Expressions;
public interface IQueryProvider
{
IQueryable CreateQuery(Expression expression);
IQueryable<TElement> CreateQuery<TElement>(Expression expression);
object Execute(Expression expression);
TResult Execute<TResult>(Expression expression);
}
}
namespace System.Linq
{
using System.Linq.Expressions;
using System.Reflection;
public static class Queryable
{
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
Func<IQueryable<TSource>, Expression<Func<TSource, bool>>, IQueryable<TSource>> currentMethod =
Where;
MethodCallExpression whereCallExpression = Expression.Call(
method: currentMethod.GetMethodInfo(),
arg0: source.Expression,
arg1: Expression.Quote(predicate));
return source.Provider.CreateQuery<TSource>(whereCallExpression);
}
public static IQueryable<TResult> Select<TSource, TResult>(
this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)
{
Func<IQueryable<TSource>, Expression<Func<TSource, TResult>>, IQueryable<TResult>> currentMethod =
Select;
MethodCallExpression selectCallExpression = Expression.Call(
method: currentMethod.GetMethodInfo(),
arg0: source.Expression,
arg1: Expression.Quote(selector));
return source.Provider.CreateQuery<TResult>(selectCallExpression);
}
public static TSource First<TSource>(
this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
Func<IQueryable<TSource>, Expression<Func<TSource, bool>>, TSource> currentMethod = First;
MethodCallExpression firstCallExpression = Expression.Call(
method: currentMethod.GetMethodInfo(),
arg0: source.Expression,
arg1: Expression.Quote(predicate));
return source.Provider.Execute<TSource>(firstCallExpression);
}
public static TSource First<TSource>(this IQueryable<TSource> source)
{
Func<IQueryable<TSource>, TSource> currentMethod = First;
MethodCallExpression firstCallExpression = Expression.Call(
method: currentMethod.GetMethodInfo(),
arg0: source.Expression);
return source.Provider.Execute<TSource>(firstCallExpression);
}
// Other members.
}
}
namespace System.Data.Entity.Core.Common.CommandTrees
{
using System.Data.Entity.Core.Metadata.Edm;
public abstract class DbExpression
{
public virtual DbExpressionKind ExpressionKind { get; }
public virtual TypeUsage ResultType { get; }
// Other members.
}
public sealed class DbFilterExpression : DbExpression
{
public DbExpressionBinding Input { get; }
public DbExpression Predicate { get; }
// Other members.
}
public sealed class DbProjectExpression : DbExpression
{
public DbExpressionBinding Input { get; }
public DbExpression Projection { get; }
// Other members.
}
public sealed class DbLimitExpression : DbExpression
{
public DbExpression Argument { get; }
public DbExpression Limit { get; }
// Other members.
}
}
namespace System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder
{
using System.Data.Entity.Core.Metadata.Edm;
public static class DbExpressionBuilder
{
public static DbFilterExpression Filter(this DbExpressionBinding input, DbExpression predicate);
public static DbProjectExpression Project(this DbExpressionBinding input, DbExpression projection);
public static DbLimitExpression Limit(this DbExpression argument, DbExpression count);
public static DbScanExpression Scan(this EntitySetBase targetSet);
public static DbPropertyExpression Property(this DbExpression instance, string propertyName);
public static DbVariableReferenceExpression Variable(this TypeUsage type, string name);
public static DbConstantExpression Constant(object value);
// Other members.
}
}
namespace System.Data.Entity.Core.Common.CommandTrees
{
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
public abstract class DbCommandTree
{
public IEnumerable<KeyValuePair<string, TypeUsage>> Parameters { get; }
// Other members.
}
public sealed class DbQueryCommandTree : DbCommandTree
{
public DbExpression Query { get; }
// Other members.
}
}
namespace System.Data.Entity.Core.Common.CommandTrees
{
public abstract class DbExpressionVisitor<TResultType>
{
public abstract TResultType Visit(DbFilterExpression expression);
public abstract TResultType Visit(DbProjectExpression expression);
public abstract TResultType Visit(DbLimitExpression expression);
public abstract TResultType Visit(DbScanExpression expression);
public abstract TResultType Visit(DbPropertyExpression expression);
public abstract TResultType Visit(DbVariableReferenceExpression expression);
public abstract TResultType Visit(DbConstantExpression expression);
// Other members.
}
}
namespace System.Data.Entity.SqlServer.SqlGen
{
using System.Collections.Generic;
using System.Data.Entity.Core.Common.CommandTrees;
internal interface ISqlFragment { }
internal class SqlGenerator : DbExpressionVisitor<ISqlFragment>
{
internal string GenerateSql(DbQueryCommandTree tree, out HashSet<string> paramsToForceNonUnicode);
// Other members.
}
}
namespace System.Data.Entity.Core.Common
{
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Infrastructure.DependencyResolution;
public abstract class DbProviderServices : IDbDependencyResolver
{
protected abstract DbCommandDefinition CreateDbCommandDefinition(
DbProviderManifest providerManifest, DbCommandTree commandTree);
// Other members.
}
}
namespace System.Data.Entity.SqlServer
{
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Common.CommandTrees;
public sealed class SqlProviderServices : DbProviderServices
{
protected override DbCommandDefinition CreateDbCommandDefinition(
DbProviderManifest providerManifest, DbCommandTree commandTree);
// Other members.
}
}
#endif
|
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace test1_task4.Test
{
[TestClass]
public class PlayerTests
{
[TestMethod]
public void FireWithCorrctCoordinate()
{
//Assert.IsTrue(new Player().Fire(new Coordinate('A', 2), new List<Coordinate>().Add(new Coordinate('A',2))));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace Looxid.Link
{
public enum Tab3DVisualizer
{
MIND_INDEX = 0,
FEATURE_INDEX = 1,
RAW_SIGNAL = 2
}
public enum FeatureIndexEnum
{
DELTA = 0,
THETA = 1,
ALPHA = 2,
BETA = 3,
GAMMA = 4
}
public class _3DVisualizer : MonoBehaviour
{
[Header("Tabs")]
public Tab3DVisualizer SelectTab;
public GameObject MindIndexTab;
public GameObject FeatureIndexTab;
public GameObject RawSignalTab;
[Header("Canvas")]
public GameObject MindIndexCanvas;
public GameObject FeatureIndexCanvas;
public GameObject RawSignalCanvas;
[Header("Sensor")]
public GameObject SensorCanvas;
[Header("Panels")]
public GameObject[] FeatureIndexPanels;
public GameObject[] RawSignalPanels;
[Header("Effect")]
public BrainEffect LeftEffect;
public BrainEffect[] LeftLineEffect;
public BrainEffect RightEffect;
public BrainEffect[] RightLineEffect;
[Header("Mind Index")]
public BarChart AttentionChart;
public BarChart RelaxationChart;
public BarChart LeftActivityChart;
public BarChart RightActivityChart;
[Header("Feature index")]
public FeatureIndexEnum SelectFeature;
public Text SelectFeatureText;
public BarChart FeatureAF3Chart;
public BarChart FeatureAF4Chart;
public BarChart FeatureFp1Chart;
public BarChart FeatureFp2Chart;
public BarChart FeatureAF7Chart;
public BarChart FeatureAF8Chart;
[Header("Raw Signal")]
public LineChart RawAF3Chart;
public LineChart RawAF4Chart;
public LineChart RawFp1Chart;
public LineChart RawFp2Chart;
public LineChart RawAF7Chart;
public LineChart RawAF8Chart;
void Start()
{
OnMindIndexTabClick();
LooxidLinkManager.Instance.SetDebug(true);
LooxidLinkManager.Instance.Initialize();
}
void OnEnable()
{
StartCoroutine(RecieveData());
}
public void OnMindIndexTabClick()
{
this.SelectTab = Tab3DVisualizer.MIND_INDEX;
}
public void OnFeatureIndexTabClick()
{
this.SelectTab = Tab3DVisualizer.FEATURE_INDEX;
}
public void OnRawSignalTabClick()
{
this.SelectTab = Tab3DVisualizer.RAW_SIGNAL;
}
IEnumerator RecieveData()
{
while (this.gameObject.activeSelf)
{
if (SelectTab == Tab3DVisualizer.MIND_INDEX)
{
List<MindIndex> mindIndex = LooxidLinkData.GetMindIndexData(4.0f);
List<double> attentionDataList = new List<double>();
List<double> relaxationDataList = new List<double>();
List<double> leftActivityDataList = new List<double>();
List<double> rightActivityDataList = new List<double>();
for (int i = 0; i < mindIndex.Count; i++)
{
attentionDataList.Add(LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, mindIndex[i].attention));
relaxationDataList.Add(LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, mindIndex[i].relaxation));
leftActivityDataList.Add(LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, mindIndex[i].leftActivity));
rightActivityDataList.Add(LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, mindIndex[i].rightActivity));
}
AttentionChart.SetValue(attentionDataList);
RelaxationChart.SetValue(relaxationDataList);
LeftActivityChart.SetValue(leftActivityDataList);
RightActivityChart.SetValue(rightActivityDataList);
}
else if (SelectTab == Tab3DVisualizer.FEATURE_INDEX)
{
FeatureAF3Chart.SetValue(GetFeatureDataList(EEGSensorID.AF3));
FeatureAF4Chart.SetValue(GetFeatureDataList(EEGSensorID.AF4));
FeatureFp1Chart.SetValue(GetFeatureDataList(EEGSensorID.Fp1));
FeatureFp2Chart.SetValue(GetFeatureDataList(EEGSensorID.Fp2));
FeatureAF7Chart.SetValue(GetFeatureDataList(EEGSensorID.AF7));
FeatureAF8Chart.SetValue(GetFeatureDataList(EEGSensorID.AF8));
}
else if (SelectTab == Tab3DVisualizer.RAW_SIGNAL)
{
EEGRawSignal AF3Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.AF3);
RawAF3Chart.SetValue(AF3Sensor.filteredRawSignal);
EEGRawSignal AF4Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.AF4);
RawAF4Chart.SetValue(AF4Sensor.filteredRawSignal);
EEGRawSignal Fp1Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.Fp1);
RawFp1Chart.SetValue(Fp1Sensor.filteredRawSignal);
EEGRawSignal Fp2Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.Fp2);
RawFp2Chart.SetValue(Fp2Sensor.filteredRawSignal);
EEGRawSignal AF7Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.AF7);
RawAF7Chart.SetValue(AF7Sensor.filteredRawSignal);
EEGRawSignal AF8Sensor = LooxidLinkData.GetEEGRawSignalData(EEGSensorID.AF8);
RawAF8Chart.SetValue(AF8Sensor.filteredRawSignal);
}
/*float left = LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, (float)LooxidLinkData.GetEEGFeatureData().left_activity);
float right = LooxidLinkUtility.Scale(LooxidLink.MIND_INDEX_SCALE_MIN, LooxidLink.MIND_INDEX_SCALE_MAX, 0.0f, 1.0f, (float)LooxidLinkData.GetEEGFeatureData().right_activity);
LeftEffect.alphaValue = 100 + (left * 200);
for (int i = 0; i < LeftLineEffect.Length; i++)
{
LeftLineEffect[i].alphaValue = 10 + (left * 20);
}
RightEffect.alphaValue = 100 + (right * 200);
for (int i = 0; i < LeftLineEffect.Length; i++)
{
RightLineEffect[i].alphaValue = 10 + (right * 20);
}*/
yield return new WaitForSeconds(0.1f);
}
}
private List<double> GetFeatureDataList(EEGSensorID sensorID)
{
List<EEGFeatureIndex> featureScaleList = LooxidLinkData.GetEEGFeatureIndexData(sensorID, 10.0f);
List<double> ScaleDataList = new List<double>();
if (featureScaleList.Count > 0)
{
for (int i = 0; i < featureScaleList.Count; i++)
{
if (SelectFeature == FeatureIndexEnum.DELTA) ScaleDataList.Add(featureScaleList[i].delta);
if (SelectFeature == FeatureIndexEnum.THETA) ScaleDataList.Add(featureScaleList[i].theta);
if (SelectFeature == FeatureIndexEnum.ALPHA) ScaleDataList.Add(featureScaleList[i].alpha);
if (SelectFeature == FeatureIndexEnum.BETA) ScaleDataList.Add(featureScaleList[i].beta);
if (SelectFeature == FeatureIndexEnum.GAMMA) ScaleDataList.Add(featureScaleList[i].gamma);
}
}
List<EEGFeatureIndex> featureDataList = LooxidLinkData.GetEEGFeatureIndexData(sensorID, 4.0f);
List<double> dataList = new List<double>();
if (featureDataList.Count > 0)
{
//double delta = LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[0].delta);
//Debug.Log(ScaleDataList.Min() + " - ( " + featureDataList[0].delta + " > " + delta + " ) - " + ScaleDataList.Max());
for (int i = 0; i < featureDataList.Count; i++)
{
if (SelectFeature == FeatureIndexEnum.DELTA) dataList.Add(LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[i].delta));
if (SelectFeature == FeatureIndexEnum.THETA) dataList.Add(LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[i].theta));
if (SelectFeature == FeatureIndexEnum.ALPHA) dataList.Add(LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[i].alpha));
if (SelectFeature == FeatureIndexEnum.BETA) dataList.Add(LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[i].beta));
if (SelectFeature == FeatureIndexEnum.GAMMA) dataList.Add(LooxidLinkUtility.Scale(ScaleDataList.Min(), ScaleDataList.Max(), 0.0f, 1.0f, featureDataList[i].gamma));
}
}
return dataList;
}
void FixedUpdate()
{
if (MindIndexTab != null) MindIndexTab.SetActive(SelectTab == Tab3DVisualizer.MIND_INDEX);
if (FeatureIndexTab != null) FeatureIndexTab.SetActive(SelectTab == Tab3DVisualizer.FEATURE_INDEX);
if (RawSignalTab != null) RawSignalTab.SetActive(SelectTab == Tab3DVisualizer.RAW_SIGNAL);
if (MindIndexCanvas != null) MindIndexCanvas.SetActive(SelectTab == Tab3DVisualizer.MIND_INDEX);
if (FeatureIndexCanvas != null) FeatureIndexCanvas.SetActive(SelectTab == Tab3DVisualizer.FEATURE_INDEX);
if (RawSignalCanvas != null) RawSignalCanvas.SetActive(SelectTab == Tab3DVisualizer.RAW_SIGNAL);
if (SensorCanvas != null) SensorCanvas.SetActive(SelectTab != Tab3DVisualizer.MIND_INDEX);
}
public void OnAllSensorOnButton()
{
if (SelectTab == Tab3DVisualizer.FEATURE_INDEX)
{
for (int i = 0; i < FeatureIndexPanels.Length; i++)
{
FeatureIndexPanels[i].SetActive(true);
}
}
if (SelectTab == Tab3DVisualizer.RAW_SIGNAL)
{
for (int i = 0; i < RawSignalPanels.Length; i++)
{
RawSignalPanels[i].SetActive(true);
}
}
}
public void OnAllSensorOffButton()
{
if (SelectTab == Tab3DVisualizer.FEATURE_INDEX)
{
for (int i = 0; i < FeatureIndexPanels.Length; i++)
{
FeatureIndexPanels[i].SetActive(false);
}
}
if (SelectTab == Tab3DVisualizer.RAW_SIGNAL)
{
for (int i = 0; i < RawSignalPanels.Length; i++)
{
RawSignalPanels[i].SetActive(false);
}
}
}
public void OnSensorButton(int num)
{
if (SelectTab == Tab3DVisualizer.FEATURE_INDEX)
{
FeatureIndexPanels[num].SetActive(!FeatureIndexPanels[num].activeSelf);
}
if (SelectTab == Tab3DVisualizer.RAW_SIGNAL)
{
RawSignalPanels[num].SetActive(!RawSignalPanels[num].activeSelf);
}
}
public void OnFeatureIndexDeltaButton()
{
SelectFeature = FeatureIndexEnum.DELTA;
SelectFeatureText.text = ("Delta (1~3Hz)");
}
public void OnFeatureIndexThetaButton()
{
SelectFeature = FeatureIndexEnum.THETA;
SelectFeatureText.text = ("Theta(4~7Hz)");
}
public void OnFeatureIndexAlphaButton()
{
SelectFeature = FeatureIndexEnum.ALPHA;
SelectFeatureText.text = ("Alpha (8~12Hz)");
}
public void OnFeatureIndexBetaButton()
{
SelectFeature = FeatureIndexEnum.BETA;
SelectFeatureText.text = ("Beta (13~30Hz)");
}
public void OnFeatureIndexGammaButton()
{
SelectFeature = FeatureIndexEnum.GAMMA;
SelectFeatureText.text = ("Gamma (31~45Hz)");
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestForm
{
public partial class Form2 : Form
{
Point loc;
Point nowLoc;
Rectangle rectangle;
public Form2()
{
InitializeComponent();
loc = new Point();
nowLoc = new Point();
}
public void Form2_MouseMove(object sender, MouseEventArgs e)
{
//Debug.WriteLine("({0},{1})", e.X, e.Y);
loc.X =nowLoc.X+ 24 - Convert.ToInt32((double)e.X / 15.0f);
loc.Y = nowLoc.Y + 14 - Convert.ToInt32((double)e.Y / 14.5f);
this.Location = loc;
System.Drawing.Drawing2D.GraphicsPath shape = new System.Drawing.Drawing2D.GraphicsPath();
rectangle = new Rectangle(-loc.X+ nowLoc.X+24, -loc.Y+ nowLoc.Y+14, 720, 404);
Debug.WriteLine("({0},{1})", loc.X, loc.Y);
shape.AddRectangle(rectangle);
this.Region = new Region(shape);
}
private void Form2_Load(object sender, EventArgs e)
{
nowLoc = this.Location;
int x = Location.X;
int y = Location.Y;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Fingo.Auth.DbAccess.Models.Statuses;
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Infrastructure.ExtensionMethods;
using Fingo.Auth.Domain.Models.UserModels;
using Fingo.Auth.Domain.Users.Interfaces;
namespace Fingo.Auth.Domain.Users.Implementation
{
public class GetAllNotAssignedUsersToProject : IGetAllNotAssignedUsersToProject
{
private readonly IUserRepository repo;
public GetAllNotAssignedUsersToProject(IUserRepository repo)
{
this.repo = repo;
}
public IEnumerable<BaseUserModel> Invoke(int projectId)
{
var users = repo.GetAll().WithoutStatuses(UserStatus.Deleted);
var model = users.Where(user => user.ProjectUsers.All(m => m.ProjectId != projectId));
var result = model.Select(user => new BaseUserModel(user));
return result;
}
}
} |
using System;
namespace Alabo.Cache {
public interface ICacheContext : IDisposable {
object Instance { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MvvmCross.Core.ViewModels;
namespace ResidentAppCross.ViewModels
{
public class ImageBundleViewModel : MvxNotifyPropertyChanged
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
RaisePropertyChanged();
}
}
public ObservableCollection<ImageBundleItemViewModel> RawImages { get; set; } = new ObservableCollection<ImageBundleItemViewModel>();
public IEnumerable<string> ImagesAsBase64 => from image in RawImages where image.Data != null select Convert.ToBase64String(image.Data);
}
public class ImageBundleItemViewModel
{
public Uri Uri { get; set; }
public byte[] Data { get; set; }
}
}
|
using Galeri.Entities.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galeri.DataAccess.Abstract
{
public interface IEntityRepository<TEntity> where TEntity:class,IEntity,new()
{
void Add(TEntity entity);
void Update(TEntity entity);
void Delete(TEntity entity);
}
}
|
using Alabo.Domains.Repositories;
using Alabo.Framework.Basic.Address.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Framework.Basic.Regions.Domain.Repositories {
public interface IUserAddressRepository : IRepository<UserAddress, ObjectId> {
}
} |
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Runtime.InteropServices;
namespace UseFul.Uteis
{
public static class Arquivos
{
public static int GetQuantidadePaginasPDF(string caminhoPDF)
{
PdfReader pdfReader = new PdfReader(caminhoPDF);
int qtdPaginas = pdfReader.NumberOfPages;
pdfReader.Dispose();
return qtdPaginas;
}
public static void UnificarPDFs(string[] fileNames, string outFile)
{
int pageOffset = 0;
int f = 0;
Document document = null;
PdfCopy writer = null;
while (f < fileNames.Length)
{
// we create a reader for a certain document
PdfReader reader = new PdfReader(fileNames[f]);
reader.ConsolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.NumberOfPages;
pageOffset += n;
if (f == 0)
{
// step 1: creation of a document-object
document = new Document(reader.GetPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
// step 3: we open the document
document.Open();
}
// step 4: we add content
for (int i = 0; i < n; )
{
++i;
if (writer != null)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
writer.AddPage(page);
page = null;
}
}
f++;
reader.Dispose();
}
// step 5: we close the document
document.Dispose();
writer.Dispose();
document = null;
writer = null;
GC.Collect();
}
public static byte[] CarregarArquivo(string caminho)
{
long tamanhoDocumento = 0;
byte[] docEmBytes = null;
FileInfo documento = new FileInfo(caminho);
tamanhoDocumento = documento.Length;
docEmBytes = new byte[Convert.ToInt32(tamanhoDocumento)];
FileStream fs = new FileStream(caminho, FileMode.Open, FileAccess.Read, FileShare.Read);
fs.Read(docEmBytes, 0, Convert.ToInt32(tamanhoDocumento));
fs.Close();
fs.Dispose();
return docEmBytes;
}
public static void AbrirArquivo(string caminho)
{
if (caminho != "")
{
try
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = true;
proc.StartInfo.FileName = caminho;
proc.Start();
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("Diretório não encontrado !");
}
catch (FileNotFoundException)
{
MessageBox.Show("Arquivo não encontrado !");
}
catch (System.IO.IOException)
{
MessageBox.Show("Arquivo não esta disponível. Pode estar em uso.");
}
catch (Exception ex)
{
MessageBox.Show("Houve um problema ao abrir o arquivo :" + ex.Message.ToString());
}
}
else
{
MessageBox.Show("Informe a localização do arquivo!");
}
}
public static void GerarArquivo(byte[] arquivo, string caminho)
{
FileStream fs = new FileStream(caminho, FileMode.Create, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write(arquivo);
fs.Close();
fs.Dispose();
}
public static void ConverterWordParaPDF(string caminhoOrigemArquivoWord, string caminhoDestinoArquivoPdf)
{
// Abrir Aplicacao Word
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
// Arquivo de Origem
object _caminhoArquivoDoc = caminhoOrigemArquivoWord;
object _caminhoArquivoPdf = caminhoDestinoArquivoPdf;
object missing = System.Type.Missing;
// Abrir documento
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref _caminhoArquivoDoc, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
// Formato para Salvar o Arquivo – Destino - No caso, PDF
object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
// Salvar Arquivo
doc.SaveAs(ref _caminhoArquivoPdf, ref formatoArquivo, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// Não salvar alterações no arquivo original
object salvarAlteracoesArqOriginal = false;
wordApp.Quit(ref salvarAlteracoesArqOriginal, ref missing, ref missing);
}
public static byte[] AddPageNumbers(byte[] pdf)
{
MemoryStream ms = new MemoryStream();
ms.Write(pdf, 0, pdf.Length);
// we create a reader for a certain document
PdfReader reader = new PdfReader(pdf);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// we retrieve the size of the first page
Rectangle psize = reader.GetPageSize(1);
// step 1: creation of a document-object
Document document = new Document(psize, 50, 50, 50, 50);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3: we open the document
document.Open();
// step 4: we add content
PdfContentByte cb = writer.DirectContent;
int p = 0;
//Console.WriteLine("There are " + n + " pages in the document.");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
document.NewPage();
p++;
PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
cb.AddTemplate(importedPage, 0, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Página " + p + " de " + n, 50, 44, 0);
cb.EndText();
}
// step 5: we close the document
document.Close();
return ms.ToArray();
}
[DllImport("shell32.dll", EntryPoint = "ShellExecute")]
public static extern int ExecutarShell(int hwnd, string lpOperacao,
string lpArquivo, string lpParametros, string lpDiretorio, int lpMostraCmd);
}
}
|
// CrowdSimulator - Crowd.cs
//
// Copyright (c) 2012, Dominik Gander
// Copyright (c) 2012, Pascal Minder
//
// Permission to use, copy, modify, and distribute this software for any
// purpose without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
using System;
using System.Collections.Generic;
using System.Drawing;
using CrowdSimulator.Human_Factories;
namespace CrowdSimulator
{
public class Crowd
{
private readonly List<Human> humans;
private readonly Field field;
private readonly Bitmap bitmap;
private static int width;
private static int height;
private int frameCount;
private readonly Graphics graphics;
private static readonly Random Rnd = new Random(DateTime.Now.Millisecond);
public Crowd(Bitmap Bitmap)
{
this.bitmap = Bitmap;
this.humans = new List<Human>();
this.field = new Field(Bitmap.Width, Bitmap.Height);
height = Bitmap.Height;
width = Bitmap.Width;
this.graphics = Graphics.FromImage(bitmap);
}
public void Init(int Humans, int Assassins)
{
var agentFactory = new AgentFactory();
var humanFactory = new HumanFactory();
for (int i = 0; i < Humans; i++)
{
humans.Add(humanFactory.CreateHuman());
}
for (int i = 0; i < Assassins; i++)
{
humans.Add(agentFactory.CreateHuman(humans));
}
field.Update(this.humans);
}
public void Update()
{
frameCount++;
foreach (var h in humans)
{
h.Update(this.GetNearestNeighbour(h));
}
if (frameCount >= 10)
{
field.Update(this.humans);
frameCount = 0;
}
this.Draw();
}
private void Draw()
{
graphics.Clear(Color.White);
foreach (var h in humans)
{
if (h.HumanType == HumanType.Normal)
{
graphics.FillEllipse(Brushes.Black, h.Position.X - 2, h.Position.Y - 2, 4, 4);
}
else if (h.HumanType == HumanType.Agent)
{
graphics.FillEllipse(Brushes.Red, h.Position.X - 2, h.Position.Y - 2, 4, 4);
}
else if (h.HumanType==HumanType.Dead)
{
graphics.FillEllipse(Brushes.GreenYellow, h.Position.X - 2, h.Position.Y - 2, 4, 4);
}
else if (h.HumanType == HumanType.Victim)
{
graphics.FillRectangle(Brushes.DeepSkyBlue, h.Position.X - 2, h.Position.Y - 2, 4, 4);
}
}
}
private List<Human> GetNearestNeighbour(Human LeMe)
{
return field.GetNearestNeighbour(LeMe.FieldIndex, LeMe.Position);
}
public static Vec2 GetRandomPosition()
{
return new Vec2(Rnd.Next(0, width), Rnd.Next(0, height));
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Linq;
using TripLog.Models;
using TripLog.Persistency;
using TripLog.Server.Controllers;
namespace TripLog.Server
{
[TestClass]
public class TripLogControllerTests
{
private readonly Mock<ILogger<TripLogController>> loggerMock;
private readonly Mock<ITripLogPersistency> persistencyMock;
private readonly TripLogController testee;
public TripLogControllerTests()
{
loggerMock = new Mock<ILogger<TripLogController>>();
persistencyMock = new Mock<ITripLogPersistency>();
testee = new TripLogController(loggerMock.Object, persistencyMock.Object);
}
[TestMethod]
public void Get_ReturnsOkResult()
{
// Arrange
persistencyMock.Setup(m => m.Retrieve()).Returns(Enumerable.Empty<TripLogEntry>);
// Act
var okResult = testee.Get();
// Assert
Assert.IsInstanceOfType(okResult.Result, typeof(OkObjectResult));
}
[TestMethod]
public void Get_PersistencyFails_ReturnsInternalError()
{
// Arrange
persistencyMock.Setup(m => m.Retrieve()).Throws(new Exception());
// Act
var internalErrorResult = testee.Get();
// Assert
Assert.AreEqual(500, ((ObjectResult)internalErrorResult.Result).StatusCode);
}
[TestMethod]
public void Post_ReturnsOkResult()
{
// Arrange
var expectedEntry = new TripLogEntry() { Title = "Title" };
// Act
var createdAtActionResult = testee.Post(expectedEntry);
// Assert
Assert.IsInstanceOfType(createdAtActionResult.Result, typeof(CreatedAtActionResult));
}
[TestMethod]
public void Post_PersistencyFails_ReturnsInternalError()
{
// Arrange
var expectedEntry = new TripLogEntry() { Title = "Title" };
persistencyMock.Setup(m => m.Store(expectedEntry)).Throws(new Exception());
// Act
var internalErrorResult = testee.Post(expectedEntry);
// Assert
Assert.AreEqual(500, ((ObjectResult)internalErrorResult.Result).StatusCode);
}
[TestMethod]
public void Delete_EntryMissing_ReturnsNotFoundObjectResult()
{
// Arrange
var expectedEntry = new TripLogEntry() { Title = "Title" };
persistencyMock.Setup(m => m.Delete(expectedEntry)).Returns(false);
// Act
var notFoundObjectResult = testee.Delete(expectedEntry);
// Assert
Assert.IsInstanceOfType(notFoundObjectResult, typeof(NotFoundObjectResult));
}
[TestMethod]
public void Delete_EntryPresent_ReturnsOkObjectResult()
{
// Arrange
var expectedEntry = new TripLogEntry() { Title = "Title" };
persistencyMock.Setup(m => m.Delete(expectedEntry)).Returns(true);
// Act
var okResult = testee.Delete(expectedEntry);
// Assert
Assert.IsInstanceOfType(okResult, typeof(OkObjectResult));
Assert.AreEqual(expectedEntry, ((OkObjectResult)okResult).Value);
}
[TestMethod]
public void Delete_PersistencyFails_ReturnsInternalError()
{
// Arrange
var expectedEntry = new TripLogEntry() { Title = "Title" };
persistencyMock.Setup(m => m.Delete(expectedEntry)).Throws(new Exception());
// Act
var internalErrorResult = testee.Delete(expectedEntry);
// Assert
Assert.AreEqual(500, ((ObjectResult)internalErrorResult).StatusCode);
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Sprites;
namespace SpritePackerOverview
{
public class SpritePackerOverviewTreeModel
{
public class AtlasInfo
{
public Texture texture;
public string size;
public string format;
}
private string[] m_AtlasNames;
private List<List<AtlasInfo>> m_AtlasInfos = new List<List<AtlasInfo>>();
public void Reload()
{
RefreshAtlasNameList();
}
public bool IsEmpty()
{
return m_AtlasNames == null || m_AtlasNames.Length == 0;
}
public string[] GetAtlasNames()
{
return m_AtlasNames;
}
public int GetAtlasPagesCount(int atlasIndex)
{
if (atlasIndex >= m_AtlasInfos.Count)
{
return 0;
}
return m_AtlasInfos[atlasIndex].Count;
}
public AtlasInfo GetAtlasPagesInfo(int atlasIndex, int pageIndex)
{
return m_AtlasInfos[atlasIndex][pageIndex];
}
private void RefreshAtlasNameList()
{
m_AtlasNames = Packer.atlasNames;
m_AtlasInfos.Clear();
for (var i = 0; i < m_AtlasNames.Length; i++)
{
var atlasName = m_AtlasNames[i];
List<AtlasInfo> infos = new List<AtlasInfo>();
Texture2D[] textures = Packer.GetTexturesForAtlas(atlasName);
foreach (var texture in textures)
{
AtlasInfo info = new AtlasInfo
{
texture = texture,
format = texture.format.ToString(),
size = string.Format("{0}x{1}", texture.width, texture.height)
};
infos.Add(info);
}
m_AtlasInfos.Add(infos);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AppointmentManagement.UI.Entity.CustomEntity
{
public class CustomAppointment
{
public int Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string OrderAsnNumber { get; set; }
public string Color { get; set; }
public string Description { get; set; }
public string VendorDescription { get; set; }
public string VehicleDesc { get; set; }
public int VehicleTypeId { get; set; }
public Guid OrderAsnHeaderId { get; set; }
public string UserId { get; set; }
public string VendorCode { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace FSDP.DATA.EF.Repositories
{
public interface IGenericRepository<TEntity> : IDisposable where TEntity : class
{
List<TEntity> Get(string includeProperties = "");
TEntity Find(object id);
void Add(TEntity entity);
void Update(TEntity entity);
void Remove(TEntity entity);
void Remove(object id);
int CountRecords();
}
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
// Commented out because DbContext will be passed in from
// the UnitOfWork
//private cStoreEntities db = new cStoreEntities();
// receiving the DbContext passed from the UnitOfWork
internal DbContext db;
//constructor
public GenericRepository(DbContext context)
{
this.db = context;
}
public List<TEntity> Get(string includeProperties = "")
{
IQueryable<TEntity> query = db.Set<TEntity>();
foreach (var prop in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(prop);
}
return query.ToList();
}
public TEntity Find(object id)
{
return db.Set<TEntity>().Find(id);
}
public void Add(TEntity entity)
{
db.Set<TEntity>().Add(entity);
db.SaveChanges();
}
public void Update(TEntity entity)
{
db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
public void Remove(TEntity entity)
{
db.Set<TEntity>().Remove(entity);
db.SaveChanges();
}
public void Remove(object id)
{
var entity = Find(id);
Remove(entity);
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public int CountRecords()
{
return Get().Count;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using Leprechaun.Logging;
namespace Leprechaun.Configuration
{
/// <summary>
/// Resolves imported config files' paths.
/// This amounts to an efficient glob implementation, which somehow seems to not exist for C#
/// </summary>
public class ConfigurationImportPathResolver
{
private readonly ILogger _logger;
public ConfigurationImportPathResolver(ILogger logger)
{
_logger = logger;
}
public virtual string[] ResolveImportPaths(string inputPath)
{
// normalize input path
inputPath = inputPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar).Trim();
// check for wildcards
if (inputPath.IndexOf('*') < 0)
{
// non-wildcard path is taken literally (e.g. ../foo.config or c:\foo.config)
if(!File.Exists(inputPath)) return new string[0];
return new[] { inputPath };
}
// for wildcard parsing we have to get fancier
var wildcardIndex = inputPath.IndexOf('*');
// get the highest non-wildcard path segment; we'll iterate for the filter under there
string rootDir = inputPath.Substring(0, wildcardIndex);
// handle partial wildcards e.g. Dir*
if (!rootDir.EndsWith($"{Path.DirectorySeparatorChar}"))
{
rootDir = rootDir.Substring(0, rootDir.LastIndexOf(Path.DirectorySeparatorChar));
}
var wildcardSegments = new Queue<string>(inputPath.Substring(wildcardIndex).Split(Path.DirectorySeparatorChar));
var pathCandidates = new Queue<string>();
pathCandidates.Enqueue(rootDir);
// process all wildcard segments except the last (these would be directories)
// e.g. /foo/*/ba*/r.config or /foo/*/*.config
while (wildcardSegments.Count > 1)
{
var currentSegment = wildcardSegments.Dequeue();
var newPathCandidates = new Queue<string>();
while (pathCandidates.Count > 0)
{
var currentPathCandidate = pathCandidates.Dequeue();
string[] directories;
if ("**".Equals(currentSegment, StringComparison.Ordinal))
{
// recursive inclusion
directories = Directory.GetDirectories(currentPathCandidate, "*", SearchOption.AllDirectories);
}
else
{
// normal filter inclusion
directories = Directory.GetDirectories(currentPathCandidate, currentSegment, SearchOption.TopDirectoryOnly);
}
foreach (var directory in directories) newPathCandidates.Enqueue(directory);
}
// replace existing candidates with new candidates that are lower down a wildcard element
pathCandidates = newPathCandidates;
}
var results = new List<string>();
var finalSegment = wildcardSegments.Dequeue();
// finally we have a queue with the last segment in it - in this case, we want to evaluate against files, not directories
while (pathCandidates.Count > 0)
{
var currentPathCandidate = pathCandidates.Dequeue();
if (!Directory.Exists(currentPathCandidate))
{
_logger.Warn($"The import path {currentPathCandidate} did not exist, and will be skipped!");
continue;
}
var currentPathFiles = Directory.GetFiles(currentPathCandidate, finalSegment, SearchOption.TopDirectoryOnly);
results.AddRange(currentPathFiles);
}
return results.ToArray();
}
}
}
|
using HowLeaky.ModelControllers;
using HowLeaky.SyncModels;
using HowLeaky.Tools;
using System;
using System.Collections.Generic;
using System.Xml;
namespace HowLeaky.Models
{
public enum ManagementEvent { mePlanting, meHarvest, meTillage, mePesticide, meIrrigation, meCropGrowing, meInPlantingWindow, meMeetsSoilWaterPlantCritera, meMeetsDaysSinceHarvestPlantCritera, meMeetsRainfallPlantCritera, meNone };
public class Simulation : CustomSyncModel
{
//public static int MISSING_DATA_VALUE = -32768;
public static int ROBINSON_CN = 0;
public static int PERFECT_CN = 1;
public static int DEFAULT_CN = 2;
public bool RunSilent { get; set; }
public bool canlog { get; set; }
public bool Use2008CurveNoFn { get; set; }
public bool Force2011CurveNoFn { get; set; }
//--------------------------------------------------------------------------
// Submodel Controller
//--------------------------------------------------------------------------
public IrrigationController IrrigationController { get; set; }
public VegetationController VegetationController { get; set; }
public TillageController TillageController { get; set; }
public PesticideController PesticideController { get; set; }
public PhosphorusController PhosphorusController { get; set; }
public NitrateController NitrateController { get; set; }
public SolutesController SolutesController { get; set; }
public ModelOptionsController ModelOptionsController { get; set; }
public ClimateController ClimateController { get; set; }
//public int LayerCount { get {return }
public double Latitude { get { return ClimateController.Latitude; } }
public double Longitude { get { return ClimateController.Longitude; } }
//--------------------------------------------------------------------------
// Input Parameters
//--------------------------------------------------------------------------
public int in_LayerCount { get; set; } // Number of soil layers used to define soil thicknesses ("Layer Depth (Cumulative)") and the soil hydraulic properties defined by "Air dry moisture", "Wilting point", "Field capacity", "Saturated water content" and "Maximum drainage from layer").
public List<double> in_Depths { get; set; } // Depth to the bottom of each soil layer defined by "Number of Horizons". The properties of each layer are defined by "Air dry moisture", "Wilting point", "Field capacity", "Saturated water content" and "Maximum drainage from layer".
public List<double> in_SoilLimitAirDry_pc { get; set; } // This is the moisture content when the soil is air-dry (40o C). It is usually much less than the lower limit of plant-available moisture. A value is needed for each soil layer defined by "Number of Horizons" and "Layer Depth (Cumulative)". However, values in deeper soil layers have no effect because evaporation only occurs in the top 10 to 30 cm of soil.
public List<double> in_SoilLimitWiltingPoint_pc { get; set; } // Wilting point is the lower limit of soil moisture content for plant water use (the moisture content at which plants permanently wilted). A value is needed for each soil layer defined by "Number of Horizons" and "Layer Depth (Cumulative)".
public List<double> in_SoilLimitFieldCapacity_pc { get; set; } // Field capacity (or drained upper limit) is the water content in the soil after free water drains. A value is needed for each soil layer defined by "Number of Horizons" and "Layer Depth (Cumulative)
public List<double> in_SoilLimitSaturation_pc { get; set; } // Saturated water content (SAT) is the soil moisture content of the soil layer when saturated. It is equal to total porosity (which can be calculated from bulk density) except where a small amount of air is entrapped in the soil (eg 0.0 � 0.05 v/v). A value is needed for each soil layer defined by "Number of Horizons" and "Layer Depth (Cumulative)".
public List<double> in_LayerDrainageLimit_mm_per_day { get; set; } // Controls the maximum rate of drainage downwards from each soil layer ("Layer Depth (Cumulative)") when it is saturated and the deep drainage below the deepest soil layer. Drainage is also influenced by drainable porosity ("Saturated water content" minus "Field capacity").
public List<double> in_BulkDensity_g_per_cm3 { get; set; } //
public double in_Cona_mm_per_sqrroot_day { get; set; } //
public double in_Stage1SoilEvapLimitU_mm { get; set; } //
public double in_RunoffCurveNumber { get; set; } // The runoff Curve Number (CN) partitions rainfall into runoff and infiltration, using a modification of the USDA method that relates CN to soil moisture content each day (Williams and La Seur 1976, Williams et al. 1985), rather than to antecedent rainfall. In PERFECT and HOWLEAKY, this is modified further to adjust CN for cover and for soil surface roughness caused by tillage (optional). The input parameter is the CN for bare soil at average antecedent moisture content (CN2bare).
public double in_CurveNumberReduction { get; set; } // Reduction in runoff Curve Number (CN2) below CN2bare (�Runoff curve number (bare soil)�) at 100% cover. Used to calculate the effect of cover on runoff.
public double in_MaxRedInCNDueToTill { get; set; } // Reduction in runoff Curve Number (CN2bare) when a tillage operation occurs (optional). Used to model effects of soil surface roughness, cause by tillage, on runoff (if selected) in conjunction with �Rainfall to 0 roughness�, based on Littleboy et al. (1996a).
public double in_RainToRemoveRoughness_mm { get; set; } //
public double in_USLE_K { get; set; } // USLE K factor is the soil erodibility factor (K) of the Universal Soil Loss Equation (USLE, Renard et al 1993). It defines the inherent susceptibility of a soil to erosion per unit of rainfall erosivity, and is defined for set cover and crop condition (bare soil, permanent fallow, C = 1), slope and length of slope (LS factor = 1) and practice factor (P=1).
public double in_USLE_P { get; set; } // USLE P factor is the practice factor (P) of the Universal Soil Loss Equation (USLE, Renard et al 1993). It defines effects of conservation practices other than those related to cover and cropping/soil water use practices. A value of 1.0 indicates no such practices and is considered the norm.
public double in_FieldSlope_pc { get; set; } //
public double in_SlopeLength_m { get; set; } // Slope length is the distance down the slope, used to calculate the USLE slope-length factor (LS) using the algorithm from the Revised USLE (Renard et al. 1993). It is converted from metres to feet in order to apply the RUSLE equations [Need this??]. It has no effect on other processes.
public double in_RillRatio { get; set; } //
public bool in_SoilCrackingSwitch { get; set; } // A value of YES turns on the option for some rainfall (defined by \"Max crack infilt.\") to infiltrate below soil layer 2 directly via cracks. Infiltration via crack will only occur when daily rainfall is greater than 10 mm and soil moisture content in the upper two soil layers is less than 30% of field capacity. Cracks extend down through all layers where soil moisture is less than 30% of field capacity. Infiltration occurs into the lowest �cracked� layer first and any layer can only fill to 50% of field capacity. This option is affected by the number and thickness of layers used.
public double in_MaxInfiltIntoCracks_mm { get; set; } //
public double in_SedDelivRatio { get; set; } //
//--------------------------------------------------------------------------
// Timeseries Inputs
//--------------------------------------------------------------------------
public List<double> MaxTemp { get; set; } //
public List<double> MinTemp { get; set; } //
public List<double> Rainfall { get; set; } //
public List<double> Evaporation { get; set; } //
public List<double> SolarRadiation { get; set; } //
//--------------------------------------------------------------------------
// Daily Outputs
//--------------------------------------------------------------------------
public double out_Rain_mm { get; set; } // Daily rainfall amount (mm) as read directly from the P51 file.
public double out_MaxTemp_oC { get; set; } // Daily max temperature (oC) as read directly from the P51 file.
public double out_MinTemp_oC { get; set; } // Daily min temperature (oC) as read directly from the P51 file.
public double out_PanEvap_mm { get; set; } // Daily pan evaporation (mm) as read directly from the P51 file.
public double out_SolarRad_MJ_per_m2_per_day { get; set; } // Daily solar radition (mMJ/m^2/day) as read directly from the P51 file.
//Water balance outputs
public double out_WatBal_Irrigation_mm { get; set; } // Irrigation amount (mm) as calcaulted in irrigation module.
public double out_WatBal_Runoff_mm { get; set; } // Total Runoff amount (mm) - includes runoff from rainfall AND irrigation.
public double out_WatBal_RunoffFromIrrigation_mm { get; set; } // Runoff amount from irrigation (mm).
public double out_WatBal_RunoffFromRainfall_mm { get; set; } // Runoff amount from rainfall (mm).
public double out_WatBal_SoilEvap_mm { get; set; } // Soil evaporation (mm).
public double out_WatBal_PotSoilEvap_mm { get; set; } // Potential soil evaporation (mm).
public double out_WatBal_Transpiration_mm { get; set; } // Transpiration (mm) calculated from current crop.
public double out_WatBal_EvapoTransp_mm { get; set; } // Evapo-transpiration (mm) is equal to the transpiration PLUS soil evaporation.
public double out_WatBal_DeepDrainage_mm { get; set; } // Deep drainage (mm) which is the amount of drainge out of the bottom layer.
public double out_WatBal_Overflow_mm { get; set; } // Overflow (mm) ADD DEF HERE
public double out_WatBal_LateralFlow_mm { get; set; } // Lateral flow (mm) ADD DEF HERE
public double out_WatBal_VBE_mm { get; set; } // Volume Balance Error
public double out_WatBal_RunoffCurveNo { get; set; } // Runoff curve number
public double out_WatBal_RunoffRetentionNo { get; set; } // Runoff retention number
//Soil outputs
public double out_Soil_HillSlopeErosion_t_per_ha { get; set; } // Hillslope errorsion (t/ha)
public double out_Soil_OffSiteSedDelivery_t_per_ha { get; set; } // Offsite sediment deliver (t/ha)
public double out_Soil_TotalSoilWater_mm { get; set; } // Total soil water (mm) is the sum of soil water in all layers
public double out_Soil_SoilWaterDeficit_mm { get; set; } // Soil water deficit (mm)
public double out_Soil_Layer1SatIndex { get; set; } // Layer 1 saturation index
public double out_Soil_TotalCropResidue_kg_per_ha { get; set; } // Total crop residue (kg/ha) - sum of all crops present
public double out_Soil_TotalResidueCover_pc { get; set; } // Total residue cover (%) - based on all crops present
public double out_Soil_TotalCover_pc { get; set; } // Total cover (%) - based on all crops present{get;set;}
public List<double> out_Soil_SoilWater_mm { get; set; } // Soil water in each layer (mm)
public List<double> out_Soil_Drainage_mm { get; set; } // Drainage in each layer
//--------------------------------------------------------------------------
// Monthly Outputs
//--------------------------------------------------------------------------
public List<double> mo_MthlyAvgRainfall_mm { get; set; } //
public List<double> mo_MthlyAvgEvaporation_mm { get; set; } //
public List<double> mo_MthlyAvgTranspiration_mm { get; set; } //
public List<double> mo_MthlyAvgRunoff_mm { get; set; } //
public List<double> mo_MthlyAvgDrainage_mm { get; set; } //
//--------------------------------------------------------------------------
// Summary Outputs
//--------------------------------------------------------------------------
public double so_YrlyAvgRainfall_mm_per_yr { get; set; } //
public double so_YrlyAvgIrrigation_mm_per_yr { get; set; } //
public double so_YrlyAvgRunoff_mm_per_yr { get; set; } //
public double so_YrlyAvgSoilEvaporation_mm_per_yr { get; set; } //
public double so_YrlyAvgTranspiration_mm_per_yr { get; set; } //
public double so_YrlyAvgEvapotransp_mm_per_yr { get; set; } //
public double so_YrlyAvgOverflow_mm_per_yr { get; set; } //
public double so_YrlyAvgDrainage_mm_per_yr { get; set; } //
public double so_YrlyAvgLateralFlow_mm_per_yr { get; set; } //
public double so_YrlyAvgSoilErosion_T_per_ha_per_yr { get; set; } //
public double so_YrlyAvgOffsiteSedDel_T_per_ha_per_yr { get; set; }//
public double so_TotalCropsPlanted { get; set; } //
public double so_TotalCropsHarvested { get; set; } //
public double so_TotalCropsKilled { get; set; } //
public double so_AvgYieldPerHrvst_t_per_ha_per_hrvst { get; set; } //
public double so_AvgYieldPerPlant_t_per_ha_per_plant { get; set; } //
public double so_AvgYieldPerYr_t_per_ha_per_yr { get; set; } //
public double so_YrlyAvgCropRainfall_mm_per_yr { get; set; } //
public double so_YrlyAvgCropIrrigation_mm_per_yr { get; set; } //
public double so_YrlyAvgCropRunoff_mm_per_yr { get; set; } //
public double so_YrlyAvgCropSoilEvap_mm_per_yr { get; set; } //
public double so_YrlyAvgCropTransp_mm_per_yr { get; set; } //
public double so_YrlyAvgCropEvapotransp_mm_per_yr { get; set; } //
public double so_YrlyAvgCropOverflow_mm_per_yr { get; set; } //
public double so_YrlyAvgCropDrainage_mm_per_yr { get; set; } //
public double so_YrlyAvgCropLateralFlow_mm_per_yr { get; set; } //
public double so_YrlyAvgCropSoilErosion_T_per_ha_per_yr { get; set; }//
public double so_YrlyAvgCropOffsiteSedDel_T_per_ha_per_yr { get; set; }//
public double so_YrlyAvgFallowRainfall_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowIrrigation_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowRunoff_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowSoilEvap_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowTransp_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowEvapotransp_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowOverflow_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowDrainage_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowLateralFlow_mm_per_yr { get; set; } //
public double so_YrlyAvgFallowSoilErosion_T_per_ha_per_yr { get; set; }//
public double so_YrlyAvgFallowOffsiteSedDel_T_per_ha_per_yr { get; set; }//
public double so_YrlyAvgPotEvap_mm { get; set; } //
public double so_YrlyAvgRunoffAsPercentOfInflow_pc { get; set; } //
public double so_YrlyAvgEvapAsPercentOfInflow_pc { get; set; } //
public double so_YrlyAvgTranspAsPercentOfInflow_pc { get; set; } //
public double so_YrlyAvgDrainageAsPercentOfInflow_pc { get; set; } //
public double so_YrlyAvgPotEvapAsPercentOfInflow_pc { get; set; } //
public double so_YrlyAvgCropSedDel_t_per_ha_per_yr { get; set; } //
public double so_YrlyAvgFallowSedDel_t_per_ha_per_yr { get; set; } //
public double so_RobinsonErrosionIndex { get; set; } //
public double so_YrlyAvgCover_pc { get; set; } //
public double so_YrlyAvgFallowDaysWithMore50pcCov_days { get; set; }//
public double so_AvgCoverBeforePlanting_pc { get; set; } //
public double so_SedimentEMCBeoreDR { get; set; } //
public double so_SedimentEMCAfterDR { get; set; } //
public double so_AvgSedConcInRunoff { get; set; } //
//--------------------------------------------------------------------------
// intermediate variables
//--------------------------------------------------------------------------
bool FReset { get; set; }
public bool NeedToUpdateOutput { get; set; }
public bool InRunoff { get; set; }
public bool InRunoff2 { get; set; }
public DateTime startdate { get; set; }
public DateTime today { get; set; }
public int seriesindex { get; set; }
public int climateindex { get; set; }
public int day { get; set; }
public int month { get; set; }
public int year { get; set; }
public int number_of_days_in_simulation { get; set; }
public int RunoffEventCount2 { get; set; }
public double previous_total_soil_water { get; set; }
public double yesterdays_rain { get; set; }
public double temperature { get; set; }
public double total_cover { get; set; }
public double total_cover_percent { get; set; }
public double total_crop_residue { get; set; }
public double total_residue_cover { get; set; }
public double total_residue_cover_percent { get; set; }
public double effective_rain { get; set; }
public double total_soil_water { get; set; }
public double crop_cover { get; set; }
public double runoff { get; set; }
public double sediment_conc { get; set; }
public double erosion_t_per_ha { get; set; }
public double offsite_sed_delivery { get; set; }
public double cumSedConc { get; set; }
public double peakSedConc { get; set; }
public double swd { get; set; }
public double satd { get; set; }
public double sse1 { get; set; }
public double sse2 { get; set; }
public double se1 { get; set; }
public double se2 { get; set; }
public double se21 { get; set; }
public double se22 { get; set; }
public double dsr { get; set; }
public double sed_catchmod { get; set; }
public double saturationindex { get; set; }
public double cn2 { get; set; }
public double overflow_mm { get; set; }
public double rain_since_tillage { get; set; }
public double infiltration { get; set; }
public double lateral_flow { get; set; }
public double potential_soil_evaporation { get; set; }
public double drainage { get; set; }
public double runoff_retention_number { get; set; }
public double usle_ls_factor { get; set; }
public double PredRh { get; set; }
public double accumulated_cover { get; set; }
public double sum_rainfall { get; set; }
public double sum_irrigation { get; set; }
public double sum_runoff { get; set; }
public double sum_potevap { get; set; }
public double sum_soilevaporation { get; set; }
public double sum_transpiration { get; set; }
public double sum_evapotranspiration { get; set; }
public double sum_overflow { get; set; }
public double sum_drainage { get; set; }
public double sum_lateralflow { get; set; }
public double sum_soilerosion { get; set; }
public double sum_crop_rainfall { get; set; }
public double sum_crop_irrigation { get; set; }
public double sum_crop_runoff { get; set; }
public double sum_crop_soilevaporation { get; set; }
public double sum_crop_transpiration { get; set; }
public double sum_crop_evapotranspiration { get; set; }
public double sum_crop_overflow { get; set; }
public double sum_crop_drainage { get; set; }
public double sum_crop_lateralflow { get; set; }
public double sum_crop_soilerosion { get; set; }
public double sum_fallow_rainfall { get; set; }
public double sum_fallow_irrigation { get; set; }
public double sum_fallow_overflow { get; set; }
public double sum_fallow_lateralflow { get; set; }
public double sum_fallow_runoff { get; set; }
public double sum_fallow_soilevaporation { get; set; }
public double sum_fallow_drainage { get; set; }
public double sum_fallow_soilerosion { get; set; }
public double fallow_efficiency { get; set; }
public double sum_fallow_soilwater { get; set; }
public double accumulate_cov_day_before_planting { get; set; }
public double fallow_days_with_more_50pc_cov { get; set; }
public double total_number_plantings { get; set; }
public double accumulated_crop_sed_deliv { get; set; }
public double accumulated_fallow_sed_deliv { get; set; }
public List<double> mcfc { get; set; }
public List<double> SoilWater_rel_wp { get; set; }
public List<double> DrainUpperLimit_rel_wp { get; set; }
public List<double> depth { get; set; }
public List<double> layer_transpiration { get; set; }
public List<double> red { get; set; }
public List<double> wf { get; set; }
public List<double> SaturationLimit_rel_wp { get; set; }
public List<double> Wilting_Point_RelOD_mm { get; set; }
public List<double> DUL_RelOD_mm { get; set; }
public List<double> AirDryLimit_rel_wp { get; set; }
public List<double> ksat { get; set; }
public List<double> swcon { get; set; }
public List<double> Seepage { get; set; }
public List<double> MaxDrainage { get; set; }
public string ControlError { get; set; }
public ManagementEvent FManagementEvent { get; set; }
//ProgramManager FProgramManager;
public List<string> ErrorList { get; set; } = new List<string>();
public List<string> ZerosList { get; set; } = new List<string>();
//--------------------------------------------------------------------------
//Progress housekeeping
//--------------------------------------------------------------------------
public int Progress { get; set; }
public int FProgress { get; set; }
public int FSimProgress { get; set; }
public int FLastProgress { get; set; }
public int FLastSimProgress { get; set; }
/// <summary>
///
/// </summary>
public Simulation()
{
// FProgramManager = manager;
ErrorList = new List<string>();
ZerosList = new List<string>();
canlog = false;
//FOnUpdateOutput = 0;
//FOnFinishSimulating = 0;
//CurrentSimulationObject = 0;
//FSimulationObjectsList = 0;
RunSilent = false;
Force2011CurveNoFn = false;
// InputDefinitions=0;//manager.PerfectInputModule();
IrrigationController = new IrrigationController(this);
VegetationController = new VegetationController(this);
TillageController = new TillageController(this);
PesticideController = new PesticideController(this);
PhosphorusController = new PhosphorusController(this);
NitrateController = new NitrateController(this);
SolutesController = new SolutesController(this);
ModelOptionsController = new ModelOptionsController(this);
}
/// <summary>
///
/// </summary>
public void Start()
{
// if(Suspended)
// Resume();
}
/// <summary>
///
/// </summary>
public void Reset()
{
FReset = true;
}
/// <summary>
///
/// </summary>
public void Execute()
{
try
{
}
catch (Exception e)
{
throw (new Exception("An error has occurred in the execution thread of the simulation.", new Exception(e.Message)));
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool Simulate()
{
// try
// {
// canlog=false;
//
//
// if(!RunSilent)Synchronize(UpdateStartMessages);
// FLastProgress=-1;
// int simcount=SimulationObjectsList.Count;
// SmartPointer<TList>ActiveSimList(new TList);
// for(int i=0;i<simcount;++i)
// {
// TScenarioInputObject*sim=(TScenarioInputObject*)SimulationObjectsList.Items[i];
// if(sim.NeedsToBeSimulated)
// ActiveSimList.Add(sim);
// }
// int activesimcount=ActiveSimList.Count;
// if(!FReset&&activesimcount>0)
// {
// for(int i=0;i<activesimcount;++i)
// {
// if(LoadSimulationObject((TScenarioInputObject*)ActiveSimList.Items[i]))
// {
// if(!FReset)Synchronize(UpdateOutput); // trial this on
// if(CurrentSimulationObject.NeedsToBeSimulated)
// if(!FReset)RunCurrentSimulation(i,activesimcount);
// if(!FReset)CurrentSimulationObject=0;
// }
// }
// if(!FReset)FProgress=100.0;
// if(!FReset&&!RunSilent)Synchronize(UpdateOutput); // trial this on
// if(!FReset&&!RunSilent)Synchronize(PostProgressMessage);
// if(!FReset&&!RunSilent)Synchronize(UpdateInputParametersForm);
// if(!FReset)Synchronize(RunOnFinishSimumulatingEvent);
// }
// else
// {
// if(!FReset)Synchronize(UpdateOutput);
// }
//
// }
// catch(Exception e)
// {
// //throw(new Exception("An error has occurred during simulation iterations.", mtError, TMsgDlgButtons() << mbOK, 0);
// return false;
// }
// Synchronize(UpdateFinishMessages);
return true;
}
/// <summary>
///
/// </summary>
/// <param name="simulationindex"></param>
/// <param name="simcount"></param>
/// <returns></returns>
public bool RunCurrentSimulation(int simulationindex, int simcount)
{
// try
// {
// if(!FReset&&CurrentSimulationObject)
// {
// FLastSimProgress=-1;
// ZerosList.Clear();
// if(!RunSilent)
// {
//
// if(!FReset)InitialiseSimulationParameters();
// if(!FReset)UpdateProgress(seriesindex,simulationindex,simcount,number_of_days_in_simulation,true);
// }
// else
// {
//
// if(!FReset)InitialiseSimulationParameters();
// }
// for(int index=0;index<number_of_days_in_simulation;++index)
// {
// today=IncDay(startdate,index);
// if(!FReset&&SimulateDay())
// {
// if(!FReset&&!RunSilent)UpdateProgress(seriesindex+1,simulationindex,simcount,number_of_days_in_simulation,false);
// ++seriesindex;
// ++climateindex;
//
// }
// else
// {
// index=number_of_days_in_simulation;
// if(!FReset)
// {
// throw;
// }
// }
// }
// // NeedToUpdateOutput=true;
// if(!RunSilent)
// {
// if(!FReset)Synchronize(CalculateSummaryParameters);
// if(!FReset)Synchronize(EndUpdate);
// Synchronize(EndOutputObjectUpdate);
// //if(!FReset)Synchronize(UpdateOutput); // trial this off
// UpdateProgress(1,simulationindex,simcount,1,true);
// if(FProgramManager.VerificationMode)
// CurrentSimulationObject.SaveVerificationOutput();
// }
// else
// {
// CalculateSummaryParameters();
// EndUpdate();
// EndOutputObjectUpdate();
//
// }
//
//
// }
// else
// {
//
// // NeedToUpdateOutput=true;
// UpdateProgress(1,simulationindex,simcount,1,true);
// }
// }
// catch(Exception e)
// {
// ErrorList.Add("A serious error occurred while running the simulation");
// if(ZerosList.Count>0)
// {
// for(int i=0;i<ZerosList.Count;++i)
// ErrorList.Add(ZerosList.Strings[i]);
// }
// throw;
// }
return true;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool SimulateDay()
{
bool result = true;
try
{
ControlError = "";
if (!FReset) InitialiseClimateData();
if (!FReset) AdjustKeyDatesForYear();
if (!FReset) SetStartOfDayParameters();
if (!FReset) ApplyResetsIfAny();
if (!FReset) TryModelIrrigation();
if (!FReset) TryModelSoilCracking();
if (!FReset) CalculateRunoff();
if (!FReset) CalculatSoilEvaporation();
if (!FReset) TryModelVegetation();
if (!FReset) UpdateWaterBalance();
if (!FReset) TryModelTillage();
if (!FReset) CalculateResidue();
if (!FReset) CalculateErosion();
if (!FReset) TryModelRingTank();
if (!FReset) TryModelPesticide();
if (!FReset) TryModelPhosphorus();
if (!FReset) TryModelNitrate();
if (!FReset) TryModelSolutes();
if (!FReset) TryModelLateralFlow();
if (!FReset) UpdateCropWaterBalance();
if (!FReset) UpdateFallowWaterBalance();
if (!FReset) UpdateTotalWaterBalance();
if (!FReset) TryUpdateRingTankWaterBalance();
if (!FReset) UpdateMonthlyStatistics();
if (!FReset) CalculateVolumeBalanceError();
if (!FReset) ExportDailyOutputs();
if (!FReset) ResetAnyParametersIfRequired();
}
catch (Exception e)
{
result = false;
List<string> Text = new List<string>();
if (today > new DateTime(1800, 1, 1) && today < new DateTime(2100, 1, 1))
Text.Add("There was an error in the simulation on day " + (seriesindex + 1).ToString() + " (" + today.ToString("dd/mm/yyyy") + ")");
if (ControlError.Length > 0)
Text.Add("The error occurred in the function called " + ControlError);
if (Text.Count > 0 && Text.Count < 3)
throw (new Exception(String.Join("\n", Text.ToArray(), e.Message))); //mtError
else
throw (new Exception("Error Simulating Day", new Exception(e.Message)));
}
return result;
}
/// <summary>
///
/// </summary>
public void InitialiseClimateData()
{
try
{
if (climateindex >= 0 && climateindex < Rainfall.Count)
{
out_Rain_mm = (Rainfall)[climateindex];
if (climateindex > 0)
yesterdays_rain = (Rainfall)[climateindex - 1];
else
yesterdays_rain = 0;
out_MaxTemp_oC = (MaxTemp)[climateindex];
out_MinTemp_oC = (MinTemp)[climateindex];
temperature = ((MaxTemp)[climateindex] + (MinTemp)[climateindex]) / 2.0;
out_PanEvap_mm = (Evaporation)[climateindex];
out_SolarRad_MJ_per_m2_per_day = (SolarRadiation)[climateindex];
}
else
throw (new Exception("The climate time-series data has been accessed incorrectly during the simulation. Array bounds were exceeded.\nPlease let David McClymont know of this problem.\n\nmcclymon@mac.com")); //mtError
}
catch (Exception e)
{
ControlError = "InitialiseClimateData";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void AdjustKeyDatesForYear()
{
try
{
day = today.Day;
month = today.Month;
year = today.Year;
}
catch (Exception e)
{
ControlError = "AdjustKeyDatesForYear";
throw new Exception(e.Message);
}
}
/// <summary>
/// /
/// </summary>
public void SetStartOfDayParameters()
{
try
{
effective_rain = out_Rain_mm;
swd = 0;
satd = 0;
for (int i = 0; i < in_LayerCount; ++i)
{
satd = satd + (SaturationLimit_rel_wp[i] - SoilWater_rel_wp[i]);
swd = swd + (DrainUpperLimit_rel_wp[i] - SoilWater_rel_wp[i]);
}
IrrigationController.SetStartOfDayParameters();
VegetationController.SetStartOfDayParameters();
TillageController.SetStartOfDayParameters();
}
catch (Exception e)
{
ControlError = "SetStartOfDayParameters";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void ApplyResetsIfAny()
{
ModelOptionsController.ApplyResetsIfAny(today);
}
/// <summary>
///
/// </summary>
public void TryModelIrrigation()
{
IrrigationController.Simulate();
out_WatBal_Irrigation_mm = IrrigationController.out_IrrigationApplied;
}
/// <summary>
///
/// </summary>
public void TryModelSoilCracking()
{
try
{
if (in_SoilCrackingSwitch)
{
//************************************************************************
//* *
//* This function allows for water to directly enter lower layers *
//* of the soil profile through cracks. For cracks to occur the top *
//* and second profile layers must be less than 30% and 50% *
//* respectively of field capacity. Cracks can extend down the *
//* profile using similar criteria. This subroutine assumes all *
//* cracks must exist at the surface. Water is placed into the *
//* lowest accessable layer first. *
//* *
//************************************************************************
int nod;
// Initialise total water redistributed through cracks
double tred = 0;
for (int i = 0; i < in_LayerCount; ++i)
{
red[i] = 0;
if (!MathTools.DoublesAreEqual(DrainUpperLimit_rel_wp[i], 0))
mcfc[i] = SoilWater_rel_wp[i] / DrainUpperLimit_rel_wp[i];
else
{
mcfc[i] = 0;
LogDivideByZeroError("ModelSoilCracking", "DrainUpperLimit_rel_wp[i]", "mcfc[i]");
}
if (mcfc[i] < 0) mcfc[i] = 0;
else if (mcfc[i] > 1) mcfc[i] = 1;
}
// Don't continue if rainfall is less than 10mm
if (effective_rain < 10)
return;
// Check if profile is dry enough for cracking to occur.
if (mcfc[0] >= 0.3 || mcfc[1] >= 0.3)
return;
// Calculate number of depths to which cracks extend
nod = 1;
for (int i = 1; i < in_LayerCount; ++i)
{
if (mcfc[i] >= 0.3)
i = in_LayerCount;
else
++nod;
}
// Fill cracks from lowest cracked layer first to a maximum of 50% of
// field capacity.
tred = Math.Min(in_MaxInfiltIntoCracks_mm, effective_rain);
for (int i = nod - 1; i >= 0; --i)
{
red[i] = Math.Min(tred, DrainUpperLimit_rel_wp[i] / 2.0 - SoilWater_rel_wp[i]);
tred -= red[i];
if (tred <= 0)
i = -1;
}
// calculate effective rainfall after infiltration into cracks.
// Note that redistribution of water into layer 1 is ignored.
effective_rain = effective_rain + red[0] - Math.Min(in_MaxInfiltIntoCracks_mm, effective_rain);
red[0] = 0.0;
// calculate total amount of water in cracks
for (int i = 0; i < in_LayerCount; ++i)
tred += red[i];
}
}
catch (Exception e)
{
ControlError = "ModelSoilCracking";
throw new Exception(e.Message);
}
}
public void CalculateRunoff()
{
int progress = 0;
try
{
// *********************************************************************
// * This subroutine calculates surface runoff using a modified form *
// * of USDA Curve numbers from CREAMS. The input value of Curve *
// * Number for AMC II is adjusted to account for the effects of crop *
// * and residue cover. The magnitude of the reduction in CNII due *
// * to cover is governed by the user defined CNRED parameter. *
// * *
// * Knisel, W.G. editor. CREAMS: A field-scale model for chemical, *
// * runoff and erosion from agricultural management systems. *
// * United States Department of Agriculture, Conservation Research *
// * Report no. 26. *
// *********************************************************************
double sumh20;
infiltration = 0.0;
out_WatBal_Runoff_mm = 0.0;
runoff_retention_number = 0;
double cn1, smx;
// ***************************************************
// * Calculate cover effect on curve number (cn2). *
// ***************************************************}
crop_cover = VegetationController.GetCropCoverIfLAIModel(crop_cover); //LAI Model uses cover from the end of the previous day whereas Cover model predefines at the start of the day
cn2 = in_RunoffCurveNumber - in_CurveNumberReduction * Math.Min(1.0, crop_cover + total_residue_cover * (1 - crop_cover));
progress = 1;
//this could need attention!!!! Danny Rattray
// *******************************************************
// * Calculate roughness effect on curve number (cn2). *
// *******************************************************
rain_since_tillage += effective_rain;
if (!MathTools.DoublesAreEqual(in_RainToRemoveRoughness_mm, 0))
{
if (rain_since_tillage < in_RainToRemoveRoughness_mm)
cn2 += TillageController.roughness_ratio * in_MaxRedInCNDueToTill * (rain_since_tillage / in_RainToRemoveRoughness_mm - 1);
}
if (effective_rain < 0.1)
{
out_WatBal_Runoff_mm = IrrigationController.out_IrrigationRunoff;
return;
}
progress = 2;
if (ModelOptionsController.UsePerfectCurveNoFn())
{
// *******************************************************
// * Calculate smx (CREAMS p14, equations i-3 and i-4) *
// *******************************************************
cn1 = -16.91 + 1.348 * cn2 - 0.01379 * cn2 * cn2 + 0.0001177 * cn2 * cn2 * cn2;
if (!MathTools.DoublesAreEqual(cn1, 0))
smx = 254.0 * ((100.0 / cn1) - 1.0);
else
{
smx = 0;
LogDivideByZeroError("CalculateRunoff", "cn1", "smx");
}
progress = 3;
// ***************************************
// * Calculate retention parameter, runoff_retention_number *
// ***************************************
sumh20 = 0.0;
for (int i = 0; i < in_LayerCount - 1; ++i)
{
if (!MathTools.DoublesAreEqual(SaturationLimit_rel_wp[i], 0))
sumh20 += wf[i] * (Math.Max(SoilWater_rel_wp[i], 0) / SaturationLimit_rel_wp[i]);
else
{
LogDivideByZeroError("CalculateRunoff", "SaturationLimit_rel_wp[i]", "sumh20");
}
}
runoff_retention_number = (int)(smx * (1.0 - sumh20));
//REMOVE INT STATEMENT AFTER VALIDATION
progress = 4;
}
else
{
// ******************************************************************
// * MODIFIED Calculate smx (CREAMS p14, equations i-3 and i-4) *
// * Fix" for oversize Smx at low CN *
// * e.g. >254mm for cn2<70 *
// * Brett Robinson May 2011 *
// ******************************************************************
double temp = 265.0 + (Math.Exp(0.17 * (cn2 - 50)) + 1);
if (!MathTools.DoublesAreEqual(temp, 0))
{
if (cn2 > 83) // linear above cn2=83
smx = 6 + (100 - cn2) * 6.66;
else // logistic for cn2<=83
smx = 254.0 - (265.0 * Math.Exp(0.17 * (cn2 - 50))) / temp;
}
else
{
smx = 0;
LogDivideByZeroError("CalculateRunoff", "(265.0+(exp(cn2)+1)", "smx");
}
progress = 3;
// ***************************************
// * Calculate retention parameter, runoff_retention_number *
// ***************************************
sumh20 = 0.0;
// * CREAMS and other model discount S for water content (linear from air dry to sat) *
// * old code = relative to WP, new code = rel to air dry *
// * Changes by Brett Robinson May 2011 *
for (int i = 0; i < in_LayerCount - 1; ++i)
{
double deno = SaturationLimit_rel_wp[i] + AirDryLimit_rel_wp[i];
if (!MathTools.DoublesAreEqual(deno, 0))
sumh20 = sumh20 + wf[i] * (SoilWater_rel_wp[i] + AirDryLimit_rel_wp[i]) / deno;
else
LogDivideByZeroError("CalculateRunoff", "SaturationLimit_rel_wp[i]+AirDryLimit_rel_wp[i]", "sumh20");
}
runoff_retention_number = (int)(smx * (1.0 - sumh20));
//REMOVE INT STATEMENT AFTER VALIDATION
progress = 4;
}
// *************************************************
// * Calculate runoff (creams p14, equation i-1) *
// *************************************************
double denom = effective_rain + 0.8 * runoff_retention_number;
double bas = effective_rain - 0.2 * runoff_retention_number;
if (!MathTools.DoublesAreEqual(denom, 0) && bas > 0)
{
out_WatBal_Runoff_mm = Math.Pow(bas, 2.0) / denom;
infiltration = effective_rain - out_WatBal_Runoff_mm;
}
else
{
out_WatBal_Runoff_mm = 0;
infiltration = effective_rain;
}
//add any runoff from irrigation.
out_WatBal_Runoff_mm += IrrigationController.out_IrrigationRunoff;
}
catch (Exception e)
{
if (progress == 0) ControlError = "CalculateRunoff - Calculate initial roughness effect on curve number (cn2).";
else if (progress == 1) ControlError = "CalculateRunoff - Updating roughness effect on curve number (cn2).";
else if (progress == 2) ControlError = "CalculateRunoff - Calculate smx (CREAMS p14, equations i-3 and i-4).";
else if (progress == 3) ControlError = "CalculateRunoff - Calculate retention parameter, runoff_retention_number.";
else if (progress == 4) ControlError = "CalculateRunoff - Calculate runoff (creams p14, equation i-1).";
else ControlError = "CalculateRunoff";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void CalculatSoilEvaporation()
{
try
{
// ********************************************************************
// * This function calculates soil evaporation using the Ritchie *
// * model. *
// ********************************************************************
// Calculate potential soil evaporation
// From proportion of bare soil
out_WatBal_PotSoilEvap_mm = VegetationController.GetPotentialSoilEvaporation();
if (IrrigationController.PondingExists())
{
out_WatBal_SoilEvap_mm = out_WatBal_PotSoilEvap_mm;
}
else
{
// Add crop residue effects
////NOTE THAT THIS USED TO ONLY BE FOR THE LAI MODEL - I"VE NOW MADE IT FOR EITHER
if (total_crop_residue > 1.0)
out_WatBal_PotSoilEvap_mm = out_WatBal_PotSoilEvap_mm * (Math.Exp(-0.22 * total_crop_residue / 1000.0));
// *******************************
// * initialize daily variables
// ******************************
se1 = 0.0;
out_WatBal_SoilEvap_mm = 0.0;
se2 = 0.0;
se21 = 0.0;
se22 = 0.0;
// **************************************************
// * If infiltration has occurred then reset sse1. *
// * Reset sse2 if infiltration exceeds sse1. *
// **************************************************
if (infiltration > 0.0)
{
sse2 = Math.Max(0, sse2 - Math.Max(0, infiltration - sse1));
sse1 = Math.Max(0, sse1 - infiltration);
if (!MathTools.DoublesAreEqual(in_Cona_mm_per_sqrroot_day, 0))
dsr = Math.Pow(sse2 / in_Cona_mm_per_sqrroot_day, 2);
else
{
dsr = 0;
LogDivideByZeroError("CalculatSoilEvaporation", "in_Cona_mm_per_sqrroot_day", "dsr");
}
}
// ********************************
// * Test for 1st stage drying. *
// ********************************
if (sse1 < in_Stage1SoilEvapLimitU_mm)
{
// *****************************************************************
// * 1st stage evaporation for today. Set se1 equal to potential *
// * soil evaporation but limited by U. *
// *****************************************************************
se1 = Math.Min(out_WatBal_PotSoilEvap_mm, in_Stage1SoilEvapLimitU_mm - sse1);
se1 = Math.Max(0.0, Math.Min(se1, SoilWater_rel_wp[0] + AirDryLimit_rel_wp[0]));
// *******************************
// * Accumulate stage 1 drying *
// *******************************
sse1 = sse1 + se1;
// ******************************************************************
// * Check if potential soil evaporation is satisfied by 1st stage *
// * drying. If not, calculate some stage 2 drying(se2). *
// ******************************************************************
if (out_WatBal_PotSoilEvap_mm > se1)
{
// *****************************************************************************
// * If infiltration on day, and potential_soil_evaporation.gt.se1 (ie. a deficit in evap) .and. sse2.gt.0 *
// * than that portion of potential_soil_evaporation not satisfied by se1 should be 2nd stage. This *
// * can be determined by Math.Sqrt(time)*in_Cona_mm_per_sqrroot_day with any remainder ignored. *
// * If sse2 is zero, then use Ritchie's empirical transition constant (0.6). *
// *****************************************************************************
if (sse2 > 0.0)
se2 = Math.Min(out_WatBal_PotSoilEvap_mm - se1, in_Cona_mm_per_sqrroot_day * Math.Pow(dsr, 0.5) - sse2);
else
se2 = 0.6 * (out_WatBal_PotSoilEvap_mm - se1);
// **********************************************************
// * Calculate stage two evaporation from layers 1 and 2. *
// **********************************************************
// Any 1st stage will equal infiltration and therefore no net change in
// soil water for layer 1 (ie can use SoilWater_rel_wp(1)+AirDryLimit_rel_wp(1) to determine se21.
se21 = Math.Max(0.0, Math.Min(se2, SoilWater_rel_wp[0] + AirDryLimit_rel_wp[0]));
se22 = Math.Max(0.0, Math.Min(se2 - se21, SoilWater_rel_wp[1] + AirDryLimit_rel_wp[1]));
// ********************************************************
// * Re-Calculate se2 for when se2-se21 > SoilWater_rel_wp(2)+AirDryLimit_rel_wp(2) *
// ********************************************************
se2 = se21 + se22;
// ************************************************
// * Update 1st and 2nd stage soil evaporation. *
// ************************************************
sse1 = in_Stage1SoilEvapLimitU_mm;
sse2 += se2;
if (!MathTools.DoublesAreEqual(in_Cona_mm_per_sqrroot_day, 0))
dsr = Math.Pow(sse2 / in_Cona_mm_per_sqrroot_day, 2);
else
{
dsr = 0;
LogDivideByZeroError("CalculatSoilEvaporation", "in_Cona_mm_per_sqrroot_day", "dsr");
}
}
else
se2 = 0.0;
}
else
{
sse1 = in_Stage1SoilEvapLimitU_mm;
// ************************************************************************
// * No 1st stage drying. Calc. 2nd stage and remove from layers 1 & 2. *
// ************************************************************************
dsr = dsr + 1.0;
se2 = Math.Min(out_WatBal_PotSoilEvap_mm, in_Cona_mm_per_sqrroot_day * Math.Pow(dsr, 0.5) - sse2);
se21 = Math.Max(0.0, Math.Min(se2, SoilWater_rel_wp[0] + AirDryLimit_rel_wp[0]));
se22 = Math.Max(0.0, Math.Min(se2 - se21, SoilWater_rel_wp[1] + AirDryLimit_rel_wp[1]));
// ********************************************************
// * Re-calculate se2 for when se2-se21 > SoilWater_rel_wp(2)+AirDryLimit_rel_wp(2) *
// ********************************************************
se2 = se21 + se22;
// *****************************************
// * Update 2nd stage soil evaporation. *
// *****************************************
sse2 = sse2 + se2;
// **************************************
// * calculate total soil evaporation *
// **************************************
}
out_WatBal_SoilEvap_mm = se1 + se2;
}
}
catch (Exception e)
{
ControlError = "CalculatSoilEvaporation";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void TryModelVegetation()
{
VegetationController.Simulate();
}
/// <summary>
///
/// </summary>
public void UpdateWaterBalance()
{
//***********************************************************************
//* This subroutine performs the water balance. New nested loop *
//* algorithm infiltrates and redistributes water in one pass. This *
//* new algorithm has many advantages over the previous one. Firstly, *
//* it is more biophysically realistic; secondly, it considers the *
//* effects of a restricted Ksat on both infiltration and *
//* redistribution. Previously, only redistribution was considered. *
//* It should also bettern explain water movemnet under saturated *
//* conditions. *
//***********************************************************************
double oflow = 0.0;
overflow_mm = 0;
double drain = infiltration;
// 1. Add all infiltration/drainage and extract ET.
// 2. Cascade a proportion of all water greater than drained upper limit (FC)
// 3. If soil water content is still greater than upper limit (SWMAX), add
// all excess above upper limit to runoff
for (int i = 0; i < in_LayerCount; ++i)
{
Seepage[i] = drain;
if (i == 0) SoilWater_rel_wp[i] += Seepage[i] - (out_WatBal_SoilEvap_mm - se22) - layer_transpiration[i];
else if (i == 1) SoilWater_rel_wp[i] += Seepage[i] - layer_transpiration[i] + red[i] - se22;
else SoilWater_rel_wp[i] += Seepage[i] - layer_transpiration[i] + red[i];
if (SoilWater_rel_wp[i] > DrainUpperLimit_rel_wp[i])
{
drain = swcon[i] * (SoilWater_rel_wp[i] - DrainUpperLimit_rel_wp[i]);
// if(drain>(ksat[i]*12.0))
// drain=ksat[i]*12.0;
if (drain > ksat[i])
drain = ksat[i];
else if (drain < 0)
drain = 0;
SoilWater_rel_wp[i] -= drain;
}
else
drain = 0;
if (SoilWater_rel_wp[i] > SaturationLimit_rel_wp[i])
{
oflow = SoilWater_rel_wp[i] - SaturationLimit_rel_wp[i];
SoilWater_rel_wp[i] = SaturationLimit_rel_wp[i];
}
int j = 0;
while (oflow > 0)
{
if (i - j == 0) //look at first layer
{
overflow_mm += oflow;
out_WatBal_Runoff_mm = out_WatBal_Runoff_mm + oflow;
infiltration -= oflow;
Seepage[0] -= oflow; //drainage in first layer
oflow = 0;
}
else //look at other layersException e
{
SoilWater_rel_wp[i - j] += oflow;
Seepage[i - j + 1] -= oflow;
if (SoilWater_rel_wp[i - j] > SaturationLimit_rel_wp[i - j])
{
oflow = SoilWater_rel_wp[i - j] - SaturationLimit_rel_wp[i - j];
SoilWater_rel_wp[i - j] = SaturationLimit_rel_wp[i - j];
}
else
oflow = 0;
++j;
}
}
}
double satrange = SaturationLimit_rel_wp[0] - DrainUpperLimit_rel_wp[0];
double satamount = SoilWater_rel_wp[0] - DrainUpperLimit_rel_wp[0];
if (satamount > 0 && satrange > 0)
saturationindex = satamount / satrange;
else
saturationindex = 0;
Seepage[in_LayerCount] = drain;
out_WatBal_DeepDrainage_mm = drain;
total_soil_water = 0;
for (int i = 0; i < in_LayerCount; ++i)
total_soil_water += SoilWater_rel_wp[i];
}
/// <summary>
///
/// </summary>
public void TryModelTillage()
{
TillageController.Simulate();
}
/// <summary>
///
/// </summary>
public void CalculateResidue()
{
try
{
VegetationController.CalculateResidue();
//we already estimated these in the Runoff function- but will recalculate here.
total_crop_residue = VegetationController.GetTotalCropResidue();
total_residue_cover = VegetationController.GetTotalResidueCover();
total_residue_cover_percent = VegetationController.GetTotalResidueCoverPercent();
total_cover = VegetationController.GetTotalCover();
crop_cover = VegetationController.GetCropCover();
total_cover_percent = total_cover * 100.0;
accumulated_cover += total_cover_percent;
}
catch (Exception e)
{
ControlError = "CalculateResidue";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void CalculateErosion()
{
try
{
// ***********************************************************************
// * This subroutine calculates sediment yield in tonnes/ha using the *
// * Dave Freebairn method *
// ***********************************************************************
erosion_t_per_ha = 0;
sed_catchmod = 0;
if (out_WatBal_Runoff_mm <= 1)
{
sediment_conc = 0;
}
else
{
double conc = 0;
double cover;
if (!IrrigationController.ConsiderCoverEffects())
cover = Math.Min(100.0, (crop_cover + total_residue_cover * (1 - crop_cover)) * 100.0);
else
cover = IrrigationController.GetCoverEffect(crop_cover, total_residue_cover);
if (cover < 50.0)
conc = 16.52 - 0.46 * cover + 0.0031 * cover * cover; //% sediment concentration Exception e max g/l is 165.2 when cover =0;
else if (cover >= 50.0)
conc = -0.0254 * cover + 2.54;
conc = Math.Max(0.0, conc);
erosion_t_per_ha = conc * usle_ls_factor * in_USLE_K * in_USLE_P * out_WatBal_Runoff_mm / 10.0;
sed_catchmod = conc * in_USLE_K * in_USLE_P * out_WatBal_Runoff_mm / 10.0;
}
if (!MathTools.DoublesAreEqual(out_WatBal_Runoff_mm, 0))
{
if (!InRunoff2)
++RunoffEventCount2;
InRunoff2 = true;
sediment_conc = erosion_t_per_ha * 100.0 / out_WatBal_Runoff_mm * in_SedDelivRatio; //sediment concentration in g/l
if (sediment_conc > peakSedConc)
peakSedConc = sediment_conc;
}
else
{
// dont log a divide by zero error for this one
if (InRunoff2)
cumSedConc += peakSedConc;
peakSedConc = 0;
InRunoff2 = false;
sediment_conc = 0;
}
offsite_sed_delivery = erosion_t_per_ha * in_SedDelivRatio;
}
catch (Exception e)
{
ControlError = "CalculateErosion";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void TryModelRingTank()
{
IrrigationController.ModelRingTank();
}
/// <summary>
///
/// </summary>
public void TryModelPesticide()
{
PesticideController.Simulate();
}
/// <summary>
///
/// </summary>
public void TryModelPhosphorus()
{
PhosphorusController.Simulate();
}
/// <summary>
///
/// </summary>
public void TryModelNitrate()
{
NitrateController.Simulate();
}
/// <summary>
///
/// </summary>
public void TryModelSolutes()
{
SolutesController.Simulate();
}
/// <summary>
///
/// </summary>
public void TryModelLateralFlow()
{
try
{
if (ModelOptionsController.CanCalculateLateralFlow())
{
// Calculate most limiting Kratio
double kr;
double kratio = 1.0;
for (int i = 1; i < in_LayerCount; ++i)
{
if (!MathTools.DoublesAreEqual(ksat[i], 0))
kr = ksat[i - 1] / ksat[i];
else
kr = 0;
if (kr > kratio)
kratio = kr;
}
// Convert in_FieldSlope_pc from percent to degrees
double slopedeg = Math.Atan(in_FieldSlope_pc / 100.0) * 180.0 / 3.14159;
// Calculate PredRH - lateral flow partitioning
double LN_kratio = Math.Log(kratio);
double LN_angle = Math.Log(slopedeg);
double LN_kratio2 = LN_kratio * LN_kratio;
double LN_angle2 = LN_angle * LN_angle;
double LNK_lnang = LN_kratio * LN_angle;
double numer = 0.04487067 + (0.019797884 * LN_kratio) - (0.020606403 * LN_angle)
+ (0.01010285 * LN_kratio2) + (0.01415831 * LN_angle2)
- (0.011046881 * LNK_lnang);
double denom = 1 - (0.11431376 * LN_kratio) - (0.35073561 * LN_angle)
+ (0.013044911) * (LN_kratio2) + (0.040556192 * LN_angle2)
+ (0.015858813 * LNK_lnang);
if (!MathTools.DoublesAreEqual(denom, 0))
PredRh = numer / denom;
else
{
PredRh = 0;
}
out_WatBal_LateralFlow_mm = Seepage[in_LayerCount] * PredRh;
Seepage[in_LayerCount] = Seepage[in_LayerCount] * (1 - PredRh);
}
else
out_WatBal_LateralFlow_mm = 0;
}
catch (Exception e)
{
ControlError = "CalculateLateralFlow";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void UpdateCropWaterBalance()
{
}
/// <summary>
///
/// </summary>
public void UpdateFallowWaterBalance()
{
try
{
if (VegetationController.InFallow())
{
sum_fallow_rainfall += out_Rain_mm;
sum_fallow_runoff += out_WatBal_Runoff_mm;
sum_fallow_soilevaporation += out_WatBal_SoilEvap_mm;
sum_fallow_drainage += out_WatBal_DeepDrainage_mm;
sum_fallow_soilerosion += erosion_t_per_ha;
if (total_cover > 0.5)
++fallow_days_with_more_50pc_cov;
}
else if (VegetationController.IsPlanting())
sum_fallow_soilwater += VegetationController.CalcFallowSoilWater();
}
catch (Exception e)
{
ControlError = "UpdateFallowWaterBalance";
throw new Exception (e.Message);
}
}
/// <summary>
///
/// </summary>
public void UpdateTotalWaterBalance()
{
try
{
sum_rainfall += out_Rain_mm;
sum_irrigation += out_WatBal_Irrigation_mm;
sum_runoff += out_WatBal_Runoff_mm;
sum_potevap += out_WatBal_PotSoilEvap_mm;
sum_soilevaporation += out_WatBal_SoilEvap_mm;
sum_transpiration += VegetationController.GetTotalTranspiration();
sum_evapotranspiration = sum_soilevaporation + sum_transpiration;
sum_overflow += overflow_mm;
sum_drainage += out_WatBal_DeepDrainage_mm;
sum_lateralflow += out_WatBal_LateralFlow_mm;
sum_soilerosion += erosion_t_per_ha;
}
catch (Exception e)
{
ControlError = "UpdateTotalWaterBalance";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void TryUpdateRingTankWaterBalance()
{
IrrigationController.UpdateRingtankWaterBalance();
}
/// <summary>
///
/// </summary>
public void UpdateMonthlyStatistics()
{
try
{
int monthindex = month - 1;
mo_MthlyAvgRainfall_mm[monthindex] += out_Rain_mm;
mo_MthlyAvgEvaporation_mm[monthindex] += out_WatBal_SoilEvap_mm;
mo_MthlyAvgTranspiration_mm[monthindex] += VegetationController.GetTotalTranspiration();
mo_MthlyAvgRunoff_mm[monthindex] += out_WatBal_Runoff_mm;
mo_MthlyAvgDrainage_mm[monthindex] += out_WatBal_DeepDrainage_mm;
}
catch (Exception e)
{
ControlError = "UpdateMonthlyStatistics";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void CalculateVolumeBalanceError()
{
try
{
double sse;
double deltasw = total_soil_water - previous_total_soil_water;
if (ModelOptionsController.CanCalculateLateralFlow())
{
if (!MathTools.DoublesAreEqual(out_Rain_mm, MathTools.MISSING_DATA_VALUE))
sse = (out_WatBal_Irrigation_mm + out_Rain_mm) - (deltasw + out_WatBal_Runoff_mm + out_WatBal_SoilEvap_mm + VegetationController.GetTotalTranspiration() + Seepage[in_LayerCount] + out_WatBal_LateralFlow_mm);
else
sse = (out_WatBal_Irrigation_mm + 0) - (deltasw + out_WatBal_Runoff_mm + out_WatBal_SoilEvap_mm + VegetationController.GetTotalTranspiration() + Seepage[in_LayerCount] + out_WatBal_LateralFlow_mm);
}
else
{
if (!MathTools.DoublesAreEqual(out_Rain_mm, MathTools.MISSING_DATA_VALUE))
sse = (out_WatBal_Irrigation_mm + out_Rain_mm) - (deltasw + out_WatBal_Runoff_mm + out_WatBal_SoilEvap_mm + VegetationController.GetTotalTranspiration() + Seepage[in_LayerCount]);
else
sse = (out_WatBal_Irrigation_mm + 0) - (deltasw + out_WatBal_Runoff_mm + out_WatBal_SoilEvap_mm + VegetationController.GetTotalTranspiration() + Seepage[in_LayerCount]);
}
out_WatBal_VBE_mm = (int)(sse * 1000000) / 100000.0;
}
catch (Exception e)
{
ControlError = "CalculateVolumeBalanceError";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void ExportDailyOutputs()
{
}
/// <summary>
///
/// </summary>
public void ResetAnyParametersIfRequired()
{
try
{
VegetationController.ResetAnyParametersIfRequired();
}
catch (Exception e)
{
ControlError = "ResetAnyParametersIfRequired";
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool ConnectParametersToModel()
{
// bool cancontinue=CurrentSimulationObject.ConnectParametersToModel(this);
// if(cancontinue)
// {
// return true;
// }
//
// ErrorList.Add("There was an error connecting parameters to the model from Simulation: "+CurrentSimulationObject.ColumnText[0]);
// throw;
return false;
}
//bool LoadSimulationObject(TSimulationInputObject* object)
//{
// // if(object&&object.ReadyToSimulate)
// // {
// //
// // CurrentSimulationObject=object;
// // CurrentSimulationObject.CreateOutputObject(); //new - didn't want to autocreate as I want it null in batch processing.
// // if(!FReset)Synchronize(BeginUpdate);
// // ResetSwitchesToDefault();
// // Synchronize(SynchronizeModelToDataConnections);
// // return(CurrentSimulationObject.IsInitialised);
// // }
// return false;
//}
/// <summary>
///
/// </summary>
public void SynchronizeModelToDataConnections()
{
// try
// {
// CurrentSimulationObject.IsInitialised=false;
// if(CurrentSimulationObject)
// {
// if(CurrentSimulationObject.ConnectParametersToModel(this))
// {
// CurrentSimulationObject.InitialiseOutputObjectForSimulation();
// CurrentSimulationObject.IsInitialised=true;
// }
// }
//
// }
// catch(Exception e)
// {
// if(CurrentSimulationObject)
// throw(new Exception("There was an error connecting "+CurrentSimulationObject.ColumnText[0]+" to the simulation engine.", mtError, TMsgDlgButtons() << mbOK, 0);
// else
// throw(new Exception("There was an error connecting parameters to the simulation engine.", mtError, TMsgDlgButtons() << mbOK, 0);
// throw;
// }
}
/// <summary>
///
/// </summary>
public void FinaliseSimulationParameters()
{
// if(CurrentSimulationObject) CurrentSimulationObject.Modified=true;
//// if(LoadSimulationObject(CurrentSimulationObject))
// // {
//
// // if(!FReset)RunCurrentSimulation(1,1);
//// if(!FReset)FProgress=100.0;
//// if(!FReset)Synchronize(PostProgressMessage);
//// if(!FReset)Synchronize(RunOnFinishSimumulatingEvent);
// // }
}
/// <summary>
///
/// </summary>
public void InitialiseSimulationParameters()
{
try
{
if (number_of_days_in_simulation > 0)
{
// seriesindex=0;
// climateindex=CurrentSimulationObject.SeriesStartIndex;
// if(CurrentOutputObject)
// CurrentOutputObject.ManagementHistory.Reset();
// InitialiseSoilParameters();
// IrrigationController.Initialise();
// VegetationController.Initialise();
// TillageController.Initialise();
// PesticideController.Initialise();
// PhosphorusController.Initialise();
// NitrateController.Initialise();
// SolutesController.Initialise();
//
// InitialiseMonthlyStatisticsParameters();
// InitialiseSummaryVariables();
// UpdateTimeSeriesNames();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
///
/// </summary>
public void InitialiseSoilParameters()
{
//InitialiseArray(depth, in_LayerCount + 1);
//InitialiseArray(red, in_LayerCount);
//InitialiseArray(wf, in_LayerCount);
//InitialiseArray(SoilWater_rel_wp, in_LayerCount);
//InitialiseArray(DrainUpperLimit_rel_wp, in_LayerCount);
//InitialiseArray(SaturationLimit_rel_wp, in_LayerCount);
//InitialiseArray(AirDryLimit_rel_wp, in_LayerCount);
//InitialiseArray(Wilting_Point_RelOD_mm, in_LayerCount);
//InitialiseArray(DUL_RelOD_mm, in_LayerCount);
//InitialiseArray(ksat, in_LayerCount);
//InitialiseArray(swcon, in_LayerCount);
//InitialiseArray(Seepage, in_LayerCount + 1);
//InitialiseArray(layer_transpiration, in_LayerCount);
//InitialiseArray(mcfc, in_LayerCount);
depth = new List<double>(in_LayerCount + 1);
red = new List<double>(in_LayerCount);
wf = new List<double>(in_LayerCount);
SoilWater_rel_wp = new List<double>(in_LayerCount);
DrainUpperLimit_rel_wp = new List<double>(in_LayerCount);
SaturationLimit_rel_wp = new List<double>(in_LayerCount);
AirDryLimit_rel_wp = new List<double>(in_LayerCount);
Wilting_Point_RelOD_mm = new List<double>(in_LayerCount);
DUL_RelOD_mm = new List<double>(in_LayerCount);
ksat = new List<double>(in_LayerCount);
swcon = new List<double>(in_LayerCount);
Seepage = new List<double>(in_LayerCount + 1);
layer_transpiration = new List<double>(in_LayerCount);
mcfc = new List<double>(in_LayerCount);
swd = 0;
sse1 = 0;
sse2 = 0;
se1 = 0;
se2 = 0;
se21 = 0;
se22 = 0;
dsr = 0;
cumSedConc = 0;
peakSedConc = 0;
depth[0] = 0;
for (int i = 0; i < in_LayerCount; ++i)
{
depth[i + 1] = (int)(in_Depths[i] + 0.5);
red[i] = 0;
ksat[i] = in_LayerDrainageLimit_mm_per_day[i];///12.0;
}
total_soil_water = 0.0;
previous_total_soil_water = 0.0;
for (int i = 0; i < in_LayerCount; ++i)
{
if (depth[i + 1] - depth[i] > 0)
{
//PERFECT soil water alorithms relate all values to wilting point.
double deltadepth = (depth[i + 1] - depth[i]) * 0.01;
Wilting_Point_RelOD_mm[i] = in_SoilLimitWiltingPoint_pc[i] * deltadepth;
DUL_RelOD_mm[i] = in_SoilLimitFieldCapacity_pc[i] * deltadepth;
if (i == 0)
AirDryLimit_rel_wp[0] = Wilting_Point_RelOD_mm[i] - in_SoilLimitAirDry_pc[i] * deltadepth;
else if (i == 1)
AirDryLimit_rel_wp[1] = 0.5 * (Wilting_Point_RelOD_mm[i] - in_SoilLimitAirDry_pc[i] * deltadepth);
else
AirDryLimit_rel_wp[i] = 0;
DrainUpperLimit_rel_wp[i] = (in_SoilLimitFieldCapacity_pc[i] * deltadepth) - Wilting_Point_RelOD_mm[i];
SaturationLimit_rel_wp[i] = (in_SoilLimitSaturation_pc[i] * deltadepth) - Wilting_Point_RelOD_mm[i];
}
else
{
DrainUpperLimit_rel_wp[i] = 0;
SaturationLimit_rel_wp[i] = 0;
AirDryLimit_rel_wp[0] = 0;
}
}
for (int i = 0; i < in_LayerCount; ++i)
{
SoilWater_rel_wp[i] = ModelOptionsController.GetInitialPAW() * DrainUpperLimit_rel_wp[i];
if (SoilWater_rel_wp[i] > SaturationLimit_rel_wp[i])
SoilWater_rel_wp[i] = SaturationLimit_rel_wp[i];
else if (SoilWater_rel_wp[i] < 0)
SoilWater_rel_wp[i] = 0;
total_soil_water += SoilWater_rel_wp[i];
}
total_crop_residue = 0;
total_residue_cover = 0;//0.707*(1.0-exp(-1.0*total_crop_residue/1000.0));
total_residue_cover_percent = 0;
CalculateInitialValuesOfCumulativeSoilEvaporation();
CalculateDepthRetentionWeightFactors();
CalculateDrainageFactors();
CalculateUSLE_LSFactor();
RunoffEventCount2 = 0;
PredRh = 0;
}
/// <summary>
///
/// </summary>
public void CalculateInitialValuesOfCumulativeSoilEvaporation()
{
// Calculate initial values of cumulative soil evaporation
if (DrainUpperLimit_rel_wp[0] - SoilWater_rel_wp[0] > in_Stage1SoilEvapLimitU_mm)
{
sse1 = in_Stage1SoilEvapLimitU_mm;
sse2 = Math.Max(0.0, DrainUpperLimit_rel_wp[0] - SoilWater_rel_wp[0]) - in_Stage1SoilEvapLimitU_mm;
}
else
{
sse1 = Math.Max(0.0, DrainUpperLimit_rel_wp[0] - SoilWater_rel_wp[0]);
sse2 = 0.0;
}
if (!MathTools.DoublesAreEqual(in_Cona_mm_per_sqrroot_day, 0))
dsr = Math.Pow(sse2 / in_Cona_mm_per_sqrroot_day, 2.0);
else
{
dsr = 0;
LogDivideByZeroError("InitialiseSoilParameters", "in_Cona_mm_per_sqrroot_day", "dsr");
}
}
/// <summary>
///
/// </summary>
public void CalculateUSLE_LSFactor()
{
if (ModelOptionsController.UsePerfectUSLELSFn())
{
double aht = in_FieldSlope_pc * in_SlopeLength_m / 100.0;
double lambda = 3.281 * (Math.Sqrt(in_SlopeLength_m * in_SlopeLength_m + aht * aht));
double theta;
if (!MathTools.DoublesAreEqual(in_SlopeLength_m, 0))
theta = Math.Asin(aht / in_SlopeLength_m);
else
{
theta = 0;
LogDivideByZeroError("CalculateUSLE_LSFactor", "in_SlopeLength_m", "theta");
}
if (!MathTools.DoublesAreEqual(1.0 + in_RillRatio, 0))
{
if (in_FieldSlope_pc < 9.0)
usle_ls_factor = Math.Pow(lambda / 72.6, in_RillRatio / (1.0 + in_RillRatio)) * (10.8 * Math.Sin(theta) + 0.03);
else
usle_ls_factor = Math.Pow(lambda / 72.6, in_RillRatio / (1.0 + in_RillRatio)) * (16.8 * Math.Sin(theta) - 0.5);
}
else
{
usle_ls_factor = 0;
LogDivideByZeroError("CalculateUSLE_LSFactor", "1.0+in_RillRatio", "usle_ls_factor");
}
}
else
{
if (!MathTools.DoublesAreEqual(1.0 + in_RillRatio, 0))
{
usle_ls_factor = Math.Pow(in_SlopeLength_m / 22.1, in_RillRatio / (1.0 + in_RillRatio)) * (0.065 + 0.0456 * in_FieldSlope_pc + 0.006541 * Math.Pow(in_FieldSlope_pc, 2));
}
else
{
usle_ls_factor = 0;
LogDivideByZeroError("CalculateUSLE_LSFactor", "1.0+in_RillRatio", "usle_ls_factor");
}
}
}
/// <summary>
///
/// </summary>
public void CalculateDepthRetentionWeightFactors()
{
double a, b;
for (int i = 0; i < in_LayerCount - 1; ++i)
{
if (depth[in_LayerCount - 1] > 0)
{
a = -4.16 * (depth[i] / depth[in_LayerCount - 1]);
b = -4.16 * (depth[i + 1] / depth[in_LayerCount - 1]);
wf[i] = 1.016 * (Math.Exp(a) - Math.Exp(b));
}
else
{
wf[i] = 0;
LogDivideByZeroError("CalculateDepthRetentionWeightFactors", "depth[in_LayerCount-1]", "wf[i]");
}
}
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
/// <param name="s2"></param>
/// <param name="s3"></param>
public void LogDivideByZeroError(string s, string s2, string s3)
{
}
/// <summary>
///
/// </summary>
public void CalculateDrainageFactors()
{
for (int i = 0; i < in_LayerCount; ++i)
{
if (ksat[i] > 0)
{
// I've got rid of the old PERFECTism regarding Ksat
// the commented bits below was just my testing algorithms,
// to make sure the results are identical to the reworked equations.
// double oldksat=ksat[i]/12.0;
// double val1 = 48.0/(2.0*(SaturationLimit_rel_wp[i]-DrainUpperLimit_rel_wp[i])/oldksat+24.0);
// double val2 = 2.0*ksat[i]/(SaturationLimit_rel_wp[i]-DrainUpperLimit_rel_wp[i]+ksat[i]);
// if(int(val1*1000000)!=int(val2*1000000))
// throw(new Exception("error!", mtError, TMsgDlgButtons() << mbOK, 0);
// swcon[i]=val2;
double temp = (SaturationLimit_rel_wp[i] - DrainUpperLimit_rel_wp[i] + ksat[i]);
if (!MathTools.DoublesAreEqual(temp, 0))
swcon[i] = 2.0 * ksat[i] / temp;
else
{
swcon[i] = 0;
LogDivideByZeroError("CalculateDrainageFactors", "SaturationLimit_rel_wp[i]-DrainUpperLimit_rel_wp[i]+ksat[i]", "swcon[i]");
}
}
else
swcon[i] = 0;
if (swcon[i] < 0)
swcon[i] = 0;
else if (swcon[i] > 1) swcon[i] = 1;
}
}
/// <summary>
///
/// </summary>
/// <param name="n"></param>
/// <param name="delay"></param>
/// <returns></returns>
public double SumRain(int n, int delay)
{
double sumrain = 0;
int index;
for (int i = 0; i < n; ++i)
{
index = climateindex - i - delay;
if (index >= 0)
sumrain += Rainfall[index];
}
return sumrain;
}
/// <summary>
///
/// </summary>
/// <param name="day"></param>
/// <param name="sim"></param>
/// <param name="simcount"></param>
/// <param name="daycount"></param>
/// <param name="forceupdate"></param>
public void UpdateProgress(int day, int sim, int simcount, int daycount, bool forceupdate)
{
if (!FReset || forceupdate)
{
double totalcount = simcount * daycount;
if (!MathTools.DoublesAreEqual(totalcount, 0))
FProgress = (int)((double)(sim * daycount + day) / totalcount * 100.0 + 0.5);
else
FProgress = 0;
if (daycount != 0)
FSimProgress = (int)((double)(day) / (double)(daycount) * 100.0 + 0.5);
else
FSimProgress = 0;
if (FLastProgress != FProgress && (forceupdate || FProgress % 5 == 0))
{
UpdateTotalSimulationProgress();
FLastProgress = Progress;
}
if (FLastSimProgress != FSimProgress && (forceupdate || FSimProgress % 10 == 0))
{
UpdateCurrentSimulationProgress();
FLastSimProgress = FSimProgress;
}
}
}
/// <summary>
///
/// </summary>
public void UpdateInputParametersForm()
{
// #ifdef GUI
// SendMessage(_MainForm.Handle, WM_UPDATEINPUTPARAMETERSFORM, 0, 0);
// #endif
}
/// <summary>
///
/// </summary>
public void UpdateCurrentSimulationProgress()
{
// #ifdef GUI
// int id=CurrentSimulationObject.ID;
// SendMessage(_MainForm.Handle, WM_UPDATECURRENTSIMULATIONPROGRESS, id, FSimProgress);
// #endif
}
/// <summary>
///
/// </summary>
public void UpdateTotalSimulationProgress()
{
// #ifdef GUI
// if(_MainForm)
// {
// int id=CurrentSimulationObject.ID;
// SendMessage(_MainForm.Handle, WM_UPDATETOTALSIMULATIONPROGRESS, id, FProgress );
// //SendMessage(_MainForm.Handle, WM_UPDATETOTALSIMULATIONPROGRESS2, id, FProgress );
// }
//
//// if(_MainForm)
//// {
//// _MainForm.ProgramManager.ActiveManager.CalculatingCaption="Simulating "+CurrentSimulationObject.ColumnText[0];
//// _MainForm.ProgramManager.ActiveManager.CalculationProgress=0;
//// }
// #endif
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void SetProgress(int value)
{
// if(value!=FProgress)
// {
// FProgress = value;
// if(value%5==0)
// Synchronize(PostProgressMessage);
//
// }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public int GetProgress()
{
return FProgress;
}
/// <summary>
///
/// </summary>
public void PostProgressMessage()
{
//if(FProgramManager.ActiveManager)
// {
// if(FProgress>0)
// {
// if(CurrentSimulationObject)
// FProgramManager.ActiveManager.CalculatingCaption="Simulating "+CurrentSimulationObject.ColumnText[0];
// }
// else
// FProgramManager.ActiveManager.CalculatingCaption="InitialisingException e ";
// FProgramManager.ActiveManager.CalculationProgress=FProgress;
//
// }
}
/// <summary>
///
/// </summary>
public void UpdateOutput()
{
//if (!FReset && FOnUpdateOutput)
//{
// FOnUpdateOutput();
//}
}
//TSimulateOutputObject* GetCurrentOutputObject()
//{
// // return CurrentSimulationObject.OutputObject;
//}
//void SetSimulationObjectsList(TList* value)
//{
// FSimulationObjectsList = value;
//}
//TList* GetSimulationObjectsList()
//{
// return FSimulationObjectsList;
//}
/// <summary>
///
/// </summary>
public void BeginUpdate()
{
// if(CurrentOutputObject)CurrentOutputObject.BeginUpdate();
// CurrentSimulationObject.ResetUsedState();
}
/// <summary>
///
/// </summary>
public void EndUpdate()
{
// if(CurrentSimulationObject&&CurrentOutputObject)
// {
// CurrentSimulationObject.Modified=false;
// for(int i=0;i<CropCount;++i)
// if(Crop[i])CurrentSimulationObject.VegetationDataTemplatePointer[i].IsUsedInSimulation=CurrentOutputObject.VegTimeSeriesHeader[i].toRootDepth.IsNonZero;
//
// CurrentSimulationObject.IrrigationDataTemplatePointer.IsUsedInSimulation=CurrentOutputObject.toIrrigation.IsNonZero;
// for(int i=0;i<PesticideCount;++i)
// CurrentSimulationObject.PesticideDataTemplatePointer[i].IsUsedInSimulation=CurrentOutputObject.PesticideTimeSeriesHeader[i].toPestInSoil_g_per_ha.IsNonZero;;
// for(int i=0;i<TillageCount;++i)
// CurrentSimulationObject.TillageDataTemplatePointer[i].IsUsedInSimulation=CurrentOutputObject.toResidueReductionFromTillage.IsNonZero;;
//
// }
}
/// <summary>
///
/// </summary>
public void EndOutputObjectUpdate()
{
// if(CurrentOutputObject)CurrentOutputObject.EndUpdate();
// if(CurrentSimulationObject&&ZerosList.Count>0)
// {
// ZerosList.Add("******* RECOMENDATIONS *********");
// ZerosList.Add("HowLeaky was able to continue simulating but you should be very wary of these results");
// if(ZerosList.Text>0&&ZerosList.Text<15)
// throw(new Exception(ZerosList.Text, mtWarning, TMsgDlgButtons() << mbOK, 0);
// else
// {
// // throw(new Exception("Many divide by zero errors ("+String(ZeroesList.Count)+")", mtWarning, TMsgDlgButtons() << mbOK, 0);
// SmartPointer<TStringList>list(new TStringList);
// for(int i=0;i<ZerosList.Count;++i)
// {
// if(i<15&&ZerosList.Strings[i].Length())
// list.Add(ZerosList.Strings[i]) ;
// }
// throw(new Exception(list.Text, mtWarning, TMsgDlgButtons() << mbOK, 0);
// }
// }
//// CurrentSimulationObject.Comments=ZerosList.Text;
}
/// <summary>
///
/// </summary>
public void UpdateStartMessages()
{
// #ifdef GUI
// Progress=0;
// if(FProgramManager&&FProgramManager.ActiveManager)
// FProgramManager.ActiveManager.IsCalculating=true;
// #endif
}
/// <summary>
///
/// </summary>
public void UpdateFinishMessages()
{
// #ifdef GUI
// FProgress=100.0;
// Synchronize(PostProgressMessage);
// if(FProgramManager&&FProgramManager.ActiveManager)
// FProgramManager.ActiveManager.IsCalculating=false;
// #endif
}
/// <summary>
///
/// </summary>
public void ResetParameters()
{
// if(CropList)CropList.Clear();
// CurrentSimulationObject=0;
// FSimulationObjectsList=0;
}
/// <summary>
///
/// </summary>
/// <param name="me"></param>
/// <param name="cropindex"></param>
public void UpdateManagementEventHistory(ManagementEvent me, int cropindex)
{
//if (CurrentOutputObject)
//{
// int index = me.GetHashCode();
// if (index > (int)ManagementEvent.meCropGrowing)
// {
// index = index - 6;
// index = 6 + (cropindex * 4) + index;
// }
// CurrentOutputObject.ManagementEvents[index]
// [seriesindex] = true;//GetManagementEventType();
// CurrentOutputObject.ManagementHistory.AddEvent(me, cropindex, year, month, day);
//}
}
/// <summary>
///
/// </summary>
public void RunOnFinishSimumulatingEvent()
{
// if(FOnFinishSimulating)
// FOnFinishSimulating();
}
/// <summary>
///
/// </summary>
public void CalculateMonthlyOutputs()
{
double simyears = number_of_days_in_simulation / 365.0;
for (int i = 0; i < 12; ++i)
{
mo_MthlyAvgRainfall_mm[i] = Divide(mo_MthlyAvgRainfall_mm[i], simyears);
mo_MthlyAvgEvaporation_mm[i] = Divide(mo_MthlyAvgEvaporation_mm[i], simyears);
mo_MthlyAvgTranspiration_mm[i] = Divide(mo_MthlyAvgTranspiration_mm[i], simyears);
mo_MthlyAvgRunoff_mm[i] = Divide(mo_MthlyAvgRunoff_mm[i], simyears);
mo_MthlyAvgDrainage_mm[i] = Divide(mo_MthlyAvgDrainage_mm[i], simyears);
}
}
/// <summary>
///
/// </summary>
public void CalculateSummaryOutputs()
{
double simyears = number_of_days_in_simulation / 365.0;
so_YrlyAvgRainfall_mm_per_yr = Divide(sum_rainfall, simyears);
so_YrlyAvgIrrigation_mm_per_yr = Divide(sum_irrigation, simyears);
so_YrlyAvgRunoff_mm_per_yr = Divide(sum_runoff, simyears);
so_YrlyAvgSoilEvaporation_mm_per_yr = Divide(sum_soilevaporation, simyears);
so_YrlyAvgTranspiration_mm_per_yr = Divide(sum_transpiration, simyears);
so_YrlyAvgEvapotransp_mm_per_yr = Divide(sum_evapotranspiration, simyears);
so_YrlyAvgOverflow_mm_per_yr = Divide(sum_overflow, simyears);
so_YrlyAvgDrainage_mm_per_yr = Divide(sum_drainage, simyears);
so_YrlyAvgLateralFlow_mm_per_yr = Divide(sum_lateralflow, simyears);
so_YrlyAvgSoilErosion_T_per_ha_per_yr = Divide(sum_soilerosion, simyears);
so_YrlyAvgOffsiteSedDel_T_per_ha_per_yr = Divide(sum_soilerosion * in_SedDelivRatio, simyears);
so_TotalCropsPlanted = VegetationController.GetTotalCropsPlanted();
so_TotalCropsHarvested = VegetationController.GetTotalCropsHarvested();
so_TotalCropsKilled = VegetationController.GetTotalCropsKilled();
so_AvgYieldPerHrvst_t_per_ha_per_hrvst = VegetationController.GetAvgYieldPerHarvest();
so_AvgYieldPerPlant_t_per_ha_per_plant = VegetationController.GetAvgYieldPerPlanting();
so_AvgYieldPerYr_t_per_ha_per_yr = VegetationController.GetAvgYieldPerYear();
so_YrlyAvgCropRainfall_mm_per_yr = Divide(sum_crop_rainfall, simyears);
so_YrlyAvgCropIrrigation_mm_per_yr = Divide(sum_crop_irrigation, simyears);
so_YrlyAvgCropRunoff_mm_per_yr = Divide(sum_crop_runoff, simyears);
so_YrlyAvgCropSoilEvap_mm_per_yr = Divide(sum_crop_soilevaporation, simyears);
so_YrlyAvgCropTransp_mm_per_yr = Divide(sum_crop_transpiration, simyears);
so_YrlyAvgCropEvapotransp_mm_per_yr = Divide(sum_crop_evapotranspiration, simyears);
so_YrlyAvgCropOverflow_mm_per_yr = Divide(sum_crop_overflow, simyears);
so_YrlyAvgCropDrainage_mm_per_yr = Divide(sum_crop_drainage, simyears);
so_YrlyAvgCropLateralFlow_mm_per_yr = Divide(sum_crop_lateralflow, simyears);
so_YrlyAvgCropSoilErosion_T_per_ha_per_yr = Divide(sum_crop_soilerosion, simyears);
so_YrlyAvgCropOffsiteSedDel_T_per_ha_per_yr = Divide(sum_crop_soilerosion * in_SedDelivRatio, simyears);
so_YrlyAvgFallowRainfall_mm_per_yr = Divide(sum_fallow_rainfall, simyears);
so_YrlyAvgFallowIrrigation_mm_per_yr = Divide(sum_fallow_irrigation, simyears);
so_YrlyAvgFallowRunoff_mm_per_yr = Divide(sum_fallow_runoff, simyears);
so_YrlyAvgFallowSoilEvap_mm_per_yr = Divide(sum_fallow_soilevaporation, simyears);
so_YrlyAvgFallowOverflow_mm_per_yr = Divide(sum_fallow_overflow, simyears);
so_YrlyAvgFallowDrainage_mm_per_yr = Divide(sum_fallow_drainage, simyears);
so_YrlyAvgFallowLateralFlow_mm_per_yr = Divide(sum_fallow_lateralflow, simyears);
so_YrlyAvgFallowSoilErosion_T_per_ha_per_yr = Divide(sum_fallow_soilerosion, simyears);
so_YrlyAvgFallowOffsiteSedDel_T_per_ha_per_yr = Divide(sum_fallow_soilerosion * in_SedDelivRatio, simyears);
fallow_efficiency = Divide(sum_fallow_soilwater * 100.0, sum_fallow_rainfall);
so_YrlyAvgPotEvap_mm = Divide(sum_potevap, simyears);
so_YrlyAvgRunoffAsPercentOfInflow_pc = Divide(so_YrlyAvgRunoff_mm_per_yr * 100.0, so_YrlyAvgRainfall_mm_per_yr + so_YrlyAvgIrrigation_mm_per_yr);
so_YrlyAvgEvapAsPercentOfInflow_pc = Divide(so_YrlyAvgSoilEvaporation_mm_per_yr * 100.0, so_YrlyAvgRainfall_mm_per_yr + so_YrlyAvgIrrigation_mm_per_yr);
so_YrlyAvgTranspAsPercentOfInflow_pc = Divide(so_YrlyAvgTranspiration_mm_per_yr * 100.0, so_YrlyAvgRainfall_mm_per_yr + so_YrlyAvgIrrigation_mm_per_yr);
so_YrlyAvgDrainageAsPercentOfInflow_pc = Divide(so_YrlyAvgDrainage_mm_per_yr * 100.0, so_YrlyAvgRainfall_mm_per_yr + so_YrlyAvgIrrigation_mm_per_yr);
so_YrlyAvgPotEvapAsPercentOfInflow_pc = Divide(so_YrlyAvgPotEvap_mm * 100.0, so_YrlyAvgRainfall_mm_per_yr + so_YrlyAvgIrrigation_mm_per_yr);
so_YrlyAvgCropSedDel_t_per_ha_per_yr = Divide(accumulated_crop_sed_deliv, simyears);
so_YrlyAvgFallowSedDel_t_per_ha_per_yr = Divide(accumulated_fallow_sed_deliv, simyears);
so_RobinsonErrosionIndex = Divide(so_YrlyAvgSoilErosion_T_per_ha_per_yr * so_YrlyAvgCover_pc, in_FieldSlope_pc);
so_YrlyAvgCover_pc = Divide(accumulated_cover, number_of_days_in_simulation);
so_YrlyAvgFallowDaysWithMore50pcCov_days = Divide(fallow_days_with_more_50pc_cov * 100.0, number_of_days_in_simulation);
so_AvgCoverBeforePlanting_pc = Divide(accumulate_cov_day_before_planting * 100.0, total_number_plantings);
so_SedimentEMCBeoreDR = -32768;
so_SedimentEMCAfterDR = -32768;
so_AvgSedConcInRunoff = Divide(sum_soilerosion * in_SedDelivRatio * 100.0, sum_runoff);//for g/L
}
public double Divide(double num, double denom)
{
return num / denom;
}
//bool LoadInputParameters(TSimulationInputObject* inputobject)
//{
// CurrentInputObject = inputobject;
// // if( LoadClimateData(inputobject.LocationData))
// {
// // LoadSoilInputParameters(inputobject.SoilData);
// //
// // IrrigationController. LoadInputParameters(inputobject.IrrigationData);
// // VegetationController. LoadInputParameters(inputobject.VegetationData);
// // TillageController. LoadInputParameters(inputobject.TillageData);
// // PesticideController. LoadInputParameters(inputobject.PesticideData);
// // PhosphorusController. LoadInputParameters(inputobject.PhosphorusData);
// // NitrateController. LoadInputParameters(inputobject.NitrateData);
// // SolutesController. LoadInputParameters(inputobject.SoluteData);
// // OptionsController. LoadInputParameters(inputobject.ModelOptionsData);
// LoadStartEndDates(inputobject);
// }
//}
//bool LoadClimateData(TSimTemplateGroup<TTimeSeriesDataTemplate>* locationdata)
//{
// try
// {
// // TLocationObjectLock lock;
// // if(DataFileObject)
// // {
// // LoadTemplateData(FileName);
// // if(FDataFileObject.TimeSeriesCount>4&&FDataFileObject.DataIsLoaded)
// // {
// // Latitude = Latitude;
// // MaxTemp = FDataFileObject.GetBaseValuesPtr(0,false);
// // MinTemp = FDataFileObject.GetBaseValuesPtr(1,false);
// // Rainfall = FDataFileObject.GetBaseValuesPtr(2,true);
// // Evaporation = FDataFileObject.GetBaseValuesPtr(3,true);
// // SolarRadiation = FDataFileObject.GetBaseValuesPtr(4,false);
// // return true;
// // }
// // }
// }
// catch (Exception e)
// {
// }
// return false;
//}
public bool LoadSoilInputParameters(Object soildata)
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="inputobject"></param>
/// <returns></returns>
public bool LoadStartEndDates(Object inputobject)
{
return false;
}
/// <summary>
///
/// </summary>
public void ResetToDefault()
{
ModelOptionsController.in_ResetSoilWaterAtDate = false;
ModelOptionsController.in_ResetResidueAtDate = false;
ModelOptionsController.in_ResetSoilWaterAtPlanting = false;
ModelOptionsController.in_CanCalculateLateralFlow = false;
ModelOptionsController.in_UsePERFECTGroundCovFn = false;
ModelOptionsController.in_IgnoreCropKill = false;
ModelOptionsController.in_UsePERFECTDryMatterFn = false;
ModelOptionsController.in_UsePERFECTLeafAreaFn = false;
ModelOptionsController.in_UsePERFECT_USLE_LS_Fn = true;
ModelOptionsController.in_UsePERFECTResidueFn = false;
ModelOptionsController.in_UsePERFECTSoilEvapFn = false;
ModelOptionsController.in_UsePERFECTCurveNoFn = Simulation.DEFAULT_CN;
ModelOptionsController.in_InitialPAW = 0.5;
}
/// <summary>
///
///
///
///
///
///
///
///
///
///
///
///
/// </summary>
////Ignore this for serialisation
//public Project parent;
////Ignore this for serialisation
//public List<string> modelPaths;
////Ignore this for serialisation
//public bool active { get; set; } = false;
//public List<DataModel> dataModels;
////Ignore this for serialisation
////public List<ModelControllers> modelControllers;
//public Simulation()
//{
// modelPaths = new List<string>();
// dataModels = new List<DataModel>();
//}
//public Simulation(Project parent) : this()
//{
// this.parent = parent;
//}
//public Simulation(List<DataModel> dataModels) : this()
//{
// //Assume how this is coing to come from Client/Server Comms doesn't neccessarily need a parent project
// //Work out which model is which by type - if possible after serialization
// this.dataModels = dataModels;
//}
//public void createFromXMLNode(XmlNode node)
//{
// //Populate the DataModels
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TwingateExrc.Tests
{
public static class FragmentationTest
{
public static void Run()
{
Console.WriteLine("Fragmentation tests start:");
var m = new MemoryManager(5);
m.Allocate('1', 0);
m.Allocate('1', 1);
m.Allocate('1', 2);
m.Free(0);
m.Free(2);
m.Allocate(new[] { '2', '2' }, 0);
if (m.Buffer[0] == '2' && m.Buffer[1] == '1' && m.Buffer[2] == '2')
{
Console.WriteLine(" passed");
}
else
{
Console.WriteLine("failed");
}
}
}
}
|
using UnityEngine;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Event Reference Listener of type `ColliderGameObject`. Inherits from `AtomEventReferenceListener<ColliderGameObject, ColliderGameObjectEvent, ColliderGameObjectEventReference, ColliderGameObjectUnityEvent>`.
/// </summary>
[EditorIcon("atom-icon-orange")]
[AddComponentMenu("Unity Atoms/Listeners/ColliderGameObject Event Reference Listener")]
public sealed class ColliderGameObjectEventReferenceListener : AtomEventReferenceListener<
ColliderGameObject,
ColliderGameObjectEvent,
ColliderGameObjectEventReference,
ColliderGameObjectUnityEvent>
{ }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.