text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
namespace GENN
{
public class NeuralNet
{
// Private data stores
private Input[] _InputLayer;
private Neuron[][] _HiddenLayers;
private Neuron[] _OutputLayer;
// Static class members
public static double ErrorThreshold = 0.9;
/// <summary>
/// Initializes a new instance of the <see cref="GENN.NeuralNet"/> class.
/// </summary>
/// <param name="inputLayer">Input layer.</param>
/// <param name="hiddenDimensions">Hidden dimensions (length of array represents depth).</param>
/// <param name="outputCount">Output count.</param>
public NeuralNet (Input[] inputLayer, int[] hiddenDimensions, int outputCount)
{
// Copy reference to input layer
_InputLayer = inputLayer;
// Start a running "last layer" tag (for depth == 0 edge case)
Input[] lastLayer = inputLayer;
// Allocate memory for hidden layers and create hidden neurons linked to previous depth layer
int hiddenDepth = hiddenDimensions.Length;
int hiddenWidth;
_HiddenLayers = new Neuron[hiddenDepth][];
for (int d = 0; d < hiddenDepth; d++) {
hiddenWidth = hiddenDimensions [d];
_HiddenLayers [d] = new Neuron[hiddenWidth];
for (int w = 0; w < hiddenWidth; w++) {
if (d != 0)
_HiddenLayers [d] [w] = new Neuron (_HiddenLayers [d - 1]);
else
_HiddenLayers [d] [w] = new Neuron (_InputLayer);
}
// Update "last layer" tag
if (d == hiddenDepth - 1)
lastLayer = _HiddenLayers [d];
}
// Allocate memory for output layer and create neurons linked to last hidden layer
_OutputLayer = new Neuron[outputCount];
for (int o = 0; o < outputCount; o++)
_OutputLayer [o] = new Neuron (lastLayer);
}
/// <summary>
/// Initializes a new instance of the <see cref="GENN.NeuralNet"/> class by "breeding" two nets.
/// </summary>
/// <param name="mate">Mate.</param>
public NeuralNet (NeuralNet mother, NeuralNet father)
{
// Copy reference to the input layer
_InputLayer = mother.InputLayer;
// Allocate memory for hidden layers and copy each neuron in the net
int hiddenDepth = mother.HiddenLayers.Length;
int hiddenLayerWidth;
_HiddenLayers = new Neuron[hiddenDepth][];
for (int d = 0; d < hiddenDepth; d++) {
hiddenLayerWidth = mother.HiddenLayers [d].Length;
_HiddenLayers[d] = new Neuron[hiddenLayerWidth];
for (int w = 0; w < hiddenLayerWidth; w++) {
if (d == 0)
_HiddenLayers[d][w] = new Neuron(
InputLayer, mother.HiddenLayers[d][w], father.HiddenLayers[d][w], ErrorThreshold);
else
_HiddenLayers[d][w] = new Neuron(
_HiddenLayers[d - 1], mother.HiddenLayers[d][w], father.HiddenLayers[d][w], ErrorThreshold);
}
}
// Allocate memory for output layer and copy each neuron
_OutputLayer = new Neuron[mother.OutputLayer.Length];
for (int o = 0; o < mother.OutputLayer.Length; o++)
_OutputLayer [o] = new Neuron (
_HiddenLayers[hiddenDepth - 1], mother.OutputLayer [o], father.OutputLayer [o], ErrorThreshold);
}
/// <summary>
/// Gets the input layer.
/// </summary>
/// <value>The input layer.</value>
protected Input[] InputLayer
{
get { return _InputLayer; }
}
/// <summary>
/// Gets the hidden layers.
/// </summary>
/// <value>The hidden layers.</value>
protected Neuron[][] HiddenLayers
{
get { return _HiddenLayers; }
}
/// <summary>
/// Gets the output layer.
/// </summary>
/// <value>The output layer.</value>
protected Neuron[] OutputLayer
{
get { return _OutputLayer; }
}
/// <summary>
/// The output values of the <see cref="NeuralNet"/> as an array of decimal values.
/// </summary>
public double[] Output
{
get
{
double[] output = new double[_OutputLayer.Length];
for (int i = 0; i < _OutputLayer.Length; i++)
output [i] = _OutputLayer [i].Output;
return output;
}
}
}
}
|
namespace Kit
{
public static class Elevator
{
public static T Elevate<T>(this object Lower)
where T : new()
{
var ElevatedType = typeof(T);
var LowerType = Lower.GetType();
if (LowerType.IsSubclassOf(ElevatedType))
{
throw new InvalidCastException($"{LowerType.Name} is not subclass of {ElevatedType.Name}");
}
string json = Newtonsoft.Json.JsonConvert.SerializeObject(Lower);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DesiClothing4u.Common.Models;
using Microsoft.Data.SqlClient;
//using Microsoft.AspNetCore.Cors;
namespace DesiClothing4u.API.Controllers
{
//[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class VendorsController : ControllerBase
{
private readonly desiclothingContext _context;
public VendorsController(desiclothingContext context)
{
_context = context;
}
// GET: api/Vendors
[HttpGet]
public async Task<ActionResult<IEnumerable<Vendor>>> GetVendors()
{
return await _context.Vendors.ToListAsync();
}
// GET: api/Vendors/5
[HttpGet("{id}")]
public async Task<ActionResult<Vendor>> GetVendor(int id)
{
var vendor = await _context.Vendors.FindAsync(id);
if (vendor == null)
{
return NotFound();
}
return vendor;
}
// Post: api/VendorBankDetail
[HttpPost("PostVendorBankDetail")]
public async Task<ActionResult<VendorBankDetail>> PostVendorBankDetail(VendorBankDetail vendorBankDetails)
{
_context.VendorBankDetails.Add(vendorBankDetails);
await _context.SaveChangesAsync();
return CreatedAtAction("GetVendorBankDetail", new { id = vendorBankDetails.Id }, vendorBankDetails);
}
// GET: api/GetVendorBankDetail/5
[HttpGet("GetVendorBankDetail")]
public async Task<ActionResult<VendorBankDetail>> GetVendorBankDetail(int id)
{
var vendorBankDetail = await _context.VendorBankDetails.FindAsync(id);
if (vendorBankDetail == null)
{
return NotFound();
}
return vendorBankDetail;
}
// GET: api/GetVendorBankDetail/5
[HttpGet("checkvendoremail")]
public async Task<ActionResult<IEnumerable<Vendor>>> checkvendoremail(string VEmail)
{
try
{
SqlParameter param1 = new SqlParameter("@Email", VEmail);
var vendor = _context.Vendors
.FromSqlRaw("Execute dbo.CheckVendorEmail @Email ", param1)
.ToList();
return vendor;
}
catch (Exception e)
{
/*incase of no category*/
return null;
}
}
// PUT: api/Vendors/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
public async Task<IActionResult> PutVendor(int id, Vendor vendor)
{
if (id != vendor.Id)
{
return BadRequest();
}
_context.Entry(vendor).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!VendorExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Vendors
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
public async Task<ActionResult<Vendor>> PostVendor(Vendor vendor)
{
_context.Vendors.Add(vendor);
await _context.SaveChangesAsync();
return CreatedAtAction("GetVendor", new { id = vendor.Id }, vendor);
}
// DELETE: api/Vendors/5
[HttpDelete("{id}")]
public async Task<ActionResult<Vendor>> DeleteVendor(int id)
{
var vendor = await _context.Vendors.FindAsync(id);
if (vendor == null)
{
return NotFound();
}
_context.Vendors.Remove(vendor);
await _context.SaveChangesAsync();
return vendor;
}
[HttpGet("ValidateVendor")]
public ActionResult<Vendor> ValidateVendor(string email, string UserPassword)
{
bool VendorExists;
VendorExists = _context.Vendors.Any(e => e.Email == email && e.password == UserPassword);
if (VendorExists == false)
{
return NotFound();
}
//var siteUsers = await _context.Vendors.FindAsync(email);
var siteUsers = _context.Vendors.SingleOrDefault(e => e.Email == email);
return siteUsers;
}
private bool VendorExists(int id)
{
return _context.Vendors.Any(e => e.Id == id);
}
//added by SM on Dec 28, 2020
[HttpGet("GetOrderitemsByVendor")]
public IEnumerable<CustOrderItems> GetOrderitemsByVendor(int VendorId)
{
try
{
var orderitem = _context.CustOrderItems
.FromSqlRaw("Execute dbo.GetOrderItems {0}", VendorId)
.ToList();
return orderitem;
}
catch (Exception e)
{
/*if the vendor dont have any product*/
return null;
}
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace Customer.Until.Chat
{
class FileParam
{
public FileParam(){ }
public DockPanel DockPane { get; set; }
public DockPanel instance
{
get{ return DockPane; }
set
{
//loadFileParam();
FileDefault.StackThird.Children.Add(FileDefault.TextFileName);
FileDefault.StackThird.Children.Add(FileDefault.LabelSize);
FileDefault.DockThird.Children.Add(FileDefault.StackThird);
FileDefault.DockThird.Children.Add(FileDefault.FileImg);
UserParam userParam = new UserParam() { Default = null }.UserParamDefault;
userParam.StackTwo.Width = 220;
userParam.StackTwo.Height = 105;
userParam.StackTwo.Children.Add(FileDefault.DockThird);
userParam.StackTwo.Children.Add(FileDefault.AppName);
userParam.UserDock = new DockPanel();
DockPane = userParam.UserDock;
}
}
private DockPanel DockThird { get; set; }
private StackPanel StackThird { get; set; }
private TextBlock TextFileName { get; set; }
private Label LabelSize { get; set; }
private Image FileImg { get; set; }
private Label AppName { get; set; }
public string FileName { get; set; }
public System.Drawing.Bitmap FileIcon { get; set; }
public BitmapSource FileIconImg { get; set; }
public string FileSize { get; set; }
public string UserImg { get; set; }
public FileParam FileDefault { get; set; }
public FileParam Default
{
get { return FileDefault; }
set
{
FileIconUtil = FileIcon;
FileDefault = new FileParam()
{
AppName = new Label() { Content = " Yestar桌面版", BorderBrush = CommonUtil.GetColorBrush(222, 221, 221), BorderThickness = new Thickness(0, 1, 0, 0) },
DockThird = new DockPanel() { HorizontalAlignment = HorizontalAlignment.Left, Height = 82 },
StackThird = new StackPanel() { Width = 165 },
TextFileName = new TextBlock() { Padding = new Thickness(15, 15, 10, 10), TextWrapping = TextWrapping.Wrap, Text = FileName, MaxWidth = 175 },
LabelSize = new Label() { Content = FileSize, Margin = new Thickness(11, 0, 0, 0) },
FileImg = new Image() { Source = FileIconImg, Width = 45 }
};
}
}
public System.Drawing.Bitmap FileIconUtil
{
set
{
if(value != null)
{
IntPtr ip = value.GetHbitmap();
FileIconImg = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
value.Dispose();
}
}
}
}
}
|
using PDV.DAO.Custom;
using PDV.DAO.DB.Controller;
using PDV.DAO.Entidades;
using PDV.DAO.Enum;
using System.Collections.Generic;
using System.Data;
namespace PDV.CONTROLER.Funcoes
{
public class FuncoesFormaDePagamento
{
public static bool Existe(decimal IDFormaDePagamento)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT 1 FROM FORMADEPAGAMENTO WHERE IDFORMADEPAGAMENTO = @IDFORMADEPAGAMENTO";
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = IDFormaDePagamento;
oSQL.Open();
return !oSQL.IsEmpty;
}
}
public static List<FormaDePagamento> GetFormasPagamentos()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT DISTINCT FORMADEPAGAMENTO.IDBANDEIRACARTAO,
FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.DESCRICAO,
CASE WHEN FORMADEPAGAMENTO.IDBANDEIRACARTAO IS NULL
THEN FORMADEPAGAMENTO.DESCRICAO ELSE FORMADEPAGAMENTO.DESCRICAO||' - '||BANDEIRACARTAO.DESCRICAO
END AS FORMADEPAGAMENTOBANDEIRA,
FORMADEPAGAMENTO.IDFORMADEPAGAMENTO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.Transacao,
FORMADEPAGAMENTO.Usa_Calendario_Comercial,
FORMADEPAGAMENTO.Qtd_Parcelas,
FORMADEPAGAMENTO.Fator_Dup_Com_Entrada,
FORMADEPAGAMENTO.Fator_Dup_Sem_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Com_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Sem_Entrada
FROM FORMADEPAGAMENTO
LEFT JOIN BANDEIRACARTAO ON (FORMADEPAGAMENTO.IDBANDEIRACARTAO = BANDEIRACARTAO.IDBANDEIRACARTAO)
WHERE FORMADEPAGAMENTO.ATIVO = 1
ORDER BY FORMADEPAGAMENTO.CODIGO, FORMADEPAGAMENTO.IDENTIFICACAO";
oSQL.Open();
return new DataTableParser<FormaDePagamento>().ParseDataTable(oSQL.dtDados);
}
}
public static bool Existe(string descricao)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT 1 FROM FORMADEPAGAMENTO WHERE DESCRICAO = @DESCRICAO";
oSQL.ParamByName["DESCRICAO"] = descricao;
oSQL.Open();
return !oSQL.IsEmpty;
}
}
public static FormaDePagamento GetFormaDePagamentoPDV(decimal Codigo)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT IDFORMADEPAGAMENTO,
CODIGO,
DESCRICAO,
IDBANDEIRACARTAO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.TEF,*
FROM FORMADEPAGAMENTO
WHERE Codigo = @IDFORMADEPAGAMENTO AND PDV = 1";
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = Codigo;
oSQL.Open();
if (oSQL.dtDados.Rows.Count == 0)
{
return null;
}
var teste = EntityUtil<FormaDePagamento>.ParseDataRow(oSQL.dtDados.Rows[0]);
return EntityUtil<FormaDePagamento>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static FormaDePagamento GetFormaDePagamento(decimal IDFormaDePagamento)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT IDFORMADEPAGAMENTO,
CODIGO,
DESCRICAO,
IDBANDEIRACARTAO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.TEF,*
FROM FORMADEPAGAMENTO
WHERE IDFORMADEPAGAMENTO = @IDFORMADEPAGAMENTO";
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = IDFormaDePagamento;
oSQL.Open();
if (oSQL.dtDados.Rows.Count == 0)
{
return null;
}
return EntityUtil<FormaDePagamento>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static List<FormaDePagamento> GetFormasPagamentos(decimal IDFormaDePagamento)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT IDFORMADEPAGAMENTO,
CODIGO,
DESCRICAO,
IDBANDEIRACARTAO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.TEF,*
FROM FORMADEPAGAMENTO
WHERE IDFORMADEPAGAMENTO = @IDFORMADEPAGAMENTO";
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = IDFormaDePagamento;
oSQL.Open();
if (oSQL.dtDados.Rows.Count == 0)
{
return null;
}
return EntityUtil<List<FormaDePagamento>>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static DataTable GetFormasDePagamento(string Codigo, string Descricao)
{
using (SQLQuery oSQL = new SQLQuery())
{
List<string> Filtros = new List<string>();
if (!string.IsNullOrEmpty(Codigo))
{
Filtros.Add(string.Format("(UPPER(FORMADEPAGAMENTO.CODIGO::VARCHAR) LIKE UPPER('%{0}%'))", Codigo));
}
if (!string.IsNullOrEmpty(Descricao))
{
Filtros.Add(string.Format("(UPPER(FORMADEPAGAMENTO.DESCRICAO) LIKE UPPER('%{0}%'))", Descricao));
}
oSQL.SQL = string.Format(
@"SELECT DISTINCT FORMADEPAGAMENTO.IDFORMADEPAGAMENTO,
FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.DESCRICAO,
BANDEIRACARTAO.DESCRICAO AS BANDEIRACARTAO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
BANDEIRACARTAO.IDBANDEIRACARTAO,
FORMADEPAGAMENTO.TEF,*
FROM FORMADEPAGAMENTO
LEFT JOIN BANDEIRACARTAO ON (FORMADEPAGAMENTO.IDBANDEIRACARTAO = BANDEIRACARTAO.IDBANDEIRACARTAO)
{0}
ORDER BY FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.IDENTIFICACAO", Filtros.Count > 0 ? "WHERE " + string.Join(" AND ", Filtros.ToArray()) : string.Empty);
oSQL.Open();
return oSQL.dtDados;
}
}
public static List<FormaDePagamento> GetFormasPagamentoPDV()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT DISTINCT FORMADEPAGAMENTO.IDBANDEIRACARTAO,
FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.DESCRICAO,
CASE WHEN FORMADEPAGAMENTO.IDBANDEIRACARTAO IS NULL
THEN FORMADEPAGAMENTO.DESCRICAO ELSE FORMADEPAGAMENTO.DESCRICAO||' - '||BANDEIRACARTAO.DESCRICAO
END AS FORMADEPAGAMENTOBANDEIRA,
FORMADEPAGAMENTO.IDFORMADEPAGAMENTO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.Transacao,
FORMADEPAGAMENTO.Usa_Calendario_Comercial,
FORMADEPAGAMENTO.Qtd_Parcelas,
FORMADEPAGAMENTO.Fator_Dup_Com_Entrada,
FORMADEPAGAMENTO.Fator_Dup_Sem_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Com_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Sem_Entrada
FROM FORMADEPAGAMENTO
LEFT JOIN BANDEIRACARTAO ON (FORMADEPAGAMENTO.IDBANDEIRACARTAO = BANDEIRACARTAO.IDBANDEIRACARTAO)
WHERE FORMADEPAGAMENTO.ATIVO = 1 AND FORMADEPAGAMENTO.PDV = 1
ORDER BY FORMADEPAGAMENTO.CODIGO, FORMADEPAGAMENTO.IDENTIFICACAO";
oSQL.Open();
return new DataTableParser<FormaDePagamento>().ParseDataTable(oSQL.dtDados);
}
}
public static List<FormaDePagamento> GetFormasPagamentoForcaDeVenda()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT DISTINCT FORMADEPAGAMENTO.IDBANDEIRACARTAO,
FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.DESCRICAO,
CASE WHEN FORMADEPAGAMENTO.IDBANDEIRACARTAO IS NULL
THEN FORMADEPAGAMENTO.DESCRICAO ELSE FORMADEPAGAMENTO.DESCRICAO||' - '||BANDEIRACARTAO.DESCRICAO
END AS FORMADEPAGAMENTOBANDEIRA,
FORMADEPAGAMENTO.IDFORMADEPAGAMENTO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.Transacao,
FORMADEPAGAMENTO.Usa_Calendario_Comercial,
FORMADEPAGAMENTO.Qtd_Parcelas,
FORMADEPAGAMENTO.Fator_Dup_Com_Entrada,
FORMADEPAGAMENTO.Fator_Dup_Sem_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Com_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Sem_Entrada
FROM FORMADEPAGAMENTO
LEFT JOIN BANDEIRACARTAO ON (FORMADEPAGAMENTO.IDBANDEIRACARTAO = BANDEIRACARTAO.IDBANDEIRACARTAO)
WHERE FORMADEPAGAMENTO.ATIVO = 1 --AND FORMADEPAGAMENTO.PDV != 1
ORDER BY FORMADEPAGAMENTO.CODIGO, FORMADEPAGAMENTO.IDENTIFICACAO";
oSQL.Open();
return new DataTableParser<FormaDePagamento>().ParseDataTable(oSQL.dtDados);
}
}
public static List<FormaDePagamento> GetFormasPagamento()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = @"SELECT DISTINCT FORMADEPAGAMENTO.IDBANDEIRACARTAO,
FORMADEPAGAMENTO.CODIGO,
FORMADEPAGAMENTO.DESCRICAO,
CASE WHEN FORMADEPAGAMENTO.IDBANDEIRACARTAO IS NULL
THEN FORMADEPAGAMENTO.DESCRICAO ELSE FORMADEPAGAMENTO.DESCRICAO||' - '||BANDEIRACARTAO.DESCRICAO
END AS FORMADEPAGAMENTOBANDEIRA,
FORMADEPAGAMENTO.IDFORMADEPAGAMENTO,
FORMADEPAGAMENTO.IDENTIFICACAO,
FORMADEPAGAMENTO.ATIVO,
FORMADEPAGAMENTO.Transacao,
FORMADEPAGAMENTO.Usa_Calendario_Comercial,
FORMADEPAGAMENTO.Qtd_Parcelas,
FORMADEPAGAMENTO.Fator_Dup_Com_Entrada,
FORMADEPAGAMENTO.Fator_Dup_Sem_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Com_Entrada,
FORMADEPAGAMENTO.Fator_Cheq_Sem_Entrada
FROM FORMADEPAGAMENTO
LEFT JOIN BANDEIRACARTAO ON (FORMADEPAGAMENTO.IDBANDEIRACARTAO = BANDEIRACARTAO.IDBANDEIRACARTAO)
WHERE FORMADEPAGAMENTO.ATIVO = 1
ORDER BY FORMADEPAGAMENTO.CODIGO, FORMADEPAGAMENTO.IDENTIFICACAO";
oSQL.Open();
return new DataTableParser<FormaDePagamento>().ParseDataTable(oSQL.dtDados);
}
}
public static bool Salvar(FormaDePagamento _FormaDePagamento, TipoOperacao Op)
{
using (SQLQuery oSQL = new SQLQuery())
{
switch (Op)
{
case TipoOperacao.INSERT:
oSQL.SQL = @"INSERT INTO FORMADEPAGAMENTO (IDFORMADEPAGAMENTO, CODIGO, DESCRICAO, IDBANDEIRACARTAO, IDENTIFICACAO, ATIVO, TEF,
Transacao,Usa_Calendario_Comercial,Qtd_Parcelas,dias_intervalo,Fator_Dup_Com_Entrada,Fator_Dup_Sem_Entrada,Fator_Cheq_Com_Entrada,Fator_Cheq_Sem_Entrada,Periodicidade,PDV)
VALUES (@IDFORMADEPAGAMENTO, @CODIGO, @DESCRICAO, @IDBANDEIRACARTAO, @IDENTIFICACAO, @ATIVO,@TEF,
@Transacao,@Usa_Calendario_Comercial,@Qtd_Parcelas,@dias_intervalo,@Fator_Dup_Com_Entrada,@Fator_Dup_Sem_Entrada,@Fator_Cheq_Com_Entrada,@Fator_Cheq_Sem_Entrada,@Periodicidade,@PDV)";
break;
case TipoOperacao.UPDATE:
oSQL.SQL = @"UPDATE FORMADEPAGAMENTO
SET CODIGO = @CODIGO,
DESCRICAO = @DESCRICAO,
IDBANDEIRACARTAO = @IDBANDEIRACARTAO,
IDENTIFICACAO = @IDENTIFICACAO,
ATIVO = @ATIVO, TEF = @TEF,
Transacao = @Transacao,
Usa_Calendario_Comercial = @Usa_Calendario_Comercial,
Qtd_Parcelas = @Qtd_Parcelas,
Fator_Dup_Com_Entrada = @Fator_Dup_Com_Entrada,
Fator_Dup_Sem_Entrada = @Fator_Dup_Sem_Entrada,
Fator_Cheq_Com_Entrada = @Fator_Cheq_Com_Entrada,
Fator_Cheq_Sem_Entrada = @Fator_Cheq_Sem_Entrada,
dias_intervalo = @dias_intervalo, Periodicidade = @Periodicidade, PDV = @PDV
WHERE IDFORMADEPAGAMENTO = @IDFORMADEPAGAMENTO";
break;
}
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = _FormaDePagamento.IDFormaDePagamento;
oSQL.ParamByName["CODIGO"] = _FormaDePagamento.Codigo;
oSQL.ParamByName["DESCRICAO"] = _FormaDePagamento.Descricao;
oSQL.ParamByName["IDBANDEIRACARTAO"] = _FormaDePagamento.IDBandeiraCartao;
oSQL.ParamByName["IDENTIFICACAO"] = _FormaDePagamento.Identificacao;
oSQL.ParamByName["ATIVO"] = _FormaDePagamento.Ativo;
oSQL.ParamByName["TEF"] = _FormaDePagamento.TEF;
oSQL.ParamByName["PDV"] = _FormaDePagamento.PDV;
oSQL.ParamByName["Transacao"] = _FormaDePagamento.Transacao;
oSQL.ParamByName["Usa_Calendario_Comercial"] = _FormaDePagamento.Usa_Calendario_Comercial;
oSQL.ParamByName["Qtd_Parcelas"] = _FormaDePagamento.Qtd_Parcelas;
oSQL.ParamByName["Fator_Dup_Com_Entrada"] = _FormaDePagamento.Fator_Dup_Com_Entrada;
oSQL.ParamByName["Fator_Dup_Sem_Entrada"] = _FormaDePagamento.Fator_Dup_Sem_Entrada;
oSQL.ParamByName["Fator_Cheq_Com_Entrada"] = _FormaDePagamento.Fator_Cheq_Com_Entrada;
oSQL.ParamByName["Fator_Cheq_Sem_Entrada"] = _FormaDePagamento.Fator_Cheq_Sem_Entrada;
oSQL.ParamByName["dias_intervalo"] = _FormaDePagamento.Dias_Intervalo;
oSQL.ParamByName["Periodicidade"] = _FormaDePagamento.Periodicidade;
return oSQL.ExecSQL() == 1;
}
}
public static bool Remover(decimal IDFormaDePagamento)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.ClearAll();
oSQL.SQL = @"DELETE FROM FORMADEPAGAMENTO WHERE IDFORMADEPAGAMENTO = @IDFORMADEPAGAMENTO";
oSQL.ParamByName["IDFORMADEPAGAMENTO"] = IDFormaDePagamento;
return oSQL.ExecSQL() == 1;
}
}
}
}
|
using System;
using System.Collections.Generic;
using Yeasca.Metier;
using Yeasca.Mongo;
namespace Yeasca.Requete
{
public class DetailConstatRequete : Requete<IDetailConstatMessage>
{
public override ReponseRequete exécuter(IDetailConstatMessage message)
{
if (estAuthentifié())
return lancerLaRequete(message);
return ReponseRequete.générerUnEchec(Ressource.Requetes.AUTH_REQUISE);
}
private ReponseRequete lancerLaRequete(IDetailConstatMessage message)
{
Guid idConstat;
if (!Guid.TryParse(message.IdConstat, out idConstat))
return ReponseRequete.générerUnEchec(Ressource.Requetes.REF_CONSTAT_INVALIDE);
IEntrepotConstat entrepot = EntrepotMongo.fabriquerEntrepot<IEntrepotConstat>();
Constat constat = entrepot.récupérerLeConstat(idConstat);
if (constat != null)
return obtenirLaRéponse(constat);
return ReponseRequete.générerUnEchec(Ressource.Requetes.REF_CONSTAT_INVALIDE);
}
private ReponseRequete obtenirLaRéponse(Constat constat)
{
DetailConstatReponse résultat = initialiserLaRéponse(constat);
ajouterLesFichiers(résultat, constat);
return ReponseRequete.générerUnSuccès(résultat);
}
private DetailConstatReponse initialiserLaRéponse(Constat constat)
{
IEntrepotParametrage paramètres = EntrepotMongo.fabriquerEntrepot<IEntrepotParametrage>();
DetailConstatReponse résultat = new DetailConstatReponse();
résultat.IdConstat = constat.Id.ToString();
résultat.Date = constat.Date.ToString(Ressource.Paramètres.FORMAT_DATE);
résultat.CivilitéClient = paramètres.récupérerLesCivilités()[constat.Client.Abréviation];
résultat.NomClient = constat.Client.Nom;
résultat.PrénomClient = constat.Client.Prénom;
résultat.CivilitéHuissier = paramètres.récupérerLesCivilités()[constat.Huissier.Abréviation];
résultat.NomHuissier = constat.Huissier.Nom;
résultat.PrénomHuissier = constat.Huissier.Prénom;
résultat.Traité = constat.EstValidé;
return résultat;
}
private void ajouterLesFichiers(DetailConstatReponse résultat, Constat constat)
{
résultat.Fichiers = new List<DetailFichierReponse>();
foreach (Fichier fichier in constat.Fichiers)
{
résultat.Fichiers.Add(new DetailFichierReponse()
{
Id = fichier.Id.ToString(),
Date = fichier.Date.ToString(Ressource.Paramètres.FORMAT_DATE),
Nom = fichier.Nom,
Type = fichier.TypeDuFichier
});
}
}
}
public class DetailConstatReponse
{
public string IdConstat { get; set; }
public string Date { get; set; }
public string CivilitéClient { get; set; }
public string NomClient { get; set; }
public string PrénomClient { get; set; }
public string CivilitéHuissier { get; set; }
public string NomHuissier { get; set; }
public string PrénomHuissier { get; set; }
public bool Traité { get; set; }
public List<DetailFichierReponse> Fichiers { get; set; }
}
public class DetailFichierReponse
{
public string Id { get; set; }
public string Nom { get; set; }
public string Date { get; set; }
public string Type { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Media;
using Microsoft.Azure.Management.Media.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.Azure.Authentication;
namespace MediaServicesAPI_Test
{
class Program
{
public static async Task Main(string[] args)
{
ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build());
try
{
IAzureMediaServicesClient client = await CreateMediaServicesClientAsync(config);
Console.WriteLine("connected");
}
catch (Exception exception)
{
if (exception.Source.Contains("ActiveDirectory"))
{
Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
}
Console.Error.WriteLine($"{exception.Message}");
ApiErrorException apiException = exception.GetBaseException() as ApiErrorException;
if (apiException != null)
{
Console.Error.WriteLine(
$"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
}
}
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
private static async Task<ServiceClientCredentials> GetCredentialsAsync(ConfigWrapper config)
{
// Use ApplicationTokenProvider.LoginSilentWithCertificateAsync or UserTokenProvider.LoginSilentAsync to get a token using service principal with certificate
//// ClientAssertionCertificate
//// ApplicationTokenProvider.LoginSilentWithCertificateAsync
// Use ApplicationTokenProvider.LoginSilentAsync to get a token using a service principal with symmetric key
ClientCredential clientCredential = new ClientCredential(config.AadClientId, config.AadSecret);
return await ApplicationTokenProvider.LoginSilentAsync(config.AadTenantId, clientCredential, ActiveDirectoryServiceSettings.Azure);
}
private static async Task<IAzureMediaServicesClient> CreateMediaServicesClientAsync(ConfigWrapper config)
{
var credentials = await GetCredentialsAsync(config);
return new AzureMediaServicesClient(config.ArmEndpoint, credentials)
{
SubscriptionId = config.SubscriptionId,
};
}
}
}
|
using yamoc.server;
namespace yamoc.stringEvaluator.value
{
public class BodyJsonValueEvaluator : ValueEvaluator {
public string Path { get; set; }
override public string evoluate(RequestMatchingContext context)
{
string value = context.Request.readBodyJson(Path);
return value;
}
public override string ToString() {
return "{" + (Path ?? null) + "}";
}
public override bool Equals(object obj) {
if (obj is BodyJsonValueEvaluator) {
var val = (BodyJsonValueEvaluator)obj;
return Path == val.Path;
}
return false;
}
public override int GetHashCode() {
return (Path != null ? Path.GetHashCode() : 0);
}
}
}
|
using BLL;
using Entidades;
using ProyectoFinal.UI;
using ProyectoFinal.UI.Consultas;
using ProyectoFinal.UI.Registros;
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 ProyectoFinal
{
public partial class MainForm : Form
{
public int IdUsuario;
private Usuarios Usuario;
public MainForm(int IdUsuario)
{
InitializeComponent();
this.IdUsuario = IdUsuario;
/*Login login = new Login();
login.ShowDialog();*/
BuscarUsuario();
Permisos();
}
private void Permisos()
{
registrarUsuariosToolStripMenuItem.Enabled = false;
consultarUsuariosToolStripMenuItem.Enabled = false;
consultarComprasToolStripMenuItem.Enabled = false;
consultarVentasToolStripMenuItem.Enabled = false;
registroDeVendedoresToolStripMenuItem.Enabled = false;
consultarVendedoresToolStripMenuItem.Enabled = false;
registrarPesadoresToolStripMenuItem.Enabled = false;
consultarPesadoresToolStripMenuItem.Enabled = false;
registroDeAgricultoresToolStripMenuItem.Enabled = false;
consultarAgriculturesToolStripMenuItem.Enabled = false;
registroDeComprasToolStripMenuItem.Enabled = false;
entradaDeProductosToolStripMenuItem.Enabled = false;
if (Usuario.NivelUsuario.Equals("Alto"))
{
registrarUsuariosToolStripMenuItem.Enabled = true;
consultarUsuariosToolStripMenuItem.Enabled = true;
consultarComprasToolStripMenuItem.Enabled = true;
consultarVentasToolStripMenuItem.Enabled = true;
registroDeVendedoresToolStripMenuItem.Enabled = true;
consultarVendedoresToolStripMenuItem.Enabled = true;
registrarPesadoresToolStripMenuItem.Enabled = true;
consultarPesadoresToolStripMenuItem.Enabled = true;
registroDeAgricultoresToolStripMenuItem.Enabled = true;
consultarAgriculturesToolStripMenuItem.Enabled = true;
registroDeComprasToolStripMenuItem.Enabled = true;
entradaDeProductosToolStripMenuItem.Enabled = true;
}
if (Usuario.NivelUsuario.Equals("Medio"))
{
registroDeVendedoresToolStripMenuItem.Enabled = true;
consultarVendedoresToolStripMenuItem.Enabled = true;
registrarPesadoresToolStripMenuItem.Enabled = true;
consultarPesadoresToolStripMenuItem.Enabled = true;
registroDeAgricultoresToolStripMenuItem.Enabled = true;
consultarAgriculturesToolStripMenuItem.Enabled = true;
registroDeComprasToolStripMenuItem.Enabled = true;
entradaDeProductosToolStripMenuItem.Enabled = true;
}
}
private void BuscarUsuario()
{
RepositorioBase<Usuarios> db = new RepositorioBase<Usuarios>();
try
{
Usuario = db.Buscar(IdUsuario);
}
catch (Exception) { }
}
private void limitador()
{
registrarUsuariosToolStripMenuItem.Enabled = false;
}
private void RegistrarUsuariosToolStripMenuItem_Click(object sender, EventArgs e)
{
rUsuario registro = new rUsuario(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void ConsultarUsuariosToolStripMenuItem_Click(object sender, EventArgs e)
{
cUsuarios consulta = new cUsuarios();
consulta.MdiParent = this;
consulta.Show();
}
private void RegistrarClientesToolStripMenuItem_Click(object sender, EventArgs e)
{
rCliente registro = new rCliente(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void RegistrarPesadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
rPesador registro = new rPesador(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void RegistroDeVendedoresToolStripMenuItem_Click(object sender, EventArgs e)
{
rVendedor registro = new rVendedor(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void RegistroDeProductosToolStripMenuItem_Click(object sender, EventArgs e)
{
rProductos registro = new rProductos(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void EntradaDeProductosToolStripMenuItem_Click(object sender, EventArgs e)
{
rEntradaProducto registro = new rEntradaProducto();
registro.MdiParent = this;
registro.Show();
}
private void RegistroDeComprasToolStripMenuItem_Click(object sender, EventArgs e)
{
rCompras registro = new rCompras(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void RegistroDeAgricultoresToolStripMenuItem_Click(object sender, EventArgs e)
{
rAgricultor registro = new rAgricultor(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void RegistroDeVentasToolStripMenuItem_Click(object sender, EventArgs e)
{
rVentas registro = new rVentas(IdUsuario);
registro.MdiParent = this;
registro.Show();
}
private void ConsultarClientesToolStripMenuItem_Click(object sender, EventArgs e)
{
cClientes consulta = new cClientes();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarVendedoresToolStripMenuItem_Click(object sender, EventArgs e)
{
cVendedor consulta = new cVendedor();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarAgriculturesToolStripMenuItem_Click(object sender, EventArgs e)
{
cAgricultor consulta = new cAgricultor();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarPesadoresToolStripMenuItem_Click(object sender, EventArgs e)
{
cPesadores consulta = new cPesadores();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarProductosToolStripMenuItem_Click(object sender, EventArgs e)
{
cProductos consulta = new cProductos();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarComprasToolStripMenuItem_Click(object sender, EventArgs e)
{
cCompras consulta = new cCompras();
consulta.MdiParent = this;
consulta.Show();
}
private void ConsultarVentasToolStripMenuItem_Click(object sender, EventArgs e)
{
cVentas consulta = new cVentas();
consulta.MdiParent = this;
consulta.Show();
}
private void LogoutToolStripMenuItem_Click(object sender, EventArgs e)
{
Login login = new Login();
Dispose();
login.ShowDialog();
}
}
}
|
// --------------------------------------------------------------------------------------------------------------
// <copyright file="LogoutViewModel.cs" company="Tiny开源团队">
// Copyright (c) 2017-2018 Tiny. All rights reserved.
// </copyright>
// <site>http://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2019/3/15 22:22:02</last-date>
// --------------------------------------------------------------------------------------------------------------
namespace Tiny.IdentityService.Models.Account
{
public class LogoutViewModel : LogoutInputModel
{
public bool ShowLogoutPrompt { get; set; } = true;
}
}
|
using System;
using System.Collections.Generic;
namespace maze_core
{
class Program
{
static List<List<int>> maze;
static void Main(string[] args)
{
maze = new List<List<int>>();
maze.Add(new List<int>() { 0, 1, 0, 1 });
maze.Add(new List<int>() { 0, 0, 0, 1 });
maze.Add(new List<int>() { 0, 0, 1, 0 });
maze.Add(new List<int>() { 1, 0, 0, 0 });
List<Position> positions = new List<Position>();
positions.Add(new Position() { column = 0, row = 0 });
var result = solve_maze_helper(maze, ref positions);
result.ForEach(b => Console.Write(string.Format("[{0} , {1}]\t", b.row, b.column)));
}
/*
maze = [
[0, 1, 0, 1],
[0, 0, 0, 1],
[1, 0, 1, 0],
[0, 0, 0, 0]
] */
private static List<Position> solve_maze_helper(List<List<int>> maze, ref List<Position> positions)
{
var position = positions[positions.Count - 1];
if (position.row > maze.Count -1){
return new List<Position>();
}
if (position.column > maze[0].Count -1){
return new List<Position>();
}
if (maze[position.row][position.column] == 1)
{
return new List<Position>();
}
positions.Add(new Position(){row = position.row +1, column = position.column });
var move_right = solve_maze_helper(maze, ref positions);
if(move_right.Count > 0){
return move_right;
}
else{
positions.RemoveAt(positions.Count -1);
}
positions.Add(new Position(){row = position.row, column = position.column +1 });
var move_down = solve_maze_helper(maze, ref positions);
if(move_down.Count > 0){
return move_down;
}
else{
positions.RemoveAt(positions.Count -1);
}
return positions;
}
}
class Position
{
public int row { get; set; }
public int column { get; set; }
}
}
|
using Microsoft.Extensions.Logging;
namespace dotBatchLib
{
public class ItemWriter
{
private readonly ILogger _logger = LibLogging.CreateLogger<ITemReader>();
public void Write()
{
_logger.LogTrace("write");
}
}
} |
using Sandbox.Shared;
using System;
using RuntimeUnitTestToolkit;
using ZeroFormatter.Formatters;
namespace ZeroFormatter.Tests
{
public class ZeroArgumentTest
{
public void Class()
{
var c = ZeroFormatterSerializer.Convert(new ZeroClass());
(c is ZeroClass).IsTrue();
}
public void Struct()
{
var bytes = ZeroFormatterSerializer.Serialize(new ZeroStruct());
bytes.Length.Is(0);
ZeroFormatterSerializer.Deserialize<ZeroStruct>(bytes);
var len = ZeroFormatter.Formatters.Formatter<DefaultResolver, ZeroStruct>.Default.GetLength();
len.IsNotNull();
len.Is(0);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPoolManager : MonoBehaviour
{
private static ObjectPoolManager inst;
public static ObjectPoolManager Inst
{
get
{
return inst;
}
}
public ObjectPool pool;
private void Awake()
{
if (inst)
{
Destroy(gameObject);
return;
}
inst = this;
}
}
|
using System.Collections;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
namespace Domain
{
public class AppUser: IdentityUser
{
public string DisplayName {set; get;}
public string Bio {get; set;}
public ICollection<ActivityAttendee> Activities { get; set; }
public ICollection<Photo> Photos { get; set; }
public ICollection<UserFollowing> Followings { get; set; }
public ICollection<UserFollowing> Followers { get; set; }
public ICollection<RefreshToken> RefresTokens { get; set; }= new List<RefreshToken>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using Entidades;
namespace Datos
{
public class Categoria
{
public IList<Entidades.Categoria> ListarCategoria()
{
Conectividad aux = new Conectividad();
SqlCommand cmd = new SqlCommand();
{
cmd.Connection = aux.conectar();
cmd.CommandText = "spr_listar_categorias";
cmd.CommandType = CommandType.StoredProcedure;
};
SqlDataReader sqlDataReader = cmd.ExecuteReader();
IList<Entidades.Categoria> categoriaList = new List<Entidades.Categoria>();
Entidades.Categoria categoria;
while (sqlDataReader.Read())
{
categoria = new Entidades.Categoria
{
IdCategoria = long.Parse( sqlDataReader["idCategoria"].ToString()),
NombreCategoria = sqlDataReader["nombreCategoria"].ToString().Trim(),
FechaCategoria = DateTime.Parse( sqlDataReader["fechaCategoria"].ToString()),
ActivoCategoria = bool.Parse( sqlDataReader["activoCategoria"].ToString()),
ImagenCategoria = (byte[]) sqlDataReader["imagenCategoria"],
//Activo = bool.Parse(sqlDataReader["activo"].ToString())
//SegundoApellido = sqlDataReader[COLUMN_SEGUNDO_APELLIDO].ToString(),
//FechaNacimiento = new DateTime(),
//Direccion = sqlDataReader[COLUMN_TELEFONO].ToString(),
//Telefono = sqlDataReader[COLUMN_DIRECCION].ToString()
};
categoriaList.Add(categoria);
}
aux.conectar();
return categoriaList;
}
}
}
|
namespace TicTacToe.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Data;
using Data.Repositories;
using GameLogic;
using Services.Controllers;
using Services.DataModels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Models;
using Moq;
using Services.Infrastructure;
[TestClass]
public class PlayActionTests
{
[TestMethod]
public void WhenIsXsTurnChangeGameStateToO()
{
var userId = "some user id";
var newGameId = Guid.NewGuid();
var game = new Game
{
Id = newGameId,
FirstPlayerId = userId,
State = GameState.TurnX
};
var userIdProviderMock = new Mock<IUserIdProvider>();
userIdProviderMock.Setup(x => x.GetUserId())
.Returns(userId);
var repositoryMock = new Mock<IRepository<Game>>();
repositoryMock.Setup(x => x.All())
.Returns(() => new List<Game>()
{
game
}
.AsQueryable());
repositoryMock.Setup(x => x.Find(It.IsAny<Guid>()))
.Returns(game);
var uowData = new Mock<ITicTacToeData>();
uowData.SetupGet(x => x.Games)
.Returns(repositoryMock.Object);
var controller = new GamesController
(
uowData.Object,
new GameResultValidator(),
userIdProviderMock.Object
);
controller.Play(new PlayRequestDataModel()
{
gameId = newGameId.ToString(),
col = 1,
row = 1
});
Assert.AreEqual(GameState.TurnO, game.State);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading;
namespace NamedPipes
{
class Program
{
static Dictionary<EntityId, EntityData> ents_ = new Dictionary<EntityId, EntityData>();
static Dictionary<ModelId, Model> models_ = new Dictionary<ModelId, Model>();
static void OnMsgAddEntity(MsgAddEntity msg)
{
ents_.Add(msg.id, msg.data);
Console.WriteLine("Adding entity: {0}", msg.data.getText());
}
static void OnMsgDeleteEntity(MsgDeleteEntity msg)
{
EntityData data = ents_[msg.id];
Console.WriteLine("Deleting entity: {0}", data.getText());
ents_.Remove(msg.id);
}
static void OnMsgUpdateEntityTransform(MsgUpdateEntityTransform msg)
{
EntityData data = ents_[msg.id];
data.transform = msg.transform;
Console.WriteLine("Updating entity transform: {0}", data.getText());
}
static void OnMsgAddModel(MsgAddModel msg)
{
models_.Add(msg.id, msg.model);
Console.WriteLine("Adding model: {0}, {1} verts", msg.model.name, msg.model.verts.Length);
}
static void OnNextFrame(MsgNextFrame msg)
{
}
static void Main(string[] args)
{
var dispatcher = new Dispatcher();
dispatcher.Add<MsgAddEntity>(0, OnMsgAddEntity);
dispatcher.Add<MsgDeleteEntity>(1, OnMsgDeleteEntity);
dispatcher.Add<MsgUpdateEntityTransform>(2, OnMsgUpdateEntityTransform);
dispatcher.Add<MsgAddModel>(3, OnMsgAddModel);
dispatcher.Add<MsgNextFrame>(100, OnNextFrame);
using (var server = new TcpServer(dispatcher))
{
server.Start();
while(server.isWorking())
{
Thread.Sleep(1000);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project3.Classes.Arrays
{
public sealed class ConstArray : ArrayBase
{
public ConstArray()
{
Name = "Const Array";
}
public override int[] CreateArray(int size)
{
int[] arr = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = 21;
}
return arr;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode.Algorithm.Hard
{
class Candy
{
/// <summary>
/// There are N children standing in a line. Each child is assigned a rating value.
/// You are giving candies to these children subjected to the following requirements:
/// 1. Each child must have at least one candy.
/// 2. Children with a higher rating get more candies than their neighbors.
/// What is the minimum candies you must give?
/// </summary>
/// <param name="ratings"></param>
/// <returns></returns>
public static int MinCandy(int[] ratings)
{
int len = ratings.Length;
if (len <= 1) return len;
int[] count = new int[len];
for (int i = 0; i < len; i++)
{
count[i] = 1;
}
for (int i = 1; i < len; i++)
{
if (ratings[i] > ratings[i - 1])
{
count[i] = count[i - 1] + 1;
}
}
for (int i = ratings.Length - 2; i >= 0; i--)
{
if (ratings[i] > ratings[i + 1])
{
if (count[i] <= count[i + 1])
{
count[i] = count[i + 1] + 1;
}
}
}
int total = 0;
for (int i = 0; i < count.Length; i++)
{
total += count[i];
}
return total;
}
}
}
|
/**************************************************************
** Name : Amanda Lewandowski **
** Due Date : March 31, 2020 **
** Course : CSc 446 - Compiler Construction **
** Instructor : George Hamer **
** Assign No. : 6 - Seq Of Stats **
** File Name : RDParser.CS **
**************************************************************
** Description : This is the RD parser **
*************************************************************/
using System;
using System.Collections.Generic;
namespace LewandowskiA5
{
class Parser
{
public bool isProc = false;
public bool isConst = false;
public SymbolTable ObjTable = new SymbolTable();
public List<string> names = new List<string>();
public ProcedureEntry tempP;
public Stack<ProcedureEntry> procNames = new Stack<ProcedureEntry>();
public List<int> paramTotalSize = new List<int>(0);
public List<int> varTotalSize = new List<int>(0);
public bool isParam = false;
public bool isSOS = false;
public Parser()
{
Vari.myLex.getNextToken(); // prime the parser
Prog();
//ObjTable.A5Display();
if (Vari.Token != Vari.Symbol.eoftt)
{
Console.WriteLine("Error: Unused tokens on line " + Vari.lineNo);
}
else
{
Console.WriteLine("\nCompiled");
}
}
/*************************************************************
** Function : Match **
** Inputs : Symbol **
** Return : Void **
**************************************************************
** Description : Checks if the wantedSymbol is equal to the **
** currentObject Symbol, else Error Message. **
*************************************************************/
void Match(Vari.Symbol desiredSym)
{
if (Vari.Token == desiredSym)
{
if (!isSOS)
{
int namesSize;
switch (Vari.Token)
{
case Vari.Symbol.proceduret:
isProc = true;
break;
case Vari.Symbol.idt:
if (isProc)
{
CheckDuplicates(Vari.Lexeme);
Vari.entryType = EntryType.procEntry;
ObjTable.insert(Vari.Lexeme, Vari.Token, Vari.depth);
newProc(Vari.Lexeme);
}
else
{ names.Add(Vari.Lexeme); }
break;
case Vari.Symbol.integert:
if (isConst)
{
Vari.entryType = EntryType.constEntry;
namesSize = names.Count;
for (int i = 0; i < namesSize; ++i)
{
CheckDuplicates(names[0]);
ObjTable.insert(names[0], Vari.Token, Vari.depth);
newConst(names[0], "integer");
names.RemoveAt(0);
}
isConst = false;
}
else
{
Vari.entryType = EntryType.varEntry;
Vari.varType = VarType.intType;
namesSize = names.Count;
for (int i = 0; i < namesSize; ++i)
{
CheckDuplicates(names[0]);
ObjTable.insert(names[0], Vari.Token, Vari.depth);
newVar(names[0]);
names.RemoveAt(0);
}
}
break;
case Vari.Symbol.floatt:
if (isConst)
{
Vari.entryType = EntryType.constEntry;
namesSize = names.Count;
for (int i = 0; i < namesSize; ++i)
{
CheckDuplicates(names[0]);
ObjTable.insert(names[0], Vari.Token, Vari.depth);
newConst(names[0], "real");
names.RemoveAt(0);
}
isConst = false;
}
else
{
Vari.entryType = EntryType.varEntry;
Vari.varType = VarType.floatType;
namesSize = names.Count;
for (int i = 0; i < namesSize; ++i)
{
CheckDuplicates(names[0]);
ObjTable.insert(names[0], Vari.Token, Vari.depth);
newVar(names[0]);
names.RemoveAt(0);
}
}
break;
case Vari.Symbol.chart:
Vari.entryType = EntryType.varEntry;
Vari.varType = VarType.charType;
namesSize = names.Count;
for (int i = 0; i < namesSize; ++i)
{
CheckDuplicates(names[0]);
ObjTable.insert(names[0], Vari.Token, Vari.depth);
newVar(names[0]);
names.RemoveAt(0);
}
break;
case Vari.Symbol.constantt:
isConst = true;
break;
case Vari.Symbol.ist:
if (isProc)
{
IncrementDepth();
isProc = false;
}
break;
case Vari.Symbol.lparent:
if (isProc)
{
IncrementDepth();
isProc = false;
isParam = true;
}
break;
case Vari.Symbol.rparent:
isParam = false;
break;
case Vari.Symbol.intt:
tempP.passing.Add(ModeType.inMode);
break;
case Vari.Symbol.inoutt:
tempP.passing.Add(ModeType.inoutMode);
break;
case Vari.Symbol.outt:
tempP.passing.Add(ModeType.outMode);
break;
default:
break;
}
}
else
{
if (Vari.Token == Vari.Symbol.idt)
{
int row = ObjTable.hashWrap(Vari.Lexeme);
int col = ObjTable.lookup(Vari.Lexeme);
if (col == -1)
{
Console.WriteLine("Error: there is an undeclared variable: " + Vari.Lexeme + " on line: " + Vari.lineNo);
}
}
}
Vari.myLex.getNextToken();
}
else if (Vari.Token == Vari.Symbol.eoftt)
{
return;
}
else
{
Console.WriteLine("Received: " + Vari.Token + " but expected: " + desiredSym);
Environment.Exit(1);
}
}
/*************************************************************
** Function : Prog **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Prog --> procedure idt Args is **
** DeclarativePart **
** Procedures **
** begin **
** SeqOfStatements **
** end idt; **
*************************************************************/
void Prog()
{
Match(Vari.Symbol.proceduret);
Match(Vari.Symbol.idt);
Args();
Match(Vari.Symbol.ist);
DeclarativePart();
Procedures();
Match(Vari.Symbol.begint);
SeqOfStats();
Match(Vari.Symbol.endt);
EndProc();
Match(Vari.Symbol.idt);
Match(Vari.Symbol.semit);
DecrementDepth();
}
/*************************************************************
** Function : newVar **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : makes a new variable entry **
*************************************************************/
void newVar(string lex)
{
VarEntry temp = new VarEntry();
int subList = ObjTable.lookup(lex);
int mainList = ObjTable.hashWrap(lex);
temp.token = Vari.Token;
temp.lexeme = lex;
temp.depth = Vari.depth;
temp.type = Vari.entryType;
switch (Vari.varType)
{
case VarType.charType:
temp.size = 1;
temp.variableType = VarType.charType;
break;
case VarType.intType:
temp.size = 2;
temp.variableType = VarType.intType;
break;
case VarType.floatType:
temp.size = 4;
temp.variableType = VarType.floatType;
break;
default:
break;
}
if (isParam)
{
paramTotalSize[Vari.depth - 1] += temp.size;
tempP.toparams.Add(temp.variableType);
}
else
{
temp.offset = Vari.offset[Vari.depth - 1];
Vari.offset[Vari.depth - 1] += temp.size;
}
ObjTable.theSymbolTable[mainList][subList] = temp;
}
/*************************************************************
** Function : newConst **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : makes new const entry **
*************************************************************/
void newConst(string lex, string numType)
{
ConstEntry temp = new ConstEntry();
int subList = ObjTable.lookup(lex);
int mainList = ObjTable.hashWrap(lex);
temp.token = Vari.Token;
temp.lexeme = lex;
temp.depth = Vari.depth;
temp.type = Vari.entryType;
switch (numType)
{
case "integer":
temp.iValue = Vari.IntValue;
break;
case "real":
temp.fValue = Vari.RealValue;
break;
}
ObjTable.theSymbolTable[mainList][subList] = temp;
}
/*************************************************************
** Function : newProc **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : makes a new procedure entry **
*************************************************************/
void newProc(string lex)
{
tempP = new ProcedureEntry();
int subList = ObjTable.lookup(lex);
int mainList = ObjTable.hashWrap(lex);
List<int> tempLocs = new List<int>();
tempLocs.Add(mainList);
tempLocs.Add(subList);
tempP.token = Vari.Token;
tempP.lexeme = lex;
tempP.depth = Vari.depth;
tempP.type = Vari.entryType;
tempP.solocals = 0;
tempP.soparams = 0;
tempP.noparams = 0;
tempP.toparams = new List<VarType>();
tempP.passing = new List<ModeType>();
procNames.Push(tempP);
ObjTable.theSymbolTable[mainList][subList] = tempP;
}
/*************************************************************
** Function : endProc **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : closes the procedure entry **
*************************************************************/
void EndProc()
{
tempP.noparams = tempP.toparams.Count;
tempP.solocals = Vari.offset[Vari.depth - 1];
for (int i = 0; i < tempP.toparams.Count; ++i)
{
VarType type = tempP.toparams[i];
if (type == VarType.charType)
{
tempP.soparams += 1;
}
else if (type == VarType.intType)
{
tempP.soparams += 2;
}
else if (type == VarType.floatType)
{
tempP.soparams += 4;
}
}
int subList = ObjTable.lookup(tempP.lexeme);
int mainList = ObjTable.hashWrap(tempP.lexeme);
while (subList < ObjTable.theSymbolTable[mainList].Count && tempP.depth != ObjTable.theSymbolTable[mainList][subList].depth)
{
++subList;
}
ObjTable.theSymbolTable[mainList][subList] = tempP;
if (Vari.Lexeme != tempP.lexeme)
{
Console.WriteLine("Error: The Procedure name: " + tempP.lexeme + " does not match the end procedure name: " + Vari.Lexeme);
Environment.Exit(1);
}
procNames.Pop();
if (procNames.Count != 0)
{
tempP = procNames.Peek();
}
}
/*************************************************************
** Function : Mode **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Mode -> in | out | inout | e **
*************************************************************/
void mode()
{
switch (Vari.Token)
{
case Vari.Symbol.intt:
Match(Vari.Symbol.intt);
break;
case Vari.Symbol.outt:
Match(Vari.Symbol.outt);
break;
case Vari.Symbol.inoutt:
Match(Vari.Symbol.inoutt);
break;
default:
break; // null terminal
}
}
/*************************************************************
** Function : MoreArgs **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** MoreArgs -> ; ArgList | e **
*************************************************************/
void moreArgs()
{
if (Vari.Token == Vari.Symbol.semit)
{
Match(Vari.Symbol.semit);
argList();
}
else
{
return; // null terminal
}
}
/*************************************************************
** Function : ArgList **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** ArgList -> Mode IdentifierList : **
** TypeMark MoreArgs **
*************************************************************/
void argList()
{
mode();
IdentifierList();
Match(Vari.Symbol.colont);
typeMark();
moreArgs();
}
/*************************************************************
** Function : Args **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Args -> ( ArgList ) | e **
*************************************************************/
void Args()
{
if (Vari.Token == Vari.Symbol.lparent)
{
Match(Vari.Symbol.lparent);
argList();
Match(Vari.Symbol.rparent);
}
else
{
return; // null
}
}
/*************************************************************
** Function : Procedures **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Procedures -> Prog Procedures | e **
*************************************************************/
void Procedures()
{
// procedures -> prog procedures | e
if (Vari.Token == Vari.Symbol.proceduret)
{
Prog();
Procedures();
}
else
{
return;
}
}
/*************************************************************
** Function : Value **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Value --> NumericalLiteral **
*************************************************************/
void value()
{
switch (Vari.Token)
{
case Vari.Symbol.integert:
Match(Vari.Symbol.integert);
break;
case Vari.Symbol.floatt:
Match(Vari.Symbol.floatt);
break;
case Vari.Symbol.literal:
Match(Vari.Symbol.literal);
break;
case Vari.Symbol.chart:
Match(Vari.Symbol.chart);
break;
default:
Console.WriteLine(" !! ERROR: Unexpected type on line " + Vari.lineNo);
Environment.Exit(1);
break;
}
}
/*************************************************************
** Function : TypeMark **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** TypeMark --> integert, realt, chart, **
** const assignop Value **
*************************************************************/
void typeMark()
{
switch (Vari.Token)
{
case Vari.Symbol.integert:
Match(Vari.Symbol.integert);
break;
case Vari.Symbol.floatt:
Match(Vari.Symbol.floatt);
break;
case Vari.Symbol.chart:
Match(Vari.Symbol.chart);
break;
case Vari.Symbol.constantt:
Match(Vari.Symbol.constantt);
break;
default:
Console.WriteLine("!! ERROR: Unexpected type on line " + Vari.lineNo);
Environment.Exit(1);
break;
}
if (Vari.Token == Vari.Symbol.assignopt)
{
Match(Vari.Symbol.assignopt);
value();
}
else
return; // null term
}
/*************************************************************
** Function : IdentifierList **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** IdentifierList --> idt | **
** IdentifierList , idt **
*************************************************************/
void IdentifierList()
{
// idList -> idt | idList , idt
Match(Vari.Symbol.idt);
if (Vari.Token == Vari.Symbol.commat)
{
Match(Vari.Symbol.commat);
IdentifierList();
}
}
/*************************************************************
** Function : DeclarativePart **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** DeclarativePart --> IdentifierList : **
** TypeMark ; **
** DeclarativePart | e **
*************************************************************/
void DeclarativePart()
{
if (Vari.Token == Vari.Symbol.idt)
{
IdentifierList();
Match(Vari.Symbol.colont);
typeMark();
Match(Vari.Symbol.semit);
DeclarativePart();
}
else
return;
}
/*************************************************************
** Function : SeqofStats **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** SeqofStats --> empty **
*************************************************************/
void SeqOfStats()
{
if (Vari.Token == Vari.Symbol.idt)
{
isSOS = true;
Statement();
Match(Vari.Symbol.semit);
StatTail();
isSOS = false;
}
else { return; }
}
/*************************************************************
** Function : StatTail **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** StatTail --> Statement ; StatTail | E **
*************************************************************/
void StatTail()
{
if (Vari.Token == Vari.Symbol.idt)
{
Statement();
Match(Vari.Symbol.semit);
StatTail();
}
else { return; }
}
/*************************************************************
** Function : Statement **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Statement --> AssignStat | IOStat **
*************************************************************/
void Statement()
{
if (Vari.Token == Vari.Symbol.idt)
{
AssignStat();
}
else
{
IOStat();
}
}
/*************************************************************
** Function : AssignStat **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** AssignStat --> idt := Expr **
*************************************************************/
void AssignStat()
{
Match(Vari.Symbol.idt);
Match(Vari.Symbol.assignopt);
Expr();
}
/*************************************************************
** Function : IOStat **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** IOStat --> E **
*************************************************************/
void IOStat()
{
// null
}
/*************************************************************
** Function : Expr **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Expr --> Relation **
*************************************************************/
void Expr()
{
Relation();
}
/*************************************************************
** Function : Relation **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Relation --> SimpleExpr **
*************************************************************/
void Relation()
{
SimpleExpr();
}
/*************************************************************
** Function : SimpleExpr **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** SimpleExpr --> Term MoreTerm **
*************************************************************/
void SimpleExpr()
{
Term();
MoreTerm();
}
/*************************************************************
** Function : MoreTerm **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** MoreTerm --> addopt Term MoreTerm | E **
*************************************************************/
void MoreTerm()
{
if (Vari.Token == Vari.Symbol.addopt || Vari.Token == Vari.Symbol.signopt)
{
if (Vari.Token == Vari.Symbol.addopt)
{
Match(Vari.Symbol.addopt);
}
else
{
Match(Vari.Symbol.signopt);
}
Term();
MoreTerm();
}
else { return; }
}
/*************************************************************
** Function : Term **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Term --> Factor MoreFactor **
*************************************************************/
void Term()
{
Factor();
MoreFactor();
}
/*************************************************************
** Function : MoreFactor **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** MoreFactor --> mulopt Factor MoreFactor | E**
*************************************************************/
void MoreFactor()
{
if (Vari.Token == Vari.Symbol.mulopt)
{
Match(Vari.Symbol.mulopt);
Factor();
MoreFactor();
}
else
{
//null
}
}
/*************************************************************
** Function : Factor **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Completes the Grammar: **
** Factor --> idt | numt | ( Expr ) | **
** nott Factor | signopt Factor **
*************************************************************/
void Factor()
{
if (Vari.Token == Vari.Symbol.idt)
{
Match(Vari.Symbol.idt);
}
else if (Vari.Token == Vari.Symbol.floatt)
{
Match(Vari.Symbol.floatt);
}
else if (Vari.Token == Vari.Symbol.integert)
{
Match(Vari.Symbol.integert);
}
else if (Vari.Token == Vari.Symbol.lparent)
{
Match(Vari.Symbol.lparent);
Expr();
Match(Vari.Symbol.rparent);
}
else if (Vari.Token == Vari.Symbol.nott)
{
Match(Vari.Symbol.nott);
Factor();
}
else if (Vari.Token == Vari.Symbol.signopt)
{
Match(Vari.Symbol.signopt);
Factor();
}
}
/*************************************************************
** Function : IncrementDepth **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Increments the depth **
*************************************************************/
void IncrementDepth()
{
Vari.offset.Add(0);
paramTotalSize.Add(0);
varTotalSize.Add(0);
Vari.depth++;
}
/*************************************************************
** Function : DecrementDepth **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : Decrements the depth **
*************************************************************/
void DecrementDepth()
{
// ObjTable.A5Display();
ObjTable.deleteDepth(Vari.depth);
Vari.offset.RemoveAt(Vari.depth - 1);
Vari.depth--;
}
/*************************************************************
** Function : CheckDuplicates **
** Inputs : None **
** Return : Void **
**************************************************************
** Description : checks for duplicates **
*************************************************************/
void CheckDuplicates(string lex)
{
int x = ObjTable.hashWrap(lex);
for (int i = 0; i < ObjTable.theSymbolTable[x].Count; ++i)
{
EntryNode temp = ObjTable.theSymbolTable[x][i];
if (temp.depth == Vari.depth && lex == temp.lexeme)
{
Console.WriteLine("Error: There is a duplicate id: " + lex + " on line: " + Vari.lineNo);
}
}
}
}
}
|
using System.Collections.Generic;
namespace CheckMySymptoms.Forms.View.Common
{
public class AboutFormSettingsView
{
public string Title { get; set; }
public RequestDetailsView RequestDetails { get; set; }
public DataRequestStateView State { get; set; }
public List<DetailItemView> FieldSettings { get; set; }
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Web.UI.WebControls;
#endregion
namespace DotNetNuke.UI.WebControls
{
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.UI.WebControls
/// Class: DNNDataGrid
/// -----------------------------------------------------------------------------
/// <summary>
/// The DNNDataGrid control provides an Enhanced Data Grid, that supports other
/// column types
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class DNNDataGrid : DataGrid
{
#region "Events"
public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged;
#endregion
#region "Private Methods"
/// -----------------------------------------------------------------------------
/// <summary>
/// Centralised Event that is raised whenever a check box is changed.
/// </summary>
/// -----------------------------------------------------------------------------
private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e)
{
if (ItemCheckedChanged != null)
{
ItemCheckedChanged(sender, e);
}
}
#endregion
#region "Protected Methods"
/// -----------------------------------------------------------------------------
/// <summary>
/// Called when the grid is Data Bound
/// </summary>
/// -----------------------------------------------------------------------------
protected override void OnDataBinding(EventArgs e)
{
foreach (DataGridColumn column in Columns)
{
if (ReferenceEquals(column.GetType(), typeof (CheckBoxColumn)))
{
//Manage CheckBox column events
var cbColumn = (CheckBoxColumn) column;
cbColumn.CheckedChanged += OnItemCheckedChanged;
}
}
}
protected override void CreateControlHierarchy(bool useDataSource)
{
base.CreateControlHierarchy(useDataSource);
}
protected override void PrepareControlHierarchy()
{
base.PrepareControlHierarchy();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SIPCA.CLASES.Models
{
[Table("Marca")]
public class Marca
{
[Key]
public int IdMarca { get; set; }
[Index("INDEX_MARCA_NOMBRE", IsUnique = true)]
[Required(ErrorMessage = "Se requiere el {0}")]
[Display(Name = "Nombre de la marca")]
public string Nombre { get; set; }
public virtual IEnumerable<Producto> Productos { get; set; }
[ScaffoldColumn(false)]
[Timestamp]
public byte[] Control { get; set; }
[ScaffoldColumn(false)]
public bool Eliminado { get; set; }
}
}
|
using Lab12_HotelDataBase.Models;
using Lab12_HotelDataBase.Models.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lab12_HotelDataBase.Data.Repositories
{
public interface IAmenitiesRepository
{
Task<IEnumerable<AmenitiesDTO>> GetAllAmenities();
Task<AmenitiesDTO> GetOneAmenity(int id);
Task<bool> UpdateAmenity(int id, Amenities amenities);
Task<AmenitiesDTO> SaveNewAmenity(Amenities amenities);
Task<Amenities> DeleteAmenity(int id);
bool AmenityExists(int id);
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using System.Collections.Specialized;
using System.Web.UI;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Instrumentation;
using DotNetNuke.Services.Localization;
#endregion
namespace DotNetNuke.UI.WebControls
{
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.UI.WebControls
/// Class: TrueFalseEditControl
/// -----------------------------------------------------------------------------
/// <summary>
/// The TrueFalseEditControl control provides a standard UI component for editing
/// true/false (boolean) properties.
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
[ToolboxData("<{0}:TrueFalseEditControl runat=server></{0}:TrueFalseEditControl>")]
public class TrueFalseEditControl : EditControl
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (TrueFalseEditControl));
#region "Constructors"
/// -----------------------------------------------------------------------------
/// <summary>
/// Constructs a TrueFalseEditControl
/// </summary>
/// -----------------------------------------------------------------------------
public TrueFalseEditControl()
{
SystemType = "System.Boolean";
}
#endregion
#region "Public Properties"
/// -----------------------------------------------------------------------------
/// <summary>
/// BooleanValue returns the Boolean representation of the Value
/// </summary>
/// <value>A Boolean representing the Value</value>
/// -----------------------------------------------------------------------------
protected bool BooleanValue
{
get
{
bool boolValue = Null.NullBoolean;
try
{
//Try and cast the value to an Boolean
boolValue = Convert.ToBoolean(Value);
}
catch (Exception exc)
{
Logger.Error(exc);
}
return boolValue;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// OldBooleanValue returns the Boolean representation of the OldValue
/// </summary>
/// <value>A Boolean representing the OldValue</value>
/// -----------------------------------------------------------------------------
protected bool OldBooleanValue
{
get
{
bool boolValue = Null.NullBoolean;
try
{
//Try and cast the value to an Boolean
boolValue = Convert.ToBoolean(OldValue);
}
catch (Exception exc)
{
Logger.Error(exc);
}
return boolValue;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// StringValue is the value of the control expressed as a String
/// </summary>
/// <value>A string representing the Value</value>
/// -----------------------------------------------------------------------------
protected override string StringValue
{
get
{
return BooleanValue.ToString();
}
set
{
bool setValue = bool.Parse(value);
Value = setValue;
}
}
#endregion
#region "Protected Methods"
/// -----------------------------------------------------------------------------
/// <summary>
/// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged
/// Event
/// </summary>
/// -----------------------------------------------------------------------------
protected override void OnDataChanged(EventArgs e)
{
var args = new PropertyEditorEventArgs(Name);
args.Value = BooleanValue;
args.OldValue = OldBooleanValue;
args.StringValue = StringValue;
base.OnValueChanged(args);
}
/// -----------------------------------------------------------------------------
/// <summary>
/// RenderEditMode renders the Edit mode of the control
/// </summary>
/// <param name="writer">A HtmlTextWriter.</param>
/// -----------------------------------------------------------------------------
protected override void RenderEditMode(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
if ((BooleanValue))
{
writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
}
writer.AddAttribute(HtmlTextWriterAttribute.Value, "True");
writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
ControlStyle.AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(Localization.GetString("True", Localization.SharedResourceFile));
writer.RenderEndTag();
writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
if ((!BooleanValue))
{
writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
}
writer.AddAttribute(HtmlTextWriterAttribute.Value, "False");
writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
ControlStyle.AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(Localization.GetString("False", Localization.SharedResourceFile));
writer.RenderEndTag();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ITDepartment.Attributes;
namespace ITDepartment.Controllers
{
[Authorized]
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ViewBag.Title = "Home Index";
return View();
}
}
} |
using SGA.Models;
using System.Data.Entity.ModelConfiguration;
using System.Web;
namespace SGA.EntitiesConfig
{
public class VoluntarioConfig : EntityTypeConfiguration<Voluntario>
{
public VoluntarioConfig()
{
HasKey(v => v.VoluntarioId);
// Map(t => t.MapInheritedProperties().ToTable("Voluntario"));
Property(t => t.Cpf).HasMaxLength(11);
Property(t => t.Nome).HasMaxLength(30);
Property(t => t.Sobrenome).HasMaxLength(100);
}
}
} |
using ALM.Reclutamiento.Entidades;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ALM.Reclutamiento.Negocio
{
public class NFuncionesHttpClient
{
private object newItem = null;
public object NewItem
{
get
{
return newItem;
}
set
{
newItem = value;
}
}
public async Task ObtenerVoid(string consulta, int idEmpresa)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(EClaseEstatica.LstParametro.Find(x => x.Nombre == "URLServicio").Valor);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync(consulta);
if (response.IsSuccessStatusCode)
{
}
}
}
public async Task ObtenerEntidad<T>(string consulta, int idEmpresa) where T : class
{
using (var client = new HttpClient())
{
NewItem = null;
client.BaseAddress = new Uri(EClaseEstatica.LstParametro.Find(x => x.Nombre == "URLServicio").Valor);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var consultaremplazo = consulta.Replace("+","__");
// HTTP GET
HttpResponseMessage response = await client.GetAsync(consultaremplazo);
if (response.IsSuccessStatusCode)
{
newItem = await response.Content.ReadAsAsync<T>();
}
}
}
public async Task ObtenerListaEntidad<T>(string consulta, int idEmpresa) where T : class
{
using (var client = new HttpClient())
{
NewItem = null;
client.BaseAddress = new Uri(EClaseEstatica.LstParametro.Find(x => x.Nombre == "URLServicio").Valor);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync(consulta);
if (response.IsSuccessStatusCode)
{
newItem = await response.Content.ReadAsAsync<List<T>>();
}
}
}
public async Task Insertar<T>(string consulta, object objInsertar, int idEmpresa)
{
using (var client = new HttpClient())
{
NewItem = null;
client.BaseAddress = new Uri(EClaseEstatica.LstParametro.Find(x => x.Nombre == "URLServicio").Valor);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
HttpResponseMessage response = await client.PostAsJsonAsync(consulta, objInsertar);
if (response.IsSuccessStatusCode)
{
newItem = await response.Content.ReadAsAsync<T>();
}
}
}
public async Task Actualizar<T>(string consulta, object objInsertar, int idEmpresa)
{
using (var client = new HttpClient())
{
NewItem = null;
client.BaseAddress = new Uri(EClaseEstatica.LstParametro.Find(x => x.Nombre == "URLServicio").Valor);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP PUT
HttpResponseMessage response = await client.PutAsJsonAsync(consulta, objInsertar);
if (response.IsSuccessStatusCode)
{
newItem = await response.Content.ReadAsAsync<T>();
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.Remote
{
/**
* The credentials for a remote user
*
* @since 13.0.0
*/
public interface ICredentials
{
/**
* @return string
*
* @since 13.0.0
*/
string getUsername();
/**
* @return string
*
* @since 13.0.0
*/
string getPassword();
}
}
|
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Transactions;
using Microsoft.Practices.TransientFaultHandling;
namespace ReliableDbProvider.Tests.SqlExpress
{
public class SqlExpressTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
public bool IsTransient(Exception ex)
{
if (ex is TransactionException)
ex = ex.InnerException;
// Is the error an error 17142 - The service is paused
// Is the error an error 233 - Connection error when the process isn't responding
var sqlException = ex as SqlException;
return sqlException != null
&& sqlException.Errors.Cast<SqlError>().Any(error => error.Number == 17142 || error.Number == 233);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace Wc3Engine
{
public class JassFunction
{
public string functionName;
private int _Count;
public List<string> list;
private static List<string> stack = new List<string>();
public JassFunction(string funcName, string arguments)
{
if (!Exist(Jass.FuntionPreffix + funcName))
{
functionName = Jass.FuntionPreffix + funcName;
list = new List<string>
{
"",
"function " + functionName + " takes " + arguments + " returns nothing",
"endfunction"
};
stack.Add(functionName + " endfunction");
}
}
public int Count
{
get { return _Count; }
}
public static bool Exist(string funcName)
{
return -1 != stack.IndexOf(Jass.FuntionPreffix + funcName + " endfunction");
}
public static int IndexOf(string funcName)
{
return stack.IndexOf(Jass.FuntionPreffix + funcName + " endfunction");
}
public void Remove()
{
stack.Remove(list.Find(x => x.Contains("function " + functionName)));
list.TrimExcess();
list = null;
functionName = null;
}
public void InsertCall(int index, string code)
{
if (list.Exists(x => x.Contains(" call " + code)))
list.Remove(" call " + code);
else
_Count++;
if (index > list.Count)
index = list.Count;
else
index = index + 2;
list.Insert(index, " call " + code);
}
}
public class AbilityStruct
{
private string structName;
private string suffix;
private int _Count;
public List<string> list;
public JassFunction OnInit;
public List<string> stackFunc;
public List<JassFunction> functions;
private static List<string> stack = new List<string>();
public AbilityStruct(string abilityName, string abilitySuffix)
{
if (!Exist())
{
structName = abilityName;
suffix = abilitySuffix;
stack.Add("// Ability: " + structName);
functions = new List<JassFunction>();
stackFunc = new List<string>();
list = new List<string>()
{
"",
"// Ability: " + structName + " " + suffix,
"//===========================================================================",
"// struct " + structName + " begins",
"// struct " + structName + " ends",
};
OnInit = new JassFunction(structName + "_Init", "nothing");
//OnInit.InsertCall(OnInit.Count, "Wc3Engine_System_DefineAbility()");
Jass.Wc3EngineInit.InsertCall(Jass.Wc3EngineInit.Count, "ExecuteFunc(\"" + Jass.FuntionPreffix + structName + "_Init" + "\")");
}
}
public int Count
{
get { return _Count; }
}
public bool Exist()
{
return stack.Exists(x => x.Contains("// Ability: " + structName + " " + suffix));
}
public bool FunctionExist(string funcName)
{
return -1 != stackFunc.IndexOf(Jass.FuntionPreffix + structName + funcName + " endfunction");
}
public int IndexOfFunction(string funcName)
{
return stackFunc.IndexOf(Jass.FuntionPreffix + structName + funcName + " endfunction");
}
public void Remove()
{
foreach (JassFunction func in functions)
func.Remove();
stack.Remove("// Ability: " + structName);
stackFunc.TrimExcess();
list.TrimExcess();
functions.TrimExcess();
stackFunc = null;
list = null;
functions = null;
structName = null;
}
public JassFunction InsertFunction(int index, string funcName, string arguments)
{
if (FunctionExist(funcName))
{
int funcIndex = IndexOfFunction(funcName);
functions[funcIndex].Remove();
functions.Remove(functions[funcIndex]);
stackFunc.RemoveAt(funcIndex);
}
else
_Count++;
if (index > functions.Count)
index = functions.Count;
stackFunc.Insert(index, Jass.FuntionPreffix + structName + funcName + " endfunction");
functions.Insert(index, new JassFunction(structName + funcName, arguments));
return functions[index];
}
}
public class Jass
{
public static JassFunction Wc3EngineInit;
public static List<string> script;
public static string FuntionPreffix
{
get { return "Wc3Engine_"; }
}
public static string Identifier
{
get { return "//" + Wc3Engine.This.aboutBox.AssemblyProduct + " build code:"; }
}
public static string[] Header
{
get
{
return new string[]
{
"//===========================================================================",
"// Map name: " + WTS.Get(W3I.mapName),
"// Map Author: " + WTS.Get(W3I.mapAutor),
"// Date: " + DateTime.Now.ToString(),
"//==========================================================================="
};
}
}
public static void Read()
{
if (script != null)
{
script.TrimExcess();
script = null;
}
script = MPQ.File.ReadScript("war3map.j", Map.mpq);
if (script.Exists(x => x.Contains(Identifier)))
{
int index = script.IndexOf(script.Find(x => x.Contains(Identifier)));
script.RemoveRange(index - 1, script.Count - index + 1);
}
script.Add("");
script.Add(Identifier);
if (null != Wc3EngineInit)
Wc3EngineInit.Remove();
Wc3EngineInit = new JassFunction("Init", "nothing");
foreach (string function in JassScript.InitList)
Wc3EngineInit.InsertCall(Wc3EngineInit.Count, "ExecuteFunc(\"" + function + "\")");
InsertCallToMainFunction("ExecuteFunc(\"" + FuntionPreffix + "Init\")");
//MainSystemScript = MPQ.File.ReadScript(Properties.Resources.MainSystem);
//Wc3Engine.DebugMsg(script.Count.ToString());
//Wc3Engine.DebugMsg(MainSystemScript.Count.ToString());
}
public static void InsertCallToMainFunction(string code)
{
int index = script.IndexOf("function main takes nothing returns nothing");
for (; !script[index].Contains("endfunction"); index++)
{
if (script[index].Contains(code))
{
script.RemoveAt(index);
break;
}
}
script.Insert(index, " call " + code);
}
}
}
|
using System;
using System.Reflection;
using System.Net.Sockets;
using System.Globalization;
namespace RTServer
{
public class RTConverter
{
/// <summary>
/// Converts the parameters.
/// </summary>
public static object[] ConvertParams(object[] startParams, ParameterInfo[] targetParams){
object[] endParamaters = new object[targetParams.Length];
if(startParams.Length == targetParams.Length){
for(int i = 0; i < targetParams.Length; i++){
try{
if(targetParams[i].ParameterType == typeof(Int32)){
endParamaters[i] = System.Convert.ToInt32(startParams[i]);
}else if(targetParams[i].ParameterType == typeof(float)){
endParamaters[i] = float.Parse (startParams[i].ToString(), CultureInfo.InvariantCulture.NumberFormat);
} else if(targetParams[i].ParameterType == typeof(String)){
endParamaters[i] = startParams[i];
} else if(targetParams[i].ParameterType == typeof(Socket)){
endParamaters[i] = startParams[i];
} else {
Debug.LogWarning("Paramater is not a valid RPC call type!");
return null;
}
}catch(Exception){
Debug.LogWarning("Paramater " + i + " does not match target type");
return null;
}
}
return endParamaters;
} else {
Debug.LogWarning("Paramaters count do not match for RPC!");
return null;
}
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class ButtonManager : MonoBehaviour
{
public void OnButtonPressPlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void OnButtonPRessPlay()
{
SceneManager.LoadScene("SampleScene");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
class a_very_big_sum : Challenge
{
public override void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp, Int32.Parse);
long sum = 0;
foreach (var x in arr)
sum += x;
Console.WriteLine(sum);
}
public a_very_big_sum()
{
Name = "A Very Big Sum";
Path = "a-very-big-sum";
Difficulty = Difficulty.Easy;
Domain = Domain.Algorithms;
Subdomain = Subdomain.Warmup;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using ExampleAPI.DataModel;
namespace ExampleAPI.DAL
{
public class AnotherGenericRepository : IGenericRepository
{
private readonly AdviceMailscoopEntities _context;
public AnotherGenericRepository()
{
_context = new AdviceMailscoopEntities();
}
public void Add<T>(T entity) where T : class
{
CheckForNullEntity(entity);
GetDatabaseSet<T>().Add(entity);
}
public void AddRange<T>(IEnumerable<T> entities) where T : class
{
var autoDetectChangesEnabled = _context.Configuration.AutoDetectChangesEnabled;
//temporarily switch it off to improve performance during our bulk add
_context.Configuration.AutoDetectChangesEnabled = false;
foreach (var entity in entities)
{
GetDatabaseSet<T>().Add(entity);
}
//now switch it back on again
_context.Configuration.AutoDetectChangesEnabled = autoDetectChangesEnabled;
}
public void Delete<T>(T entity) where T : class
{
CheckForNullEntity(entity);
GetDatabaseSet<T>().Remove(entity);
}
public void Update<T>(T entity) where T : class
{
_context.Entry(entity).State = EntityState.Modified;
}
public T GetById<T>(object id) where T : class
{
return GetDatabaseSet<T>().Find(id);
}
public IEnumerable<T> All<T>() where T : class
{
return GetDatabaseSet<T>().AsEnumerable();
}
private DbSet<T> GetDatabaseSet<T>() where T : class
{
return _context.Set<T>();
}
private static void CheckForNullEntity<T>(T entity) where T : class
{
if (entity == null)
{
throw new ArgumentNullException(typeof(T).Name);
}
}
}
} |
using System.Security.Claims;
using GraphQL.Types;
using Im.Access.GraphPortal.Repositories;
namespace Im.Access.GraphPortal.Graph.OperationalGroup.Queries
{
public class OperationalQueryType : ObjectGraphType
{
public OperationalQueryType(
ICircuitBreakerPolicyRepository circuitBreakerPolicyRepository,
IChaosPolicyRepository chaosPolicyRepository)
{
Name = "Operations";
Description = "Query operations scoped to service operations";
FieldAsync<ListGraphType<CircuitBreakerPolicyType>>(
"CircuitBreakerPolicies",
"Gets the circuit breaker policies.",
resolve: async (fieldContext) =>
{
return await circuitBreakerPolicyRepository
.GetAllAsync(
fieldContext.UserContext as ClaimsPrincipal,
"",
fieldContext.CancellationToken);
});
FieldAsync<ListGraphType<ChaosPolicyType>>(
"ChaosPolicies",
"Gets the chaos policies.",
resolve: async (fieldContext) =>
{
return await chaosPolicyRepository
.GetAllAsync(
fieldContext.UserContext as ClaimsPrincipal,
"",
fieldContext.CancellationToken);
});
}
}
}
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
public class InventoryIconAC
{
// Use this for initialization
void Start () {
/* InitLiveAnimation();
float s = this.gameObject.transform.localScale.x;
UILabel label = this.gameObject.GetComponent<UILabel>();
List<string> filteredlist = new List<string>();
string[] list = label.text.Split(';');
filteredlist.AddRange(list);
filteredlist.RemoveAll(str => String.IsNullOrEmpty(str));
string itemtype = filteredlist[0];
*/
//Our UILabel that we get the string from has ALL of the possible bindable fields from ANY baseitem. These fields will be blank if they aren't used. Example: the Weapon object
//has the blade,guard, etc fields, which will contain strings for those texture names, and an ItemType, but its "armor" fields will be blank, as it is a weapon object and only set
//the weapon related fields.
//We then parse this string and remove all the unused empty strings, and we maintain our element order and use it below.
//(ALL baseitems have an itemtype set in their constructors, and it is ALWAYS the first
//element of the array),
/* if(itemtype=="Weapon")
{
// _liveAnimation.SwapTexture("Blades", "l_blade1", "Blades", filteredlist[1]);
// _liveAnimation.SwapTexture("Guards", "l_guard1", "Guards", filteredlist[2]);
// _liveAnimation.Play("Weapon");
}
else if(itemtype=="Chest")
{
// _liveAnimation.SwapTexture("Guards", "l_guard1", "Guards", filteredlist[1]);
// _liveAnimation.Play("Chest");
}
*/
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using GalaSoft.MvvmLight;
using System.Windows.Input;
using Xamarin.Forms;
using NoteTaker1.Data.ViewModel;
using Microsoft.Practices.ServiceLocation;
namespace NoteTaker1.Data
{
public class TabbedHomeViewModel : ViewModelBase
{
public ICommand RemindersButtonCommand { get; private set; }
public ICommand PromptingButtonCommand { get; private set; }
public ICommand MappingButtonCommand { get; private set; }
public ICommand SettingsButtonCommand { get; private set; }
public TabbedHomeViewModel(IMyNavigationService navigationService)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Ex03.GarageLogic
{
public class ValueOutOfRangeException : Exception
{
private float m_MinValue;
private float m_MaxValue;
public ValueOutOfRangeException(float i_StartOfRange, float i_EndOfRange, string i_Message)
: base(i_Message)
{
m_MinValue = i_StartOfRange;
m_MaxValue = i_EndOfRange;
}
public ValueOutOfRangeException(float i_StartOfRange, float i_EndOfRange, string i_Message, Exception innerException)
: base(i_Message, innerException)
{
m_MinValue = i_StartOfRange;
m_MaxValue = i_EndOfRange;
}
public float MinValue
{
get { return m_MinValue; }
set { m_MinValue = value; }
}
public float MaxValue
{
get { return m_MaxValue; }
set { m_MaxValue = value; }
}
}
} |
/********************************************************************
* 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;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Framework.Db;
using Framework.Utils;
namespace Framework.Metadata
{
/// <summary>
/// Class for managing multilanguage texts
/// </summary>
public class CxMultilanguage
{
//-------------------------------------------------------------------------
/// <summary>
/// Predefined object type codes.
/// </summary>
public const string OTC_TEXT = "Text";
public const string OTC_ERROR = "Error";
//-------------------------------------------------------------------------
/// <summary>
/// Predefined property codes.
/// </summary>
public const string PC_TEXT = "Text";
//-------------------------------------------------------------------------
public const string DEFAULT_LANGUAGE = "EN"; // Default language code
//-------------------------------------------------------------------------
protected CxMetadataHolder m_Holder = null;
protected string m_ApplicationCode = null;
protected string m_LocalizationApplicationCode = null;
protected string m_LanguageCode = DEFAULT_LANGUAGE;
protected bool m_IsLoaded = false;
private Hashtable m_ObjectProperties = new Hashtable();
private Hashtable m_LocalizedValues = new Hashtable();
private Hashtable m_DictionaryValues = new Hashtable();
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/// <summary>
/// Constructor
/// </summary>
public CxMultilanguage(CxMetadataHolder holder)
{
m_Holder = holder;
m_ApplicationCode = m_Holder.ApplicationCode;
}
//-------------------------------------------------------------------------
/// <summary>
/// Reads multilanguage data from the database
/// </summary>
public void ReadFromDatabase(CxDbConnection connection, string localizationApplicationCode)
{
m_LocalizationApplicationCode = localizationApplicationCode;
if (CxUtils.IsEmpty(m_LocalizationApplicationCode))
{
m_LocalizationApplicationCode = m_ApplicationCode;
}
string appCode = Convert.ToString( m_Holder.SlSections.JsAppProperties["app_name"]);
if (string.IsNullOrWhiteSpace(appCode))
appCode = m_LocalizationApplicationCode;
// Load object type and property dictionary
ObjectProperties.Clear();
DataTable dtObjectProperties = new DataTable();
connection.GetQueryResult(
dtObjectProperties,
@"select t.*
from Framework_LocalizationObjectProperties t
where t.ApplicationCd = :ApplicationCd OR t.ApplicationCd = :AppCode",
m_LocalizationApplicationCode, appCode);
foreach (DataRow dr in dtObjectProperties.Rows)
{
string key = dr["ObjectTypeCd"].ToString().ToUpper() + "." +
dr["PropertyCd"].ToString().ToUpper();
string value = dr["Name"].ToString();
ObjectProperties[key] = value;
}
// Load localized values
LocalizedValues.Clear();
DataTable dtLocalizedValues = new DataTable();
connection.GetQueryResult(
dtLocalizedValues,
@"select t.*
from Framework_LocalizedValues t
where t.ApplicationCd = :ApplicationCd OR t.ApplicationCd = :AppCode",
m_LocalizationApplicationCode, appCode);
foreach (DataRow dr in dtLocalizedValues.Rows)
{
string key = dr["LanguageCd"].ToString().ToUpper() + "." +
dr["ObjectTypeCd"].ToString().ToUpper() + "." +
dr["PropertyCd"].ToString().ToUpper() + "." +
dr["ObjectName"].ToString().ToUpper();
string value = dr["Value"].ToString();
LocalizedValues[key] = value;
}
// Load localization dictionary values
DictionaryValues.Clear();
DataTable dtDictionaryValues = new DataTable();
connection.GetQueryResult(
dtDictionaryValues,
@"select t.*
from Framework_LocalizationDictionary t
where t.ApplicationCd = :ApplicationCd OR t.ApplicationCd = :AppCode",
m_LocalizationApplicationCode, appCode);
foreach (DataRow dr in dtDictionaryValues.Rows)
{
string key = dr["LanguageCd"].ToString().ToUpper() + "." +
dr["DefaultValue"].ToString().ToUpper();
string value = dr["Value"].ToString();
DictionaryValues[key] = value;
}
IsLoaded = true;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns localized value for the given object type, property and object name.
/// Returns null if value is not localized.
/// </summary>
/// <param name="languageCode">language code</param>
/// <param name="objectTypeCode">code of object type</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object unique name</param>
/// <param name="defaultValue">current (default) property value</param>
/// <returns>localized value</returns>
public string GetLocalizedValue(
string languageCode,
string objectTypeCode,
string propertyCode,
string objectName,
string defaultValue)
{
if (IsLocalizable(objectTypeCode, propertyCode))
{
string key = CxText.ToUpper(languageCode) + "." +
CxText.ToUpper(objectTypeCode) + "." +
CxText.ToUpper(propertyCode) + "." +
CxText.ToUpper(objectName);
string value = (string)LocalizedValues[key];
if (value == null)
{
key = CxText.ToUpper(languageCode) + "." +
CxText.ToUpper(defaultValue);
value = (string)DictionaryValues[key];
}
//string keyDefault = CxText.ToUpper("EN") + "." +
// CxText.ToUpper(objectTypeCode) + "." +
// CxText.ToUpper(propertyCode) + "." +
// CxText.ToUpper(objectName);
//if (LocalizedValues[keyDefault] == null)
// LocalizedValues[keyDefault] = defaultValue;
return value;
}
return null;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns localized value for the given object type, property and object name.
/// Returns null if value is not localized.
/// </summary>
/// <param name="objectTypeCode">code of object type</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object unique name</param>
/// <param name="defaultValue">current (default) property value</param>
/// <returns>localized value</returns>
public string GetLocalizedValue(
string objectTypeCode,
string propertyCode,
string objectName,
string defaultValue)
{
return GetLocalizedValue(LanguageCode, objectTypeCode, propertyCode, objectName, defaultValue);
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns localized value for the given object type, property and object name.
/// Returns currentValue if value is not localized.
/// </summary>
/// <param name="languageCode">language code</param>
/// <param name="objectTypeCode">code of object type</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object unique name</param>
/// <param name="defaultValue">current (default) property value</param>
/// <returns>localized value</returns>
public string GetValue(
string languageCode,
string objectTypeCode,
string propertyCode,
string objectName,
string defaultValue)
{
string localizedValue =
GetLocalizedValue(languageCode, objectTypeCode, propertyCode, objectName, defaultValue);
return localizedValue ?? defaultValue;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns localized value for the given object type, property and object name.
/// Returns currentValue if value is not localized.
/// </summary>
/// <param name="objectTypeCode">code of object type</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object unique name</param>
/// <param name="currentValue">current (default) property value</param>
/// <returns>localized value</returns>
public string GetValue(
string objectTypeCode,
string propertyCode,
string objectName,
string currentValue)
{
return GetValue(LanguageCode, objectTypeCode, propertyCode, objectName, currentValue);
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns localized value for the given multilanguage item.
/// </summary>
/// <param name="item">multilanguage item</param>
/// <param name="defaultValue">current (default) property value</param>
/// <returns>localized value</returns>
public string GetValue(CxMultilanguageItem item, string defaultValue)
{
return item != null ?
GetValue(item.ObjectTypeCd, item.PropertyCd, item.ObjectName, defaultValue) : defaultValue;
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns true if property with the given code of the object of the given type
/// is registered as localizable.
/// </summary>
/// <param name="objectTypeCode">code of the object type</param>
/// <param name="propertyCode">property code</param>
public bool IsLocalizable(string objectTypeCode, string propertyCode)
{
string key = CxText.ToUpper(objectTypeCode + "." + propertyCode);
return ObjectProperties.ContainsKey(key);
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns true if value is localized.
/// </summary>
/// <param name="objectTypeCode">code of the object type</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">unique object name</param>
/// <param name="currentValue">current (default) value</param>
public bool IsLocalized(
string objectTypeCode,
string propertyCode,
string objectName,
string currentValue)
{
string localizedValue =
GetLocalizedValue(objectTypeCode, propertyCode, objectName, currentValue);
return localizedValue != null;
}
//-------------------------------------------------------------------------
/// <summary>
/// Exports all non-translated maultilanguage items into the given datatable.
/// </summary>
/// <param name="connection">db connection to multilanguage tables</param>
/// <param name="dt">target data table</param>
/// <param name="languageCd">language code to export (current if empty)</param>
/// <param name="applicationCd">application code to export (default if empty)</param>
public void ExportNonTranslatedItems(
CxDbConnection connection,
DataTable dt,
string languageCd,
string applicationCd)
{
if (CxUtils.IsEmpty(languageCd))
{
languageCd = LanguageCode;
}
if (CxUtils.IsEmpty(applicationCd))
{
applicationCd = LocalizationApplicationCode;
}
string sql =
@"select t.ApplicationCd,
t.LanguageCd,
t.ObjectTypeCd,
t.PropertyCd,
t.ObjectName,
t.ObjectTypeName,
t.PropertyName,
t.OriginalValue,
t.TranslatedValue,
t.DictionaryValue
from v_Framework_LocalizationValues t
where t.ApplicationCd = :ApplicationCd
and t.LanguageCd = :LanguageCd
and ((t.TranslatedValue is null and t.DictionaryValue is null)
or
t.IsNotSynchronized = 1)
order by t.ApplicationCd, t.LanguageCd, t.ObjectTypeCd, t.PropertyCd, t.ObjectName";
CxHashtable valueProvider = new CxHashtable();
valueProvider["ApplicationCd"] = applicationCd;
valueProvider["LanguageCd"] = languageCd;
connection.GetQueryResult(dt, sql, valueProvider);
}
//-------------------------------------------------------------------------
/// <summary>
/// Exports all translated maultilanguage items into the given datatable.
/// </summary>
/// <param name="connection">db connection to multilanguage tables</param>
/// <param name="dt">target data table</param>
/// <param name="languageCd">language code to export (current if empty)</param>
/// <param name="applicationCd">application code to export (default if empty)</param>
public void ExportTranslatedItems(
CxDbConnection connection,
DataTable dt,
string languageCd,
string applicationCd)
{
if (CxUtils.IsEmpty(languageCd))
{
languageCd = LanguageCode;
}
if (CxUtils.IsEmpty(applicationCd))
{
applicationCd = LocalizationApplicationCode;
}
string sql =
@"select t.ApplicationCd,
t.LanguageCd,
t.ObjectTypeCd,
t.PropertyCd,
t.ObjectName,
t.ObjectTypeName,
t.PropertyName,
t.OriginalValue,
case when t.DictionaryValue is null then t.TranslatedValue else null end as TranslatedValue,
t.DictionaryValue
from v_Framework_LocalizationValues t
where t.ApplicationCd = :ApplicationCd
and t.LanguageCd = :LanguageCd
and ((t.TranslatedValue is not null or t.DictionaryValue is not null)
and (t.IsNotSynchronized = 0 or t.IsNotSynchronized is null))
order by t.ApplicationCd, t.LanguageCd, t.ObjectTypeCd, t.PropertyCd, t.ObjectName";
CxHashtable valueProvider = new CxHashtable();
valueProvider["ApplicationCd"] = applicationCd;
valueProvider["LanguageCd"] = languageCd;
connection.GetQueryResult(dt, sql, valueProvider);
}
//-------------------------------------------------------------------------
private List<string> GetKeysStartingFrom(Hashtable hashtable, string startsWith)
{
List<string> result = new List<string>();
foreach (string key in hashtable.Keys)
{
if (key.StartsWith(startsWith))
result.Add(key);
}
return result;
}
//-------------------------------------------------------------------------
/// <summary>
/// Imports translated multilanguage items from the data table.
/// DataTable must have the following columns:
/// ApplicationCd,
/// LanguageCd,
/// ObjectTypeCd,
/// PropertyCd,
/// ObjectName,
/// OriginalValue,
/// TranslatedValue,
/// DictionaryValue
/// </summary>
/// <param name="connection">DB connection to the multilanguage tables</param>
/// <param name="dt">data table with translated values</param>
/// <param name="languageCd">language to import (or null to import all records)</param>
/// <param name="applicationCd">application to import (or null to import all records)</param>
/// <param name="doOverwrite">do overwrite existing translations</param>
/// <param name="importLogText">string to put import log</param>
public void ImportTranslatedItems(
CxDbConnection connection,
DataTable dt,
string languageCd,
string applicationCd,
bool doOverwrite,
out string importLogText)
{
if (dt.Rows.Count == 0)
{
importLogText = m_Holder.GetTxt("No rows imported. Source table is empty.");
return;
}
// Check required columns
string[] requiredColumns =
{"ApplicationCd", "LanguageCd", "ObjectTypeCd", "PropertyCd", "ObjectName",
"OriginalValue", "TranslatedValue", "DictionaryValue"};
foreach (string columnName in requiredColumns)
{
if (!dt.Columns.Contains(columnName))
{
throw new ExValidationException(
m_Holder.GetErr("Source table is invalid. Must have column with name '{0}'.",
new object[]{columnName}));
}
}
// Read existing multilanguage data from the database
DataTable dtTarget = new DataTable();
string sql =
@"select t.ApplicationCd,
t.LanguageCd,
t.ObjectTypeCd,
t.PropertyCd,
t.ObjectName,
t.OriginalValue,
t.TranslatedValue,
t.IsTranslated,
t.IsNotSynchronized,
t.DictionaryValue
from v_Framework_LocalizationValues t";
if (CxUtils.NotEmpty(applicationCd))
{
CxDbUtils.AddToWhere(sql, "ApplicationCd = :ApplicationCd");
}
if (CxUtils.NotEmpty(languageCd))
{
CxDbUtils.AddToWhere(sql, "LanguageCd = :LanguageCd");
}
CxHashtable valueProvider = new CxHashtable();
valueProvider["ApplicationCd"] = applicationCd;
valueProvider["LanguageCd"] = languageCd;
connection.GetQueryResult(dtTarget, sql, valueProvider);
// Compose hashtables with existing multilanguage data
Hashtable targetItems = new Hashtable();
Hashtable targetValues = new Hashtable();
Hashtable targetDictionary = new Hashtable();
foreach (DataRow dr in dtTarget.Rows)
{
string itemKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectTypeCd"]).ToUpper() + "." +
CxUtils.ToString(dr["PropertyCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectName"]).ToUpper();
targetItems[itemKey] = true;
if (CxBool.Parse(dr["IsTranslated"]))
{
string valueKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["LanguageCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectTypeCd"]).ToUpper() + "." +
CxUtils.ToString(dr["PropertyCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectName"]).ToUpper();
targetValues[valueKey] = dr;
}
if (CxUtils.NotEmpty(dr["DictionaryValue"]))
{
string dictionaryKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["LanguageCd"]).ToUpper() + "." +
CxUtils.ToString(dr["OriginalValue"]).ToUpper();
targetDictionary[dictionaryKey] = dr;
}
}
// Initialize counters
int importedRows = 0;
int skippedRows = 0;
int rejectedRows = 0;
int rejectedByApplication = 0;
int rejectedBySpecificError = 0;
int rejectedByLanguage = 0;
int rejectedByEmptyValue = 0;
int rejectedByInvalidKey = 0;
string errorLog = "";
// Initialize SQL statements
string insertValueSql =
@"insert into Framework_LocalizedValues
(
ObjectTypeCd,
ObjectName,
LanguageCd,
PropertyCd,
ApplicationCd,
Value
)
values
(
:ObjectTypeCd,
:ObjectName,
:LanguageCd,
:PropertyCd,
:ApplicationCd,
:TranslatedValue
)";
string updateValueSql =
@"update Framework_LocalizedValues
set Value = :TranslatedValue,
IsNotSynchronized = 0
where ObjectTypeCd = :ObjectTypeCd
and ObjectName = :ObjectName
and LanguageCd = :LanguageCd
and PropertyCd = :PropertyCd
and ApplicationCd = :ApplicationCd";
string insertDictionarySql =
@"insert into Framework_LocalizationDictionary
(
DefaultValue,
ApplicationCd,
LanguageCd,
Value
)
values
(
:OriginalValue,
:ApplicationCd,
:LanguageCd,
:DictionaryValue
)";
string updateDictionarySql =
@"update Framework_LocalizationDictionary
set Value = :DictionaryValue
where LanguageCd = :LanguageCd
and DefaultValue = :OriginalValue
and ApplicationCd = :ApplicationCd";
// Perform import
int rowIndex = 1;
foreach (DataRow dr in dt.Rows)
{
// Validate application code
if (CxUtils.NotEmpty(applicationCd) &&
CxUtils.ToString(dr["ApplicationCd"]).ToUpper() != CxText.ToUpper(applicationCd))
{
rejectedByApplication++;
rejectedRows++;
continue;
}
// Validate language code
if (CxUtils.NotEmpty(languageCd) &&
CxUtils.ToString(dr["LanguageCd"]).ToUpper() != CxText.ToUpper(languageCd))
{
rejectedByLanguage++;
rejectedRows++;
continue;
}
// Check for non-empty values
string translatedValue = CxUtils.ToString(dr["TranslatedValue"]);
string dictionaryValue = CxUtils.ToString(dr["DictionaryValue"]);
if (CxUtils.IsEmpty(translatedValue) && CxUtils.IsEmpty(dictionaryValue))
{
rejectedByEmptyValue++;
rejectedRows++;
continue;
}
// Check for valid multilanguage item key
string itemKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectTypeCd"]).ToUpper() + "." +
CxUtils.ToString(dr["PropertyCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectName"]).ToUpper();
//var keys = targetItems.Keys.Cast<string>().ToList();
//keys.Sort();
bool isImported = false;
bool isImportError = false;
if (!targetItems.ContainsKey(itemKey))
{
if (!doOverwrite)
{
rejectedByInvalidKey++;
rejectedRows++;
string displayKey = CxText.Format(
"ApplicationCd = {0}; ObjectTypeCd = {1}; PropertyCd = {2}; ObjectName = {3}",
dr["ApplicationCd"], dr["ObjectTypeCd"], dr["PropertyCd"], dr["ObjectName"]);
errorLog += m_Holder.GetErr("Row {0} import error: Invalid key ({1})\r\n",
new object[]{rowIndex, displayKey});
continue;
}
else
{
string sqlInsertItem = "insert into Framework_LocalizationItems " +
" (ApplicationCd, ObjectTypeCd, PropertyCd, ObjectName, DefaultValue, IsNotUsed) " +
" values (:ApplicationCd, :ObjectTypeCd, :PropertyCd, :ObjectName, :OriginalValue, 0)";
connection.BeginTransaction();
try
{
connection.ExecuteCommand(sqlInsertItem, new CxDataRowValueProvider(dr));
connection.Commit();
}
catch (Exception ex)
{
connection.Rollback();
errorLog += m_Holder.GetErr("Row {0} localization item import error: {1}\r\n",
new object[] { rowIndex, ex.Message });
isImportError = true;
}
}
}
// Try to import translated value
if (CxUtils.NotEmpty(translatedValue))
{
string valueKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["LanguageCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectTypeCd"]).ToUpper() + "." +
CxUtils.ToString(dr["PropertyCd"]).ToUpper() + "." +
CxUtils.ToString(dr["ObjectName"]).ToUpper();
DataRow targetRow = (DataRow) targetValues[valueKey];
string stmt = null;
if (targetRow == null)
{
stmt = insertValueSql;
}
else if (doOverwrite &&
CxUtils.ToString(targetRow["TranslatedValue"]) != translatedValue ||
CxBool.Parse(targetRow["IsNotSynchronized"]))
{
stmt = updateValueSql;
}
if (CxUtils.NotEmpty(stmt))
{
connection.BeginTransaction();
try
{
connection.ExecuteCommand(stmt, new CxDataRowValueProvider(dr));
connection.Commit();
isImported = true;
}
catch (Exception e)
{
connection.Rollback();
rejectedBySpecificError++;
errorLog += m_Holder.GetErr("Row {0} translated value import error: {1}\r\n",
new object[]{rowIndex, e.Message});
isImportError = true;
}
}
}
// Try to import dictionary value
// Dictionary value is imported only if there is no such dictionary value in DB
if (CxUtils.NotEmpty(dictionaryValue))
{
string dictionaryKey = CxUtils.ToString(dr["ApplicationCd"]).ToUpper() + "." +
CxUtils.ToString(dr["LanguageCd"]).ToUpper() + "." +
CxUtils.ToString(dr["OriginalValue"]).ToUpper();
DataRow targetRow = (DataRow) targetDictionary[dictionaryKey];
string stmt = null;
if (targetRow == null)
{
stmt = insertDictionarySql;
}
else if (doOverwrite &&
CxUtils.ToString(targetRow["DictionaryValue"]) != dictionaryValue)
{
stmt = updateDictionarySql;
}
if (CxUtils.NotEmpty(stmt))
{
connection.BeginTransaction();
try
{
connection.ExecuteCommand(stmt, new CxDataRowValueProvider(dr));
connection.Commit();
isImported = true;
}
catch (Exception e)
{
rejectedBySpecificError++;
connection.Rollback();
errorLog += m_Holder.GetErr("Row {0} dictionary value import error: {1}\r\n",
new object[]{rowIndex, e.Message});
isImportError = true;
}
}
}
if (isImported)
{
importedRows++;
}
else if (isImportError)
{
rejectedRows++;
}
else
{
skippedRows++;
}
rowIndex++;
}
// Compose import log
importLogText = "";
importLogText += m_Holder.GetTxt("Total rows: {0}", new object[]{dt.Rows.Count}) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Imported rows: {0}", new object[] { importedRows }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Skipped rows: {0}", new object[] { skippedRows }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected rows: {0}", new object[] { rejectedRows }) + Environment.NewLine + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected by invalid application code: {0}", new object[] { rejectedByApplication }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected by invalid language code: {0}", new object[] { rejectedByLanguage }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected by empty translation: {0}", new object[] { rejectedByEmptyValue }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected by invalid key: {0}", new object[] { rejectedByInvalidKey }) + Environment.NewLine;
importLogText += m_Holder.GetTxt("Rejected by specific error: {0}", new object[] { rejectedBySpecificError }) + Environment.NewLine + Environment.NewLine;
importLogText += (CxUtils.NotEmpty(errorLog) ?
m_Holder.GetTxt("Database errors:") + Environment.NewLine + errorLog : "");
// Reload multilanguage data from database.
if (IsLoaded && importedRows > 0)
{
ReadFromDatabase(connection, CxAppInfo.LocalizationApplicationCode);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Updates localized value in the database.
/// </summary>
/// <param name="connection">database connection</param>
/// <param name="languageCode">language code</param>
/// <param name="objectTypeCode">object type code</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object name</param>
/// <param name="value">value to set</param>
public void SetLocalizedValue(
CxDbConnection connection,
string languageCode,
string objectTypeCode,
string propertyCode,
string objectName,
string defaultValue,
string value)
{
SetLocalizedValueInMemory(languageCode, objectTypeCode, propertyCode, objectName, value);
string sql =
@"exec p_Framework_LocalizedValue_Insert
@ApplicationCd = :ApplicationCd,
@ObjectTypeCd = :ObjectTypeCd,
@PropertyCd = :PropertyCd,
@ObjectName = :ObjectName,
@LanguageCd = :LanguageCd,
@DefaultValue = :DefaultValue,
@Value = :Value";
CxHashtable provider = new CxHashtable();
provider["ApplicationCd"] = m_LocalizationApplicationCode;
provider["ObjectTypeCd"] = objectTypeCode;
provider["PropertyCd"] = propertyCode;
provider["ObjectName"] = objectName;
provider["LanguageCd"] = languageCode;
provider["DefaultValue"] = defaultValue;
provider["Value"] = value;
connection.ExecuteCommand(sql, provider);
}
//-------------------------------------------------------------------------
/// <summary>
/// Updates the localized value in memory so that the application can start working with the newly
/// modified localization string immediately.
/// </summary>
public void SetLocalizedValueInMemory(
string languageCode,
string objectTypeCode,
string propertyCode,
string objectName,
string value)
{
string key = languageCode.ToUpper() + "." +
objectTypeCode.ToUpper() + "." +
propertyCode.ToUpper() + "." +
objectName.ToUpper();
LocalizedValues[key] = value;
}
//-------------------------------------------------------------------------
/// <summary>
/// Updates localized value in the database.
/// </summary>
/// <param name="connection">database connection</param>
/// <param name="objectTypeCode">object type code</param>
/// <param name="propertyCode">property code</param>
/// <param name="objectName">object name</param>
/// <param name="value">value to set</param>
public void SetLocalizedValue(
CxDbConnection connection,
string objectTypeCode,
string propertyCode,
string objectName,
string defaultValue,
string value)
{
SetLocalizedValue(connection, LanguageCode, objectTypeCode, propertyCode, objectName, defaultValue, value);
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns true if multilanguage data is loaded from the database.
/// </summary>
public bool IsLoaded
{
get { return m_IsLoaded; }
protected set { m_IsLoaded = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets code of the current language to return values.
/// </summary>
public string LanguageCode
{ get { return m_LanguageCode; } set { m_LanguageCode = value; } }
//-------------------------------------------------------------------------
/// <summary>
/// Returns code of the localization application.
/// </summary>
public string LocalizationApplicationCode
{ get { return CxUtils.Nvl(m_LocalizationApplicationCode, m_ApplicationCode); } }
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets localized values.
/// </summary>
public Hashtable LocalizedValues
{
get { return m_LocalizedValues; }
set { m_LocalizedValues = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets localization dictionary values.
/// </summary>
public Hashtable DictionaryValues
{
get { return m_DictionaryValues; }
set { m_DictionaryValues = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets object type and property dictionary.
/// </summary>
public Hashtable ObjectProperties
{
get { return m_ObjectProperties; }
set { m_ObjectProperties = value; }
}
//-------------------------------------------------------------------------
}
} |
namespace OmniGui
{
public class KeyArgs
{
public KeyArgs(MyKey key)
{
Key = key;
}
public MyKey Key { get; set; }
}
} |
using System.ComponentModel.DataAnnotations;
namespace ActivityTracker.Dtos
{
public class ActivityUpdateDto
{
// Id is created by the database
[Required]
[MaxLength(250)]
public string ActivityType { get; set; }
[Required]
public int Met { get; set; }
[Required]
public int DailyGoal { get; set; }
[Required]
public int TotalGoal { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business.Helper;
using eIVOGo.Models.ViewModel;
using ClosedXML.Excel;
using Model.DataEntity;
using Model.Locale;
using Model.Helper;
using Model.Security.MembershipManagement;
using ModelExtension.DataExchange;
using Utility;
using Newtonsoft.Json;
using System.Threading.Tasks;
using eIVOGo.Helper;
using Model.Models.ViewModel;
using eIVOGo.Helper.Security.Authorization;
using Newtonsoft.Json.Linq;
using DocumentFormat.OpenXml.EMMA;
using ModelExtension.Helper;
using System.Data.Linq;
using static System.Web.Razor.Parser.SyntaxConstants;
using System.Reflection;
using ZXing.QrCode.Internal;
using System.Text;
using System.Linq.Dynamic.Core;
using Microsoft.Data.OData;
using System.Runtime.InteropServices;
namespace eIVOGo.Controllers
{
[Authorize]
public class DataExchangeController : SampleController<InvoiceItem>
{
// GET: DataExchange
[RoleAuthorize(RoleID = new Naming.RoleID[] { Naming.RoleID.ROLE_SYS })]
public ActionResult Index()
{
return View("~/Views/DataExchange/Index.cshtml");
}
public ActionResult UpdateBuyer(bool? issueNotification)
{
var profile = HttpContext.GetUser();
try
{
var buyerDetails = Request.Files["InvoiceBuyer"];
if (buyerDetails != null)
{
using(XLWorkbook xlwb = new XLWorkbook(buyerDetails.InputStream))
{
InvoiceBuyerExchange exchange = new InvoiceBuyerExchange();
switch ((Naming.RoleID)profile.CurrentUserRole.RoleID)
{
case Naming.RoleID.ROLE_SYS:
exchange.ExchangeData(xlwb);
break;
case Naming.RoleID.ROLE_SELLER:
case Naming.RoleID.ROLE_NETWORKSELLER:
exchange.ExchangeData(xlwb, item =>
{
return item.SellerID == profile.CurrentUserRole.OrganizationCategory.CompanyID
|| item.CDS_Document.DocumentOwner.OwnerID == profile.CurrentUserRole.OrganizationCategory.CompanyID;
});
break;
default:
break;
}
if (issueNotification == true && exchange.EffectiveItems.Count > 0)
{
exchange.EffectiveItems.Select(i => i.InvoiceID)
.NotifyIssuedInvoice(true);
}
String result = Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".xslx");
xlwb.SaveAs(result);
return File(result, "application/octet-stream", "修改買受人資料(回應).xlsx");
}
}
ViewBag.AlertMessage = "檔案錯誤!!";
}
catch(Exception ex)
{
Logger.Error(ex);
ViewBag.AlertMessage = ex.ToString();
}
return View("Index");
}
public ActionResult UpdateBuyerInfo(bool? issueNotification)
{
ActionResult result = UpdateBuyer(issueNotification);
if(result is FilePathResult)
{
return View("~/Views/DataExchange/Module/UpdateBuyerInfo.cshtml", result);
}
else
{
return View("~/Views/Shared/AlertMessage.cshtml");
}
}
public ActionResult UpdateTrackCode()
{
var profile = HttpContext.GetUser();
try
{
var xlFile = Request.Files["TrackCode"];
if (xlFile != null)
{
using (XLWorkbook xlwb = new XLWorkbook(xlFile.InputStream))
{
TrackCodeExchange exchange = new TrackCodeExchange();
switch ((Naming.RoleID)profile.CurrentUserRole.RoleID)
{
case Naming.RoleID.ROLE_SYS:
exchange.ExchangeData(xlwb);
break;
default:
break;
}
String result = Path.Combine(Logger.LogDailyPath, Guid.NewGuid().ToString() + ".xslx");
xlwb.SaveAs(result);
return File(result, "message/rfc822", "修改發票字軌(回應).xlsx");
}
}
ViewBag.AlertMessage = "檔案錯誤!!";
}
catch (Exception ex)
{
Logger.Error(ex);
ViewBag.AlertMessage = ex.ToString();
}
return View("Index");
}
public ActionResult GetResource(String path)
{
if (path != null)
{
String filePath = path.DecryptData();
if (System.IO.File.Exists(filePath))
{
return File(filePath, "application/octet-stream", Path.GetFileName(filePath));
}
}
return new EmptyResult { };
}
public ActionResult DownloadResource(AttachmentViewModel viewModel)
{
if (viewModel.KeyID != null)
{
viewModel = JsonConvert.DeserializeObject<AttachmentViewModel>(viewModel.KeyID.DecryptData());
}
ViewBag.ViewModel = viewModel;
if (System.IO.File.Exists(viewModel.FileName))
{
return File(viewModel.FileName,
viewModel.ContentType ?? "application/octet-stream",
viewModel.FileDownloadName ?? Path.GetFileName(viewModel.FileName));
}
else
{
return new EmptyResult { };
}
}
public ActionResult CheckResource(AttachmentViewModel viewModel)
{
if (viewModel.KeyID != null)
{
viewModel = JsonConvert.DeserializeObject<AttachmentViewModel>(viewModel.KeyID.DecryptData());
}
ViewBag.ViewModel = viewModel;
if (System.IO.File.Exists(viewModel.FileName))
{
return Json(new { result = true, viewModel.KeyID }, JsonRequestBehavior.AllowGet);
}
else if (viewModel.TaskID.HasValue)
{
var taskItem = models.GetTable<ProcessRequest>().Where(p => p.TaskID == viewModel.TaskID).FirstOrDefault();
if (taskItem != null)
{
if (taskItem.ResponsePath != null && System.IO.File.Exists(taskItem.ResponsePath))
{
return Json(new { result = true, KeyID = viewModel.JsonStringify().EncryptData() }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = false, KeyID = viewModel.JsonStringify().EncryptData(), message = taskItem.ExceptionLog?.DataContent }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { result = false, KeyID = viewModel.JsonStringify().EncryptData() }, JsonRequestBehavior.AllowGet);
}
public async Task<ActionResult> ImportInvoice()
{
var userProfile = HttpContext.GetUser();
if (Request.Files.Count <= 0)
{
return View("~/Views/Shared/AlertMessage.cshtml", model: "請選擇匯入檔!!");
}
var file = Request.Files[0];
String fileName = Path.Combine(Logger.LogDailyPath, DateTime.Now.Ticks + "_" + Path.GetFileName(file.FileName));
ViewBag.ImportFile = fileName;
String content;
using (StreamReader reader = new StreamReader(Request.Files[0].InputStream))
{
content = reader.ReadToEnd();
}
InvoiceEntity[] items = await Task.Run<InvoiceEntity[]>(() =>
{
InvoiceEntity[] result = null;
try
{
result = JsonConvert.DeserializeObject<InvoiceEntity[]>(content);
if (result != null && result.Length > 0)
{
Parallel.ForEach(result, item =>
{
try
{
item.Save();
}
catch (Exception ex)
{
Logger.Error(ex);
item.Status = Naming.UploadStatusDefinition.匯入失敗;
item.Reason = ex.Message;
}
});
System.IO.File.WriteAllText(fileName, JsonConvert.SerializeObject(result));
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
return result;
});
return View("~/Views/DataExchange/Module/ImportInvoiceResult.cshtml", items);
}
public ActionResult MaintainData(DataTableQueryViewModel viewModel)
{
ViewBag.ViewModel = viewModel;
return View("~/Views/DataExchange/MaintainData.cshtml");
}
Type PrepareDataTable(DataTableQueryViewModel viewModel)
{
ViewBag.ViewModel = viewModel;
viewModel.TableName = viewModel.TableName.GetEfficientString();
if (viewModel.TableName == null)
{
ModelState.AddModelError("Message", "請選擇資料表!!");
return null;
}
String typeName = typeof(EIVOEntityDataContext).AssemblyQualifiedName.Replace("EIVOEntityDataContext", viewModel.TableName);
var type = Type.GetType(typeName);
if (type == null)
{
ModelState.AddModelError("Message", "資料表錯誤!!");
return null;
}
return type;
}
public ActionResult ShowDataTable(DataTableQueryViewModel viewModel)
{
var type = PrepareDataTable(viewModel);
if (type == null)
{
return View("~/Views/Shared/AlertMessage.cshtml", model: ModelState.ErrorMessage());
}
ViewBag.TableType = type;
IQueryable items = models.DataContext.GetTable(type);
if (viewModel.DataItem != null && viewModel.DataItem.Length > 0)
{
items = BuildQuery(viewModel.DataItem, type, items);
}
viewModel.RecordCount = items?.Count();
if (viewModel.PageIndex.HasValue)
{
viewModel.PageIndex--;
return View("~/Views/DataExchange/Module/DataItemList.cshtml", items);
}
else
{
viewModel.PageIndex = 0;
return View("~/Views/DataExchange/Module/DataTableQueryResult.cshtml", items);
}
}
private static IQueryable BuildQuery(DataTableColumn[] fields, Type type, IQueryable items)
{
foreach (DataTableColumn field in fields)
{
PropertyInfo propertyInfo = type.GetProperty(field.Name);
var columnAttribute = propertyInfo?.GetColumnAttribute();
if (columnAttribute != null)
{
String fieldValue = field.Value.GetEfficientString();
if (fieldValue == null)
{
continue;
}
var t = propertyInfo.PropertyType;
if (t == typeof(String))
{
items = items.Where($"{propertyInfo.Name}.StartsWith(@0)", fieldValue);
}
else
{
items = items.Where($"{propertyInfo.Name} == @0", Convert.ChangeType(fieldValue, propertyInfo.PropertyType));
}
}
}
return items;
}
public ActionResult DataItem(DataTableQueryViewModel viewModel)
{
var type = PrepareDataTable(viewModel);
if (type == null)
{
return View("~/Views/Shared/AlertMessage.cshtml", model: ModelState.ErrorMessage());
}
ViewBag.TableType = type;
IQueryable items = ViewBag.DataTable = models.DataContext.GetTable(type);
//var items = dataTable.Cast<dynamic>();
dynamic dataItem;
if (viewModel.KeyItem?.Any(k => k.Name != null && k.Value != null) == true)
{
items = BuildQuery(viewModel.KeyItem, type, items);
}
else
{
items = items.Where(" 1 = 0");
}
//var key = viewModel.KeyItem?.Where(k => k.Name != null && k.Value != null);
//if (key?.Any() == true)
//{
// int idx = 0;
// String sqlCmd = String.Concat(items.ToString(),
// " where ",
// String.Join(" and ", key.Select(k => $"{k.Name} = {{{idx++}}}")));
// var paramValues = key.Select(k => k.Value).ToArray();
// dataItem = ((IEnumerable<dynamic>)models.DataContext.ExecuteQuery(type, sqlCmd, paramValues))
// .FirstOrDefault();
//}
//else
//{
// dataItem = items.FirstOrDefault();
//}
dataItem = items.FirstOrDefault();
return View("~/Views/DataExchange/Module/DataItem.cshtml", dataItem);
}
public ActionResult EditItem(DataTableQueryViewModel viewModel)
{
ViewResult result = (ViewResult)DataItem(viewModel);
result.ViewName = "~/Views/DataExchange/Module/EditItem.cshtml";
return result;
}
public ActionResult CommitItem(DataTableQueryViewModel viewModel)
{
ViewResult result = (ViewResult)DataItem(viewModel);
Type type = ViewBag.TableType as Type;
if (type == null)
{
return result;
}
ITable dataTable = ViewBag.DataTable as ITable;
dynamic dataItem = result.Model;
if (dataItem == null)
{
dataItem = Activator.CreateInstance(type);
dataTable.InsertOnSubmit(dataItem);
}
if(viewModel.DataItem!= null)
{
foreach (DataTableColumn field in viewModel.DataItem)
{
PropertyInfo propertyInfo = type.GetProperty(field.Name);
if (propertyInfo != null && propertyInfo.CanWrite)
{
object value = field.Value != null
? Convert.ChangeType(field.Value, propertyInfo.PropertyType)
: null;
propertyInfo.SetValue(dataItem, value, null);
}
}
}
models.SubmitChanges();
return View("~/Views/DataExchange/Module/DataItem.cshtml", dataItem);
}
public ActionResult DeleteItem(DataTableQueryViewModel viewModel)
{
var type = PrepareDataTable(viewModel);
if (type == null)
{
return View("~/Views/Shared/AlertMessage.cshtml", model: ModelState.ErrorMessage());
}
ViewBag.TableType = type;
ITable dataTable = ViewBag.DataTable = models.DataContext.GetTable(type);
if(viewModel.KeyItems!= null)
{
foreach(var keyItem in viewModel.KeyItems)
{
DataTableColumn[] keyData = JsonConvert.DeserializeObject<DataTableColumn[]>(keyItem.DecryptData());
dynamic item = BuildQuery(keyData, type, (IQueryable)dataTable).FirstOrDefault();
if (item != null)
{
dataTable.DeleteOnSubmit(item);
models.SubmitChanges();
}
}
}
return Json(new { result = true }, JsonRequestBehavior.AllowGet);
}
}
} |
/**
Animate an airlock door moving up and down.
Original by Orion Lawlor, 2020-07, for Nexus Aurora (Public Domain)
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AirlockDoor : MonoBehaviour
{
public Vector3 closePos=new Vector3(0.0f,0f,0f);
public Vector3 openPos=new Vector3(0.75f,2.2f,0f);
public Quaternion closeRot=Quaternion.Euler(0f,0f,0f);
public Quaternion openRot=Quaternion.Euler(0f,0f,90f);
public float openState=0.0f; // current open state, from 0 to 1
public float openDir=0.0f; // + for opening, - for closing.
public float openSpeed=0.8f; // constant open/close speed (in cycles/second)
private GameObject door; /// The instantiated door object
private bool lastOpen=false;
private void play(bool opening) {
if (opening==lastOpen) return; // <- remove repeated calls
else lastOpen=opening;
AudioSource[] s=door.GetComponentsInChildren<AudioSource>();
int index=opening?0:1; // index into door's list of AudioSource objects
if (s[index]) s[index].Play();
}
public void Open() {
openDir=+openSpeed;
play(true);
}
public void Close() {
openDir=-openSpeed;
play(false);
}
// Move the graphical door to this location
private void setOpenClose(float openness)
{
door.transform.localPosition=Vector3.Lerp(closePos,openPos,openness);
door.transform.localRotation=Quaternion.Lerp(closeRot,openRot,openness);
}
// Start is called before the first frame update
void Start()
{
door=gameObject; // This script is attached to the door itself.
// Move our positions to be relative to our start configuration
Transform tf=door.transform;
closePos+=tf.localPosition;
openPos+=tf.localPosition;
closeRot=closeRot*tf.localRotation;
openRot=openRot*tf.localRotation;
// Our setup is all in the airlock
setOpenClose(openState);
}
// Update is called once per graphics frame
void Update()
{
float lastOpen=openState;
openState+=openDir*Time.deltaTime;
if (openState>1.0f) openState=1.0f;
if (openState<0.0f) openState=0.0f;
if (openState!=lastOpen) // update the animation
setOpenClose(openState);
}
}
|
using AppBase.Services.Model;
namespace OrganizationOne.Services.Model
{
public class AccessToken : IModelBase
{
public string Token { get; set; }
public bool Authenticated { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ToDo.Client.ViewModels;
namespace ToDo.Client
{
/// <summary>
/// Interaction logic for ParentSelectWindow.xaml
/// </summary>
public partial class ParentSelectWindow : Window
{
private readonly ParentSelectWindowViewModel vm;
public ParentSelectWindow(int listId, int? currentTaskId)
{
InitializeComponent();
vm = new ParentSelectWindowViewModel(listId, currentTaskId, this);
this.DataContext = vm;
}
public bool Cancelled
{
get
{
return vm.Cancelled;
}
}
public TaskItemViewModel SelectedItem { get
{
return vm.SelectedItem;
}
}
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
vm.SelectedItem = (TaskItemViewModel) e.NewValue;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BookStore.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BookStore.DAL.Tests
{
[TestClass()]
public class QuaterinformationDALTests
{
[TestMethod()]
public void GetQuaterinformByQuaterAndusernameTest()
{
Assert.Fail();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using Uxnet.Web.Module.Common;
using Uxnet.Web.Module.DataModel;
namespace eIVOGo.Module.Base
{
public abstract partial class EntityItemListModal<T, TEntity> : EntityItemList<T, TEntity>
where T : DataContext, new()
where TEntity : class, new()
{
//protected global::AjaxControlToolkit.ModalPopupExtender ModalPopupExtender;
public event EventHandler Done;
public virtual void Show()
{
this.Visible = true;
}
protected virtual void OnDone(object sender, EventArgs e)
{
if (Done != null)
{
Done(this, new EventArgs());
}
}
public virtual void Close()
{
this.Visible = false;
}
public override void BindData()
{
this.Visible = true;
base.BindData();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += new EventHandler(EntityItemListModal_PreRender);
}
void EntityItemListModal_PreRender(object sender, EventArgs e)
{
if (this.Visible)
{
//this.ModalPopupExtender.Show();
}
else
{
//this.ModalPopupExtender.Hide();
}
}
}
} |
using Godot;
using System;
using static Lib;
public class MenuButton : Button
{
protected Root root;
protected int num;
public void _on_button_up()
{
root.menuPanel = num;
}
public override void _Ready()
{
root = (Root)GetNode("/root/root");
if (this.Name.Length > 0 && this.Name[0] >= '0' && this.Name[0] <= '9')
{
num = ((int)this.Name[0]) - '0';
}
else
{
num = M_MAIN_PANEL;
}
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD50
{
/// <summary>
/// LD5025 的摘要说明。
/// </summary>
public class LD5025 : BasePage
{
protected System.Web.UI.WebControls.Button Button3;
protected DataDynamics.ActiveReports.Web.WebViewer WebViewer1;
protected Infragistics.WebUI.WebDataInput.WebDateTimeEdit dcsWTRQ;
protected Infragistics.WebUI.WebDataInput.WebDateTimeEdit dcsWTRQ2;
protected System.Web.UI.WebControls.TextBox WTDWMC;
protected System.Web.UI.WebControls.TextBox WTDW;
protected System.Web.UI.HtmlControls.HtmlImage IMG1;
protected System.Web.UI.WebControls.DropDownList ddlYWZT;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
this.dcsWTRQ.Value = DateTime.Today.AddDays(-1);
this.dcsWTRQ2.Value = DateTime.Today;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
#region 报表数据源
/// <summary>
/// 报表数据源
/// </summary>
/// <returns>报表数据源</returns>
private SqlDataReader rptData()
{
string strSql = "";
strSql = "SELECT MAX(b.JSRQ) AS JSRQ, a.YWLSH, a.JSDW, MAX(a.JSDWMC) AS JSDWMC, ";
strSql += " MAX(b.CH) AS CH, MAX(b.JSY) AS JSY, MAX(b.CMHC) AS CMHC, MAX(b.GDH) AS GDH,";
strSql += " MAX(b.XH) AS XH, MAX(b.XX) AS XX, MAX(b.TXD) AS TXD, MAX(b.XHD) AS XHD,";
strSql += " MAX(b.HXD) AS HXD, SL=1, SUM(a.JE) AS JE, MAX(b.BZ) AS BZ ";
strSql += " FROM F_JZXFY a INNER JOIN B_JZX b ON a.YWLSH = b.YWLSH";
strSql += " WHERE (b.SC = 'N') AND (a.SC = 'N') AND (a.YWLX = '10') AND (a.YSYF = '20') AND (a.JSBZ = '20')";
// 结算单位
if (this.WTDW.Text != "")
strSql += " and a.JSDW='"+ this.WTDW.Text +"'";
// 结算时间
if (this.dcsWTRQ.Value != null && this.dcsWTRQ.Value != System.DBNull.Value)
strSql += " and left(CONVERT(char(8),b.JSRQ,112),6) >= '"+ Convert.ToDateTime(this.dcsWTRQ.Value).ToString("yyyyMM") +"'";
if (this.dcsWTRQ2.Value != null && this.dcsWTRQ2.Value != System.DBNull.Value)
strSql += " and left(CONVERT(char(8),b.JSRQ,112),6) <= '"+ Convert.ToDateTime(this.dcsWTRQ2.Value).ToString("yyyyMM") +"'";
// 收款状态
if (this.ddlYWZT.SelectedValue != "")
{
if (this.ddlYWZT.SelectedValue == "20")
strSql += " and a.ZT = '20'";
else
strSql += " and a.ZT <> '20'";
}
strSql += " GROUP BY a.YWLSH, a.JSDW ORDER BY a.JSDW,a.YWLSH";
SqlDataReader dr;
dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSql,null);
return dr;
}
#endregion
private void Button3_Click(object sender, System.EventArgs e)
{
if(this.dcsWTRQ.Value == null || this.dcsWTRQ2.Value == null || this.dcsWTRQ.Value == DBNull.Value || this.dcsWTRQ2.Value == DBNull.Value)
{
this.msgbox("请先选择日期!");
return;
}
this.WebViewer1.ClearCachedReport();
DataDynamics.ActiveReports.ActiveReport ar;
ar = new LD502510RP(Session["UserName"].ToString(),this.WTDW.Text,this.dcsWTRQ.Value.ToString(),this.dcsWTRQ2.Value.ToString());
ar.DataSource = rptData();
ar.Run(false);
this.WebViewer1.Report = ar;
}
}
}
|
using Sitecore.Eventing;
using Sitecore.Install;
using Sitecore.Shell.Framework;
using Sitecore.Sites.Events;
namespace Sitecore.Shell.Applications.Dialogs
{
using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.Web.UI.Pages;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Diagnostics;
using Sitecore.Web.UI.Sheer;
using Sitecore.Jobs;
using Sitecore.Globalization;
using Sitecore.Data.Items;
using Sitecore.Data;
using System.Web.UI.HtmlControls;
using Sitecore.Configuration;
using Sitecore.Text;
using System.Web.UI;
using Sitecore.Sites;
using Sitecore.Publishing;
using Sitecore.Extensions;
public class FlushSitesForm : WizardForm
{
#region fields
//Settings page
protected Scrollbox SettingsPane;
protected Groupbox FlushingTargetsPanel;
protected Border FlushTargets;
//retry page
protected Memo ErrorText;
// last page
protected Literal Status;
protected Memo ResultText;
//first page
protected Literal Welcome;
protected Checkbox RestartLocalServer;
/// <summary/>
protected Checkbox RestartRemoteServer;
#endregion
private bool Cancelling
{
get
{
return MainUtil.GetBool(Context.ClientPage.ServerProperties["__cancelling"], false);
}
set
{
Context.ClientPage.ServerProperties["__cancelling"] = (value ? 1 : 0);
}
}
protected string JobHandle
{
get { return StringUtil.GetString(base.ServerProperties["JobHandle"]); }
set
{
Assert.ArgumentNotNullOrEmpty(value, "value");
base.ServerProperties["JobHandle"] = value;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Context.ClientPage.IsEvent)
{
BuildCheckList();
}
}
protected override void ActivePageChanged(string page, string oldPage)
{
base.ActivePageChanged(page, oldPage);
if (page == "Settings")
{
}
else if (page == "Flushing")
{
base.NextButton.Disabled = true;
base.BackButton.Disabled = true;
base.CancelButton.Disabled = true;
SheerResponse.SetInnerHtml("PublishingTarget", "");
SheerResponse.Timer("StartJob", 10);
}
else if (page == "LastPage")
{
this.BackButton.Disabled = true;
}
}
protected override void EndWizard()
{
if (!this.Cancelling)
{
// If the event manager is enabled then send the event through the queue
// otherwise call the Flush method directly
if (EventManager.Enabled)
{
// Send event into event queue to let farm instances know its time to refresh some stuff
EventManager.QueueEvent(new FlushRemoteEvent(this.RestartRemoteServer.Checked), true, false);
EventManager.QueueEvent(new FlushRemoteEvent(this.RestartLocalServer.Checked), false, true);
}
}
Sitecore.Shell.Framework.Windows.Close();
}
private void BuildCheckList()
{
this.FlushTargets.Controls.Clear();
string str2 = Settings.DefaultPublishingTargets.ToLowerInvariant();
ListString str = new ListString(Registry.GetString("/Current_User/Publish/Targets"));
// add master database
Sitecore.Publishing.PublishManager.GetPublishingTargets(Context.ContentDatabase).ForEach(target =>
{
string str3 = "pb_" + ShortID.Encode(target.ID);
HtmlGenericControl child = new HtmlGenericControl("input");
this.FlushTargets.Controls.Add(child);
child.Attributes["type"] = "checkbox";
child.ID = str3;
bool flag = str2.IndexOf('|' + target.Key + '|', StringComparison.InvariantCulture) >= 0;
if (str.Contains(target.ID.ToString()))
{
flag = true;
}
if (flag)
{
child.Attributes["checked"] = "checked";
}
child.Disabled = !target.Access.CanWrite();
HtmlGenericControl control2 = new HtmlGenericControl("label");
this.FlushTargets.Controls.Add(control2);
control2.Attributes["for"] = str3;
control2.InnerText = target.DisplayName;
this.FlushTargets.Controls.Add(new LiteralControl("<br>"));
});
}
protected void CheckStatus()
{
Handle handle = Handle.Parse(this.JobHandle);
if (!handle.IsLocal)
{
SheerResponse.Timer("CheckStatus", Settings.Publishing.PublishDialogPollingInterval);
}
else
{
PublishStatus status = PublishManager.GetStatus(handle);
if (status == null)
{
throw new Exception("The flushing process was unexpectedly interrupted.");
}
if (status.Failed)
{
this.Status.Text = Translate.Text("Could not process. Please Try again", new object[] { status.Processed.ToString() });
base.Active = "LastPage";
base.BackButton.Disabled = true;
string str2 = StringUtil.StringCollectionToString(status.Messages, "\n");
if (!string.IsNullOrEmpty(str2))
{
this.ResultText.Value = str2;
}
}
string str;
if (status.State == JobState.Running)
{
object[] objArray = new object[] { Translate.Text("Database:"), " ", StringUtil.Capitalize(status.CurrentTarget.NullOr<Database, string>(db => db.Name)), "<br/><br/>", Translate.Text("Language:"), " ", status.CurrentLanguage.NullOr<Language, string>(lang => lang.CultureInfo.DisplayName), "<br/><br/>", Translate.Text("Processed:"), " ", status.Processed };
str = string.Concat(objArray);
}
else if (status.State == JobState.Initializing)
{
str = Translate.Text("Initializing.");
}
else
{
str = Translate.Text("Queued.");
}
if (status.IsDone)
{
this.Status.Text = Translate.Text("Items processed: {0}.", new object[] { status.Processed.ToString() });
base.Active = "LastPage";
base.BackButton.Disabled = true;
string str2 = StringUtil.StringCollectionToString(status.Messages, "\n");
if (!string.IsNullOrEmpty(str2))
{
this.ResultText.Value = string.Format("{0}{1}{2}", str2, Environment.NewLine, Translate.Text("Job ended: Initialize Sites Refresh."));
}
}
else
{
SheerResponse.SetInnerHtml("PublishingTarget", str);
SheerResponse.Timer("CheckStatus", Settings.Publishing.PublishDialogPollingInterval);
}
}
}
protected void StartJob()
{
List<Database> publishingTargetDatabases = GetPublishingTargetDatabases();
if (publishingTargetDatabases.Any())
{
Handle publishHandle = null;
publishHandle = MultiSitesManager.PublishSites(publishingTargetDatabases);
if (publishHandle != null)
{
this.JobHandle = publishHandle.ToString();
SheerResponse.Timer("CheckStatus", 400);
}
else
{
base.Active = "LastPage";
base.BackButton.Disabled = true;
this.ResultText.Value = this.Status.Text = Translate.Text("Oops looks like something went wrong. Please try again or have a developer check the logs.");
}
}
else
{
MultiSitesManager.Flush();
base.Active = "LastPage";
base.BackButton.Disabled = true;
this.ResultText.Value = this.Status.Text = Translate.Text("Flushed");
}
}
private static List<Database> GetPublishingTargetDatabases()
{
List<Database> list = new List<Database>();
foreach (Item item in GetPublishingTargets())
{
string name = item["Target database"];
Database database = Factory.GetDatabase(name);
Assert.IsNotNull(database, typeof(Database), Translate.Text("Database \"{0}\" not found."), new object[] { name });
list.Add(database);
}
return list;
}
private static List<Item> GetPublishingTargets()
{
List<Item> list = new List<Item>();
foreach (string str in Context.ClientPage.ClientRequest.Form.Keys)
{
if ((str != null) && str.StartsWith("pb_", StringComparison.InvariantCulture))
{
string str2 = ShortID.Decode(str.Substring(3));
Item item = Context.ContentDatabase.Items[str2];
Assert.IsNotNull(item, typeof(Item), "Publishing target not found.", new object[0]);
list.Add(item);
}
}
return list;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace durable_functions_sample.Shared
{
public class DetectLanguageResponse
{
public DetectLanguageResponse()
{
Documents = new List<Document>();
}
public class Document
{
public Document()
{
DetectedLanguages = new List<Language>();
}
public string Id { get; set; }
public IList<Language> DetectedLanguages { get; set; }
public string InferredLanguage => DetectedLanguages
.FirstOrDefault(l => l.Score == DetectedLanguages.Max(l2 => l2.Score))?.Iso6391Name;
public string InferredLanguageName => DetectedLanguages
.FirstOrDefault(l => l.Score == DetectedLanguages.Max(l2 => l2.Score))?.Name;
public string ContentModerationLanguageCode
{
get
{
switch (InferredLanguage)
{
case "en":
return "eng";
case "ar":
return "ara";
default:
throw new Exception("language not supported");
}
}
}
}
public class Language
{
public string Name { get; set; }
public long Score { get; set; }
public string Iso6391Name { get; set; }
}
public IList<Document> Documents { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WF.SDK.Models.Internal
{
[Serializable]
public class UserItem
{
public Guid Id;
public string Title;
public string FirstName;
public string LastName;
public string CompanyName;
public string Email;
public bool EmailValidated;
public string Fax;
public string MobilePhone;
public string Phone;
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
public string Country;
public string TimeZone;
public UserItem()
{ }
}
}
|
using System;
namespace StratCorp.CorpSMS.Entities
{
public class MessageDetailEntity
{
public string StatusDescription { get; set; }
public DateTime StatusDate { get; set; }
public string Reason { get; set; }
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD10
{
/// <summary>
/// LD1030 的摘要说明。
/// </summary>
public class LD1030 : BasePage
{
protected System.Web.UI.WebControls.Button Button3;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ2;
protected System.Web.UI.WebControls.TextBox WTDWMC;
protected System.Web.UI.WebControls.TextBox WTDW;
protected System.Web.UI.HtmlControls.HtmlImage IMG1;
protected DataDynamics.ActiveReports.Web.WebViewer WebViewer1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
this.dcsWTRQ.Value = DateTime.Today.AddDays(-1);
this.dcsWTRQ2.Value = DateTime.Today;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button3_Click(object sender, System.EventArgs e)
{
this.WebViewer1.ClearCachedReport();
DataDynamics.ActiveReports.ActiveReport ar = new DataDynamics.ActiveReports.ActiveReport();
string strName;
string strWTDW;
string strWTRQ;
string strWTRQ2;
strName = Session["UserName"].ToString();
strWTDW = this.WTDW.Text;
strWTRQ = this.dcsWTRQ.Value.ToString();
strWTRQ2 = this.dcsWTRQ2.Value.ToString();
ar = new LD103010RP(strName,strWTDW, strWTRQ,strWTRQ2);
ar.Run(false);
this.WebViewer1.Report = ar;
}
}
}
|
using DevExpress.Office.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Filtering.Templates;
using DevExpress.XtraReports.UI;
using PDV.CONTROLER.Funcoes;
using PDV.CONTROLER.FuncoesFaturamento;
using PDV.DAO.DB.Utils;
using PDV.DAO.Enum;
using PDV.REPORTS.Reports.Modelo_2;
using PDV.VIEW.App_Context;
using PDV.VIEW.Forms.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Sequence = PDV.DAO.DB.Utils.Sequence;
namespace PDV.VIEW.Forms.Gerenciamento.OS
{
public partial class FCO_OrdemDeServico : XtraForm
{
public decimal IDOrdemServico
{
get => Grids.GetValorDec(gridView1, "IDOrdemDeServico");
}
public List<decimal> IdsSelecionados
{
get
{
var ids = new List<decimal>();
foreach (var row in gridView1.GetSelectedRows())
ids.Add(Grids.GetValorDec(gridView1, "IDOrdemDeServico", row));
return ids;
}
}
public FCO_OrdemDeServico()
{
InitializeComponent();
DataDe = DateTime.Today;
DataAte = DataDe.AddDays(1);
Atualizar();
FormatarGrid();
}
private void FormatarGrid()
{
Grids.FormatGrid(ref gridView1);
Grids.FormatColumnType(ref gridView1, new List<string>() { }, GridFormats.Count);
}
public DateTime DataDe
{
get => dateEdit1.DateTime.Date;
set => dateEdit1.DateTime = value;
}
public DateTime DataAte
{
get => dateEdit2.DateTime.Date;
set => dateEdit2.DateTime = value;
}
private void atualizarMetroButton_Click(object sender, System.EventArgs e)
{
Atualizar();
}
private void Atualizar()
{
gridControl1.DataSource = FuncoesOrdemServico.GetOrdensDeServico(DataDe, DataAte);
}
private void novoMetroButton_Click(object sender, EventArgs e)
{
Novo();
}
private void Novo()
{
new FCA_OrdemDeServico().ShowDialog();
Atualizar();
}
private void editarMetroButton_Click(object sender, EventArgs e)
{
Editar();
}
private void Editar()
{
new FCA_OrdemDeServico(IDOrdemServico).ShowDialog();
Atualizar();
}
private void dateEdit1_EditValueChanged(object sender, EventArgs e)
{
if (DataDe >= DataAte)
DataAte = DataDe.AddDays(1);
}
private void dateEdit2_EditValueChanged(object sender, EventArgs e)
{
if (DataDe >= DataAte)
DataDe = DataAte.AddDays(-1);
}
private void gridView1_DoubleClick(object sender, EventArgs e)
{
Editar();
}
private void buttonFaturar_Click(object sender, EventArgs e)
{
Faturar();
}
private void Faturar()
{
if (Confirm("Deseja faturar a(s) ordem(ns) selecionada(s)") == DialogResult.Yes)
{
foreach (var id in IdsSelecionados)
{
try
{
PDVControlador.BeginTransaction();
var osFaturamento = new OSFaturamento(id, Contexto.USUARIOLOGADO);
osFaturamento.FaturarOS();
PDVControlador.Commit();
}
catch (Exception exception)
{
PDVControlador.Rollback();
Alert(exception.Message);
}
}
Atualizar();
}
}
private void Alert(string message)
{
MessageBox.Show(message, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
{
if (e.Column.FieldName == "Status")
{
string valor;
try
{
valor = Grids.GetValorStr(gridView1, "Status", e.RowHandle);
}
catch (Exception)
{
valor = "";
}
switch (valor)
{
case "FATURADO":
e.Appearance.ForeColor = System.Drawing.Color.Green;
break;
case "CANCELADO":
e.Appearance.ForeColor = System.Drawing.Color.Red;
break;
case "ABERTO":
e.Appearance.ForeColor = System.Drawing.Color.Blue;
break;
case "DESFEITO":
e.Appearance.ForeColor = System.Drawing.Color.Purple;
break;
case "APP":
e.Appearance.ForeColor = System.Drawing.Color.Blue;
e.Appearance.BackColor = System.Drawing.Color.Yellow;
break;
}
}
}
private void buttonCancelar_Click(object sender, EventArgs e)
{
Cancelar();
}
private void Cancelar()
{
if (Confirm("Deseja cancelar a(s) ordem(ns) selecionada(s)") == DialogResult.Yes)
{
try
{
PDVControlador.BeginTransaction();
foreach (var id in IdsSelecionados)
{
var motivo = XtraInputBox
.Show($"Informe o motivo de cancelamento para a ordem de servico {id}",
"Cancelar Ordem de Serviço",
"");
var osFaturamento = new OSFaturamento(id, Contexto.USUARIOLOGADO);
osFaturamento.CancelarOs(motivo);
}
PDVControlador.Commit();
}
catch (Exception exception)
{
PDVControlador.Rollback();
Alert(exception.Message);
}
Atualizar();
}
}
private DialogResult Confirm(string msg)
{
return MessageBox.Show(msg, Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
private void simpleButtonDuplicar_Click(object sender, EventArgs e)
{
Duplicar();
}
private void Duplicar()
{
if (Confirm("Deseja duplicar a(s) ordem(ns) de serviço selecionada(s)") == DialogResult.Yes)
{
foreach (var id in IdsSelecionados)
{
try
{
PDVControlador.BeginTransaction();
var ordemServico = FuncoesOrdemServico.GetOrdemDeServico(id);
ordemServico.DataCadastro = DateTime.Now;
ordemServico.DataFaturamento = null;
ordemServico.Status = Status.Aberto;
ordemServico.IDOrdemDeServico = Sequence.GetNextID("ORDEMDESERVICO", "IDORDEMDESERVICO");
FuncoesOrdemServico.Salvar(ordemServico, TipoOperacao.INSERT);
var itensOS = FuncoesItemOrdemDeServico.GetItensOrdemServico(id);
foreach (var item in itensOS)
{
item.IDOrdemDeServico = ordemServico.IDOrdemDeServico;
item.IDItemOrdemDeServico = Sequence.GetNextID("ITEMORDEMDESERVICO", "IDITEMORDEMDESERVICO");
FuncoesItemOrdemDeServico.Salvar(item);
}
var duplicatas = FuncoesDuplicataServico.GetDuplicatasServicos(id);
foreach (var duplicata in duplicatas)
{
duplicata.IDDuplicataServico = Sequence.GetNextID("DUPLICATASERVICO", "IDDUPLICATASERVICO");
duplicata.IDOrdemDeServico = ordemServico.IDOrdemDeServico;
FuncoesDuplicataServico.Salvar(duplicata);
}
PDVControlador.Commit();
}
catch (Exception ex)
{
PDVControlador.Rollback();
Alert(ex.Message);
}
}
Atualizar();
}
}
private void metroButtonRemover_Click(object sender, EventArgs e)
{
Remover();
}
private void Remover()
{
if (Confirm("Deseja remover a(s) ordem(ns) de serviço selecionada(s)") == DialogResult.Yes)
{
foreach (var id in IdsSelecionados)
{
try
{
PDVControlador.BeginTransaction();
var ordemDeServico = FuncoesOrdemServico.GetOrdemDeServico(id);
if (ordemDeServico.Status != Status.Aberto)
continue;
FuncoesDuplicataServico.Remover(id);
FuncoesItemOrdemDeServico.Remover(id);
if (!FuncoesOrdemServico.Remover(id))
throw new Exception($"Não foi possível remover a ordem {id}");
PDVControlador.Commit();
}
catch (Exception exception)
{
PDVControlador.Rollback();
Alert(exception.Message);
}
}
Atualizar();
}
}
private void simpleButton7_Click(object sender, EventArgs e)
{
IdsSelecionados.ForEach(id => Imprimir(id));
}
private void Imprimir(decimal idOS, bool visualizar = false)
{
var report = new Modelo2Servico(idOS);
using (var printTool = new ReportPrintTool(report))
{
report.ShowPrintMarginsWarning = report.PrintingSystem.ShowMarginsWarning = false;
if (visualizar)
{
printTool.ShowPreviewDialog();
return;
}
if (Confirm("Confirmar impressão?") == DialogResult.Yes)
printTool.Print();
}
}
private void simpleButton4_Click(object sender, EventArgs e)
{
Imprimir(IdsSelecionados.FirstOrDefault(), true);
}
}
}
|
using UnityEngine;
namespace HT.Framework
{
[CustomDebugger(typeof(Transform))]
internal sealed class DebuggerTransform : DebuggerComponentBase
{
private Transform _target;
private int _childCount;
public override void OnEnable()
{
_target = Target as Transform;
_childCount = _target.childCount;
}
public override void OnDebuggerGUI()
{
GUILayout.BeginHorizontal();
GUILayout.Label("ChildCount: " + _childCount);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Position:", GUILayout.Width(60));
_target.position = Vector3Field(_target.position);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Rotation:", GUILayout.Width(60));
_target.rotation = Quaternion.Euler(Vector3Field(_target.rotation.eulerAngles));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Scale:", GUILayout.Width(60));
_target.localScale = Vector3Field(_target.localScale);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.RepeatButton("x-"))
{
_target.Translate(-0.1f, 0, 0, Space.Self);
}
if (GUILayout.RepeatButton("x+"))
{
_target.Translate(0.1f, 0, 0, Space.Self);
}
if (GUILayout.RepeatButton("y-"))
{
_target.Translate(0, -0.1f, 0, Space.Self);
}
if (GUILayout.RepeatButton("y+"))
{
_target.Translate(0, 0.1f, 0, Space.Self);
}
if (GUILayout.RepeatButton("z-"))
{
_target.Translate(0, 0, -0.1f, Space.Self);
}
if (GUILayout.RepeatButton("z+"))
{
_target.Translate(0, 0, 0.1f, Space.Self);
}
GUILayout.EndHorizontal();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tryReflection
{
class Program
{
static void Main(string[] args)
{
cc<T> Do1<T>()
{
var ee = new cc<T>();
return ee;
}
var bb = Do1<aa>();
var dd = bb.GetType();
Console.WriteLine();
var hh = bb.GetType().GenericTypeArguments.Count();
var gg = bb.GetType().GenericTypeArguments[0].Name;
var jj = bb.GetType().GenericTypeArguments[0].FullName;
var ii = Type.GetType(jj);
var kk = System.Activator.CreateInstance(ii);
//var ll = ii.InvokeMember("ID");
//ii.GetMethod("ID");
aa aaa = new aa();
var mm = aaa.GetType().Name;
System.Reflection.MethodInfo method = ii.GetMethod(gg);
Console.ReadLine();
}
public static void doSomething<T>(T tt)
{
var aa = tt.GetType();
}
public class aa
{
public int ID { get; set; }
public string Name { get; set; }
}
public class cc<T>
{
public int ID { get; set; }
public string Name { get; set; }
}
}
}
|
using UnityEngine;
using System.Collections;
public class HandleController : MonoBehaviour
{
public ReelController[] reels;
Animation animation;
public int curReel = 0;
// Use this for initialization
void Start ()
{
animation = GetComponent<Animation> ();
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown (KeyCode.Space) && curReel < 3) {
reels[curReel].Rotate(Random.Range(0, 5));
curReel ++;
}
}
void OnMouseDown()
{
Debug.Log ("Spinning To Winning!");
animation.Play ();
foreach (ReelController reel in reels)
{
reel.rotating = true;
}
curReel = 0;
}
public void HandleDownAnimation()
{
//animation.Stop();
}
}
|
namespace Visitor.Entities.Interfaces
{
public interface IVisitor
{
void Identificar(Chefao chefao);
void Identificar(FaseJogo faseJogo);
}
}
|
using Dapper;
using HelperLibrary.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using static HelperLibrary.Tools;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConnectLibrary.Logger;
using ConnectLibrary.SQLRepository.Interfaces;
using ConnectLibrary.SQLRepository.Prototypes;
using HelperLibrary;
using static ConnectLibrary.DataAccess;
using static ConnectLibrary.LibrarySettings;
namespace ConnectLibrary.SQLRepository
{
public class GradeRepository : GeneralRepository<GradeModel>, IGradeRepository
{
public GradeRepository() : base(Tables.Grades){}
public event EventHandler<StudentEventArgs> AddedGrade;
readonly IDbConnection _connection = Connection;
private static DynamicParameters GradeProperties(GradeModel grade)
{
var p = new DynamicParameters();
p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output);
p.Add("@StudentId", grade.StudentId);
p.Add("@LectionId", grade.LectionId);
p.Add("@Grade", grade.Grade);
p.Add("@Date", grade.Date);
return p;
}
public int AddGrade(GradeModel grade)
{
if (grade == null)
{
Log.MakeLog(LoggerOperations.Error, "ArgumentNullException");
throw new ArgumentNullException(nameof(grade));
}
using (IDbConnection connection = _connection)
{
var p = GradeProperties(grade);
string sql = $@"insert into dbo.{Tables.Grades} (StudentId, LectionId, Grade, Date)
values (@StudentId, @LectionId, @Grade, @Date); select @Id = @@IDENTITY";
connection.Execute(sql, p);
OnGradeAdded(new StudentEventArgs() {grade = grade});
return p.Get<int>("@Id");
}
}
public GradeModel UpdateGrade(GradeModel grade)
{
if (grade == null)
{
Log.MakeLog(LoggerOperations.Error, "ArgumentNullException");
throw new ArgumentNullException(nameof(grade));
}
using (IDbConnection connection = _connection)
{
var p = GradeProperties(grade);
string sql = $@"update dbo.{Tables.Grades} set StudentId = @StudentId, LectionId = @LectionId,
Grade = @Grade, Date = @Date
where Id = {grade.Id}; select @Id = @@IDENTITY";
connection.Execute(sql, p);
return FindByID(grade.Id);
}
}
protected virtual void OnGradeAdded(StudentEventArgs args)
{
AddedGrade?.Invoke(this, args);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using KelpNet.Common.Functions;
using KelpNet.Functions.Mathmetrics.BasicMath;
namespace KelpNet.Common
{
[Serializable]
[DebuggerDisplay("{Name + ToString(\"Size\")}", Type = "{\"NdArray\" + ToString(\"Size\")}")]
public class NdArray
{
public string Name = "NdArray";
public Real[] Data;
[NonSerialized]
public Real[] Grad;
//Size of each dimension of this NdArray
public int[] Shape { private set; get; }
//Length calculated from Shape is different from Length of Data
public int Length { private set; get; }
//Count the number of times used by the function to try the timing of the backward operation
[NonSerialized]
public int UseCount;
//If it is generated from a function, save that function here
[NonSerialized]
public Function ParentFunc;
//Indicates the number of batches executed together in each function and used in the discount in the Loss function
public int BatchCount;
//Count the number of Backwards executed without updating and use it when executing Optimizer
[NonSerialized]
public int TrainCount;
public NdArray(Array data, Function parentFunc = null)
{
Real[] resultData = Real.GetArray(data);
int[] resultShape = new int[data.Rank];
for (int i = 0; i < data.Rank; i++)
{
resultShape[i] = data.GetLength(i);
}
this.Data = resultData;
this.Shape = resultShape;
this.Length = Data.Length;
//this.Grad = new Real[this.Length];
this.BatchCount = 1;
this.TrainCount = 0;
this.ParentFunc = parentFunc;
}
public NdArray(params int[] shape)
{
this.Data = new Real[ShapeToArrayLength(shape)];
this.Shape = shape.ToArray();
this.Length = Data.Length;
this.BatchCount = 1;
//this.Grad = new Real[this.Length];
this.TrainCount = 0;
}
public NdArray(Real[] data, int[] shape, int batchCount = 1, Function parentFunc = null)
{
this.Shape = shape.ToArray();
this.Length = ShapeToArrayLength(this.Shape);
this.BatchCount = batchCount;
this.Data = data.ToArray();
//this.Grad = new Real[this.Length * batchCount];
this.TrainCount = 0;
this.ParentFunc = parentFunc;
}
public NdArray(int[] shape, int batchCount, Function parentFunc = null)
{
this.Shape = shape.ToArray();
this.Length = ShapeToArrayLength(this.Shape);
this.BatchCount = batchCount;
this.Data = new Real[this.Length * batchCount];
//this.Grad = new Real[this.Length * batchCount];
this.TrainCount = 0;
this.ParentFunc = parentFunc;
}
public void InitGrad()
{
if (Grad == null)
Grad = new Real[Length];
}
//Register array array as batch
public static NdArray FromArrays(Array[] arrays, Function parentFunc = null)
{
int[] resultShape = new int[arrays[0].Rank];
for (int i = 0; i < arrays[0].Rank; i++)
{
resultShape[i] = arrays[0].GetLength(i);
}
int length = arrays[0].Length;
Real[] result = new Real[length * arrays.Length];
for (int i = 0; i < arrays.Length; i++)
{
Array.Copy(Real.GetArray(arrays[i]), 0, result, length * i, length);
}
return new NdArray(result, resultShape, arrays.Length, parentFunc);
}
public static NdArray Convert(Real[] data, int[] shape, int batchCount, Function parentFunc = null)
{
return new NdArray(shape, batchCount, parentFunc) { Data = data };
}
public static NdArray ZerosLike(NdArray baseArray)
{
return new NdArray(baseArray.Shape.ToArray(), baseArray.BatchCount);
}
//Because the indexer is not so early, I do not recommend using it when accessing frequently. Please divide it for debugging purpose.
public Real this[int batchcount, params int[] indices]
{
get
{
return this.Data[this.GetLocalIndex(batchcount, indices)];
}
set
{
this.Data[this.GetLocalIndex(batchcount, indices)] = value;
}
}
public void Reshape(params int[] shape)
{
int val = 0;
int dimension = Length;
//Calculate -1 designation
if (shape.Contains(-1))
{
int minusIndex = -1;
for (int i = 0; i < shape.Length; i++)
{
if (shape[i] != -1)
{
val += Length % shape[i];
if (val == 0)
{
dimension /= shape[i];
}
else
{
throw new Exception("The specification of the element is wrong");
}
}
else
{
if (minusIndex != -1)
{
throw new Exception("Two or more -1 are specified");
}
minusIndex = i;
}
}
shape[minusIndex] = dimension;
}
#if DEBUG
else if (Length != ShapeToArrayLength(shape)) throw new Exception("The size of the specified Shape is not equal to the current Data.Length");
#endif
Shape = shape.ToArray();
}
//Dispatch the unified array in batch and discharge
public NdArray[] DivideArrays()
{
NdArray[] result = new NdArray[BatchCount];
for (int i = 0; i < result.Length; i++)
{
result[i] = GetSingleArray(i);
}
return result;
}
//Eject the array corresponding to the batch number
public NdArray GetSingleArray(int i)
{
Real[] data = new Real[this.Length];
Array.Copy(this.Data, i * this.Length, data, 0, this.Length);
return new NdArray(data, this.Shape);
}
static int ShapeToArrayLength(params int[] shapes)
{
int result = 1;
foreach (int shape in shapes)
{
result *= shape;
}
return result;
}
public void Backward()
{
if (ParentFunc != null)
{
for (int i = 0; i < Grad.Length; i++)
{
Grad[i] = 1;
}
NdArray.Backward(this);
}
}
public static void Backward(NdArray y)
{
if (y.ParentFunc != null)
{
List<NdArray[]> prevInputs = y.ParentFunc.PrevInputs;
NdArray[] xs = prevInputs[prevInputs.Count - 1];
y.ParentFunc.Backward(y);
for (int i = 0; i < xs.Length; i++)
{
if (xs[i].UseCount == 0)
{
NdArray.Backward(xs[i]);
}
}
}
}
public void CountUp()
{
TrainCount++;
}
//Correction of slope
public bool Reduce()
{
if (this.TrainCount > 0)
{
for (int i = 0; i < this.Grad.Length; i++)
{
this.Grad[i] /= this.TrainCount;
}
return true;
}
return false;
}
//Initialization of slope
public void ClearGrad()
{
this.Grad = new Real[this.Data.Length];
//Reset counter
this.TrainCount = 0;
}
public override string ToString()
{
return ToString(this.Data);
}
public string ToString(string format)
{
switch (format)
{
case "Data":
return ToString(this.Data);
case "Grad":
return ToString(this.Grad);
case "Shape":
return "[" + string.Join(",", Shape) + "]";
case "Size":
return "[" + string.Join(",", Shape) + "]" +
(BatchCount > 1 ? "x" + BatchCount + "batch" : string.Empty);
case "Name":
return Name;
default:
return Name;
}
}
public string ToString(Real[] datas)
{
StringBuilder sb = new StringBuilder();
int intMaxLength = 0; //Maximum value of integer part
int realMaxLength = 0; //Maximum value after the decimal point
bool isExponential = false; //Will it be exponential representation?
foreach (Real data in datas)
{
string[] divStr = ((double)data).ToString().Split('.');
intMaxLength = Math.Max(intMaxLength, divStr[0].Length);
if (divStr.Length > 1)
{
isExponential |= divStr[1].Contains("E");
}
if (realMaxLength != 8 && divStr.Length == 2)
{
realMaxLength = Math.Max(realMaxLength, divStr[1].Length);
if (realMaxLength > 8)
{
realMaxLength = 8;
}
}
}
//Get divisor of array
int[] commonDivisorList = new int[this.Shape.Length];
//First manual acquisition
commonDivisorList[0] = this.Shape[this.Shape.Length - 1];
for (int i = 1; i < this.Shape.Length; i++)
{
commonDivisorList[i] = commonDivisorList[i - 1] * this.Shape[this.Shape.Length - i - 1];
}
if (this.BatchCount > 1)
{
sb.Append("{");
}
for (int batch = 0; batch < this.BatchCount; batch++)
{
int indexOffset = batch * Length;
//Leading parenthesis
for (int i = 0; i < this.Shape.Length; i++)
{
sb.Append("[");
}
int closer = 0;
for (int i = 0; i < Length; i++)
{
string[] divStr;
if (isExponential)
{
divStr = string.Format("{0:0.00000000e+00}", (Real)datas[indexOffset + i]).Split('.');
}
else
{
divStr = ((Real)datas[indexOffset + i]).ToString().Split('.');
}
//Align indentation with maximum number of characters
for (int j = 0; j < intMaxLength - divStr[0].Length; j++)
{
sb.Append(" ");
}
sb.Append(divStr[0]);
if (realMaxLength != 0)
{
sb.Append(".");
}
if (divStr.Length == 2)
{
sb.Append(divStr[1].Length > 8 && !isExponential ? divStr[1].Substring(0, 8) : divStr[1]);
for (int j = 0; j < realMaxLength - divStr[1].Length; j++)
{
sb.Append(" ");
}
}
else
{
for (int j = 0; j < realMaxLength; j++)
{
sb.Append(" ");
}
}
//If it is perfect after investigating divisors, it outputs parentheses
if (i != Length - 1)
{
foreach (int commonDivisor in commonDivisorList)
{
if ((i + 1) % commonDivisor == 0)
{
sb.Append("]");
closer++;
}
}
sb.Append(" ");
if ((i + 1) % commonDivisorList[0] == 0)
{
//Add line feed by closing parenthesis
for (int j = 0; j < closer; j++)
{
sb.Append("\n");
}
closer = 0;
if (BatchCount > 1) sb.Append(" ");
//Indentation before bracket
foreach (int commonDivisor in commonDivisorList)
{
if ((i + 1) % commonDivisor != 0)
{
sb.Append(" ");
}
}
}
foreach (int commonDivisor in commonDivisorList)
{
if ((i + 1) % commonDivisor == 0)
{
sb.Append("[");
}
}
}
}
//Parenthesis at the back end
for (int i = 0; i < this.Shape.Length; i++)
{
sb.Append("]");
}
if (batch < this.BatchCount - 1)
{
sb.Append("},\n{");
}
}
if (this.BatchCount > 1)
{
sb.Append("}");
}
return sb.ToString();
}
public static NdArray operator +(NdArray a, NdArray b)
{
return new Add().Forward(a, b)[0];
}
public static NdArray operator +(NdArray a, Real b)
{
return new AddConst().Forward(a, b)[0];
}
public static NdArray operator +(Real a, NdArray b)
{
return new AddConst().Forward(b, a)[0];
}
public static NdArray operator *(NdArray a, NdArray b)
{
return new Mul().Forward(a, b)[0];
}
public static NdArray operator *(NdArray a, Real b)
{
return new MulConst().Forward(a, b)[0];
}
public static NdArray operator *(Real a, NdArray b)
{
return new MulConst().Forward(b, a)[0];
}
public static NdArray operator -(NdArray a, NdArray b)
{
return new Sub().Forward(a, b)[0];
}
public static NdArray operator -(NdArray a, Real b)
{
return new SubConst().Forward(a, b)[0];
}
public static NdArray operator -(Real a, NdArray b)
{
return new ConstSub().Forward(a, b)[0];
}
public static NdArray operator /(NdArray a, NdArray b)
{
return new Div().Forward(a, b)[0];
}
public static NdArray operator /(NdArray a, Real b)
{
return new DivConst().Forward(a, b)[0];
}
public static NdArray operator /(Real a, NdArray b)
{
return new ConstDiv().Forward(a, b)[0];
}
public static implicit operator NdArray(Real[] a)
{
return new NdArray(a);
}
public static implicit operator NdArray(Real a)
{
return new NdArray(new[] { a });
}
public static implicit operator NdArray(long a)
{
return new NdArray(new[] { (Real)a });
}
//Method to create copy
public NdArray Clone()
{
return new NdArray
{
ParentFunc = ParentFunc,
Data = Data.ToArray(),
Grad = Grad.ToArray(),
Shape = Shape.ToArray(),
Name = Name,
Length = Length,
BatchCount = BatchCount,
UseCount = UseCount,
TrainCount = TrainCount
};
}
public static NdArray Sum(NdArray a, bool keepDims = false, params int[] axis)
{
#if DEBUG
if (axis.Length != axis.Distinct().ToArray().Length)
{
throw new Exception("The specified element is duplicated");
}
if (axis.Length != 0 && a.Shape.Length < axis.Max())
{
throw new Exception("The specified element is out of range");
}
#endif
if (axis.Length == 0)
{
axis = Enumerable.Range(0, a.Shape.Length).ToArray();
}
Array.Sort(axis);
NdArray result = Sum(a, axis[0]);
for (int i = 1; i < axis.Length; i++)
{
result = Sum(result, axis[i] - i);
}
if (keepDims)
{
List<int> resultKeepDimShape = new List<int>();
int count = a.Shape.Length - result.Shape.Length;
for (int i = 0; i < count; i++)
{
resultKeepDimShape.Add(1);
}
resultKeepDimShape.AddRange(result.Shape);
result.Shape = resultKeepDimShape.ToArray();
}
return result;
}
private static NdArray Sum(NdArray a, int axis)
{
int[] resultShape = new int[a.Shape.Length - 1];
for (int i = 0, j = 0; i < a.Shape.Length; i++)
{
if (i != axis)
{
resultShape[j++] = a.Shape[i];
}
}
NdArray result = new NdArray(resultShape, a.BatchCount);
for (int i = 0; i < a.Length; i++)
{
List<int> index = new List<int>(a.GetDimensionsIndex(i));
index.RemoveAt(axis);
int localIndex = result.GetLocalIndex(0, index.ToArray());
for (int batchCount = 0; batchCount < a.BatchCount; batchCount++)
{
result.Data[batchCount * result.Length + localIndex] += a.Data[batchCount * a.Length + i];
result.Grad[batchCount * result.Length + localIndex] += a.Grad[batchCount * a.Length + i];
}
}
return result;
}
public static NdArray[] Split(NdArray array, int indices, int axis = 1)
{
return Split(array, new[] { indices }, axis);
}
public static NdArray[] Split(NdArray array, int[] indices, int axis = 1)
{
int[] shapeOffets = new int[indices.Length + 1]; //An array in which the leading 0 of the input indices is added
int[] resultAxisShapes = new int[indices.Length + 1]; //Shape of specified axis after division
for (int i = 0; i < indices.Length; i++)
{
shapeOffets[i + 1] = indices[i];
resultAxisShapes[i] = indices[i] - shapeOffets[i];
}
resultAxisShapes[indices.Length] = array.Shape[axis] - indices[indices.Length - 1];
NdArray[] resultArrays = new NdArray[indices.Length + 1];
for (int i = 0; i < resultArrays.Length; i++)
{
int[] resultShape = array.Shape.ToArray();
resultShape[axis] = resultAxisShapes[i];
resultArrays[i] = new NdArray(resultShape, array.BatchCount);
}
for (int batchCount = 0; batchCount < array.BatchCount; batchCount++)
{
for (int i = 0; i < resultArrays.Length; i++)
{
for (int j = 0; j < resultArrays[i].Length; j++)
{
int[] resultIndex = resultArrays[i].GetDimensionsIndex(j);
resultIndex[axis] += shapeOffets[i];
int localIndex = array.GetLocalIndex(batchCount, resultIndex);
resultArrays[i].Data[batchCount * resultArrays[i].Length + j] = array.Data[localIndex];
resultArrays[i].Grad[batchCount * resultArrays[i].Length + j] = array.Grad[localIndex];
}
}
}
return resultArrays;
}
public static NdArray Concatenate(NdArray a, NdArray b, int axis)
{
int[] shapeList = a.Shape.ToArray();
shapeList[axis] += b.Shape[axis];
#if DEBUG
for (int i = 0; i < a.Shape.Length; i++)
{
if (i != axis && a.Shape[i] != b.Shape[i])
{
throw new Exception("The size of the array is not matched");
}
}
if (a.BatchCount != b.BatchCount)
{
throw new Exception("Batch size is not matched");
}
#endif
NdArray result = new NdArray(shapeList.ToArray(), a.BatchCount);
for (int batchCount = 0; batchCount < a.BatchCount; batchCount++)
{
int aInputBatchoffset = batchCount * a.Length;
int bInputBatchoffset = batchCount * b.Length;
for (int i = 0; i < a.Length; i++)
{
int resultindex = result.GetLocalIndex(batchCount, a.GetDimensionsIndex(i));
result.Data[resultindex] = a.Data[i + aInputBatchoffset];
result.Grad[resultindex] = a.Grad[i + aInputBatchoffset];
}
for (int i = 0; i < b.Length; i++)
{
int[] tmpIndex = b.GetDimensionsIndex(i);
tmpIndex[axis] += a.Shape[axis];
int resultIndex = result.GetLocalIndex(batchCount, tmpIndex);
result.Data[resultIndex] = b.Data[i + bInputBatchoffset];
result.Grad[resultIndex] = b.Grad[i + bInputBatchoffset];
}
}
return result;
}
internal int[] GetDimensionsIndex(int index)
{
//Correct batch
int batchCount = index / this.Length;
index -= this.Length * batchCount;
int[] dimensionsIndex = new int[this.Shape.Length];
for (int i = this.Shape.Length - 1; i >= 0; i--)
{
dimensionsIndex[i] = index % this.Shape[i];
index /= this.Shape[i];
}
return dimensionsIndex;
}
internal int GetLocalIndex(int batchIndex, params int[] indices)
{
int indicesLastIndex = indices.Length - 1;
int index = batchIndex * this.Length + indices[indicesLastIndex];
int rankoffset = 1;
for (int i = 1; i < indices.Length; i++)
{
rankoffset *= this.Shape[indicesLastIndex--];
index += indices[indicesLastIndex] * rankoffset;
}
return index;
}
}
} |
using System.Linq;
using System.Threading.Tasks;
namespace ChuanGoing.Base.Interface.Db
{
public interface IRepository<TEntity, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
#region Query
TEntity Get(TPrimaryKey key);
Task<TEntity> GetAsync(TPrimaryKey key);
IQueryable<TEntity> GetAll();
#endregion
#region Command
int Insert(TEntity entity);
Task<int> InsertAsync(TEntity entity);
int Update(TEntity entity);
Task<int> UpdateAsync(TEntity entity);
int Delete(TPrimaryKey key);
Task<int> DeleteAsync(TPrimaryKey key);
#endregion
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Windows;
using System.Windows.Controls.Primitives;
using JetBrains.Application.DataContext;
using JetBrains.Application.Settings;
using JetBrains.Application.UI.Options;
using JetBrains.Application.UI.Options.Options.ThemedIcons;
using JetBrains.Application.UI.UIAutomation;
using JetBrains.DataFlow;
using KaVE.RS.Commons;
using KaVE.VS.FeedbackGenerator.Settings;
using KaVE.VS.FeedbackGenerator.UserControls.Anonymization;
using KaVE.VS.FeedbackGenerator.Utils;
using KaVEISettingsStore = KaVE.RS.Commons.Settings.ISettingsStore;
namespace KaVE.VS.FeedbackGenerator.UserControls.OptionPage.AnonymizationOptions
{
[OptionsPage(
PID,
"Anonymization Settings",
typeof(OptionsThemedIcons.ExportLayer),
ParentId = RootOptionPage.PID,
Sequence = 2.0)]
public partial class AnonymizationOptionsControl : IOptionsPage
{
private const string PID =
"KaVE.VS.FeedbackGenerator.UserControls.OptionPage.AnonymizationOptions.AnonymizationOptionsControl";
public const ResetTypes ResetType = ResetTypes.AnonymizationSettings;
private readonly Lifetime _lifetime;
private readonly OptionsSettingsSmartContext _ctx;
private readonly KaVEISettingsStore _settingsStore;
private readonly IActionExecutor _actionExecutor;
private readonly DataContexts _dataContexts;
private readonly AnonymizationSettings _anonymizationSettings;
private readonly IMessageBoxCreator _messageBoxCreator;
public bool OnOk()
{
_settingsStore.SetSettings(_anonymizationSettings);
return true;
}
public AnonymizationOptionsControl(Lifetime lifetime,
OptionsSettingsSmartContext ctx,
KaVEISettingsStore settingsStore,
IActionExecutor actionExecutor,
DataContexts dataContexts,
IMessageBoxCreator messageBoxCreator)
{
_lifetime = lifetime;
_ctx = ctx;
_settingsStore = settingsStore;
_actionExecutor = actionExecutor;
_dataContexts = dataContexts;
InitializeComponent();
_anonymizationSettings = settingsStore.GetSettings<AnonymizationSettings>();
var anonymizationContext = new AnonymizationContext(_anonymizationSettings);
DataContext = anonymizationContext;
if (_ctx != null)
{
BindChangesToAnonymization();
}
_messageBoxCreator = messageBoxCreator;
}
public bool ValidatePage()
{
return true;
}
public EitherControl Control
{
get { return this; }
}
public string Id
{
get { return PID; }
}
private void OnResetSettings(object sender, RoutedEventArgs e)
{
var resetSettingDialog = AnonymizationOptionsMessages.ResetSettingDialog;
var result = _messageBoxCreator.ShowYesNo(resetSettingDialog);
if (result)
{
var settingResetType = new SettingResetType {ResetType = ResetType};
_actionExecutor.ExecuteActionGuarded<SettingsCleaner>(
settingResetType.GetDataContextForSettingResultType(_dataContexts, _lifetime));
var window = Window.GetWindow(this);
if (window != null)
{
window.Close();
}
}
}
#region jetbrains smart-context bindings
private void BindChangesToAnonymization()
{
_ctx.SetBinding(
_lifetime,
(AnonymizationSettings s) => (bool?) s.RemoveCodeNames,
Anonymization.RemoveCodeNamesCheckBox,
ToggleButton.IsCheckedProperty);
_ctx.SetBinding(
_lifetime,
(AnonymizationSettings s) => (bool?) s.RemoveDurations,
Anonymization.RemoveDurationsCheckBox,
ToggleButton.IsCheckedProperty);
_ctx.SetBinding(
_lifetime,
(AnonymizationSettings s) => (bool?) s.RemoveStartTimes,
Anonymization.RemoveStartTimesCheckBox,
ToggleButton.IsCheckedProperty);
}
#endregion
}
} |
using EmployeeCRUD.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace EmployeeCRUD.Repository
{
public class EmployeeRepository
{
private SqlConnection con;
//To Handle connection related activities
public EmployeeRepository()
{
string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new SqlConnection(constr);
}
//To Add Employee details
public bool AddEmployee(Employee obj)
{
SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@First_Name", obj.FirstName);
com.Parameters.AddWithValue("@Last_Name", obj.LastName);
com.Parameters.AddWithValue("@Gender", obj.Gender);
com.Parameters.AddWithValue("@Languages_known", obj.LanguagesKnown);
com.Parameters.AddWithValue("@Address_Id", obj.AddressId);
com.Parameters.AddWithValue("@Salary", obj.Salary);
com.Parameters.AddWithValue("@Is_Active", obj.IsActive);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
//To view employee details with generic list
public List<Employee> GetAllEmployees()
{
List<Employee> EmpList = new List<Employee>();
SqlCommand com = new SqlCommand("GetEmployees", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();
//Bind EmpModel generic list using dataRow
foreach (DataRow dr in dt.Rows)
{
EmpList.Add(
new Employee
{
Empid = Convert.ToInt32(dr["Id"]),
FirstName = Convert.ToString(dr["First_Name"]),
LastName = Convert.ToString(dr["Last_Name"]),
Gender = Convert.ToInt32(dr["Gender"]),
LanguagesKnown = Convert.ToString(dr["Languages_known"]),
AddressId = Convert.ToInt32(dr["Address_Id"]),
Salary = Convert.ToInt32(dr["Salary"]),
IsActive = Convert.ToBoolean(dr["Is_Active"]),
}
);
}
return EmpList;
}
//To Update Employee details
public bool UpdateEmployee(Employee obj)
{
SqlCommand com = new SqlCommand("UpdateEmpDetails", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", obj.Empid);
com.Parameters.AddWithValue("@First_Name", obj.FirstName);
com.Parameters.AddWithValue("@Last_Name", obj.LastName);
com.Parameters.AddWithValue("@Gender", obj.Gender);
com.Parameters.AddWithValue("@Languages_known", obj.LanguagesKnown);
com.Parameters.AddWithValue("@Address_Id", obj.AddressId);
com.Parameters.AddWithValue("@Salary", obj.Salary);
com.Parameters.AddWithValue("@Is_Active", obj.IsActive);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
//To delete Employee details
public bool DeleteEmployee(int Id)
{
SqlCommand com = new SqlCommand("DeleteEmpById", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@EmpId", Id);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
//Get all Countries
public DataSet Get_Country()
{
SqlCommand com = new SqlCommand("Select * from Country_Name", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
//Get all States
public DataSet Get_State(string country_id)
{
SqlCommand com = new SqlCommand("Select * from State_Name where CountryId=" + country_id, con);
com.Parameters.AddWithValue("@CountryId", country_id);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
//Get all Districts
public DataSet Get_District(string state_id)
{
SqlCommand com = new SqlCommand("Select * from District_Name where StateId=" + state_id, con);
com.Parameters.AddWithValue("@StateId", state_id);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public string GetAddressById(int addressId)
{
string address = "";
var countries = GetCountries();
var states = GetStates();
var districts = GetDistricts();
SqlCommand command = new SqlCommand("Select * from Address1 where Id=" + addressId, con);
command.Parameters.AddWithValue("@Id", addressId);
SqlDataReader reader;
con.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
address = reader.GetString(1) + "," + reader.GetString(2) + "," + countries[reader.GetInt32(3)-1] + "," + states[reader.GetInt32(4)-1] + "," + districts[reader.GetInt32(5)-1] + ',' + reader.GetString(6);
}
}
reader.Close();
con.Close();
return address;
}
public List<string> GetCountries()
{
List<string> countries = new List<string>();
SqlCommand command = new SqlCommand("Select * from Country_Name " , con);
SqlDataReader reader;
con.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
countries.Add(reader.GetString(1));
}
}
reader.Close();
con.Close();
return countries;
}
public List<string> GetStates()
{
List<string> states = new List<string>();
SqlCommand command = new SqlCommand("Select * from State_Name " , con);
SqlDataReader reader;
con.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
states.Add( reader.GetString(1));
}
}
reader.Close();
con.Close();
return states;
}
public List<string> GetDistricts()
{
List<string> districts = new List<string>();
SqlCommand command = new SqlCommand("Select * from District_Name ", con);
SqlDataReader reader;
con.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
districts.Add(reader.GetString(1));
}
}
reader.Close();
con.Close();
return districts;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MB.Models.POCO
{
public class UserInfo
{
public UserInfo()
{
this.users_roles = new HashSet<users_roles>();
}
[Key]
public string username { get; set; }
public string email_address { get; set; }
public string password { get; set; }
public Nullable<bool> locked { get; set; }
public Nullable<System.DateTime> locked_date { get; set; }
public Nullable<System.DateTime> last_login { get; set; }
public Nullable<System.DateTime> created_date { get; set; }
[ForeignKey("Account_Types")]
public string account_type { get; set; }
public string ip { get; set; }
public string security_question { get; set; }
public string security_answer { get; set; }
public Nullable<bool> online { get; set; }
public Nullable<bool> disabled { get; set; }
public virtual Account_Types Account_Types { get; set; }
public virtual StaffMember StaffMember { get; set; }
public virtual ICollection<users_roles> users_roles { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace Promelectro.Api.Models
{
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public DateTime DateCreate { get; set; }
public int? RoleId { get; set; }
public string Name { get; set; }
}
} |
using Books.Api.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Books.Api.Controllers
{
[Route("api/synchronousbooks")]
[ApiController]
public class SynchronousBookController:ControllerBase
{
private IBooksRepository _booksRepository;
public SynchronousBookController(IBooksRepository booksRepository)
{
_booksRepository = booksRepository ?? throw new ArgumentNullException(nameof(booksRepository));
}
[HttpGet]
public IActionResult GetBooks()
{
var bookEntites = _booksRepository.GetBooks();
return Ok(bookEntites);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Entidades
{
public class PersonaDAO
{
static SqlConnection conexion;
static SqlCommand comando;
static PersonaDAO()
{
conexion = new SqlConnection("Data Source = ./SQLEXPRESS;Initial Catalog = Persona; Integrated Security = True");
comando = new SqlCommand();
comando.Connection = conexion;
comando.CommandType = System.Data.CommandType.Text;
}
public void Guardar(Persona p)
{
String consulta = String.Format("INSERT INTO Personas (Nombre, Apellido) VALUES ('{0}', '{1}')", p.Nombre, p.Apellido);
conexion.Open();
comando.CommandText = consulta;
comando.ExecuteNonQuery();
conexion.Close();
}
public List<Persona> Leer()
{
List<Persona> lista = new List<Persona>();
String consulta = String.Format("SELECT ID, Nombre, Apellido FROM Persona");
conexion.Open();
comando.CommandText = consulta;
SqlDataReader oDr = comando.ExecuteReader();
while (oDr.Read())
{
lista.Add(new Persona (oDr["ID"].ToString(), oDr["Nombre"].ToString(), oDr["Apellido"].ToString()));
}
conexion.Close();
return lista;
}
public Persona LeerPorID(string id)
{
String consulta = String.Format("SELECT ID, Nombre, Apellido FROM Persona WHERE ID = {0}",id);
conexion.Open();
comando.CommandText = consulta;
SqlDataReader oDr = comando.ExecuteReader();
if (oDr.Read())
{
Persona p = new Persona(id, oDr["Nombre"].ToString(), oDr["Apellido"].ToString());
conexion.Close();
return p;
}
conexion.Close();
return null;
}
public void Modificar(string id, Persona p)
{
String consulta = String.Format("UPDATE Persona SET Nombre = '{0}', Apellido = '{1}' WHERE ID = {2}", id, p.Nombre, p.Apellido);
conexion.Open();
comando.CommandText = consulta;
comando.ExecuteNonQuery();
conexion.Close();
}
public void Borrar(string id)
{
String consulta = String.Format("DELETE FROM Persona WHERE ID = {0}", id);
conexion.Open();
comando.CommandText = consulta;
comando.ExecuteNonQuery();
conexion.Close();
}
}
}
|
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Maze_Finding_Bean
{
public class MenuNewGame : Menu
{
public MenuNewGame(float left, float top, List<Texture2D> background) : base(left,top,background)
{
}
public override int ProcessEvent(object obj)
{
return 1;
}
}
}
|
using System;
using System.Reactive;
using System.Threading;
using System.Threading.Tasks;
using OmniSharp.Extensions.DebugAdapter.Protocol.Client;
using OmniSharp.Extensions.DebugAdapter.Protocol.Server;
using OmniSharp.Extensions.JsonRpc.Testing;
using Xunit;
using Xunit.Abstractions;
namespace Dap.Tests.Integration.Fixtures
{
public abstract class DebugAdapterProtocolFixtureTest<TConfigureFixture, TConfigureClient, TConfigureServer>
: IClassFixture<DebugAdapterProtocolFixture<TConfigureFixture, TConfigureClient, TConfigureServer>>
where TConfigureFixture : IConfigureDebugAdapterProtocolFixture, new()
where TConfigureClient : IConfigureDebugAdapterClientOptions, new()
where TConfigureServer : IConfigureDebugAdapterServerOptions, new()
{
protected DebugAdapterProtocolFixture<TConfigureFixture, TConfigureClient, TConfigureServer> Fixture { get; }
protected DebugAdapterProtocolFixtureTest(ITestOutputHelper testOutputHelper, DebugAdapterProtocolFixture<TConfigureFixture, TConfigureClient, TConfigureServer> fixture)
{
Fixture = fixture;
Client = fixture.Client;
Server = fixture.Server;
CancellationToken = fixture.CancellationToken;
ClientEvents = fixture.ClientEvents;
ServerEvents = fixture.ServerEvents;
Events = fixture.Events;
fixture.Swap(testOutputHelper);
}
protected IDebugAdapterServer Server { get; }
protected IDebugAdapterClient Client { get; }
protected CancellationToken CancellationToken { get; }
public ISettler ClientEvents { get; }
public ISettler ServerEvents { get; }
public ISettler Events { get; }
public Task SettleNext() => Events.SettleNext();
public IObservable<Unit> Settle() => Events.Settle();
}
}
|
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UdemyMurat.Models.Sınıflar;
namespace UdemyMurat.Controllers
{
public class KargoController : Controller
{
Context c = new Context();
// GET: Kargo
public ActionResult Index(string p)
{
var kargolar = from x in c.KargoDetays select x;
if (!string.IsNullOrEmpty(p))
{
kargolar = kargolar.Where(z => z.TakipKodu.Contains(p));
}
return View(kargolar.ToList());
}
public ActionResult KargoEkle()
{
Random rnd = new Random();
string[] karakterler = {"A", "B", "C", "D", "E", "F", "G", "H", "K" };
int k1, k2, k3;
k1 = rnd.Next(0, karakterler.Length);
k2 = rnd.Next(0, karakterler.Length);
k3 = rnd.Next(0, karakterler.Length);
int s1, s2, s3;
s1 = rnd.Next(100, 1000);
s2 = rnd.Next(10, 99);
s3 = rnd.Next(10, 99);
string kod = s1.ToString() + karakterler[k1] + s2 + karakterler[k2] + s3 + karakterler[k3];
ViewBag.takipkod = kod;
return View();
}
[HttpPost]
public ActionResult KargoEkle(KargoDetay k)
{
k.Tarih = DateTime.Now;
if (!ModelState.IsValid)
{
return View("KargoEkle");
}
c.KargoDetays.Add(k);
c.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult KargoTakip(string id)
{
var degerler = c.KargoTakips.Where(x => x.TakipKodu == id).ToList();
using (MemoryStream ms = new MemoryStream())
{
QRCodeGenerator kodyarat = new QRCodeGenerator();
QRCodeGenerator.QRCode karekod = kodyarat.CreateQrCode(id,
QRCodeGenerator.ECCLevel.Q);
using (Bitmap sekil = karekod.GetGraphic(10))
{
sekil.Save(ms, ImageFormat.Png);
ViewBag.karekodsekil = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
}
return View(degerler);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MrHai.Core.Models;
using TwinkleStar.Common.Others;
using MrHai.Application.Models;
using TwinkleStar.Common.Extensions;
using MrHai.Core.Models.Enums;
namespace MrHai.Core
{
/// <summary>
/// Category相关
/// </summary>
public abstract partial class MrHaiService
{
/// <summary>
/// 获取树状菜单列表
/// </summary>
/// <param name="type"></param>
/// <param name="pids"></param>
/// <param name="isGetEnabled"></param>
/// <returns></returns>
public virtual OperationResult GetCategories(NavigationType type = NavigationType.MainNavigation, List<string> pids = null, bool isGetEnabled = false)
{
var or = new OperationResult(OperationResultType.Success);
var models = CategoryRepository.GetModel().Where(p => p.CategoryType == type &&
p.IsDeleted == false);
if (!isGetEnabled)
{
models = models.Where(p => p.Enabled == true);
}
if (pids != null && pids.Count > 0)
{
models = models.Where(p => pids.Contains(p.ParentId));
}
else
{
models = models.Where(p => p.ParentId == null);
}
var data = models.OrderByDescending(p => p.OrderNum).ToList().MapToList<CategoryListDto>().ToList();
GetChildCategories(data, type);
or.AppendData = data;
return or;
}
public virtual OperationResult GetCategories(List<string> ids)
{
ids = ids ?? new List<string>();
var or = new OperationResult(OperationResultType.Success);
var data = CategoryRepository.GetModel().Where(p => ids.Contains(p.Id)).ToList();
or.AppendData = data;
return or;
}
public virtual OperationResult GetCategory(string id)
{
var or = new OperationResult(OperationResultType.Success);
var data = CategoryRepository.GetModel().FirstOrDefault(p => p.Id == id);
or.AppendData = data;
return or;
}
public virtual OperationResult GetRootCategories()
{
var or = new OperationResult(OperationResultType.Success);
var data = CategoryRepository.GetModel().Where(p => p.Enabled == true
&& p.CategoryType == NavigationType.MainNavigation
&& p.IsDeleted == false && p.Level == 0).OrderByDescending(p => p.OrderNum);
or.AppendData = data.ToList();
return or;
}
public virtual OperationResult GetChildCategories(string pid, NavigationType type)
{
var or = new OperationResult(OperationResultType.Success);
var data = CategoryRepository.GetModel().Where(p => p.Enabled == true
&& p.CategoryType == type && p.ParentId == pid
&& p.IsDeleted == false).OrderByDescending(p=>p.OrderNum);
or.AppendData = data.ToList();
return or;
}
/// <summary>
/// 获取菜单数据
/// </summary>
/// <param name="parentCategories"></param>
/// <param name="type"></param>
/// <returns></returns>
public virtual IEnumerable<CategoryListDto> GetChildCategories(List<CategoryListDto> parentCategories, NavigationType type)
{
var models = new List<CategoryListDto>();
if (parentCategories != null)
{
var pids = parentCategories.Select(p => p.Id).ToList();
models = CategoryRepository.GetModel().Where(p => pids.Contains(p.ParentId) &&
p.IsDeleted == false && p.Enabled == true).ToList()?.MapToList<CategoryListDto>();
if (models != null && models.Count > 0)
{
GetChildCategories(models, type);
}
foreach (var category in parentCategories)
{
var mainchilds = models.Where(p => p.ParentId == category.Id && p.CategoryType == type).OrderByDescending(p => p.OrderNum).ToList() ?? new List<CategoryListDto>();
var articleChilds = models.Where(p => p.ParentId == category.Id && p.CategoryType != type).OrderByDescending(p => p.OrderNum).ToList() ?? new List<CategoryListDto>();
category.ChildCategory = mainchilds;
category.HasOtherNavigation = articleChilds != null && articleChilds.Count > 0;
}
}
return models;
}
//获取所有作品名
public virtual OperationResult GetWorksName()
{
var or = new OperationResult(OperationResultType.Success);
List<CategoryListDto> workList = new List<CategoryListDto>();
var worksPNode = GetCategories(NavigationType.MainNavigation, new List<string> { "1" }).AppendData as List<CategoryListDto>;
foreach (var item in worksPNode)
{
foreach (var child in item.ChildCategory)
{
CategoryListDto entity = new CategoryListDto()
{
Id = child.Id,
Name = child.Name
};
workList.Add(entity);
}
}
or.AppendData = workList;
return or;
}
public virtual OperationResult GetWorksName(string id)
{
var or = new OperationResult(OperationResultType.Success);
List<CategoryListDto> workList = new List<CategoryListDto>();
var worksPNode = GetCategories(NavigationType.MainNavigation, new List<string> { id }).AppendData as List<CategoryListDto>;
foreach (var item in worksPNode)
{
foreach (var child in item.ChildCategory)
{
CategoryListDto entity = new CategoryListDto()
{
Id = child.Id,
Name = child.Name
};
workList.Add(entity);
}
}
or.AppendData = workList;
return or;
}
public virtual int AddCategory(string name, string pid, NavigationType type, bool isThird = false)
{
Category parent = null;
if (!string.IsNullOrEmpty(pid))
{
parent = CategoryRepository.Find(pid);
}
var maxOrdModel = CategoryRepository.GetModel().OrderByDescending(p => p.OrderNum).FirstOrDefault();
var max = maxOrdModel?.OrderNum + 1 ?? 1;
var model = new Category()
{
Name = name,
ParentId = string.IsNullOrEmpty(pid) ? null : pid,
CategoryType = type,
Level = parent == null ? 0 : parent.Level + 1,
OrderNum = max,
Enabled = true,
IsDeleted = false,
};
if (isThird)
{
AddChildCategory(model.Id);
}
return CategoryRepository.Insert(model);
}
public virtual string AddCategoryAndReturnId(string name, string pid, NavigationType type)
{
Category parent = null;
if (!string.IsNullOrEmpty(pid))
{
parent = CategoryRepository.Find(pid);
}
var maxOrdModel = CategoryRepository.GetModel().OrderByDescending(p => p.OrderNum).FirstOrDefault();
var max = maxOrdModel?.OrderNum + 1 ?? 1;
var model = new Category()
{
Name = name,
ParentId = string.IsNullOrEmpty(pid) ? null : pid,
CategoryType = type,
Level = parent == null ? 0 : parent.Level + 1,
OrderNum = max,
Enabled = true,
IsDeleted = false,
};
model.Url = GlobalConstants.FragmentUrl + $"?pid={model.ParentId}&infoid={model.Id}";
CategoryRepository.Insert(model);
return model.Id;
}
public int AddChildCategory(string pid)
{
var nameList = new List<string>() { "about", "film trailer", "film stills", "installation", "exhibitions", "related texts", "publications" };
int orderNum = 6;
foreach (var name in nameList)
{
var model = new Category()
{
Name = name,
ParentId = string.IsNullOrEmpty(pid) ? null : pid,
CategoryType = NavigationType.ArticleNavigation,
Level = 0,
OrderNum = orderNum,
Enabled = true,
IsDeleted = false,
};
this.CategoryRepository.Insert(model);
orderNum--;
}
return 1;
}
public virtual int EditCategory(string name, string id)
{
var editCount = 0;
var model = this.CategoryRepository.Find(id);
model.Url= GlobalConstants.ProaboutUrl + $"?pid={model.ParentId}&infoid={model.Id}";
if (model != null)
{
model.Name = name;
editCount = this.CategoryRepository.Update(model);
}
return editCount;
}
public virtual int SortCategory(string pid, int num)
{
var model = this.CategoryRepository.Find(pid);
var changeNum = 0;
Category changeModel = null;
if (num > 0)
{
changeModel = this.CategoryRepository.GetModel(p => p.OrderNum > model.OrderNum && p.ParentId == model.ParentId && p.IsDeleted == false && p.Enabled == true)
.OrderBy(p => p.OrderNum)
.FirstOrDefault();
changeNum = changeModel?.OrderNum ?? model.OrderNum + 1;
}
else
{
changeModel = this.CategoryRepository.GetModel(p => p.OrderNum < model.OrderNum && p.ParentId == model.ParentId && p.IsDeleted == false && p.Enabled == true)
.OrderByDescending(p => p.OrderNum)
.FirstOrDefault();
changeNum = changeModel?.OrderNum ?? model.OrderNum - 1;
}
if (changeModel != null)
{
changeModel.OrderNum = model.OrderNum;
CategoryRepository.Update(changeModel);
}
model.OrderNum = changeNum;
return CategoryRepository.Update(model);
}
public virtual int DeleteCategory(string id, bool isDelChild = true)
{
var model = CategoryRepository.GetModel().FirstOrDefault(p => p.Id == id &&
p.IsDeleted == false && p.Enabled == true);
if (isDelChild)
{
DeleteChild(model.Id);
}
model.DeletedTime = DateTime.Now;
model.IsDeleted = true;
CategoryRepository.Update(model);
return 0;
}
private void DeleteChild(string pid)
{
var items = CategoryRepository.GetModel().Where(p => p.ParentId == pid).ToList();
foreach (var category in items)
{
DeleteChild(category.Id);
category.DeletedTime = DateTime.Now;
category.IsDeleted = true;
this.CategoryRepository.Update(category);
}
}
public virtual int ChangeCategoryEnabled(string id)
{
var model = CategoryRepository.Find(id);
var enabled = !(model.Enabled.HasValue ? model.Enabled : true);
model.Enabled = enabled;
return this.CategoryRepository.Update(model);
}
//public virtual int DeleteCategory(string id)
//{
// var model =
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Facultate.Data;
using Facultate.Models;
namespace Facultate.Pages.ProfessorRanks
{
public class IndexModel : PageModel
{
private readonly Facultate.Data.FacultateContext _context;
public IndexModel(Facultate.Data.FacultateContext context)
{
_context = context;
}
public IList<ProfessorRank> ProfessorRank { get;set; }
public async Task OnGetAsync()
{
ProfessorRank = await _context.ProfessorRank.ToListAsync();
}
}
}
|
namespace ModelAndroidAppSimples
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("BaseAPP")]
public partial class BaseAPP
{
public int ID { get; set; }
public string Cliente { get; set; }
public string Vendedores { get; set; }
public string Condicao { get; set; }
public string Produto { get; set; }
public string Pedido { get; set; }
public string PedidoItem { get; set; }
public string Documento { get; set; }
public string Movimento { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scrEnemyManager : MonoBehaviour {
public static scrEnemyManager EnemyManager;
[Header("BaseEnemies")]
public GameObject[] BaseEnemiesArray;
//public SpriteRenderer[] BaseEnemiesRendererArray;
public float randomVariable;
public float currentRandomVariable;
public Transform enemyBaseTarget;
public Transform Player;
public int baseEnemyDamages;
[Header("Gorilla Mini Boss")]
public int gorillaRockDamage;
public int gorillaContactDamage;
public GameObject GorillaBossTarget;
public Transform gorillaPivot;
// Use this for initialization
void Start () {
EnemyManager = this;
}
// Update is called once per frame
void Update () {
if (scrCompetenceManager.CompetenceManager.taunted)
{
enemyBaseTarget = scrCompetenceManager.CompetenceManager.totemPosition;
}
else
{
enemyBaseTarget = Player;
}
}
}
|
using DEMO_DDD.DOMAIN.Entidades;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DEMO_DDD.DOMAIN.Interfaces.Services
{
public interface IProdutoService : IServiceBase<Produto>
{
Task<IEnumerable<Produto>> BuscarPorNome(string nome);
}
}
|
using System.Diagnostics;
using System.Reflection;
using System.Windows;
namespace HandyControlDemo.Window
{
public partial class AboutWindow
{
public AboutWindow()
{
InitializeComponent();
DataContext = this;
var versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);
CopyRight = versionInfo.LegalCopyright;
Version = $"v {versionInfo.FileVersion}";
}
public static readonly DependencyProperty CopyRightProperty = DependencyProperty.Register(
"CopyRight", typeof(string), typeof(AboutWindow), new PropertyMetadata(default(string)));
public string CopyRight
{
get => (string) GetValue(CopyRightProperty);
set => SetValue(CopyRightProperty, value);
}
public static readonly DependencyProperty VersionProperty = DependencyProperty.Register(
"Version", typeof(string), typeof(AboutWindow), new PropertyMetadata(default(string)));
public string Version
{
get => (string) GetValue(VersionProperty);
set => SetValue(VersionProperty, value);
}
}
}
|
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace JqD.Common.WindsorInstaller
{
public class CurrentTimeProviderInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<ICurrentTimeProvider>().ImplementedBy<CurrentTimeProvider>().LifestyleSingleton()
);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MaterialDesignColors.WpfExample.Domain;
using Emgu.CV;
using Emgu.CV.Structure;
using Chpoi.SuitUp.Source;
using Chpoi.SuitUp.Entity;
using Chpoi.SuitUp.Service;
using Chpoi.SuitUp.Util;
namespace chpoi.suitup.ui
{
/// <summary>
/// Interaction logic for SellerInforWindow.xaml
/// </summary>
public partial class SellerInforWindow : Window
{
public SellerInforWindow()
{
InitializeComponent();
try
{
//从内存中初始化信息
this.OldClientName.Text = SourceManager.client.clientname;
//this.OldPassword.Text = SourceManager.client.password;
if (SourceManager.client.age == 0)
{
this.OldAge.Text = "";
}
else
{
this.OldAge.Text = SourceManager.client.age.ToString();
}
this.OldAddress.Text = SourceManager.client.address;
}
catch
{
MessageBox.Show("初始化买家信息错误!");
}
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
private void CloseButtonClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void MinimizeButtonClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void ModifyButtonClick(object sender, RoutedEventArgs e)
{
//点击修改按钮,转换为可编辑文本
ClientNameSP.Visibility = Visibility.Collapsed;
AgeSP.Visibility = Visibility.Collapsed;
AddressSP.Visibility = Visibility.Collapsed;
PasswordSP.Visibility = Visibility.Collapsed;
ModifyClientNameSP.Visibility = Visibility.Visible;
ModifyAgeSP.Visibility = Visibility.Visible;
ModifyAddressSP.Visibility = Visibility.Visible;
ModifyPasswordSP.Visibility = Visibility.Visible;
ModifyButton.Visibility = Visibility.Collapsed;
SaveChangesButton.Visibility = Visibility.Visible;
CancelchangesButton.Visibility = Visibility.Visible;
}
private void SaveChangesButtonClick(object sender, RoutedEventArgs e)
{
//保存修改后的信息
try
{
string NewClientName = InputClientName.Text;
int NewAge;
if (InputAge.Text == "")
{
NewAge = SourceManager.client.age;
}
else
{
try
{
int.Parse(InputAge.Text);
}
catch
{
MessageBox.Show("年龄不合法!");
return;
}
NewAge = int.Parse(InputAge.Text);
}
string NewAddress = InputAddress.Text;
string NewPassword = InputPassword.Password;
//保存信息到服务器
ClientService cS = ServiceFactory.GetClientService();
cS.ModifyInfor(NewClientName, NewAge, NewAddress, NewPassword);
Client c = new Client(NewPassword, NewClientName, NewAge, NewAddress);
SourceManager.client = c;
//显示修改后信息
this.OldClientName.Text = SourceManager.client.clientname;
//this.OldPassword.Text = SourceManager.client.password;
if (SourceManager.client.age == 0)
{
this.OldAge.Text = "";
}
else
{
this.OldAge.Text = SourceManager.client.age.ToString();
}
this.OldAddress.Text = SourceManager.client.address;
//切换到不可编辑界面
ClientNameSP.Visibility = Visibility.Visible;
AgeSP.Visibility = Visibility.Visible;
AddressSP.Visibility = Visibility.Visible;
PasswordSP.Visibility = Visibility.Visible;
ModifyClientNameSP.Visibility = Visibility.Collapsed;
ModifyAgeSP.Visibility = Visibility.Collapsed;
ModifyAddressSP.Visibility = Visibility.Collapsed;
ModifyPasswordSP.Visibility = Visibility.Collapsed;
SaveChangesButton.Visibility = Visibility.Collapsed;
CancelchangesButton.Visibility = Visibility.Collapsed;
ModifyButton.Visibility = Visibility.Visible;
}
catch
{
MessageBox.Show("修改买家信息错误!");
}
}
private void CancelChangesButtonClick(object sender, RoutedEventArgs e)
{
//切换到不可编辑界面
try
{
ClientNameSP.Visibility = Visibility.Visible;
AgeSP.Visibility = Visibility.Visible;
AddressSP.Visibility = Visibility.Visible;
PasswordSP.Visibility = Visibility.Visible;
ModifyClientNameSP.Visibility = Visibility.Collapsed;
ModifyAgeSP.Visibility = Visibility.Collapsed;
ModifyAddressSP.Visibility = Visibility.Collapsed;
ModifyPasswordSP.Visibility = Visibility.Collapsed;
SaveChangesButton.Visibility = Visibility.Collapsed;
CancelchangesButton.Visibility = Visibility.Collapsed;
ModifyButton.Visibility = Visibility.Visible;
}
catch
{
MessageBox.Show("系统错误,请稍后再试。");
}
}
private void PersonalInforButtonClick(object sender, RoutedEventArgs e)
{
}
private void UploadAvatarButtonClick(object sender, RoutedEventArgs e)
{
//上传头像
try
{
string sidePhotoPath = InputAvatarTextBox.Text;
Image<Bgr, byte> srcImage = new Image<Bgr, byte>(sidePhotoPath);
AvatarImage.Source = new BitmapImage(new Uri(sidePhotoPath, UriKind.RelativeOrAbsolute));
MessageBox.Show("Upload Compelete!");
}
catch
{
MessageBox.Show("Upload Failed!");
}
//to do with server
}
private void LogOutButtonClick(object sender, RoutedEventArgs e)
{
//注销
LoginWindow lW = new LoginWindow();
lW.Show();
this.Close();
}
private void OrderManageButtonClick(object sender, RoutedEventArgs e)
{
}
private void GoodsManageButtonClick(object sender, RoutedEventArgs e)
{
}
private void SellerInforButtonClick(object sender, RoutedEventArgs e)
{
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Casualty
{
public string name;
public int num_wounded = 0;
public int num_killed = 0;
}
// Class that contains pre battle information, and will be populated with post battle information after it is done.
// Create this object before the battle, load the battle level, when the battle is finished we will load back the overworld and can analyze the battle results.
// This object persists between level loads. Destroy this object when done analyzing post battle info.
// Ensure only of these objects ever exist.
public class PersistentBattleSettings : MonoBehaviour
{
public static PersistentBattleSettings battle_settings;
// PRE BATTLE SETTINGS
public string path_to_battle_file; // Ex: /Resources/Battles/LevelFiles/Level1.txt
public bool can_retreat = true;
public bool must_include_main_hero = false;
public bool player_goes_first = true; // If the player is ambusdhing the enemy or has an advantage, check this so the player goes first and has an advantage
public bool show_enemy_units_in_deployment = false; // If the player is ambusdhing the enemy or has an advantage, check this so the player has maximum information when deploying
public int number_of_deployable_units; // How many guys can we bring to this brawl? Leadership will affect this
public float enemy_agressiveness = 1; // 1 means agressive. 0 means defensive. Set to whether or not the player is defending or attacking
// POST BATTLE INFORMATION
public bool victory; // Did we win?
public bool game_over = false; // Did this battle result in all units being casualties while Odysseus was deployed?
public bool hero_went_down = false; // Did our hero die? Perhaps used to write different after-battle reports.
// Overall statistics
// Accessed by using the faction's ID in the arrays below. Player faction is always 1. Enemy faction is 2. 0 is unused.
public int[] units_lost; // Full squads who were killed who belonged to this faction
public int[] individuals_lost; // Ex: Each squad has 5 individuals, say in the battle we killed 38 guys, from 8 squads. 38 individuals killed. 1 hero = 1 individual
public int[] units_retreated;
public int[] individuals_retreated;
// Specific units statistics
// Accessed by faction ID and u_name
public Dictionary<string, Casualty>[] casualties;
void Awake ()
{
// If there's already a battle_settings, delete it. There should only be one battle settings
if (PersistentBattleSettings.battle_settings != null)
{
Debug.Log("PersistentBattleSettings already exist. Destroy this script");
this.gameObject.SetActive(false);
//DestroyImmediate(this.gameObject);
return;
}
else
{
battle_settings = this;
DontDestroyOnLoad(this.gameObject);
}
}
// Called after all factions have been created
public void PopulateBattleStatistics()
{
units_lost = new int[BattleManager.battle_manager.factions.Count + 1];
individuals_lost = new int[BattleManager.battle_manager.factions.Count + 1];
units_retreated = new int[BattleManager.battle_manager.factions.Count + 1];
individuals_retreated = new int[BattleManager.battle_manager.factions.Count + 1];
casualties = new Dictionary<string, Casualty>[BattleManager.battle_manager.factions.Count + 1];
for (int x = 0; x < casualties.Length; x++)
casualties[x] = new Dictionary<string, Casualty>();
}
public string GetProperPathToFile()
{
return "/Resources/Battles/LevelFiles/" + path_to_battle_file;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business.Helper;
using Model.DataEntity;
using Model.Locale;
using Model.Security.MembershipManagement;
using Utility;
using Uxnet.Web.WebUI;
using Model.InvoiceManagement;
using eIVOGo.Module.Common;
using eIVOGo.Helper;
namespace eIVOGo.Module.EIVO
{
public partial class ImportAllowanceCancellationPreview : ImportInvoicePreview
{
protected override void btnAddCode_Click(object sender, EventArgs e)
{
try
{
//檢核成功寫入資料庫
if (_mgr is GoogleAllowanceCancellationUploadManager && _mgr.Save())
{
Response.Redirect(NextAction.RedirectTo);
}
else
{
this.AjaxAlert("匯入失敗!!");
}
}
catch (Exception ex)
{
Logger.Error(ex);
this.AjaxAlert("匯入失敗,錯誤原因:" + ex.Message);
}
}
}
} |
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.Transfers
{
public class TransferXRegisterToStackPointer : OpCode
{
public override string Name => "TXS";
public TransferXRegisterToStackPointer(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
public override int Execute()
{
cpu.StackPointer = cpu.XRegister;
return 0;
}
}
} |
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 WindowsFormsApp1
{
public partial class Exercicio2 : Form
{
public Exercicio2()
{
InitializeComponent();
// Desabilitando os campos de resultado (Total da compra, desconto e total final)
textTotalCompra.Enabled = false;
textTotalFinal.Enabled = false;
textDesconto.Enabled = false;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
//Botão Calcular
private void btnCalcular_Click(object sender, EventArgs e)
{
int quantidade;
double valorUnitario, totalCompra, desconto,totalFinal;
//Variável quantidade recebendo o valor do campo de texto convertido para o tipo inteiro
quantidade = int.Parse(textQuantidade.Text);
//Variável quantidade recebendo o valor do campo de texto convertido para o tipo double ou real
valorUnitario = double.Parse(textValorUnitario.Text);
//Calculando o total da compra
totalCompra = quantidade * valorUnitario;
//Mostrando(atribuindo) o valor da compra no textTotalCompra
textTotalCompra.Text = totalCompra.ToString();
// Se a quantidade for entre 1 e 5
if (quantidade >= 1 && quantidade <= 5)
{
//calculando o desconto, multiplica-se o valor da compra vezes percentual
desconto = totalCompra * 0.02;
// total final da compra
totalFinal = totalCompra - desconto;
}
else if (quantidade >= 6 && quantidade <= 10)
{
//calculando o desconto, multiplica-se o valor da compra vezes percentual
desconto = totalCompra * 0.03;
// total final da compra
totalFinal = totalCompra - desconto;
}
else
{
//calculando o desconto, multiplica-se o valor da compra vezes percentual
desconto = totalCompra * 0.05;
// total final da compra
totalFinal = totalCompra - desconto;
}
//Atribuindo o desconto do desconto no textDesconto, para isso o valor do desconto deve ser convertido para string
textDesconto.Text = desconto.ToString();
// Atribuindo o total final no textTotalFinal, para isso o valor do total final deve ser convertido para string
textTotalFinal.Text = totalFinal.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
using System.Collections.Generic;
namespace Lykke.Service.SmsSender.Core.Domain.SmsSenderSettings
{
public class SmsProviderCountries : SmsSenderSettingsBase
{
public Dictionary<SmsProvider, string[]> Countries { get; set; } = new Dictionary<SmsProvider, string[]>();
public override string GetKey() => "SmsProviderCountries";
public static SmsProviderCountries CreateDefault() => new SmsProviderCountries();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ToolsImages.Structures
{
public class Structure
{
public int X { get; set; }
public int Y { get; set; }
public int Largeur { get; set; }
public int Hauteur { get; set; }
public int ligne { get; set; }
public int mot { get; set; }
public int caractere { get; set; }
public int Valeur { get; set; }
public int TDG { get; set; }
public Structure(int x, int y)
{
this.X = x;
this.Y = y;
}
public Structure(int x, int y, int largeur, int hauteur)
{
this.X = x;
this.Y = y;
this.Largeur = largeur;
this.Hauteur = hauteur;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Locky.Shared;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Locky.Droid
{
[Activity(Label = "PasswordsListActivity")]
public class PasswordsListActivity : Activity
{
Button addButton;
ListView passwordsListView;
List<Password> passwords;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Passwords);
passwordsListView = FindViewById<ListView>(Resource.Id.passwordListView);
passwordsListView.ItemClick += PasswordsListView_ItemClick;
addButton = FindViewById<Button>(Resource.Id.addButton);
addButton.Click += AddButton_Click;
PopulateListView();
}
void PasswordsListView_ItemClick (object sender, AdapterView.ItemClickEventArgs e)
{
if (e.Position != null)
{
var selectedItem = passwords[e.Position];
var intent = new Android.Content.Intent(this, typeof(DetailActivity));
Bundle bundle = new Bundle();
bundle.PutString("password_name", selectedItem.Name);
bundle.PutString("password_value", selectedItem.PasswordValue);
intent.PutExtras(bundle);
StartActivity(intent);
}
}
async void PopulateListView()
{
passwords = await Passwords.readPasswords();
List<string> passwordNames = new List<string>();
foreach (var password in passwords)
{
passwordNames.Add(password.Name);
}
passwordsListView.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, passwordNames);
}
void AddButton_Click (object sender, EventArgs e)
{
StartActivity(typeof(NewPasswordActivity));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AdvancedConcepts
{
// This program demo. how to use Action Delegate.
// Action delegate is an in-built generic type delegate.you need not to create custom delegate.
// it can contain minimum 1 param. and maximum 16 param.
// The Action delegate generally used for functions which do not return value.
class ActionDel
{
public static void Add(int firstNum, int secondNum)
{
Console.WriteLine($"The result is:{firstNum + secondNum}");
}
static void Main()
{
Action<int, int> action = Add;
action(30, 50);
Console.ReadLine();
}
}
}
|
using EDU_Rent.data_layer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EDU_Rent.business_layer
{
class Address
{
public string AddressL1 { get; set; }
public string AddressL2 { get; set; }
public string AddressCity { get; set; }
public string AddressState { get; set; }
public string AddressZip { get; set; }
public string UserName { get; set; }
public int AddressID { get; set; }
public Address(string AddressL1, string AddressL2, string AddressCity, string AddressState, string AddressZip, string UserName)
{
this.AddressL1 = AddressL1;
this.AddressL2 = AddressL2;
this.AddressCity = AddressCity;
this.AddressState = AddressState;
this.AddressZip = AddressZip;
this.UserName = UserName;
}
public Address()
{
this.AddressL1 = "";
this.AddressL2 = "";
this.AddressCity = "";
this.AddressState = "";
this.AddressZip = "";
}
public string AddAddress()
{
string fieldCheck = FieldCheck();
if (fieldCheck.Equals(""))
{
Addresses.AddAddress(this);
return "";
}
else
{
return fieldCheck;
}
}
public string FieldCheck()
{
if (AddressL1.Equals(""))
{
return " Try these: \n 1.) Address L1 blank?";
}
if (AddressCity.Equals(""))
{
return " Try these: \n 1.) City blank?";
}
if (AddressState.Equals(""))
{
return " Try these: \n 1.) State blank?";
}
if (AddressZip.Equals(""))
{
return " Try these: \n 1.) Zip blank?";
}
return "";
}
internal List<Address> GetAllAddressesByUsername(string UserName)
{
return Addresses.GetAllAddressesByUsername(UserName);
}
internal void DeleteAddressByID(int AddressID)
{
Addresses.DeleteAddressByID(AddressID);
}
}
}
|
using System.Threading.Tasks;
using dk.via.ftc.businesslayer.Models;
namespace dk.via.ftc.web.Data
{
public interface IDispensaryService
{
public Task<bool> CheckLicense(string license);
public Task AddDispensaryAsync(Dispensary dispensary);
public Task<string> GetDispensaryLicense(string license);
Task AddDispensaryAdminAsync(DispensaryAdmin aD);
}
} |
namespace ReturnOfThePioneers.Common.System {
public class AppConstants {
#region ----- Family -----
public const string INVENTORY = "Inventory";
public const string SERVER_TEST = "DreamLand";
#endregion
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace HeladacWeb.Migrations
{
public partial class credentialService : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "credentialService_DBid",
table: "HelmUsers",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.CreateTable(
name: "CredentialServices",
columns: table => new
{
id = table.Column<string>(type: "nvarchar(450)", nullable: false),
ServiceType_DB = table.Column<string>(type: "nvarchar(450)", nullable: true),
Url = table.Column<string>(type: "nvarchar(max)", nullable: true),
Domain_DB = table.Column<string>(type: "nvarchar(450)", nullable: true),
Url_DB = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_CredentialServices", x => x.id);
});
migrationBuilder.CreateIndex(
name: "IX_HelmUsers_credentialService_DBid",
table: "HelmUsers",
column: "credentialService_DBid");
migrationBuilder.CreateIndex(
name: "CredentialService_Domain",
table: "CredentialServices",
columns: new[] { "ServiceType_DB", "Domain_DB" },
unique: true,
filter: "[ServiceType_DB] IS NOT NULL AND [Domain_DB] IS NOT NULL");
migrationBuilder.AddForeignKey(
name: "FK_HelmUsers_CredentialServices_credentialService_DBid",
table: "HelmUsers",
column: "credentialService_DBid",
principalTable: "CredentialServices",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_HelmUsers_CredentialServices_credentialService_DBid",
table: "HelmUsers");
migrationBuilder.DropTable(
name: "CredentialServices");
migrationBuilder.DropIndex(
name: "IX_HelmUsers_credentialService_DBid",
table: "HelmUsers");
migrationBuilder.DropColumn(
name: "credentialService_DBid",
table: "HelmUsers");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2.admin
{
public partial class defaultyeni : System.Web.UI.Page
{
sql_baglanti baglan = new sql_baglanti();
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmdmakale = new SqlCommand("SELECT dbo.Makale.makaleTarih,dbo.Makale.makaleID, dbo.kategori.kategoriResim, dbo.Makale.makaleBaslik, dbo.Makale.makaleOzet FROM dbo.kategori INNER JOIN dbo.Makale ON dbo.kategori.kategoriID = dbo.Makale.kategoriID", baglan.baglan());
SqlDataReader drmakaleGetir = cmdmakale.ExecuteReader();
dl_makale.DataSource = drmakaleGetir;
dl_makale.DataBind();
}
}
}
|
// Copyright (c) 2007 - Dave Kerr
// http://www.dopecode.co.uk
//
//
// This file is part of SharpGL.
//
// SharpGL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// SharpGL 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
// If you are using this code for commerical purposes then you MUST
// purchase a license. See http://www.dopecode.co.uk for details.
// A few words are needed to correctly describe this class. In a particle system,
// a set of particles will be made. Each particle will be initialised with a call
// to Initialise(). Use this function to make each particle random. When the particle
// needs to move on a step, Tick() is called. Make sure the code is random, otherwise
// all particles will have the same behaviour.
using System;
using System.Collections;
using SharpGL.SceneGraph.Collections;
namespace SharpGL.SceneGraph.ParticleSystems
{
/// <summary>
/// This is the main particle class, if you want specialised particles derive from it.
/// </summary>
[Serializable()]
public abstract class Particle
{
/// <summary>
/// This function should initialise the particle so that it's ready to tick.
/// </summary>
/// <param name="rand">The random number generator.</param>
public abstract void Intialise(System.Random rand);
/// <summary>
/// This function moves the particle on a stage.
/// </summary>
/// <param name="rand">The random nunber generator.</param>
public abstract void Tick(System.Random rand);
/// <summary>
/// This function draws the particle.
/// </summary>
/// <param name="gl"></param>
public abstract void Draw(OpenGL gl);
}
public class BasicParticle : Particle
{
public BasicParticle()
{
}
/// <summary>
/// This function initialises the basic particle.
/// </summary>
/// <param name="rand"></param>
public override void Intialise(System.Random rand)
{
position.Set(0, 0, 0);
velocity.Set(0, 0, 0);
color.R = rand.Next(256) / 256.0f;
color.G = rand.Next(1) / 256.0f;
color.B = rand.Next(1) / 256.0f;
life = (rand.Next(100) / 1000.0f) + 0.03f;
direction.X += rand.Next(10) / 100.0f;
direction.Y += rand.Next(10) / 100.0f;
direction.Z += rand.Next(10) / 100.0f;
}
/// <summary>
/// This function 'ticks' the particle, i.e moves it on a stage.
/// </summary>
/// <param name="rand">A random object.</param>
public override void Tick(System.Random rand)
{
// Randomise the direction.
direction.X = directionRandomise.X - (2 * (float)rand.NextDouble() * directionRandomise.X);
direction.Y = directionRandomise.Y - (2 * (float)rand.NextDouble() * directionRandomise.Y);
direction.Z = directionRandomise.Z - (2 * (float)rand.NextDouble() * directionRandomise.Z);
// Now we randomise the color.
color.R += colorRandomise.R - (2 * (float)rand.NextDouble() * colorRandomise.R);
color.G += colorRandomise.G - (2 * (float)rand.NextDouble() * colorRandomise.G);
color.B += colorRandomise.B - (2 * (float)rand.NextDouble() * colorRandomise.B);
color.A += colorRandomise.A - (2 * (float)rand.NextDouble() * colorRandomise.A);
// First we update the velocity.
velocity += direction;
velocity += gravity;
// Now we move the particle.
position += velocity;
life -= lifespan;
}
public override void Draw(OpenGL gl)
{
gl.Color(color.R, color.G, color.B, life);
gl.Begin(OpenGL.TRIANGLE_STRIP);
gl.Vertex(position.X+0.1f, position.Y+0.1f, position.Z+0.1f);
gl.Vertex(position.X-0.1f, position.Y+0.1f, position.Z);
gl.Vertex(position.X+0.1f, position.Y-0.1f, position.Z);
gl.Vertex(position.X-0.1f, position.Y-0.1f, position.Z);
gl.End();
}
#region Member Data
/// <summary>
/// This is the vertex's current position in space.
/// </summary>
protected Vertex position = new Vertex(0, 0, 0);
/// <summary>
/// This is the velocity, do not modify!
/// </summary>
protected Vertex velocity = new Vertex(0, 0, 0);
/// <summary>
/// This is the direction of the particle.
/// </summary>
protected Vertex direction = new Vertex(0, 0, 0);
/// <summary>
/// This shows the potential magnitude of the random effects of the direction.
/// </summary>
protected Vertex directionRandomise = new Vertex(0.1f, 0.1f, 0.1f);
/// <summary>
/// This is the gravity affecting the particle.
/// </summary>
protected Vertex gravity = new Vertex(0, -0.1f, 0);
/// <summary>
/// Particles colour.
/// </summary>
protected GLColor color = new GLColor(1, 0, 0, 0);
/// <summary>
/// How much the particles colour can change by each tick.
/// </summary>
protected GLColor colorRandomise = new GLColor(0.1f, 0.1f, 0.1f, 0);
/// <summary>
/// The life left of the particle.
/// </summary>
protected float life = 1;
/// <summary>
/// The lifespan of the particle.
/// </summary>
protected float lifespan = 0.01f;
/// <summary>
/// Does the particle only exist once?
/// </summary>
protected bool dieForever = false;
#endregion
#region Properties
public Vertex Position
{
get {return position;}
set {position = value;}
}
public Vertex Velocity
{
get {return velocity;}
set {velocity = value;}
}
public Vertex Direction
{
get {return direction;}
set {direction = value;}
}
public Vertex DirectionRandomise
{
get {return directionRandomise;}
set {directionRandomise = value;}
}
public Vertex Gravity
{
get {return gravity;}
set {gravity = value;}
}
public GLColor Color
{
get {return color;}
set {color = value;}
}
public GLColor ColorRandomise
{
get {return colorRandomise;}
set {colorRandomise = value;}
}
public float Life
{
get {return life;}
set {life = value;}
}
public float LifeSpan
{
get {return lifespan;}
set {lifespan = value;}
}
public bool DieForever
{
get {return dieForever;}
set {dieForever = value;}
}
#endregion
}
public class SphereParticle : BasicParticle
{
public SphereParticle()
{
}
public override void Draw(OpenGL gl)
{
// Create the sphere if need be.
if(sphere == null)
sphere = new Quadrics.Sphere();
// Set the properties.
sphere.Translate = position;
sphere.Draw(gl);
}
protected static Quadrics.Sphere sphere = null;
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IntegrationTechnoLinkMap.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
namespace CGI.Reflex.Core.Mappings
{
public class IntegrationTechnoLinkMap : BaseEntityMap<IntegrationTechnoLink>
{
public IntegrationTechnoLinkMap()
{
References(x => x.Integration).Cascade.None();
References(x => x.Technology).Cascade.None();
}
}
}
|
using EFCoreDatabaseFirstSample.Models;
using EFCoreDatabaseFirstSample.Models.DTO;
using EFCoreDatabaseFirstSample.Models.Repository;
using Microsoft.AspNetCore.Mvc;
namespace EFCoreDatabaseFirstSample.Controllers
{
[Route("api/books")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly IDataRepository<Book, BookDto> _dataRepository;
public BooksController(IDataRepository<Book, BookDto> dataRepository)
{
_dataRepository = dataRepository;
}
// GET: api/Books/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var book = _dataRepository.Get(id);
if (book == null)
{
return NotFound("Book not found.");
}
return Ok(book);
}
}
} |
using System.ComponentModel.Composition;
using Microsoft.Practices.Prism.Regions;
namespace Torshify.Radio.EchoNest.Views.Browse.Tabs
{
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
[RegionMemberLifetime(KeepAlive = true)]
public partial class AlbumView
{
public AlbumView()
{
InitializeComponent();
}
[Import]
public AlbumViewModel Model
{
get
{
return DataContext as AlbumViewModel;
}
set
{
DataContext = value;
}
}
}
}
|
using System;
namespace ScreeningTesterWebSite.Models
{
public class AddressConfirmationOutput : InitializeQuestionnaireOutput
{
public AddressConfirmationOutput()
{
}
public AddressConfirmationOutput (InitializeQuestionnaireOutput baseObj, InputNewApplicant newApplicantIn)
{
TransferCommonProperties(newApplicantIn);
PassThroughBaseProps(baseObj);
PassThroughContactInfo(newApplicantIn);
}
public String ssn { get; set; }
public String fname { get; set; }
public String mi { get; set; }
public String lname { get; set; }
public String birthdate { get; set; }
public String hourlyrate { get; set; }
public String position { get; set; }
public String optout { get; set; }
public String primaryphone { get; set; }
public String email { get; set; }
protected void PassThroughBaseProps(InitializeQuestionnaireOutput baseObj)
{
this.optouttext = baseObj.optouttext;
this.address = baseObj?.address ?? "";
this.city = baseObj?.city ?? "";
this.state = baseObj?.state ?? "";
this.zip = baseObj?.zip ?? "";
this.ReturnedErrorText = baseObj.ReturnedErrorText;
}
protected void PassThroughContactInfo(InputNewApplicant newApplicantIn)
{
this.ssn = newApplicantIn.ssn;
this.fname = newApplicantIn.fname;
this.mi = newApplicantIn.mi;
this.lname = newApplicantIn.lname;
this.birthdate = newApplicantIn.birthdate;
this.hourlyrate = newApplicantIn.hourlyrate;
this.position = newApplicantIn.position;
this.optout = newApplicantIn.optout;
this.primaryphone = newApplicantIn.primaryphone;
this.email = newApplicantIn.email;
}
}
} |
using UnityEngine;
using System.Collections;
public class ThrowTrigger : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D collider){
gameObject.GetComponentInParent<BullyController>().OnTriggerStayChild2D(collider);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.