text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PDV.DAO.Enum
{
public class StatusConta
{
public static readonly int Cancelado = 0;
public static readonly int Aberto = 1;
public static readonly int Parcial = 2;
public static readonly int Baixado = 3;
}
}
|
using CRUDXamarin_BL.Handler;
using CRUDXamarin_BL.List;
using CRUDXamarin_Ent;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Xamarin.Forms;
namespace CRUDXamarin.viewModels
{
public class VMMainPage : clsVMBase
{
private ObservableCollection<clsPersona> listadoPersonas;
private clsPersona _personaSeleccionada;
private clsPersona _personaAux { get; set; }
public ObservableCollection<clsPersona> ListadoPersonas
{
get {
//cargarListados();
return this.listadoPersonas;
}
set { this.listadoPersonas = value; }
}
public DelegateCommand DeleteCommand
{
get;
}
public DelegateCommand SaveCommand
{
get;
}
private async void ExecuteDeleteCommand()
{
var answer = await Application.Current.MainPage.DisplayAlert("Delete", "Do you want to delete this element?", "Yes", "No");
if (answer)
{
//TODO
}
if (answer)
{
//Se procede a la borración
//Aqui va el codigo de delete
//this._listadoPersonas.Remove((this._personaSeleccionada)); //Esto no puede ser asi porque persona seleccionada no es un item de listado Personas
clsGestionPersonasBL gestionPersonasBl = new clsGestionPersonasBL();
try
{
if (await gestionPersonasBl.eliminarPersona(this._personaSeleccionada) == 1)
{
cargarListados();
this._personaSeleccionada = null;
NotifyPropertyChanged("PersonaSeleccionada");
}
}
catch (Exception)
{
falloConexion();
}
}
}
private bool CanExecuteDeleteCommand()
{
bool habilitado = true;
if (this._personaSeleccionada == null)
{
habilitado = false;
}
return habilitado;
}
public clsPersona PersonaAux
{
get
{
NotifyPropertyChanged("PersonaSeleccionada");
return this._personaAux;
}
set
{
this._personaSeleccionada = value;
}
}
public clsPersona PersonaSeleccionada
{
get
{
try
{
if (this._personaSeleccionada != null)
{
clsListadosPersonaBL listadosPersonaBL = new clsListadosPersonaBL();
clsPersona personaReal = listadosPersonaBL.obtenerObjetoPersonaPorID(this._personaSeleccionada.idPersona);
}
}
catch (Exception e)
{
}
return this._personaSeleccionada;
}
set
{
if (_personaSeleccionada != value)//esto solo se necesita si usas xBind
{
this._personaSeleccionada = value;
DeleteCommand.RaiseCanExecuteChanged();
//SaveCommand.RaiseCanExecuteChanged();
NotifyPropertyChanged("PersonaSeleccionada");
}
}
}
public VMMainPage()
{
try
{
cargarListados(); //esto esta mal
NotifyPropertyChanged("ListadoPersonas");
}
catch (Exception e)
{
//Mostrar algo para cuando falle la conexion (ej- un dialog)
falloConexion();
}
//this._personaSeleccionada = new clsPersona();
this._personaAux = new clsPersona();
this.DeleteCommand = new DelegateCommand
(ExecuteDeleteCommand, CanExecuteDeleteCommand);
}
private async void cargarListados()
{
try
{
this.listadoPersonas = new ObservableCollection<clsPersona>
(await new clsListadosPersonaBL().listadoPersonasOrdinario());
NotifyPropertyChanged("ListadoPersonas");
}
catch (Exception e)
{
falloConexion();
}
}
private async void falloConexion()
{
await Application.Current.MainPage.DisplayAlert(
"Alert",
"Alerta mannn",
"OK"
);
return;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Docs.v1;
using Google.Apis.Docs.v1.Data;
using Google.Apis.Services;
namespace Isshiki
{
public class GoogleDocsRecipeSource : IDisposable
{
private const string ApplicationName = "Isshiki";
private const string RecipesDocumentId = "1wuf_9JDuW3kKBTdPgoISmZspB4CTF8Om7qagRCzQNxc";
private readonly DocsService docsService;
public GoogleDocsRecipeSource(string jsonCredential)
{
var credential = GoogleCredential
.FromJson(jsonCredential)
.CreateScoped(DocsService.ScopeConstants.DocumentsReadonly)
.UnderlyingCredential as ServiceAccountCredential;
docsService = new DocsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
}
public async Task<List<Recipe>> GetRecipesAsync()
{
var request = docsService.Documents.Get(RecipesDocumentId);
var doc = await request.ExecuteAsync();
var result = new List<Recipe>();
Recipe currentRecipe = null;
foreach (var se in doc.Body.Content)
{
if (se.Paragraph == null)
{
continue;
}
var p = se.Paragraph;
var isNewRecipeStart = IsHeader2(p);
if (isNewRecipeStart)
{
if (currentRecipe != null)
{
FinalizeRecipe(currentRecipe);
result.Add(currentRecipe);
}
currentRecipe = new Recipe
{
Name = p.Elements.FirstOrDefault()?.TextRun?.Content?.Trim()
};
}
else
{
AddToCurrentRecipe(currentRecipe, p);
}
}
if (currentRecipe != null)
{
FinalizeRecipe(currentRecipe);
result.Add(currentRecipe);
}
return result;
}
private void FinalizeRecipe(Recipe currentRecipe)
{
currentRecipe.Text = currentRecipe.Text.Trim();
ComputeTags(currentRecipe);
}
private void ComputeTags(Recipe recipe)
{
var regex = new Regex(@"#\w+");
recipe.Tags = regex
.Matches(recipe.Text)
.Select(m => m.Value)
.Distinct()
.ToArray();
}
private void AddToCurrentRecipe(Recipe currentRecipe, Paragraph paragraph)
{
var sb = new StringBuilder();
foreach (var element in paragraph.Elements)
{
if (element.TextRun == null)
{
continue;
}
sb.Append(element.TextRun.Content);
}
currentRecipe.Text += sb.ToString();
}
private bool IsHeader2(Paragraph paragraph)
{
return paragraph.ParagraphStyle.NamedStyleType == "HEADING_2";
}
public void Dispose()
{
docsService.Dispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FinanceApp
{
public class Expense : Transaction
{
public Expense()
{
}
public Expense(String expenseTitle, DateTime date, float amount, Contact payee)
{
this.expenseTitle = expenseTitle;
this.date = date;
this.amount = amount;
this.payee = payee;
}
public String expenseTitle { get; set; }
public DateTime date { get; set; }
public float amount { get; set; }
public Contact payee {get; set; }
public void Store()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Accounting.Utility
{
public class NullManager
{
public NullManager() { }
public NullManager(IDataReader objReader)
{
_objReader = objReader;
}
#region Fields
private IDataReader _objReader;
#endregion
#region methods
public bool GetBoolean(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? false : _objReader.GetBoolean(i);
}
public byte GetByte(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? (byte)0 : _objReader.GetByte(i);
}
public Int16 GetInt16(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? (Int16)0 : _objReader.GetInt16(i);
}
public Int32 GetInt32(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return (_objReader.IsDBNull(i)) ? 0 : _objReader.GetInt32(i);
}
public Int64 GetInt64(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? 0 : _objReader.GetInt64(i);
}
public decimal GetDecimal(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? 0 : _objReader.GetDecimal(i);
}
public float GetFloat(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? 0 : _objReader.GetFloat(i);
}
public double GetDouble(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? 0 : _objReader.GetDouble(i);
}
public double GetMoney(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? 0 : Convert.ToDouble(_objReader.GetValue(i));
}
public DateTime GetDateTime(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? DateTime.Now : _objReader.GetDateTime(i);
}
public char GetChar(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? Convert.ToChar(string.Empty) : _objReader.GetChar(i);
}
public string GetString(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? "" : _objReader.GetString(i);
}
public byte[] GetBytes(string sColumnName)
{
int i = _objReader.GetOrdinal(sColumnName);
return _objReader.IsDBNull(i) ? null : (byte[])_objReader.GetValue(i);
}
#endregion
}
}
|
using System;
using System.Globalization;
namespace Aula89DateTime
{
class Program
{
static void Main(string[] args)
{
//Most Used Constructors
DateTime d1 = new DateTime(2021, 10, 27); //date. time is 00:00:00.
Console.WriteLine(d1);
DateTime d2 = new DateTime(2021, 10, 27, 14, 45, 03); //date and time.
Console.WriteLine(d2);
DateTime d3 = new DateTime(2021, 10, 27, 14, 45, 03, 500); //date and time with milliseconds.
Console.WriteLine(d3);
//Most Used Builders
DateTime date = DateTime.Now; // Current Date & Time
DateTime date2 = DateTime.Today;
DateTime date3 = DateTime.UtcNow; // GMT time.
Console.WriteLine(date);
Console.WriteLine(date2);
Console.WriteLine(date3);
//Parse. Provide date & time
DateTime dateParse = DateTime.Parse("2021-10-27"); //DataBase format. yyyy-MM-dd
DateTime dateParse2 = DateTime.Parse("2021-10-27 14:59:50");
DateTime dateParse3 = DateTime.Parse("27/10/2021");
DateTime dateParse4 = DateTime.Parse("2021/10/27 15:00:00");
Console.WriteLine("Date Parse 1: " + dateParse);
Console.WriteLine("Date Parse 2: " + dateParse2);
Console.WriteLine("Date Parse 3: " + dateParse3);
Console.WriteLine("Date Parse 4: " + dateParse4);
//ParseExact - Format Mask
DateTime dateExact = DateTime.ParseExact("2021-08-15", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine("1 - Date Parse Exact: " + dateParse);
DateTime dateExact2 = DateTime.ParseExact("27/10/2021 15:08:50", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine("2 - Date Parse Exact: " + dateParse);
}
}
}
|
using AnnealingWPF.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace AnnealingWPF.Solver.TryStrategies
{
public class RandomTryStrategy : TryStrategy
{
public RandomTryStrategy(int seed) : base(seed)
{
}
//Performs a random bit-flip
public override bool Try(SimulatedAnnealingSolver solverInstance, ref SatConfiguration currentConfiguration)
{
var bitToFlip = random.Next(0, solverInstance.SatInstance.Literals.Count - 1);
var triedConfiguration = new SatConfiguration(currentConfiguration);
triedConfiguration.Valuations[bitToFlip] = !triedConfiguration.Valuations[bitToFlip];
triedConfiguration.Score = solverInstance.Options.ScoreStrategy.CalculateScore(triedConfiguration, solverInstance);
if(Accept(triedConfiguration, currentConfiguration, solverInstance.CurrentTemperature))
{
currentConfiguration = triedConfiguration;
return true;
}
return false;
}
}
}
|
using System.Text.Json.Serialization;
using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json;
using PlatformRacing3.Server.Game.Lobby;
namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json;
internal sealed class JsonMatchesOutgoingMessage : JsonPacket
{
private protected override string InternalType => "receiveMatches";
[JsonPropertyName("lobbyId")]
public uint LobbyId { get; set; }
[JsonPropertyName("matches")]
public IReadOnlyCollection<IReadOnlyDictionary<string, object>> Matches { get; set; }
internal JsonMatchesOutgoingMessage(uint lobbyId, IReadOnlyCollection<MatchListing> matchListings)
{
this.LobbyId = lobbyId;
List<IReadOnlyDictionary<string, object>> matches = new();
foreach(MatchListing matchListing in matchListings)
{
matches.Add(matchListing.GetVars("*"));
}
this.Matches = matches;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class AssemblyHelper
{
public static bool IsRunningUnderTest=> AppDomain.CurrentDomain.GetAssemblies().Any(ass => ass.FullName.StartsWith("Microsoft.VisualStudio.TestPlatform"));
}
|
using System.Collections.Generic;
using Entities;
using DataAccess;
using System.Threading.Tasks;
namespace BusinessLayer
{
public class MedicamentoBL
{
public static List<Medicamento> ListaMedicamentos;
// METODOS
public async Task<List<Medicamento>> GetListaMedicamentosAsync()
{
MedicamentoDAL dal = new MedicamentoDAL();
ListaMedicamentos = await dal.GetMedicamentosAsync();
return ListaMedicamentos;
}
public async Task<Medicamento> BuscarMedicamentoAsync(string CodMedicamento)
{
MedicamentoDAL dal = new MedicamentoDAL();
Medicamento medicamento = new Medicamento();
ListaMedicamentos = await dal.GetMedicamentosAsync();
bool flag = false;
foreach (var item in ListaMedicamentos)
{
if (item.CodMedicamento == CodMedicamento)
{
flag = true;
medicamento = item;
break;
}
}
if (flag)
return medicamento;
else
medicamento = null;
return medicamento;
}
public async Task<int> InsertarMedicamentoAsync(Medicamento medicamento)
{
MedicamentoDAL dal = new MedicamentoDAL();
return await dal.InsertarMedicamentoAsync(medicamento);
}
public async Task<int> UpdateMedicamentoAsync(Medicamento medicamento)
{
MedicamentoDAL dal = new MedicamentoDAL();
return await dal.UpdateMedicamentoAsync(medicamento);
//return alumno;
}
public async Task<int> EliminarMedicamentoAsync(string CodMedicamento)
{
MedicamentoDAL dal = new MedicamentoDAL();
return await dal.EliminarMedicamentoAsync(CodMedicamento);
//return alumno;
}
}
}
|
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace DotNetCoreSwagger
{
//Listify implements the IList interface to get an IEnmunerable (an unstructured array) to act like a List (a well defined, structured array)
public class Listify : IList<int>
{
public int Start = 10;
public int End = 20;
IEnumerable<int> oIEnumerable;
public Listify()
{
oIEnumerable = Enumerable.Range(Start, End).Select(x => x);
}
public Listify(int pStart, int pEnd)
{
Start = pStart;
End = pEnd;
oIEnumerable = Enumerable.Range(Start, End).Select(x => x);
}
readonly IList<int> _list = new List<int>();
public int this[int index] { get => oIEnumerable.ElementAt<int>(index); set => throw new NotImplementedException(); }
public int Count => Math.Abs(End - Start);
public bool IsReadOnly => throw new NotImplementedException();
public void Add(int item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(int item)
{
throw new NotImplementedException();
}
public void CopyTo(int[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public IEnumerator<int> GetEnumerator()
{
return oIEnumerable.GetEnumerator();
}
public int IndexOf(int item)
{
throw new NotImplementedException();
}
public void Insert(int index, int item)
{
throw new NotImplementedException();
}
public bool Remove(int item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return oIEnumerable.GetEnumerator();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FoodBehavior : MonoBehaviour {
public void Update() {
Quaternion rot = gameObject.transform.rotation;
float spd = Random.Range(0f, 5f);
rot.x += Mathf.Cos(rot.x * rot.z) * spd;
rot.y += Mathf.Sin(rot.x) * spd;
rot.z += 1.5f * spd;
gameObject.transform.Rotate(rot.x, rot.y, rot.z, Space.World);
}
public void OnTriggerEnter(Collider collision) {
collision.gameObject.GetComponent<PlayerBehavior>().addFood();
collision.gameObject.GetComponent<PlayerBehavior>().randomRoute();
Destroy(gameObject);
}
}
|
using System.Windows.Forms;
namespace TrafficDissector.Visualization
{
internal static class StatusStripVisualizer
{
internal static void SetLabelText(string itemName, string text, StatusStrip statusStrip)
{
statusStrip.Items[itemName].Text = text;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airfield_Simulator.Core.Models
{
public class SimulationProperties : ISimulationProperties
{
public event PropertyChangedEventHandler PropertyChanged;
private double _simulationSpeed;
public double SimulationSpeed
{
get
{
return _simulationSpeed;
}
set
{
_simulationSpeed = value;
NotifyPropertyChanged("SimulationSpeed");
}
}
private int _instructionsPerMinute;
public int InstructionsPerMinute
{
get
{
return _instructionsPerMinute;
}
set
{
_instructionsPerMinute = value;
NotifyPropertyChanged("InstructionsPerMinute");
}
}
private int _aircraftSpawnsPerMinute;
public int AircraftSpawnsPerMinute
{
get
{
return _aircraftSpawnsPerMinute;
}
set
{
_aircraftSpawnsPerMinute = value;
NotifyPropertyChanged("AircraftSpawnsPerMinute");
}
}
private int _aircraftSpeed;
public int AircraftSpeed
{
get
{
return _aircraftSpeed;
}
set
{
_aircraftSpeed = value;
NotifyPropertyChanged("AircraftSpeed");
}
}
private void NotifyPropertyChanged(string prop)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
}
|
//Problem 10. Employee Data
//A marketing company wants to keep record of its employees. Each record would have the following characteristics:
// First name
// Last name
// Age (0...100)
// Gender (m or f)
// Personal ID number (e.g. 8306112507)
// Unique employee number (27560000…27569999)
//Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console.
using System;
namespace Problem10EmployeeData
{
class EmployeeData
{
static void Main()
{
string firstName, lastName;
byte age;
bool isMale;
long personalIdNumber;
int uniqueNumber;
firstName = "Ivan";
lastName = "Ivanov";
age = 18;
isMale = true;
personalIdNumber = 9601035487;
uniqueNumber = 27560001;
Console.WriteLine("Name: "+ firstName + " " +lastName);
Console.WriteLine("Age: " + age);
Console.WriteLine("Gender: " + (isMale == true ? "M" : "F"));
Console.WriteLine("Personal Number: " + personalIdNumber);
Console.WriteLine("Work Number: " + uniqueNumber);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Controle.Domain.Entities;
using FluentNHibernate.Mapping;
namespace Controle.Domain.Mappings
{
public sealed class SaidaMap :ClassMap<Saida>
{
public SaidaMap()
{
Id(x => x.Codigo);
Map(x => x.DataPagamento);
Map(x => x.DataVencimento);
Map(x => x.Nome);
Map(x => x.Valor);
References(x => x.Usuario);
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tree;
using Infra;
namespace AlgTest
{
[TestClass]
public class TreeTest
{
[TestMethod]
public void TestConvertBinaryTreeToDll()
{
ConvertBinaryTreeToDll target = new ConvertBinaryTreeToDll();
TreeNode root = TreeNode.CreatTree(new string[] { "1", "#", "5", "#", "-7", "#", "#" });
TreeNode actual = target.Convert(root);
TreeNode.index = 0;
root = TreeNode.CreatTree(new string[] { "4", "5", "-7", "#", "#", "#", "6", "#", "#" });
actual = target.Convert(root);
Assert.AreEqual(-7, actual.Value);
Assert.AreEqual(5, actual.RightChild.Value);
Assert.AreEqual(4, actual.RightChild.RightChild.Value);
Assert.AreEqual(6, actual.RightChild.RightChild.RightChild.Value);
}
}
}
|
using Modelos.Cadastros.Produtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modelos.Formulas
{
public class EstruturaProduto
{
public virtual int Id { get; set; }
public virtual int Nivel { get; set; }
public virtual string Filial { get; set; }
public virtual string Componente { get; set; }
public virtual string DescricaoComponente { get; set; }
public virtual string Produto { get; set; }
public virtual string Tipo { get; set; }
public virtual string Unidade { get; set; }
public virtual string CentroCustoProduto { get; set; }
public virtual string CentroCustoComponente { get; set; }
public virtual double PercentualFormula { get; set; }
public virtual double Rendimento { get; set; }
public virtual double UltimoCustoMedio { get; set; }
public virtual double CustoMedioUnitario
{
get
{
return UltimoCustoMedio * (PercentualFormula / 100);
}
}
public virtual double CustoMateriPrima { get; set; }
public virtual double DespesaOperacional { get; set; }
public virtual double CustoTotalComponente
{
get
{
return this.CustoMateriPrima * (this.PercentualFormula / 100);
}
}
}
}
|
using CT.UI;
using CT.Net;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CT.Data;
using CT.UI.Training;
using CT.UI.Army;
namespace CT.Manager
{
public class InteractManager : UIManager
{
public enum InteractMode { Interact, Upgrade }
public InteractMode interactMode;
public Sprite interactIcon, upgradeIcon;
public Image interactModeImage;
public GameObject gridUI;
public static InteractManager instance;
protected override KeyCode ActivationKey => KeyCode.I;
InteractGridManager gridManager;
ConstructionManager constructionManager;
Base _base;
protected override void Awake()
{
base.Awake();
instance = this;
}
protected override void Start()
{
base.Start();
gridManager = InteractGridManager.instance;
constructionManager = ConstructionManager.instance;
_base = Base.active;
}
bool Upgrade(bool withResources)
{
if (!constructionManager.IsAvailable) return false;
var building = gridManager.SelectedBuilding;
var instanceData = building.BaseInstanceData;
if (instanceData.BaseNextData.hallLevelNeeded > _base.MainHall.InstanceData.level) return false;
//var data = building.data;
//int x = instanceData.tileX;
//int y = instanceData.tileY;
Vector3 pos = building.transform.position;
Quaternion rot = building.transform.rotation;
GameTime time;
int gold = 0, elixir = 0, gems = 0;
var player = GameManager.Player;
if (withResources)
{
gold = instanceData.UpgradeCostGold;
elixir = instanceData.UpgradeCostElixir;
time = instanceData.UpgradeTime;
if (_base.Gold < gold || _base.Elixir < elixir) return false;
ClientSend.SubtractResources(_base.Data.ID, gold, elixir);
}
else
{
gems = instanceData.UpgradeCostGems;
time = GameTime.Second;
if (player.gems < gems) return false;
ClientSend.SubtractGems(player.username, gems);
player.gems -= gems;
}
gridManager.OnUpgrade();
var conData = new ConstructionData(instanceData, time);
constructionManager.Init(conData);
return true;
}
void TryToUpgrade(bool normally)
{
bool upgraded = Upgrade(normally);
if (upgraded) Disable();
else Debug.Log("Failed to Upgrade!"); //to do some kind of ui
}
public void UpgradeWithResources()
{
TryToUpgrade(true);
}
public void UpgradeWithGems()
{
TryToUpgrade(false);
}
public void CancelConstruction(bool fromUpgrade)
{
var construction = gridManager.SelectedConstruction;
construction.Cancel();
Disable();
}
public void RushConstruction(bool fromUpgrade)
{
var construction = gridManager.SelectedConstruction;
construction.Rush();
Disable();
}
protected override void OnUIToggled()
{
if (on)
{
gridUI.SetActive(true);
interactMode = InteractMode.Interact;
interactModeImage.sprite = interactIcon;
}
else Disable();
}
public void SwitchInteractMode()
{
switch (interactMode)
{
case InteractMode.Interact:
interactMode = InteractMode.Upgrade;
interactModeImage.sprite = upgradeIcon;
break;
case InteractMode.Upgrade:
interactMode = InteractMode.Interact;
interactModeImage.sprite = interactIcon;
break;
}
}
public void Cancel()
{
Disable();
}
void OnDisable()
{
Disable();
}
protected override void Disable()
{
base.Disable();
if(ui != null) ui.SetActive(false);
if(gridManager != null) gridManager.Deactivate();
if(TrainingUI.instance != null) TrainingUI.instance.Deactivate();
if(ArmyUI.instance != null) ArmyUI.instance.Deactivate();
}
}
} |
namespace RoboBank.Merchant.Application
{
public class MerchantWebsiteInfo
{
public string WebsiteKey { get; set; }
public string SecretKey { get; set; }
public string CustomerId { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class BatteryDropArea : MonoBehaviour {
[SerializeField] Robot robot;
[SerializeField] SpriteRenderer spriteRenderer;
int chargeCount;
[SerializeField] Sprite zeroChargesSprite;
[SerializeField] Sprite oneChargeSprite;
[SerializeField] Sprite twoChargesSprite;
[SerializeField] Sprite threeChargesSprite;
public void addCharge() {
chargeCount += 1;
if (chargeCount >= 3) {
robot.becomeActive();
StartCoroutine(resetChargesRoutine());
} else if (chargeCount == 2) {
robot.becomeCharged(false);
} else {
robot.becomeCharged(true);
}
updateChargeCountDisplay();
}
IEnumerator resetChargesRoutine() {
yield return new WaitForSeconds(4);
chargeCount = 0;
updateChargeCountDisplay();
}
void updateChargeCountDisplay() {
switch (chargeCount) {
case 0: spriteRenderer.sprite = zeroChargesSprite; break;
case 1: spriteRenderer.sprite = oneChargeSprite; break;
case 2: spriteRenderer.sprite = twoChargesSprite; break;
case 3: default: spriteRenderer.sprite = threeChargesSprite; break;
}
}
void OnValidate() {
if (spriteRenderer == null) { spriteRenderer = GetComponent<SpriteRenderer>(); }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ManagerSoftware.CoreEngine
{
class Engine
{
public Engine()
{
}
private Employee funcionario;
public Queue<Archive> InsertQueue(string name, string email, string contact, List<Archive> list)
{
funcionario = new Director(name,email,contact);
funcionario.Save(list);
// devolve a estrutura de dados de Archive associada ao funcionario (p.e. funcionario.GetList())
return (Director) funcionario).GetStructure();
}
public Stack<Archive> InsertStack(string name, string email, string contact, List<Archive> list)
{
funcionario = new Salesman(name, email, contact);
funcionario.Send(list);
// devolve a estrutura de dados de Archive associada ao funcionaario (p.e. funcionario.GetList())
((Salesman)funcionario).SaveData(list);
return new Stack<Archive>(list);
}
public List<Archive> Send()
{
//chama o método send do funcionario e devolve a lista retomada
List<Archive> list = funcionario.Send();
return new List<Archive>();
}
public void Reset()
{
funcionario = null;
//Limpa a informação armazenada (i.e. atributos no Engine e no Funcionário)
}
}
} |
using MarsRover.BLL.Concrete;
using MarsRover.Model.Concrete;
using MarsRover.Model.Constant;
using System;
namespace MarsRoverCase
{
class Program
{
static void Main(string[] args)
{
Location location = new Location();
var maxPoint = Console.ReadLine().Split(' ');
var commandPositions = Console.ReadLine().Trim().Split(' ');
if (commandPositions.Length == 3)
{
location.X = Convert.ToInt32(commandPositions[0]);
location.Y = Convert.ToInt32(commandPositions[1]);
location.Direction = (Direction)Enum.Parse(typeof(Direction), commandPositions[2]);
}
var commandRotations = Console.ReadLine().ToUpper();
try
{
StartMoving sm = new StartMoving();
sm.Execute(location, commandRotations.ToCharArray(), maxPoint);
if (location != null)
{
Console.WriteLine($"{location.X} {location.Y} {location.Direction}");
}
else
{
Console.WriteLine("Not valid input!");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistencia
{
public class pCategoria
{
String idCategoria;
String descricao;
public void inserir(String descricao)
{
String SQL = "INSERT INTO dbo.Categoria(descricao) VALUES('" + descricao + "')";
Conexao oConexao = new Conexao("SQLServer");
oConexao.executeNoQuery(SQL);
oConexao.fechaConexao();
}
public void alterar(String descricao, String idCategoria)
{
String SQL = "UPDATE dbo.Categoria";
SQL += " SET descricao = '" + descricao + "'";
SQL += " WHERE idCategoria = " + idCategoria;
Conexao oConexao = new Conexao("SQLServer");
oConexao.executeNoQuery(SQL);
oConexao.fechaConexao();
}
public void apagar(String idCategoria, String descricao)
{
String SQL = "DELETE dbo.Categoria WHERE idCategoria =" + idCategoria;
Conexao oConexao = new Conexao("SQLServer");
oConexao.executeNoQuery(SQL);
oConexao.fechaConexao();
}
public DataSet consultarTodos()
{
String SQL = "SELECT idCategoria as ID, descricao as Descrição FROM dbo.Categoria";
Conexao oConexao = new Conexao("SQLServer");
SqlDataAdapter adapter = new SqlDataAdapter(SQL, oConexao.cn);
DataSet ds = new DataSet("Tabela");
adapter.Fill(ds, "Tabela");
oConexao.fechaConexao();
return ds;
}
}
}
|
using System;
namespace GENN
{
/// <summary>
/// An input class which provides the basic "Output" value to serve as the first layer in the network
/// </summary>
public class Input
{
public Input ()
{
Random rand = new Random ();
Output = rand.NextDouble ();
}
public Input (double output)
{
Output = output;
}
public double Value;
public double Output;
}
}
|
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Particles.Profiles
{
public class BoxProfile : Profile
{
public float Width { get; set; }
public float Height { get; set; }
public override void GetOffsetAndHeading(out Vector2 offset, out Axis heading)
{
switch (FastRand.NextInteger(3))
{
case 0: // Left
offset = new Vector2(Width*-0.5f, FastRand.NextSingle(Height*-0.5f, Height*0.5f));
break;
case 1: // Top
offset = new Vector2(FastRand.NextSingle(Width*-0.5f, Width*0.5f), Height*-0.5f);
break;
case 2: // Right
offset = new Vector2(Width*0.5f, FastRand.NextSingle(Height*-0.5f, Height*0.5f));
break;
default: // Bottom
offset = new Vector2(FastRand.NextSingle(Width*-0.5f, Width*0.5f), Height*0.5f);
break;
}
FastRand.NextUnitVector(out heading);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Vehicles
{
class Truck:Vehicle
{
public Truck(string fuelquantity,string consum,string tankcapacity)
{
this.TankCapacity = double.Parse(tankcapacity);
this.FuelQuantity = double.Parse(fuelquantity);
this.Fuelconsum = double.Parse(consum) + 1.6;
}
public override void Refuel(double quantity)
{
if (quantity > TankCapacity)
{
Console.WriteLine($"Cannot fit {quantity} fuel in the tank");
}
else if (quantity <= 0)
{
Console.WriteLine("Fuel must be a positive number");
}
else
FuelQuantity += quantity*0.95;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdsWebshop.Logic;
namespace AdsWebshop.Models
{
public class CategoryModel
{
public List<Ad> Ads{ get; set; }
public List<Category> Categories { get; set; }
public Category Category { get; set; }
public Ad Ad { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CIS420Redux.Models;
using CIS420Redux.Models.ViewModels.Advisor;
namespace CIS420Redux.Controllers
{
public class AdminController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Dashboard()
{
return View();
}
public ActionResult Search()
{
return View();
}
// GET: Admin
public ActionResult Index()
{
return View(db.Admins.ToList());
}
// GET: Admin/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Admin admin = db.Admins.Find(id);
if (admin == null)
{
return HttpNotFound();
}
return View(admin);
}
// GET: Admin/Create
public ActionResult Create()
{
return View();
}
// POST: Admin/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id")] Admin admin)
{
if (ModelState.IsValid)
{
db.Admins.Add(admin);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(admin);
}
// GET: Admin/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Admin admin = db.Admins.Find(id);
if (admin == null)
{
return HttpNotFound();
}
return View(admin);
}
// POST: Admin/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id")] Admin admin)
{
if (ModelState.IsValid)
{
db.Entry(admin).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(admin);
}
// GET: Admin/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Admin admin = db.Admins.Find(id);
if (admin == null)
{
return HttpNotFound();
}
return View(admin);
}
// POST: Admin/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Admin admin = db.Admins.Find(id);
db.Admins.Remove(admin);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult StudentTodos()
{
return View(db.Events.ToList());
}
public ActionResult ComplianceDocs()
{
var clinicalCompliances = db.ClincalCompliances.ToList();
//var clinicalCompliances = db.ClincalCompliances.Where(c => c.Student.Id == student.Id).ToList();
//var isStudentCompliant = db.ClincalCompliances.Any(cc => cc.Student.Id == student.Id && cc.IsCompliant == false);
var ccdocidList = clinicalCompliances.Select(d => d.DocumentId).ToList();
var documents = db.Documents.Where(d => ccdocidList.Contains(d.Id)).ToList();
var viewModel = clinicalCompliances.Select(c => new AdvisorCCIndexViewModel
{
ExpirationDate = c.ExpirationDate,
DocumentId = c.DocumentId,
IsComplaint = c.IsCompliant,
ID = c.ID,
Type = c.Type,
StudentNumber = c.Student.StudentNumber,
FirstName = c.Student.FirstName,
LastName = c.Student.LastName,
IsExpired = c.ExpirationDate <= DateTime.Today ? true : false
});
foreach (var doc in documents)
{
viewModel.FirstOrDefault(v => v.DocumentId == doc.Id).Document = doc;
}
return View(viewModel);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
// Lic:
// High/KittyHighC.cs
// Kitty
// version: 23.01.04
// Copyright (C) 2019, 2023 Jeroen P. Broks
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// EndLic
namespace Kitty {
class KittyHighC : KittyPL {
public KittyHighC() {
Langs["c"] = this;
Langs["cpp"] = this;
Langs["h"] = this;
Langs["hpp"] = this;
Language = "C/C++";
BaseTypes.Add("void");
BaseTypes.Add("bool");
BaseTypes.Add("auto");
BaseTypes.Add("char");
BaseTypes.Add("int");
KeyWords.Add("asm");
KeyWords.Add("else");
KeyWords.Add("new");
KeyWords.Add("this");
KeyWords.Add("enum");
KeyWords.Add("operator");
KeyWords.Add("throw");
KeyWords.Add("explicit");
KeyWords.Add("private");
KeyWords.Add("true");
KeyWords.Add("break");
KeyWords.Add("export");
KeyWords.Add("protected");
KeyWords.Add("try");
KeyWords.Add("case");
KeyWords.Add("extern");
KeyWords.Add("public");
KeyWords.Add("typedef");
KeyWords.Add("catch");
KeyWords.Add("false");
KeyWords.Add("register");
KeyWords.Add("typeid");
KeyWords.Add("float");
KeyWords.Add("reinterpret_cast");
KeyWords.Add("typename");
KeyWords.Add("class");
KeyWords.Add("for");
KeyWords.Add("return");
KeyWords.Add("union");
KeyWords.Add("const");
KeyWords.Add("friend");
KeyWords.Add("short");
KeyWords.Add("unsigned");
KeyWords.Add("const_cast");
KeyWords.Add("goto");
KeyWords.Add("signed");
KeyWords.Add("using");
KeyWords.Add("continue");
KeyWords.Add("if");
KeyWords.Add("sizeof");
KeyWords.Add("virtual");
KeyWords.Add("default");
KeyWords.Add("inline");
KeyWords.Add("static");
KeyWords.Add("delete");
KeyWords.Add("static_cast");
KeyWords.Add("volatile");
KeyWords.Add("do");
KeyWords.Add("long");
KeyWords.Add("struct");
KeyWords.Add("wchar_t");
KeyWords.Add("double");
KeyWords.Add("mutable");
KeyWords.Add("switch");
KeyWords.Add("while");
KeyWords.Add("dynamic_cast");
KeyWords.Add("namespace");
KeyWords.Add("template");
}
}
} |
using System;
public interface IFLEventDispatcher
{
void AddEventListener(string eventType, FLEventBase.FLEventHandler handler);
void RemoveEventListener(string eventType, FLEventBase.FLEventHandler handler);
void DispatchEvent(FLEventBase e, string type = "");
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace BookLibrary
{
class Program
{
static void Main()
{
var booksCount = int.Parse(Console.ReadLine());
var myLib = new Library
{
Name = "myLibrary",
Books = new List<Book>()
};
for (int i = 0; i < booksCount; i++)
{
var input = Console.ReadLine().Split();
var bookTitle = input[0];
var bookAuthor = input[1];
var publisher = input[2];
var releaseDate = DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture);
var isbn = input[4];
var price = decimal.Parse(input[5]);
var book = new Book(bookTitle, bookAuthor, publisher, releaseDate, isbn, price);
myLib.Books.Add(book);
}
var authorSales = myLib.Books
.Select(author => author.Author)
.Distinct()
.Select(author => new Author
{
Name = author,
Sales = myLib.Books.Where(a => a.Author == author).Sum(z => z.Price)
})
.OrderByDescending(a => a.Sales)
.ThenBy(a => a.Name)
.ToArray();
var bookDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
var bookSales = myLib.Books
.Where(b => b.ReleaseDate > bookDate)
.Select(b => new Bookz
{
Name = b.Title,
ReleaseDate = b.ReleaseDate
})
.OrderBy(b => b.ReleaseDate)
.ThenBy(b => b.Name)
.ToArray();
foreach (var item in bookSales)
{
Console.WriteLine($"{item.Name} -> {item.ReleaseDate.ToString("dd.MM.yyyy")}");
}
}
}
class Bookz
{
public string Name { get; set; }
public DateTime ReleaseDate { get; set; }
}
class Author
{
public string Name { get; set; }
public decimal Sales { get; set; }
}
class Book
{
public Book(string title, string author, string publisher, DateTime releaseDate, string isbnNumber, decimal price)
{
this.Title = title;
this.Author = author;
this.Publisher = publisher;
this.ReleaseDate = releaseDate;
this.IsbnNumber = isbnNumber;
this.Price = price;
}
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public string IsbnNumber { get; set; }
public decimal Price { get; set; }
}
class Library
{
public string Name { get; set; }
public List<Book> Books { get; set; }
}
} |
using BigEndian.IO;
namespace nuru.IO.NUI.Cell.Metadata
{
public class MetadataUInt8Reader : IMetadataReader
{
public virtual ushort Read(BigEndianBinaryReader reader)
{
return reader.ReadByte();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.G_Code
{
public class G_019_SearchString
{
/*
*
已知每个待查找的字符串长度为10,如何在一个很长的字符串的序列里快速查找这
样的字符串
*/
public bool SearchString(string s, string p)
{
return false;
}
}
}
|
using System;
namespace Dice_Roller
{
internal class Die
{
public int numSides { get; set; } // number of sides that the die has
private Random rng;
public Die()
{
this.numSides = 6;
rng = new Random();
}
public Die(int numSides)
{
this.numSides = numSides;
rng = new Random();
}
public int Roll()
{
return (rng.Next() % numSides) + 1;
}
}
} |
using System;
using UnityEngine;
using UnityEngine.Networking;
[AttributeUsage(AttributeTargets.Method)]
public class ServerAccess : Attribute
{
private readonly bool _hasAccess;
public ServerAccess()
{
_hasAccess = SP_Manager.Instance.IsSinglePlayer() || NetworkServer.active || GameObject.Find("GameManager").GetComponent<NetworkIdentity>()
.isServer;
}
public virtual bool HasAccess
{
get { return _hasAccess; }
}
}
[AttributeUsage(AttributeTargets.Method)]
public class ClientAccess : Attribute
{
private readonly bool _hasAccess;
public ClientAccess()
{
_hasAccess = SP_Manager.Instance.IsSinglePlayer() || GameObject.Find("GameManager").GetComponent<NetworkIdentity>()
.isClient;
}
public virtual bool HasAccess
{
get { return _hasAccess; }
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Auction_proj.Models;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace Auction_proj.Controllers
{
public class AuctionController : Controller
{
private AuctionContext _context;
public AuctionController(AuctionContext context)
{
_context = context;
}
[HttpGet]
[Route("NewAuction")]
public IActionResult NewAuction(){
int? Int = HttpContext.Session.GetInt32("Userid");
User Cur = _context.Users.Include(b => b.Bids).ThenInclude(w => w.Auction).Where(c => c.Userid == (int)Int).SingleOrDefault();
ViewBag.Userid = Cur.Userid;
return View("NewAuction");
}
[HttpPost]
[Route("Auct")]
public IActionResult Auct(RegisterAuctModel model){
int? Int = HttpContext.Session.GetInt32("Userid");
User Cur = _context.Users.Include(b => b.Bids).ThenInclude(w => w.Auction).Where(c => c.Userid == (int)Int).SingleOrDefault();
ViewBag.Userid = Cur.Userid;
if(ModelState.IsValid){
if(model.StartingBid < 1){
TempData["Error"] = "Starting bid must be greater than 0";
return View("NewAuction");
}if(DateTime.Now > model.EndDate){
TempData["Error"] = "EndDate Can't be in the past";
return View("NewAuction");
}
Auction New = new Auction();
New.ProductName = model.ProductName;
New.Description = model.Description;
New.StartingBid = model.StartingBid;
New.Creator = Cur.UserName;
New.EndDate = model.EndDate;
_context.Auctions.Add(New);
_context.SaveChanges();
return Redirect($"/Dash/{Cur.Userid}");
}
return View("NewAuction");
}
[HttpGet]
[Route("/Delete/{Auctionid}")]
public IActionResult Delete(int auctionid){
int? Int = HttpContext.Session.GetInt32("Userid");
User Cur = _context.Users.Include(b => b.Bids).ThenInclude(w => w.Auction).Where(c => c.Userid == (int)Int).SingleOrDefault();
Auction A = _context.Auctions.Where(d => d.Auctionid == auctionid).SingleOrDefault();
_context.Auctions.Remove(A);
_context.SaveChanges();
return Redirect($"/Dash/{Cur.Userid}");
}
[HttpGet]
[Route("/Product/{Auctionid}")]
public IActionResult Product(int Auctionid){
int? Int = HttpContext.Session.GetInt32("Userid");
User Cur = _context.Users.Include(b => b.Bids).ThenInclude(w => w.Auction).Where(c => c.Userid == (int)Int).SingleOrDefault();
Auction B = _context.Auctions.Where(h => h.Auctionid == Auctionid).SingleOrDefault();
double days = (B.EndDate - DateTime.Now).TotalDays;
ViewBag.Days = days;
ViewBag.Userid = Cur.Userid;
ViewBag.B = B;
return View("Product");
}
[HttpPost]
[Route("NewBid/{Auctionid}")]
public IActionResult NewBid(int Auctionid, int amount){
int? Int = HttpContext.Session.GetInt32("Userid");
Auction B = _context.Auctions.Where(h => h.Auctionid == Auctionid).SingleOrDefault();
User Cur = _context.Users.Include(b => b.Bids).ThenInclude(w => w.Auction).Where(c => c.Userid == (int)Int).SingleOrDefault();
if(amount > B.StartingBid){
Bid L = new Bid();
L.Userid = Cur.Userid;
L.Auctionid = B.Auctionid;
L.Amount = amount;
B.StartingBid = amount;
_context.Bids.Add(L);
_context.SaveChanges();
return Redirect($"/Product/{B.Auctionid}");
}else{
TempData["Error"] = "Bid must be higher then current highest";
return Redirect($"/Product/{B.Auctionid}");
}
}
}
} |
using System.Transactions;
using SpecsFor.Configuration;
namespace Base.Test.Helpers
{
public class TransactionsScopeWrapper : Behavior<INeedDatabase>
{
private TransactionScope _scope;
public override void SpecInit(INeedDatabase instance)
{
_scope = new TransactionScope();
}
public override void AfterSpec(INeedDatabase instance)
{
_scope.Dispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chpoi.SuitUp.Service
{
//3d扫描服务
public interface ScanService
{
void scan();
}
}
|
// Copyright (c) Daniel Crenna & Contributors. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading.Tasks;
using ActiveApi.Configuration;
using ActiveRoutes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace ActiveApi
{
partial class Use
{
public static void UseResourceRewriting(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
if (context.FeatureEnabled<ResourceRewritingOptions>(out var options))
{
await ExecuteFeature(context, options, next);
}
else
{
await next();
}
});
static async Task ExecuteFeature(HttpContext c, ResourceRewritingOptions o, Func<Task> next)
{
// Use X-Action to disambiguate one vs. many resources in a write call
// See: http://restlet.com/blog/2015/05/18/implementing-bulk-updates-within-restful-services/
var action = c.Request.Headers[o.ActionHeader];
if (action.Count > 0)
{
var path = c.Request.Path.ToUriComponent();
path = $"{path}/{action}";
c.Request.Path = path;
}
// Use 'application/merge-patch+json' header to disambiguate JSON patch strategy:
// See: https://tools.ietf.org/html/rfc7386
var contentType = c.Request.Headers[HeaderNames.ContentType];
if (contentType.Count > 0 && contentType.Contains(MediaTypeNames.Application.JsonMergePatch))
{
var path = c.Request.Path.ToUriComponent();
path = $"{path}/merge";
c.Request.Path = path;
}
await next();
}
}
}
} |
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;
using System.Windows.Threading;
namespace GameRasmusGyllenhammar
{
/// <summary>
/// Interaction logic for GameWindow.xaml
/// </summary>
public partial class GameWindow : Window
{
bool goUp, goDown;
int playerSpeed = 8;
int playerTwoSpeed = 8;
double ballSpeedX = 12;
double ballSpeedY = 2;
bool openStartMenu = true;
bool openPopup = true;
DispatcherTimer gameTimer = new DispatcherTimer(); //instans av timer
Player firstPlayer = new Player();
Player secondPlayer = new Player();
Ball gameBall = new Ball { XPosition = 740, YPosition = 50 };
public GameWindow()
{
InitializeComponent();
myCanvas.Focus(); //fokusera på canvasen bara
gameTimer.Tick += GameTimerEvent; //Länkar till ett event
gameTimer.Interval = TimeSpan.FromMilliseconds(20); //hur ofta vi vill att den ska ticka
gameTimer.Start();
}
/// <summary>
/// Metoden länkad till tick så denna uppdateras varje 20 millisekund.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GameTimerEvent(object sender, EventArgs e)
{
PlayersMovement();
CheckCollisionWithPlayers();
UpdateBallPosition();
NewPoint();
CheckCollisionWithWalls();
EndScreen();
}
/// <summary>
/// Kollar ifall boolean är sann och spelaren är innanför skärmen så ska den
/// kunna röra på sig,
/// </summary>
private void PlayersMovement()
{
firstPlayer.Move(goUp);
secondPlayer.Move(goUp);
if (goUp == true && Canvas.GetTop(player) > 5)
{
Canvas.SetTop(player, Canvas.GetTop(player) - playerSpeed);
}
else if (goDown == true && Canvas.GetTop(player) + (player.Height + 45) < Application.Current.MainWindow.Height)
{
Canvas.SetTop(player, Canvas.GetTop(player) + playerSpeed);
}
//player two
if (goUp == true && Canvas.GetTop(playerTwo) > 5)
{
Canvas.SetTop(playerTwo, Canvas.GetTop(playerTwo) - playerTwoSpeed);
}
else if (goDown == true && Canvas.GetTop(playerTwo) + (playerTwo.Height + 45) < Application.Current.MainWindow.Height)
{
Canvas.SetTop(playerTwo, Canvas.GetTop(playerTwo) + playerTwoSpeed);
}
}
/// <summary>
/// ifall man inte trycker på någon knapp så ska det var true
/// känner av ifall en av pilarna är trycka
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void KeyIsDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Up: //ha player.move boolean?
goUp = true;
goDown = false;
playerSpeed = 0;
break;
case Key.W:
goUp = true;
goDown = false;
playerTwoSpeed = 0;
break;
case Key.Down:
goUp = false;
goDown = true;
playerSpeed = 0;
break;
case Key.S:
goUp = false;
goDown = true;
playerTwoSpeed = 0;
break;
}
}
/// <summary>
/// ifall man inte trycker på någon knapp så ska det var false
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void KeyIsUp(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.W:
goUp = false;
playerTwoSpeed = 8;
break;
case Key.Up:
goUp = false;
playerSpeed = 8;
break;
case Key.Down:
goDown = false;
playerSpeed = 8;
break;
case Key.S:
goDown = false;
playerTwoSpeed = 8;
break;
default:
break;
}
}
/// <summary>
/// Metoden kollar ifall bollen åker ut ur sidorna och då ska(borde gjort en ny metod)
/// bollen byta riktning och man kallar på ResetBallPosition()
/// beroende vilket håll den åker ut så ökar spelarnas score med 1
/// och uppdaterar labeln
/// </summary>
private void NewPoint()
{
//kolla ifall den överstiger skärmen, sen reset (x,y)
if (Canvas.GetLeft(ball) < 1)
{
ballSpeedX = -ballSpeedX;
ResetBallPosition();
firstPlayer.Score += 1;
greenPlayerLabel.Content = "Green Score: " + firstPlayer.Score;
}
if (Canvas.GetLeft(ball) + (ball.Width * 1.3) > Application.Current.MainWindow.Width)
{
ballSpeedX = -ballSpeedX;
ResetBallPosition();
secondPlayer.Score += 1;
redPlayerLabel.Content = "Red Score: " + secondPlayer.Score;
}
}
/// <summary>
/// Metoden återställer bollen grund position dvs i mitten
/// </summary>
private void ResetBallPosition()
{
Canvas.SetTop(ball, 200);
Canvas.SetLeft(ball, 400);
}
/// <summary>
/// Denna metod kollar ifall bollen interagerar med spelarna. Jag kollar efter rektanglar som har taggen "paddle"
/// Skapar två rect med egenskaperna
/// från bollen och racken(från taggen) och ifall de interagerar så ska X hastigheten byta riktning samt att
/// man kallar på BallAngle för att skapa vinkeln åt bollen när den nuddar racken.
/// </summary>
private void CheckCollisionWithPlayers()
{
foreach (var rectangles in myCanvas.Children.OfType<Rectangle>())
{
if ((string)rectangles.Tag == "paddle")
{
rectangles.Stroke = Brushes.Black;
Rect ballHitBox = new Rect(Canvas.GetLeft(ball), Canvas.GetTop(ball), ball.Width, ball.Height);
Rect playerHitBox = new Rect(Canvas.GetLeft(rectangles), Canvas.GetTop(rectangles), rectangles.Width, rectangles.Height);
if (ballHitBox.IntersectsWith(playerHitBox))
{
ballSpeedX = -ballSpeedX;
ballSpeedX -= 1;
BallAngle(ballHitBox.Y + 12.5, playerHitBox.Y + 65);
//ballSpeedY += 1;
Canvas.SetRight(ball, Canvas.GetRight(rectangles) - ball.Height);
}
}
}
}
/// <summary>
/// Metoden räknar ut vinkeln när den nuddar racken, man utgår ifrån mitten av racken.
/// man utgår ifrån spelarnas halva höjd. Sedan tar vi skillnaden mellan y-pos av bollen och spelarn och delar det på
/// spelarnas höjd gånger maxvinkeln vi vill den ska studsa. Sedan räknar vi ut speed och har den till samma hastighet.
/// I slutet uppdaterar man X och Y hastighet med den hastigheten gånger vinkeln.
/// </summary>
/// <param name="ballY">Y-pos för bollen</param>
/// <param name="playerY">Y-pos för spelaren för att kunna se vart bollen och spelaren kolliderar med varandra</param>
private void BallAngle(double ballY, double playerY)
{
//halva spelarnas höjd
var playerHeight = 65;
var maxAngle = (Math.PI / 3); //75 eller 60 degree, max vinklen
//vinkeln att rotera hastigheten
var nextAngle = (ballY - playerY) / playerHeight * maxAngle;
//samma speed
var speedMagnitude = Math.Sqrt(Math.Pow(ballSpeedX, 2) + Math.Pow(ballSpeedY, 2));
//upptadera bollV i x och y
ballSpeedX = speedMagnitude * Math.Cos(nextAngle) * Math.Sign(ballSpeedX); // kollar också ifall det är negativt eller positivt
ballSpeedY = speedMagnitude * Math.Sin(nextAngle);
}
/// <summary>
/// uppdaterar bollen och sätter igång att den åker åt ett visst håll;
/// </summary>
private void UpdateBallPosition()
{
// var ballDirection = randomize.Next(-12, 12);
// ballSpeedX = randomize.Next(-11, 21);
Canvas.SetLeft(ball, Canvas.GetLeft(ball) + ballSpeedX);
Canvas.SetTop(ball, Canvas.GetTop(ball) + ballSpeedY);
}
/// <summary>
/// Kollar ifall bollen kolliderar med väggarna isåfall ska Y-värdet ändra riktning
/// </summary>
private void CheckCollisionWithWalls()
{
if (Canvas.GetTop(ball) + (ball.Height + 37) > Application.Current.MainWindow.Height)
{
ballSpeedY = -ballSpeedY;
}
if (Canvas.GetTop(ball) < 8)
{
ballSpeedY = -ballSpeedY;
}
}
/* private void StartScreen()
{
if (openStartMenu)
{
StartMenu StartWindow = new StartMenu();
StartWindow.Show();
openStartMenu = false;
}
}*/
/// <summary>
/// stannar bollen och öppnar pop up fönstret med alternativ att stänga ner eller att starta nytt spel sedan stänger man ner spelfönstret
/// </summary>
private void EndScreen()
{
if (firstPlayer.Score >= 5 || secondPlayer.Score >= 5)
{
ballSpeedX = 0;
ballSpeedY = 0;
if (openPopup)
{
EndMenu MenuWindow = new EndMenu();
MenuWindow.Show();
openPopup = false;
this.Close();
}
}
}
}
}
|
namespace JumpAndRun
{
public enum BlockSide
{
Top,
Bottom,
Side
}
}
|
using System;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.Graphics.Effects;
using Terraria.Graphics.Shaders;
using Terraria.ID;
using Terraria.ModLoader;
namespace Malum.Items.Weapons.Azurite
{
public class Siegfried : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Siegfried");
Tooltip.SetDefault("Will become legendary in the 14th sequel. Has high knockback.");
}
public override void SetDefaults()
{
item.damage = 12;
item.melee = true;
item.noMelee = false;
item.width = 42;
item.height = 44;
item.useTime = 20;
item.useAnimation = 23;
item.useStyle = 1;
item.knockBack = 10;
item.value = 100000;
item.rare = 3;
//item.reuseDelay = 20;
item.UseSound = SoundID.Item1;
item.autoReuse = true;
item.useTurn = true;
item.maxStack = 1;
item.consumable = false;
//item.noUseGraphic = true;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(null, "AzuriteBar", 10);
recipe.AddTile(16);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace peasants
{
public class Manager : MonoBehaviour
{
public Peasant prefab = null;
public List<Peasant> peasants;
void Awake()
{
peasants = FindObjectsOfType<Peasant>().ToList();
}
public Peasant Create(Vector3 position)
{
var p = (Peasant)Instantiate(prefab, position, Quaternion.identity);
p.transform.parent = DynamicObjectsManager.Instance.transform;
peasants.Add(p);
return p;
}
/// <summary>
/// Assign peasant to work
/// </summary>
/// <param name="prof"></param>
/// <param name="count"></param>
public void AssignWork(Profession prof, int count)
{
var profPeasants = new List<Peasant>();
var available = new List<Peasant>();
foreach (var p in peasants)
{
if (p.Profession == prof)
{
profPeasants.Add(p);
}
else if(p.Profession == Profession.None)
{
available.Add(p);
}
}
if (count > profPeasants.Count && available.Count > 0)
{
var arr = available.Take(count - profPeasants.Count);
foreach (var p in arr)
{
//see property __set__
p.Profession = prof;
}
}
else if(count < profPeasants.Count)
{
var arr = profPeasants.Take(profPeasants.Count - count);
foreach (var p in arr)
{
p.Profession = Profession.None;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Team3ADProject.Code;
namespace Team3ADProject.Protected
{
public partial class ViewCollectionInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Load_Collections();
}
protected void Load_Collections()
{
gridview1.DataSource = BusinessLogic.ViewCollectionListNew();
gridview1.DataBind();
}
//store details in session to display in detail on the next page(AcknowledgeDistributionList)
protected void gridview1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
Session["EmployeeName"] = gridview1.Rows[e.NewSelectedIndex].Cells[1].Text;
Session["DepartmentName"] = gridview1.Rows[e.NewSelectedIndex].Cells[2].Text;
Session["CollectionDate"] = gridview1.Rows[e.NewSelectedIndex].Cells[5].Text;
Session["CollectionLocation"] = gridview1.Rows[e.NewSelectedIndex].Cells[4].Text;
Session["CollectionTime"] = gridview1.Rows[e.NewSelectedIndex].Cells[6].Text;
Session["collection_id"] = gridview1.Rows[e.NewSelectedIndex].Cells[3].Text;
Response.Redirect("~/Protected/AcknowledgeDistributionList.aspx");
}
}
} |
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using UnityEngine;
namespace Worldbuilder
{
public class Tools
{
public static List<List<System.Drawing.Color>> getColor(string path)
{
//Debug.Log("getting zonecolor form map image "+path);
Bitmap zoneMapImage;
zoneMapImage = new Bitmap(path);
List<List<System.Drawing.Color>> zoneListe = new List<List<System.Drawing.Color>>();
List<System.Drawing.Color> row = new List<System.Drawing.Color>();
System.Drawing.Color pixelColor = new System.Drawing.Color();
//zonemapimage = new Bitmap(path);
for (int i = 0; i < zoneMapImage.Height; i++)
{
row = new List<System.Drawing.Color>();
for (int j = 0; j < zoneMapImage.Width; j++)
{
pixelColor = zoneMapImage.GetPixel(j, i);
row.Add(pixelColor);
//Debug.Log(" " + pixelColor.R + " " + pixelColor.G + " " + pixelColor.B + " " + pixelColor.A + " \n");
}
zoneListe.Add(row);
}
zoneMapImage.Dispose();
return zoneListe;
}
public static string[] getMapZones(string path)
{
//Debug.Log("getting zone name from "+ path);
string zoneRecu = path;
//Debug.Log("reader opened");
StreamReader reader = openTextFile(zoneRecu);
string input;
List<string> zoneTexte = new List<string>();
List<string> zoneARenvoyer = new List<string>();
//Debug.Log("reading document");
input = reader.ReadLine();
while (input != null)
{
zoneTexte.Add(input);
input = reader.ReadLine();
}
//Debug.Log("end reading");
reader.Close();
//Debug.Log ("computting");
for (int i = 0; i < zoneTexte.Count; i++)
{
if (!zoneTexte[i].StartsWith("="))
{
if (!zoneTexte[i].StartsWith(" "))
{
if (!zoneTexte[i].StartsWith("*"))
{
zoneARenvoyer.Add(zoneTexte[i]);
}
}
}
}
string definition;
string[] zoneAComparer = new string[zoneARenvoyer.Count];
int j = 0;
for (int i = 0; i < zoneARenvoyer.Count; i++)
{
definition = zoneARenvoyer[i] + ",";
i++;
definition = definition + zoneARenvoyer[i] + ",";
i++;
definition = definition + zoneARenvoyer[i] + ",";
i++;
definition = definition + zoneARenvoyer[i];
//Debug.Log(definition);
zoneAComparer[j] = definition;
j++;
}
//Debug.Log("returning string array of zone definitions");
return zoneAComparer;
}
public static string getNomZone(string[] configZone, string recZone)
{
string[] mapConfig = new string[200];
string receivedColor = string.Empty;
mapConfig = configZone;
receivedColor = recZone;
string[] configParts = new string[4];
string[] recparts = new string[3];
string zoneName = string.Empty;
//Debug.Log("spliting recived zone" + recivedcolor);
recparts = receivedColor.Split(',');
for (int i = 0; i < mapConfig.Length; i++)
{
configParts = mapConfig[i].Split(',');
//Debug.Log("spliting config zone" + mapconfig[i]);
if (configParts[0] == recparts[0])
{
if (configParts[1] == recparts[1])
{
if (configParts[2] == recparts[2])
{
zoneName = configParts[3];
//Debug.Log("sending back data "+zonename);
return zoneName;
}
}
}
}
return "error";
}
public static StreamReader openTextFile(string fichier)
{
StreamReader streamReader;
streamReader = File.OpenText(fichier);
return streamReader;
}
public static string colorToString(System.Drawing.Color uneCouleur)
{
System.Drawing.Color couleur = uneCouleur;
string couleurString = couleur.R.ToString() + "," + couleur.G.ToString() + "," + couleur.B.ToString();
return couleurString;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
public class GraphConnectedComponents
{
static bool[] visitedNodes;
static new List<int>[] graph = new List<int>[]
{
new List<int>(){3, 6}, //0
new List<int>(){3, 4, 5, 6}, //1
new List<int>(){8}, //2
new List<int>(){0, 1, 5}, //3
new List<int>(){1, 6}, //4
new List<int>(){1, 3}, //5
new List<int>(){0, 1, 4}, //6
new List<int>(){}, //7
new List<int>(){2} //8
};
static List<int>[] ReadGraph()
{
int numOfNodes = int.Parse(Console.ReadLine());
var graph = new List<int>[numOfNodes];
for (int i = 0; i < graph.Length; i++)
{
graph[i] = Console.ReadLine().Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
}
return graph;
}
static void DFS(int node)
{
if(!visitedNodes[node])
{
visitedNodes[node] = true;
foreach(var connectdNode in graph[node])
{
DFS(connectdNode);
}
Console.Write(" " + node);
}
}
static void FindConnectedNodes()
{
visitedNodes = new bool[graph.Length];
for (var currNode = 0; currNode < graph.Length; currNode++ )
{
if(!visitedNodes[currNode])
{
Console.Write("Connected component:");
DFS(currNode);
Console.WriteLine();
}
}
}
public static void Main()
{
graph = ReadGraph();
FindConnectedNodes();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SynchWebService.Entity
{
[Serializable]
public class EmpOrder
{
/// <summary>
/// 工号
/// </summary>
public string empno { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string empname { get; set; }
/// <summary>
/// 部门编号
/// </summary>
public string dptno { get; set; }
/// <summary>
/// 部门名称
/// </summary>
public string dptname { get; set; }
/// <summary>
/// 性别
/// </summary>
public string sex { get; set; }
/// <summary>
/// 联系电话
/// </summary>
public string conectpho { get; set; }
/// <summary>
/// 电子邮件
/// </summary>
public string email { get; set; }
/// <summary>
/// 家庭地址
/// </summary>
public string address { get; set; }
/// <summary>
/// 登录编号
/// </summary>
public string useno { get; set; }
/// <summary>
/// 密码
/// </summary>
public string psw { get; set; }
/// <summary>
/// 使用标记
/// </summary>
public string yorn { get; set; }
/// <summary>
/// 简码
/// </summary>
public string helpmemorycode { get; set; }
/// <summary>
/// 级次
/// </summary>
public string jc { get; set; }
/// <summary>
/// 照片
/// </summary>
public string photo { get; set; }
/// <summary>
/// 源区编号
/// </summary>
public string yqbillno { get; set; }
/// <summary>
/// 源区名称
/// </summary>
public string yqname { get; set; }
/// <summary>
/// 更新人
/// </summary>
public string Updator { get; set; }
/// <summary>
/// 离职时间
/// </summary>
public DateTime? LjDate { get; set; }
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityStandardAssets.ImageEffects;
public class ParticleSea : MonoBehaviour {
public PropagationType propagation;
public Camera cam;
public bool render;
public ParticleSystem particleSystem;
public Text particlesText;
public Vector3 meshOffset;
public int x_meshResolution;
public int y_meshResolution;
public float x_meshSpacing;
public float y_meshSpacing;
public float meshHeightScale;
public float perlinNoiseScale;
public float posRandomness;
public Vector2 perlinNoiseOffset;
public Gradient colorsGradient;
public bool useGradientColors;
public Color defaultColor;
public float x_randomLimit;
public float y_randomLimit;
private Vector3[] positions;
private bool colorsAssigned = false;
private ParticleSystem.Particle[] particlesArray;
private float xPos;
private float yPos;
private float zPos;
public float xAnimSpeed;
public float yAnimSpeed;
private int frameCount;
private bool hasAnythingChanged;
public enum PropagationType {
Regular,
Random
}
public void PerlinNoiseScale(float noise) {
if(noise > 0f)
perlinNoiseScale = noise * 100;
}
public void HeightModifier(float height) {
if(height > 0f)
meshHeightScale = height * 3;
}
public void Spacing(float spacing) {
hasAnythingChanged = true;
if(spacing > 0f) {
x_meshSpacing = spacing;
y_meshSpacing = spacing;
}
}
public void Render(bool isActive) {
render = isActive;
}
public void UseGradient(bool isActive) {
useGradientColors = isActive;
colorsAssigned = false;
}
public void Bloom(bool isActive) {
cam.GetComponent<BloomOptimized>().enabled = isActive;
}
public void Vignetting(bool isActive) {
cam.GetComponent<VignetteAndChromaticAberration>().enabled = isActive;
}
public void XAnimSpeed(float speed) {
xAnimSpeed = speed;
}
public void YAnimSpeed(float speed) {
yAnimSpeed = speed;
}
IEnumerator Animate() {
while(true) {
perlinNoiseOffset = new Vector2(perlinNoiseOffset.x + xAnimSpeed, perlinNoiseOffset.y + yAnimSpeed);
yield return new WaitForSeconds(0.02f);
}
}
public void Resolution(float i) {
x_meshResolution = (int) i;
y_meshResolution = (int) i;
particlesArray = new ParticleSystem.Particle[x_meshResolution * y_meshResolution];
positions = new Vector3[x_meshResolution * y_meshResolution];
RegenerateRandomPositionsArray(x_meshResolution * y_meshResolution);
particleSystem.maxParticles = x_meshResolution * y_meshResolution;
particlesText.text = "Particles count: "+(y_meshResolution * y_meshResolution).ToString();
hasAnythingChanged = true;
}
void Start() {
particlesArray = new ParticleSystem.Particle[x_meshResolution * y_meshResolution];
positions = new Vector3[x_meshResolution * y_meshResolution];
RegenerateRandomPositionsArray(x_meshResolution * y_meshResolution);
StartCoroutine("Animate");
colorsAssigned = false;
hasAnythingChanged = true;
particlesText.text = "Particles count: 40000";
}
void Update () {
if(render && frameCount % 2 == 0) {
if(hasAnythingChanged) meshOffset = new Vector3(x_meshSpacing * x_meshResolution * -0.5f, y_meshSpacing * y_meshResolution * -0.5f, 0f);
hasAnythingChanged = false;
particleSystem.GetParticles(particlesArray);
for(int i = 0; i < x_meshResolution; i++) {
for(int j = 0; j < y_meshResolution; j++) {
xPos = (perlinNoiseOffset.x + i) / perlinNoiseScale;
yPos = (perlinNoiseOffset.y + j) / perlinNoiseScale;
zPos = Mathf.PerlinNoise(xPos, yPos);
//Set position based on these three
particlesArray[i * x_meshResolution + j].position = new Vector3(i * x_meshSpacing + meshOffset.x, j * y_meshSpacing + meshOffset.y, zPos * meshHeightScale);
if(useGradientColors) particlesArray[i * x_meshResolution + j].color = colorsGradient.Evaluate(zPos);
else if(!colorsAssigned) particlesArray[i * x_meshResolution + j].color = defaultColor;
colorsAssigned = true;
}
}
particleSystem.SetParticles(particlesArray, particlesArray.Length);
}
frameCount++;
colorsAssigned = true;
}
private void RegenerateRandomPositionsArray(int arraySize) {
for(int i = 0; i < arraySize; i++) {
positions[i] = new Vector3(Random.Range(-x_randomLimit, x_randomLimit), Random.Range(-y_randomLimit, y_randomLimit), 0);
}
}
}
|
using System;
namespace SKT.MES.PartsManagement.Model
{
[Serializable]
public class PartsOutComingInfo
{
private Int32 iD;
private String partsName;
private String partsAlias;
private String partsNumber;
private String partsCategory;
private String usingEquipment;
private String storagePlace;
private String brand;
private String specifications;
private String parameter;
private Decimal safetyInventory;
private Decimal currentInventory;
private String company;
private Decimal thisOutComingNumber;
private String station;
private String outComingType;
private String applicant;
private int p;
private string p_2;
private string p_3;
private string p_4;
private string p_5;
private string p_6;
private string p_7;
private string p_8;
private string p_9;
private string p_10;
private decimal p_11;
private decimal p_12;
private string p_13;
private decimal p_14;
private string p_15;
private DateTime dateTime;
private string p_16;
/// <summary>
/// 初始化 SKT.MES.Model.PartsOutComingInfo 类的新实例。
/// </summary>
public PartsOutComingInfo()
{
}
/// <summary>
/// 初始化 SKT.MES.Model.PartsOutComingInfo 类的新实例。
/// </summary>
/// <param name="iD">主键自增ID</param>
/// <param name="partsName">备件名</param>
/// <param name="partsAlias">备件别名</param>
/// <param name="partsNumber">备件号</param>
/// <param name="partsCategory">备件类别</param>
/// <param name="usingEquipment">使用设备</param>
/// <param name="storagePlace">存放位置</param>
/// <param name="brand">品牌</param>
/// <param name="specifications">规格</param>
/// <param name="parameter">参数</param>
/// <param name="safetyInventory">安全库存</param>
/// <param name="currentInventory">当前库存</param>
/// <param name="company">单位</param>
/// <param name="thisOutComingNumber">出仓数量</param>
/// <param name="station">工位</param>
/// <param name="outComingType">出仓类型</param>
/// <param name="applicant">申请人</param>
public PartsOutComingInfo(Int32 iD, String partsName, String partsAlias, String partsNumber,
String partsCategory, String usingEquipment, String storagePlace, String brand, String specifications,
String parameter, Decimal safetyInventory, Decimal currentInventory, String company, Decimal thisOutComingNumber,
String station, String outComingType, String applicant)
{
this.iD = iD;
this.partsName = partsName;
this.partsAlias = partsAlias;
this.partsNumber = partsNumber;
this.partsCategory = partsCategory;
this.usingEquipment = usingEquipment;
this.storagePlace = storagePlace;
this.brand = brand;
this.specifications = specifications;
this.parameter = parameter;
this.safetyInventory = safetyInventory;
this.currentInventory = currentInventory;
this.company = company;
this.thisOutComingNumber = thisOutComingNumber;
this.station = station;
this.outComingType = outComingType;
this.applicant = applicant;
}
public PartsOutComingInfo(int p, string p_2, string p_3, string p_4, string p_5, string p_6, string p_7, string p_8, string p_9, string p_10, decimal p_11, decimal p_12, string p_13, decimal p_14, string p_15, DateTime dateTime)
{
// TODO: Complete member initialization
this.p = p;
this.p_2 = p_2;
this.p_3 = p_3;
this.p_4 = p_4;
this.p_5 = p_5;
this.p_6 = p_6;
this.p_7 = p_7;
this.p_8 = p_8;
this.p_9 = p_9;
this.p_10 = p_10;
this.p_11 = p_11;
this.p_12 = p_12;
this.p_13 = p_13;
this.p_14 = p_14;
this.p_15 = p_15;
this.dateTime = dateTime;
}
public PartsOutComingInfo(int p, string p_2, string p_3, string p_4, string p_5, string p_6, string p_7, string p_8, string p_9, string p_10, decimal p_11, decimal p_12, string p_13, decimal p_14, string p_15, string p_16)
{
// TODO: Complete member initialization
this.p = p;
this.p_2 = p_2;
this.p_3 = p_3;
this.p_4 = p_4;
this.p_5 = p_5;
this.p_6 = p_6;
this.p_7 = p_7;
this.p_8 = p_8;
this.p_9 = p_9;
this.p_10 = p_10;
this.p_11 = p_11;
this.p_12 = p_12;
this.p_13 = p_13;
this.p_14 = p_14;
this.p_15 = p_15;
this.p_16 = p_16;
}
/// <summary>
/// 获取或设置主键自增ID
/// </summary>
public Int32 ID
{
get { return this.iD; }
set { this.iD = value; }
}
/// <summary>
/// 获取或设置备件名
/// </summary>
public String PartsName
{
get { return this.partsName; }
set { this.partsName = value; }
}
/// <summary>
/// 获取或设置备件别名
/// </summary>
public String PartsAlias
{
get { return this.partsAlias; }
set { this.partsAlias = value; }
}
/// <summary>
/// 获取或设置备件号
/// </summary>
public String PartsNumber
{
get { return this.partsNumber; }
set { this.partsNumber = value; }
}
/// <summary>
/// 获取或设置备件类别
/// </summary>
public String PartsCategory
{
get { return this.partsCategory; }
set { this.partsCategory = value; }
}
/// <summary>
/// 获取或设置使用设备
/// </summary>
public String UsingEquipment
{
get { return this.usingEquipment; }
set { this.usingEquipment = value; }
}
/// <summary>
/// 获取或设置存放位置
/// </summary>
public String StoragePlace
{
get { return this.storagePlace; }
set { this.storagePlace = value; }
}
/// <summary>
/// 获取或设置品牌
/// </summary>
public String Brand
{
get { return this.brand; }
set { this.brand = value; }
}
/// <summary>
/// 获取或设置规格
/// </summary>
public String Specifications
{
get { return this.specifications; }
set { this.specifications = value; }
}
/// <summary>
/// 获取或设置参数
/// </summary>
public String Parameter
{
get { return this.parameter; }
set { this.parameter = value; }
}
/// <summary>
/// 获取或设置安全库存
/// </summary>
public Decimal SafetyInventory
{
get { return this.safetyInventory; }
set { this.safetyInventory = value; }
}
/// <summary>
/// 获取或设置当前库存
/// </summary>
public Decimal CurrentInventory
{
get { return this.currentInventory; }
set { this.currentInventory = value; }
}
/// <summary>
/// 获取或设置单位
/// </summary>
public String Company
{
get { return this.company; }
set { this.company = value; }
}
/// <summary>
/// 获取或设置出仓数量
/// </summary>
public Decimal ThisOutComingNumber
{
get { return this.thisOutComingNumber; }
set { this.thisOutComingNumber = value; }
}
/// <summary>
/// 获取或设置工位
/// </summary>
public String Station
{
get { return this.station; }
set { this.station = value; }
}
/// <summary>
/// 获取或设置出仓类型
/// </summary>
public String OutComingType
{
get { return this.outComingType; }
set { this.outComingType = value; }
}
/// <summary>
/// 获取或设置申请人
/// </summary>
public String Applicant
{
get { return this.applicant; }
set { this.applicant = value; }
}
}
} |
using Discovery.Core.GlobalData;
using Discovery.Core.Model;
using Discovery.Core.RelationalModel.DataBaseService;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Discovery.Core.RelationalModel
{
public class PostRelationalModel : BindableBase
{
/// <summary>
/// 帖子
/// </summary>
private Post _post;
public Post Post
{
get => _post;
set => SetProperty(ref _post, value);
}
/// <summary>
/// 是否已经被当前用户收藏
/// </summary>
private bool _isBeFavorited;
public bool IsBeFavorited
{
get => _isBeFavorited;
set => SetProperty(ref _isBeFavorited, value);
}
/// <summary>
/// 当前用户收藏/取消收藏此帖子
/// </summary>
public DelegateCommand FavoriteOrCancelFavoriteCommand { get; }
private void FavoriteOrCancelFavorite()
{
using (var databaseService = new DataBaseServiceClient())
{
if (IsBeFavorited)
{
databaseService.CancelFavorite(
GlobalObjectHolder.CurrentUser.BasicInfo.ID,
Post.ID);
IsBeFavorited = false;
}
else
{
databaseService.FavoriteAPost(
GlobalObjectHolder.CurrentUser.BasicInfo.ID,
Post.ID);
IsBeFavorited = true;
}
}
}
/// <summary>
/// 构造函数
/// </summary>
public PostRelationalModel() { }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="post"></param>
/// <param name="isBeFavorited"></param>
public PostRelationalModel(
Post post,
bool isBeFavorited)
{
Post = post;
IsBeFavorited = isBeFavorited;
FavoriteOrCancelFavoriteCommand = new DelegateCommand(FavoriteOrCancelFavorite);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace irc_client.services.parcers {
public class Parcer {
private const char ADDRESS_SPLIT_SIMBOL = ':';
private const int MAX_PORT_VALUE = 9999;
public static bool ParceAddress(string text, ParcedAddress addressObject) {
string[] splittedText = text.Split(ADDRESS_SPLIT_SIMBOL);
// add checking for exception after this comment
try {
addressObject.IP = splittedText[0];
addressObject.Port = Convert.ToInt32(splittedText[1]);
}
catch (Exception ex) {
return false;
}
if (addressObject.Port > MAX_PORT_VALUE) {
return false;
}
return true;
}
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD20
{
/// <summary>
/// LD20A41 的摘要说明。
/// </summary>
public class LD20G3 : BasePage
{
protected System.Web.UI.WebControls.Button BT_QUERY;
protected System.Web.UI.WebControls.Button BT_RETRUN;
protected System.Web.UI.WebControls.TextBox TB_XHD;
protected System.Web.UI.WebControls.TextBox TB_SHDWMC;
protected System.Web.UI.WebControls.DropDownList TB_HWQF;
protected System.Web.UI.WebControls.TextBox TB_WTDWMC;
protected System.Web.UI.WebControls.Button BT_UPDATE;
protected System.Web.UI.WebControls.Label HJ_JZ;
protected System.Web.UI.WebControls.Label HJ_MZ;
protected System.Web.UI.WebControls.Label HJ_JS;
protected System.Web.UI.WebControls.TextBox WTDWMC;
protected System.Web.UI.WebControls.TextBox WTDW;
protected System.Web.UI.WebControls.TextBox SHDWMC;
protected System.Web.UI.WebControls.TextBox SHDW;
protected Infragistics.WebUI.WebSchedule.WebDateChooser WD_WTRQ_FROM;
protected Infragistics.WebUI.WebSchedule.WebDateChooser WD_WTRQ_TO;
protected Infragistics.WebUI.UltraWebGrid.UltraWebGrid Ultrawebgrid2;
protected Infragistics.WebUI.WebCombo.WebCombo PM;
protected System.Web.UI.WebControls.Label HJ_JZ_Ultrawebgrid2;
protected System.Web.UI.WebControls.Label HJ_MZ_Ultrawebgrid2;
protected System.Web.UI.WebControls.Label HJ_JS_Ultrawebgrid2;
protected System.Web.UI.WebControls.Label HJ_JZ_UltraWebGrid1;
protected System.Web.UI.WebControls.Label HJ_MZ_UltraWebGrid1;
protected System.Web.UI.WebControls.Label HJ_JS_UltraWebGrid1;
protected System.Web.UI.WebControls.TextBox TB_CLH_FILTER_1;
protected System.Web.UI.WebControls.TextBox TB_CLH_FILTER_2;
protected System.Web.UI.WebControls.Button BT_DELETE;
protected System.Web.UI.WebControls.TextBox TB_TLCPH;
protected System.Web.UI.WebControls.TextBox TB_CPBZ;
protected System.Web.UI.WebControls.Button BT_COMPLETE;
protected Infragistics.WebUI.UltraWebGrid.UltraWebGrid UltraWebGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.IsPostBack)
{
//品名的初始化
this.PM.DataSource=Common.getPM();
this.PM.DataBind();
this.WD_WTRQ_TO.Value = DateTime.Today;
this.WD_WTRQ_FROM.Value = DateTime.Today.AddDays(-30);
string TLCPH = this.Request.QueryString["TLCPH"];
if(TLCPH != null)
{
this.TB_TLCPH.Text = TLCPH;
query();
}
this.WTDWMC.Attributes.Add("onclick","return OpenEditWin('LD20FDDW.aspx','WT')");
this.SHDWMC.Attributes.Add("onclick","return OpenEditWin('LD20FDDW.aspx','SH')");
this.TB_XHD.Attributes.Add("ondblclick","return OpenEditWin('LD2050.aspx','DDX')");
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.BT_QUERY.Click += new System.EventHandler(this.BT_QUERY_Click);
this.BT_RETRUN.Click += new System.EventHandler(this.BT_RETRUN_Click);
this.BT_UPDATE.Click += new System.EventHandler(this.BT_UPDATE_Click);
this.BT_COMPLETE.Click += new System.EventHandler(this.BT_COMPLETE_Click);
this.BT_DELETE.Click += new System.EventHandler(this.BT_DELETE_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void query()
{
// 查询水运批次数据
string strSQL="SELECT * FROM B_TLCP WHERE TLCPH = @TLCPH";
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@TLCPH",this.TB_TLCPH.Text.Trim())
};
SqlDataReader sr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,paras);
if(sr.Read())
{
this.TB_CPBZ.Text = sr["CPBZ"]+"";
}
// 查询待安排的材料数据
strSQL = "SELECT T.*, (SELECT XHD FROM B_TYD T1 WHERE T1.TYDH=T.TYDH) AS XHD FROM B_TYDMX_CL T";
string where = " WHERE TLCPH = ' ' AND EXISTS( SELECT 1 FROM B_TYD A, B_TYDMX B WHERE A.TYDH=B.TYDH AND B.TYDH=T.TYDH AND B.XH=T.XH AND A.WTDW LIKE @WTDW+'%' AND A.SHDW LIKE @SHDW+'%' AND A.XHD LIKE @XHD+'%' AND A.WTRQ >= @WTRQ_FROM AND A.WTRQ <= @WTRQ_TO AND B.PM LIKE @PM+'%' AND A.TY='Y' ) ";
string CLHFW = this.TB_CLH_FILTER_1.Text.Trim(); // 材料号范围
if(CLHFW.Length > 0)
{
string[] tokens = CLHFW.Split(' ');
where += " AND CLH IN ('" + string.Join("','", tokens) + "') ";
}
strSQL += where;
paras = new SqlParameter[] {
new SqlParameter("@WTDW",this.WTDW.Text.Trim()),
new SqlParameter("@SHDW",this.SHDW.Text.Trim()),
new SqlParameter("@XHD",this.TB_XHD.Text.Trim()),
new SqlParameter("@WTRQ_FROM",this.WD_WTRQ_FROM.Text.Trim()),
new SqlParameter("@WTRQ_TO",this.WD_WTRQ_TO.Text.Trim()),
new SqlParameter("@PM",this.PM.DisplayValue==null?"":this.PM.DisplayValue.Trim())
};
this.UltraWebGrid1.Rows.Clear();
this.UltraWebGrid1.DataSource=SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,paras);
this.UltraWebGrid1.DataBind();
// 查询已安排的材料数据
strSQL = "SELECT T.*, (SELECT XHD FROM B_TYD T1 WHERE T1.TYDH=T.TYDH) AS XHD, (SELECT COUNT(1) FROM B_TLCPCL T1 WHERE T1.TLCPH=T.TLCPH AND T1.HTH=T.HTH AND T1.CLH=T.CLH) AS GEN FROM B_TYDMX_CL T ";
where = " WHERE TLCPH = @TLCPH ";
CLHFW = this.TB_CLH_FILTER_2.Text.Trim(); // 材料号范围
if(CLHFW.Length > 0)
{
string[] tokens = CLHFW.Split(' ');
where += " AND CLH IN ('" + string.Join("','", tokens) + "') ";
}
strSQL += where;
paras = new SqlParameter[] {
new SqlParameter("@TLCPH",this.TB_TLCPH.Text.Trim())
};
this.Ultrawebgrid2.Rows.Clear();
this.Ultrawebgrid2.DataSource=SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,paras);
this.Ultrawebgrid2.DataBind();
for(int i=0;i<this.Ultrawebgrid2.Rows.Count;i++)
{
if(this.Ultrawebgrid2.Rows[i].Cells.FromKey("GEN").Value.Equals(0)==false)
{
this.Ultrawebgrid2.Rows[i].Style.ForeColor = System.Drawing.Color.Green;
}
}
}
private void BT_QUERY_Click(object sender, System.EventArgs e)
{
query();
}
private void BT_UPDATE_Click(object sender, System.EventArgs e)
{
using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING))
{
cn.Open(); // 连接数据库
using(SqlTransaction trans = cn.BeginTransaction())
{ // 事务处理
try
{
for(int i=0;i<this.UltraWebGrid1.Rows.Count;i++)
{
if(this.UltraWebGrid1.Rows[i].Cells.FromKey("SELECT").Text.ToLower().Equals("true"))
{
// 检查卸货地点
string XHD = this.UltraWebGrid1.Rows[i].Cells.FromKey("XHD").Value +"";
string[] XHDtokens = XHD.Trim().Split('-');
if(XHDtokens.Length < 2)
{
throw new Exception("卸货地不是XXX-XXX的格式!请修改托运单的卸货地数据以符合要求!托运单号="+this.UltraWebGrid1.Rows[i].Cells.FromKey("TYDH").Value);
}
else if(XHDtokens[0].Length==0 || XHDtokens[1].Length==0)
{
throw new Exception("卸货地不是XXX-XXX的格式!请修改托运单的卸货地数据以符合要求!托运单号="+this.UltraWebGrid1.Rows[i].Cells.FromKey("TYDH").Value);
}
// 调用存储过程
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@ReturnValue",SqlDbType.Int), // 返回值
new SqlParameter("@MSG",SqlDbType.VarChar,200),
new SqlParameter("@CJR", this.Session["UserName"].ToString()),
new SqlParameter("@TYDH", this.UltraWebGrid1.Rows[i].Cells.FromKey("TYDH").Value),
new SqlParameter("@HTH", this.UltraWebGrid1.Rows[i].Cells.FromKey("HTH").Value),
new SqlParameter("@XH", this.UltraWebGrid1.Rows[i].Cells.FromKey("XH").Value),
new SqlParameter("@CLH", this.UltraWebGrid1.Rows[i].Cells.FromKey("CLH").Value),
new SqlParameter("@TLCPH",this.TB_TLCPH.Text)
};
paras[0].Direction = ParameterDirection.ReturnValue;
paras[1].Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(trans,CommandType.StoredProcedure,"sp_TYD_MX_CL_TLAP",paras);
if ((int)paras[0].Value !=0)
{
throw new Exception(paras[1].Value.ToString());
}
}
}
trans.Commit();
query();
this.msgbox("数据保存成功!");
}
catch(Exception ex)
{
trans.Rollback();
this.msgbox(ex.Message.Replace("\r\n",""));
return;
}
}
cn.Close();
}
}
private void BT_DELETE_Click(object sender, System.EventArgs e)
{
using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING))
{
cn.Open(); // 连接数据库
using(SqlTransaction trans = cn.BeginTransaction())
{ // 事务处理
try
{
for(int i=0;i<this.Ultrawebgrid2.Rows.Count;i++)
{
if(this.Ultrawebgrid2.Rows[i].Cells.FromKey("SELECT").Text.ToLower().Equals("true"))
{
// 调用存储过程
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@ReturnValue",SqlDbType.Int), // 返回值
new SqlParameter("@MSG",SqlDbType.VarChar,200),
new SqlParameter("@CJR", this.Session["UserName"].ToString()),
new SqlParameter("@TYDH", this.Ultrawebgrid2.Rows[i].Cells.FromKey("TYDH").Value),
new SqlParameter("@HTH", this.Ultrawebgrid2.Rows[i].Cells.FromKey("HTH").Value),
new SqlParameter("@XH", this.Ultrawebgrid2.Rows[i].Cells.FromKey("XH").Value),
new SqlParameter("@CLH", this.Ultrawebgrid2.Rows[i].Cells.FromKey("CLH").Value),
new SqlParameter("@TLCPH"," ")
};
paras[0].Direction = ParameterDirection.ReturnValue;
paras[1].Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(trans,CommandType.StoredProcedure,"sp_TYD_MX_CL_TLAP",paras);
if ((int)paras[0].Value !=0)
{
throw new Exception(paras[1].Value.ToString());
}
}
}
trans.Commit();
query();
this.msgbox("数据保存成功!");
}
catch(Exception ex)
{
trans.Rollback();
this.msgbox(ex.Message.Replace("\r\n",""));
return;
}
}
cn.Close();
}
}
private void BT_RETRUN_Click(object sender, System.EventArgs e)
{
this.Response.Redirect("LD20G0.aspx");
}
private void BT_COMPLETE_Click(object sender, System.EventArgs e)
{
using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING))
{
cn.Open(); // 连接数据库
using(SqlTransaction trans = cn.BeginTransaction())
{ // 事务处理
try
{
// 调用存储过程
SqlParameter[] paras = new SqlParameter[] {
new SqlParameter("@ReturnValue",SqlDbType.Int), // 返回值
new SqlParameter("@MSG",SqlDbType.VarChar,200),
new SqlParameter("@CJR", this.Session["UserName"].ToString()),
new SqlParameter("@TLCPH",this.TB_TLCPH.Text)
};
paras[0].Direction = ParameterDirection.ReturnValue;
paras[1].Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(trans,CommandType.StoredProcedure,"sp_TLCP_CL_FROM_TYDCL",paras);
if ((int)paras[0].Value !=0)
{
throw new Exception(paras[1].Value.ToString());
}
trans.Commit();
query();
this.msgbox("数据生成成功!");
}
catch(Exception ex)
{
trans.Rollback();
this.msgbox(ex.Message.Replace("\r\n",""));
return;
}
}
cn.Close();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class PapyScript : MonoBehaviour
{
Rigidbody ailes_Bone;
Rigidbody ailesSup_Bone;
Rigidbody ailes_Bone2;
Rigidbody ailesSup_Bone2;
Rigidbody def_Bone;
Rigidbody jambesSup_Bone;
Rigidbody def_Bone1;
Rigidbody jambesSup_Bone2;
Rigidbody bras_Bone;
Rigidbody bras_Bone1;
Rigidbody[] rs;
NeuralNetwork net;
float[][][][] tabChromosome;
int[] layers = { 30, 25, 25, 30 };
float[] notes;
System.Random random = new System.Random();
public Vector3 force;
// Start is called before the first frame update
void Start()
{
//RagdollScript r = new RagdollScript(transform.Find("z_Armature"));
this.GetComponent<RagdollScript>().bones();
ailes_Bone = transform.Find("z_Armature/Bone/Ailes-Bone").GetComponent<Rigidbody>();
ailesSup_Bone = transform.Find("z_Armature/Bone/Ailes-Bone/AilesSup-Bone").GetComponent<Rigidbody>();
ailes_Bone2 = transform.Find("z_Armature/Bone/Ailes-Bone2").GetComponent<Rigidbody>();
ailesSup_Bone2 = transform.Find("z_Armature/Bone/Ailes-Bone2/AilesSup2-Bone").GetComponent<Rigidbody>();
def_Bone = transform.Find("z_Armature/Bone/Def-Bone").GetComponent<Rigidbody>();
jambesSup_Bone = transform.Find("z_Armature/Bone/Def-Bone/JambesSup-Bone").GetComponent<Rigidbody>();
def_Bone1 = transform.Find("z_Armature/Bone/Def-Bone1").GetComponent<Rigidbody>();
jambesSup_Bone2 = transform.Find("z_Armature/Bone/Def-Bone1/JambesSup-Bone2").GetComponent<Rigidbody>();
bras_Bone = transform.Find("z_Armature/Bone/Bras-Bone").GetComponent<Rigidbody>();
bras_Bone1 = transform.Find("z_Armature/Bone/Bras-Bone1").GetComponent<Rigidbody>();
rs = new Rigidbody[10];
rs[0] = ailes_Bone;
rs[1] = ailesSup_Bone;
rs[2] = ailes_Bone2;
rs[3] = ailesSup_Bone2;
rs[4] = def_Bone;
rs[5] = jambesSup_Bone;
rs[6] = def_Bone1;
rs[7] = jambesSup_Bone2;
rs[8] = bras_Bone;
rs[9] = bras_Bone1;
force = new Vector3(0, 0, 0);
net = new NeuralNetwork(layers);
}
// Update is called once per frame
void Update()
{
float[] t = new float[30];
for (int i = 0; i < rs.Length; i++) {
t[i * 3] = rs[i].velocity.x;
t[i * 3 + 1] = rs[i].velocity.y;
t[i * 3 + 2] = rs[i].velocity.z;
}
float[] res = net.FeedForward(t);
for (int i = 0; i < rs.Length; i++) {
rs[i].AddForce(new Vector3(res[i * 3] * 5, res[i * 3 + 1] * 5, res[i * 3 + 2] * 5));
}
}
public void initNeural(float[][][] weights) {
net = new NeuralNetwork(layers);
net.setWeights(weights);
}
public float[][][] getWeights() {
return net.getWeights();
}
}
|
using System;
namespace Searching_for_a_String
{
class Program
{
static void Main(string[] args)
{
string data = "Can we find this character: a\u030a";
}
}
}
|
/*
* Lauren Cairco Dukes
* January 2014
*
* AvatarUtils.cs
*
* Utilities for avatars to be loaded with BuildAvatar script
*
* Right now all it does is export out some t-pose data, if your skeleton isn't in tpose to begin with
* Steps to make this work:
*
* Load an an avatar with the same skeletal structure as you need to import at runtime
* Select it in the project tab, then go through the humanoid rigging process, ensuring everything is correct
* Select "Enforce T-Pose"
* GO to the hierarchy tab and drag your gameobject into your project tab
* It will turn blue in the hierarchy and show up as a prefab in your project
* Put that prefab in a scene. It should be your character standing in tpose
* Run. Select your character and its root. Click the button.
*
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AvatarUtils : MonoBehaviour {
List<GameObject> characters;
List<string> characterNames;
int selectedCharacter;
int root;
// Use this for initialization
void Start () {
//Get all the characters in the scene that are humanoid avatars and store them
selectedCharacter = 0;
root = 0;
characters = new List<GameObject>();
characterNames = new List<string>();
foreach (GameObject obj in UnityEngine.Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.GetComponent<Animator>() != null && obj.transform.parent == null && obj.GetComponent<Animator>().avatar != null && obj.GetComponent<Animator>().avatar.isHuman)
{
characters.Add(obj);
characterNames.Add(obj.name);
}
}
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
//Show a list of the humanoid avatars in the scene
GUILayout.BeginArea(new Rect(0, 0, Screen.width / 4.0f, Screen.height));
GUILayout.BeginVertical();
GUILayout.Label("Please select the character you'd like to try and export the info for. Be sure your character is rigged using Mechanim and is in a t-pose.");
selectedCharacter = GUILayout.SelectionGrid(selectedCharacter, characterNames.ToArray(), 1);
//Show a list of that character's children.
GUILayout.Label("Please select the character's root (the parent to the hips bone):");
List<string> names = new List<string>();
for (int i = 0; i < characters[selectedCharacter].transform.childCount; i++)
{
names.Add(characters[selectedCharacter].transform.GetChild(i).name);
}
root = GUILayout.SelectionGrid(root, names.ToArray(), 1);
GUILayout.FlexibleSpace();
//show a button for exporting the tpose file
if (GUILayout.Button("Export tpose file"))
{
exportData(selectedCharacter, names[root]);
}
GUILayout.EndVertical();
GUILayout.EndArea();
}
//Gets the transforms of the children of the given character and prints them out to file
void exportData(int selectedCharacter, string root){
GameObject character = characters[selectedCharacter];
Transform xform = character.transform.Find(root);
Dictionary<string, Transform> xforms = new Dictionary<string, Transform>();
//recursively visit the children, gathering their transform data into the xforms dictionary
recursiveTransform(xform, ref xforms);
List<string> lines = new List<string>();
//write out to file the names with all the transform data
foreach (KeyValuePair<string, Transform> t in xforms)
{
string s = t.Key + ",";
s = s + t.Value.localPosition.x + "," + t.Value.localPosition.y + "," + t.Value.localPosition.z + ",";
s = s + t.Value.localRotation.x + "," + t.Value.localRotation.y + "," +t.Value.localRotation.z + "," +t.Value.localRotation.w + ",";
s = s + t.Value.localPosition.x + "," + t.Value.localPosition.y + "," + t.Value.localPosition.z;
lines.Add(s);
}
System.IO.File.WriteAllLines("tpose.txt", lines.ToArray());
}
void recursiveTransform(Transform current, ref Dictionary<string, Transform> xforms)
{
xforms.Add(current.name, current);
for (int i = 0; i < current.childCount; ++i)
{
recursiveTransform(current.GetChild(i), ref xforms);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebCore.Models;
using WebCore.Serves;
namespace WebCore.Controllers
{
public class DepartmentsController : Controller
{
private IDepartment _db;
public DepartmentsController(IDepartment db)
{
_db = db;
}
public IActionResult Index()
{
return View(_db.GetAllDepartment());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Department ss)
{
_db.AddDepartment(ss);
return RedirectToAction("index");
}
public IActionResult Details(int id)
{
return View(_db.GetDepartment(id));
}
[HttpGet]
public IActionResult Edit(int id)
{
return View(_db.GetDepartment(id));
}
[HttpPost]
public IActionResult Edit(int id, Department st)
{
_db.EditDepartment(id, st);
return RedirectToAction("index");
}
public IActionResult Delete(int id)
{
_db.RemoveDepartment(id);
return RedirectToAction("index");
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Advertisements;
using System.Collections;
public class GameAndUIController : MonoBehaviour
{
public Text HUDLevelText;
public GameObject levelComplete;
public Text WhatRoomAndLevel;
public GameObject retryLevel;
public GameObject continueGame;
public Text timeTakenText;
public static float timeTaken;
public static int TotalRooms;
public static int RoomNumberCheckpoint;
bool RoomComplete;
public GameObject MainPausePanel;
public GameObject areYouSure;
float startTime;
bool startedUp;
public static bool HitTrigger = false;
public static bool hitCop = false;
public GameObject room1Items;
public GameObject room2Items;
public GameObject room3Items;
void Awake()
{
if(room2Items)
{
foreach (Rigidbody rb in room2Items.GetComponentsInChildren<Rigidbody>())
{
if (!rb.isKinematic)
{
rb.isKinematic = true;
}
}
}
if (room3Items)
{
foreach (Rigidbody rb in room3Items.GetComponentsInChildren<Rigidbody>())
{
if (!rb.isKinematic)
{
rb.isKinematic = true;
}
}
}
Time.timeScale = 1.0f;
Screen.sleepTimeout = SleepTimeout.NeverSleep;
HitTrigger = false;
startTime = Time.time;
UpdateRoomText();
RoomNumberCheckpoint = 1;
RoomComplete = false;
if (!hitCop)
{
timeTaken = 0f;
}
else
{
hitCop = false;
}
if (Advertisement.isSupported && !Advertisement.isInitialized)
{
Advertisement.allowPrecache = true;
Advertisement.Initialize("32757");
}
}
// Use this for initialization
//void Start()
//{
// Screen.sleepTimeout = SleepTimeout.NeverSleep;
// HitTrigger = false;
// startTime = Time.time;
// UpdateRoomText();
// RoomNumberCheckpoint = 1;
// RoomComplete = false;
// if (!hitCop)
// {
// timeTaken = 0f;
// }
// else
// {
// hitCop = false;
// }
//}
// Update is called once per frame
void Update()
{
if (!RoomComplete)
{
if (startTime + .01 < Time.time && startedUp == false)
{
MainPausePanel.SetActive(false);
startedUp = true;
}
if (Input.GetKeyUp(KeyCode.Escape))
{
if (MainPausePanel.activeInHierarchy == true)
{
UnPause();
}
else
{
Pause();
}
}
timeTaken += Time.deltaTime;
}
if (HitTrigger && !RoomComplete)
{
HitTrigger = false;
RoomComplete = true;
if (RoomNumberCheckpoint == TotalRooms)
{
switch (Application.loadedLevelName)
{
case "Level1":
{
WhatRoomAndLevel.text = "Level 1 Completed";
if (StatTracker.Level1_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 1;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level1_Complete", 1);
LevelSelector.CurrentCity = 1;
}
break;
}
case "Level2":
{
WhatRoomAndLevel.text = "Level 2 Completed";
if (StatTracker.Level2_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 1;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level2_Complete", 1);
LevelSelector.CurrentCity = 1;
}
break;
}
case "Level3":
{
WhatRoomAndLevel.text = "Level 3 Completed";
if (StatTracker.Level3_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 1;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level3_Complete", 1);
LevelSelector.CurrentCity = 2;
}
break;
}
case "Level4":
{
WhatRoomAndLevel.text = "Level 4 Completed";
if (StatTracker.Level4_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 2;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level4_Complete", 1);
LevelSelector.CurrentCity = 2;
}
break;
}
case "Level5":
{
WhatRoomAndLevel.text = "Level 5 Completed";
if (StatTracker.Level5_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 2;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level5_Complete", 1);
LevelSelector.CurrentCity = 2;
}
break;
}
case "Level6":
{
WhatRoomAndLevel.text = "Level 6 Completed";
if (StatTracker.Level6_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 2;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level6_Complete", 1);
LevelSelector.CurrentCity = 3;
}
break;
}
case "Level7":
{
WhatRoomAndLevel.text = "Level 7 Completed";
if (StatTracker.Level7_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 3;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level7_Complete", 1);
LevelSelector.CurrentCity = 3;
}
break;
}
case "Level8":
{
WhatRoomAndLevel.text = "Level 8 Completed";
if (StatTracker.Level8_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 3;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level8_Complete", 1);
LevelSelector.CurrentCity = 3;
}
break;
}
case "Level9":
{
WhatRoomAndLevel.text = "Level 9 Completed";
if (StatTracker.Level9_Complete == 1)
{
LevelSelector.UpdateMap = false;
LevelSelector.CurrentCity = 3;
}
else
{
LevelSelector.UpdateMap = true;
PlayerPrefs.SetInt("Level9_Complete", 1);
LevelSelector.CurrentCity = 3;
}
break;
}
}
StatTracker.updateStats();
}
else
{
switch (Application.loadedLevelName)
{
case "Level1":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level2":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level3":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level4":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level5":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level6":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level7":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level8":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
case "Level9":
{
WhatRoomAndLevel.text = "Room " + RoomNumberCheckpoint + " Completed";
break;
}
}
}
timeTakenText.text = "Time Taken " + string.Format("{0:00}:{1:00}", (int)(timeTaken / 60) + "m", (int)(timeTaken % 60)+"s ");
levelComplete.SetActive(true);
Time.timeScale = 0f;
if (Advertisement.isSupported && RoomNumberCheckpoint == TotalRooms && Advertisement.isInitialized)
{
StartCoroutine(ShowAdWhenReady());
}
else
{
AdFinished();
}
}
}
void UpdateRoomText()
{
switch (Application.loadedLevelName)
{
case "Level1":
{
HUDLevelText.text = "Level 1 : Room " + 1;
break;
}
case "Level2":
{
HUDLevelText.text = "Level 2 : Room " + 1;
break;
}
case "Level3":
{
HUDLevelText.text = "Level 3 : Room " + 1;
break;
}
case "Level4":
{
HUDLevelText.text = "Level 4 : Room " + 1;
break;
}
case "Level5":
{
HUDLevelText.text = "Level 5 : Room " + RoomNumberCheckpoint;
break;
}
case "Level6":
{
HUDLevelText.text = "Level 6 : Room " + RoomNumberCheckpoint;
break;
}
case "Level7":
{
HUDLevelText.text = "Level 7 : Room " + RoomNumberCheckpoint;
break;
}
case "Level8":
{
HUDLevelText.text = "Level 8 : Room " + RoomNumberCheckpoint;
break;
}
case "Level9":
{
HUDLevelText.text = "Level 9 : Room " + RoomNumberCheckpoint;
break;
}
}
}
IEnumerator ShowAdWhenReady()
{
while (!Advertisement.isReady())
yield return null;
Advertisement.Show(null, new ShowOptions
{
pause = true,
resultCallback = result =>
{
AdFinished();
}
});
}
void AdFinished()
{
continueGame.SetActive(true);
retryLevel.SetActive(true);
}
public void RestartRoom()
{
Application.LoadLevel(Application.loadedLevel);
}
public void ContinueGame()
{
Time.timeScale = 1f;
if (RoomNumberCheckpoint == TotalRooms)
{
if (Application.loadedLevelName == "Level9")
{
LoadingScreen.levelToLoad = "EndScene";
Application.LoadLevel("LoadingScreen");
}
else
{
LoadingScreen.levelToLoad = "LevelSelect";
Application.LoadLevel("LoadingScreen");
}
}
else
{
HitTrigger = false;
RoomComplete = false;
RoomNumberCheckpoint++;
if (RoomNumberCheckpoint == 2 && room2Items && room1Items)
{
foreach (Rigidbody rb in room2Items.GetComponentsInChildren<Rigidbody>())
{
if (rb.isKinematic)
{
rb.isKinematic = false;
}
}
foreach (Rigidbody rb in room1Items.GetComponentsInChildren<Rigidbody>())
{
if (!rb.isKinematic)
{
rb.isKinematic = true;
}
}
}
else if (RoomNumberCheckpoint == 3 && room3Items && room2Items)
{
foreach (Rigidbody rb in room3Items.GetComponentsInChildren<Rigidbody>())
{
if (rb.isKinematic)
{
rb.isKinematic = false;
}
}
foreach (Rigidbody rb in room2Items.GetComponentsInChildren<Rigidbody>())
{
if (!rb.isKinematic)
{
rb.isKinematic = true;
}
}
}
UpdateRoomText();
//timeTaken = 0f;
levelComplete.SetActive(false);
continueGame.SetActive(false);
retryLevel.SetActive(false);
}
}
public void AreYouSure()
{
areYouSure.SetActive(true);
}
public void GoToLevelSelect()
{
Time.timeScale = 1;
Application.LoadLevel("LevelSelect");
}
public void UnPause()
{
MainPausePanel.SetActive(false);
areYouSure.SetActive(false);
Time.timeScale = 1;
}
public void Pause()
{
MainPausePanel.SetActive(true);
areYouSure.SetActive(false);
Time.timeScale = 0;
}
}
|
using BarinakProjesi.DAL.Context;
using BarinakProjesi.DATA.Context;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Linq;
namespace BarinakProjesi.UI.Pages
{
public class IndexModel : PageModel
{
private readonly BarinakDbContext _context;
public IndexModel(BarinakDbContext context)
{
_context = context;
}
public BarinakBilgileri BarinakBilgileri { get; set; }
public void OnGet()
{
BarinakBilgileri = _context.BarinakBilgileri.Where(b => b.id == 1).FirstOrDefault();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace MediaManager.DAL.DBEntities
{
class PlaylistContent
{
[Key, Column(Order = 0)]
public int PlaylistId { get; set; }
public Playlist Playlist { get; set; }
[Key, Column(Order = 1)]
public int Id { get; set; }
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// UserAckState
/// </summary>
[DataContract]
public partial class UserAckState : IEquatable<UserAckState>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="UserAckState" /> class.
/// </summary>
/// <param name="NeedsAck">Indicates the related item has not been acknowledged..</param>
/// <param name="AckId">Identifier to use when acknowledging the related item. [category]:[entityId]:[targetId].</param>
public UserAckState(bool? NeedsAck = default(bool?), string AckId = default(string))
{
this.NeedsAck = NeedsAck;
this.AckId = AckId;
}
/// <summary>
/// Indicates the related item has not been acknowledged.
/// </summary>
/// <value>Indicates the related item has not been acknowledged.</value>
[DataMember(Name="needsAck", EmitDefaultValue=false)]
public bool? NeedsAck { get; set; }
/// <summary>
/// Identifier to use when acknowledging the related item. [category]:[entityId]:[targetId]
/// </summary>
/// <value>Identifier to use when acknowledging the related item. [category]:[entityId]:[targetId]</value>
[DataMember(Name="ackId", EmitDefaultValue=false)]
public string AckId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UserAckState {\n");
sb.Append(" NeedsAck: ").Append(NeedsAck).Append("\n");
sb.Append(" AckId: ").Append(AckId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as UserAckState);
}
/// <summary>
/// Returns true if UserAckState instances are equal
/// </summary>
/// <param name="input">Instance of UserAckState to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(UserAckState input)
{
if (input == null)
return false;
return
(
this.NeedsAck == input.NeedsAck ||
(this.NeedsAck != null &&
this.NeedsAck.Equals(input.NeedsAck))
) &&
(
this.AckId == input.AckId ||
(this.AckId != null &&
this.AckId.Equals(input.AckId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.NeedsAck != null)
hashCode = hashCode * 59 + this.NeedsAck.GetHashCode();
if (this.AckId != null)
hashCode = hashCode * 59 + this.AckId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using SafeSpace.core.Data;
using SafeSpace.core.Views;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SafeSpace.domain.Services
{
public class OrganizationAssociatedPersonRatingService
{
private readonly SafeSpaceContext _context;
private readonly AppUserRatingService _aurs;
public OrganizationAssociatedPersonRatingService(SafeSpaceContext context)
{
_context = context;
_aurs = new AppUserRatingService(context);
}
public async Task<List<AssociatedPersonView>> GetAssociatedPersonRatings(long id, string category)
{
var organization = await _context.Organizations.Include(o => o.AssociatedPersons).FirstOrDefaultAsync(o => o.Id == id);
var personlist = new List<AssociatedPersonView>();
foreach (var person in organization.AssociatedPersons)
{
var appuser = await _context.AppUsers.FirstOrDefaultAsync(a => a.Email == person.Email || a.Phone == person.Phone);
var ap = new AssociatedPersonView()
{
AssociatedPerson = person,
Rating = appuser != null ?_aurs.GetRating(appuser.Id, category) : null,
ContactRating = appuser != null ? _aurs.GetContactRating(appuser.Id, category) : null
};
personlist.Add(ap);
}
return personlist;
}
}
}
|
using System.Runtime.Serialization;
namespace Shunxi.Business.Enums
{
public enum DirectionEnum
{
[EnumMember(Value = "In")]
Anticlockwise = 0,
[EnumMember(Value = "Out")]
Clockwise
}
}
|
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class WarriorUISlot : MonoBehaviour
{
[SerializeField] private Text warriorIdText;
[SerializeField] private Text warriorNameText;
[SerializeField] private Text warriorStatsText;
[SerializeField] private Text warriorRoundText;
private Image slotImage;
private void Awake()
{
slotImage = gameObject.GetComponent<Image>();
}
public void SetSlotData(WarriorInfo warriorInfo)
{
warriorIdText.text = warriorInfo.Id.ToString();
warriorNameText.text = warriorInfo.WarriorName;
warriorStatsText.text = $"Initiative: {warriorInfo.Initiative}, Speed: {warriorInfo.Speed}";
warriorRoundText.text = warriorInfo.RoundIndex.ToString();
switch (warriorInfo.SideOfEnemy)
{
case EnemySide.RED:
slotImage.color = Color.red;
break;
case EnemySide.BLUE:
slotImage.color = Color.blue;
break;
default:
break;
}
gameObject.name =$"{warriorInfo.RoundIndex}. {warriorInfo.WarriorName} - {warriorInfo.Initiative}:{warriorInfo.Speed}";
}
public void ClearData()
{
warriorIdText.text = string.Empty;
warriorNameText.text = string.Empty;
warriorStatsText.text = string.Empty;
}
}
|
using System;
using Xamarin.Forms;
using MyListApp_5;
namespace MyListApp
{
/// <summary>
/// Tab controller.
/// </summary>
public class TabController : TabbedPage
{
MyListPage myListPage = new MyListPage();
SettingsPage settingsPage = new SettingsPage();
public TabController()
{
Children.Add(myListPage);
Children.Add(settingsPage);
Title = "My List App";
// Handle page selections
CurrentPageChanged += OnCurrentPageChanged;
}
// You may change the title.
void OnCurrentPageChanged(object obj, EventArgs args)
{
if (CurrentPage == myListPage)
Title = "My List App";
else
Title = "Settings";
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Mentors.Migrations
{
public partial class MoreContacts : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "City",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Country",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Email",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Facebook",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LinkedIn",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Phone",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "StudyPlace",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Vk",
table: "Students",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "City",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Country",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Email",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Facebook",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LinkedIn",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Phone",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "StudyPlace",
table: "Mentors",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Vk",
table: "Mentors",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "City",
table: "Students");
migrationBuilder.DropColumn(
name: "Country",
table: "Students");
migrationBuilder.DropColumn(
name: "Email",
table: "Students");
migrationBuilder.DropColumn(
name: "Facebook",
table: "Students");
migrationBuilder.DropColumn(
name: "LinkedIn",
table: "Students");
migrationBuilder.DropColumn(
name: "Phone",
table: "Students");
migrationBuilder.DropColumn(
name: "StudyPlace",
table: "Students");
migrationBuilder.DropColumn(
name: "Vk",
table: "Students");
migrationBuilder.DropColumn(
name: "City",
table: "Mentors");
migrationBuilder.DropColumn(
name: "Country",
table: "Mentors");
migrationBuilder.DropColumn(
name: "Email",
table: "Mentors");
migrationBuilder.DropColumn(
name: "Facebook",
table: "Mentors");
migrationBuilder.DropColumn(
name: "LinkedIn",
table: "Mentors");
migrationBuilder.DropColumn(
name: "Phone",
table: "Mentors");
migrationBuilder.DropColumn(
name: "StudyPlace",
table: "Mentors");
migrationBuilder.DropColumn(
name: "Vk",
table: "Mentors");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Media;
namespace thenewTextadventure
{
class Program
{
static void Main(string[] args)
{
int timer = 300;
Console.WriteLine("H");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Ha");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Hal");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Hall");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Hallo");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Hallo?");
Thread.Sleep(timer);
timer = 500;
Console.Clear();
Console.WriteLine("Hallo?, hört");
Thread.Sleep(timer);
Console.Clear();
Console.WriteLine("Hallo?, hört mich");
Thread.Sleep(timer);
Console.Clear();
sprungmarke:
Console.WriteLine("Hallo?, hört mich jemand?");
Thread.Sleep(timer);
Console.WriteLine("");
Console.WriteLine("Anworten:");
Console.WriteLine("Ja oder Nein!");
int hoeren = Antwort(Console.ReadLine());
if (hoeren == 1)
{
Console.Clear();
Console.WriteLine("Gut, wer bist du?");
}
else if (hoeren == 0)
{
Console.Clear();
Console.WriteLine("HAAAAAAALLLLLLLLOOOO, niemand da? NEEEEIIIIINNNN!");
}
else if (hoeren == -1)
{
Console.WriteLine("Ich kann dich nicht verstehen");
goto sprungmarke;
}
else
{
goto sprungmarke;
}
Console.ReadKey();
}
static int Antwort(string a)
{
if (a == "Ja")
{
return 1;
}
else if (a == "Nein")
{
return 0;
}
else
{
return -1;
}
}
}
}
|
// <copyright file="StringsTest.cs"></copyright>
using System;
using Dsa.Algorithms;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Settings;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
namespace Dsa.Algorithms
{
/// <summary>This class contains parameterized unit tests for Strings</summary>
[PexClass(typeof(Strings))]
//[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
//[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class StringsTest
{
/// <summary>Test stub for Any(String, String)</summary>
[PexMethod]
public int Any(string word, string match)
{
Func<string, string, bool> CharInAnotherString = (_word, _match) =>
{
if (_match == null)
return false;
foreach (char s in _match)
{
if (!char.IsWhiteSpace(s) && _word.Contains(s))
return true;
}
return false;
};
//match, word
Func<string, string, bool> CharInAnotherStringBeforeOrAtIndex = (_s1, _s2) =>
{
/*foreach (char s in _s2)
{
if (!char.IsWhiteSpace(s) && _s1.Contains(s))
return true;
}*/
if (_s2.TrimStart().Length == 0)
return true;
if (_s1.Contains(_s2.TrimStart()[0]))
return true;
return false;
};
Func<string, bool> EndWithWhiteSpace = (_word) =>
{
if (_word == null)
return false;
bool suffixIsWhite = false;
for (int i = 0; i < _word.Length; i++)
{
if (char.IsWhiteSpace(_word[i]))
suffixIsWhite = true;
else
suffixIsWhite = false;
}
return suffixIsWhite;
};
Func<string, bool> AllIsWhiteSpace = (_word) =>
{
int allWhite = 0;
for (int i = 0; i < _word.Length; i++)
{
if (char.IsWhiteSpace(_word[i]))
allWhite++;
}
if (_word.Length == 0)
return false;
if (allWhite == _word.Length)
return true;
return false;
};
//Isolate one exception
//PexAssume.IsTrue(word != null);
//PexAssume.IsTrue(match != null/* || word.Length == 0 || AllIsWhiteSpace(word) == true*/);
//PexAssume.IsTrue(EndWithWhiteSpace(word) == false || CharInAnotherString(word, match) == true);
//PexAssume.IsTrue(EndWithWhiteSpace(match) == false || CharInAnotherStringBeforeOrAtIndex(match, word) == true || word.Length == 0);
int result = Strings.Any(word, match);
return result;
// TODO: add assertions to method StringsTest.Any(String, String)
}
/// <summary>Test stub for IsPalindrome(String)</summary>
[PexMethod(MaxRuns=100)]
public bool IsPalindrome(string word)
{
//NullRefernce:
PexAssume.IsTrue(word != null);
//IndexOutOfRange:
//PexAssume.TrueForAny(0, word.Length, i => !char.IsWhiteSpace(word[i]) && !char.IsPunctuation(word[i]) && !char.IsSymbol(word[i]));
bool result = Strings.IsPalindrome(word);
return result;
// TODO: add assertions to method StringsTest.IsPalindrome(String)
}
/// <summary>Test stub for RepeatedWordCount(String)</summary>
[PexMethod]
public int RepeatedWordCount(string value)
{
int result = Strings.RepeatedWordCount(value);
return result;
// TODO: add assertions to method StringsTest.RepeatedWordCount(String)
}
/// <summary>Test stub for Reverse(String)</summary>
[PexMethod]
public string Reverse(string value)
{
string result = Strings.Reverse(value);
return result;
// TODO: add assertions to method StringsTest.Reverse(String)
}
/// <summary>Test stub for ReverseWords(String)</summary>
[PexMethod(MaxRuns = 100, TestEmissionFilter = PexTestEmissionFilter.All)]
public string ReverseWords(string value)
{
//PexAssume.IsTrue(value != null); -> NullReference
//PexAssume.TrueForAny(0, value.Length, i => char.IsWhiteSpace(value[i]) == false ); -> IndexOutofRange
//PexAssume.TrueForAll(0, value.Length, i => char.IsWhiteSpace(value[i]) == true); negated precondition -> IndexOutOfRange
string result = Strings.ReverseWords(value);
return result;
// TODO: add assertions to method StringsTest.ReverseWords(String)
}
/*** Seed test for ReverseWords(string value) ***/
[TestMethod]
public void seedReverseWords()
{
string seed = "\t\t\t\t\t\t\t\t"; // string of length 8
ReverseWords(seed);
}
/// <summary>Test stub for Strip(String)</summary>
[PexMethod]
public string Strip(string value)
{
string result = Strings.Strip(value);
return result;
// TODO: add assertions to method StringsTest.Strip(String)
}
/// <summary>Test stub for WordCount(String)</summary>
[PexMethod]
public int WordCount(string value)
{
int result = Strings.WordCount(value);
return result;
// TODO: add assertions to method StringsTest.WordCount(String)
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Extensions.Options;
namespace AzureBlobUpload.Pages
{
public class UploadModel : PageModel
{
private readonly IOptions<StorageAccountInfo> _storageAccountInfOptions;
public UploadModel(IOptions<StorageAccountInfo> storageAccountInfOptions)
=> _storageAccountInfOptions = storageAccountInfOptions;
[BindProperty]
public IFormFile Upload { get; set; }
[BindProperty]
public List<CloudBlob> CarrierLogos { get; set; }
public void OnGet()
{
var cloudStorageAccount = CloudStorageAccount.Parse(_storageAccountInfOptions.Value.ConnectionString);
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(_storageAccountInfOptions.Value.ContainerName);
CarrierLogos = cloudBlobContainer.ListBlobs()
.Select(_ => (CloudBlob) _)
.ToList();
}
public async Task OnPostAsync()
{
var cloudStorageAccount = CloudStorageAccount.Parse(_storageAccountInfOptions.Value.ConnectionString);
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(_storageAccountInfOptions.Value.ContainerName);
var fileName = Upload.FileName;
var fileMimeType = Upload.ContentType;
if (await cloudBlobContainer.CreateIfNotExistsAsync())
await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
cloudBlockBlob.Properties.ContentType = fileMimeType;
await cloudBlockBlob.UploadFromStreamAsync(Upload.OpenReadStream());
var uri = cloudBlockBlob.Uri.AbsoluteUri;
OnGet();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BusSunburnTextbarScript : MonoBehaviour
{
RectTransform rectTrans;
float y;
private Vector2 hide;
GameObject BusConvo;
BusConvoScript busConvoScript;
bool sTalking;
bool talking;
// Start is called before the first frame update
void Start()
{
rectTrans = GetComponent<RectTransform>();
y = rectTrans.position.y;
hide = new Vector2(0, 1000);
BusConvo = GameObject.FindWithTag("GameController");
busConvoScript = BusConvo.GetComponent<BusConvoScript>();
sTalking = busConvoScript.sTalking;
talking = busConvoScript.talking;
}
// Update is called once per frame
void Update()
{
talking = busConvoScript.getTalking();
if (talking == true && busConvoScript.sTalking == true)
{
}
if (busConvoScript.sTalking == false)
{
}
}
}
|
#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
#endregion
namespace ScratchyXna
{
class TestScreen : Scene
{
Text ScoreText;
Text RestartText;
Text HappyText;
Hypnodisc hypnodisc;
Mugatu mugatu;
/// <summary>
/// Load the game over screen
/// </summary>
public override void Load()
{
// GridStyle = GridStyles.Ticks;
BackgroundColor = Color.Black;
FontName = "QuartzMS";
// Add the score text
ScoreText = AddText(new Text
{
Alignment = HorizontalAlignments.Left,
VerticalAlign = VerticalAlignments.Top,
Scale = .4f,
Position = new Vector2(-100f, 100f),
Color = Color.White
});
// Add the start key text
RestartText = AddText(new Text
{
Value = "Press SPACE to Play Again",
Position = new Vector2(0f, -100f),
Alignment = HorizontalAlignments.Center,
VerticalAlign = VerticalAlignments.Bottom,
AnimationType = TextAnimations.Typewriter,
AnimationSeconds = 0.2,
Scale = 0.5f,
Color = Color.Lime
});
if (Game.Platform == GamePlatforms.XBox)
{
RestartText.Value = "Press START to Play Again";
}
else if (Game.Platform == GamePlatforms.WindowsPhone)
{
RestartText.Value = "TAP to Play Again";
}
AddSound("happyhappy");
hypnodisc = AddSprite<Hypnodisc>();
mugatu = AddSprite<Mugatu>();
HappyText = AddText(new Text {
Value = "HAPPY",
Color = Color.OrangeRed,
Scale = 3,
Position = new Vector2(0, 90),
Alignment = HorizontalAlignments.Center });
}
/// <summary>
/// Start the game over screen
/// </summary>
public override void StartScene()
{
// Display the final score
ScoreText.Value = "Score: Kickass"; // +SpaceInvaders.score;
PlaySound("happyhappy", true);
}
/// <summary>
/// Update the game over screen
/// </summary>
/// <param name="gameTime">Time since the last update</param>
public override void Update(GameTime gameTime)
{
HappyText.X = (float)Math.Sin(gameTime.TotalGameTime.TotalSeconds) * 20;
HappyText.Color = new Color(
(int)(Math.Sin(gameTime.TotalGameTime.TotalSeconds) * 255f),
(int)(Math.Sin(gameTime.TotalGameTime.TotalSeconds * 1.3) * 255f),
(int)(Math.Sin(gameTime.TotalGameTime.TotalSeconds * 2) * 255f));
if (Keyboard.KeyPressed(Keys.H))
{
//HappyText.Y = -50;
HappyText.VerticalAlign = VerticalAlignments.Top;
// HappyText.Position = new Vector2(0, 0);
Sprite HappySprite = HappyText.CreateSprite();
//HappySprite.Costume.YCenter = VerticalAlignments.Bottom;
//AddSprite(HappySprite);
hypnodisc.Stamp(HappySprite, StampMethods.Cutout);
HappySprite.X -= 1;
HappySprite.Y += 1;
hypnodisc.Stamp(HappySprite, StampMethods.Normal);
}
if (Keyboard.KeyPressed(Keys.S))
{
mugatu.Costume.YCenter = VerticalAlignments.Top;
//mugatu.X = Random.Next(-100, 100);
//mugatu.Y = Random.Next(-100, 100);
//mugatu.X = -80;
//mugatu.Y = -80;
//hypnodisc.X = -80;
//hypnodisc.Y = -80;
//hypnodisc.Stamp(mugatu, StampMethods.Cutout);
hypnodisc.Stamp(mugatu, StampMethods.Normal);
//mugatu.X = 0;
//mugatu.Y = 0;
//hypnodisc.X = 0;
//hypnodisc.Y = 0;
}
// Space key to play again
if (Keyboard.KeyPressed(Keys.Space))
{
//todo: also do this for phone tap
//todo: also do this for xbox a button
ShowScene("play");
}
}
}
}
|
using Smart.Distribution.Station.Configuration;
using Smart.Distribution.Station.Controls;
using Smart.Distribution.Station.Domain;
using Smart.Distribution.Station.Jobs;
using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Smart.Distribution.Station
{
public partial class MainForm : Form
{
private static readonly ILog Logger = LogManager.GetLogger(typeof(MainForm));
private SwitchStationPanel switchStationPanel;
private LowValtageStationPanel lowValtageStationPanel;
private UserStationControl userStationControl;
private PartialDischargeControl partialDischargeControl;
private LowValtageControl lowValtageControl;
private VedioControl vedioControl;
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public MainForm()
{
this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
this.MouseDown += new MouseEventHandler(MainForm_MouseDown);
this.vedioControl.InitializeRealPlayBox(HenleeConfigurator.Configuration.Vedios.ToArray());
this.timer.Interval = 5000;
this.timer.Enabled = true;
this.timer.Start();
}
private void ResetButtonBackColor(Button clickedButton)
{
foreach (var c in this.navBar.tableLayoutPanel1.Controls)
{
Button btn = null;
if (c is Button)
{
btn = ((Button)c);
}
if (btn != null)
{
Color backColor = Color.FromArgb(27, 41, 75);
if (btn.Name == clickedButton.Name)
{
backColor = Color.FromArgb(54, 133, 254);
}
btn.BackColor = backColor;
}
}
}
private void RelayoutMasterPanel(Action<TableLayoutPanel> action, TableLayoutPanel tlp)
{
tlp.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
tlp.Controls.Clear();
action(tlp);
tlp.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
tlp.PerformLayout();
this.tableLayoutPanel1.PerformLayout();
this.PerformLayout();
}
private void MainForm_Load(object sender, EventArgs e)
{
this.lblCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
this.timerTimeSync.Interval = 1000;
this.timerTimeSync.Start();
this.timerTimeSync.Enabled = true;
Application.DoEvents();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.lblCurrentTime.Text =DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
CHCNetSDK.NET_DVR_Cleanup();
Application.Exit();
}
private void TimerEventProcessor(object sender, EventArgs e)
{
timer.Stop();
Application.DoEvents();
var job = new MonitorJob();
job.Execute(null);
var properties = HenleeConfigurator.Configuration.Modbus.Properties.ToArray();
var property = properties[0];
//label1.Text = string.Format("{0}: {1}{2}", property.Name, property.Value * property.Precision, property.Unit);
//property = properties[1];
//label2.Text = string.Format("{0}: {1}{2}", property.Name, property.Value * property.Precision, property.Unit);
//property = properties[2];
//label3.Text = string.Format("{0}: {1}{2}", property.Name, property.Value * property.Precision, property.Unit);
//property = properties[3];
//label4.Text = string.Format("{0}: {1}{2}", property.Name, property.Value * property.Precision, property.Unit);
timer.Start();
}
private void InitializeTimer(int interval)
{
timer.Tick += new EventHandler(TimerEventProcessor);
timer.Enabled = true;
// Sets the timer interval to 5 seconds.
timer.Interval = interval;
timer.Start();
}
private void MainForm_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
private void timer_Tick(object sender, EventArgs e)
{
OnDataChanged();
}
private void OnDataChanged()
{
Random random = new Random();
SwitchStationPanelEntity sspe = new SwitchStationPanelEntity()
{
Degree = random.Next(2510, 3610),
Humidity = random.Next(5650, 7830),
SF6 = Convert.ToBoolean(random.Next(0, 2)),
Magnetic = Convert.ToBoolean(random.Next(0, 2)),
SmokeDetector = Convert.ToBoolean(random.Next(0, 2)),
Vibration = Convert.ToBoolean(random.Next(0, 2)),
Infrared = Convert.ToBoolean(random.Next(0, 2)),
WaterSoaked = Convert.ToBoolean(random.Next(0, 2)),
Lighting = Convert.ToBoolean(random.Next(0, 2)),
Ventilator = Convert.ToBoolean(random.Next(0, 2)),
MouseAntiMouse = Convert.ToBoolean(random.Next(0, 2)),
FloodTideLamp = Convert.ToBoolean(random.Next(0, 2))
};
LowValtagePanelEntity lvpe = new LowValtagePanelEntity()
{
DegreeA = random.Next(2510, 3610),
DegreeB = random.Next(2600, 3800),
DegreeC = random.Next(2810, 3910),
Ua = random.Next(4650, 7830),
Ub = random.Next(3050, 7830),
Uc = random.Next(5650, 7830),
Ia = random.Next(1850, 2030),
Ib = random.Next(2050, 2130),
Ic = random.Next(2550, 3130),
SF6 = Convert.ToBoolean(random.Next(0, 2)),
Magnetic = Convert.ToBoolean(random.Next(0, 2)),
SmokeDetector = Convert.ToBoolean(random.Next(0, 2)),
Vibration = Convert.ToBoolean(random.Next(0, 2)),
Infrared = Convert.ToBoolean(random.Next(0, 2)),
WaterSoaked = Convert.ToBoolean(random.Next(0, 2)),
Lighting = Convert.ToBoolean(random.Next(0, 2)),
Ventilator = Convert.ToBoolean(random.Next(0, 2)),
MouseAntiMouse = Convert.ToBoolean(random.Next(0, 2)),
FloodTideLamp = Convert.ToBoolean(random.Next(0, 2))
};
for (int i = 0; i < this.userStationControl.UserStationControls.Length; i++)
{
UserStationEntity use = new UserStationEntity()
{
P = random.Next(6250, 7250),
I = random.Next(2730, 3600),
U = random.Next(2730, 3600),
};
this.userStationControl.UserStationControls[i].DataSource = use;
}
LowValtageEntity lve = new LowValtageEntity()
{
Ajx = Convert.ToBoolean(random.Next(0, 2)),
Drg = Convert.ToBoolean(random.Next(0, 2)),
QfOne = Convert.ToBoolean(random.Next(0, 2)),
QfTwo = Convert.ToBoolean(random.Next(0, 2)),
QfThree = Convert.ToBoolean(random.Next(0, 2)),
Yellow = random.Next(2510, 3610),
Green = random.Next(2600, 3800),
Red = random.Next(2810, 3910),
};
this.lowValtageControl.DataSource = lve;
this.switchStationPanel.DataSource = sspe;
this.lowValtageStationPanel.DataSource = lvpe;
}
private void navBar_ButtonClicked(object sender, NavBarClickEventArgs e)
{
ResetButtonBackColor((Button)sender);
switch (e.ButtonType)
{
case ButtonType.Environment:
RelayoutMasterPanel(tlp =>
{
tlp.Controls.Add(this.switchStationPanel, 0, 0);
tlp.Controls.Add(this.lowValtageStationPanel, 2, 0);
}, tableLayoutPanel2);
break;
case ButtonType.LowValtage:
RelayoutMasterPanel(tlp =>
{
tlp.Controls.Add(lowValtageControl, 0, 0);
tlp.SetColumnSpan(lowValtageControl, 3);
}, tableLayoutPanel2);
break;
case ButtonType.PartialDischarge:
RelayoutMasterPanel(tlp =>
{
tlp.Controls.Add(partialDischargeControl, 0, 0);
tlp.SetColumnSpan(partialDischargeControl, 3);
}, tableLayoutPanel2);
break;
case ButtonType.UserStation:
RelayoutMasterPanel(tlp =>
{
tlp.Controls.Add(userStationControl, 0, 0);
tlp.SetColumnSpan(userStationControl, 3);
}, tableLayoutPanel2);
break;
case ButtonType.Vedio:
RelayoutMasterPanel(tlp =>
{
tlp.Controls.Add(vedioControl, 0, 0);
tlp.SetColumnSpan(vedioControl, 3);
}, tableLayoutPanel2);
break;
default:
break;
}
}
}
}
|
namespace Codelet.AspNetCore.Mvc.Cqrs
{
using System;
using System.Collections.Concurrent;
using Codelet.AspNetCore.Mvc.Cqrs.Infrastructure;
using Codelet.AspNetCore.Mvc.Cqrs.Infrastructure.Routing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
/// <summary>
/// Helpers for generation URLs for queries, commands and view models.
/// </summary>
public static class UrlHelperExtensions
{
private static ConcurrentDictionary<Type, string> ViewsCache { get; }
= new ConcurrentDictionary<Type, string>();
/// <summary>
/// Generates the URL for the GET request for the given <paramref name="route"/>.
/// </summary>
/// <remarks>
/// <paramref name="route"/> properties are converted to URL query parameters.
/// </remarks>
/// <typeparam name="TRoute">The type of the route.</typeparam>
/// <param name="urlHelper">The URL helper.</param>
/// <param name="route">The route.</param>
/// <returns>The generated URL.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="urlHelper" /> == <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="route" /> == <c>null</c>.</exception>
public static Uri Get<TRoute>(this IUrlHelper urlHelper, TRoute route)
=> urlHelper.Link<TRoute>(CqrsRouter.UrlRoute, route);
/// <summary>
/// Generates the URL for the POST request for the given <paramref name="route"/>.
/// </summary>
/// <remarks>
/// <paramref name="route"/> properties are ignored as they should be a part of POST request body.
/// </remarks>
/// <typeparam name="TRoute">The type of the route.</typeparam>
/// <param name="urlHelper">The URL helper.</param>
/// <param name="route">The route.</param>
/// <returns>The generated URL.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="urlHelper" /> == <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="route" /> == <c>null</c>.</exception>
public static Uri Post<TRoute>(this IUrlHelper urlHelper, TRoute route)
=> new UriBuilder(urlHelper.Get(route)) { Query = string.Empty }.Uri;
/// <summary>
/// Generates the view path for the given <paramref name="route"/>.
/// </summary>
/// <typeparam name="TRoute">The type of the route.</typeparam>
/// <param name="urlHelper">The URL helper.</param>
/// <param name="route">The route.</param>
/// <returns>The generated view path.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="urlHelper" /> == <c>null</c>.</exception>
internal static string ViewPath<TRoute>(this IUrlHelper urlHelper, TRoute route)
=> ViewsCache.GetOrAdd(typeof(TRoute), _ => urlHelper.Link<TRoute>(CqrsRouter.ViewRoute, route).AbsolutePath.Trim('/'));
private static Uri Link<TRoute>(this IUrlHelper urlHelper, string route, TRoute value)
{
urlHelper = urlHelper ?? throw new ArgumentNullException(nameof(urlHelper));
route = route.HasContent() ? route : throw new ArgumentNullException(nameof(route));
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var values = new RouteValueDictionary(value) { { CqrsRouter.RouteTypeKey, value.GetType() } };
var url = urlHelper.Link(route, values);
return new Uri(url, UriKind.Absolute);
}
}
} |
using System;
using System.Text;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class ApplicationHelper
{
public static string platformFolder
{
get
{
return ApplicationHelper.GetPlatformFolderForAssetBundles(Application.get_platform());
}
}
public static string persistentDataPath
{
get
{
return Application.get_persistentDataPath();
}
}
public static bool AssetBundleLoadMode
{
get
{
return true;
}
}
private static string GetPlatformFolderForAssetBundles(RuntimePlatform platform)
{
switch (platform)
{
case 1:
return "OSX";
case 2:
return "Windows";
case 3:
case 5:
return "WebPlayer";
case 8:
return "iOS";
case 11:
return "Android";
}
return null;
}
public static string ParseToUTF8URL(string url)
{
string text = string.Empty;
for (int i = 0; i < url.get_Length(); i++)
{
if (url.get_Chars(i) >= '一' && url.get_Chars(i) <= '龥')
{
text += WWW.EscapeURL(url.get_Chars(i).ToString(), Encoding.get_UTF8());
}
else
{
text += url.get_Chars(i).ToString();
}
}
return text;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
//using UnityEditor;
public class BvaAnim : MonoBehaviour {
public string fname="samiNewSoran.vpm";
public string setting="map15seg.dat";
public Boolean hipMove=true;
public float mocapScale=-1.0f;
public int fixFrame=-1;
public AudioSource music = null;
public BvaAnim follow = null;
public string poseType="T_POSE";
public Boolean upperBodyFlag = true;
public Boolean lowerBodyFlag = true;
public Boolean hipRotFlag = true;
private Dictionary<string,string> reName = new Dictionary<string,string>();
private Dictionary<string,GameObject> bodys = new Dictionary<string,GameObject>();
private Dictionary<string,SSens> sensors = new Dictionary<string,SSens>();
private string[] delimiter = {" ","\t"};//区切り文字
private string[] names ={
"Head","Body","Hip",
"R-UpperArm","R-ForeArm","R-Hand",
"L-UpperArm","L-ForeArm","L-Hand",
"R-Thigh","R-Shin","R-Foot",
"L-Thigh","L-Shin","L-Foot"};
private float ang=0;
private Quaternion baseForm;
private Vector3 basePos;
private int loadFlag=-1;
// Use this for initialization
void Start () {
baseForm = this.transform.rotation;
basePos= this.transform.position;
if(mocapScale<=0){
mocapScale = this.transform.localScale[1];
}
for(int i=0;i<names.Length;i++){
string n = names[i];
bodys[n]=getBodyObject(n);
sensors[n]=new SSens();
}
loadSetting();
if(follow==null){
loadMoCap();
}
else{
sensors = follow.getSensors();
}
loadFlag=1;
}
public Dictionary<string,SSens> getSensors(){
return sensors;
}
// Update is called once per frame
void Update () {
float time= -1;
if(music!=null){
time=music.time;
}
if(loadFlag==1){
ang +=1;
for(int i=0;i<names.Length;i++){
string n=names[i];
if(getBodyFlag(n)){
if(music==null){
sensors[n].nextTime();
}
else {
sensors[n].setSec(time);
}
GameObject body=bodys[n];
Quaternion rot = sensors[n].getRot();
Quaternion tBase = new Quaternion();
tBase.eulerAngles=new Vector3(0,0,0);
Quaternion b = new Quaternion();
b.eulerAngles=new Vector3(0,0,0);
if(fixFrame>=0){
tBase = sensors[n].getRot(fixFrame);
}
int dir=0;
if(poseType=="T_POSE"){
dir=1;
}
else if(poseType=="I_POSE"){
dir=-1;
}
if(dir!=0){ // not N_POSE
if(n=="R-UpperArm" || n=="R-ForeArm" || n=="R-Hand"){
b.eulerAngles=new Vector3(0,0, 45*dir);
}
else if(n=="L-UpperArm" || n=="L-ForeArm" || n=="L-Hand"){
b.eulerAngles=new Vector3(0,0,-45*dir);
}
}
Quaternion r =baseForm*rot* Quaternion.Inverse(tBase)*b;
body.transform.rotation=r;
if(n=="Hip" && hipMove){
Vector3 tPos = sensors[n].getPos(0);
tPos[1]=0;
Vector3 pos = sensors[n].getPos();
body.transform.position=pos-tPos+basePos;
}
}
}
}
}
private Boolean getBodyFlag(string n){
Boolean result = true;
if(n=="Hip"){
result = hipRotFlag;
}
else if(n=="R-Thigh" || n=="R-Shin" || n=="R-Foot"
|| n=="L-Thigh" || n=="L-Shin" || n=="L-Foot"){
result=lowerBodyFlag;
}
else if(n=="Head" || n=="Body"
|| n=="R-UpperArm" || n=="R-ForeArm" || n=="R-Hand"
|| n=="L-UpperArm" || n=="L-ForeArm" || n=="L-Hand"){
result=upperBodyFlag;
}
return result;
}
private void loadMoCap(){
int nlineCount = 0;
System.IO.StreamReader cReader = (
new System.IO.StreamReader(Application.dataPath+"/MoCap/"+fname, System.Text.Encoding.Default)
);
string st;
int frame=-5;
string segName="";
while( (st = cReader.ReadLine())!=null){
nlineCount++;
frame++;
string[] stBuffer = st.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
if(stBuffer[0]=="Segment:"){
frame=-5;
segName=reName[stBuffer[1]];
}
if(frame>=0 && segName!=null){
Vector3 pos = str2Pos(stBuffer[0],stBuffer[1],stBuffer[2]);
Vector3 rot = str2Rot(stBuffer[3],stBuffer[4],stBuffer[5]);
sensors[segName].addData(frame,pos,rot);
}
}
cReader.Close();
}
Vector3 str2Pos(string px,string py,string pz){
float w = (float)(0.024*mocapScale);
Vector3 pos = new Vector3(
-float.Parse(px)*w,
float.Parse(py)*w,
float.Parse(pz)*w
);
return pos;
}
Vector3 str2Rot(string rx,string ry, string rz){
Vector3 rot = new Vector3(
-float.Parse(rz), //ry,-
-float.Parse(ry),
float.Parse(rx) //rx
);
return rot;
}
private void loadSetting(){
int nlineCount = 0;
System.IO.StreamReader cReader = (
new System.IO.StreamReader(Application.dataPath+"/MoCap/"+setting, System.Text.Encoding.Default)
);
string st;
while( (st = cReader.ReadLine())!=null){
nlineCount++;
string[] stBuffer = st.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
if(stBuffer[0]!="#"){
this.reName[stBuffer[0]]=stBuffer[1];
}
}
cReader.Close();
}
private GameObject getBodyObject(string n){
string path = this.name+"/-1.!Root/-1.!joint_Char/0.!joint_Center";
if(n=="R-UpperArm"){
path+="/1.joint_Torso/29.joint_RightClavicle/30.joint_RightShoulder";
}
else if(n=="R-ForeArm"){
path+="/1.joint_Torso/29.joint_RightClavicle/30.joint_RightShoulder/31.joint_RightElbow";
}
else if(n=="R-Hand"){
path+="/1.joint_Torso/29.joint_RightClavicle/30.joint_RightShoulder/31.joint_RightElbow/32.joint_RightWrist";
}
//////
else if(n=="L-UpperArm"){
path+="/1.joint_Torso/7.joint_LeftClavicle/8.joint_LeftShoulder";
}
else if(n=="L-ForeArm"){
path+="/1.joint_Torso/7.joint_LeftClavicle/8.joint_LeftShoulder/9.joint_LeftElbow";
}
else if(n=="L-Hand"){
path+="/1.joint_Torso/7.joint_LeftClavicle/8.joint_LeftShoulder/9.joint_LeftElbow/10.joint_LeftWrist";
}
///////////////////
else if(n=="R-Thigh"){
path+="/6.joint_HipMaster/48.joint_RightHip";
}
else if(n=="R-Shin"){
path+="/6.joint_HipMaster/48.joint_RightHip/49.joint_RightKnee";
}
else if(n=="R-Foot"){
path+="/6.joint_HipMaster/48.joint_RightHip/49.joint_RightKnee/50.joint_RightFoot";
}
//////
else if(n=="L-Thigh"){
path+="/6.joint_HipMaster/26.joint_LeftHip";
}
else if(n=="L-Shin"){
path+="/6.joint_HipMaster/26.joint_LeftHip/27.joint_LeftKnee";
}
else if(n=="L-Foot"){
path+="/6.joint_HipMaster/26.joint_LeftHip/27.joint_LeftKnee/28.joint_LeftFoot";
}
///////////////////
else if(n=="Head"){
path+="/1.joint_Torso/2.joint_Neck/3.joint_Head";
}
else if(n=="Body"){
path+="/1.joint_Torso";
}
else if(n=="Hip"){
//path+="/6.joint_HipMaster";
path+="";
}
return GameObject.Find(path);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace ProducerConsumer
{
/// <summary>
/// Place an order for a total amount across a collection of stores.
/// Process takes place as follows:
/// - each store creates an order task that holds all state and store-order functionality
/// - for every order task, launch a get quote task
/// - a get quote task attempts to get a store quote, then add it to the quote list, the check to see if the minimum amount of time has passed, then signal that storeorders should be attempted
/// - store orders are attempted by checking if there is any amount left to fill in the order
/// - if yes then pull the best quote, and attempt to place an order. all state variables need to be updated.
/// - after an order is completed signal that store orders should be attempted
/// </summary>
class Program
{
static async Task Main(string[] args)
{
List<Store> stores = Enumerable.Range( 0, 10 ).Select( i => new Store( i.ToString() ) ).ToList();
var order = new Order(stores, 1100);
await order.Start();
Console.ReadKey();
}
}
}
|
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Twitter
{
public static class SessionExtensions
{
private const string MAIL = "usermail";
private const string ID = "userid";
public static void SetUserEmail (this ISession session, string email)
{
session.SetString("MAIL", email);
}
public static string GetUserEmail(this ISession session)
{
return session.GetString("MAIL");
}
public static void SetUserId (this ISession session, int id)
{
session.SetInt32("ID",id);
}
public static int? GetUserId(this ISession session)
{
return session.GetInt32(ID);
}
}
}
|
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 System.Diagnostics;
using System.Collections;
using FurnitureRentalSystem.Model;
using FurnitureRentalSystem.Controller;
using FurnitureRentalSystem.View;
namespace FurnitureRentalSystem
{
public partial class EmployeeForm : Form
{
private ErrorProvider errorProvider;
private LoginInformation loginInformation;
private ArrayList stateAbbrevs;
private ErrorProvider rentErrorProvider;
private DataTable rentalInfoTable;
private DataTable returnInfoTable;
public EmployeeForm(LoginInformation loginInformation)
{
InitializeComponent();
this.AcceptButton = this.registerCustomerButton;
this.PopulateStateComboBox();
this.SetUpRegisterCustomerControls();
this.errorProvider = new ErrorProvider();
this.loginInformation = loginInformation;
this.loggedInLabel.Text = String.Format("You are logged in as: {0}. Click to logout.", this.loginInformation.getName());
this.rentErrorProvider = new ErrorProvider();
this.SetUpRentalInfoTable();
this.SetUpReturnInfoTable();
}
//******************************Menu Item Event Handlers**************************
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
String aboutMessage = "Furniture Rental System\nVersion 0.1\nCreated By: Justin Walker and Jennifer Holland";
MessageBox.Show(aboutMessage, "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void registerCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.SelectTab(registerCustomerTab);
}
private void searchForCustomerIDToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.SelectTab(searchForCustomerIDTab);
}
private void searchForFurnitureToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.SelectTab(searchFurnitureTab);
}
private void rentFurnitureToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.SelectTab(rentFurnitureTab);
}
private void returnFurnitureToolStripMenuItem_Click(object sender, EventArgs e)
{
tabControl.SelectTab(returnFurnitureTab);
}
//****************************Tab Control Event Handlers***************************
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
switch (tabControl.SelectedIndex)
{
case 0:
this.AcceptButton = this.registerCustomerButton;
break;
case 1:
this.AcceptButton = this.searchSearchCustomerButton;
break;
}
}
//***************************Login Label Event Handlers*******************
private void loggedInLabel_Click(object sender, EventArgs e)
{
Application.Restart();
}
//***************************************************************************************************************
//*******************************************SEARCH FURNITURE TAB **********************************************
//***************************************************************************************************************
//************************Search Furniture Methods***************************
private bool EnsureSearchFurnitureFieldsAreCompleted()
{
if (String.IsNullOrEmpty(this.searchFurnitureCriteriaTextBox.Text))
{
this.errorSearchFurnitureLabel.Text = "Please provide search criteria.";
this.errorSearchFurnitureLabel.Visible = true;
return false;
}
else
{
this.errorSearchFurnitureLabel.Visible = false;
return true;
}
}
private void PerformFurnitureSearch()
{
DatabaseAccessController dbAccess = new DatabaseAccessController();
string searchCriteria = this.searchFurnitureCriteriaTextBox.Text;
ArrayList results = dbAccess.SearchFurniture(searchCriteria);
if (results.Count != 0)
{
this.PlaceSearchResultsInList(results, this.searchResultsSearchFurnitureListView);
}
else
{
this.NoResultsFound(this.searchResultsSearchFurnitureListView);
}
this.ResizeListViewColumns(this.searchResultsSearchFurnitureListView);
}
//************************Click Event Handlers*******************************
private void searchSearchFurnitureButton_Click(object sender, EventArgs e)
{
this.searchResultsSearchFurnitureListView.Items.Clear();
bool canPerformSearch = this.EnsureSearchFurnitureFieldsAreCompleted();
if (canPerformSearch)
{
this.PerformFurnitureSearch();
}
}
//***************************************************************************************************************
//*******************************************SEARCH CUSTOMER TAB **********************************************
//***************************************************************************************************************
//************************Search Customer ID Methods*************************
private bool EnsureSearchCustomerFieldsAreCompleted()
{
if ((String.IsNullOrEmpty(this.firstNameSearchCustomerTextBox.Text) || String.IsNullOrEmpty(this.lastNameSearchCustomerTextBox.Text)) && this.nameSearchCustomerRadioButton.Checked)
{
this.errorSearchCustomerLabel.Text = "Please fill out both First and Last Name.";
this.errorSearchCustomerLabel.Visible = true;
return false;
}
else if (String.IsNullOrEmpty(this.phoneNumberSearchCustomerMaskedTextBox.Text) && this.phoneSearchCustomerRadioButton.Checked)
{
this.errorSearchCustomerLabel.Text = "Please enter a valid Phone Number.";
this.errorSearchCustomerLabel.Visible = true;
return false;
}
else
{
this.errorSearchCustomerLabel.Visible = false;
return true;
}
}
private void PerformCustomerSearch()
{
DatabaseAccessController dbc = new DatabaseAccessController();
String fname = this.firstNameSearchCustomerTextBox.Text;
String lname = this.lastNameSearchCustomerTextBox.Text;
String phone = this.phoneNumberSearchCustomerMaskedTextBox.Text;
ArrayList customers = dbc.GetCustomers(fname, lname, phone);
if (customers.Count != 0)
{
this.PlaceSearchResultsInList(customers, this.searchResultsSearchCustomerListView);
}
else
{
this.NoResultsFound(this.searchResultsSearchCustomerListView);
}
this.ResizeListViewColumns(this.searchResultsSearchCustomerListView);
}
private void ClearSearchCustomerFields()
{
this.firstNameSearchCustomerTextBox.Text = "";
this.lastNameSearchCustomerTextBox.Text = "";
this.phoneNumberSearchCustomerMaskedTextBox.Text = "";
this.errorSearchCustomerLabel.Visible = false;
this.errorProvider.Clear();
}
//************************Click event handlers*************************
private void searchSearchCustomerButton_Click(object sender, EventArgs e)
{
this.searchResultsSearchCustomerListView.Items.Clear();
bool canPerformSearch = this.EnsureSearchCustomerFieldsAreCompleted();
if (canPerformSearch)
{
this.PerformCustomerSearch();
}
}
private void keyPress(object sender, KeyPressEventArgs e)
{
int asciiCode = Convert.ToInt32(e.KeyChar);
if (!(asciiCode >= 65 && asciiCode <= 90) && !(asciiCode >= 97 && asciiCode <= 122) && !(asciiCode == 8) && !(asciiCode == 45) && !(asciiCode == 39))
{
e.Handled = true;
}
}
//************************KeyDown event handlers**************
private void nameSearchCustomerRadioButton_CheckedChanged(object sender, EventArgs e)
{
this.ClearSearchCustomerFields();
if (this.nameSearchCustomerRadioButton.Checked)
{
this.phoneNumberSearchCustomerMaskedTextBox.Enabled = false;
}
else
{
this.phoneNumberSearchCustomerMaskedTextBox.Enabled = true;
}
}
private void phoneSearchCustomerRadioButton_CheckedChanged(object sender, EventArgs e)
{
this.ClearSearchCustomerFields();
if (this.phoneSearchCustomerRadioButton.Checked)
{
this.firstNameSearchCustomerTextBox.Enabled = false;
this.lastNameSearchCustomerTextBox.Enabled = false;
}
else
{
this.firstNameSearchCustomerTextBox.Enabled = true;
this.lastNameSearchCustomerTextBox.Enabled = true;
}
}
//***************************************************************************************************************
//*******************************************SEARCH TABS SHARED **********************************************
//***************************************************************************************************************
//**********************************************Search Methods*************************************************
private void PlaceSearchResultsInList(ArrayList results, ListView resultView)
{
int numberOfColumns = resultView.Columns.Count;
int counter = 0;
ListViewItem listViewItem = new ListViewItem();
while (counter < results.Count)
{
if (counter == 0)
{
listViewItem = new ListViewItem(Convert.ToString(results[counter]), 0);
counter++;
}
else if (counter % numberOfColumns == 0)
{
resultView.Items.Add(listViewItem);
listViewItem = new ListViewItem(Convert.ToString(results[counter]), 0);
counter++;
}
else
{
listViewItem.SubItems.Add(Convert.ToString(results[counter]));
counter++;
}
if (counter == results.Count)
{
resultView.Items.Add(listViewItem);
}
}
}
private void NoResultsFound(ListView resultView)
{
resultView.Items.Clear();
ListViewItem noResultsViewItem = new ListViewItem("No Results Found", 0);
resultView.Items.Add(noResultsViewItem);
}
private void ResizeListViewColumns(ListView lv)
{
foreach (ColumnHeader column in lv.Columns)
{
column.Width = -2;
}
}
//***************************************************************************************************************
//*******************************************REGISTER CUSTOMER TAB **********************************************
//***************************************************************************************************************
//**********************Select ComboBox Item Event Handlers******************************
private void stateAbbrevComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.stateAbbrevs.Contains(this.stateAbbrevComboBox.SelectedItem))
{
this.errorProvider.SetError(this.stateAbbrevComboBox, "Must make selection.");
}
else
{
this.errorProvider.SetError(this.stateAbbrevComboBox, "");
}
this.stateAbbrevComboBox.Tag = this.stateAbbrevs.Contains(this.stateAbbrevComboBox.SelectedItem);
this.ValidateAll();
}
//**********************MaskInputRejected event handlers************************
private void numericMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
MaskedTextBox maskedTextBox = (MaskedTextBox)sender;
if (!maskedTextBox.MaskFull && e.Position != maskedTextBox.Mask.Length)
{
this.errorProvider.SetError(maskedTextBox, "You can only add numeric characters (0-9) into this field.");
}
}
private void letterMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
MaskedTextBox maskedTextBox = (MaskedTextBox)sender;
if (!maskedTextBox.MaskFull && e.Position != maskedTextBox.Mask.Length)
{
this.errorProvider.SetError(maskedTextBox, "You can only add letter characters into this field.");
}
}
//*********************Validating event handlers (includes one key up event to validate last field)*************
private void textBoxEmpty_Validating(object sender, CancelEventArgs e)
{
TextBox textBox = (TextBox)sender;
String controlName = textBox.Name;
controlName = controlName.TrimEnd("TextBox".ToCharArray());
Debug.WriteLine("control name trimmed: " + controlName);
controlName += "LabelError";
if (textBox.Text.Length == 0)
{
this.errorProvider.SetError(textBox, "The field must be completed.");
textBox.Tag = false;
}
else
{
textBox.BackColor = System.Drawing.SystemColors.Window;
textBox.Tag = true;
this.errorProvider.SetError(textBox, "");
}
ValidateAll();
}
private void maskedTextBox_Validating(object sender, CancelEventArgs e)
{
MaskedTextBox maskedTextBox = (MaskedTextBox)sender;
this.CheckMaskedTextMaskIsComplete(maskedTextBox);
}
private void PhoneMaskedTextBox_KeyUp(object sender, KeyEventArgs e)
{
MaskedTextBox maskedTextBox = (MaskedTextBox)sender;
if (maskedTextBox.MaskCompleted)
{
this.CheckMaskedTextMaskIsComplete(maskedTextBox);
}
}
//************MouseClick event handlers******************************
private void maskedTextBox_MouseClick(object sender, MouseEventArgs e)
{
MaskedTextBox mTextBox = (MaskedTextBox)sender;
mTextBox.SelectionStart = 0;
}
//************************Click event handlers*************************
private void registerCustomerButton_Click(object sender, EventArgs e)
{
Customer customer = new Customer();
customer.FName = this.firstNameRegisterCustomerTextBox.Text;
customer.MName = this.middleNameRegisterCustomerTextBox.Text;
customer.LName = this.lastNameRegisterCustomerTextBox.Text;
customer.StreetAddress = this.streetAddressRegisterCustomerTextBox.Text;
customer.City = this.cityRegisterCustomerTextBox.Text;
customer.State = this.stateAbbrevComboBox.SelectedItem.ToString();
customer.ZIPCode = this.zipCodeRegisterCustomerMaskedTextBox.Text;
customer.SSN = this.ssnRegisterCustomerMaskedTextBox.Text;
customer.Phone = this.phoneRegisterCustomerMaskedTextBox.Text;
/**
String firstName = this.firstNameRegisterCustomerTextBox.Text;
String middleName = this.middleNameRegisterCustomerTextBox.Text;
String lastName = this.lastNameRegisterCustomerTextBox.Text;
String streetAddress = this.streetAddressRegisterCustomerTextBox.Text;
String city = this.cityRegisterCustomerTextBox.Text;
String state = this.stateAbbrevComboBox.SelectedItem.ToString();
String zipCode = this.zipCodeRegisterCustomerMaskedTextBox.Text;
String ssn = this.ssnRegisterCustomerMaskedTextBox.Text;
String phone = this.phoneRegisterCustomerMaskedTextBox.Text;
**/
//String message = "Customer registered:\n" +
// " First Name: " + firstName +
// "\n Middle Name: " + middleName +
// "\n Last Name: " + lastName +
// "\n Street Address: " + streetAddress +
// "\n City: " + city +
// "\n State: " + state +
// "\n ZIP Code: " + zipCode +
// "\n SSN: " + ssn +
// "\n phone: " + phone;
//MessageBox.Show(message, "Entered Info", MessageBoxButtons.OK, MessageBoxIcon.None);
//this.customerID++;
DatabaseAccessController dbc = new DatabaseAccessController();
String customerID = dbc.AddCustomer(customer);
MessageBox.Show(customer.FName + " " + customer.LName + "\n\nCustomer ID: " + customerID, "Registered Customer", MessageBoxButtons.OK, MessageBoxIcon.None);
this.ResetAllControls();
}
private void clearButton_Click(object sender, EventArgs e)
{
this.ResetAllControls();
}
//*************************private helper methods********************
private void CheckMaskedTextMaskIsComplete(MaskedTextBox maskedTextBox)
{
if (!maskedTextBox.MaskCompleted)
{
maskedTextBox.Tag = false;
this.errorProvider.SetError(maskedTextBox, "The field must be completed.");
}
else
{
this.errorProvider.SetError(maskedTextBox, "");
maskedTextBox.Tag = true;
}
ValidateAll();
}
private void ValidateAll()
{
bool enable = ((bool)(this.firstNameRegisterCustomerTextBox.Tag) &&
(bool)(this.lastNameRegisterCustomerTextBox.Tag) &&
(bool)(this.streetAddressRegisterCustomerTextBox.Tag) &&
(bool)(this.cityRegisterCustomerTextBox.Tag) &&
(bool)(this.stateAbbrevComboBox.Tag) &&
(bool)(this.zipCodeRegisterCustomerMaskedTextBox.Tag) &&
(bool)(this.ssnRegisterCustomerMaskedTextBox.Tag) &&
(bool)(this.phoneRegisterCustomerMaskedTextBox.Tag));
this.registerCustomerButton.Enabled = enable;
}
private void SetUpRegisterCustomerControls()
{
this.firstNameRegisterCustomerTextBox.Tag = false;
this.lastNameRegisterCustomerTextBox.Tag = false;
this.streetAddressRegisterCustomerTextBox.Tag = false;
this.cityRegisterCustomerTextBox.Tag = false;
this.stateAbbrevComboBox.Tag = false;
this.zipCodeRegisterCustomerMaskedTextBox.Tag = false;
this.ssnRegisterCustomerMaskedTextBox.Tag = false;
this.phoneRegisterCustomerMaskedTextBox.Tag = false;
this.registerCustomerButton.Enabled = false;
}
private void PopulateStateComboBox()
{
DatabaseAccessController dbc = new DatabaseAccessController();
stateAbbrevs = dbc.GetStateAbbrevs();
foreach (String abbrev in stateAbbrevs)
{
this.stateAbbrevComboBox.Items.Add(abbrev);
}
}
private void ResetAllControls()
{
foreach (Control control in this.registerCustomerTab.Controls)
{
if (control is TextBox || control is MaskedTextBox)
{
control.Text = "";
}
}
this.errorProvider.Clear();
this.SetUpRegisterCustomerControls();
}
//****************************************************************************
//****************************Rent Furniture Tab******************************
//****************************************************************************
private void customerIDValidation(object sender, CancelEventArgs e)
{
HandleCustomerIDValidation();
}
private void HandleCustomerIDValidation()
{
DatabaseAccessController dba = new DatabaseAccessController();
ArrayList customerInfo = dba.CustomerValidation(this.rentCustomerIDTextBox.Text);
if (customerInfo.Count == 2)
{
this.errorProvider.SetError(this.rentCustomerIDTextBox, "");
this.rentCustomerNameTextBox.Visible = true;
this.rentFurnitureNumLabel.Enabled = true;
this.rentFurnitureNumberCombBox.Enabled = true;
this.rentCustomerNameTextBox.Text = customerInfo[0] + " " + customerInfo[1];
this.SetUpFurnitureNumberComboBox();
this.rentFurnitureNumberCombBox.Focus();
}
else
{
this.errorProvider.SetError(this.rentCustomerIDTextBox, "Invalid Customer ID");
}
}
private void SetUpFurnitureNumberComboBox()
{
DatabaseAccessController dba = new DatabaseAccessController();
ArrayList furnitureNums = dba.GetFurnitureItemNumbers();
this.rentFurnitureNumberCombBox.Items.Clear();
foreach (int number in furnitureNums)
{
this.rentFurnitureNumberCombBox.Items.Add(number);
}
}
private void rentCustomerIDTextBox_KeyUp(object sender, KeyEventArgs e)
{
//MessageBox.Show(((e.KeyCode == Keys.Return) || (e.KeyCode == Keys.Enter)).ToString(), "Key Press", MessageBoxButtons.OK, MessageBoxIcon.None);
if ((e.KeyCode == Keys.Return) || (e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))
{
this.HandleCustomerIDValidation();
}
}
private void rentFurnitureNumberCombBox_SelectionChangeCommitted(object sender, EventArgs e)
{
this.rentQuantityComboBox.Items.Clear();
this.ValidateFurnitureNumberSelection();
}
private void ValidateFurnitureNumberSelection()
{
DatabaseAccessController dba = new DatabaseAccessController();
int furnNum = (int)this.rentFurnitureNumberCombBox.SelectedItem;
int quantity = dba.GetQuantityForFurnitureNumber(furnNum);
if (quantity < 1)
{
this.errorProvider.SetError(this.rentFurnitureNumberCombBox, "Out of stock");
//this.rentQuantityComboBox.Enabled = false;
this.rentAddItemButton.Enabled = false;
}
else
{
this.errorProvider.SetError(this.rentFurnitureNumberCombBox, "");
this.SetUpQuantityComboBox(quantity);
this.rentQuantityComboBox.Enabled = true;
this.rentQuantityLabel.Enabled = true;
}
}
private void SetUpQuantityComboBox(int quantity)
{
for (int i = 1; i <= quantity; i++)
{
this.rentQuantityComboBox.Items.Add(i);
}
}
private void rentQuantityComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
this.rentAddItemButton.Enabled = true;
}
private void rentAddItemButton_Click(object sender, EventArgs e)
{
if (this.rentQuantityComboBox.SelectedItem == null)
{
this.errorProvider.SetError(this.rentQuantityComboBox, "Must make selection.");
return;
}
this.errorProvider.SetError(this.rentQuantityComboBox, "");
int furnitureNumber = (int)this.rentFurnitureNumberCombBox.SelectedItem;
DatabaseAccessController dba = new DatabaseAccessController();
string[] data = dba.GetFurnitureDescription(furnitureNumber);
string description = data[0];
string dailyRate = data[1];
string dailyFee = data[2];
DataRow newRow = this.rentalInfoTable.NewRow();
newRow["FurnitureID"] = this.rentFurnitureNumberCombBox.SelectedItem;
newRow["Description"] = description;
newRow["Quantity"] = this.rentQuantityComboBox.SelectedItem;
newRow["DailyRate"] = Convert.ToDecimal(dailyRate);
newRow["DailyFee"] = Convert.ToDecimal(dailyFee);
this.rentalInfoTable.Rows.Add(newRow);
//dataGridView1.Rows.Add(new object[] { this.rentFurnitureNumberCombBox.SelectedItem, description, this.rentQuantityComboBox.SelectedItem });
this.rentFurnitureNumberCombBox.SelectedIndex = -1;
this.rentFurnitureNumberCombBox.Items.Remove(furnitureNumber);
this.rentQuantityComboBox.Items.Clear();
this.rentButton.Enabled = true;
this.rentalInfoDataGridView.Enabled = true;
}
private void rentFurnitureNumberCombBox_Validating(object sender, CancelEventArgs e)
{
if (this.rentFurnitureNumberCombBox.SelectedItem != null)
{
this.rentQuantityComboBox.Items.Clear();
this.ValidateFurnitureNumberSelection();
}
else
{
this.errorProvider.SetError(this.rentFurnitureNumberCombBox, "Must make selection");
// this.rentQuantityComboBox.Enabled = false;
this.rentAddItemButton.Enabled = false;
}
}
private void rentalInfoDataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
ArrayList data = new ArrayList();
foreach (DataGridViewCell cell in e.Row.Cells)
{
data.Add(cell.Value);
}
this.rentFurnitureNumberCombBox.Items.Add(data[0]);
}
private void rentButton_Click(object sender, EventArgs e)
{
string custID = this.rentCustomerIDTextBox.Text;
int customerID = Convert.ToInt32(custID);
int empID = this.loginInformation.getEmployeeID();
DatabaseAccessController dba = new DatabaseAccessController();
string rentalID = dba.AddRental(customerID, empID, rentalInfoTable);
ReceiptForm receipt = new ReceiptForm(rentalID);
receipt.ShowDialog();
this.setUpRentForm();
}
private void setUpRentForm()
{
this.rentFurnitureNumberCombBox.Items.Clear();
this.rentFurnitureNumberCombBox.Enabled = false;
this.errorProvider.SetError(this.rentFurnitureNumberCombBox, "");
this.rentCustomerIDTextBox.Text = "";
this.rentCustomerNameTextBox.Text = "";
this.rentQuantityComboBox.Items.Clear();
this.rentQuantityComboBox.Enabled = false;
this.rentalInfoTable.Rows.Clear();
this.rentalInfoDataGridView.Enabled = false;
this.rentCustomerIDTextBox.Focus();
}
private void rentClearButton_Click(object sender, EventArgs e)
{
this.setUpRentForm();
}
private void SetUpRentalInfoTable()
{
rentalInfoTable = new DataTable();
rentalInfoTable.Columns.Add("FurnitureID", typeof(int));
rentalInfoTable.Columns.Add("Description", typeof(string));
rentalInfoTable.Columns.Add("Quantity", typeof(int));
rentalInfoTable.Columns.Add("DailyRate", typeof(decimal));
rentalInfoTable.Columns.Add("DailyFee", typeof(decimal));
this.rentalInfoDataGridView.DataSource = rentalInfoTable;
}
//******************************************************************************
//****************************Return Furniture Tab******************************
//******************************************************************************
private void returnCustomerIdTextBox_Validating(object sender, CancelEventArgs e)
{
this.HandleReturnCustomerIDValidation();
}
private void HandleReturnCustomerIDValidation()
{
DatabaseAccessController dba = new DatabaseAccessController();
ArrayList customerInfo = dba.CustomerValidation(this.returnCustomerIdTextBox.Text);
if (customerInfo.Count == 2)
{
this.errorProvider.SetError(this.returnCustomerIdTextBox, "");
this.returnRentalIDComboBox.Enabled = true;
this.SetUpReturnRentalIDComboBox();
this.returnRentalIDComboBox.Focus();
}
else
{
this.errorProvider.SetError(this.returnCustomerIdTextBox, "Invalid Customer ID");
}
}
private void SetUpReturnRentalIDComboBox()
{
DatabaseAccessController dba = new DatabaseAccessController();
ArrayList rentalIDs = dba.GetRentalIDsNumbers(this.returnCustomerIdTextBox.Text.ToString());
this.returnRentalIDComboBox.Items.Clear();
foreach (int id in rentalIDs)
{
this.returnRentalIDComboBox.Items.Add(id);
}
}
private void returnRentalIDComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
int rentalID = (int)this.returnRentalIDComboBox.SelectedItem;
DatabaseAccessController dba = new DatabaseAccessController();
returnInfoTable.Rows.Clear();
dba.GetRentalInfo(rentalID, returnInfoTable);
}
private void SetUpReturnInfoTable()
{
returnInfoTable = new DataTable();
returnInfoTable.Columns.Add("FurnitureID", typeof(int));
returnInfoTable.Columns.Add("Description", typeof(string));
returnInfoTable.Columns.Add("RentalItemID", typeof(int));
returnInfoTable.Columns.Add("QuantityNotReturned", typeof(int));
returnInfoTable.Columns.Add("DailyRate", typeof(decimal));
returnInfoTable.Columns.Add("DailyFee", typeof(decimal));
returnInfoTable.Columns.Add("RentalDate", typeof(DateTime));
returnInfoTable.Columns.Add("DueDate", typeof(DateTime));
returnInfoTable.Columns.Add("QuantityToReturn", typeof(int));
returnInfoTable.Columns.Add("AmountDue", typeof(decimal));
this.returnDataGridView.DataSource = returnInfoTable;
this.returnDataGridView.Columns[0].ReadOnly = true;
this.returnDataGridView.Columns[1].ReadOnly = true;
this.returnDataGridView.Columns[2].ReadOnly = true;
this.returnDataGridView.Columns[3].ReadOnly = true;
this.returnDataGridView.Columns[4].ReadOnly = true;
this.returnDataGridView.Columns[5].ReadOnly = true;
this.returnDataGridView.Columns[6].ReadOnly = true;
this.returnDataGridView.Columns[7].ReadOnly = true;
this.returnDataGridView.Columns[9].ReadOnly = true;
}
private void returnDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string columnName = returnInfoTable.Columns[e.ColumnIndex].ColumnName;
int value = 0;
if (!columnName.Equals("QuantityToReturn")) return;
try
{
value = Convert.ToInt32(e.FormattedValue);
}
catch (Exception ex)
{
returnInfoTable.Rows[e.RowIndex].RowError =
"Quantity must be an integer";
e.Cancel = true;
this.returnReturnButton.Enabled = false;
}
int maxValue = Convert.ToInt32(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(3));
if (value > maxValue || value < 0)
{
returnInfoTable.Rows[e.RowIndex].RowError =
"Quantity must be between 0 and "+ maxValue+ ".";
e.Cancel = true;
this.returnReturnButton.Enabled = false;
}
}
private void returnDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Clear the row error in case the user presses ESC.
returnInfoTable.Rows[e.RowIndex].RowError = String.Empty;
DateTime today = DateTime.Now;
Debug.WriteLine("Today: " + today);
decimal amount;
int numberReturning = Convert.ToInt32(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(8));
DateTime rentalDate = Convert.ToDateTime(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(6));
DateTime dueDate = Convert.ToDateTime(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(7));
int days = (today - rentalDate).Days;
days = (days == 0) ? 1 : days;
Debug.WriteLine("days: " + days);
decimal rate = Convert.ToDecimal(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(4));
if (today.Date <= dueDate.Date)
{
amount = rate * days * numberReturning;
}
else
{
days = (dueDate - rentalDate).Days;
int overdays = (today - dueDate).Days;
decimal fee = Convert.ToDecimal(returnInfoTable.Rows[e.RowIndex].ItemArray.ElementAt(5));
amount = (days * rate* numberReturning) + (overdays * fee* numberReturning);
}
Debug.WriteLine("amount: " + amount);
this.returnInfoTable.Rows[e.RowIndex][9]= amount;
Debug.WriteLine("amount after: " + this.returnInfoTable.Rows[e.RowIndex][9]);
this.returnReturnButton.Enabled = true;
}
private void returnClearButton_Click(object sender, EventArgs e)
{
this.returnReturnButton.Enabled = false;
this.returnRentalIDComboBox.Items.Clear();
this.returnCustomerIdTextBox.Text = String.Empty;
this.returnInfoTable.Rows.Clear();
}
private void returnReturnButton_Click(object sender, EventArgs e)
{
int employeeID = loginInformation.getEmployeeID();
int rentalID = Convert.ToInt32(this.returnRentalIDComboBox.SelectedItem);
DataTable data = new DataTable();
data.Columns.Add("rentalItemID", typeof(int));
data.Columns.Add("quantityReturned", typeof(int));
foreach (DataRow row in this.returnInfoTable.Rows)
{
int rentalItemID = Convert.ToInt32(row[2]);
Debug.WriteLine("rentalItemId: " + rentalItemID);
int quantity = Convert.ToInt32(row[8]);
Debug.WriteLine("quantity: " + quantity);
if (quantity > 0)
{
DataRow newRow = data.NewRow();
newRow["rentalItemID"] = rentalItemID;
Debug.WriteLine("newRow rentalItemId: " + newRow["rentalItemID"]);
newRow["quantityReturned"] = quantity;
Debug.WriteLine("newRow quantityReturned: " + newRow["quantityReturned"]);
data.Rows.Add(newRow);
}
}
DatabaseAccessController dba = new DatabaseAccessController();
bool isReturnSuccessful = dba.InsertReturns(data, employeeID);
string successReturn = "Your items were returned.";
if (!isReturnSuccessful)
{
successReturn = "Your return was not successful. Contact Administrator.";
}
MessageBox.Show(successReturn, "Return", MessageBoxButtons.OK, MessageBoxIcon.None);
this.returnInfoTable.Rows.Clear();
dba.GetRentalInfo(rentalID, returnInfoTable);
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using Caliburn.Micro;
using Frontend.Core.Common.Proxies;
using Frontend.Core.Helpers;
using Frontend.Core.Model.Paths;
using Frontend.Core.Model.Paths.Interfaces;
namespace Frontend.Core.Factories.TagReaders
{
public class FileTagReader : TagReaderBase
{
public FileTagReader(IEventAggregator eventAggregator)
: base(eventAggregator, new DirectoryHelper(), new EnvironmentProxy())
{
}
public IRequiredFile ReadFile(XElement xmlElement)
{
var tagName = XElementHelper.ReadStringValue(xmlElement, "tag", false);
var internalTagName = XElementHelper.ReadStringValue(xmlElement, "internalTag", false);
var friendlyName = XElementHelper.ReadStringValue(xmlElement, "friendlyName");
var description = XElementHelper.ReadStringValue(xmlElement, "description");
var extension = XElementHelper.ReadStringValue(xmlElement, "extension", false);
var predefinedFileName = XElementHelper.ReadStringValue(xmlElement, "predefinedFileName", false);
var alternativePaths = ReadDefaultLocationPaths(xmlElement, tagName, friendlyName, predefinedFileName);
var isMandatory = XElementHelper.ReadBoolValue(xmlElement, "isMandatory", false);
var hidden = XElementHelper.ReadBoolValue(xmlElement, "hidden", false);
return BuildRequiredFolderObject(tagName, alternativePaths, friendlyName, description, extension,
predefinedFileName, internalTagName, isMandatory, hidden);
}
/// <summary>
/// Todo: Move this to a separate factory somehow.
/// </summary>
/// <param name="tagName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
private IRequiredFile BuildRequiredFolderObject(string tagName, IList<IAlternativePath> alternatives,
string friendlyName, string description, string extension, string predefinedFileName, string internalTagName,
bool isMandatory, bool hidden)
{
return new RequiredFile(tagName, friendlyName, description, alternatives, extension, predefinedFileName,
internalTagName, isMandatory, hidden);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using SiscomSoft.Models;
using System.Data.Entity;
namespace SiscomSoft.Controller
{
public class ManejoCatalogo
{
/// <summary>
/// Funcion encargada de obtener todo los registros activos y retonar una lista con los mismos.
/// </summary>
/// <param name="status">variable de tipo Boolean</param>
/// <returns></returns>
public static List<Catalogo> getAll(Boolean status)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Catalogos.Where(r => r.bStatus == status).ToList();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de guardar un nuevo registro en la base de datos
/// </summary>
/// <param name="nUDM">variable de tipo modelo catalogo</param>
public static void RegistrarNuevoUDM(Catalogo nUDM)
{
try
{
using (var ctx = new DataModel())
{
ctx.Catalogos.Add(nUDM);
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de obtener un registro mediante una id
/// </summary>
/// <param name="idCatalogo">variable de tipo entera</param>
/// <returns></returns>
public static Catalogo getById(int idCatalogo)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Catalogos.Where(r => r.bStatus == true && r.idCatalogo == idCatalogo).FirstOrDefault();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de eliminar un registro de la base de datos mediante una id
/// </summary>
/// <param name="pkCatalogo"></param>
public static void Eliminar(int pkCatalogo)
{
try
{
using (var ctx = new DataModel())
{
Catalogo nCatalogo = ManejoCatalogo.getById(pkCatalogo);
nCatalogo.bStatus = false;
ctx.Entry(nCatalogo).State = EntityState.Modified;
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
public static List<Catalogo> Buscar(string valor, Boolean Status)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Catalogos.Where(r => r.bStatus == Status && r.sUDM.Contains(valor)).ToList();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de modificar un registro de la base de datos
/// </summary>
/// <param name="nCatalogo">variable de tipo modelo catalogo</param>
public static void Modificar(Catalogo nCatalogo)
{
try
{
using (var ctx = new DataModel())
{
ctx.Catalogos.Attach(nCatalogo);
ctx.Entry(nCatalogo).State = EntityState.Modified;
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Funcion encargada de obtener todos los registros activos de la base de datos y retornar una lista de los mismos.
/// </summary>
/// <returns></returns>
public static List<Catalogo> getAll()
{
try
{
using (var ctx = new DataModel())
{
return ctx.Catalogos.Where(r => r.bStatus == true).ToList();
}
}
catch (Exception)
{
throw;
}
}
}
}
|
using System;
using InsertionSort.Classes;
namespace InsertionSort
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Insertion Sort!");
Console.WriteLine("");
int[] arrayOne = new int[9] { 5, 23, 12, 4, 1, 2, 15, 78, 222};
int[] arrayTwo = new int[7] { 66, 22, 55,33, 44, 77, 11};
int[] arrayThree = new int[7] { 22, 66, 55, 33, 44, 77, 11 };
Console.Write("Initial Array: ");
for (int i = 0; i < arrayOne.Length-1; i++)
{
Console.Write(arrayOne[i] + " ");
}
SortTypes sortArray = new SortTypes();
sortArray.IterativeSort(arrayOne);
Console.WriteLine("Sorted: ");
Console.WriteLine(String.Join(" ", arrayOne));
Console.Write("Initial Array: ");
for (int i = 0; i < arrayTwo.Length - 1; i++)
{
Console.Write(arrayTwo[i] + " ");
}
sortArray.RecursiveSort(arrayTwo);
Console.WriteLine("Sorted: ");
Console.WriteLine(String.Join(" ", arrayTwo));
Console.Write("Initial Array: ");
for (int i = 0; i < arrayThree.Length - 1; i++)
{
Console.Write(arrayThree[i] + " ");
}
sortArray.RecursiveSort(arrayThree);
Console.WriteLine("Sorted: ");
Console.WriteLine(String.Join(" ", arrayThree));
Console.ReadLine();
}
}
}
|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Utilities.Memory;
using System;
namespace NtApiDotNet.Net.Firewall
{
/// <summary>
/// Class to represent an IPsec security association context.
/// </summary>
public sealed class IPsecSecurityAssociationContext
{
/// <summary>
/// ID of the context.
/// </summary>
public ulong Id { get; }
/// <summary>
/// Inbound security association.
/// </summary>
public IPsecSecurityAssociation Inbound { get; }
/// <summary>
/// Outbound security association.
/// </summary>
public IPsecSecurityAssociation Outbound { get; }
internal IPsecSecurityAssociationContext(IPSEC_SA_CONTEXT1 context, Func<FWPM_FILTER0, FirewallFilter> get_filter)
{
Id = context.saContextId;
if (context.inboundSa != IntPtr.Zero)
{
Inbound = new IPsecSecurityAssociation(context.inboundSa.ReadStruct<IPSEC_SA_DETAILS1>(), get_filter);
}
if (context.outboundSa != IntPtr.Zero)
{
Outbound = new IPsecSecurityAssociation(context.outboundSa.ReadStruct<IPSEC_SA_DETAILS1>(), get_filter);
}
}
}
}
|
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(GameStartPanel))]
[CanEditMultipleObjects]
public class GameStartPanelEditor : Editor {
public override void OnInspectorGUI() {
DrawDefaultInspector();
var obj = (GameStartPanel)target;
GUILayout.Space(10);
GUILayout.Label("Test editor");
if (GUILayout.Button("Perform")) { obj.perform(); }
}
}
#endif
public class GameStartPanel : MonoBehaviour {
[SerializeField] NumberSlideAnimation number1;
[SerializeField] NumberSlideAnimation number2;
[SerializeField] NumberSlideAnimation number3;
[SerializeField] NumberSlideAnimation numberGo;
[SerializeField] SlideAnimation slide;
[SerializeField] FadeAnimation fade;
public void perform() {
StartCoroutine(performRoutine());
}
public IEnumerator performRoutine() {
slide.gameObject.SetActive(true);
fade.gameObject.SetActive(true);
number1.gameObject.SetActive(false);
number2.gameObject.SetActive(false);
number3.gameObject.SetActive(false);
numberGo.gameObject.SetActive(false);
fade.perform();
slide.perform(slideIn: true);
number3.perform();
yield return new WaitForSeconds(1);
number2.perform();
yield return new WaitForSeconds(1);
number1.perform();
yield return new WaitForSeconds(1);
numberGo.perform();
yield return new WaitForSeconds(1.5f);
slide.perform(slideIn: false);
fade.gameObject.SetActive(false);
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using System;
namespace Pong
{
class Pad
{
public Vector2 position, startPosition, origin, collisionOrigin;
public Texture2D playerTex, collisionTex;
Keys upKey, downKey;
public Rectangle padRect;
int playerSpeed = 5;
public int lives = 3;
int playerIndex;
int collisionOffset = 15; //a slight offset is added to the rect collision because otherwise the collision box is sometimes slightly too small
int sideOffset = 70; //offset from side of screen to pad
bool playerBoogie = true; //You can turn this off if you don't want to use boogie
public Pad(ContentManager content, int playerID)
{
playerIndex = playerID;
collisionTex = content.Load<Texture2D>("GameObjects/collisionMask");
if (playerIndex == 0)
{
upKey = Keys.W;
downKey = Keys.S;
playerTex = content.Load<Texture2D>("GameObjects/paddleLeft");
}
else
{
upKey = Keys.Up;
downKey = Keys.Down;
playerTex = content.Load<Texture2D>("GameObjects/paddleRight");
}
collisionOrigin = new Vector2(collisionTex.Width, collisionTex.Height) / 2;
origin = new Vector2(playerTex.Width, playerTex.Height) / 2;
}
public void Update(GameTime gameTime)
{
padRect = new Rectangle((int)(position.X - collisionOrigin.X - collisionOffset), (int)(position.Y - collisionOrigin.Y), collisionTex.Width + collisionOffset, collisionTex.Height);
if (PongGame.InputHelper.KeyDown(upKey))
{
position.Y -= playerSpeed;
}
if (PongGame.InputHelper.KeyDown(downKey))
{
position.Y += playerSpeed;
}
if (playerBoogie)
{
position.X = xBoogie(position.Y);
}
position.Y = Math.Min(PongGame.GameDimensions.Y - (playerTex.Height - origin.Y), position.Y);
position.Y = Math.Max(origin.Y, position.Y);
}
public float xBoogie(float curY) //function that makes the player path wobble
{
return startPosition.X + 50 * (float)Math.Sin((double)((Math.PI * 2) / 300 * curY));
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Begin();
//spriteBatch.Draw(collisionTex, position - collisionOrigin, Color.White);
spriteBatch.Draw(playerTex, position - origin, Color.White);
spriteBatch.End();
}
public void Reset()
{
if (playerIndex == 0)
{
position = new Vector2(sideOffset, PongGame.GameDimensions.Y / 2);
}
else
{
position = new Vector2(PongGame.GameDimensions.X - sideOffset, PongGame.GameDimensions.Y / 2);
}
startPosition = position;
if (playerBoogie)
{
position.X = xBoogie(position.Y);
}
}
}
}
|
using CMS_ShopOnline.Areas.CMS_Sale.Models;
using System.Web.Mvc;
namespace CMS_ShopOnline.Areas.CMS_Sale
{
public class CMS_SaleAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "CMS_Sale";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"CMS_Sale_default",
"CMS_Sale/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
CreateMap();
}
public void CreateMap()
{
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.NguyenLieu, NguyenLieuViewModel>();
AutoMapper.Mapper.CreateMap<NguyenLieuViewModel, CMS_Database.Entities.NguyenLieu>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.ThanhPham, ThanhPhamViewModel>();
AutoMapper.Mapper.CreateMap<ThanhPhamViewModel, CMS_Database.Entities.ThanhPham>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.HoaDon, POSViewModel>();
AutoMapper.Mapper.CreateMap<POSViewModel, CMS_Database.Entities.HoaDon>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.HoaDon, HoaDonViewModel>();
AutoMapper.Mapper.CreateMap<HoaDonViewModel, CMS_Database.Entities.HoaDon>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.CTHoaDon, POSDetailsViewModel>();
AutoMapper.Mapper.CreateMap<POSDetailsViewModel, CMS_Database.Entities.CTHoaDon>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.PhieuXuat, PhieuXuatViewModel>();
AutoMapper.Mapper.CreateMap<PhieuXuatViewModel, CMS_Database.Entities.PhieuXuat>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.PhieuNhap, PhieuNhapViewModel>();
AutoMapper.Mapper.CreateMap<PhieuNhapViewModel, CMS_Database.Entities.PhieuNhap>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.CTPhieuNhap, CTPhieuNhapViewModel>();
AutoMapper.Mapper.CreateMap<CTPhieuNhapViewModel, CMS_Database.Entities.CTPhieuNhap>();
AutoMapper.Mapper.CreateMap<CMS_Database.Entities.CTHoaDon, CTHoaDonViewModel>();
AutoMapper.Mapper.CreateMap<CTHoaDonViewModel, CMS_Database.Entities.CTHoaDon>();
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace OctreeTests
{
[TestClass]
public class OctreeTests
{
//[TestMethod]
//public void TestMethod1()
//{
// var centre = new Vector3(0, 0, 0);
// var halfSize = 50;
// var volume = BoundingVolume.CreateVolume(centre, halfSize);
// OcTree tree = new OcTree(volume);
// var ten = 10;
// var centre1 = new Vector3();
// var volume1 = BoundingVolume.CreateVolume(centre1, ten);
// var centre2 = new Vector3();
// var volume2 = BoundingVolume.CreateVolume(centre2, ten);
// tree.Insert(volume1);
// tree.Insert(volume2);
//}
//[TestMethod]
//public void TestHighLevelBlocks()
//{
// var centre = new Vector3(0, 0, 0);
// var halfSize = 80;
// var allVolume = BoundingVolume.CreateVolume(centre, halfSize);
// var MainTree = new OcTree(allVolume);
// var y = 20;
// var o = BoundingVolume.CreateVolume(new Vector3(-5, y, 5), 10, 20);
// o.Name = "n8";
// MainTree.Insert(o);
// o = BoundingVolume.CreateVolume(new Vector3(-47, y, 0), 5, 10);
// o.Name = "n7";
// MainTree.Insert(o);
// o = BoundingVolume.CreateVolume(new Vector3(-10, y, 40), 15, 10);
// o.Name = "n10";
// MainTree.Insert(o);
// o = BoundingVolume.CreateVolume(new Vector3(40, y, -5), 10, 10);
// o.Name = "n9";
// MainTree.Insert(o);
// o = BoundingVolume.CreateVolume(new Vector3(10, y, -25), 15, 10);
// o.Name = "n6";
// MainTree.Insert(o);
// o = BoundingVolume.CreateVolume(new Vector3(-2, y, -70), 10, 4);
// o.Name = "n2";
// MainTree.Insert(o);
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name == "n2"), "n2");
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name == "n6"), "n6");
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name == "n7"), "n7");
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name == "n8"), "n8");
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name == "n9"), "n9");
// Assert.IsTrue(MainTree.Root.Objects.Any(ob => ob.Name.Equals("n10", StringComparison.CurrentCulture)), "n10");
//}
/* [TestMethod]
public void CreateCube()
{
var y = 5;
var speed = new Vector3(-0.1f, 0, 0);
var o = BoundingVolume.CreateVolume(new Vector3(-5, y, 5), 10, 20, 3);
var plane = new GameObject()
{
BoundingBox = o,
Name = "n8",
Speed = speed,
};
// result.Add(plane);
o = BoundingVolume.CreateVolume(new Vector3(34f, y, -45), 3, 3, 1);
var plane2 = new GameObject()
{
BoundingBox = o,
Name = "n11",
Speed = speed,
};
o = BoundingVolume.CreateVolume(new Vector3(34f, y, -55), 3, 3, 1);
var plane3 = new GameObject()
{
BoundingBox = o,
Name = "n12",
Speed = speed,
};
var tree = new OcTree(BoundingVolume.CreateVolume(new Vector3(0, 0, 0), 160));
tree.Insert(plane);
tree.Insert(plane2);
tree.Insert(plane3);
var w1 = plane2.TreeSegment.Width;
var w2 = plane3.TreeSegment.Width;
Assert.IsTrue(w1 == 10, "plane2");
Assert.IsTrue(w2 == 10, "plane3");
//Assert.IsTrue(tree.Root.Objects.Any(ob => ob.Name == "n2"), "n2");
}*/
}
}
|
using System.Collections.Generic;
using System.ServiceModel;
using Server.WS.Item;
namespace Server.WS
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IConstantsService" in both code and config file together.
[ServiceContract]
public interface IConstantsService
{
/// <summary>
/// Permet de récupérer une liste de cartes.
/// </summary>
/// <param name="typeOfCards">voir enum pour le types de cartes à récupérer</param>
/// <param name="isRandomOrder">ordre classique ou random?</param>
/// <returns></returns>
[OperationContract]
List<Card> GetCards(CardsType typeOfCards,bool isRandomOrder);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArteVida.Dominio.Entidades;
namespace ArteVida.Dominio.Repositorio
{
public class RepositorioEvento : Repositorio<Evento>
{
public RepositorioEvento(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
}
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("2.0.0")]
[assembly: InternalsVisibleTo("Tests")] |
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using YCSOrderSystem.Models;
namespace YCSOrderSystem.Controllers
{
public class SalariesController : Controller
{
private YCSDatabaseEntities db = new YCSDatabaseEntities();
// GET: Salaries
public ActionResult Index()
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
var salaries = db.Salaries.Include(s => s.Staff);
return View(salaries.ToList());
}
// GET: Salaries/Details/5
public ActionResult Details(int? id)
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Salary salary = db.Salaries.Find(id);
if (salary == null)
{
return HttpNotFound();
}
return View(salary);
}
// GET: Salaries/Create
public ActionResult Create()
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
ViewBag.StaffNum = new SelectList(db.Staffs, "StaffNum", "StaffName");
return View();
}
// POST: Salaries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SalaryNum,Amount,Benefits,Deductions,StaffNum,Description")] Salary salary)
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
if (ModelState.IsValid)
{
db.Salaries.Add(salary);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StaffNum = new SelectList(db.Staffs, "StaffNum", "StaffName", salary.StaffNum);
return View(salary);
}
// GET: Salaries/Edit/5
public ActionResult Edit(int? id)
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Salary salary = db.Salaries.Find(id);
if (salary == null)
{
return HttpNotFound();
}
ViewBag.StaffNum = new SelectList(db.Staffs, "StaffNum", "StaffName", salary.StaffNum);
return View(salary);
}
// POST: Salaries/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "SalaryNum,Amount,Benefits,Deductions,StaffNum,Description")] Salary salary)
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
if (ModelState.IsValid)
{
db.Entry(salary).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StaffNum = new SelectList(db.Staffs, "StaffNum", "StaffName", salary.StaffNum);
return View(salary);
}
// GET: Salaries/Delete/5
public ActionResult Delete(int? id)
{
if (SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Salary salary = db.Salaries.Find(id);
if (salary == null)
{
return HttpNotFound();
}
return View(salary);
}
// POST: Salaries/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
if(SUserRole() != "Customer" && SUserRole() != null)
{
ViewBag.displayMenu = "Yes";
}
Salary salary = db.Salaries.Find(id);
db.Salaries.Remove(salary);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public String SUserRole()
{
if (User.Identity.IsAuthenticated)
{
var user = User.Identity;
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var s = UserManager.GetRoles(user.GetUserId());
if (s[0].ToString() == "Admin")
{
return "Admin";
}
else if (s[0].ToString() == "Manager")
{
return "Manager";
}
else if (s[0].ToString() == "Employee")
{
return "Employee";
}
else
{
return "Customer";
}
}
return "Customer";
}
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : NetworkBehaviour
{
[SerializeField]
[SyncVar]
private float speed = 5;
[SerializeField]
private Animator PlayerAnimator;
[SerializeField]
private Rigidbody2D Rigidbody;
[SyncVar(hook = "FacingCallback")]
private bool FacingRight = true;
void Start ()
{
PlayerAnimator = GetComponent<Animator>();
Rigidbody = GetComponent<Rigidbody2D>();
}
void FixedUpdate ()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
if(!horizontal.Equals(0f) || !vertical.Equals(0f))
Move(horizontal, vertical);
TryFlip(horizontal);
PlayAnimation(horizontal, vertical);
}
void Move(float horizontal, float vertical)
{
var wantedPosition = transform.position + new Vector3(horizontal, vertical) * speed * Time.deltaTime;
Rigidbody.MovePosition(wantedPosition);
}
void PlayAnimation(float horizontal, float vertical)
{
if (!horizontal.Equals(0f) || vertical < 0f)
{
PlayerAnimator.SetBool("Walk", true);
PlayerAnimator.SetBool("WalkUp", false);
}
if (vertical > 0f)
{
PlayerAnimator.SetBool("WalkUp", true);
PlayerAnimator.SetBool("Walk", false);
}
if (vertical.Equals(0f) && horizontal.Equals(0f))
{
PlayerAnimator.SetBool("Idle", true);
PlayerAnimator.SetBool("Walk", false);
PlayerAnimator.SetBool("WalkUp", false);
}
}
void TryFlip(float horizontal)
{
if (horizontal > 0f && !FacingRight || horizontal < 0f && FacingRight)
{
FacingRight = !FacingRight;
CmdFlipSprite(FacingRight);
}
}
[Command]
public void CmdFlipSprite(bool facing)
{
Flip(facing);
}
void FacingCallback(bool facing)
{
Flip(facing);
}
void Flip(bool facing)
{
FacingRight = facing;
if (FacingRight)
{
var spriteScale = transform.localScale;
spriteScale.x = 1;
transform.localScale = spriteScale;
}
else
{
var spriteScale = transform.localScale;
spriteScale.x = -1;
transform.localScale = spriteScale;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
Board m_gameBoard;
Spawner m_spawner;
Shape m_activeShape;
public float m_dropInterval = 0.5f;
float m_dropIntervalModded;
float m_timeToDrop;
/*
float m_timeToNextKey;
[Range(0.02f, 1f)]
public float m_keyRepeatRate = 0.25f;
*/
float m_timeToNextKeyLeftRight;
[Range(0.02f, 1f)]
public float m_keyRepeatRateLeftRight = 0.25f;
float m_timeToNextKeyDown;
[Range(0.01f, 1f)]
public float m_keyRepeatRateDown = 0.02f;
float m_timeToNextKeyRotate;
[Range(0.02f, 1f)]
public float m_keyRepeatRateRotate = 0.2f;
bool m_gameOver = false;
public GameObject m_gameOverPanel;
public IconToggle m_rotIconToggle;
bool m_clockwise = true;
public bool m_isPaused = false;
public GameObject m_pausePanel;
SoundManager m_soundManager;
ScoreManager m_scoreManager;
Holder m_holder;
Ghost m_ghost;
public ParticlePlayer m_gameOverFx;
// Start is called before the first frame update
void Start()
{
m_timeToNextKeyLeftRight = Time.time + m_keyRepeatRateLeftRight;
m_timeToNextKeyDown = Time.time + m_keyRepeatRateDown;
m_timeToNextKeyRotate = Time.time + m_keyRepeatRateRotate;
m_gameBoard = GameObject.FindObjectOfType<Board>();
m_spawner = GameObject.FindObjectOfType<Spawner>();
m_soundManager = GameObject.FindObjectOfType<SoundManager>();
m_scoreManager = GameObject.FindObjectOfType<ScoreManager>();
m_ghost = GameObject.FindObjectOfType<Ghost>();
m_holder = GameObject.FindObjectOfType<Holder>();
if (m_spawner)
{
m_spawner.transform.position = Vectorf.Round(m_spawner.transform.position);
if (m_activeShape == null)
{
m_activeShape = m_spawner.SpawnShape();
}
}
else
{
Debug.LogWarning("WARNING! There is no game spawner defined!");
}
if (!m_gameBoard)
{
Debug.LogWarning("WARNING! There is no game board defined!");
}
if (!m_soundManager)
{
Debug.LogWarning("WARNING! There is no sound manager defined!");
}
if (!m_scoreManager)
{
Debug.LogWarning("WARNING! There is no score manager defined!");
}
if (m_gameOverPanel)
{
m_gameOverPanel.SetActive(false);
}
if (m_pausePanel)
{
m_pausePanel.SetActive(false);
}
m_dropIntervalModded = m_dropInterval;
}
void PlayerInput()
{
if (!m_gameBoard || !m_spawner)
{
return;
}
if (Input.GetButtonDown("MoveRight") || (Input.GetButton("MoveRight") && Time.time > m_timeToNextKeyLeftRight))
{
m_activeShape.MoveRight();
m_timeToNextKeyLeftRight = Time.time + m_keyRepeatRateLeftRight;
if (!m_gameBoard.IsValidPosition(m_activeShape))
{
m_activeShape.MoveLeft();
PlaySound(m_soundManager.m_errorSound, 0.5f);
}
else
{
PlaySound(m_soundManager.m_moveSound, 0.5f);
}
}
else if (Input.GetButtonDown("MoveLeft") || (Input.GetButton("MoveLeft") && Time.time > m_timeToNextKeyLeftRight))
{
m_activeShape.MoveLeft();
m_timeToNextKeyLeftRight = Time.time + m_keyRepeatRateLeftRight;
if (!m_gameBoard.IsValidPosition(m_activeShape))
{
m_activeShape.MoveRight();
PlaySound(m_soundManager.m_errorSound, 0.5f);
}
else
{
PlaySound(m_soundManager.m_moveSound, 0.5f);
}
}
else if ((Input.GetButton("Rotate") && Time.time > m_timeToNextKeyRotate) || Input.GetButtonDown("Rotate"))
{
m_activeShape.RotateClockwise(m_clockwise);
m_timeToNextKeyRotate = Time.time + m_keyRepeatRateRotate;
if (!m_gameBoard.IsValidPosition(m_activeShape))
{
m_activeShape.RotateClockwise(!m_clockwise);
PlaySound(m_soundManager.m_errorSound, 0.5f);
}
else
{
PlaySound(m_soundManager.m_errorSound, 0.5f);
}
}
else if ((Input.GetButton("MoveDown") && Time.time > m_timeToNextKeyDown) || Time.time > m_timeToDrop || Input.GetButtonDown("MoveDown"))
{
m_timeToDrop = Time.time + m_dropIntervalModded;
m_timeToNextKeyDown = Time.time + m_keyRepeatRateDown;
m_activeShape.MoveDown();
if (!m_gameBoard.IsValidPosition(m_activeShape))
{
if (m_gameBoard.IsOverLimit(m_activeShape))
{
GameOver();
}
else
{
LandShape();
}
}
}
else if (Input.GetButtonDown("ToggleRot"))
{
ToggleRotDirection();
}
else if (Input.GetButtonDown("Pause"))
{
TogglePause();
}
else if (Input.GetButtonDown("Hold"))
{
Hold();
}
}
void GameOver()
{
m_activeShape.MoveUp();
m_gameOver = true;
Debug.LogWarning(m_activeShape.name + "is over the limit.");
StartCoroutine(GameOverRoutine());
PlaySound(m_soundManager.m_gameOverSound, 5f);
PlaySound(m_soundManager.m_gameOverVocalClip, 5f);
}
IEnumerator GameOverRoutine()
{
if (m_gameOverFx)
{
m_gameOverFx.Play();
}
yield return new WaitForSeconds(0.3f);
if (m_gameOverPanel)
{
m_gameOverPanel.SetActive(true);
}
}
void LandShape()
{
if (m_activeShape)
{
m_timeToNextKeyLeftRight = Time.time;
m_timeToNextKeyDown = Time.time;
m_timeToNextKeyRotate = Time.time;
m_activeShape.MoveUp();
m_gameBoard.StoreShapeInGrid(m_activeShape);
m_activeShape.LandShapeFX();
if (m_ghost)
{
m_ghost.Reset();
}
if (m_holder)
{
m_holder.m_canRelease = true;
}
m_activeShape = m_spawner.SpawnShape();
m_gameBoard.StartCoroutine("ClearAllRows");
PlaySound(m_soundManager.m_dropSound, 0.75f);
if (m_gameBoard.m_completedRows > 0)
{
m_scoreManager.ScoreLines(m_gameBoard.m_completedRows);
if (m_scoreManager.m_didLevelUp)
{
PlaySound(m_soundManager.m_levelUpVocalClip);
m_dropIntervalModded = Mathf.Clamp(m_dropInterval - (((float)m_scoreManager.m_level - 1) * 0.1f), 0.05f, 1f);
}
else
{
if (m_gameBoard.m_completedRows > 1)
{
AudioClip randomVocal = m_soundManager.GetRandomClip(m_soundManager.m_vocalClips);
PlaySound(randomVocal);
}
}
PlaySound(m_soundManager.m_clearRowSound);
}
}
}
// Update is called once per frame
void Update()
{
if(!m_gameBoard || !m_spawner || !m_activeShape || m_gameOver || !m_soundManager)
{
return;
}
PlayerInput();
}
void LateUpdate()
{
if (m_ghost)
{
m_ghost.DrawGhost(m_activeShape, m_gameBoard);
}
}
public void Restart()
{
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
void PlaySound(AudioClip clip, float volMultiplier = 1)
{
if (m_soundManager.m_fxEnabled && clip)
{
AudioSource.PlayClipAtPoint(clip, Camera.main.transform.position, Mathf.Clamp(m_soundManager.m_fxVolume * volMultiplier, 0.05f, 1f));
}
}
public void ToggleRotDirection()
{
m_clockwise = !m_clockwise;
if (m_rotIconToggle)
{
m_rotIconToggle.ToggleIcon(m_clockwise);
}
}
public void TogglePause()
{
if (m_gameOver)
{
return;
}
m_isPaused = !m_isPaused;
if (m_pausePanel)
{
m_pausePanel.SetActive(m_isPaused);
if (m_soundManager)
{
m_soundManager.m_musicSource.volume = (m_isPaused) ? m_soundManager.m_musicVolume * 0.25f : m_soundManager.m_musicVolume;
}
Time.timeScale = (m_isPaused) ? 0 : 1;
}
}
public void Hold()
{
if (!m_holder)
{
return;
}
if (!m_holder.m_heldShape)
{
m_holder.Catch(m_activeShape);
m_activeShape = m_spawner.SpawnShape();
PlaySound(m_soundManager.m_holdSound);
}
else if (m_holder.m_canRelease)
{
Shape shape = m_activeShape;
m_activeShape = m_holder.Release();
m_activeShape.transform.position = m_spawner.transform.position;
m_holder.Catch(shape);
PlaySound(m_soundManager.m_holdSound);
}
else
{
Debug.LogWarning("HOLDER WARNING! Wait for cool down!");
PlaySound(m_soundManager.m_errorSound);
}
if (m_ghost)
{
m_ghost.Reset();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace KekManager.Data.Models
{
public class ResearchFellowModel
{
public int Id { get; set; }
// SecurityUser - coming from separate app
public int? UserId { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Title { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ABB_mobileASI
{
class ListenForIncomingData
{
public Dictionary<string, string> processMessage(byte[] data, List<DataItem> m_dataItemInfo, Dictionary<string, string> m_receivedData)
{
try
{
String responseCode = string.Empty;
String dataGroup = string.Empty;
String dataField = string.Empty;
String recData = string.Empty;
Int16 lengthOfData = 0;
String nextField = string.Empty;
for (int i = 0; i <= data.Length - 1; i++)
{
if (i < 2)
{
responseCode = responseCode + data[i];
//if error code break to handle error
if (i == 1 && responseCode.Equals("018"))
{
handleSpiError(data);
break;
}
}
else if (i < 4)
{
dataGroup = dataGroup + data[i];
}
else if (i < 6)
{
dataField = dataField + data[i];
if (i == 5)
{
int group = Convert.ToInt32(dataGroup, 16);
//int field = Convert.ToInt32(dataField, 16);
int field = Convert.ToInt32(dataField);
foreach (DataItem item in m_dataItemInfo)
{
if (item.getDataGroup() == group && item.getDataField() == field)
{
lengthOfData = item.getLength();
break;
}
}
}
}
else if (i < 6 + lengthOfData)
{
recData = recData + data[i];
}
else if (i < 6 + lengthOfData + 2)
{
//add recieved data into a hashmap
string key = dataGroup + "," + dataField;
if (!m_receivedData.ContainsKey(key))
{
m_receivedData.Add(key, recData);
}
else
{
if (m_receivedData[key] != recData)
{
m_receivedData[key] = recData;
MessageBox.Show("New Data" + m_receivedData[key] + " - " + recData);
}
}
nextField = nextField + data[i];
if (i == 6 + lengthOfData + 1)
{
int group = Convert.ToInt32(nextField, 16);
//break on null terminator
if (group == 0)
{
return m_receivedData;
}
}
}
}
return m_receivedData;
}
catch (Exception e)
{
return m_receivedData;
}
}
public void handleSpiError(byte[] data)
{
String errorCode = string.Empty;
String dataGroup = string.Empty;
String dataField = string.Empty;
String modifier = string.Empty;
for (int i = 0; i <= data.Length - 1; i++)
{
if (i > 2 && i < 4)
{
//error code to identify the error
errorCode = errorCode + data[i];
if (i == 3)
{
if (errorCode.Equals("1"))
{
errorCode = "ILLEGAL_CMD" + "\n" +
"Undefined Command";
}
else if (errorCode.Equals("2"))
{
errorCode = "NO_BUFFERS" + "\n" +
"Cannot accomodate any more data field assignments";
}
else if (errorCode.Equals("4"))
{
errorCode = "DATA_UNAVIL" + "\n" +
"Referenced data cannot be located";
}
else if (errorCode.Equals("5"))
{
errorCode = "BAD_GROUP" + "\n" +
"Undefined group number";
}
else if (errorCode.Equals("6"))
{
errorCode = "BAD_FIELD" + "\n" +
"Undefined field number";
}
else if (errorCode.Equals("7"))
{
errorCode = "BAD_EVENT" + "\n" +
"Undefined event code";
}
else if (errorCode.Equals("9"))
{
errorCode = "BAD_DIRECTION" + "\n" +
"Access Error";
}
else if (errorCode.Equals("12"))
{
errorCode = "UC_UNAVIL" + "\n" +
"Referenced uController not on-line";
}
else if (errorCode.Equals("16"))
{
errorCode = "BAD_TAG" + "\n" +
"Reference to non-existant data dictionary tag";
}
else
{
errorCode = "DUP_FIELD" + "\n" +
"Attempted to assign a tag to a data group and field that is already assigned.";
}
}
}
else if (i < 6)
{
//data group associated with the error
dataGroup = dataGroup + data[i];
}
else if (i < 8)
{
//data field within the above group with the error
dataField = dataField + data[i];
}
else
{
//modifier, if non-zero contains further info about the error
modifier = modifier + data[i];
}
}
MessageBox.Show("Error contained in data group number" + dataGroup +
" and field number " + dataField + ". \nError was the following: " + errorCode);
}
}
class Worker
{
// This method will be called when the thread is started.
public Dictionary<string, string> DoWork(Socket m_clientSocket, List<DataItem> m_dataItemInfo, Dictionary<string, string> m_receivedData)
{
while (m_clientSocket.Connected)
{
int value = receiveHeader(m_clientSocket);
//create a buffer to contain the incoming data
byte[] data = new byte[value];
//recive the data
int rec = m_clientSocket.Receive(data);
if (rec != -1)
{
ListenForIncomingData process = new ListenForIncomingData();
m_receivedData = process.processMessage(data, m_dataItemInfo, m_receivedData);
}
//return m_receivedData;
}
return m_receivedData;
}
public int receiveHeader(Socket m_clientSocket)
{
//set up to only read the recieved header
try
{
byte[] recieveData = new byte[6];
// m_clientSocket.ReceiveTimeout = 5000;
int bytesRec = m_clientSocket.Receive(recieveData);
String hexArr = string.Empty;
for (int i = 0; i <= recieveData.Length - 1; i++)
{
if (i >= 2)
{
hexArr = hexArr + recieveData[i];
}
}
hexArr.TrimStart('0');
// Convert the number expressed in base-16 to an integer.
//int value = Convert.ToInt32(hexArr, 16);
int value = Convert.ToInt32(hexArr);
return value;
}catch(Exception)
{
MessageBox.Show("No more data available");
return -1;
}
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
}
}
|
#region Properties
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
#endregion
namespace Zengo.WP8.FAS.Controls.ListItems
{
public partial class PlayerVotingItem : UserControl
{
public PlayerVotingItem()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Singleton
{
public class SingletonServico
{
static Servico singleton = new Servico();
public Servico Instancia {
get
{
return singleton;
}
}
}
}
|
using UnityEngine;
public class TransformResetter : MonoBehaviour {
public Vector3 position, size;
public Quaternion rotation;
public bool trigger;
void OnValidate() {
position = transform.localPosition;
rotation = transform.localRotation;
size = transform.localScale;
}
public void ResetTransform() {
transform.localPosition = position;
transform.localRotation = rotation;
transform.localScale = size;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Servers
{
public List<string> List { get; set; } = new List<string>();
}
|
namespace Shellbound
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Shellbound
{
public static void Main(string[] args)
{
//var for input;
var input = Console.ReadLine();
//dictionary for result;
var result = new Dictionary<string, HashSet<int>>();
while (input != "Aggregate")
{
//var for town;
var town = input.Split(' ')[0];
//var for shell;
var shell = int.Parse(input.Split(' ')[1]);
if (!result.ContainsKey(town))
{
result[town] = new HashSet<int>();
}
result[town].Add(shell);
input = Console.ReadLine();
}//end of while loop;
//printing the result;
foreach (var item in result)
{
//var for giant shell;
var giantShell = Math.Ceiling(item.Value.Sum() - item.Value.Average());
Console.WriteLine("{0} -> {1} ({2})", item.Key, string.Join(", ", item.Value), giantShell);
}
}
}
}
|
using Pchp.Library.Spl;
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.RichObjectStrings
{
/**
* Class InvalidObjectExeption
*
* @package OCP\RichObjectStrings
* @since 11.0.0
*/
public class InvalidObjectExeption : InvalidArgumentException {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.