text stringlengths 13 6.01M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class PortalScript : MonoBehaviour
{
private GameObject spawnedObject;
[SerializeField] private GameObject targetFrame;
[SerializeField] private GameObject spawnedRoom;
void Awake()
{
Renderer[] rs = spawnedRoom.GetComponentsInChildren<Renderer>();
foreach (Renderer r in rs)
r.enabled = false;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.touchCount >0 && Input.touches[0].phase == TouchPhase.Began)
{
spawnedObject = Instantiate(spawnedRoom, spawnedRoom.transform.position, spawnedRoom.transform.rotation);
Renderer[] rs = spawnedObject.GetComponentsInChildren<Renderer>();
foreach (Renderer r in rs)
r.enabled = true;
Destroy(targetFrame);
Destroy(spawnedRoom);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallHouseManagerDAL;
using SmallHouseManagerModel;
namespace SmallHouseManagerBLL
{
public class BaseParkBLL
{
BaseParkDAL dal = new BaseParkDAL();
public bool CheckHomePark(int parkID)
{
int result = dal.CheckHomePark(parkID);
return result == 0 ? false : true;
}
public List<BaseParkModel> GetBasePark()
{
return dal.GetBasePark();
}
public BaseParkModel GetBaseParkByID(int parkID)
{
return dal.GetBaseParkByID(parkID);
}
public bool UpdateBasePark(BaseParkModel basePark)
{
int result = dal.UpdateBasePark(basePark);
return result == 0 ? false : true;
}
public bool InsertBasePark(BaseParkModel basePark)
{
int result = dal.InsertBasePark(basePark);
return result == 0 ? false : true;
}
public int DeleteBasePark(int parkID)
{
return dal.DeleteBasePark(parkID);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using TxHumor.Common;
using TxHumor.Model;
/// <summary>
///CommentHelper 的摘要说明
/// </summary>
public class CommentHelper
{
public CommentHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 获取引用内容
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static m_CommentXml GetReplyContent(string content)
{
if (string.IsNullOrWhiteSpace(content))
{
return null;
}
XElement root = XElement.Parse(content);
XElement xFloor = root.Element("Floor");
int floor = 0;
if (xFloor != null)
{
floor = xFloor.Value.ToSimpleT(0);
}
m_CommentXml comment=new m_CommentXml()
{
Floor = floor,
Content = root.Element("Content") == null ? string.Empty : root.Element("Content").Value,
ReplyId = root.Element("ReplyId") == null ? 0 : root.Element("ReplyId").Value.ToSimpleT(0),
UserId = root.Element("UserId") == null ? 0 : root.Element("UserId").Value.ToSimpleT(0),
UserName = root.Element("UserName") == null ? string.Empty : root.Element("UserName").Value
};
return comment;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
public abstract class Lærer : Person
{
public string Bankkonto { get; set; }
// Constructor som giver mulighed for at angive navn
public Lærer(string fornavn, string efternavn, string bankkonto): base(fornavn, efternavn)
{
this.Bankkonto = bankkonto;
//this.Fornavn = fornavn;
//this.Efternavn = efternavn;
}
public override string ToString()
{
return base.ToString() + " bankkonto " + this.Bankkonto;
}
public abstract int udbetalSalary();
}
}
|
namespace Sesi.WebsiteDaSaude.WebApi.ViewModels
{
public class LoginViewModel
{
public string Email {get;set;}
public string Senha {get;set;}
}
} |
using System;
using Reciclagem.Models;
using Reciclagem.Interfaces;
namespace Reciclagem.Models
{
public abstract class Materiais
{
}
} |
using FindSelf.Infrastructure.Idempotent;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace FindSelf.Infrastructure.Database.EntityConfigurations
{
public class IdempotentRequestEntityTypeConfiguration : IEntityTypeConfiguration<IdempotentRequest>
{
public void Configure(EntityTypeBuilder<IdempotentRequest> builder)
{
builder.ToTable("IdempotentRequest");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).IsRequired().ValueGeneratedNever();
builder.Property(x => x.CommandType).IsRequired();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using MahApps.Metro.Controls;
using MedicinesDatabase;
using MedicinesInStockDatabase;
using ReportGenerator;
using UserDatabaseAPI.Service;
using UserDatabaseAPI.UserDB.Entities;
using UserInterface.Command;
using Medicine = MedicinesInStockDatabase.Medicine;
namespace UserInterface.ViewModel
{
public class PharmacistViewModel : ViewModelBase
{
public PharmacistViewModel()
{
GetGeneralPharmacyStateCommand.Execute(null);
}
private int actualPharmacyMedicinesCount;
MedicinesInStockDB pharmacyDB = new MedicinesInStockDB("1");
public MedicinesInStockDatabase.Medicine GeneralMedicineFilter { get; set; } = new MedicinesInStockDatabase.Medicine("", "", "");
public MedicinesInStockDatabase.Medicine SelectedGeneralMedicine { get; set; }
public MedicinesInStockDatabase.MedicineInStock InStockMedicineFilter { get; set; } = new MedicineInStock("", "", "", "0", "0", "0");
public List<string> FileExtensions { get; set; } = new List<string>() { "Select file extension", "pdf", "csv" };
public string SelectedFileExtension { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public UserDTO SelectedPharmacist { get; set; }
public UserDTO PatientFilter { get; set; } = new UserDTO();
public UserDTO PharmacistFilter { get; set; } = new UserDTO();
public DoctorViewModel.Prescription SelectedPatientsUnrealisedPrescription { get; set; }
public ObservableCollection<DoctorViewModel.Prescription> SelectedPatientsUnrealisedPrescriptions { get; set; }
private List<UserDTO> _pharmacists;
public List<UserDTO> Pharmacists
{
get => _pharmacists;
set
{
_pharmacists = value;
OnPropertyChanged();
}
}
private UserDTO _selectedPatient;
public UserDTO SelectedPatient
{
get => _selectedPatient;
set { _selectedPatient = value; OnPropertyChanged(); }
}
private ObservableCollection<MedicineInStock> _pharmacyState;
public ObservableCollection<MedicineInStock> PharmacyState
{
get => _pharmacyState;
set
{
_pharmacyState = value;
OnPropertyChanged();
}
}
private ObservableCollection<Medicine> _generalPharmacyState;
public ObservableCollection<Medicine> GeneralPharmacyState
{
get => _generalPharmacyState;
set
{
_generalPharmacyState = value;
OnPropertyChanged();
}
}
private List<UserDTO> _patients;
public List<UserDTO> Patients
{
get => _patients;
set { _patients = value; OnPropertyChanged(); }
}
public ICommand AddToPharmacyCommand => new RelayCommand(AddToPharmacy, () => true);
public ICommand LoadPatientsCommand => new RelayCommand(LoadPatients, () => true);
public ICommand LoadPharmacistsCommand => new RelayCommand(LoadPharmacists, () => true);
public ICommand GetGeneralPharmacyStateCommand => new RelayCommandAsync(GetGeneralPharmacyState, () => true);
public ICommand UpdatePharmacyStateCommand => new RelayCommandAsync(UpdatePharmacyState, () => true);
public ICommand RealizePrescriptionCommand => new RelayCommand(RealizePrescription, CanBeRealised);
public ICommand GetPharmacistsSalesCommand => new RelayCommand(GetPharmacistsSales, IsSalesDataReady);
public ICommand GetPatientsPrescriptionsCommand => new RelayCommand(GetPatientsPrescriptions, IsPrescriptionsDataReady);
public ICommand LoadPatientsUnrealisedPrescriptionsCommand => new RelayCommand(GetPatientsUnrealisedPrescriptions, () => true);
private bool IsSalesDataReady()
{
if (SelectedPharmacist == null)
return false;
if (SelectedFileExtension == FileExtensions[0])
return false;
if (EndDate == null)
return false;
if (StartDate == null)
return false;
if (EndDate < StartDate)
return false;
return true;
}
private async void GetPatientsUnrealisedPrescriptions()
{
if (SelectedPatient == null)
return;
IsWorking = true;
await Task.Run(async () =>
{
try
{
var selectedPatientsUnrealisedPrescriptions = new ObservableCollection<DoctorViewModel.Prescription>();
var allPrescriptions =
blockChainHandler.GetAllPrescriptionsByPatient(_selectedPatient.Id.ToString());
var realizedPrescriptions =
blockChainHandler.GetAllRealizedPrescriptionsByPatient(SelectedPatient.Id.ToString());
var unrealizedPrescriptions = new ObservableCollection<BlockChain.Prescription>();
foreach (var prescription in allPrescriptions)
{
if (!realizedPrescriptions.Select(x => x.prescriptionId).Contains(prescription.prescriptionId))
unrealizedPrescriptions.Add(prescription);
}
foreach (var prescription in unrealizedPrescriptions)
{
var medicines = new ObservableCollection<DoctorViewModel.PrescriptionMedicine>();
foreach (var prescriptionMedicine in prescription.medicines)
{
medicines.Add(new DoctorViewModel.PrescriptionMedicine
{
Amount = prescriptionMedicine.amount,
Medicine = (await medicineModule.SearchMedicineById(prescriptionMedicine.id.ToString()))
.Single(),
});
var actualMedicine =
PharmacyState.SingleOrDefault(x => x.Name == medicines.Last().Medicine.Name);
medicines.Last().InStockAmount = actualMedicine == null ? 0 : actualMedicine.Amount;
}
selectedPatientsUnrealisedPrescriptions.Add(new DoctorViewModel.Prescription
{
Date = prescription.Date,
Doctor = await userService.GetUser(Convert.ToInt32(prescription.doctorId)),
Id = prescription.prescriptionId,
ValidSince = prescription.ValidSince,
Medicines = medicines
});
}
SelectedPatientsUnrealisedPrescriptions = selectedPatientsUnrealisedPrescriptions;
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace);
}
OnPropertyChanged("SelectedPatientsUnrealisedPrescriptions");
});
IsWorking = false;
}
private void AddToPharmacy()
{
var medicine = new MedicineInStock(SelectedGeneralMedicine.Id, SelectedGeneralMedicine.Name, SelectedGeneralMedicine.Manufacturer, "1", "100", "1");
PharmacyState.Add(medicine);
GeneralPharmacyState.Remove(SelectedGeneralMedicine);
}
private async void LoadPatients()
{
IsWorking = true;
SelectedPatientsUnrealisedPrescriptions?.Clear();
OnPropertyChanged("SelectedPatientsUnrealisedPrescriptions");
if (SelectedPatient != null)
SelectedPatient = null;
PatientFilter.Role = "Patient";
PatientFilter.Username = "";
var users = await userService.GetUsers(PatientFilter.Name, PatientFilter.LastName,
PatientFilter.Pesel, PatientFilter.Role, PatientFilter.Username);
Patients = new List<UserDTO>(users);
IsWorking = false;
}
private async void LoadPharmacists()
{
IsWorking = true;
PharmacistFilter.Role = "Pharmacist";
PharmacistFilter.Username = "";
var users = await userService.GetUsers(PharmacistFilter.Name, PharmacistFilter.LastName,
PharmacistFilter.Pesel, PharmacistFilter.Role, PharmacistFilter.Username);
Pharmacists = new List<UserDTO>(users);
IsWorking = false;
}
private async Task GetGeneralPharmacyState()
{
IsWorking = true;
PharmacyState = new ObservableCollection<MedicineInStock>(await pharmacyDB.SearchMedicineInStock(InStockMedicineFilter.Name, InStockMedicineFilter.Manufacturer));
actualPharmacyMedicinesCount = PharmacyState.Count;
GeneralPharmacyState = new ObservableCollection<Medicine>(await pharmacyDB.SearchMedicine(GeneralMedicineFilter.Name, GeneralMedicineFilter.Manufacturer));
var temp = (from x in PharmacyState
join y in GeneralPharmacyState
on x.Id equals y.Id
select y).ToList();
GeneralPharmacyState = new ObservableCollection<Medicine>(GeneralPharmacyState.Except(temp));
IsWorking = false;
}
private async Task UpdatePharmacyState()
{
for (int i = 0; i < actualPharmacyMedicinesCount; i++)
{
var medicine = PharmacyState[i];
if (medicine.Amount == 0)
{
await pharmacyDB.RemoveMedicineFromStock(medicine.Id);
}
else
{
await pharmacyDB.UpdateMedicineAmountInStock(medicine.Id, medicine.Amount.ToString(),
medicine.Cost.ToString("G", CultureInfo.InvariantCulture));
}
}
for (int i = actualPharmacyMedicinesCount; i < PharmacyState.Count; i++)
{
var medicine = PharmacyState[i];
if (medicine.Amount == 0)
continue;
await pharmacyDB.AddMedicineToStock(medicine.Id, medicine.Amount.ToString(), medicine.Cost.ToString("G", CultureInfo.InvariantCulture));
}
GetGeneralPharmacyStateCommand.Execute(null);
GetPatientsUnrealisedPrescriptions();
//LoadPatients();
}
private bool CanBeRealised()
{
if (SelectedPatientsUnrealisedPrescription == null)
return false;
if (SelectedPatientsUnrealisedPrescription.ValidSince > DateTime.Now.Date)
return false;
foreach (var medicine in SelectedPatientsUnrealisedPrescription.Medicines)
{
if (medicine.Amount > medicine.InStockAmount)
return false;
}
return true;
}
private async void RealizePrescription()
{
IsWorking = true;
await Task.Run(async () =>
{
if (!blockChainHandler.RealizePrescription(SelectedPatientsUnrealisedPrescription.Id, CurrentUserId.ToString()))
{
MessageBox.Show("Blockchain unavailable, signing out..");
MainViewModel.LogOut();
}
await GetGeneralPharmacyState();
foreach (var prescriptionMedicine in SelectedPatientsUnrealisedPrescription.Medicines)
{
PharmacyState.SingleOrDefault(x => x.Name == prescriptionMedicine.Medicine.Name).Amount -=
prescriptionMedicine.Amount;
}
await UpdatePharmacyState();
//SelectedPatientsUnrealisedPrescriptions.Remove(SelectedPatientsUnrealisedPrescription);
//GetPatientsUnrealisedPrescriptions();
});
IsWorking = false;
}
private bool IsPrescriptionsDataReady()
{
return SelectedPatient != null && StartDate != null && EndDate != null &&
SelectedFileExtension != String.Empty && EndDate >= StartDate && SelectedFileExtension != FileExtensions[0];
}
private async void GetPatientsPrescriptions()
{
IsWorking = true;
await Task.Run(() =>
{
if (!blockChainHandler.IsBlockChainAvailable())
{
MessageBox.Show("Blockchain unavailable, signing out..");
MainViewModel.LogOut();
}
var ext = ReportExt.CSV.ToString().ToLower() == SelectedFileExtension ? ReportExt.CSV : ReportExt.PDF;
try
{
Generator.Generate(ReportType.PrescriptionsReport, ext, StartDate.Value, EndDate.Value,
SelectedPatient.Id, ref blockChainHandler);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
});
IsWorking = false;
}
private async void GetPharmacistsSales()
{
IsWorking = true;
await Task.Run(() =>
{
try
{
if (!blockChainHandler.IsBlockChainAvailable())
{
MessageBox.Show("Blockchain unavailable, signing out..");
MainViewModel.LogOut();
}
var ext = ReportExt.CSV.ToString().ToLower() == SelectedFileExtension
? ReportExt.CSV
: ReportExt.PDF;
Generator.Generate(ReportType.SoldMedicamentsReport, ext, StartDate.Value, EndDate.Value,
SelectedPharmacist.Id, ref blockChainHandler);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
});
IsWorking = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using API.Models;
using Swashbuckle.Swagger.Annotations;
using System.Runtime.Serialization.Json;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Web.Http.Description;
using API.Banco;
using System.Data;
using System.Web.Http.Cors;
using API.Notificacoes;
namespace API.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ColetaController : ApiController
{
public BancoMaquina BancoMaquina
{
get => default(BancoMaquina);
set
{
}
}
public BancoLeitura BancoLeitura
{
get => default(BancoLeitura);
set
{
}
}
public BancoLogs BancoLogs
{
get => default(BancoLogs);
set
{
}
}
public Telegram Telegram
{
get => default(Telegram);
set
{
}
}
public Email Email
{
get => default(Email);
set
{
}
}
// GET api/Coleta
[SwaggerOperation("GetAll")]
[HttpGet]
//[Produces("application/json")]
public IEnumerable<string> Get()
{
return new string[] {
"Get: https://imperius.azurewebsites.net/api/Coleta/Get Mostra todos os caminhos da API da parte de coleta",
"POST:LeituraAgora: https://imperius.azurewebsites.net/api/Coleta/LeituraAgora Salva Leitura vinda do coletor em forma de json para classe de leitura",
"POST:KeepAlive: https://imperius.azurewebsites.net/api/Coleta/KeepAlive Recebe sinal das maquinas ativas no momento (fora do ar no momento)",
"POST:InfoMaquina: https://imperius.azurewebsites.net/api/Coleta/InfoMaquina Salva uma MAquina nova vinda do coletor em forma de json para classe de Maquina",
"POST:InfoProcessador: https://imperius.azurewebsites.net/api/Coleta/InfoProcessador Salva as informaçoes de processador de uma maquina existente vinda do coletor em forma de json para classe de Processador",
"POST:InfoMemoria: https://imperius.azurewebsites.net/api/Coleta/InfoMemoria Salva as informações de memoria de uma maquina existente vinda do coletor em forma de json para classe de Memoria",
"POST:InfoDisco: https://imperius.azurewebsites.net/api/Coleta/InfoDisco Salva as informações de disco uma maquina existente vinda do coletor em forma de json para classe de Disco",
"POST:PesquisaCadastro: https://imperius.azurewebsites.net/api/Coleta/PesquisaCadastro Verifica de ja existe um cadastro de maquina com o id enviado e reotrna o id do grupo dessa maquina",
"POST:SalvaLogs: https://imperius.azurewebsites.net/api/Coleta/SalvaLogs Salva logs vinda do coletor em forma de json para classe de Logss",
"POST:CarregaAviso: https://imperius.azurewebsites.net/api/Coleta/CarregaAviso Carrega todos os aviso personalizados da maquina",
"POST:SalvaAviso: https://imperius.azurewebsites.net/api/Coleta/SalvaAviso Salva uma aviso personalidado vindo do coletor em forma de json para classe de Aviso",
};
}
[HttpPost]
public int LeituraAgora([FromBody]Leitura l)
{
BancoLeitura bl = new BancoLeitura();
return bl.Salva_Leitura(l);
}
[HttpPost]
public bool KeepAlive([FromBody]bool ok)
{
if(ok == true)
{
return true;
}
else
{
return false;
}
}
[HttpPost]
public int InfoMaquina([FromBody]Maquina maq)
{
BancoMaquina bm = new BancoMaquina();
return bm.Salva_Maquina(maq);
}
[HttpPost]
public bool InfoProcessador([FromBody]Processador maq)
{
BancoMaquina bm = new BancoMaquina();
return bm.Salva_Processador(maq);
}
[HttpPost]
public bool InfoMemoria([FromBody]Memoria maq)
{
BancoMaquina bm = new BancoMaquina();
return bm.Salva_Memoria(maq);
}
[HttpPost]
public bool InfoDisco([FromBody]Disco maq)
{
BancoMaquina bm = new BancoMaquina();
return bm.Salva_Disco(maq);
}
[HttpPost] //api/Coleta/PesquisaCadastro
public int PesquisaCadastro(string email)
{
BancoGrupo emp = new BancoGrupo();
return emp.Carregar_Grupo_Esp(email);
}
[HttpPost] //api/Coleta/SalvaLogs
public void SalvaLogs([FromBody] Logs l)
{
BancoLogs lo = new BancoLogs();
Email.EnvioEmail(l.Msg, lo.Busca_Email(lo.Salva_Logs(l)));
Telegram.EnvioTelegram(l.Data+ " "+ l.Msg);
}
[HttpPost] //api/Coleta/CarregaAviso
public DataTable CarregaAviso(int maquina)
{
BancoAviso a = new BancoAviso();
return a.Carrega_Aviso(maquina);
}
[HttpPost] //api/Coleta/SalvaAviso
public bool SalvaAviso([FromBody]Aviso aviso)
{
BancoAviso a = new BancoAviso();
DataTable lista = a.Carrega_Aviso(aviso.Maquina_Aviso);
foreach (DataRow s in lista.Rows){
if (s[1].ToString() ==aviso.NomeAviso)
{
return a.Alterar_Aviso(aviso);
}
}
return a.Salva_Aviso(aviso);
}
}
}
|
using System;
using System.Collections;
namespace Collections.CollectionsExamples
{
public static class StackExample
{
public static void ShowStack()
{
Stack humsters = new Stack();
humsters.Push("John");
humsters.Push("Carter");
humsters.Push("Abraham");
humsters.Push("Gon");
//Реализация стека в C# позволяет перебирать элементы в цикле
foreach (var humster in humsters)
{
//Элементы выводятся в том порядке, в котором они бы доставались со стека
Console.WriteLine(humster);
}
}
public static void PopElement()
{
Stack humsters = new Stack();
humsters.Push("John");
humsters.Push("Carter");
humsters.Push("Abraham");
humsters.Push("Gon");
var popedHumster = humsters.Pop();
foreach (var humster in humsters)
{
Console.WriteLine(humster);
}
//Console.WriteLine(popedHumster);
}
public static void PeekElement()
{
Stack humsters = new Stack();
humsters.Push("John");
humsters.Push("Carter");
humsters.Push("Abraham");
humsters.Push("Gon");
var peekedHumster = humsters.Peek();
foreach (var humster in humsters)
{
Console.WriteLine(humster);
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace APIChallenge
{
public static class ReceitaUtils
{
public static Estabelecimento obterEstabelecimentoReceita(string cnpj)
{
string receitaws = "https://www.receitaws.com.br/v1/cnpj/";
string url = receitaws + cnpj;
Estabelecimento stab = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
request.Accept = "application/json";
var response = request.GetResponseAsync().Result;
//Task.WaitAll(response);
using (System.IO.Stream s = response.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
stab = JsonConvert.DeserializeObject<Estabelecimento>(jsonResponse);
if (stab.Cnpj == null)
{
throw new Exception();
}
}
}
return stab;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Converter.Units
{
[Unit(nameof(LenghtUnit))]
class Feet : LenghtUnit
{
protected override double UnitDevidedByMeter => 0.3048;
public override string ToString()
{
return nameof(Feet);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UberFrba.Abm_Cliente;
namespace UberFrba.Facturacion
{
public class Factura
{
public DateTime FechaInicio { get; set; }
public DateTime FechaFin { get; set; }
public Decimal Cliente { get; set; }
public DateTime Fecha { get; set; }
public static DataTable traerViajesDeFactura(Cliente clienteElegido, DateTime fechaInicio, DateTime fechaFin)
{
DataTable dtViajes = new DataTable();
//Creo el comando a ejecutar para traer todos los viajes de un cliente entre las fechas de facturación indicadas
SqlCommand cmd = new SqlCommand("SELECT Viaje_Cant_Kilometros,Viaje_Fecha_Hora_Inicio,Viaje_Fecha_Hora_Fin,Viaje_Chofer as Dni_Chofer_Viaje,Viaje_Auto,Turno_Descripcion,Turno_Valor_Kilometro,Turno_Precio_Base FROM SAPNU_PUAS.Viaje JOIN SAPNU_PUAS.Turno on Viaje_Turno = Turno_Codigo WHERE Viaje_Cliente = @cliente AND (Viaje_Fecha_Hora_Inicio BETWEEN @fechaInicioFact AND @fechaFinFact)");
cmd.Connection = DBconnection.getInstance();
cmd.Parameters.Add("@cliente", SqlDbType.Decimal).Value = clienteElegido.Telefono;
cmd.Parameters.Add("@fechaInicioFact", SqlDbType.Date).Value = fechaInicio.Date;
cmd.Parameters.Add("@fechaFinFact", SqlDbType.Date).Value = fechaFin.Date;
SqlDataAdapter adapterViajes = new SqlDataAdapter(cmd);
try
{
adapterViajes.Fill(dtViajes);
}
catch (Exception ex)
{
throw ex;
}
return dtViajes;
}
public static String[] grabarFactura(Factura nuevaFactura)
{
//Creo el comando necesario para grabar la factura y sus items
SqlCommand cmdFactura = new SqlCommand("SAPNU_PUAS.sp_fact_cliente");
cmdFactura.CommandType = CommandType.StoredProcedure;
cmdFactura.Connection = DBconnection.getInstance();
cmdFactura.Parameters.Add("@fecha_ini", SqlDbType.DateTime).Value = nuevaFactura.FechaInicio;
cmdFactura.Parameters.Add("@fecha_fin", SqlDbType.DateTime).Value = nuevaFactura.FechaFin;
cmdFactura.Parameters.Add("@cliente", SqlDbType.Decimal).Value = nuevaFactura.Cliente;
//Creo los parametros respuesta
SqlParameter responseMsg = new SqlParameter();
SqlParameter responseErr = new SqlParameter();
responseMsg.ParameterName = "@resultado";
responseErr.ParameterName = "@codOp";
responseMsg.SqlDbType = System.Data.SqlDbType.VarChar;
responseMsg.Direction = System.Data.ParameterDirection.Output;
responseMsg.Size = 255;
responseErr.SqlDbType = System.Data.SqlDbType.Int;
responseErr.Direction = System.Data.ParameterDirection.Output;
cmdFactura.Parameters.Add(responseMsg);
cmdFactura.Parameters.Add(responseErr);
//Se realiza toda la creacion de la factura y sus items
try
{
cmdFactura.Connection.Open();
//Ejecuto el SP y veo el codigo de error
cmdFactura.ExecuteNonQuery();
int codigoError = Convert.ToInt32(cmdFactura.Parameters["@codOp"].Value);
if (codigoError != 0) throw new Exception(cmdFactura.Parameters["@resultado"].Value.ToString());
cmdFactura.Connection.Close();
}
catch (Exception ex)
{
cmdFactura.Connection.Close();
return new String[2] { "Error", ex.Message };
}
return new String[2] { "Ok", "Cliente facturado satisfactoriamente" };
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using JT7SKU.Lib.Twitch;
using Orleans;
using Services.Kirjasto.Unit.Twitch.Interfaces;
namespace Services.Kirjasto.Unit.Twitch.Grains
{
public class FollowerGrain : Grain, ITwitchFollower
{
private readonly Follower follower;
private bool IsFollowing = false;
public override Task OnActivateAsync()
{
return base.OnActivateAsync();
}
public Task NewFollower(User user,Message message)
{
follower.User = user;
IsFollowing = true;
return Task.CompletedTask;
}
}
}
|
/*
* 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.0.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using BungieNetPlatform.BungieNetPlatform.Api;
using BungieNetPlatform.BungieNetPlatform.Model;
using BungieNetPlatform.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace BungieNetPlatform.Test
{
/// <summary>
/// Class for testing DestinyDefinitionsDestinyNodeStepDefinition
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class DestinyDefinitionsDestinyNodeStepDefinitionTests
{
// TODO uncomment below to declare an instance variable for DestinyDefinitionsDestinyNodeStepDefinition
//private DestinyDefinitionsDestinyNodeStepDefinition instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of DestinyDefinitionsDestinyNodeStepDefinition
//instance = new DestinyDefinitionsDestinyNodeStepDefinition();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of DestinyDefinitionsDestinyNodeStepDefinition
/// </summary>
[Test]
public void DestinyDefinitionsDestinyNodeStepDefinitionInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" DestinyDefinitionsDestinyNodeStepDefinition
//Assert.IsInstanceOfType<DestinyDefinitionsDestinyNodeStepDefinition> (instance, "variable 'instance' is a DestinyDefinitionsDestinyNodeStepDefinition");
}
/// <summary>
/// Test the property 'DisplayProperties'
/// </summary>
[Test]
public void DisplayPropertiesTest()
{
// TODO unit test for the property 'DisplayProperties'
}
/// <summary>
/// Test the property 'StepIndex'
/// </summary>
[Test]
public void StepIndexTest()
{
// TODO unit test for the property 'StepIndex'
}
/// <summary>
/// Test the property 'NodeStepHash'
/// </summary>
[Test]
public void NodeStepHashTest()
{
// TODO unit test for the property 'NodeStepHash'
}
/// <summary>
/// Test the property 'InteractionDescription'
/// </summary>
[Test]
public void InteractionDescriptionTest()
{
// TODO unit test for the property 'InteractionDescription'
}
/// <summary>
/// Test the property 'DamageType'
/// </summary>
[Test]
public void DamageTypeTest()
{
// TODO unit test for the property 'DamageType'
}
/// <summary>
/// Test the property 'DamageTypeHash'
/// </summary>
[Test]
public void DamageTypeHashTest()
{
// TODO unit test for the property 'DamageTypeHash'
}
/// <summary>
/// Test the property 'ActivationRequirement'
/// </summary>
[Test]
public void ActivationRequirementTest()
{
// TODO unit test for the property 'ActivationRequirement'
}
/// <summary>
/// Test the property 'CanActivateNextStep'
/// </summary>
[Test]
public void CanActivateNextStepTest()
{
// TODO unit test for the property 'CanActivateNextStep'
}
/// <summary>
/// Test the property 'NextStepIndex'
/// </summary>
[Test]
public void NextStepIndexTest()
{
// TODO unit test for the property 'NextStepIndex'
}
/// <summary>
/// Test the property 'IsNextStepRandom'
/// </summary>
[Test]
public void IsNextStepRandomTest()
{
// TODO unit test for the property 'IsNextStepRandom'
}
/// <summary>
/// Test the property 'PerkHashes'
/// </summary>
[Test]
public void PerkHashesTest()
{
// TODO unit test for the property 'PerkHashes'
}
/// <summary>
/// Test the property 'StartProgressionBarAtProgress'
/// </summary>
[Test]
public void StartProgressionBarAtProgressTest()
{
// TODO unit test for the property 'StartProgressionBarAtProgress'
}
/// <summary>
/// Test the property 'StatHashes'
/// </summary>
[Test]
public void StatHashesTest()
{
// TODO unit test for the property 'StatHashes'
}
/// <summary>
/// Test the property 'AffectsQuality'
/// </summary>
[Test]
public void AffectsQualityTest()
{
// TODO unit test for the property 'AffectsQuality'
}
/// <summary>
/// Test the property 'StepGroups'
/// </summary>
[Test]
public void StepGroupsTest()
{
// TODO unit test for the property 'StepGroups'
}
/// <summary>
/// Test the property 'AffectsLevel'
/// </summary>
[Test]
public void AffectsLevelTest()
{
// TODO unit test for the property 'AffectsLevel'
}
/// <summary>
/// Test the property 'SocketReplacements'
/// </summary>
[Test]
public void SocketReplacementsTest()
{
// TODO unit test for the property 'SocketReplacements'
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Entities.Tabs
{
/// <summary>
/// This interface is responsible to provide the tab workflow settings
/// </summary>
public interface ITabWorkflowSettings
{
/// <summary>
/// This method returns the default tab workflow of the portal
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <remarks>If no default workflow is defined for a portal the method returns the Direct Publish system workflow</remarks>
/// <returns>The workflow Id of the portal default workflow</returns>
int GetDefaultTabWorkflowId(int portalId);
/// <summary>
/// This method sets the default workflow for a portal
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <param name="workflowId">Workflow Id</param>
void SetDefaultTabWorkflowId(int portalId, int workflowId);
/// <summary>
/// This method enables or disables the tab workflow for the entire portal
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <param name="enabled">true for enable it, false for disable it</param>
void SetWorkflowEnabled(int portalId, bool enabled);
/// <summary>
/// This method enables or disables the tab workflow for a specific tab
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <param name="tabId">Tab Id</param>
/// <param name="enabled">true for enable it, false for disable it</param>
/// <remarks>this won't enable workflow of a tab if the tab workflow is disabled at portal level</remarks>
void SetWorkflowEnabled(int portalId, int tabId, bool enabled);
/// <summary>
/// The method returns true if the workflow is enabled for a tab
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <param name="tabId">Tab Id</param>
/// <returns>True if the workflow is enabled, false otherwise</returns>
bool IsWorkflowEnabled(int portalId, int tabId);
/// <summary>
/// The method returns true is the workflow is enabled at portal level
/// </summary>
/// <param name="portalId">Portal Id</param>
/// <returns>True if the workflow is enabled, false otherwise</returns>
bool IsWorkflowEnabled(int portalId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConsultingManager.Domain.Repository;
using ConsultingManager.Dto;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ConsultingManager.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : TnfController
{
private ICustomerRepository _customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
[HttpPost]
public async Task<IActionResult> Add(CustomerDto customerDto)
{
return Ok(await _customerRepository.Add(customerDto));
}
[HttpPut]
public async Task<IActionResult> Update(CustomerDto customerDto)
{
try {
return Ok(await _customerRepository.Update(customerDto));
} catch (Exception ex)
{
return BadRequest("Erro ao atualizar cliente: " + ex.Message);
}
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Ok(await _customerRepository.GetAll());
}
[HttpGet("chart")]
public async Task<IActionResult> GetCustomersDueTasks()
{
try
{
return Ok(await _customerRepository.GetChartResult());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("cities")]
public async Task<IActionResult> GetCities()
{
try
{
return Ok(await _customerRepository.GetCities());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("platforms")]
public async Task<IActionResult> GetPlatforms()
{
try
{
return Ok(await _customerRepository.GetPlatforms());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("categories")]
public async Task<IActionResult> GetCustomerCategories()
{
try
{
return Ok(await _customerRepository.GetCustomerCategories());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("plans")]
public async Task<IActionResult> GetPlans()
{
try
{
return Ok(await _customerRepository.GetPlans());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("situations")]
public async Task<IActionResult> GetCustomerSituations()
{
try
{
return Ok(await _customerRepository.GetCustomerSituations());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
[HttpGet("consultants")]
public async Task<IActionResult> GetConsultants()
{
try
{
return Ok(await _customerRepository.GetConsultants());
}
catch (Exception ex)
{
return BadRequest("Erro ao buscar informações.");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BPiaoBao.Web.SupplierManager.Models
{
public class TicketSumQueryEntity
{
public string OrderId { get; set; }
public string OutOrderId { get; set; }
public string PNR { get; set; }
public string TicketNumber { get; set; }
public string PlatformCode { get; set; }
public string PolicyType { get; set; }
public string CarrayCode { get; set; }
public string FromCity { get; set; }
public string ToCity { get; set; }
public int? TicketStatus { get; set; }
public string BusinessmanName { get; set; }
public string BusinessmanCode { get; set; }
public string OperatorAccount { get; set; }
public DateTime? StartIssueRefundTime { get; set; }
public DateTime? EndIssueRefundTime { get; set; }
public int? PayWay { get; set; }
public int page { get; set; }
public int rows { get; set; }
}
} |
using LogicBuilder.Attributes;
using LogicBuilder.Expressions.Utils.Strutures;
namespace Contoso.Parameters.Expansions
{
public class SortDescriptionParameters
{
public SortDescriptionParameters()
{
}
public SortDescriptionParameters
(
[ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)]
[NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "fieldTypeSource")]
[Comments("Update fieldTypeSource first. This property to sort by.")]
string propertyName,
[Comments("Click the variable button and select th configured ListSortDirection.")]
ListSortDirection order,
[ParameterEditorControl(ParameterControlType.ParameterSourceOnly)]
[Comments("Fully qualified class name for the model type.")]
string fieldTypeSource = "Contoso.Domain.Entities"
)
{
this.PropertyName = propertyName;
this.SortDirection = order;
}
public string PropertyName { get; set; }
public ListSortDirection SortDirection { get; set; }
}
}
|
using System;
using System.Threading.Tasks;
using W3ChampionsStatisticService.CommonValueObjects;
using W3ChampionsStatisticService.Matches;
using W3ChampionsStatisticService.PadEvents;
using W3ChampionsStatisticService.Ports;
using W3ChampionsStatisticService.ReadModelBase;
namespace W3ChampionsStatisticService.PlayerStats.RaceOnMapVersusRaceStats
{
public class PlayerRaceOnMapVersusRaceRatioHandler : IReadModelHandler
{
private readonly IPlayerStatsRepository _playerRepository;
private readonly IPatchRepository _patchRepository;
public PlayerRaceOnMapVersusRaceRatioHandler(
IPlayerStatsRepository playerRepository,
IPatchRepository patchRepository
)
{
_playerRepository = playerRepository;
_patchRepository = patchRepository;
}
public async Task Update(MatchFinishedEvent nextEvent)
{
if (nextEvent.WasFakeEvent) return;
var dataPlayers = nextEvent.match.players;
if (dataPlayers.Count == 2)
{
var p1 = await _playerRepository.LoadMapAndRaceStat(dataPlayers[0].battleTag, nextEvent.match.season)
?? PlayerRaceOnMapVersusRaceRatio.Create(dataPlayers[0].battleTag, nextEvent.match.season);
var p2 = await _playerRepository.LoadMapAndRaceStat(dataPlayers[1].battleTag, nextEvent.match.season)
?? PlayerRaceOnMapVersusRaceRatio.Create(dataPlayers[1].battleTag, nextEvent.match.season);
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = start.AddMilliseconds(nextEvent.match.startTime);
var patch = await _patchRepository.GetPatchVersionFromDate(date);
p1.AddMapWin(dataPlayers[0].race,
dataPlayers[1].race,
"Overall",
dataPlayers[0].won, patch);
p1.AddMapWin(dataPlayers[0].race,
dataPlayers[1].race,
"Overall",
dataPlayers[0].won, "All");
p2.AddMapWin(dataPlayers[1].race,
dataPlayers[0].race,
"Overall",
dataPlayers[1].won, patch);
p2.AddMapWin(dataPlayers[1].race,
dataPlayers[0].race,
"Overall",
dataPlayers[1].won, "All");
p1.AddMapWin(dataPlayers[0].race,
dataPlayers[1].race,
new MapName(nextEvent.match.map).Name,
dataPlayers[0].won, patch);
p1.AddMapWin(dataPlayers[0].race,
dataPlayers[1].race,
new MapName(nextEvent.match.map).Name,
dataPlayers[0].won, "All");
p2.AddMapWin(dataPlayers[1].race,
dataPlayers[0].race,
new MapName(nextEvent.match.map).Name,
dataPlayers[1].won, patch);
p2.AddMapWin(dataPlayers[1].race,
dataPlayers[0].race,
new MapName(nextEvent.match.map).Name,
dataPlayers[1].won, "All");
await _playerRepository.UpsertMapAndRaceStat(p1);
await _playerRepository.UpsertMapAndRaceStat(p2);
}
}
}
} |
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace AlquilerVideo.Models
{
public class Cliente
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)]
[DisplayName("Identificador")]
public string _id { get; set; }
[Required]
[DisplayName("Cedula")]
public string Cedula { get; set; }
[Required]
[DisplayName("Nombre")]
public string Nombre { get; set; }
[Required]
[DisplayName("Primer Apellido")]
public string Apellido1 { get; set; }
[Required]
[DisplayName("Segundo Apellido")]
public string Apellido2 { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Fecha de Registro")]
public string Fecha_Registro { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Fecha de Nacimiento")]
public string Fecha_Nacimiento { get; set; }
[Required]
[DisplayName("Direccion")]
public string Direccion { get; set; }
//public string cedula { get; set; }
//public string nombreCompleto { get; set; }
//public bool mayorEdad { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class SpriteController : MonoBehaviour
{
[SerializeField] private Sprite[] _Sprites;
private SpriteRenderer _SpriteRenderer;
private void Awake()
{
_SpriteRenderer = GetComponent<SpriteRenderer>();
}
private void OnEnable()
{
var spriteToSelect = Random.Range(0, _Sprites.Length);
_SpriteRenderer.sprite = _Sprites[spriteToSelect];
}
}
|
using System;
namespace RipplerES.SubscriptionHandler
{
public interface ISubscriptionRepository
{
void Subscribe(Guid channelId, string name);
EventData[] Fetch(Guid channelId);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ImageProcAhmetCAN
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
Bitmap imageSource;
private void Form2_Load(object sender, EventArgs e)
{
}
private void açToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult getImage = openFileDialog1.ShowDialog();
if (getImage == DialogResult.OK){
imageSource = new Bitmap(openFileDialog1.FileName);
imageBox.Image = imageSource;
}
}
private void getColor_Click(object sender, EventArgs e)
{
if (imageBox.Image != null){
int xCoor = int.Parse(x.Text);
int yCoor = int.Parse(y.Text);
Color getImageColor = imageSource.GetPixel(xCoor, yCoor);
getColor.BackColor = getImageColor;
}else{
MessageBox.Show("Herhangi bir resim açmadınız");
}
}
private void renkAlToolStripMenuItem_Click(object sender, EventArgs e)
{
if (imageBox.Image != null){
int xCoor = int.Parse(x.Text);
int yCoor = int.Parse(y.Text);
Color getImageColor = imageSource.GetPixel(xCoor, yCoor);
getColor.BackColor = getImageColor;
}else{
MessageBox.Show("Herhangi bir resim açmadınız");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using RoutingSlipWebApp.Models;
namespace RoutingSlipWebApp.Services
{
public class NewOrderCommand : ICommand
{
private readonly ILogger<ICommand> _logger;
private readonly ServicesResolver _servicesResolver;
public NewOrderCommand(ILogger<ICommand> logger, ServicesResolver servicesResolver)
{
_servicesResolver = servicesResolver;
_logger = logger;
}
public async Task ExecuteAsync()
{
var newOrder = new Order
{
Id = Guid.NewGuid().ToString()
};
await _servicesResolver.Resolve<NewOrder>(newOrder).RunAsync();
_logger.LogInformation($"{nameof(NewOrderCommand)} executed.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Hotel.Data.Models
{
public class VrstaSmjestaja
{
public int Id { set; get; }
public string Naziv { set; get; }
}
}
|
using System;
namespace InterfacesDIDelegatesEvents
{
class Program
{
static void Main(string[] args)
{
var youngest = new YoungestSon();
var eldest = new EldestSon();
var dad = new Dad(eldest);
dad.SeekHelpConstructorInjection("Need help");
dad.SeekHelpMethodInjection(youngest, "Need help");
dad.Son = eldest;
dad.SeekHelpPropertyInjection("Help");
/** Generics */
Comparation<int> comparation = new Comparation<int>();
bool b = comparation.CompareIfSame(10, 10);
Console.WriteLine(b);
/** Delegates */
DelegateTest del = new DelegateTest();
del.LongRunning(Callback);
Console.ReadLine();
}
static void Callback(int num)
{
Console.WriteLine("Delegate passed value: {0}", num);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GameShop.Models
{
public class GamesPublishers
{
public int GameId { get; set; }
public int PublisherId { get; set; }
public int Id { get; set; }
public virtual Publishers Publishers { get; set; }
public virtual Games Games { get; set; }
}
}
|
namespace DD5eShapedStatblockMaker.Data.Definition
{
public enum CreatureSize
{
Tiny, Small, Medium, Large, Huge, Gargantuan
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class GroupForum
{
public static int GetGroupIdByForumID(int ForumID)
{
int result = 0;
result = GroupForum.All().Where(gf => gf.ForumID == ForumID).Select(gf => gf.GroupID).FirstOrDefault();
return result;
}
public static void SaveGroupForum(GroupForum groupForum)
{
if (GroupForum.All().Where(gf => gf.ForumID == groupForum.ForumID && gf.GroupID == groupForum.GroupID).FirstOrDefault() == null)
{
Add(groupForum);
}
}
public static void DeleteGroupForum(int ForumID, int GroupID)
{
Delete(GroupForum.All().Where(gf => gf.GroupID == GroupID && gf.ForumID == ForumID).FirstOrDefault().GroupID);
}
public static void DeleteGroupForum(GroupForum groupForum)
{
Delete(groupForum);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Project.Service;
using Project.Service.Model;
namespace Project.MVC.Controllers
{
public abstract class VehicleMakeController : Controller
{
private IVehicleMake _vehiclemake;
public VehicleMakeController(IVehicleMake vehiclemake)
{
_vehiclemake = vehiclemake;
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(IVehicleMake model)
{
return View();
}
[HttpGet]
public ActionResult Update(int Id)
{
return View();
}
[HttpPost]
public ActionResult Update(IVehicleMake model)
{
return View();
}
[HttpGet]
public ActionResult Delete(int Id)
{
return View();
}
/* [HttpPost]
public ActionResult Delete(int Id)
{
return View();
}*/
}
} |
// Accord Imaging Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © Diego Catalano, 2013
// diego.catalano at live.com
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Imaging
{
using System.Drawing;
/// <summary>
/// Co-occurrence Degree.
/// </summary>
///
public enum CooccurrenceDegree
{
/// <summary>
/// Find co-occurrences at 0° degrees.
/// </summary>
///
Degree0,
/// <summary>
/// Find co-occurrences at 45° degrees.
/// </summary>
///
Degree45,
/// <summary>
/// Find co-occurrences at 90° degrees.
/// </summary>
///
Degree90,
/// <summary>
/// Find co-occurrences at 135° degrees.
/// </summary>
///
Degree135
};
/// <summary>
/// Gray-Level Co-occurrence Matrix (GLCM).
/// </summary>
///
public class GrayLevelCooccurrenceMatrix
{
private CooccurrenceDegree degree;
private bool autoGray = true;
private bool normalize = true;
private int numPairs = 0;
private int distance = 1;
/// <summary>
/// Gets or sets whether the maximum value of gray should be
/// automatically computed from the image. If set to false,
/// the maximum gray value will be assumed 255.
/// </summary>
///
public bool AutoGray
{
get { return autoGray; }
set { autoGray = value; }
}
/// <summary>
/// Gets or sets whether the produced GLCM should be normalized,
/// dividing each element by the number of pairs. Default is true.
/// </summary>
///
/// <value>
/// <c>true</c> if the GLCM should be normalized; otherwise, <c>false</c>.
/// </value>
///
public bool Normalize
{
get { return normalize; }
set { normalize = value; }
}
/// <summary>
/// Gets or sets the direction at which the co-occurrence should be found.
/// </summary>
///
public CooccurrenceDegree Degree
{
get { return degree; }
set { degree = value; }
}
/// <summary>
/// Gets or sets the distance at which the
/// texture should be analyzed. Default is 1.
/// </summary>
///
public int Distance
{
get { return distance; }
set { distance = value; }
}
/// <summary>
/// Gets the number of pairs registered during the
/// last <see cref="Compute(UnmanagedImage)">computed GLCM</see>.
/// </summary>
///
public int Pairs
{
get { return numPairs; }
}
/// <summary>
/// Initializes a new instance of the <see cref="GrayLevelCooccurrenceMatrix"/> class.
/// </summary>
///
public GrayLevelCooccurrenceMatrix() { }
/// <summary>
/// Initializes a new instance of the <see cref="GrayLevelCooccurrenceMatrix"/> class.
/// </summary>
///
/// <param name="distance">The distance at which the texture should be analyzed.</param>
///
public GrayLevelCooccurrenceMatrix(int distance)
{
this.distance = distance;
}
/// <summary>
/// Initializes a new instance of the <see cref="GrayLevelCooccurrenceMatrix"/> class.
/// </summary>
///
/// <param name="distance">The distance at which the texture should be analyzed.</param>
/// <param name="degree">The direction to look for co-occurrences.</param>
///
public GrayLevelCooccurrenceMatrix(int distance, CooccurrenceDegree degree)
{
this.distance = distance;
this.degree = degree;
}
/// <summary>
/// Initializes a new instance of the <see cref="GrayLevelCooccurrenceMatrix"/> class.
/// </summary>
///
/// <param name="distance">The distance at which the texture should be analyzed.</param>
/// <param name="degree">The direction to look for co-occurrences.</param>
/// <param name="autoGray">Whether the maximum value of gray should be
/// automatically computed from the image. Default is true.</param>
/// <param name="normalize">Whether the produced GLCM should be normalized,
/// dividing each element by the number of pairs. Default is true.</param>
///
public GrayLevelCooccurrenceMatrix(int distance, CooccurrenceDegree degree,
bool normalize = true, bool autoGray = true)
{
this.distance = distance;
this.degree = degree;
this.normalize = normalize;
this.autoGray = autoGray;
}
/// <summary>
/// Computes the Gray-level Co-occurrence Matrix (GLCM)
/// for the given source image.
/// </summary>
///
/// <param name="source">The source image.</param>
///
/// <returns>A square matrix of double-precision values containing
/// the GLCM for the given <paramref name="source"/>.</returns>
///
public double[,] Compute(UnmanagedImage source)
{
return Compute(source, new Rectangle(0, 0, source.Width, source.Height));
}
/// <summary>
/// Computes the Gray-level Co-occurrence Matrix for the given matrix.
/// </summary>
///
/// <param name="source">The source image.</param>
/// <param name="region">A region of the source image where
/// the GLCM should be computed for.</param>
///
/// <returns>A square matrix of double-precision values containing the GLCM for the
/// <paramref name="region"/> of the given <paramref name="source"/>.</returns>
///
public double[,] Compute(UnmanagedImage source, Rectangle region)
{
int width = region.Width;
int height = region.Height;
int stride = source.Stride;
int offset = stride - width;
int maxGray = 255;
int startX = region.X;
int startY = region.Y;
double[,] cooccurrence;
unsafe
{
byte* src = (byte*)source.ImageData.ToPointer() + startY * stride + startX;
if (autoGray)
maxGray = max(width, height, offset, src);
numPairs = 0;
int size = maxGray + 1;
cooccurrence = new double[size, size];
switch (degree)
{
case CooccurrenceDegree.Degree0:
for (int y = startY; y < height; y++)
{
for (int x = startX + distance; x < width; x++)
{
byte a = src[stride * y + (x - distance)];
byte b = src[stride * y + x];
cooccurrence[a, b]++;
numPairs++;
}
}
break;
case CooccurrenceDegree.Degree45:
for (int y = startY + distance; y < height; y++)
{
for (int x = startX; x < width - distance; x++)
{
byte a = src[stride * y + x];
byte b = src[stride * (y - distance) + (x + distance)];
cooccurrence[a, b]++;
numPairs++;
}
}
break;
case CooccurrenceDegree.Degree90:
for (int y = startY + distance; y < height; y++)
{
for (int x = startX; x < width; x++)
{
byte a = src[stride * (y - distance) + x];
byte b = src[stride * y + x];
cooccurrence[a, b]++;
numPairs++;
}
}
break;
case CooccurrenceDegree.Degree135:
for (int y = startY + distance; y < height; y++)
{
int steps = width - 1;
for (int x = startX; x < width - distance; x++)
{
byte a = src[stride * y + (steps - x)];
byte b = src[stride * (y - distance) + (steps - distance - x)];
cooccurrence[a, b]++;
numPairs++;
}
}
break;
}
if (normalize && numPairs > 0)
{
fixed (double* ptrMatrix = cooccurrence)
{
double* c = ptrMatrix;
for (int i = 0; i < cooccurrence.Length; i++, c++)
*c /= numPairs;
}
}
}
return cooccurrence;
}
unsafe private static int max(int width, int height, int offset, byte* src)
{
int maxGray = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++, src++)
if (*src > maxGray) maxGray = *src;
src += offset;
}
return maxGray;
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using WebAPI.Models;
namespace WebAPI.Data{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base (options) { }
public DbSet<Funcionario> Funcionario { get; set; }
public DbSet<Departamento> Departamento { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Integrated Security=SSPI;Persist Security Info=False;User ID=DESKTOP-6JIGCVA\kinha;Initial Catalog=Departamento;Data Source=DESKTOP-6JIGCVA");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Departamento>()
.HasData(new List<Departamento>(){
new Departamento(1, "Administrativo","SP"),
new Departamento(2, "Financeiro","SP"),
new Departamento(3, "Recursos Humanos","SP"),
new Departamento(4, "Departamento Comercial","SP"),
});
builder.Entity<Funcionario>()
.HasData(new List<Funcionario>{
new Funcionario(1, "Marcos","Enviar","11554454x",3),
new Funcionario(2, "João","Enviar","81584454x",2),
new Funcionario(3, "Clara","Enviar","31759454x",1),
new Funcionario(4, "Matheus","Enviar","51534454x",4),
new Funcionario(5, "Maria","Enviar","11254464x",3)
});
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Navigation.Models
{
public class Blog
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Boş buraxmayın")]
public int Orderby { get; set; }
public string BigPhoto { get; set; }
public string SmallPhoto { get; set; }
[Required(ErrorMessage = "Boş buraxmayın")]
[MaxLength(250, ErrorMessage = "Max 250 simvol istifadə edə bilərsiniz!")]
public string Title { get; set; }
[Required(ErrorMessage = "Boş buraxmayın")]
[Column(TypeName = "datetime")]
public DateTime CreateAt { get; set; }
[Required(ErrorMessage = "Boş buraxmayın")]
[MaxLength(50, ErrorMessage = "Max 50 simvol istifadə edə bilərsiniz!")]
public string BlogType { get; set; }
[Required(ErrorMessage = "Boş buraxmayın")]
[Column(TypeName = "ntext")]
public string Info { get; set; }
}
} |
using System.Collections.Generic;
using Printer_Status.Helpers;
using SnmpSharpNet;
// ReSharper disable MemberCanBePrivate.Global
#pragma warning disable 1591
namespace Printer_Status.Printers
{
/// <summary>
/// An object representation of a printer's output tray.
/// </summary>
public struct Output
{
/// <summary>
/// Initialises an Output instance from a dictionary representation of an SNMP row.
/// </summary>
/// <param name="results">A dictionary representation of an SNMP row.</param>
public Output(Dictionary<string, AsnType> results)
{
OutputType = (OutputType) results["Type"].ToInt();
CapacityUnit = (CapacityUnit)results["CapacityUnit"].ToInt();
MaxCapacity = results["MaxCapacity"].ToInt();
RemainingCapacity = results["RemainingCapacity"].ToInt();
Name = results["Name"].ToString();
VendorName = results["VendorName"].ToString();
Model = results["Model"].ToString();
Version = results["Version"].ToString();
SerialNumber = results["SerialNumber"].ToString();
Description = results["Description"].ToString();
Security = (PresentOnOff)results["Security"].ToInt();
DimUnit = (MediaUnit)results["DimUnit"].ToInt();
StackingOrder = (OutputStackingOrder)results["StackingOrder"].ToInt();
PageDeliveryOrientation = (OutputPageDeliveryOrientation)results["PageDeliveryOrientation"].ToInt();
Bursting = (PresentOnOff)results["Bursting"].ToInt();
Decollating = (PresentOnOff)results["Decollating"].ToInt();
PageCollated = (PresentOnOff)results["PageCollated"].ToInt();
OffsetStacking = (PresentOnOff)results["OffsetStacking"].ToInt();
Percent = ValueHelper.LevelToPercent(MaxCapacity, RemainingCapacity);
}
public OutputType OutputType { get; }
public CapacityUnit CapacityUnit { get; }
public int MaxCapacity { get; }
public int RemainingCapacity { get; }
public string Name { get; }
public string VendorName { get; }
public string Model { get; }
public string Version { get; }
public string SerialNumber { get; }
public string Description { get; }
public PresentOnOff Security { get; }
public MediaUnit DimUnit { get; }
public OutputStackingOrder StackingOrder { get; }
public OutputPageDeliveryOrientation PageDeliveryOrientation { get; }
public PresentOnOff Bursting { get; }
public PresentOnOff Decollating { get; }
public PresentOnOff PageCollated { get; }
public PresentOnOff OffsetStacking { get; }
public string Percent { get; }
}
public enum OutputType
{
other = 1,
unknown = 2,
removableBin = 3,
unRemovableBin = 4,
continuousRollDevice = 5,
mailBox = 6,
continuousFanFold = 7
}
public enum OutputStackingOrder
{
unknown = 2,
firstToLast = 3,
LastToFirst = 4
}
public enum OutputPageDeliveryOrientation
{
faceUp = 3,
faceDown = 4
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace SolarDataUploader
{
public partial class Form1 : Form
{
/// <summary>
/// Database connection object
/// </summary>
private MySqlConnection _conn;
/// <summary>
/// Creates a new instance of the dialog
/// </summary>
public Form1()
{
InitializeComponent();
comboBoxSchema.Enabled = !checkBox1.Checked;
buttonDbTest.Enabled = !checkBox1.Checked;
reopenDatabase();
}
private void buttonDbTest_Click(object sender, EventArgs e)
{
reopenDatabase();
comboBoxSchema.Items.Clear();
MySqlDataReader dr = new MySqlCommand("SHOW DATABASES;", _conn).ExecuteReader();
while(dr.Read())
{
comboBoxSchema.Items.Add(dr.GetString(0));
}
dr.Close();
}
private void reopenDatabase()
{
MySqlConnectionStringBuilder mycsb = new MySqlConnectionStringBuilder
{
Password = textBox3.Text,
Port = (uint) numericUpDown1.Value,
Server = textBox1.Text,
UserID = textBox2.Text
};
if (_conn != null)
if (_conn.State == ConnectionState.Open)
_conn.Close();
_conn = new MySqlConnection(mycsb.GetConnectionString(true));
_conn.Open();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
comboBoxSchema.Enabled = !checkBox1.Checked;
buttonDbTest.Enabled = !checkBox1.Checked;
}
Dictionary<DateTime, float> data = new Dictionary<DateTime, float>();
float gen = 0;
DateTime date = DateTime.MinValue;
private void buttonDatafileBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
labelFileName.Text = openFileDialog1.FileName;
try
{
data = analyseFile(openFileDialog1.FileName, out date, out gen);
}
catch (IOException ex)
{
MessageBox.Show("IO error encountered reading file. Please try again.\n\n" + ex.Message);
}
label8.Text = string.Format("On {0}, {1} kWh was generated.", date, gen);
chartDataVisualiser.Series[0].Points.Clear();
foreach (KeyValuePair<DateTime, float> keyValuePair in data)
{
chartDataVisualiser.Series[0].Points.AddXY(keyValuePair.Key, keyValuePair.Value);
}
groupBox3.Visible = true;
}
private static Dictionary<DateTime, float> analyseFile(string path, out DateTime fileDate, out float totalGeneration)
{
StreamReader sr = new StreamReader(path);
sr.ReadLine(); // sep=;
string data = sr.ReadLine();
Regex r = new Regex(@"\|(?<date>[0-9]{2}/[0-9]{2}/[0-9]{4})$");
string date = r.Match(data).Groups["date"].Value;
Dictionary<DateTime, float> dataDict = new Dictionary<DateTime, float>();
r = new Regex(@"^(?<time>[0-2][0-9]:[0-5]0);(?<kwh>[0-9.]+)$");
Regex rtotal = new Regex(@"^E-Today kWh;(?<kwh>[0-9.]+)$");
totalGeneration = 0;
while (!sr.EndOfStream)
{
data = sr.ReadLine();
Match m = r.Match(data);
if (m.Success)
{
float gen = float.Parse(m.Groups["kwh"].Value);
dataDict.Add(DateTime.Parse(date + " " + m.Groups["time"].Value), gen);
}
m = rtotal.Match(data);
if (m.Success)
{
totalGeneration = float.Parse(m.Groups["kwh"].Value);
}
}
fileDate = DateTime.Parse(date);
return dataDict;
}
private void buttonSave_Click(object sender, EventArgs e)
{
_conn.ChangeDatabase(comboBoxSchema.Text);
MySqlTransaction t = _conn.BeginTransaction(IsolationLevel.Serializable);
try
{
MySqlCommand cmd;
foreach (KeyValuePair<DateTime, float> keyValuePair in data)
{
cmd = new MySqlCommand(
string.Format("INSERT INTO hourlydata VALUES ('{0}','{1}');",
keyValuePair.Key.ToString("yyyy'-'MM'-'dd HH':'mm':'ss"),
keyValuePair.Value), _conn);
cmd.ExecuteNonQuery();
}
cmd = new MySqlCommand(
string.Format("INSERT INTO dailydata VALUES ('{0}','{1}');",
date.ToString("yyyy'-'MM'-'dd HH':'mm':'ss"),
gen), _conn);
cmd.ExecuteNonQuery();
t.Commit();
}
catch(MySqlException)
{
t.Rollback();
}
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Input;
using City_Center.Clases;
using City_Center.Services;
using GalaSoft.MvvmLight.Command;
using Xamarin.Forms;
using static City_Center.Models.TarjetaUsuarioResultado;
namespace City_Center.ViewModels
{
public class ConsultaTarjetaWinViewModel:BaseViewModel
{
#region Services
private ApiService apiService;
#endregion
#region Attributes
private string imagenTarjeta;
private int puntosWin;
private string noSocio;
private string tipoDocumento;
private string numeroDocumento;
private TarjetaUsuarioReturn listaTarjetausuario;
#endregion
#region Properties
public string ImagenTarjeta
{
get { return this.imagenTarjeta; }
set { SetValue(ref this.imagenTarjeta, value); }
}
public int PuntosWin
{
get { return this.puntosWin; }
set { SetValue(ref this.puntosWin, value); }
}
public string NoSocio
{
get { return this.noSocio; }
set { SetValue(ref this.noSocio, value); }
}
public string TipoDocumento
{
get { return this.tipoDocumento; }
set { SetValue(ref this.tipoDocumento, value); }
}
public string NumeroDocumento
{
get { return this.numeroDocumento; }
set { SetValue(ref this.numeroDocumento, value); }
}
#endregion
#region Commands
public ICommand ConsultaPuntosCommand
{
get
{
return new RelayCommand(ConsultaPuntos);
}
}
private async void ConsultaPuntos()
{
try
{
LoadTarjetaUsuario();
}
catch (Exception ex)
{
//await Application.Current.MainPage.DisplayAlert(
// "Error",
// ex.ToString(),
// "Ok");
}
}
#endregion
#region Methods
private async void LoadTarjetaUsuario()
{
try
{
var connection = await this.apiService.CheckConnection();
if (!connection.IsSuccess)
{
await Mensajes.Alerta("Verificá tu conexión a Internet");
return;
}
NoSocio = Application.Current.Properties["NumeroSocio"].ToString();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("usu_id_tarjeta",NoSocio )
});
var response = await this.apiService.Get<TarjetaUsuarioReturn>("/tarjetas", "/tarjetaUsuario", content);
if (!response.IsSuccess)
{
await Mensajes.Alerta("Ha habido un error en tu solicitud, por favor volvé a intentarlo");
return;
}
this.listaTarjetausuario = (TarjetaUsuarioReturn)response.Result;
ImagenTarjeta = VariablesGlobales.RutaServidor + listaTarjetausuario.resultado.tar_imagen;
PuntosWin = listaTarjetausuario.resultado.tar_puntos;
NumeroDocumento = Application.Current.Properties["NumeroDocumento"].ToString();
TipoDocumento = Application.Current.Properties["TipoDocumento"].ToString();
//NoSocio = listaTarjetausuario.resultado.tar_id;
}
catch (Exception ex)
{
//await Mensajes.Error(ex.ToString());
}
}
#endregion
#region Contructors
public ConsultaTarjetaWinViewModel()
{
this.apiService = new ApiService();
LoadTarjetaUsuario();
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine.UI;
public class ObjectList{
private static ObjectList instance = new ObjectList();
private string[] objects;
private AcceptedTags[] acceptedTags;
private List<Text>[] currentObjects = new List<Text>[3];
private int[] usedIndexs;
private int counter;
private int subCount;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectList"/> class.
/// Made private so that it can be a singleton.
/// </summary>
private ObjectList(){}
/// <summary>
/// Returns the single instance of the ObjectList.
/// </summary>
/// <returns>The single instance of the ObjectList class.</returns>
public static ObjectList getInstance(){
return instance;
}
/// <summary>
/// Initializes the instance of the ObjectList.
/// </summary>
/// <param name="asset">Asset.</param>
public void initialize(TextAsset objectListTextAsset, TextAsset acceptedTagsTextAsset){
counter = 0;
subCount = 0;
// get array of available objects
char[] lineSplitters = { '\n', '\r' };
objects = objectListTextAsset.text.Split (lineSplitters, System.StringSplitOptions.RemoveEmptyEntries);
usedIndexs = new int[objects.Length];
//initialize to 0, reperesenting nothing has been used yet
for (int j = 0; j < usedIndexs.Length; j++)
{
usedIndexs[j] = 0;
}
// get text objects from game
for (int i = 0; i < currentObjects.Length; i++) {
List<GameObject> text = StartGame.findInactive ("tObject" + i, "vMenu");
List<Text> texts = new List<Text> ();
for(int j = 0; j < text.Count; j++){
texts.Add (text [j].GetComponent<Text> ());
}
currentObjects[i] = texts;
}
pickCurrentObjects ();
char[] tagSplitters = { ',' };
string[] lines = acceptedTagsTextAsset.text.Split (lineSplitters);
acceptedTags = new AcceptedTags[lines.Length];
for (int i = 0; i < lines.Length; i++) {
string[] tags = lines [i].Split (tagSplitters);
acceptedTags [i] = new AcceptedTags (tags [0], tags);
}
}
public void prepareScore()
{
long coins = PlayerData.getInstance().getMonies();
string oldRank = EnumRank.getRankFromCoins(coins).name;
Text tRank = StartGame.findInactive("tRank_main","vMenu")[0] .GetComponent<Text>(),
tCoins = StartGame.findInactive("tCoins_main","vMenu")[0].GetComponent<Text>();
tRank.text = string.Concat("Rank:\n", oldRank);
tCoins.text = string.Concat("$", coins.ToString());
}
public static void pickCurrentObjectsStatic()
{
ObjectList.getInstance().pickCurrentObjects();
}
/// <summary>
/// Picks a new set of 3 objects to give to the player and displays them in the main menu panel.
/// </summary>
///
/// Todo: get it so that the list resets immediately if exhausted
/// Todo: update the rank and money
public void pickCurrentObjects(){
prepareScore();
for (int i = 0; i < currentObjects.Length; i++) {
if (subCount == 5) {
Debug.Log ("reseting list");
subCount = 0;
counter = 0;
for (int k = 0; k < usedIndexs.Length; k++) {
usedIndexs [k] = 0;
}
}
if (counter == usedIndexs.Length) {
//if we've exhausted the entire list, indicate as such
Debug.Log ("object list exhausted");
for (int j = 0; j < currentObjects [i].Count; j++) {
currentObjects [i] [j].text = "no more unique objects";
}
subCount++;
continue;
}
//get first random value
int index = Random.Range (0, objects.Length);
//if used before, keep searching for unused word
while(usedBefore(usedIndexs, index)){
index = Random.Range (0, objects.Length);
}
Debug.Log("object "+objects[index]);
for (int j = 0; j < currentObjects [i].Count; j++) {
currentObjects [i][j].text = objects [index];
}
usedIndexs [index] = 1;
counter++;
}
}
/// <summary>
/// Checks if the number was found in the array up to a given index.
/// </summary>
/// <returns><c>true</c>, If number was found in array, <c>false</c> otherwise.</returns>
/// <param name="array">The int array to look through</param>
/// <param name="num">The number to make sure that is not already present in the array.</param>
/// <param name="maxIndex">The maximum index to look up to in the array (exclusive)</param>
public bool inArray(int[] array, int num, int maxIndex){
for (int i = 0; i < maxIndex; i++) {
if (array [i] == num) {
return true;
}
}
return false;
}
/// <summary>
/// Checks if the randomly chosen index for a word has been used already.
/// </summary>
/// <returns><c>true</c>, If word was used already, <c>false</c> otherwise.</returns>
/// <param name="array">The int array to look through</param>
/// <param name="num">The Index to check against.</param>
public bool usedBefore(int[] array, int num){
if (array [num] == 1) {
return true;
} else {
return false;
}
}
/// <summary>
/// Returs the current Text objects so that you can check the current list of objects the player is tasked to find.
/// </summary>
/// <returns>The current text objects the player is searching for.</returns>
public List<Text>[] getCurrentObjects(){
return currentObjects;
}
public AcceptedTags[] getAcceptedTags(){
return acceptedTags;
}
}
public class AcceptedTags {
private string _acceptedTags;
private string[] _similarTags;
public AcceptedTags(string acceptedTags, string[] similarTags){
_acceptedTags = acceptedTags;
_similarTags = similarTags;
}
public string getAcceptedTag(){
return _acceptedTags;
}
public string[] getSimilarTags(){
return _similarTags;
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace HackerRank_HomeCode
{
public class SockMerchant
{
public void FindNoOfMatchingPairs()
{
int[] ar = Array.ConvertAll(Console.ReadLine().Split(' '), arTemp => Convert.ToInt32(arTemp));
var pairsFound = 0;
var stocksDict = new Dictionary<int, int>();
foreach(var sock in ar)
{
if(stocksDict.ContainsKey(sock))
{
pairsFound++;
stocksDict.Remove(sock);
}
else
{
stocksDict.Add(sock,1);
}
}
Console.WriteLine(pairsFound);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UrTLibrary.Shaders.Directives.ShaderDirectives.General
{
public class NoPicMip : GeneralDirective
{
public override string ToString()
{
return "noPicMip";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FictionFantasyServer.Data.Entities.Base;
using Microsoft.EntityFrameworkCore;
namespace FictionFantasyServer.Data
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
private readonly FFDbContext _dbContext;
public Repository(FFDbContext dbContext)
{
_dbContext = dbContext;
}
public void Add(TEntity entity)
{
_dbContext.Set<TEntity>().Add(entity);
}
public void AddRange(IEnumerable<TEntity> entities)
{
_dbContext.Set<TEntity>().AddRange(entities);
}
public void Delete(TEntity entity)
{
_dbContext.Set<TEntity>().Remove(entity);
}
public void DeleteRange(IEnumerable<TEntity> entities)
{
_dbContext.Set<TEntity>().RemoveRange(entities);
}
public IQueryable<TEntity> GetAll()
{
return _dbContext.Set<TEntity>();
}
public Task<TEntity> GetById(Guid id)
{
return _dbContext.Set<TEntity>().FindAsync(id);
}
public void Update(TEntity entity)
{
_dbContext.Set<TEntity>().Update(entity);
}
public void UpdateRange(IEnumerable<TEntity> entities)
{
_dbContext.Set<TEntity>().UpdateRange(entities);
}
}
} |
using SnakeGameConsole.Models;
namespace SnakeGameConsole.Interfaces
{
public interface IBoardService
{
void AddFood(Game game);
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Luxand;
namespace LogUrFace
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
FSDK.ActivateLibrary("bSB3NdbTnv/0eW/uhypSe6hDMtjZ76Sisw5NwcN+0sfahxOtoUW22el54e/M6cSG5/xsdVIorPgugbTIfoIIn7ltyw1QMSleNebVx/Xe8aRA8bP+aVDybjoWdW/0rDP9Pv7yqBzNXyuwjgsVhPB53VGP8oTirTSUP7PTzSwOEe0=");
FSDK.InitializeLibrary();
FSDKCam.InitializeCapturing();
System.IO.Directory.CreateDirectory("Faces");
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class singletonMenu : MonoBehaviour
{
private static singletonMenu _instance = null;
public Button btPlay;
public static singletonMenu Instance
{
get
{
return _instance;
}
}
void Awake()
{
if (_instance == null)
{
_instance = this;
}
}
private void OnDestroy()
{
if (_instance == this)
{
_instance = null;
}
}
// Use this for initialization
void Start()
{
btPlay.onClick.AddListener(playGame);
}
public void playGame()
{
Singleton.Instance.SceneDestName = "gp0";
Singleton.Instance.sceneAsync();
}
// Update is called once per frame
void Update()
{
}
public void webRanking()
{
//a implementar
}
public void webAchiev()
{
//a implementar
}
public void muteAudio()
{
//a implementar
}
public void changeLanguage()
{
//a implementar
}
} |
namespace HandyControlDemo.UserControl
{
public partial class RepeatButtonDemoCtl
{
public RepeatButtonDemoCtl()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Device
{
public enum InternalDeviceMode
{
SM_CONVERTIBLESLATEMODE = 0x2003,
SM_SYSTEMDOCKED = 0x2004
}
}
|
namespace MusicStoreSystem.Api.Controllers
{
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using Data;
using MusicStoreSystem.Models;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ArtistsController : ApiController
{
private MusicStoreSystemDbContext db = new MusicStoreSystemDbContext();
// GET: api/Artists
public IQueryable<Artist> GetArtists()
{
return db.Artists;
}
// GET: api/Artists/5
[ResponseType(typeof(Artist))]
public IHttpActionResult GetArtist(int id)
{
Artist artist = db.Artists.Find(id);
if (artist == null)
{
return NotFound();
}
return Ok(artist);
}
// PUT: api/Artists/5
[ResponseType(typeof(void))]
public IHttpActionResult PutArtist(int id, Artist artist)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != artist.Id)
{
return BadRequest();
}
db.Entry(artist).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ArtistExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Artists
[ResponseType(typeof(Artist))]
public IHttpActionResult PostArtist(Artist artist)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Artists.Add(artist);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = artist.Id }, artist);
}
// DELETE: api/Artists/5
[ResponseType(typeof(Artist))]
public IHttpActionResult DeleteArtist(int id)
{
Artist artist = db.Artists.Find(id);
if (artist == null)
{
return NotFound();
}
db.Artists.Remove(artist);
db.SaveChanges();
return Ok(artist);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ArtistExists(int id)
{
return db.Artists.Count(e => e.Id == id) > 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airfield_Simulator.Core.Models
{
public class GeoPoint
{
public double X { get; set; }
public double Y { get; set; }
public GeoPoint(double x, double y)
{
X = x;
Y = y;
}
public double GetDistanceTo(GeoPoint point)
{
return GetDistance(this, point);
}
public double GetHeadingTo(GeoPoint point)
{
return GetHeading(this, point);
}
public static double GetDistance(GeoPoint pointA, GeoPoint pointB)
{
return Math.Round(Math.Sqrt(Math.Pow((pointB.X - pointA.X), 2)+ Math.Pow((pointB.Y - pointA.Y), 2)), 1);
}
public static double GetHeading(GeoPoint pointA, GeoPoint pointB)
{
var a = pointA.X - pointB.X;
var b = pointA.Y - pointB.Y;
var c = Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2));
var q = Math.Pow(a, 2) / c;
var p = c - q;
var h = Math.Sqrt(p * q);
var alpha = Math.Atan(h / p);
var degrees = alpha * (360 / (2 * Math.PI));
if (pointA.X < pointB.X && pointA.Y < pointB.Y)
return degrees;
else if (pointA.X > pointB.X && pointA.Y < pointB.Y)
return 360 - degrees;
else if (pointA.X > pointB.X && pointA.Y > pointB.Y)
return 180 + degrees;
else
return 180 - degrees;
}
}
}
|
using PDV.DAO.Atributos;
namespace PDV.DAO.Entidades
{
public class EmailEmitente
{
[CampoTabela("IDEMAILEMITENTE")]
[MaxLength(18)]
public decimal IDEmailEmitente { get; set; } = -1;
[CampoTabela("IDEMITENTE")]
[MaxLength(18)]
public decimal IDEmitente { get; set; }
[CampoTabela("AUTORIZARENVIAREMAIL")]
[MaxLength(1)]
public decimal AutorizarEnviarEmail { get; set; }
[CampoTabela("AUTORIZARASSUNTO")]
[MaxLength(150)]
public string AutorizarAssunto { get; set; }
[CampoTabela("AUTORIZARMENSAGEM")]
[MaxLength(1000)]
public string AutorizarMensagem { get; set; }
[CampoTabela("CANCELARENVIAREMAIL")]
[MaxLength(1)]
public decimal CancelarEnviarEmail { get; set; }
[CampoTabela("CANCELARASSUNTO")]
[MaxLength(150)]
public string CancelarAssunto { get; set; }
[CampoTabela("CANCELARMENSAGEM")]
[MaxLength(1000)]
public string CancelarMensagem { get; set; }
public EmailEmitente()
{
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="CSharpCodegenKeyCodeWriter.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using Mlos.SettingsSystem.Attributes;
namespace Mlos.SettingsSystem.CodeGen.CodeWriters.CSharpTypesCodeWriters
{
/// <summary>
/// Code writer class for CSharp primary key.
/// </summary>
/// <remarks>
/// Writes all properties.
/// </remarks>
internal class CSharpCodegenKeyCodeWriter : CSharpCodeWriter
{
/// <inheritdoc />
public override bool Accept(Type sourceType) => sourceType.IsCodegenType() && sourceType.HasPrimaryKey();
/// <inheritdoc />
public override void WriteOpenTypeNamespace(string @namespace)
{
WriteLine($"namespace {@namespace}");
WriteLine("{");
++IndentationLevel;
}
/// <inheritdoc />
public override void WriteCloseTypeNamespace(string @namespace)
{
--IndentationLevel;
WriteLine($"}} // end namespace {@namespace}");
WriteLine();
}
/// <inheritdoc />
public override void BeginVisitType(Type sourceType)
{
WriteOpenTypeDeclaration(sourceType);
WriteBlock($@"
/// <summary>
/// Lookup primary key type definition for: {sourceType.Name}.
/// </summary>
public partial struct CodegenKey
{{");
IndentationLevel++;
WriteLine();
}
/// <inheritdoc/>
public override void EndVisitType(Type sourceType)
{
IndentationLevel--;
WriteLine("}");
WriteCloseTypeDeclaration(sourceType);
}
/// <inheritdoc />
public override void WriteComments(CodeComment codeComment)
{
foreach (string enumLineComment in codeComment.Summary.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
{
string lineComment = $" {enumLineComment.Trim()}";
WriteLine($"//{lineComment.TrimEnd()}");
}
WriteLine("//");
}
/// <inheritdoc />
public override void VisitField(CppField cppField)
{
if (!cppField.FieldInfo.IsPrimaryKey())
{
// This field is not a primary key, ignore it.
//
return;
}
string fieldName = cppField.FieldInfo.Name;
Type fieldType = cppField.FieldInfo.FieldType;
string fieldTypeName = $"global::{fieldType.FullName}";
WriteLine($"public {fieldTypeName} {fieldName};");
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using Logs.Models;
namespace Logs.Data.Mappings
{
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
// Properties
this.Property(t => t.Description)
.HasMaxLength(500);
// Table & Column Mappings
this.ToTable("AspNetUsers");
this.Property(t => t.LogId).HasColumnName("LogId");
this.Property(t => t.GenderType).HasColumnName("GenderType");
this.Property(t => t.Weight).HasColumnName("Weight");
this.Property(t => t.Age).HasColumnName("Age");
this.Property(t => t.BodyFatPercent).HasColumnName("BodyFatPercent");
this.Property(t => t.Height).HasColumnName("Height");
this.Property(t => t.Description).HasColumnName("Description");
this.Property(t => t.ProfileImageUrl).HasColumnName("ProfileImageUrl");
// Relationships
this.HasOptional(t => t.TrainingLog)
.WithMany(t => t.Users)
.HasForeignKey(d => d.LogId);
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
namespace DomaciRozpocet {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
Records allRecords = new Records();
ICollectionView defaultView;
Predicate<object> dvFilter = item => true;
public MainWindow() {
InitializeComponent();
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("cs-CZ");
allRecords.LoadFromCSV();
defaultView = CollectionViewSource.GetDefaultView(allRecords);
DGRecords.ItemsSource = defaultView;
SetTotalLabel(allRecords.TotalAmount(dvFilter));
}
/// <summary>
/// When this button is pressed, a selected record or multiple records get deleted
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDelete_Click(object sender, RoutedEventArgs e) {
if (DGRecords.SelectedItems.Count != 0) {
if (MessageBox.Show("Opravdu chcete vymazat vybrané záznamy?", "Smazat", MessageBoxButton.YesNo) == MessageBoxResult.Yes) {
foreach (Record item in DGRecords.SelectedItems)
allRecords.Remove((Record)item);
if (!allRecords.SaveToCSV())
MessageBox.Show("Chyba při zápisu do souboru");
defaultView.Refresh();
SetTotalLabel(allRecords.TotalAmount(dvFilter));
}
}
}
/// <summary>
/// When this button is pressed, it opens a new dialog window where the user can enter the info about a new record
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, RoutedEventArgs e) {
var addWindow = new AddWindow();
addWindow.Owner = this;
if ((bool)addWindow.ShowDialog()) {
allRecords.Add(new Record(addWindow.PersonText, (DateTime)addWindow.Date, addWindow.ReasonText, (decimal)addWindow.Amount));
if (!allRecords.AppendLastToCSV())
MessageBox.Show("Chyba při zápisu do souboru");
defaultView.Refresh();
SetTotalLabel(allRecords.TotalAmount(dvFilter));
}
}
/// <summary>
/// Deselecting records after click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DGRecords_MouseDown(object sender, MouseButtonEventArgs e) {
(sender as DataGrid).SelectedItem = null;
}
/// <summary>
/// Clicking this button opens a new dialog window where the user can set the properties for filtering
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFilter_Click(object sender, RoutedEventArgs e) {
var filterWindow = new FilterWindow();
filterWindow.Owner = this;
if ((bool)filterWindow.ShowDialog()) {
//Combining predicates to allow for multiple filters
Predicate<object> pred = defaultView.Filter;
if (pred == null) {
dvFilter = item => filterWindow.FilterPredicate(item);
}
else {
dvFilter = item => pred(item) && filterWindow.FilterPredicate(item);
}
defaultView.Filter = dvFilter;
defaultView.Refresh();
SetTotalLabel(allRecords.TotalAmount(dvFilter));
}
}
/// <summary>
/// Clicking removes all filters
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRemoveFilter_Click(object sender, RoutedEventArgs e) {
dvFilter = item => true;
defaultView.Filter = null;
defaultView.Refresh();
SetTotalLabel(allRecords.TotalAmount(dvFilter));
}
/// <summary>
/// Clicking exports filtered datagrid into Exported.csv file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExport_Click(object sender, RoutedEventArgs e) {
if (allRecords.SaveToCSV(dvFilter, "Exported.csv"))
MessageBox.Show("Úspěšně exportováno");
else
MessageBox.Show("Při ukládání souboru došlo k chybě");
}
/// <summary>
/// Setting the value and colour of the 'Celkem' (lblTotal) label
/// </summary>
/// <param name="amount"></param>
private void SetTotalLabel(decimal amount) {
lblTotal.Content = amount.ToString("C", CultureInfo.CurrentCulture);
//green for total amount > 0
if (amount > 0) {
lblTotal.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00b026"));
}
//red for total < 0
else if (amount < 0) {
lblTotal.Foreground = Brushes.Red;
}
//black for amount == 0
else
lblTotal.Foreground = Brushes.Black;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
public enum EnemyType
{
Pink, Black
}
}
|
/* *********************************************************************** *
* File : AddSiteProcessor.cs Part of Sitecore *
* Version: 2.1.0 www.sitecore.net *
* *
* *
* Purpose: Represents item:added event handler *
* *
* Bugs : None known. *
* *
* Status : Published. *
* *
* Copyright (C) 1999-2007 by Sitecore A/S. All rights reserved. *
* *
* This work is the property of: *
* *
* Sitecore A/S *
* Meldahlsgade 5, 4. *
* 1613 Copenhagen V. *
* Denmark *
* *
* This is a Sitecore published work under Sitecore's *
* shared source license. *
* *
* *********************************************************************** */
namespace Sitecore.Sites
{
using System;
using System.Collections.Generic;
using Configuration;
using Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Events;
using Sitecore.Shell.Framework;
/// <summary>
/// Defines the add site processor class.
/// </summary>
public class AddSiteProcessor
{
/// <summary>
/// Called when the site has added.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public void OnSiteAdded(object obj, EventArgs eventArgs)
{
var item = Event.ExtractParameter(eventArgs, 0) as Item;
if (item == null || item.Parent == null || item.Parent.Name != "Sites")
{
return;
}
if (item.TemplateName != MultiSitesManager.SiteDefinitionTemplateName && item.TemplateName != MultiSitesManager.SiteReferenceTemplateName)
{
return;
}
Items.MoveLast(new[] { item });
MultiSitesManager.ArrangeSitesContext();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TableManageData;
namespace TableManagerData
{
public interface IOrdersRepository
{
/// <summary>
/// Adds passed order to a database
/// </summary>
/// <param name="order">Order to be added</param>
void AddOrder(Order order);
/// <summary>
/// Submits update to an existing order
/// </summary>
/// <param name="order">Updated order</param>
void UpdateOrder(Order orderNew, Order orderOld);
/// <summary>
/// Gets information about available dishes from a database
/// </summary>
/// <returns>Untracked dish instances with id, name, price and cost</returns>
IEnumerable<Dish> GetDishes();
/// <summary>
/// Returns active orders for specified table from a database
/// </summary>
/// <param name="tablesId">Id of the table to look up active orders for</param>
/// <returns>Untracked collection of orders for specified table</returns>
IEnumerable<Order> GetActiveOrders(int tablesId);
/// <summary>
/// Completes an order
/// </summary>
/// <param name="orderId">Id of the order to be completed</param>
void OrderComplete(int orderId);
/// <summary>
/// Canceles an order, which was added, but not completed
/// </summary>
/// <param name="orderId"></param>
void CancelOrder(int orderId);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using UnityEngine.UI;
public class ControleAnim : MonoBehaviour {
Animator animator;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision col)
{
if (col.gameObject.name == "Wolf White Magic") {
animator.SetTrigger("todance");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InfoPole.Core.Models
{
public class OperationResult
{
public long Number { get; set; }
public IEnumerable<string> Messages { get; set; }
public bool IsSuccess { get; set; }
public TimeSpan? ElapsedTime { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace Dashboard.API.Domain.Models
{
public class UserSubscriptionModel
{
public List<ClientAndUserServices> Subscriptions { get; set; } = new List<ClientAndUserServices>();
public class ClientAndUserServices
{
public Guid ClientId { get; set; }
public string Name { get; set; }
public List<Service> Services { get; set; } = new List<Service>();
}
}
} |
namespace WikiMusic.Services.Controllers
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using AutoMapper.QueryableExtensions;
using Data;
using Models;
using WebGrease.Css.Extensions;
using WikiMusic.Models;
[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api/artists")]
public class ArtistsController : ApiController
{
private IWikiMusicData data;
public ArtistsController()
{
this.data = new WikiMusicData();
}
public IHttpActionResult Get()
{
var artists = this.data.Artists.All().ToList();
return this.Ok(artists);
}
public IHttpActionResult GetById(int id)
{
return this.Ok(this.data.Artists.SearchFor(x => x.ID == id).First());
}
public IHttpActionResult Post([FromBody] ArtistRequestModel artist)
{
this.data.Artists.Add(new Artist
{
Name = artist.Name,
Country = artist.Country,
BirthDate = artist.BirthDate,
ImgLink = artist.ImgLink
});
this.data.SaveChanges();
return this.Ok(artist.Name);
}
public IHttpActionResult Put([FromBody] UpdateArtistByIdModel data)
{
data.Updates.Id = data.Id;
this.data.Artists
.SearchFor(x => x.ID == data.Id)
.ToList()
.ForEach(y =>
{
y.Name = data.Updates.Name;
y.BirthDate = data.Updates.BirthDate;
y.Country = data.Updates.Country;
y.ImgLink = data.Updates.ImgLink;
this.data.Artists.Update(y);
});
this.data.SaveChanges();
return this.Ok();
}
[HttpDelete]
public IHttpActionResult Delete([FromBody] int id)
{
var artist = this.data.Artists.SearchFor(x => x.ID == id).FirstOrDefault();
this.data.Artists.Delete(artist);
this.data.SaveChanges();
return this.Ok();
}
}
} |
using System;
namespace StringOfObjects
{
class Program
{
public static void Main(string[] args)
{
Enemy[] enemies = //string of class Enemy
{
new Enemy("Monster"), //object of class Enemy
new Enemy("Dragon") //another object
};
foreach(Enemy enemy in enemies) //variable enemy of data-type Enemy, enemies is the instance
{
enemy.Attack();
}
}
}
class Enemy
{
private string name;
public Enemy(string name) //constructor
{
this.name = name;
}
public void Attack()
{
Console.WriteLine(name + " attacked.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary.Model;
namespace ClassLibrary.ViewModels
{
public class VisitaModel
{
public int idVisita { get; set; }
public string data { get; set; }
public string descrição { get; set; }
public string horaInicio { get; set; }
public int idPercurso { get; set; }
public int idUser { get; set; }
public VisitaModel(){ }
public VisitaModel(Visita visita)
{
this.idVisita = idVisita;
this.data = data;
this.descrição = descrição;
this.horaInicio = horaInicio;
this.idPercurso = idPercurso;
this.idUser = idUser;
}
}
}
|
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TNBase.External.DataImport;
namespace TNBase.Forms
{
public partial class FormDataImportReport : Form
{
private ImportResult result;
public FormDataImportReport(ImportResult result)
{
InitializeComponent();
this.result = result;
}
private void FormDataImportReport_Load(object sender, System.EventArgs e)
{
var succededCount = result.Records.Count(x => !x.HasError);
var failedCount = result.Records.Count(x => x.HasError);
if (succededCount == 0)
{
ImportStatusLabel.Text = "Import has failed";
ImportStatusLabel.ForeColor = Color.IndianRed;
}
else if (failedCount > 0)
{
ImportStatusLabel.Text = "Import completed with errors";
ImportStatusLabel.ForeColor = Color.Chocolate;
}
else
{
ImportStatusLabel.Text = "Import completed successfully";
ImportStatusLabel.ForeColor = Color.Green;
}
ImportedCountLabel.Text = succededCount.ToString();
FailedCountLabel.Text = failedCount.ToString();
TotalCountLabel.Text = result.Records.Count().ToString();
GetFailedRecordsButton.Enabled = failedCount > 0;
foreach (var record in result.Records.Where(x => x.HasError).ToList())
{
var item = new ListViewItem(new[] { record.Row.ToString(), record.Error.ErrorMessage });
ErrorListView.Items.Add(item);
}
}
private void GetFailedRecordsButton_Click(object sender, System.EventArgs e)
{
var dialog = new SaveFileDialog
{
Filter = "CSV Text|*.csv",
Title = "Save Failed Listeners Records",
FileName = "Failed Listeners Records.csv"
};
dialog.ShowDialog();
if (!string.IsNullOrWhiteSpace(dialog.FileName))
{
var builder = new StringBuilder();
builder.AppendLine(result.RawHeader);
foreach (var record in result.Records.Where(x => x.HasError).ToList())
{
builder.Append(record.Error.RawRecord);
}
File.WriteAllText(dialog.FileName, builder.ToString(), Encoding.UTF8);
}
}
}
}
|
using System;
namespace PositionOfMiddleElement
{
class Program
{
static void Main(string[] args)
{
//double[] threeNumbers = { 2, 3, 1 };
double[] threeNumbers = { 10, 14, 5 };
Console.WriteLine("The index of the middle number is {0}", Gimme(threeNumbers));
}
//Works only for arrays with excactly three values
//Doesn't check if there are duplicate numbers
public static int Gimme(double[] inputArray)
{
double[] unSortedInputArray = new double[3];
Array.Copy(inputArray, unSortedInputArray, 3);
Array.Sort(inputArray);
double middleNumber = inputArray[1];
int indexOfMiddleValue = Array.IndexOf(unSortedInputArray, middleNumber);
return indexOfMiddleValue;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Grades
{
public class CalculatingEventArgs : EventArgs
{
public float oldAverage;
}
public class AddGradeEventArgs : EventArgs
{
public float Grade;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NoteAttractor : NoteInteractable
{
[Range(0f, 100f)]
public float scale;
private List<Projectile> projectiles;
private bool canInteract;
private void Awake()
{
col = GetComponent<Collider2D>();
projectiles = new List<Projectile>();
canInteract = true;
}
private void Update()
{
for (int i = 0; i < projectiles.Count; i++)
{
if (projectiles[i] != null)
{
Vector2 towardsCenter = ((Vector2)transform.position - projectiles[i].Position).OfMagnitude(scale * Time.unscaledDeltaTime);
projectiles[i].Velocity = projectiles[i].Velocity + towardsCenter;
}
else
{
projectiles.RemoveAt(i);
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
Projectile proj = collision.GetComponent<Projectile>();
if (proj != null && projectiles.Contains(proj))
{
projectiles.Remove(proj);
}
}
public override void EnableCollider(bool b)
{
col.enabled = b;
}
public override Vector2 GetReturnDirection(Vector2 inDirection)
{
return Vector2.zero;
}
public override Vector2 GetObjectHitPoint(RaycastHit2D hit)
{
return hit.point;
}
public override void OnProjectileHit(Projectile proj)
{
projectiles.Add(proj);
proj.DistanceLeft = proj.DistanceLeft * 5;
}
public override bool CanInteract()
{
return canInteract;
}
}
|
using SGA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SGA.Context;
using System.Net;
using System.Data.Entity;
namespace SGA.Controllers
{
public class VoluntarioController : Controller
{
private Context.AppContext db = new Context.AppContext();
public ActionResult Index()
{
return View("Index",db.Voluntarios.ToList().Where(v => v.Status != "D"));
}
[HttpGet]
public ActionResult Create()
{
return View("Create");
}
[HttpPost]
public ActionResult Create(Voluntario aula)
{
aula.DtCadastro = DateTime.Now;
aula.Status = "A";
if(ModelState.IsValid)
{
db.Voluntarios.Add(aula);
db.SaveChanges();
}
return View("Index",db.Voluntarios.ToList());
}
[HttpGet]
public ActionResult Edit(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var registro = db.Voluntarios.Find(id);
return View(registro);
}
[HttpPost]
public ActionResult Edit(Voluntario model)
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index","Voluntario");
}
[HttpGet]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var registro = db.Voluntarios.Find(id);
return View(registro);
}
[HttpPost,ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
var registro = db.Voluntarios.Find(id);
if(registro != null)
{
registro.Status = "D";
db.Entry(registro).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index", "Voluntario");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
} |
using System;
using System.Linq;
using System.Text;
using System.Net.Http.Headers;
namespace Microsoft.DataStudio.WebExtensions
{
public static class HttpRequestHeadersExtensions
{
public static string ToStringWithoutPII(this HttpRequestHeaders headers)
{
var requestHeadersText = new StringBuilder();
foreach (var header in headers)
{
if (!header.Key.Equals("Authorization"))
{
requestHeadersText.Append(header.Key + ": " + string.Join(" ", header.Value.ToArray()) + Environment.NewLine);
}
}
return requestHeadersText.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace FillablePdfExample.Models
{
public class Test1FormModel
{
[Display(Name = "Given Name")]
public string GivenName { get; set; }
[Display(Name = "Family Name")]
public string FamilyName { get; set; }
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
[Display(Name = "House Number")]
public string HouseNumber { get; set; }
[Display(Name = "Postcode")]
public string Postcode { get; set; }
[Display(Name = "City")]
public string City { get; set; }
[Display(Name = "Height")]
public string Height { get; set; }
[Display(Name = "Country")]
public string Country { get; set; }
[Display(Name = "Gender")]
public string Gender { get; set; }
[Display(Name = "Driving License")]
public bool DrivingLicense { get; set; }
[Display(Name = "Deutsch")]
public bool Lang1 { get; set; }
[Display(Name = "English")]
public bool Lang2 { get; set; }
[Display(Name = "Français")]
public bool Lang3 { get; set; }
[Display(Name = "Esperanto")]
public bool Lang4 { get; set; }
[Display(Name = "Latin")]
public bool Lang5 { get; set; }
[Display(Name = "Favourite colour")]
public string FavColor { get; set; }
}
} |
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System.Drawing;
using Framework.Metadata;
using Framework.Utils;
namespace Framework.Entity
{
/// <summary>
/// Entity representing DB image library element.
/// </summary>
public class CxImageLibraryEntity : CxBaseEntity
{
//----------------------------------------------------------------------------
public const string IMAGE_WIDTH_ATTR = "IMAGEWIDTH";
public const string IMAGE_HEIGHT_ATTR = "IMAGEHEIGHT";
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="metadata">metadata that describes this entity</param>
public CxImageLibraryEntity(CxEntityUsageMetadata metadata)
: base(metadata)
{
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns image attribute.
/// </summary>
/// <returns>image attribute</returns>
virtual protected CxAttributeMetadata GetImageAttribute()
{
return Metadata.GetFirstDbFileAttribute();
}
//----------------------------------------------------------------------------
/// <summary>
/// Validates entity.
/// </summary>
override public void Validate()
{
base.Validate();
CxAttributeMetadata imageAttr = GetImageAttribute();
if (imageAttr != null)
{
object imageValue = this[imageAttr.Id];
if (!(imageValue is byte[]))
{
throw new ExValidationException(
Metadata.Holder.GetErr("Image is empty or invalid."), imageAttr.Id);
}
CxBlobFile bFile = new CxBlobFile();
bFile.LoadFromDbField((byte[]) imageValue);
if (bFile.IsEmpty)
{
throw new ExValidationException(
Metadata.Holder.GetErr("Image could not be empty."), imageAttr.Id);
}
CxAttributeMetadata nameAttr = Metadata.NameAttribute;
if (nameAttr != null && nameAttr.ReadOnly)
{
if (CxUtils.NotEmpty(bFile.FileName))
{
this[nameAttr.Id] = bFile.FileName;
}
else if (CxUtils.NotEmpty(this[nameAttr.Id]))
{
bFile.Header.FileName = CxUtils.ToString(this[nameAttr.Id]);
}
}
CxAttributeMetadata widthAttr = Metadata.GetAttribute(IMAGE_WIDTH_ATTR);
CxAttributeMetadata heightAttr = Metadata.GetAttribute(IMAGE_HEIGHT_ATTR);
if (widthAttr != null && heightAttr != null)
{
Size imageSize;
try
{
imageSize = CxImage.GetSize(bFile.Data);
}
catch
{
imageSize = Size.Empty;
}
if (imageSize != Size.Empty)
{
this[widthAttr.Id] = imageSize.Width;
this[heightAttr.Id] = imageSize.Height;
}
else
{
this[widthAttr.Id] = null;
this[heightAttr.Id] = null;
}
}
}
}
//----------------------------------------------------------------------------
}
} |
using System;
using System.Globalization;
namespace EmployeeStorage.Api.Extensions
{
public static class StringExtensions
{
public static bool ToDate(this string value, string[] dateFormat, out DateTime scheduleDate)
{
if (DateTime.TryParseExact(value, dateFormat, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out scheduleDate))
{
return true;
}
return false;
}
}
}
|
/*
* 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>
/// ForumPollResponse
/// </summary>
[DataContract]
public partial class ForumPollResponse : IEquatable<ForumPollResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ForumPollResponse" /> class.
/// </summary>
/// <param name="TopicId">TopicId.</param>
/// <param name="Results">Results.</param>
/// <param name="TotalVotes">TotalVotes.</param>
public ForumPollResponse(long? TopicId = default(long?), List<ForumPollResult> Results = default(List<ForumPollResult>), int? TotalVotes = default(int?))
{
this.TopicId = TopicId;
this.Results = Results;
this.TotalVotes = TotalVotes;
}
/// <summary>
/// Gets or Sets TopicId
/// </summary>
[DataMember(Name="topicId", EmitDefaultValue=false)]
public long? TopicId { get; set; }
/// <summary>
/// Gets or Sets Results
/// </summary>
[DataMember(Name="results", EmitDefaultValue=false)]
public List<ForumPollResult> Results { get; set; }
/// <summary>
/// Gets or Sets TotalVotes
/// </summary>
[DataMember(Name="totalVotes", EmitDefaultValue=false)]
public int? TotalVotes { 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 ForumPollResponse {\n");
sb.Append(" TopicId: ").Append(TopicId).Append("\n");
sb.Append(" Results: ").Append(Results).Append("\n");
sb.Append(" TotalVotes: ").Append(TotalVotes).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 ForumPollResponse);
}
/// <summary>
/// Returns true if ForumPollResponse instances are equal
/// </summary>
/// <param name="input">Instance of ForumPollResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ForumPollResponse input)
{
if (input == null)
return false;
return
(
this.TopicId == input.TopicId ||
(this.TopicId != null &&
this.TopicId.Equals(input.TopicId))
) &&
(
this.Results == input.Results ||
this.Results != null &&
this.Results.SequenceEqual(input.Results)
) &&
(
this.TotalVotes == input.TotalVotes ||
(this.TotalVotes != null &&
this.TotalVotes.Equals(input.TotalVotes))
);
}
/// <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.TopicId != null)
hashCode = hashCode * 59 + this.TopicId.GetHashCode();
if (this.Results != null)
hashCode = hashCode * 59 + this.Results.GetHashCode();
if (this.TotalVotes != null)
hashCode = hashCode * 59 + this.TotalVotes.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 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 Logbog.DataAccess;
using Logbog.Model;
using System.Data.SqlClient;
namespace Kørselslogbog
{
public partial class Form_Chauffør : Form
{
private Chauffør CurrentChauffør;
public Form_Chauffør()
{
InitializeComponent();
}
private void button_Mainmenu_Click(object sender, EventArgs e)
{
Opret Menu = new Opret();
this.Close();
Menu.Show();
}
private void but_Gem_Click(object sender, EventArgs e)
{
try
{
if (IsCustomerNameValid())
{
CurrentChauffør = new Chauffør();
CurrentChauffør.Ch_ID = Int32.Parse(txtCHID.Text);
CurrentChauffør.ForNavn = txtFornavn.Text;
CurrentChauffør.EfterNavn = txtEfternavn.Text;
CurrentChauffør.OpretDato = dateTime_opret.Value;
int result = DataAccessChauffør.Insert(CurrentChauffør);
MessageBox.Show("Antal indsatte rækker er: " + result.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// Storage for IDENTITY values returned from database. /// <summary>
/// Verifies that the customer name text box is not empty.
/// </summary>
private bool IsCustomerNameValid()
{
if (txtCHID.Text == "")
{
MessageBox.Show("Indtast venligst valid ID.");
return false;
}
else if (txtFornavn.Text == "")
{
MessageBox.Show("Indtast venligst ForNavn.");
return false;
}
else if (txtEfternavn.Text == "")
{
MessageBox.Show("Indtast venligst EfterNavn.");
return false;
}
else if (dateTime_opret.Checked == false)
{
MessageBox.Show("Indtast venligst valid dato!");
return false;
}
else
{
return true;
}
}
private void button_vise_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = DataAccessChauffør.Select();
}
private void button_clear_Click(object sender, EventArgs e)
{
txtCHID.Text = "";
txtFornavn.Text = "";
txtEfternavn.Text = "";
}
private void txtCHID_TextChanged(object sender, EventArgs e)
{
}
private void button_slet_Click(object sender, EventArgs e)
{
if (IsCh_IDValid())
{
try
{
int result = DataAccessChauffør.Delete(Int32.Parse(txtCHID.Text));
MessageBox.Show("Number of deleted rows is: " + result.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Fejl: " + ex.Message);
}
}
}
private bool IsCh_IDValid()
{
if (txtCHID.Text == "")
{
MessageBox.Show("Indtast venligst et Nummer.");
return false;
}
else if ((Int32.Parse(txtCHID.Text) < 1))
{
MessageBox.Show("Indtast venligst en valid nummer.");
return false;
}
else
{
return true;
}
}
private void button_rette_Click(object sender, EventArgs e)
{
if (IsChNummerValid())
{
try
{
int result= DataAccessChauffør.Update(Int32.Parse(txtCHID.Text), txtFornavn.Text, txtEfternavn.Text,dateTime_opret.Value);
if (result > 0)
{
MessageBox.Show("Antal række påvirket: " + result.ToString());
}
else { MessageBox.Show("Kan ikke finde ID."); }
}
catch
{
MessageBox.Show("Kan ikke redigere chauffør oplysninger.");
}
}
}
private bool IsChNummerValid()
{
if (txtCHID.Text == "")
{
MessageBox.Show("Indtast venligst et Kunde Nummer.");
return false;
}
else if (Int32.Parse(txtCHID.Text) < 0)
{
MessageBox.Show("Indtast venligst en valid nummer.");
return false;
}
else
{
return true;
}
}
}
}
|
using System.Collections.Concurrent;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Dtos;
namespace Umbraco.Core.Persistence.Mappers
{
[MapperFor(typeof(AuditItem))]
[MapperFor(typeof(IAuditItem))]
public sealed class AuditItemMapper : BaseMapper
{
private static readonly ConcurrentDictionary<string, DtoMapModel> PropertyInfoCacheInstance = new ConcurrentDictionary<string, DtoMapModel>();
internal override ConcurrentDictionary<string, DtoMapModel> PropertyInfoCache => PropertyInfoCacheInstance;
protected override void BuildMap()
{
CacheMap<AuditItem, LogDto>(src => src.Id, dto => dto.NodeId);
CacheMap<AuditItem, LogDto>(src => src.CreateDate, dto => dto.Datestamp);
CacheMap<AuditItem, LogDto>(src => src.UserId, dto => dto.UserId);
CacheMap<AuditItem, LogDto>(src => src.AuditType, dto => dto.Header);
CacheMap<AuditItem, LogDto>(src => src.Comment, dto => dto.Comment);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
using MoviesApp.Data.Models;
using MoviesApp.Data.Repositories;
using MoviesApp.Models;
namespace MoviesApp.Controllers
{
public class PeopleController : Controller
{
GenericRepository<Person> people = new GenericRepository<Person>();
GenericRepository<Studio> studios = new GenericRepository<Studio>();
public ActionResult Index()
{
return this.View(new List<PersonViewModel>());
}
public ActionResult GetAll()
{
var allPeople = people.All().ProjectTo<PersonViewModel>().ToList();
Thread.Sleep(2222);
return this.PartialView("_AllPeople", allPeople);
}
public ActionResult Create()
{
var newPerson = new PersonViewModel()
{
AllStudios = studios.All().Select(x => x.Name).ToList()
};
return PartialView("_Create", newPerson);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonViewModel person)
{
if (ModelState.IsValid)
{
var studio = studios.All().FirstOrDefault(x => x.Name == person.StudioName);
people.Add(new Person()
{
Name = person.Name,
Age = person.Age,
Studio = studio
});
people.SaveChanges();
return Content("Done!");
}
person.AllStudios = studios.All().Select(x => x.Name).ToList();
return PartialView("_Create", person);
}
public ActionResult Delete()
{
return PartialView("_Delete");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
var idInt = int.Parse(id);
people.Delete(idInt);
people.SaveChanges();
return Content("Done!");
}
public ActionResult Edit(string id)
{
var idInt = int.Parse(id);
var person = people.All().Where(s => s.Id == idInt).ProjectTo<PersonViewModel>().FirstOrDefault();
person.AllStudios = studios.All().Select(x => x.Name).ToList();
return PartialView("_Edit", person);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonViewModel person)
{
var studio = studios.All().FirstOrDefault(x => x.Name == person.StudioName);
if (ModelState.IsValid)
{
var personDb = people.GetById(person.Id);
personDb.Name = person.Name;
personDb.Age = person.Age;
personDb.Studio = studio;
people.SaveChanges();
return Content("Done!");
}
return PartialView("_Edit", person);
}
}
} |
using UnityEngine;
using System.Collections;
public class ActorController : MonoBehaviour
{
public Puppet puppet;
public LayerMask mask;
Vector3 goal;
[System.Serializable]
public class Puppet
{
public GameObject head;
public GameObject body;
public GameObject leftHand;
public GameObject rightHand;
}
void Start()
{
goal = transform.position;
if(xa.emptyObj == null) {xa.emptyObj = new GameObject("emptyObj"); }
}
void Update()
{
//Get goal
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 999, mask))
{
goal = hit.point;
}
}
MoveToGoal();
}
Vector3 oldAngles;
Vector3 oldAngles2;
void MoveToGoal()
{
oldAngles = transform.localEulerAngles;
transform.localEulerAngles = oldAngles2;
if (Vector3.Distance(transform.position, goal) > 0.3f)
{
goal = new Vector3(goal.x,goal.y,0);
//Slow turn at a flat rate
//transform.rotation = Setup.SlowTurn(transform.position, transform.rotation, goal, 555, new Vector3(0,0,1));
//Vector3 lookPos = goal - transform.position;
//lookPos.y = 0;
// Quaternion rotation = Quaternion.LookRotation(lookPos);
//transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 0.5f);
//Quaternion rotation = Quaternion.LookRotation(goal - transform.position, transform.TransformDirection(Vector3.up));
//transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
transform.LookAt(goal);
transform.Translate(new Vector3(-1 * Time.deltaTime, 0, 0));
}
oldAngles2 = transform.localEulerAngles;
transform.localEulerAngles = oldAngles;
}
}
|
using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
namespace Game.Online.Users
{
public class Avatar : MonoBehaviour
{
public Image UserAvatar;
public static Sprite GetTextureFromServer(byte[] buffer)
{
var texture = new Texture2D(54, 54);
texture.LoadImage(buffer, false);
return Sprite.Create(texture, new Rect(0,0,texture.width, texture.height), Vector2.zero);
}
}
} |
namespace CloneDeploy_Entities.DTOs
{
public class ServerRoleDTO
{
public string Identifier { get; set; }
public bool IsImageServer { get; set; }
public bool IsMulticastServer { get; set; }
public bool IsTftpServer { get; set; }
public string OperationMode { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FoodDelivery.Models
{
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public Address RestaurantAddress { get; set; }
public List<Dish> Menu { get; set; }
}
}
|
// Accord Neural Net Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Neuro
{
using Accord.Math.Random;
/// <summary>
/// Gaussian weight initialization.
/// </summary>
///
public class GaussianWeights
{
private ActivationNetwork network;
private GaussianGenerator random;
/// <summary>
/// Gets ors sets whether the initialization
/// should update neurons thresholds (biases)
/// </summary>
///
public bool UpdateThresholds { get; set; }
/// <summary>
/// Constructs a new Gaussian Weight initialization.
/// </summary>
///
/// <param name="network">The activation network whose weights will be initialized.</param>
/// <param name="stdDev">The standard deviation to be used. Common values lie in the 0.001-
/// 0.1 range. Default is 0.1.</param>
///
public GaussianWeights(ActivationNetwork network, double stdDev = 0.1)
{
this.network = network;
this.random = new GaussianGenerator(0f, (float)stdDev, Accord.Math.Random.Generator.Random.Next());
this.UpdateThresholds = false;
}
/// <summary>
/// Randomizes (initializes) the weights of
/// the network using a Gaussian distribution.
/// </summary>
///
public void Randomize()
{
foreach (ActivationLayer layer in network.Layers)
{
foreach (ActivationNeuron neuron in layer.Neurons)
{
for (int i = 0; i < neuron.Weights.Length; i++)
neuron.Weights[i] = random.Next();
if (UpdateThresholds)
neuron.Threshold = random.Next();
}
}
}
/// <summary>
/// Randomizes (initializes) the weights of
/// the network using a Gaussian distribution.
/// </summary>
///
public void Randomize(int layerIndex)
{
var layer = network.Layers[layerIndex] as ActivationLayer;
foreach (ActivationNeuron neuron in layer.Neurons)
{
for (int i = 0; i < neuron.Weights.Length; i++)
neuron.Weights[i] = random.Next();
if (UpdateThresholds)
neuron.Threshold = random.Next();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
// Write a program that reads a text file and inserts line numbers in front of
// each of its lines. The result should be written to another text file.
class InsertLineNumbers
{
static void Main(string[] args)
{
//you can find the the .txt files in the directory of the project
InsertLinesNumbers(@"..\..\input.txt", @"..\..\newFile.txt");
ReadAndPrintTextFile(@"..\..\newFile.txt");
}
static void InsertLinesNumbers(string filePath, string newFilePath)
{
StreamReader reader = new StreamReader(filePath);
StreamWriter writer = new StreamWriter(newFilePath);
int readerLineNum = 0;
string readerLine = reader.ReadLine();
while (readerLine != null)
{
writer.WriteLine((readerLineNum + 1) + ": " + readerLine);
readerLineNum++;
readerLine = reader.ReadLine();
}
reader.Close();
writer.Close();
}
static void ReadAndPrintTextFile(string filePath)
{
StreamReader reader = new StreamReader(filePath);
using (reader)
{
int lineNum = 0;
string line = reader.ReadLine();
while (line != null)
{
Console.WriteLine(line);
lineNum++;
line = reader.ReadLine();
}
}
}
}
|
namespace Yeasca.Requete
{
public interface IDetailConstatMessage : IMessageRequete
{
string IdConstat { get; set; }
}
}
|
namespace ChatAppUtils.Configuration
{
public interface IConfigurationProvider
{
string GetConnectionString(string key);
string GetDefaultConnection();
string GetAppSetting(string key);
object GetSection(string key);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IsADamager : MonoBehaviour {
private IsAMecha _mecha;
public MecaAnimationHandler mecaAnimationHandler;
public IsAMecha mechaMainPart
{
get { return _mecha; }
set { if (_mecha == null)_mecha = value; } // adds a little bit of protection
}
public int myAttack;
protected bool _hit;
public bool hit
{
get { return _hit; }
}
// Use this for initialization
void Start () {
if (mecaAnimationHandler != null)
{
}
else
{
Debug.Log("mecaAnimationHandler is null at " + name);
}
}
// Update is called once per frame
void Update () {
}
public virtual int GetDamage()
{
// if the calculation it's considering the damage, it already hit
_hit = true;
return 0;
}
public void SetHit()
{
_hit = true;
}
public virtual void HitEffect()
{
}
}
|
using System;
using UnityEngine;
namespace RO
{
public class GyroHelper
{
private readonly Quaternion baseIdentity = Quaternion.Euler(90f, 0f, 0f);
private Quaternion cameraBase = Quaternion.get_identity();
private Quaternion calibration = Quaternion.get_identity();
private Quaternion baseOrientation = Quaternion.Euler(90f, 0f, 0f);
private Quaternion baseOrientationRotationFix = Quaternion.get_identity();
private Quaternion referanceRotation = Quaternion.get_identity();
public static Func<Quaternion> GyroAttitudeHooker;
public GyroHelper()
{
this.Reset(null);
}
private static Quaternion GetGyroAttitude()
{
if (GyroHelper.GyroAttitudeHooker != null)
{
return GyroHelper.GyroAttitudeHooker.Invoke();
}
return Input.get_gyro().get_attitude();
}
private static Quaternion ConvertRotation(Quaternion q)
{
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
public void Reset(Transform cameraTransform = null)
{
this.ResetBaseOrientation();
this.UpdateCalibration(true);
this.UpdateCameraBaseRotation(true, cameraTransform);
this.RecalculateReferenceRotation();
}
private Quaternion GetRotFix()
{
return Quaternion.get_identity();
}
private void ResetBaseOrientation()
{
this.baseOrientationRotationFix = this.GetRotFix();
this.baseOrientation = this.baseOrientationRotationFix * this.baseIdentity;
}
private void RecalculateReferenceRotation()
{
this.referanceRotation = Quaternion.Inverse(this.baseOrientation) * Quaternion.Inverse(this.calibration);
}
private void UpdateCalibration(bool onlyHorizontal)
{
if (onlyHorizontal)
{
Vector3 vector = GyroHelper.GetGyroAttitude() * -Vector3.get_forward();
vector.z = 0f;
if (vector == Vector3.get_zero())
{
this.calibration = Quaternion.get_identity();
}
else
{
this.calibration = Quaternion.FromToRotation(this.baseOrientationRotationFix * Vector3.get_up(), vector);
}
}
else
{
this.calibration = GyroHelper.GetGyroAttitude();
}
}
private void UpdateCameraBaseRotation(bool onlyHorizontal, Transform cameraTransform = null)
{
if (onlyHorizontal)
{
Vector3 vector = (!(null != cameraTransform)) ? Vector3.get_forward() : cameraTransform.get_forward();
vector.y = 0f;
if (vector == Vector3.get_zero())
{
this.cameraBase = Quaternion.get_identity();
}
else
{
this.cameraBase = Quaternion.FromToRotation(Vector3.get_forward(), vector);
}
}
else
{
this.cameraBase = ((!(null != cameraTransform)) ? Quaternion.get_identity() : cameraTransform.get_rotation());
}
}
public Quaternion GetWorldRotation()
{
return this.cameraBase * (GyroHelper.ConvertRotation(this.referanceRotation * GyroHelper.GetGyroAttitude()) * this.GetRotFix());
}
}
}
|
using System;
using System.ComponentModel;
using Penumbra.Mods;
namespace Penumbra.Game
{
[Flags]
public enum EqpEntry : ulong
{
BodyEnabled = 0x00_01ul,
BodyHideWaist = 0x00_02ul,
_2 = 0x00_04ul,
BodyHideGlovesS = 0x00_08ul,
_4 = 0x00_10ul,
BodyHideGlovesM = 0x00_20ul,
BodyHideGlovesL = 0x00_40ul,
BodyHideGorget = 0x00_80ul,
BodyShowLeg = 0x01_00ul,
BodyShowHand = 0x02_00ul,
BodyShowHead = 0x04_00ul,
BodyShowNecklace = 0x08_00ul,
BodyShowBracelet = 0x10_00ul,
BodyShowTail = 0x20_00ul,
_14 = 0x40_00ul,
_15 = 0x80_00ul,
BodyMask = 0xFF_FFul,
LegsEnabled = 0x01ul << 16,
LegsHideKneePads = 0x02ul << 16,
LegsHideBootsS = 0x04ul << 16,
LegsHideBootsM = 0x08ul << 16,
_20 = 0x10ul << 16,
LegsShowFoot = 0x20ul << 16,
_22 = 0x40ul << 16,
_23 = 0x80ul << 16,
LegsMask = 0xFFul << 16,
HandsEnabled = 0x01ul << 24,
HandsHideElbow = 0x02ul << 24,
HandsHideForearm = 0x04ul << 24,
_27 = 0x08ul << 24,
HandShowBracelet = 0x10ul << 24,
HandShowRingL = 0x20ul << 24,
HandShowRingR = 0x40ul << 24,
_31 = 0x80ul << 24,
HandsMask = 0xFFul << 24,
FeetEnabled = 0x01ul << 32,
FeetHideKnee = 0x02ul << 32,
FeetHideCalf = 0x04ul << 32,
FeetHideAnkle = 0x08ul << 32,
_36 = 0x10ul << 32,
_37 = 0x20ul << 32,
_38 = 0x40ul << 32,
_39 = 0x80ul << 32,
FeetMask = 0xFFul << 32,
HeadEnabled = 0x00_00_01ul << 40,
HeadHideScalp = 0x00_00_02ul << 40,
HeadHideHair = 0x00_00_04ul << 40,
HeadShowHairOverride = 0x00_00_08ul << 40,
HeadHideNeck = 0x00_00_10ul << 40,
HeadShowNecklace = 0x00_00_20ul << 40,
_46 = 0x00_00_40ul << 40,
HeadShowEarrings = 0x00_00_80ul << 40,
HeadShowEarringsHuman = 0x00_01_00ul << 40,
HeadShowEarringsAura = 0x00_02_00ul << 40,
HeadShowEarHuman = 0x00_04_00ul << 40,
HeadShowEarMiqote = 0x00_08_00ul << 40,
HeadShowEarAuRa = 0x00_10_00ul << 40,
HeadShowEarViera = 0x00_20_00ul << 40,
_54 = 0x00_40_00ul << 40,
_55 = 0x00_80_00ul << 40,
HeadShowHrothgarHat = 0x01_00_00ul << 40,
HeadShowVieraHat = 0x02_00_00ul << 40,
_58 = 0x04_00_00ul << 40,
_59 = 0x08_00_00ul << 40,
_60 = 0x10_00_00ul << 40,
_61 = 0x20_00_00ul << 40,
_62 = 0x40_00_00ul << 40,
_63 = 0x80_00_00ul << 40,
HeadMask = 0xFF_FF_FFul << 40
}
public static class Eqp
{
public static (int, int) BytesAndOffset( EquipSlot slot )
{
return slot switch
{
EquipSlot.Body => ( 2, 0 ),
EquipSlot.Legs => ( 1, 2 ),
EquipSlot.Hands => ( 1, 3 ),
EquipSlot.Feet => ( 1, 4 ),
EquipSlot.Head => ( 3, 5 ),
_ => throw new InvalidEnumArgumentException()
};
}
public static EqpEntry FromSlotAndBytes( EquipSlot slot, byte[] value )
{
EqpEntry ret = 0;
var (bytes, offset) = BytesAndOffset( slot );
if( bytes != value.Length )
{
throw new ArgumentException();
}
for( var i = 0; i < bytes; ++i )
{
ret |= ( EqpEntry )( ( ulong )value[ i ] << ( ( offset + i ) * 8 ) );
}
return ret;
}
public static EqpEntry Mask( EquipSlot slot )
{
return slot switch
{
EquipSlot.Body => EqpEntry.BodyMask,
EquipSlot.Head => EqpEntry.HeadMask,
EquipSlot.Legs => EqpEntry.LegsMask,
EquipSlot.Feet => EqpEntry.FeetMask,
EquipSlot.Hands => EqpEntry.HandsMask,
_ => 0
};
}
}
public static class EqpEntryExtension
{
public static bool Apply( this ref EqpEntry entry, MetaManipulation manipulation )
{
if( manipulation.Type != MetaType.Eqp )
{
return false;
}
var mask = Eqp.Mask( manipulation.EqpIdentifier.Slot );
var result = ( entry & ~mask ) | manipulation.EqpValue;
var ret = result != entry;
entry = result;
return ret;
}
public static EqpEntry Reduce( this EqpEntry entry, EquipSlot slot )
=> entry & Eqp.Mask( slot );
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PauseMenuPanelController : MonoBehaviour
{
[SerializeField]
private Button resume;
[SerializeField]
private Button quit;
private void Awake()
{
Initialize();
}
public void Initialize()
{
resume.onClick.RemoveAllListeners();
resume.onClick.AddListener(OnResumeClick);
quit.onClick.RemoveAllListeners();
quit.onClick.AddListener(OnQuitClick);
}
private void OnResumeClick()
{
ReferencesHolder.Instance.GameManager.UnPauseGame();
}
private void OnQuitClick()
{
ReferencesHolder.Instance.UIStateManager.CloseAll();
ReferencesHolder.Instance.GameManager.QuitGame();
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Logging;
using Microsoft.Owin.Hosting;
using ModernDataServices.App.Config;
using NLog;
namespace ModernDataServices.Service.Host
{
public class ServiceApiApp
{
/// <summary>
/// The logger
/// </summary>
private readonly NLog.Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// The owin web application
/// </summary>
protected IDisposable WebApplication;
/// <summary>
/// Start MemberApi Host Server
/// </summary>
public virtual void Start()
{
_logger.Info("Starting ModernDataServices.Service");
WebApplication = WebApp.Start<OwinHostedConfig>(ConfigurationManager.AppSettings["OwinUrl"]);
_logger.Info("ModernDataServices.Service Started");
}
/// <summary>
/// Method to stop the application.
/// </summary>
public virtual void Stop()
{
WebApplication.Dispose();
_logger.Info("ModernDataServices.Service Stopped");
}
/// <summary>
/// Method to pause the application.
/// </summary>
public virtual void Pause()
{
_logger.Info("ModernDataServices.Service Paused");
}
/// <summary>
/// Method to continue the application.
/// </summary>
public virtual void Continue()
{
_logger.Info("ModernDataServices.Service Now Running");
}
/// <summary>
/// Method to shut down the application.
/// </summary>
public virtual void Shutdown()
{
_logger.Info("ModernDataServices.ServiceShutdown Completed.");
}
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
namespace TimeDisplay
{
public class HomeController : Controller
{
[HttpGet("")]
public ViewResult MyTime()
{
DateTime CurrentTime = DateTime.Now;
ViewBag.day = CurrentTime.ToString("MMMM dd yyyy");
ViewBag.time = CurrentTime.ToString("HH:mm tt");
return View();
}
}
} |
using System.ComponentModel;
using System.IO;
namespace CopyByExif.Core
{
public static class CopyPhotos
{
public static void Copy(CopySettings settings, BackgroundWorker copyWorker)
{
copyWorker.ReportProgress(0);
int i = 0;
var allPhotos = settings.FromDirectory.GetFiles("*.jp*g", SearchOption.AllDirectories);
foreach (var photoFile in allPhotos)
{
var photoToCopy = new PhotoToCopy(photoFile);
photoToCopy.CopyPhoto(settings);
copyWorker.ReportProgress(100 * ++i / allPhotos.Length);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace POTM
{
public class FirstPersonCameraController : MonoBehaviour
{
public float HorizontalSens;
public Camera cineCam;
public LevelChanger lc;
private float startTime = 0f;
// Update is called once per frame
void FixedUpdate()
{
float turn = Input.GetAxis("Horizontal");
Vector3 rot = transform.rotation.eulerAngles;
//transform.Rotate(-rot);
//transform.Local.Rotate(new Vector3(0, turn * HorizontalSens * Time.deltaTime, 0));
//transform.Rotate(rot);
transform.RotateAroundLocal(Vector3.up, turn * HorizontalSens * Time.deltaTime);
if(Time.time - startTime > 30.0f)
{
AkSoundEngine.PostEvent("Stop_All", gameObject);
lc.FadeToLevel("IslandLevel");
}
}
void OnEnable()
{
startTime = Time.time;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using System.Linq;
using AnnealingWPF.Common;
using AnnealingWPF.Exceptions;
using System.IO;
using System.Text.RegularExpressions;
namespace AnnealingWPF.Helpers
{
public static class InputFieldParser
{
public const int CLAUSE_LENGTH = 3;
public static int ParseIntField(string field, string fieldName)
{
int value;
try
{
value = int.Parse(field);
}
catch (ArgumentException)
{
throw new InvalidInputFormatException($"{fieldName} is not an int");
}
return value;
}
public static int ParseNonNegativeIntField(string field, string fieldName)
{
var value = ParseIntField(field, fieldName);
if (value < 0)
throw new InvalidInputFormatException($"{fieldName} is negative");
return value;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="clauseLength">Length of the clause, 0 stands for variable length</param>
/// <returns></returns>
public static SatClause ParseSatClause(string line, IList<SatLiteral> literals, int clauseLength = 0)
{
var splitLine = line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
if (clauseLength > 0 && splitLine.Length - 1 != clauseLength)
throw new InvalidInputFormatException("Invalid number of literals in a clause");
if (!int.TryParse(splitLine.Last(), out int result) || result != 0)
throw new InvalidArgumentException("Last number in a clause is not 0");
var ratedLiterals = new List<SatRatedLiteral>();
foreach (var literalId in splitLine.Take(splitLine.Length - 1))
{
if (int.TryParse(literalId, out int parsedId))
ratedLiterals.Add(new SatRatedLiteral(parsedId < 0, literals[Math.Abs(parsedId)-1]));
else
throw new InvalidArgumentException("Could not parse literal id in a clause");
}
return new SatClause(ratedLiterals);
}
public static List<SatLiteral> ParseLiteralWeights(string line, int expectedLiteralCount)
{
var splitLine = line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
if (splitLine.Length - 2 != expectedLiteralCount)
throw new InvalidInputFormatException("Number of expected literals does not match number of weight parameters");
var test = splitLine.Skip(1)
.SkipLast(1).ToList();
return splitLine.Skip(1)
.SkipLast(1)
.Select((weight, index) => new SatLiteral(index+1, int.Parse(weight)))
.ToList();
}
public static void ParseInstanceInfoLine(string line, out int numberOfLiterals, out int numberOfClauses)
{
var splitLine = line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
if (splitLine[1] != "mwcnf")
throw new InvalidInputFormatException("p definition line contains incorrect name (should be mwcnf)");
if (!int.TryParse(splitLine[2], out numberOfLiterals))
throw new InvalidInputFormatException("could not parse number of literals");
if (!int.TryParse(splitLine[3], out numberOfClauses))
throw new InvalidInputFormatException("could not parse number of clauses");
}
public static int ParseInstanceId(string fileName)
{
string pattern = @"\-\d+\.";
Regex rg = new Regex(pattern);
var match = rg.Match(fileName);
if (!match.Success)
throw new Exception("File name is in invalid format");
return int.Parse(Regex.Replace(match.Value, "[^0-9]", ""));
}
public static ReferenceConfiguration ParseOptimalConfiguration(string line)
{
var splitLine = line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
if (!int.TryParse(splitLine.Last(), out int result) || result != 0)
throw new InvalidArgumentException("Last number in the definition is not 0");
var instanceSize = int.Parse(Regex.Replace(Regex.Match(splitLine[0], @"\d+\-").Value, "[^0-9]", ""));
var instanceId = int.Parse(Regex.Replace(Regex.Match(splitLine[0], @"\-\d+").Value, "[^0-9]", ""));
if (instanceSize != splitLine.Length - 3)
throw new InvalidArgumentException("Invalid number of literals hurr durr");
return new ReferenceConfiguration
{
InstanceId = instanceId,
OptimalizationValue = ParseNonNegativeIntField(splitLine[1], "optimalization value"),
Valuations = splitLine.Skip(2).SkipLast(1).Select(id => ParseIntField(id, "id") > 0).ToList()
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using KnapsackProblem.Common;
namespace KnapsackProblem.DecisionVersion
{
public class DecisionBruteForce : DecisionStrategy
{
public override DecisionResult Solve(DecisionKnapsackInstance knapsackInstance)
{
numberOfSteps = 0;
bool permutationExists = DoesSolutionExist(knapsackInstance.Items.Count, 0, 0, knapsackInstance);
return new DecisionResult { KnapsackInstance = knapsackInstance, NumberOfSteps = numberOfSteps, PermutationExists = permutationExists };
}
bool DoesSolutionExist(int itemsRemaining, int currentPrice, int currentWeight, DecisionKnapsackInstance knapsackInstance)
{
numberOfSteps++;
if (itemsRemaining == 0)
return currentWeight <= knapsackInstance.KnapsackSize && currentPrice >= knapsackInstance.MinimalPrice;
KnapsackItem currentItem = knapsackInstance.Items[itemsRemaining - 1];
if (DoesSolutionExist(itemsRemaining - 1, currentPrice + currentItem.Price, currentWeight + currentItem.Weight, knapsackInstance))
return true;
if (DoesSolutionExist(itemsRemaining - 1, currentPrice, currentWeight, knapsackInstance))
return true;
return false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[SerializeField]
public class TileRect
{
public TileType type;
public int xMin;
public int zMin;
public int xMax;
public int zMax;
public int width
{
get
{
return xMax - xMin + 1;
}
}
public int length
{
get
{
return zMax - zMin + 1;
}
}
}
|
using System.Collections.Generic;
using eForm.Authorization.Users.Dto;
using eForm.Dto;
namespace eForm.Authorization.Users.Exporting
{
public interface IUserListExcelExporter
{
FileDto ExportToFile(List<UserListDto> userListDtos);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
namespace CoterieTakeHome.Interfaces
{
interface IBusinessType
{
public void Architect();
public void Plumber();
public void Programmer();
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class PlayerMovement : MonoBehaviour {
public float speed;
public Text scoreText;
public Text levelText;
public Text gameOverText;
public GameObject lifeAvatar1;
public GameObject lifeAvatar2;
public GameObject lifeAvatar3;
public Material cube1;
public Material cube2;
public Material cube3;
public Material cube4;
public Material panel1;
public Material panel2;
public Material panel3;
public Material panel4;
public AudioSource winSound;
public AudioSource dieSound;
public AudioSource jumpSound;
public AudioSource splatSound;
public AudioSource fallingSound;
public AudioSource gameOverSound;
private int _level;
private int _lives;
private float _waitForNextLevel;
private bool _hasBeatLevel;
private bool _canMove;
private bool _isFalling;
private float _startingYPos;
private float _normalTimeScale;
private GameObject[] _cubes;
private GameObject[] _cubePanels;
private List<GameObject> _transporters;
private bool _isGameOver;
void Start() {
_normalTimeScale = Time.timeScale;
this.gameObject.GetComponent<Rigidbody> ().freezeRotation = true;
_cubes = GameObject.FindGameObjectsWithTag("Cube");
_cubePanels = GameObject.FindGameObjectsWithTag("Top Panel");
_transporters = new List<GameObject>(2);
_transporters.Add(GameObject.FindGameObjectWithTag("Trans1"));
_transporters.Add(GameObject.FindGameObjectWithTag("Trans2"));
InitGame ();
}
void InitGame() {
_level = 1;
_lives = 3;
_canMove = false;
_isFalling = false;
_isGameOver = false;
scoreText.text = "000000";
lifeAvatar1.SetActive (true);
lifeAvatar2.SetActive (true);
lifeAvatar3.SetActive (true);
gameOverText.gameObject.SetActive(false);
InitNewLevel ();
}
void InitNewLevel() {
_hasBeatLevel = false;
levelText.text = "Level " + _level;
foreach (var transporter in _transporters) {
transporter.GetComponent<TransportToTop> ().Init();
}
Time.timeScale = _normalTimeScale;
this.transform.position = new Vector3 (0.0f, 3.0f, 10.0f);
this.gameObject.GetComponent<Rigidbody> ().velocity = Vector3.zero;
this.transform.rotation = Quaternion.Euler (new Vector3 (0.0f, 225.0f, 0.0f));
switch (_level % 3) {
case 0:
foreach (var cube in _cubes) {
cube.GetComponent<MeshRenderer> ().material = cube4;
}
foreach (var panel in _cubePanels) {
panel.GetComponent<MeshRenderer> ().material = panel4;
panel.GetComponent<ChangeCubeColour> ().SetLandedCount (0);
panel.GetComponent<ChangeCubeColour> ().SetHasChangedColour (false);
panel.GetComponent<ChangeCubeColour> ().SetCanChangeColour (false);
}
break;
case 1:
foreach (var cube in _cubes) {
cube.GetComponent<MeshRenderer> ().material = cube1;
}
foreach (var panel in _cubePanels) {
panel.GetComponent<MeshRenderer> ().material = panel1;
panel.GetComponent<ChangeCubeColour> ().SetLandedCount (0);
panel.GetComponent<ChangeCubeColour> ().SetHasChangedColour (false);
panel.GetComponent<ChangeCubeColour> ().SetCanChangeColour (false);
}
break;
case 2:
foreach (var cube in _cubes) {
cube.GetComponent<MeshRenderer> ().material = cube2;
}
foreach (var panel in _cubePanels) {
panel.GetComponent<MeshRenderer> ().material = panel2;
panel.GetComponent<ChangeCubeColour> ().SetLandedCount (0);
panel.GetComponent<ChangeCubeColour> ().SetHasChangedColour (false);
panel.GetComponent<ChangeCubeColour> ().SetCanChangeColour (false);
}
break;
case 3:
foreach (var cube in _cubes) {
cube.GetComponent<MeshRenderer> ().material = cube3;
}
foreach (var panel in _cubePanels) {
panel.GetComponent<MeshRenderer> ().material = panel3;
panel.GetComponent<ChangeCubeColour> ().SetLandedCount (0);
panel.GetComponent<ChangeCubeColour> ().SetHasChangedColour (false);
panel.GetComponent<ChangeCubeColour> ().SetCanChangeColour (false);
}
break;
}
}
void Update() {
if (_canMove) {
MovePlayer ();
}
if (this.gameObject.transform.position.y < (_startingYPos-1.5f) && !_isFalling) {
_isFalling = true;
fallingSound.Play ();
}
if (_hasBeatLevel && !winSound.isPlaying) {
_level++;
InitNewLevel ();
}
if (_isGameOver && !gameOverSound.isPlaying) {
Time.timeScale = _normalTimeScale;
UnityEngine.SceneManagement.SceneManager.LoadScene ("Menu");
}
}
void MovePlayer() {
if (Input.GetKeyDown (KeyCode.DownArrow)) {
_canMove = false;
_startingYPos = this.transform.position.y;
jumpSound.Play ();
this.transform.rotation = Quaternion.Euler (0.0f, 225.0f, 0.0f);
this.transform.Translate (new Vector3 (0.0f, 0.5f, 1.0f));
//ApplyDownwardForce ();
} else if (Input.GetKeyDown (KeyCode.UpArrow)) {
_canMove = false;
_startingYPos = this.transform.position.y;
jumpSound.Play ();
this.transform.rotation = Quaternion.Euler (0.0f, 45.0f, 0.0f);
this.transform.Translate (new Vector3 (0.0f, 1.3f, 1.0f));
//ApplyDownwardForce ();
} else if (Input.GetKeyDown (KeyCode.RightArrow)) {
_canMove = false;
_startingYPos = this.transform.position.y;
jumpSound.Play ();
this.transform.rotation = Quaternion.Euler (0.0f, 135.0f, 0.0f);
this.transform.Translate (new Vector3 (0.0f, 0.5f, 1.0f));
//ApplyDownwardForce ();
} else if (Input.GetKeyDown (KeyCode.LeftArrow)) {
_canMove = false;
_startingYPos = this.transform.position.y;
jumpSound.Play ();
this.transform.rotation = Quaternion.Euler (0.0f, 315.0f, 0.0f);
this.transform.Translate (new Vector3 (0.0f, 1.3f, 1.0f));
//ApplyDownwardForce ();
}
}
void ApplyDownwardForce() {
this.GetComponent<Rigidbody>().AddForce (Vector3.down * speed);
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.CompareTag ("Top Panel")) {
_canMove = true;
_isFalling = false;
if (!(collision.gameObject.GetComponent<ChangeCubeColour>().HasChangedColour())) {
if (collision.gameObject.GetComponent<ChangeCubeColour>().CanChangeColour()) {
collision.gameObject.GetComponent<ChangeCubeColour> ().SetHasChangedColour (true);
scoreText.text = string.Format("{0:000000}", (int.Parse (scoreText.text) + 25));
switch (_level % 3) {
case 0:
collision.gameObject.GetComponent<ChangeCubeColour> ().ChangeMaterial(panel1);
break;
case 1:
collision.gameObject.GetComponent<ChangeCubeColour> ().ChangeMaterial(panel2);
break;
case 2:
collision.gameObject.GetComponent<ChangeCubeColour> ().ChangeMaterial(panel3);
break;
case 3:
collision.gameObject.GetComponent<ChangeCubeColour> ().ChangeMaterial(panel4);
break;
}
collision.gameObject.GetComponent<ChangeCubeColour> ().SetLandedCount (
collision.gameObject.GetComponent<ChangeCubeColour> ().GetLandedCount() + 1); // increment landed cube count
// Check if level is beat
if (collision.gameObject.GetComponent<ChangeCubeColour> ().GetLandedCount() == 28) { // total number of cubes
_waitForNextLevel = Time.time;
Time.timeScale = 0.0f;
winSound.Play ();
_hasBeatLevel = true;
scoreText.text = string.Format("{0:000000}", (int.Parse (scoreText.text) + 1000));
}
} else {
collision.gameObject.GetComponent<ChangeCubeColour> ().SetCanChangeColour(true);
}
}
} else if (collision.gameObject.CompareTag ("Jelly")) {
PlayerDies (false);
}
}
void OnTriggerExit(Collider other) {
if (other.CompareTag ("Boundary")) {
PlayerDies (true);
}
}
void PlayerDies(bool isSplat) {
if (isSplat) splatSound.Play ();
else dieSound.Play ();
if (_lives > 0) {
this.transform.position = new Vector3 (0.0f, 3.0f, 10.0f);
this.gameObject.GetComponent<Rigidbody> ().velocity = Vector3.zero;
this.transform.rotation = Quaternion.Euler (new Vector3 (0.0f, 225.0f, 0.0f));
}
switch (_lives--) {
case 1:
lifeAvatar1.SetActive (false);
break;
case 2:
lifeAvatar2.SetActive (false);
break;
case 3:
lifeAvatar3.SetActive (false);
break;
default:
GameOver ();
break;
}
}
void GameOver() {
_isGameOver = true;
gameOverSound.Play ();
Time.timeScale = 0.0f;
gameOverText.gameObject.SetActive(true);
}
public int GetLevel() {
return _level;
}
}
|
using LazyVocabulary.Common.Entities;
using LazyVocabulary.Common.Enums;
using LazyVocabulary.Logic.Services;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Ninject;
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace LazyVocabulary.Web.Filters
{
public class SetCultureAttribute : FilterAttribute, IActionFilter
{
private UserService _userService;
public UserService UserService
{
get
{
return _userService ?? HttpContext.Current.GetOwinContext().Get<UserService>();
}
private set
{
_userService = value;
}
}
public SetCultureAttribute()
{
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
CultureInfo cultureInfo;
// Get culture from cookies.
HttpCookie cultureFromCookie = filterContext.HttpContext.Request.Cookies["locale"];
if (cultureFromCookie == null)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
cultureInfo = UserProfile.DefaultCulture;
}
else
{
// Get culture from database and set cookie.
var resultWithData = UserService.GetCultureByUserId(filterContext.HttpContext.User.Identity.GetUserId());
if (!resultWithData.Success)
{
cultureInfo = UserProfile.DefaultCulture;
}
cultureInfo = resultWithData.ResultData;
}
AddOrUpdateLocaleCookie(filterContext, cultureInfo.Name.ToLower());
}
else
{
// Invalid cookie.
if (!Enum.GetNames(typeof(LocaleLanguage)).Any(l => l.ToLower() == cultureFromCookie.Value.ToLower()))
{
cultureInfo = UserProfile.DefaultCulture;
AddOrUpdateLocaleCookie(filterContext, cultureInfo.Name.ToLower());
}
else
{
cultureInfo = CultureInfo.CreateSpecificCulture(cultureFromCookie.Value);
}
}
// Formatting data: dates, numbers etc.
Thread.CurrentThread.CurrentCulture = cultureInfo;
// Resources localization.
Thread.CurrentThread.CurrentUICulture = cultureInfo;
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
// Without implementation.
}
private void AddOrUpdateLocaleCookie(ActionExecutedContext filterContext, string locale)
{
HttpCookie cookie = filterContext.HttpContext.Request.Cookies["locale"];
if (cookie == null)
{
cookie = new HttpCookie("locale");
}
cookie.Value = locale;
cookie.Expires = DateTime.Now.AddDays(30);
filterContext.HttpContext.Response.Cookies.Add(cookie);
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace OptGui.Services
{
public class NullableValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (string.IsNullOrEmpty(value.ToString()))
{
return null;
}
else
{
foreach (var c in value.ToString())
{
if (char.IsSymbol(c) && !char.IsDigit(c))
{
return null;
}
}
return value;
}
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using Domain.Entities;
namespace Domain.UseCase
{
public class ShortcutInteractor
{
public IReadOnlyCollection<Shortcut> GetShortcuts(int[][] matrix, int start)
{
var adjacencyMatrix = new AdjacencyMatrix(matrix);
var calculator = new ShortcutCalculator();
return calculator.Shortcuts(adjacencyMatrix, start).ToImmutableList();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsultingManager.Dto
{
public class CustomerDto
{
public Guid Id { get; set; }
public DateTime CreatedDate { get; set; }
public string Name { get; set; }
public string LogoUrl { get; set; }
public string StoreUrl { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public Guid? ConsultantId { get; set; }
public UserDto Consultant { get; set; }
public Guid? PlatformId { get; set; }
public PlatformDto Platform { get; set; }
public Guid? PlanId { get; set; }
public PlanDto Plan { get; set; }
public Guid? CategoryId { get; set; }
public CustomerCategoryDto Category { get; set; }
public Guid? SituationId { get; set; }
public CustomerSituationDto Situation { get; set; }
public Guid? CityId { get; set; }
public CityDto City { get; set; }
public ICollection<UserDto> Users { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.