text
stringlengths
13
6.01M
using System.ComponentModel.DataAnnotations; using iCopy.Model.Attributes; namespace iCopy.Model.Request { public class ChangePassword { [Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoCurrentPassword")] [MaxLength(100, ErrorMessage = "ErrMaxLength")] public string CurrentPassword { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoNewPassword")] [MaxLength(100, ErrorMessage = "ErrMaxLength")] [MinLength(8, ErrorMessage = "ErrMinLenghtPassword")] [PasswordPolicy(ErrorMessage = "ErrPasswordPolicy")] public string NewPassword { get; set; } [Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoConfirmPassword")] [MaxLength(100, ErrorMessage = "ErrMaxLength")] [Compare(nameof(NewPassword), ErrorMessage = "ErrNotSamePasswordConfirm")] public string ConfirmNewPassword { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Infra; namespace Console2.G_Code { /* Find deepest nodes in a binary tree. Q: binary search tree? A: no Q: all of the deepest nodes, or just one? A: find the right-most deepest node */ /// <summary> /// the following method is basically a indorder traversal which keep track the maxDepth while /// pop up node. I used (s.Count+1 >= maxDepth) so I can keep the last deepest node. /// /// or I can use BFS and keep the last node in the queue. /// </summary> class G_054_DeppestNode { public TreeNode FindDeepestNode(TreeNode root) { int maxDepth = int.MinValue; TreeNode res = null; Stack<TreeNode> s = new Stack<TreeNode>(); s.Push(root); bool IsbackTrack = false; while (s.Count != 0) { TreeNode tmp = s.Peek(); if (!IsbackTrack && tmp.LeftChild != null) { s.Push(tmp.LeftChild); continue; } tmp = s.Pop(); IsbackTrack = true; if (s.Count + 1 >= maxDepth) { maxDepth = s.Count + 1; res = tmp; } if (tmp.RightChild != null) { s.Push(tmp.RightChild); IsbackTrack = false; } } return res; } } }
using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using RoleTopMVC.Enums; using RoleTopMVC.Models; using RoleTopMVC.Repositories; using RoleTopMVC.ViewModels; namespace RoleTopMVC.Controllers { public class ReservarController : AbstractController { AgendamentoRepository agendamentoRepository = new AgendamentoRepository(); PagamentoRepository pagamentoRepository = new PagamentoRepository(); ServicosRepository servicosRepository = new ServicosRepository(); ClienteRepository clienteRepository = new ClienteRepository(); public IActionResult Index() { AgendamentoViewModel avm = new AgendamentoViewModel(); avm.FormasDePagamento = pagamentoRepository.ObterTodos(); avm.Servicos = servicosRepository.ObterTodos(); var usuarioLogado = ObterUsuarioSession(); var nomeUsuarioLogado = ObterUsuarioNomeSession(); if(!string.IsNullOrEmpty(nomeUsuarioLogado)) { avm.NomeUsuario = nomeUsuarioLogado; var clienteLogado = clienteRepository.ObterPor(usuarioLogado); avm.Cliente = clienteLogado; }else{ return View(avm); } avm.NomeView = "Reservar"; avm.UsuarioEmail = usuarioLogado; avm.UsuarioNome = nomeUsuarioLogado; return View(avm); } public IActionResult Registrar(IFormCollection form) { Agendamento agendamento = new Agendamento(); Cliente cliente = new Cliente(); cliente.Nome = form["nome"]; cliente.Email = form["email"]; cliente.Cpf = form["cpfCnpj"]; agendamento.NomeEvento = form["nomeEvento"]; agendamento.Informacoes = form["informacoesdoevento"]; agendamento.ServicosAdicionais = form["ServicosAdicionais"]; agendamento.PubPriv = form["pubPriv"]; agendamento.formaPagamento = form["formaPagamento"]; agendamento.Cliente = cliente; agendamento.DataDoEvento = DateTime.Parse(form["calendario"]); double precoDefinitivo = servicosRepository.ObterPrecoTotal(agendamento.ServicosAdicionais); agendamento.PrecoTotal = precoDefinitivo; if(agendamentoRepository.Inserir(agendamento)) { return View("Sucesso", new RespostaViewModel() { NomeView = "Agendamento", UsuarioEmail = ObterUsuarioSession(), UsuarioNome = ObterUsuarioNomeSession() }); } else { return View("Erro", new RespostaViewModel()); } } public IActionResult PendenteAprovado(ulong id) { var agendamento = agendamentoRepository.ObterPor(id); agendamento.Status = (uint) StatusAgendamento.PENDENTE; if(agendamentoRepository.Atualizar(agendamento)) { return RedirectToAction("Aprovado", "Administrador"); } else { return View("Erro", new RespostaViewModel("Não foi possível devolver este evento") { NomeView = "Dashboard", UsuarioEmail = ObterUsuarioSession(), UsuarioNome = ObterUsuarioNomeSession() }); } } public IActionResult PendenteReprovado(ulong id) { var agendamento = agendamentoRepository.ObterPor(id); agendamento.Status = (uint) StatusAgendamento.PENDENTE; if(agendamentoRepository.Atualizar(agendamento)) { return RedirectToAction("Reprovado", "Administrador"); } else { return View("Erro", new RespostaViewModel("Não foi possível devolver este evento") { NomeView = "Dashboard", UsuarioEmail = ObterUsuarioSession(), UsuarioNome = ObterUsuarioNomeSession() }); } } public IActionResult Aprovar(ulong id) { var agendamento = agendamentoRepository.ObterPor(id); agendamento.Status = (uint) StatusAgendamento.APROVADO; if(agendamentoRepository.Atualizar(agendamento)) { return RedirectToAction("Dashboard", "Administrador"); } else { return View("Erro", new RespostaViewModel("Não foi possível aprovar este evento") { NomeView = "Dashboard", UsuarioEmail = ObterUsuarioSession(), UsuarioNome = ObterUsuarioNomeSession() }); } } public IActionResult Reprovar(ulong id) { var agendamento = agendamentoRepository.ObterPor(id); agendamento.Status = (uint) StatusAgendamento.REPROVADO; if(agendamentoRepository.Atualizar(agendamento)) { return RedirectToAction("Dashboard", "Administrador"); } else { return View("Erro", new RespostaViewModel("Não foi possível reprovar este evento") { NomeView = "Dashboard", UsuarioEmail = ObterUsuarioSession(), UsuarioNome = ObterUsuarioNomeSession() }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoursIngesup.Class2 { class Arguments_nommés_et_facultatifs { string s; public int Test (int a, string coucou = "coucou", int b = 1) { int c = a * b; Console.WriteLine(coucou); return 0; } public void Appel() { Console.WriteLine(Test(1)); Console.WriteLine(Test(1, "Hey")); Console.WriteLine(Test(1, "Hey", 2)); Console.WriteLine(Test(a : 1, b: 3)); Console.WriteLine(Test(b : 3, a: 1)); Console.WriteLine(Test(coucou : "Hey" ,b : 3, a: 1)); } } }
using apiInovaPP.Models.Repository.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Web; using apiInovaPP.Models.Entrega; using apiInovaPP.AcessoDados; using System.Text; using System.Data; namespace apiInovaPP.Models.Repository { public class EntregaRepository : IEntregaRepository { PostgreSql _PostgreSql; Parametros _Parametros; public EntregaRepository() { _PostgreSql = new PostgreSql(); _Parametros = new Parametros(); } public bool Add(Entrega.Entrega entrega) { try { StringBuilder sb = new StringBuilder(); _Parametros.Params.Clear(); _PostgreSql.Parametros.Clear(); sb.Append("INSERT INTO entrega(desc_entrega, nome_cliente, id_endereco, data_prevista, id_tipo_entrega, id_empresa, status, codigo_rastreio) "); sb.Append(" VALUES (@desc_entrega,@nome_cliente,@id_endereco,@data_prevista,@id_tipo_entrega,@id_empresa,@status,@codigo_rastreio) "); _Parametros.Add("@desc_entrega", entrega.Descricao); _Parametros.Add("@nome_cliente", entrega.Nome_Cliente); _Parametros.Add("@id_endereco", entrega.IdEndereco); _Parametros.Add("@data_prevista", entrega.DataPrevista); _Parametros.Add("@id_tipo_entrega", entrega.IdTipoEntrega); _Parametros.Add("@id_empresa", entrega.IdEmpresa); _Parametros.Add("@status", entrega.Status); _Parametros.Add("@codigo_rastreio", entrega.CodigoRastreio); _PostgreSql.Script = sb.ToString(); _PostgreSql.Parametros.AddRange(_Parametros.Params); if (!_PostgreSql.ExecuteNonQuery()) { throw new Exception("Erro: " + _PostgreSql.msg); } return true; } catch (Exception ex) { throw new Exception("Erro: " + ex.Message); } } public Entrega.Entrega Get(string codigoRastreio) { try { StringBuilder sb = new StringBuilder(); _Parametros.Params.Clear(); _PostgreSql.Parametros.Clear(); _Parametros.Add("@codigo_rastreio", codigoRastreio); _PostgreSql.Parametros.AddRange(_Parametros.Params); sb.Append("SELECT e.*, hist.id_historico, hist.data_hist, hist.msg_historico from entrega e "); sb.Append("left join historico_entrega hist on hist.id_entrega = e.id_entrega "); sb.Append(" where e.codigo_rastreio = @codigo_rastreio"); _PostgreSql.Script = sb.ToString(); return ExecutarConsulta(_PostgreSql).FirstOrDefault(); } catch (Exception ex) { throw new Exception(ex.Message); } } public Entrega.Entrega Get(int idEntrega) { try { StringBuilder sb = new StringBuilder(); _Parametros.Params.Clear(); _PostgreSql.Parametros.Clear(); _Parametros.Add("@id_entrega", idEntrega); _PostgreSql.Parametros.AddRange(_Parametros.Params); sb.Append("SELECT e.*, hist.id_historico, hist.data_hist, hist.msg_historico from entrega e "); sb.Append("left join historico_entrega hist on hist.id_entrega = e.id_entrega "); sb.Append(" where e.id_entrega = @id_entrega"); _PostgreSql.Script = sb.ToString(); return ExecutarConsulta(_PostgreSql).FirstOrDefault(); } catch (Exception ex) { throw new Exception(ex.Message); } } public bool Update(Entrega.Entrega entrega) { IHistoricoEntregaRepository _repoHistorico = new HistoricoEntregaRepository(); IEntregaDespesaRepository _repoDespesa = new EntregaDespesaRepository(); try { StringBuilder sb = new StringBuilder(); _Parametros.Params.Clear(); _PostgreSql.Parametros.Clear(); sb.Append("update entrega set logradouro = @logradouro where id_entrega = @id_entrega "); _Parametros.Add("@logradouro", entrega.Logradouro); _Parametros.Add("@id_entrega", entrega.Id_Entrega); _PostgreSql.Script = sb.ToString(); _PostgreSql.Parametros.AddRange(_Parametros.Params); if (!_PostgreSql.ExecuteNonQuery()) { throw new Exception("Erro: " + _PostgreSql.msg); } _repoHistorico.Add(entrega.Historico); _repoDespesa.Add(entrega.Despesas); return true; } catch (Exception ex) { throw new Exception("Erro: " + ex.Message); } } public bool ExtenderPrazoColeta(Entrega.Entrega entrega) { IHistoricoEntregaRepository _repoHistorico = new HistoricoEntregaRepository(); IEntregaDespesaRepository _repoDespesa = new EntregaDespesaRepository(); try { StringBuilder sb = new StringBuilder(); _Parametros.Params.Clear(); _PostgreSql.Parametros.Clear(); sb.Append("update entrega set data_prevista = @data_prevista where id_entrega = @id_entrega "); _Parametros.Add("@data_prevista", entrega.DataPrevista); _Parametros.Add("@id_entrega", entrega.Id_Entrega); _PostgreSql.Script = sb.ToString(); _PostgreSql.Parametros.AddRange(_Parametros.Params); if (!_PostgreSql.ExecuteNonQuery()) { throw new Exception("Erro: " + _PostgreSql.msg); } Historico hist = new Historico(); hist.Mensagem = string.Format("Alteração da data de entrega para {0}", entrega.DataPrevista); hist.IdEntrega = entrega.Id_Entrega; entrega.Historico.Add(hist); _repoHistorico.Add(entrega.Historico); //_repoDespesa.Add(entrega.Despesas); return true; } catch (Exception ex) { throw new Exception("Erro: " + ex.Message); } } public string GetCalcularTrocaEndereco(int idCidade, decimal distancia) { string retValor = string.Empty; if (idCidade > 0 && distancia > 0) { ICustoFreteRepository _repoCustoFrete = new CustoFreteRepository(); var custo = _repoCustoFrete.Get(idCidade); if (custo != null) { distancia = distancia < 1000 ? 1 : distancia / 1000; retValor = (distancia * custo.Custo ).ToString(); } } return retValor; } public bool PostTrocarEnderecoEntrega(Entrega.Entrega entrega, int idCidade, int distancia, string Logradouro) { string custo = GetCalcularTrocaEndereco(idCidade, distancia); Historico historico = new Historico() { Data_Historico = DateTime.Now, Mensagem = string.Format("Alteração de endereço de entrega. De {0} para {1}, Custo: {2}", entrega.Id_Entrega, entrega.Logradouro, Logradouro, custo) }; entrega.Historico.Add(historico); entrega.Logradouro = Logradouro; EntregaDespesa despesa = new EntregaDespesa(); despesa.Id_Despesa = 1; despesa.Valor = custo; entrega.Despesas.Add(despesa); return Update(entrega); } public IEnumerable<Entrega.Entrega> ExecutarConsulta(PostgreSql _PostgreSql) { DataTable dtbResultado; List<Entrega.Entrega> lstEntrega = new List<Entrega.Entrega>(); try { if (_PostgreSql.ExecuteQuery(out dtbResultado)) { if (dtbResultado != null) { if (dtbResultado.Rows.Count > 0) { Entrega.Entrega entrega = new Entrega.Entrega() { Id_Entrega = Convert.ToInt32(dtbResultado.Rows[0]["id_entrega"].ToString()), //IdEndereco = Convert.ToInt32(dtbResultado.Rows[0]["id_endereco"].ToString()), Nome_Cliente = dtbResultado.Rows[0]["nome_cliente"].ToString(), DataPrevista = Convert.ToDateTime(dtbResultado.Rows[0]["data_prevista"].ToString()), //IdTipoEntrega = Convert.ToInt32(dtbResultado.Rows[0]["id_tipo_entrega"].ToString()), //IdEmpresa = Convert.ToInt32(dtbResultado.Rows[0]["id_empresa"].ToString()), CodigoRastreio = dtbResultado.Rows[0]["codigo_rastreio"].ToString(), Logradouro = dtbResultado.Rows[0]["Logradouro"].ToString(), //Status = dtbResultado.Rows[0]["status"].ToString() }; List<Entrega.Historico> lstHistorico = new List<Historico>(); for (int i = 0; i < dtbResultado.Rows.Count; i++) { if (!string.IsNullOrEmpty(dtbResultado.Rows[i]["id_historico"].ToString())) { lstHistorico.Add(new Entrega.Historico() { Id_Historico = Convert.ToInt32(dtbResultado.Rows[0]["id_historico"].ToString()), IdEntrega = Convert.ToInt32(dtbResultado.Rows[0]["id_entrega"].ToString()), Mensagem = dtbResultado.Rows[0]["nome_cliente"].ToString(), Data_Historico = Convert.ToDateTime(dtbResultado.Rows[0]["data_prevista"].ToString()) }); } } entrega.Historico = lstHistorico; lstEntrega.Add(entrega); } } } return lstEntrega.ToArray(); } catch (Exception ex) { throw new Exception(ex.Message); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MacroWeb.Models; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Session; namespace MacroWeb.Controllers { public class CommentController : Controller { private MyContext _context; public CommentController(MyContext context) { _context = context; } [HttpGet("newcommentpartial/{MessageId}")] public PartialViewResult NewComment(int MessageId) { int userid = (int)HttpContext.Session.GetInt32("UserId"); ViewBag.curuser = _context.Users .Include(u=>u.UsersFollowed) .ThenInclude(c=>c.UserFollowed) .FirstOrDefault(u=>u.UserId == userid); ViewBag.allusers = _context.Users.ToList(); ViewBag.curmessage = _context.Messages .FirstOrDefault(m=>m.MessageId==MessageId); return PartialView("_PostComment"); } [ValidateAntiForgeryToken] [HttpPost("processnewcomment")] public IActionResult ProcessNewComment(Comment NewComment) { int userid = (int)HttpContext.Session.GetInt32("UserId"); ViewBag.curuser = _context.Users .Include(u=>u.UsersFollowed) .ThenInclude(c=>c.UserFollowed) .FirstOrDefault(u=>u.UserId == userid); ViewBag.curmessage = _context.Messages .FirstOrDefault(m=>m.MessageId==NewComment.MessageId); if(ModelState.IsValid) { _context.Comments.Add(NewComment); _context.SaveChanges(); var html = Helper.RenderRazorViewToString(this, "_ShowMessage", _context.Messages .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.Creator) .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.UserLikedThisComment) .ThenInclude(lc=>lc.UserWhoLiked) .Include(m=>m.Creator) .Include(m=>m.UsersLikedThisMessage) .ThenInclude(lm=>lm.UserWhoLiked) .Include(m=>m.Spirals) .Include(m=>m.Center) .OrderByDescending(m=>m.UpdatedAt) .ToList()); var returnedJson = new { successful = true, renderPage = html }; return Json(returnedJson); }else{ var html = Helper.RenderRazorViewToString(this, "_PostComment", NewComment); var returnedJson = new { successful = false, renderPage = html }; return Json(returnedJson); } } // like comment [HttpGet("likecomment/{id}")] public JsonResult LikeComment(int id) { int userid = (int)HttpContext.Session.GetInt32("UserId"); ViewBag.curuser = _context.Users .Include(u=>u.UsersFollowed) .ThenInclude(c=>c.UserFollowed) .FirstOrDefault(u=>u.UserId == userid); LikedComment NewLike = new LikedComment(); NewLike.UserId = userid; NewLike.CommentId = id; _context.LikedComments.Add(NewLike); _context.SaveChanges(); var html = Helper.RenderRazorViewToString(this,"_ShowMessage", _context.Messages .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.Creator) .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.UserLikedThisComment) .ThenInclude(lc=>lc.UserWhoLiked) .Include(m=>m.Creator) .Include(m=>m.UsersLikedThisMessage) .ThenInclude(lm=>lm.UserWhoLiked) .Include(m=>m.Spirals) .Include(m=>m.Center) .OrderByDescending(m=>m.UpdatedAt) .ToList()); return Json(new{renderPage = html}); } // unlike [HttpGet("unlikecomment/{id}")] public JsonResult UnLikeComment(int id) { int userid = (int)HttpContext.Session.GetInt32("UserId"); ViewBag.curuser = _context.Users .Include(u=>u.UsersFollowed) .ThenInclude(c=>c.UserFollowed) .FirstOrDefault(u=>u.UserId == userid); LikedComment ToDelete = _context.LikedComments .FirstOrDefault(l=>l.UserId==userid && l.CommentId==id); _context.LikedComments.Remove(ToDelete); _context.SaveChanges(); var html = Helper.RenderRazorViewToString(this,"_ShowMessage", _context.Messages .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.Creator) .Include(m=>m.CommentsForMessage) .ThenInclude(c=>c.UserLikedThisComment) .ThenInclude(lc=>lc.UserWhoLiked) .Include(m=>m.Creator) .Include(m=>m.UsersLikedThisMessage) .ThenInclude(lm=>lm.UserWhoLiked) .Include(m=>m.Spirals) .Include(m=>m.Center) .OrderByDescending(m=>m.UpdatedAt) .ToList()); return Json(new{renderPage = html}); } [HttpGet("userslikedcomment/{id}")] public PartialViewResult UsersLikedComment(int id) { int userid = (int)HttpContext.Session.GetInt32("UserId"); ViewBag.curuser = _context.Users .Include(u=>u.UsersFollowed) .ThenInclude(c=>c.UserFollowed) .FirstOrDefault(u=>u.UserId == userid); ViewBag.ThisComment = _context.Comments .Include(c=>c.UserLikedThisComment) .ThenInclude(lc=>lc.UserWhoLiked) .FirstOrDefault(c=>c.CommentId==id); return PartialView("_LikedCommentUsers"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System; using System.Runtime.Serialization; namespace MKService.Messages { public class MageKnightCoordinatesChanged :MessageBase { [DataMember] public Guid UserId { get; set; } [DataMember] public Guid InstantiatedMageId { get; set; } [DataMember] public double XCoordinate { get; set;} [DataMember] public double YCoordinate { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; using System.Data; using System.Drawing; using System.Drawing.Printing; using ThoughtWorks.QRCode.Codec; namespace SKT.WMS.Printer.BLL { using System = global::System; public class ZPLPrinter { public string Name; #region DLL声明 //ZPL [DllImport(@"FNTHEX32.DLL", CharSet = CharSet.Ansi)] public static extern int GETFONTHEX( string chnstr, string fontname, string chnname, int orient, int height, int width, int bold, int italic, StringBuilder param1); //EPL [DllImport(@"Eltronp.dll", CharSet = CharSet.Ansi)] public static extern int PrintHZ(int Lpt, //0:LPT1,1 LPT2 int x, int y, string HZBuf, string FontName, int FontSize, int FontStyle); #endregion #region 指令说明 /** ^XA 开始 ^XZ 结束 ^LH起始坐标 ^PR进纸回纸速度 ^MD 对比度 ^FO标签左上角坐标 ^XG打印图片参数1图片名称后两个为坐标 ^FS标签结束符 ^CI切换国际字体 ^FT坐标 ^FD定义一个字符串 ^A定义字体 ^FH十六进制数 ^BY模块化label ^BC条形码128 ^PQ打印设置 参数一 打印数量 参数二暂停 参数三重复数量 参数四为Y时表明无暂停 **/ #endregion #region PrintDocument 打印条码、二维码 public void Print() { System.Drawing.Printing.PrintDocument _Document = new System.Drawing.Printing.PrintDocument(); _Document.PrintPage += _Document_PrintPage; PageSettings pageSet = new PageSettings(); pageSet.Landscape = false; pageSet.Margins.Top = 0; pageSet.Margins.Left = 1; pageSet.PaperSize = new System.Drawing.Printing.PaperSize("小票", 2, 2); _Document.DefaultPageSettings = pageSet; _Document.Print(); } void _Document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { float x = 0; float y = 0; float width = 300; float height = 60; e.Graphics.DrawImage(CreateBarcodeImage("--test--", ""), x, y, width, height); e.HasMorePages = false; } #endregion #region ZPL 打印条码、二维码 /// <summary> /// 条码打印(标签两列) /// </summary> /// <param name="l">左边距 推荐值:0</param> /// <param name="h">上边距 推荐值:0</param> /// <param name="cl">第一列与第二列的距离 推荐值:0</param> /// <param name="bch">条码高 推荐值:0</param> /// <param name="str">条码内容1,内容2两个字符串 推荐值:11位字母数字组成</param> /// <returns>true /false 执行状态</returns> public string PrintBarcode(int l, int h, int cl, int bch, params string[] str) { l = l == 0 ? 0 : l; h = h == 0 ? 8 : h; cl = cl == 0 ? 30 : cl; bch = bch == 0 ? 100 : bch; StringBuilder sb = new StringBuilder(); sb.Append("^XA"); //连续打印两列(单列只写一条) sb.Append(string.Format("^MD30^LH{0},{1}^FO{2},{3}^ACN,18,10^BY1.8,3,{4}^BC,,Y,N^FD{5}^FS", l, h, l, h, bch, str[0])); sb.Append(string.Format("^MD30^LH{0},{1}^FO{2},{3}^ACN,18,10^BY1.8,3,{4}^BC,,Y,N^FD{5}^FS", l, h, l + cl, h, bch, str[1])); sb.Append("^XZ"); return sb.ToString(); } /// <summary> /// 二维码打印(标签两列) /// </summary> /// <param name="l">左边距 推荐值:0</param> /// <param name="h">上边距 推荐值:0</param> /// <param name="cl">第一列与第二列的距离 推荐值:0</param> /// <param name="bch">二维码放大倍数 推荐值:0</param> /// <param name="str">内容1,内容2两个字符串 推荐值:字母数字组成(位数不限制)</param> /// <returns>true /false 执行状态</returns> public string PrintQRCode(int l, int h, int cl, int bch, params string[] str) { if (str.Length < 2) return ""; string[] str0 = str[0].Split(','); string[] str1 = str[1].Split(','); l = l == 0 ? 5 : l; h = h == 0 ? 8 : h; cl = cl == 0 ? 360 : cl; bch = bch == 0 ? 5 : bch; StringBuilder sb = new StringBuilder(); sb.Append("^XA"); sb.Append(string.Format("^LH{0},{1}^FO{2},{3}^BQ,2,{4}^FDQA,{5}^FS", l, h, 0, h, bch, str0[0])); sb.Append(TextToHex(str0[1], str0[0], 24)); sb.Append(string.Format("^FT{0},{1}^XG{2},1,1^FS", 125 + l, h + 60, str0[0])); sb.Append(TextToHex(str0[0], str0[0], 20)); sb.Append(string.Format("^FT{0},{1}^XG{2},1,1^FS", 125 + l, h + 90, str0[0])); sb.Append(string.Format("^LH{0},{1}^FO{2},{3}^BQ,2,{4}^FDQA,{5}^FS", l, h, 0 + cl, h, bch, str1[0])); sb.Append(TextToHex(str1[1], str1[0], 24)); sb.Append(string.Format("^FT{0},{1}^XG{2},1,1^FS", 125 + cl + l, h + 60, str1[0])); sb.Append(TextToHex(str1[0], str1[0], 20)); sb.Append(string.Format("^FT{0},{1}^XG{2},1,1^FS", 125 + cl + l, h + 90, str1[0])); sb.Append("^XZ"); return sb.ToString(); } #endregion #region 条码、二维码图片生成 /// <summary> /// 生成条形码图片 /// </summary> /// <param name="num">条形码序列号</param> /// <param name="path">图片存放路径(绝对路径)</param> /// <returns>返回图片</returns> public System.Drawing.Image CreateBarcodeImage(string num, string path) { BarcodeLib.Barcode b = new BarcodeLib.Barcode(); b.BackColor = System.Drawing.Color.White; b.ForeColor = System.Drawing.Color.Black; b.IncludeLabel = true; b.Alignment = BarcodeLib.AlignmentPositions.CENTER; b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER; b.ImageFormat = System.Drawing.Imaging.ImageFormat.Png; System.Drawing.Font font = new System.Drawing.Font("verdana", 10f); b.LabelFont = font; try { System.Drawing.Image image = b.Encode(BarcodeLib.TYPE.CODE128B, num); image.Save(path); return image; } catch (Exception) { } return null; } /// <summary> /// 生成二维码图片 /// </summary> /// <param name="num">二维码序列号</param> /// <param name="path">图片存放路径(绝对路径)</param> /// <returns>返回图片</returns> public System.Drawing.Image CreateQRCodeImage(string num, string path) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(); String encoding = "Byte"; if (encoding == "Byte") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE; } else if (encoding == "AlphaNumeric") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC; } else if (encoding == "Numeric") { qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC; } try { int scale = Convert.ToInt16(4); qrCodeEncoder.QRCodeScale = scale; } catch (Exception) { } try { int version = Convert.ToInt16(7); qrCodeEncoder.QRCodeVersion = version; } catch (Exception) { } string errorCorrect = "M"; if (errorCorrect == "L") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L; else if (errorCorrect == "M") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M; else if (errorCorrect == "Q") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q; else if (errorCorrect == "H") qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; try { Bitmap bm = qrCodeEncoder.Encode(num); bm.Save(path); MemoryStream ms = new MemoryStream(); bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return System.Drawing.Image.FromStream(ms); } catch (Exception) { } return null; } #endregion #region ZPL 打印中文小票 public string TextToHex(string text, string textId, int height) { StringBuilder hexBuilder = new StringBuilder(4 * 1024); int subStrCount = 0; subStrCount = GETFONTHEX(text, "宋体", textId, 0, height, 0, 1, 0, hexBuilder); return hexBuilder.ToString().Substring(0, subStrCount); } public string DeviceLabelToHex(string text, string textId) { StringBuilder hexBuilder = new StringBuilder(4 * 1024); int subStrCount = 0; subStrCount = 1; // GETFONTHEX(text, "Arial", textId, 0, 40, 0, 1, 0, hexBuilder); return hexBuilder.ToString().Substring(0, subStrCount); } public bool IsZebraPrinter(string printerName) { return printerName.IndexOf("ZDesigner") + printerName.IndexOf("Zebra") >= -1; } public string ZPLPrintGRNLabel(DataTable dt, bool isRequireTextToHex, string left) { string strReturn=""; SKT.WMS.Print.Model.Label label = null; foreach (DataRow row in dt.Rows) { List<SKT.WMS.Print.Model.Label> labelList = new List<SKT.WMS.Print.Model.Label>(); label = new SKT.WMS.Print.Model.Label(); #region Data label.Id = "vendor"; label.Text = row["vendor"].ToString(); label.chnFont = 1; //label.XPos = 150; //label.YPos = 60; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "grn"; label.Text = row["grn"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "ItemName"; label.Text = row["ItemName"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "Code"; label.Text = row["Code"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "Desc"; label.Text = row["Desc"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "Qty"; label.Text = row["Qty"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "Date"; label.Text = row["Date"].ToString(); label.chnFont = 1; labelList.Add(label); label = new SKT.WMS.Print.Model.Label(); label.Id = "2DBar"; label.Text = row["2DBar"].ToString(); label.chnFont = 0; #endregion labelList.Add(label); if (isRequireTextToHex) { strReturn = ZPLPrintGRNLabels(labelList.ToArray(), 50, left); } else { strReturn = ZPLPrintGRNLabelsWithHexText(labelList.ToArray()); } } return strReturn; } private string ZPLPrintGRNLabelsWithHexText(SKT.WMS.Print.Model.Label[] labels) { string labelIdCmd = string.Empty; string labelContentCmd = string.Empty; foreach (SKT.WMS.Print.Model.Label label in labels) { labelIdCmd += "^FT" + label.XPos.ToString() + "," + label.YPos.ToString() + "^XG" + label.Id + ",1,1^FS"; labelContentCmd += label.Text; } string content = labelContentCmd + "^XA^LH0,0^PR2,2^MD20^FO0,0" + labelIdCmd + "^PQ1,0,1,Y^XZ"; return content; } private string ZPLPrintGRNLabels(SKT.WMS.Print.Model.Label[] labels, int height,string left) { string labelContentCmd = string.Empty; foreach (SKT.WMS.Print.Model.Label label in labels) { if (label.chnFont == 1) { labelContentCmd += TextToHex(label.Text, label.Id, height); } } #region 打印GRN条码 string content = "CT~~CD,~CC^~CT~^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH00,0^JMA^PR6,6~SD15^JUS^LRN^CI0^XZ" + labelContentCmd + "^XA^MMT^PW496^LL0614^LS0" + @" ^FT30,96^XGvendor,1,1^FS ^FT30,490^XGQty,1,1^FS ^FT30,576^XGDate,1,1^FS ^FT30,192^XGgrn,1,1^FS ^FT30,404^XGDesc,1,1^FS ^FT30,275^XGItemName,1,1^FS ^FT30,320^XGCode,1,1^FS ^BY80,80^FT182,214^BXN,5,200,20,20,1 ^FH\^FD2DBar^FS ^PQ1,0,1,Y^XZ"; //替换非文字变量 foreach (SKT.WMS.Print.Model.Label label in labels) { if (label.chnFont == 0) { content = content.Replace(label.Id,label.Text); } } //整体左移,右移 if (left.Trim().Length>0) { content = content.Replace("LH00", "LH"+left.Trim()); } return content; #endregion } #endregion } }
using Android.App; using Android.Widget; using Android.OS; namespace S04_MoreBasicsUI_5_Task_OfficialSolution { [Activity(Label = "S04_MoreBasicsUI_5_Task_OfficialSolution", MainLauncher = true)] public class MainActivity : Activity { Spinner spinner; RadioGroup radioGroup; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); var toggleButton = FindViewById<ToggleButton>(Resource.Id.toggleButton1); var linearLayout = FindViewById<LinearLayout>(Resource.Id.linearLayout1); radioGroup = FindViewById<RadioGroup>(Resource.Id.radioGroup1); spinner = FindViewById<Spinner>(Resource.Id.spinner1); toggleButton.CheckedChange += delegate { if (toggleButton.Checked) { linearLayout.Visibility = Android.Views.ViewStates.Visible; } else { linearLayout.Visibility = Android.Views.ViewStates.Gone; } }; ChangeList(); radioGroup.CheckedChange += delegate { ChangeList(); }; } protected void ChangeList() { var checkedId = radioGroup.CheckedRadioButtonId; ArrayAdapter adapter; if (checkedId == Resource.Id.radioButtonItalian) { adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.italian, Android.Resource.Layout.SimpleSpinnerItem); } else { adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.french, Android.Resource.Layout.SimpleSpinnerItem); } adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = adapter; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Preferences : MonoBehaviour { public static Preferences instance; public string PlayerName = ""; public string[] RandomNames = {"Comi", "Zika", "Shomy", "Eric M. Lang", "Batman", "Daum"}; void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } DontDestroyOnLoad(gameObject); } public InputField PlayerNameInputField; // Use this for initialization void Start () { if(PlayerPrefs.HasKey("PlayerName") == true) { PlayerName = PlayerPrefs.GetString("PlayerName"); } else { PlayerName = RandomNames[Random.Range(0,RandomNames.Length)]; PlayerPrefs.SetString("PlayerName", PlayerName); } //PlayerNameText.text = PlayerName; PlayerNameInputField.text = PlayerName; } public void ChangePlayerName(string playerName) { PlayerPrefs.SetString("PlayerName", playerName); PlayerName = PlayerPrefs.GetString("PlayerName"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Obout.Interface; public partial class Pages_screentest2 : System.Web.UI.Page { protected void Page_PreRender(object sender, EventArgs e) { if (Session["wx"] == null) { Session["wx"] = Request.QueryString["wx"]; } if (Session["wy"] == null) { Session["wy"] = Request.QueryString["wy"]; } Page.Header.Title = String.Format("Screen Test 1.0 ({0}x{1})", Session["wx"], Session["wy"]); txt1.Text = "window.innerWidth"; txt2.Text = "window.innerHeight"; txt3.Text = "window.outerHeight"; txt4.Text = "window.outerWidth"; txt5.Text = "window.pageXOffset"; txt6.Text = "window.pageYOffset"; txt7.Text = "window.screen.availHeight"; txt8.Text = "window.screen.availWidth"; txt9.Text = "window.screen.height"; txt10.Text = "window.screen.width"; txt11.Text = "navigator.userAgent"; txt12.Text = "navigator.appVersion"; value1.Text = Session["wx"].ToString(); value2.Text = Session["wy"].ToString(); value3.Text = Request.QueryString["oh"].ToString(); value4.Text = Request.QueryString["ow"].ToString(); value5.Text = Request.QueryString["ox"].ToString(); value6.Text = Request.QueryString["oy"].ToString(); value7.Text = Request.QueryString["sx"].ToString(); value8.Text = Request.QueryString["sy"].ToString(); value9.Text = Request.QueryString["hx"].ToString(); value10.Text = Request.QueryString["hy"].ToString(); value11.Text = Request.QueryString["ua"].ToString(); value12.Text = Request.QueryString["av"].ToString(); } protected void Page_Load(object sender, EventArgs e) { } }
using Newtonsoft.Json; using System.Collections.Generic; using System.IO; namespace DT071G_project { class DataSerializer { string favoritesFilePath = @"favorits.json"; //serilize favorite music public void JsonSerializeFavorits(List<FavoriteMusic> favoriteMusicList) { //check if json file eist and create if it dosen´t exist if (!File.Exists(favoritesFilePath)) { FileStream fs = File.Create(favoritesFilePath); } //serialise data string jsonData = JsonConvert.SerializeObject(favoriteMusicList); System.IO.File.WriteAllText(favoritesFilePath, jsonData); } //deserilize favorite music public List<FavoriteMusic> JsonDeserializeFavorits() { //check if json file eist and create if it dosen´t exist if (!File.Exists(favoritesFilePath)) { return new List<FavoriteMusic>(); } else { //read json file var jsonData = System.IO.File.ReadAllText(favoritesFilePath); // Deserialise json file to C# object and create list var favoriteMusicList = JsonConvert.DeserializeObject<List<FavoriteMusic>>(jsonData) ?? new List<FavoriteMusic>(); //return list return favoriteMusicList; } } } }
public static class Leap { public static bool IsLeapYear(int year) { if ((IsDivisbleByFour(year) && !IsDivisbleByOneHundred(year)) || IsDivisbleByFourHundred(year)) { return true; } return false; } private static bool IsDivisbleByFour(int year) { return year % 4 == 0; } private static bool IsDivisbleByOneHundred(int year) { return year % 100 == 0; } private static bool IsDivisbleByFourHundred(int year) { return year % 400 == 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Okra.Core { public class DelegateCommand : DelegateCommand<object> { // *** Constructors *** public DelegateCommand(Action execute, Func<bool> canExecute) : base(null, null) { throw new NotImplementedException(); } public DelegateCommand(Action execute) : this(null, null) { } } }
using System; using System.Collections.Generic; #nullable disable namespace Quinelita.Entities.DTOs { public partial class TblTournament { public TblTournament() { TblGroupBets = new HashSet<TblGroupBet>(); TblMatches = new HashSet<TblMatch>(); } public int Id { get; set; } public string Name { get; set; } public virtual ICollection<TblGroupBet> TblGroupBets { get; set; } public virtual ICollection<TblMatch> TblMatches { get; set; } } }
using System; using Xunit; using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using System.Linq; namespace WebApiTestsCore { [CollectionDefinition("WebApiInit")] public class IisCollection : ICollectionFixture<Fonlow.Testing.IisExpressFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } [Collection("WebApiInit")] public class ValuesApiIntegration : IClassFixture<ValuesFixture> { public ValuesApiIntegration(ValuesFixture fixture) { api = fixture.Api; } Values api; [Fact] public void TestValuesGet() { //var task = authorizedClient.GetStringAsync(new Uri(baseUri, "api/Values")); //var text = task.Result; //var array = JArray.Parse(text); var array = api.Get().ToArray(); Assert.Equal("value2", array[1]); } [Fact] public void TestValuesDelete() { api.Delete(1); } } ///// <summary> ///// Test with Proxy http://localhost:8888 ///// </summary> //public class ValuesApiWithProxyIntegration : IClassFixture<ValuesWithProxyFixture> //{ // public ValuesApiWithProxyIntegration(ValuesWithProxyFixture fixture) // { // api = fixture.Api; // } // Values api; // [Fact] // public void TestValuesGet() // { // //var task = authorizedClient.GetStringAsync(new Uri(baseUri, "api/Values")); // //var text = task.Result; // //var array = JArray.Parse(text); // var array = api.Get().ToArray(); // Assert.Equal("value2", array[1]); // } // [Fact] // public void TestValuesDelete() // { // api.Delete(1); // } //} public class ValuesFixture : Fonlow.Testing.DefaultHttpClient { public ValuesFixture() { Api = new Values(base.HttpClient, base.BaseUri); } public Values Api { get; private set; } } public class ValuesWithProxyFixture : Fonlow.Testing.DefaultHttpClient { public ValuesWithProxyFixture(): base(handler) { Api = new Values(base.HttpClient, base.BaseUri); } static readonly HttpMessageHandler handler = new HttpClientHandler() { Proxy = new System.Net.WebProxy() { Address = new Uri("http://localhost:8888"), // Talk to proxy of Fiddler. Whether Fiddler is capturing traffic does not matter. BypassProxyOnLocal = false, //UseDefaultCredentials = proxyCredentials == null ? true : false, //Credentials = proxyCredentials, }, UseProxy = true, }; public Values Api { get; private set; } } public partial class Values { private System.Net.Http.HttpClient client; private System.Uri baseUri; public Values(System.Net.Http.HttpClient client, System.Uri baseUri) { if (client == null) throw new ArgumentNullException("client", "Null HttpClient."); if (baseUri == null) throw new ArgumentNullException("baseUri", "Null baseUri"); this.client = client; this.baseUri = baseUri; } /// <summary> /// DELETE api/Values/{id} /// </summary> public async Task DeleteAsync(int id) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); var responseMessage = await client.DeleteAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); } /// <summary> /// DELETE api/Values/{id} /// </summary> public void Delete(int id) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); var responseMessage = this.client.DeleteAsync(requestUri).Result; responseMessage.EnsureSuccessStatusCode(); } /// <summary> /// GET api/Values /// </summary> public async Task<string[]> GetAsync() { var requestUri = new Uri(this.baseUri, "api/Values"); var responseMessage = await client.GetAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { var serializer = new JsonSerializer(); return serializer.Deserialize<string[]>(jsonReader); } } /// <summary> /// GET api/Values /// </summary> public string[] Get() { var requestUri = new Uri(this.baseUri, "api/Values"); var responseMessage = this.client.GetAsync(requestUri).Result; responseMessage.EnsureSuccessStatusCode(); var stream = responseMessage.Content.ReadAsStreamAsync().Result; using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { var serializer = new JsonSerializer(); return serializer.Deserialize<string[]>(jsonReader); } } /// <summary> /// GET api/Values/{id}?name={name} /// </summary> public async Task<string> GetAsync(int id, string name) { var requestUri = new Uri(this.baseUri, "api/Values/" + id + "?name=" + Uri.EscapeDataString(name)); var responseMessage = await client.GetAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// GET api/Values/{id}?name={name} /// </summary> public string Get(int id, string name) { var requestUri = new Uri(this.baseUri, "api/Values/" + id + "?name=" + Uri.EscapeDataString(name)); var responseMessage = this.client.GetAsync(requestUri).Result; responseMessage.EnsureSuccessStatusCode(); var stream = responseMessage.Content.ReadAsStreamAsync().Result; using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// GET api/Values?name={name} /// </summary> public async Task<string> GetAsync(string name) { var requestUri = new Uri(this.baseUri, "api/Values?name=" + Uri.EscapeDataString(name)); var responseMessage = await client.GetAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// GET api/Values?name={name} /// </summary> public string Get(string name) { var requestUri = new Uri(this.baseUri, "api/Values?name=" + Uri.EscapeDataString(name)); var responseMessage = this.client.GetAsync(requestUri).Result; responseMessage.EnsureSuccessStatusCode(); var stream = responseMessage.Content.ReadAsStreamAsync().Result; using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// GET api/Values/{id} /// </summary> public async Task<string> GetAsync(int id) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); var responseMessage = await client.GetAsync(requestUri); responseMessage.EnsureSuccessStatusCode(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// GET api/Values/{id} /// </summary> public string Get(int id) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); var responseMessage = this.client.GetAsync(requestUri).Result; responseMessage.EnsureSuccessStatusCode(); var stream = responseMessage.Content.ReadAsStreamAsync().Result; using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } /// <summary> /// POST api/Values /// </summary> public async Task<string> PostAsync(string value) { var requestUri = new Uri(this.baseUri, "api/Values"); using (var requestWriter = new System.IO.StringWriter()) { var requestSerializer = JsonSerializer.Create(); requestSerializer.Serialize(requestWriter, value); var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); var responseMessage = await client.PostAsync(requestUri, content); responseMessage.EnsureSuccessStatusCode(); var stream = await responseMessage.Content.ReadAsStreamAsync(); using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } } /// <summary> /// POST api/Values /// </summary> public string Post(string value) { var requestUri = new Uri(this.baseUri, "api/Values"); using (var requestWriter = new System.IO.StringWriter()) { var requestSerializer = JsonSerializer.Create(); requestSerializer.Serialize(requestWriter, value); var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); var responseMessage = this.client.PostAsync(requestUri, content).Result; responseMessage.EnsureSuccessStatusCode(); var stream = responseMessage.Content.ReadAsStreamAsync().Result; using (JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream))) { return jsonReader.ReadAsString(); } } } /// <summary> /// PUT api/Values/{id} /// </summary> public async Task PutAsync(int id, string value) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); using (var requestWriter = new System.IO.StringWriter()) { var requestSerializer = JsonSerializer.Create(); requestSerializer.Serialize(requestWriter, value); var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); var responseMessage = await client.PutAsync(requestUri, content); responseMessage.EnsureSuccessStatusCode(); } } /// <summary> /// PUT api/Values/{id} /// </summary> public void Put(int id, string value) { var requestUri = new Uri(this.baseUri, "api/Values/" + id); using (var requestWriter = new System.IO.StringWriter()) { var requestSerializer = JsonSerializer.Create(); requestSerializer.Serialize(requestWriter, value); var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); var responseMessage = this.client.PutAsync(requestUri, content).Result; responseMessage.EnsureSuccessStatusCode(); } } } }
using System; using System.Collections.Generic; namespace TemplateMethodExample { internal abstract class UiElement { public ICollection<UiElement> Children { get; } = new List<UiElement>(); // Template Method public void Zeichnen() { // 1. ZeichneRahmen(); // 2. ZeichneInhalt(); // 3. ZeichneUnterelemente(); } // Möglichkeit 1: kann bei Bedarf überschrieben werden. protected virtual void ZeichneRahmen() => Console.WriteLine("Zeichne default Rahmen."); // Möglichkeit 2: muss immer überschrieben werden. protected abstract void ZeichneInhalt(); // Möglichkeit 3: kann nicht überschrieben werden. private void ZeichneUnterelemente() { foreach (var c in Children) c.Zeichnen(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Xml; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Xml.Serialization; using ObjectDataTypes; using GameUtilities; namespace PirateWars { /// <summary> /// This is the main type for your game /// </summary> #region Game1 public class Game1 : Microsoft.Xna.Framework.Game { #region Private Variables #region Player Values /// <value>initial spawning location for the player</value> Vector2 playerStartingPos; /// <value>the Ship that the player controls. It is made static so that the Enemy class can access it for movement purposes</value> protected Player player; #endregion #region Graphics and Timer GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Timer gameTimer; #endregion #region Textures Texture2D playerCBTexture; Texture2D enemyCBTexture; Texture2D playerBrig; Texture2D playerFrigate; Texture2D playerManOfWar; Texture2D enemyBrig; Texture2D enemyFrigate; Texture2D enemyFireBoat; Texture2D enemyManOfWar; Texture2D healthPowerup; Texture2D multiplierTexture; Texture2D healthBar; Texture2D playerCBPowerUpTexture; Texture2D BossTexture; Texture2D BorderTexture; #endregion #region Music and Sounds //List<Song> BackgroundSongs; //Song mainMenuTheme; //Song gameMusic; List<Song> BackgroundSongs; SoundEffect mainMenuSong; SoundEffectInstance mainMenuSongInstance; SoundEffect gameSong; SoundEffectInstance gameSongInstance; SoundEffect gameOverSong; SoundEffectInstance gameOverSongInstance; #endregion #region Menus Menu mainMenu; Menu bootMenu; Menu pauseMenu; Menu shipSelectionMenu; #endregion #region MouseAndKeyboard InputManager inputManager; #endregion #region SpawningVariables ///<value>random number generator used for all randomizing aspects</value> Random randomGenerator = new Random(); /// <value>lastSpawn keeps track of the time at which the last spawn occured and is later used to enforce spawning on regular time intervals</value> TimeSpan lastSpawn = new TimeSpan(0); ///<value>the lowest x-coordinate value that can be assigned when spawning a new enemy</value> const int LOWER_SPAWN_X = 30; /// <value>the lowest y-coordinate value that can be assigned when spawning a new enemy</value> const int LOWER_SPAWN_Y = 30; /// <value>The max time interval inbetween spawns in milliseconds</value> float SPAWN_TIME_MAX = 4000; /// <value>The min time interval in between spawns in milliseconds</value> float SPAWN_TIME_MIN = 1500; /// <value>the maximum number of enemies that can be on screen at a given point in time</value> int SPAWN_NUMBER_THRESHOLD = 9; float NextSpawn; #endregion #region Lists /// <value>EnemyList holds all enemies that have been spawned on the map</value> List<Enemy> EnemyList; /// <value>List that holds all playerInteractables (multipliers and powerups)</value> List<PlayerInteractable> playerInteractableList; /// <value>List to contain player friendly ships when the user is using the Man Of War and activates its ability</value> List<FriendlyShips> friendlyList; #endregion #region UI /// <value>the score that the player has earned during this game session</value> int score = 0; /// <value>multiplies the worth of each enemy. Increases when multipliers are collected</value> int scoreMultiplier = 1; SpriteFont HUDFont; GameButton startButton, returnToMenu, resumeGame; Vector2 startButtonPos; Texture2D logo; SpriteFont logoFont; SpriteFont mottoFont; GameButton brigButton, frigateButton, manOfWarButton; #endregion //UI #region ObjectDataTypes PlayerData PLAYER_BRIG_DATA, PLAYER_FRIG_DATA, PLAYER_MOW_DATA; EnemyData FIREBOAT_DATA, ENEMY_BRIG_DATA, ENEMY_FRIG_DATA, ENEMY_MOW_DATA, FRIENDLY_SHIPS_DATA; EnemyData BOSS_DATA; PlayerInteractableData HEALTH_POWER_DATA, MULTIPLIER_DATA; #endregion #region Boss Values Vector2 BOSS_POSITION; bool BOSS_SPAWN_SUCCESS = false; bool BOSS_READY_TO_SPAWN = false; #endregion /// <summary> /// The game has several states, but it can only be in one state at a time. /// </summary> enum GameState { BootMenu, MainMenu, ShipSelection, Instructions, Pause, GameOver, Loading, GameOn } /// <value>keep track of this game's current state</value> GameState gameState; #endregion //private variables #region HighScore /// <summary> /// High Scores come with three pieces of information: /// the game the score belongs to /// the high score itself /// and the date that the high score was created /// </summary> public struct HighScoreData { /// <summary> /// The game type that the score was achieved in /// </summary> public string GameType; /// <summary> /// the score that the player achieved /// </summary> public int HighScore; /// <summary> /// Date at which high score is achieved /// </summary> public DateTime date; } /// <summary> /// write to an XML file the high score data for this game type /// </summary> private void saveHighScoreData() { HighScoreData highScore = new HighScoreData(); highScore.GameType = this.ToString(); highScore.HighScore = score; highScore.date = DateTime.Now; //if the new score is larger than the current high score, reset the high score; else do nothing. if (score > readHighScoreData().HighScore) { XmlSerializer writer = new XmlSerializer(typeof(HighScoreData)); StreamWriter file = new StreamWriter("HighScore.xml"); writer.Serialize(file, highScore); file.Close(); } } /// <summary> /// read from an XML file the high score data for this gametype /// </summary> /// <returns>The high score for this game type</returns> private HighScoreData readHighScoreData() { StreamReader file = new StreamReader("HighScore.xml"); XmlSerializer reader = new XmlSerializer(typeof(HighScoreData)); HighScoreData data = (HighScoreData)reader.Deserialize(file); file.Close(); return data; } #endregion #region Initialization /// <summary> /// Sets the basics for the graphics, and GUI for this game /// </summary> public Game1() { /*set graphics properties*/ graphics = new GraphicsDeviceManager(this); graphics.IsFullScreen = false; //Changes the settings that you just applied graphics.ApplyChanges(); Content.RootDirectory = "Content"; //set default screen to the main menu screen gameState = GameState.BootMenu; IsMouseVisible = true; inputManager = new InputManager(); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); IsFixedTimeStep = true; gameTimer = new Timer(); //try opening the high score file. If it does not open, presume that it has not been created before try { StreamReader file = new StreamReader("HighScore.xml"); file.Close(); } catch { //create a new high score where the score is 0 and the date and time is the first time this game was opened HighScoreData highScore = new HighScoreData(); highScore.HighScore = 0; highScore.date = DateTime.Now; XmlSerializer writer = new XmlSerializer(typeof(HighScoreData)); StreamWriter file = new StreamWriter("HighScore.xml"); writer.Serialize(file, highScore); file.Close(); } } #region ChangeMenuFunctions private void ToMainMenu() { gameState = GameState.MainMenu; } //change to MainMenu private void ToShipSelection() { gameState = GameState.ShipSelection; } //change to ShipSelection private void ToGameOn() { gameState = GameState.GameOn; } //Change to GameOn private void ToGameOver() { gameState = GameState.GameOver; } //change to GameOver private void ToPause() { gameState = GameState.Pause; } //change to pause private void LoadPlayerBrig() { player = new Player_Brig(PLAYER_BRIG_DATA, playerBrig, playerCBTexture); ToGameOn(); } private void LoadPlayerFrig() { player = new Player_Frigate(PLAYER_FRIG_DATA, playerFrigate, playerCBTexture); ToGameOn(); } private void LoadPlayerMOW() { player = new Player_ManOfWar(PLAYER_MOW_DATA, playerManOfWar, playerCBTexture); ToGameOn(); } #endregion /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { graphics.PreferredBackBufferHeight = (graphics.GraphicsDevice.DisplayMode.Height - (graphics.GraphicsDevice.DisplayMode.Height / 9)); graphics.PreferredBackBufferWidth = graphics.GraphicsDevice.DisplayMode.Width - (graphics.GraphicsDevice.DisplayMode.Width / 7); graphics.ApplyChanges(); #region Textures playerBrig = Content.Load<Texture2D>("PlayerImages/Brig2_1"); playerFrigate = Content.Load<Texture2D>("PlayerImages/Frigate"); playerManOfWar = Content.Load<Texture2D>("PlayerImages/ManOfWar"); enemyBrig = Content.Load<Texture2D>("EnemyImages/Brig2_1 - Enemy"); enemyFireBoat = Content.Load<Texture2D>("EnemyImages/FireBoat"); enemyFrigate = Content.Load<Texture2D>("EnemyImages/Frigate - Enemy"); enemyManOfWar = Content.Load<Texture2D>("EnemyImages/ManOfWar - Enemy"); healthPowerup = Content.Load<Texture2D>("HealthPowerup"); BossTexture = Content.Load<Texture2D>("EnemyImages/Boss"); #endregion BOSS_POSITION = new Vector2(BossTexture.Width / 2, graphics.PreferredBackBufferHeight / 2 - BossTexture.Height / 2); #region Main Menu logo = Content.Load<Texture2D>("BeardCoded2_1"); logoFont = Content.Load<SpriteFont>("Fonts/LogoFont"); mottoFont = Content.Load<SpriteFont>("Fonts/MottoFont"); #endregion #region GameMaterial // Create a new SpriteBatch, which can be used to draw textures. // player = new Player_Brig(Content); //player = new Player_Frigate(Content); playerStartingPos = new Vector2(graphics.PreferredBackBufferWidth / 2, graphics.PreferredBackBufferHeight / 2); EnemyList = new List<Enemy>(); spriteBatch = new SpriteBatch(GraphicsDevice); playerInteractableList = new List<PlayerInteractable>(); friendlyList = new List<FriendlyShips>(); //load player ship textures playerCBTexture = Content.Load<Texture2D>("CannonBall"); enemyCBTexture = Content.Load<Texture2D>("CannonBall_Enemy"); playerCBPowerUpTexture = Content.Load<Texture2D>("CannonBall_PowerUp"); //Load HUD HUDFont = Content.Load<SpriteFont>("Fonts/HUDFont"); healthBar = Content.Load<Texture2D>("healthBar"); multiplierTexture = Content.Load<Texture2D>("Multiplier"); #endregion #region Time Variables #endregion //Load object data #region ObjectData PLAYER_BRIG_DATA = Content.Load<PlayerData>("ObjectDataFiles/Player/Player_BrigData"); PLAYER_FRIG_DATA = Content.Load<PlayerData>("ObjectDataFiles/Player/Player_FrigateData"); PLAYER_MOW_DATA = Content.Load<PlayerData>("ObjectDataFiles/Player/Player_ManOfWarData"); FIREBOAT_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/FireboatData"); ENEMY_BRIG_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/Enemy_BrigData"); ENEMY_FRIG_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/Enemy_FrigateData"); ENEMY_MOW_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/Enemy_ManOfWarData"); FRIENDLY_SHIPS_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/FriendlyShipsData"); BOSS_DATA = Content.Load<EnemyData>("ObjectDataFiles/AI/BossData"); HEALTH_POWER_DATA = Content.Load<PlayerInteractableData>("ObjectDataFiles/PlayerInteractables/HealthPowerupData"); MULTIPLIER_DATA = Content.Load<PlayerInteractableData>("ObjectDataFiles/PlayerInteractables/MultiplierData"); #endregion #region Sounds //load songs from folder and put in list BackgroundSongs = new List<Song>(); //main menu theme mainMenuSong = Content.Load<SoundEffect>("Sounds/PirateWarsMainMenu"); mainMenuSongInstance = mainMenuSong.CreateInstance(); mainMenuSongInstance.IsLooped = true; //game music gameSong = Content.Load<SoundEffect>("Sounds/GIOmetryWars"); gameSongInstance = gameSong.CreateInstance(); gameSongInstance.IsLooped = true; //game over gameOverSong = Content.Load<SoundEffect>("Sounds/GameOver"); gameOverSongInstance = gameOverSong.CreateInstance(); #endregion #region Menus //General buttons startButtonPos = new Vector2(300, 300); startButton = new GameButton(Content.Load<Texture2D>("StartButton"), startButtonPos); returnToMenu = new GameButton(Content.Load<Texture2D>("ReturnToMenu"), new Vector2(250, 325)); resumeGame = new GameButton(Content.Load<Texture2D>("StartButton"), new Vector2(250, 500)); //Boot Menu TextField motto = new TextField(("Omnis Erigere Niger Vexillum"), new Vector2(200, 600)); GameButton logoB = new GameButton(logo, new Vector2(graphics.PreferredBackBufferWidth / 2 - logo.Width / 2, graphics.PreferredBackBufferHeight / 2 - logo.Height / 2)); bootMenu = new Menu(motto, this); bootMenu.AddMenuButton(logoB, ToMainMenu); //MainMenu TextField menuTitle = new TextField(("BOATS BOATS BOATS"), CenterText("BOATS BOATS BOATS", logoFont)); mainMenu = new Menu(menuTitle, this); mainMenu.AddMenuButton(startButton, ToShipSelection); //PauseMenu TextField pauseTitle = new TextField("PAUSE", CenterText("PAUSE", logoFont)); pauseMenu = new Menu(pauseTitle, this); pauseMenu.AddMenuButton(resumeGame, ToGameOn); pauseMenu.AddMenuButton(returnToMenu, ToMainMenu); //ShipSelectionMenu float x1 = (float)graphics.PreferredBackBufferWidth / 6 - playerBrig.Width / 2; float x2 = (x1 + ((float)graphics.PreferredBackBufferWidth / 3.0f)) - (playerFrigate.Width / 2); float x3 = (x2 + ((float)graphics.PreferredBackBufferWidth / 3.0f)) - (playerManOfWar.Width / 2); Vector2 ship1Pos = new Vector2(x1, (graphics.PreferredBackBufferHeight / 2) - playerBrig.Height / 2); Vector2 ship2Pos = new Vector2(x2, (graphics.PreferredBackBufferHeight / 2) - playerFrigate.Height / 2); Vector2 ship3Pos = new Vector2(x3, (graphics.PreferredBackBufferHeight / 2) - playerManOfWar.Height / 2); brigButton = new GameButton(playerBrig, ship1Pos); frigateButton = new GameButton(playerFrigate, ship2Pos); manOfWarButton = new GameButton(playerManOfWar, ship3Pos); TextField shipSelectionTitle = new TextField("CHOOSE YOUR SHIP", CenterText("CHOOSE YOUR SHIP", logoFont)); shipSelectionMenu = new Menu(shipSelectionTitle, this); shipSelectionMenu.AddMenuButton(brigButton, LoadPlayerBrig); shipSelectionMenu.AddMenuButton(frigateButton, LoadPlayerFrig); shipSelectionMenu.AddMenuButton(manOfWarButton, LoadPlayerMOW); shipSelectionMenu.AddMenuText(new TextField(PLAYER_BRIG_DATA.PrintData(), new Vector2(brigButton.Position.X, brigButton.Position.Y + brigButton.Texture.Height + 20))); shipSelectionMenu.AddMenuText(new TextField(PLAYER_FRIG_DATA.PrintData(), new Vector2(frigateButton.Position.X, frigateButton.Position.Y + brigButton.Texture.Height + 20))); shipSelectionMenu.AddMenuText(new TextField(PLAYER_MOW_DATA.PrintData(), new Vector2(manOfWarButton.Position.X, manOfWarButton.Position.Y + brigButton.Texture.Height + 20))); #endregion } #endregion #region Unload /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { Content.Unload(); base.UnloadContent(); } #endregion #region Game Updating /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> #region Update protected override void Update(GameTime gameTime) { //update the appropriate menu inputManager.Update(gameTime); if (gameState == GameState.BootMenu) bootMenu.Update(gameTime, inputManager); else if (gameState == GameState.MainMenu) mainMenu.Update(gameTime, inputManager); else if (gameState == GameState.Pause) pauseMenu.Update(gameTime, inputManager); else if (gameState == GameState.ShipSelection) shipSelectionMenu.Update(gameTime, inputManager); // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (gameState == GameState.GameOver) { saveHighScoreData(); } /*CHECK WHAT MUSIC SHOULD BE PLAYING*/ //main menu music if (gameState == GameState.MainMenu) { if (gameOverSongInstance.State == SoundState.Playing) gameOverSongInstance.Stop(); if (mainMenuSongInstance.State == SoundState.Stopped) mainMenuSongInstance.Play(); } //game music else if (gameState == GameState.GameOn) { if (mainMenuSongInstance.State == SoundState.Playing) mainMenuSongInstance.Stop(); if (gameSongInstance.State == SoundState.Stopped) gameSongInstance.Play(); } //game over screen music else if (gameState == GameState.GameOver) { if (gameSongInstance.State == SoundState.Playing) gameSongInstance.Stop(); if (gameOverSongInstance.State == SoundState.Stopped) gameOverSongInstance.Play(); } //if game state is GAME ON, do all game updating if (gameState == GameState.GameOn) { if (gameTimer.RawTime == TimeSpan.Zero) StartGame(); IsMouseVisible = false; /*COLLISION DETECTIONS*/ //player against enemy for (int i = EnemyList.Count - 1; i >= 0; i--) { CollisionDetection(player, EnemyList.ElementAt(i), i); } //player against interactables for (int i = playerInteractableList.Count - 1; i >= 0; i--) { CollisionDetection(player, playerInteractableList.ElementAt(i), i); } //enemies against player for (int i = EnemyList.Count - 1; i >= 0; i--) { CollisionDetection(EnemyList.ElementAt(i), player, i); } //friendlies against enemies for (int i = friendlyList.Count - 1; i >= 0; i--) { for (int j = EnemyList.Count - 1; j >= 0; j--) CollisionDetection(friendlyList.ElementAt(i), EnemyList.ElementAt(j), j); } UpdateKeyboardInput(gameTime); player.Update(gameTimer.RawTime); //update object positions foreach (Enemy e in EnemyList) { e.UpdateAndMove(gameTimer.RawTime, player); } for (int i = playerInteractableList.Count - 1; i >= 0; i--) { //update all PlayerInteractables playerInteractableList.ElementAt(i).Update(player, gameTimer.RawTime); //if one has timed out, remove it from the list if (playerInteractableList.ElementAt(i).TimedOut == true) { playerInteractableList.RemoveAt(i); } } /*check the friendlyList; if the list has been initialized, and the ship's ability is not activated, then the list should be cleared. Only applies to Player_ManOfWar. Otherwise, nothing will happen here*/ if (friendlyList.Count >= 0 && (player.getShipState() != Player.ShipState.AbilityActivated)) friendlyList.Clear(); else { if (EnemyList.Count != 0 && friendlyList.Count != 0) { for (int i = 0; i < friendlyList.Count(); i++) { //The targets are the first four elements of enemyList. If there is less than four, then the last one will be attacked by multiple ships int target = i; if (i >= EnemyList.Count - 1) target = EnemyList.Count - 1; friendlyList.ElementAt(i).UpdateAndMove(gameTimer.RawTime, EnemyList.ElementAt(target)); } } } Spawn(gameTime); gameTimer.Update(gameTime); base.Update(gameTime); } else { IsMouseVisible = true; } } #endregion #region KeyboardInput /// <summary> /// Checks for keyboard input, and interprets that keyboard input. /// W: move forward /// A: turn left /// D: turn right /// SPACE: fire /// </summary> /// <param name="time">GameTime used to limit the rate of fire of the player</param> private void UpdateKeyboardInput(GameTime time) { //KeyboardState newState = Keyboard.GetState(); Vector2 newP = player.Position; float angle = player.Angle; TimeSpan newKeyPress = time.TotalGameTime; /* * WAD are the movement keys, but only W will actually move the ship * W: move ship forward in the direction that the ship is pointing * A: rotate the ship to the left (-radians) * D: rotate the ship to the right (+radians) */ if (inputManager.KeyIsDown(Keys.Escape)) { gameState = GameState.Pause; gameTimer.Pause(); } if (inputManager.KeyIsDown(Keys.Tab)) { if (player.getShipState() == Player.ShipState.AbilityCharged) { player.ActivateAbility(gameTimer.RawTime); if (player.GetType() == typeof(Player_ManOfWar)) { //brute force math where the 4 ships should spawn GenerateFriendlies(); } } } if (inputManager.KeyIsDown(Keys.A) || inputManager.KeyIsDown(Keys.Left)) { angle = player.Angle - player.TurnSpeed; } if (inputManager.KeyIsDown(Keys.D) || inputManager.KeyIsDown(Keys.Right)) { angle = player.Angle + player.TurnSpeed; } if (inputManager.KeyIsDown(Keys.W) || inputManager.KeyIsDown(Keys.Up)) { Vector2 direction = new Vector2((float)(Math.Cos(player.Angle)), (float)(Math.Sin(player.Angle))); direction.Normalize(); newP += direction * player.Speed; } //check to make sure it stays within bounds, and then update position and angle if (BOSS_SPAWN_SUCCESS) { OutOfBounds(ref newP, player.Texture, BOSS_POSITION.X, graphics.PreferredBackBufferWidth, 0, graphics.PreferredBackBufferHeight - 50); } else OutOfBounds(ref newP, player.Texture, 0, graphics.PreferredBackBufferWidth, 0, graphics.PreferredBackBufferHeight); player.Position = newP; player.Angle = angle; //place a delay on the space bar firing if (inputManager.KeyIsDown(Keys.Space)) player.Fire(gameTimer.RawTime); }//end UpdateInput (Keyboard #endregion //keyboard private void GenerateFriendlies() { FriendlyShips e = new FriendlyShips(ENEMY_FRIG_DATA, playerFrigate, playerCBTexture); float BUFFER = 25; friendlyList = new List<FriendlyShips>(); //ship 1 (12:00) float x = player.Position.X; float y = player.Position.Y - (2 * player.Origin.Y) - (2 * e.Origin.Y) - BUFFER; Vector2 ePos = new Vector2(x, y); e.Position = ePos; friendlyList.Add(e); //ship 2 (9 position) x = player.Position.X - player.Origin.X - e.Origin.X - BUFFER; y = player.Position.Y - player.Origin.Y; FriendlyShips e1 = new FriendlyShips(ENEMY_FRIG_DATA, playerFrigate, playerCBTexture); ePos = new Vector2(x, y); e1.Position = ePos; friendlyList.Add(e1); //ship 3 (6:00) x = player.Position.X; y = player.Position.Y + (2 * player.Origin.Y) + (2 * e.Origin.Y) + BUFFER; ePos = new Vector2(x, y); FriendlyShips e2 = new FriendlyShips(ENEMY_FRIG_DATA, playerFrigate, playerCBTexture); e2.Position = ePos; friendlyList.Add(e2); //ship 4 (3:00) x = player.Position.X + player.Origin.X + e.Origin.X + BUFFER; y = player.Position.Y - player.Origin.Y; FriendlyShips e3 = new FriendlyShips(ENEMY_FRIG_DATA, playerFrigate, playerCBTexture); ePos = new Vector2(x, y); e3.Position = ePos; friendlyList.Add(e3); } #region Helpers /// <summary> /// Set all game values to default value. Called when first starting the game (or restarting the game) /// </summary> private void StartGame() { gameState = GameState.Loading; //ready the player player.Position = playerStartingPos; player.Reset(); //set game constants score = 0; scoreMultiplier = 1; lastSpawn = TimeSpan.Zero; //make sure all lists are empty EnemyList.Clear(); player.CannonBalls.Clear(); playerInteractableList.Clear(); //set gameState to GameOn gameState = GameState.GameOn; //set Boss values to false BOSS_SPAWN_SUCCESS = false; BOSS_READY_TO_SPAWN = false; //make sure the timer is set to 0, and then start it gameTimer.Reset(); gameTimer.Start(); } private void DropPowerup(Enemy e) { int r = randomGenerator.Next(0, 100); if (r >= 0 && r < 10) { playerInteractableList.Add(new HealthPowerup(HEALTH_POWER_DATA, e.Position, new Vector2(0, -1), (float)(Math.PI / 2), healthPowerup, gameTimer.RawTime)); } } private Vector2 CenterText(string s, SpriteFont f) { float x = graphics.PreferredBackBufferWidth / 2 - f.MeasureString(s).X / 2; float y = 25 + f.MeasureString(s).Y; return new Vector2(x, y); } #endregion #region Draw /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); //check game state and draw screen accordingly if (gameState == GameState.BootMenu) { GraphicsDevice.Clear(Color.Black); bootMenu.DrawMenu(spriteBatch, graphics, mottoFont, null); //DrawBootMenu(spriteBatch, gameTime); } else if (gameState == GameState.Loading) { spriteBatch.DrawString(logoFont, "LOADING " + (gameTimer.DisplayTime), new Vector2(300, 200), Color.Black); } else if (gameState == GameState.MainMenu) { //draw main menu GraphicsDevice.Clear(Color.Black); mainMenu.DrawMenu(spriteBatch, graphics, logoFont, null); } else if (gameState == GameState.ShipSelection) { //draw ship selection menu shipSelectionMenu.DrawMenu(spriteBatch,graphics,logoFont, mottoFont); } else if (gameState == GameState.GameOn) { //draw main game DrawGame(spriteBatch, gameTime); } else if (gameState == GameState.Pause) { //draw pause menu //DrawPauseMenu(spriteBatch, gameTime); } else if (gameState == GameState.GameOver) { //draw game over screen spriteBatch.DrawString(logoFont, "GAME OVER", new Vector2(250, 100), Color.Black); spriteBatch.DrawString(mottoFont, "Score: " + score, new Vector2(250, 300), Color.Black); spriteBatch.DrawString(mottoFont, "High Score: " + readHighScoreData().HighScore + " " + readHighScoreData().date, new Vector2(400, 300), Color.Black); spriteBatch.Draw(returnToMenu.Texture, returnToMenu.Position, Color.White); } spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Draw the main game /// </summary> /// <param name="spriteBatch">SpriteBatch used to draw all textures</param> /// <param name="gameTime">Contains timing information for the game</param> private void DrawGame(SpriteBatch spriteBatch, GameTime gameTime) { //set background color GraphicsDevice.Clear(new Color(28, 107, 160)); //draw player spriteBatch.Draw(player.Texture, player.Position, null, Color.White, player.Angle, player.Origin, 1.0f, SpriteEffects.None, 0.0f); //if there are friendlies if (player.GetType() == typeof(Player_ManOfWar)) { for (int i = friendlyList.Count - 1; i >= 0; i--) { spriteBatch.Draw(friendlyList.ElementAt(i).Texture, friendlyList.ElementAt(i).Position, null, Color.White, friendlyList.ElementAt(i).Angle, friendlyList.ElementAt(i).Origin, 1.0f, SpriteEffects.None, 0.0f); } } /*draw enemies*/ for (int i = (EnemyList.Count - 1); i >= 0; i--) { Enemy e1 = EnemyList.ElementAt(i); spriteBatch.Draw(e1.Texture, e1.Position, null, Color.White, e1.Angle, e1.Origin, 1.0f, SpriteEffects.None, 0.0f); //if it is a boss enemy, draw a health bar if (e1.GetType() == typeof(Boss1)) { int x = (int)(e1.Position.X - e1.Texture.Width / 2); int y = (int)(e1.Position.Y - e1.Texture.Height / 2); //give the enemy a health bar that the player can see int healthBarL = (int)((healthBar.Width * .5f) * (double)((e1.Health / e1.MaxHealth))); spriteBatch.Draw(healthBar, new Rectangle(x, y, healthBarL / 2, 15), Color.Red); } } //draw player cannon balls for (int i = player.CannonBalls.Count - 1; i >= 0; i--) { CannonBall c = player.CannonBalls.ElementAt(i); /*if the cannon ball has gone out of bounds, remove it and do not draw, else draw it*/ if (OutOfBounds(player.CannonBalls.ElementAt(i))) { player.CannonBalls.RemoveAt(i); } else { if (player.GetType() == typeof(Player_Frigate) && player.getShipState() == Player.ShipState.AbilityActivated) spriteBatch.Draw(playerCBPowerUpTexture, c.Position, null, Color.White, c.Angle, c.Origin, 1.0f, SpriteEffects.None, 0.0f); else spriteBatch.Draw(playerCBTexture, c.Position, null, Color.White, c.Angle, c.Origin, 1.0f, SpriteEffects.None, 0.0f); } } //draw enemy cannon balls foreach (Enemy e in EnemyList) { for (int i = e.CannonBalls.Count - 1; i >= 0; i--) { CannonBall c = e.CannonBalls.ElementAt(i); if (OutOfBounds(c)) { e.CannonBalls.RemoveAt(i); } else spriteBatch.Draw(enemyCBTexture, c.Position, null, Color.White, c.Angle, c.Origin, 1.0f, SpriteEffects.None, 0.0f); } } //draw friendly cannon balls foreach (FriendlyShips fs in friendlyList) { for (int i = fs.CannonBalls.Count - 1; i >= 0; i--) { if (OutOfBounds(fs.CannonBalls.ElementAt(i))) { fs.CannonBalls.Remove(fs.CannonBalls.ElementAt(i)); } else { spriteBatch.Draw(playerCBTexture, fs.CannonBalls.ElementAt(i).Position, null, Color.White, fs.CannonBalls.ElementAt(i).Angle, fs.CannonBalls.ElementAt(i).Origin, 1.0f, SpriteEffects.None, 0.0f); } } } //draw player interactables for (int i = playerInteractableList.Count - 1; i >= 0; i--) { if (OutOfBounds(playerInteractableList.ElementAt(i))) playerInteractableList.RemoveAt(i); else if (playerInteractableList.ElementAt(i).Faded == false) { spriteBatch.Draw(playerInteractableList.ElementAt(i).Texture, playerInteractableList.ElementAt(i).Position, Color.White); } } /*Draw HUD*/ //draw score spriteBatch.DrawString(HUDFont, "Score: " + score + "\nx" + scoreMultiplier, new Vector2(50, 50), Color.Black); Color healthBarC = new Color(); healthBarC = Color.Green; //if the player's ability is activated, then they are invincible. Turn the health bar to gold to indicate this if (player.getShipState() == Player.ShipState.AbilityActivated) { healthBarC = Color.Gold; } //draw health bar spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, (int)(healthBar.Width * ((double)player.Health / player.MaxHealth)), 44), healthBarC); /* * draw ability duration bar underneath the health bar * If the ability is depleting, draw gameTimer.RawTime - abilityActivateTime / AbilityDuration */ if (player.getShipState() == Player.ShipState.AbilityActivated) { //width of the ability activated bar int width = (int)(healthBar.Width * (1 - (gameTimer.RawTime.TotalMilliseconds - player.getAbilityActivateTime().TotalMilliseconds) / player.getAbilityDuration())); spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 75, width, 25), Color.Red); } //draw ability recharging else if (player.getShipState() != Player.ShipState.AbilityActivated) { int width = (int)(MathHelper.Clamp((float)(healthBar.Width * (((gameTimer.RawTime.TotalMilliseconds - player.getAbilityRechargeStartTime().TotalMilliseconds) / player.getAbilityRecharge()))), 0, (int)healthBar.Width)); spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 75, width, 25), Color.Red); } //draw time spriteBatch.DrawString(HUDFont, "Time: " + (gameTimer.DisplayTime), new Vector2(graphics.PreferredBackBufferWidth - 200, 50), Color.Black); } #endregion #region Spawn /// <summary> /// Creates new enemies and adds them to <see cref="EnemyList"/>. Only spawns new enemies every 3 seconds. /// </summary> /// <param name="gameTime">snapshot of time values used to limit enemy spawning to happen every 3 seconds</param> private void Spawn(GameTime gameTime) { TimeSpan currentTime = gameTimer.RawTime; int scorePerMinute = (int)((score * 1000) / currentTime.TotalMilliseconds); //subtract from NextSpawn the time since the last update NextSpawn -= (float)gameTime.ElapsedGameTime.TotalMilliseconds; int numberToSpawn = (int)Math.Floor(Math.Log(1 + currentTime.TotalSeconds) + Math.Log((1 + scorePerMinute), 5)); if (numberToSpawn >= SPAWN_NUMBER_THRESHOLD && BOSS_SPAWN_SUCCESS == false) { //check to see if the boss can successfully spawn. If it can't at least set BOSS_READ_TO_SPAWN to true so other enemies stop spawnin BOSS_SPAWN_SUCCESS = SpawnBoss(); BOSS_READY_TO_SPAWN = true; } //if the boss has spawned successfully, it should be the only thing in the list. When EnemyList.Count == 0, then the boss is dead. Set BOSS_SPAWNED_SUCCESS to false, and restart spawning smaller enemies if (BOSS_SPAWN_SUCCESS == true) { if (EnemyList.Count == 0) { BOSS_SPAWN_SUCCESS = false; ResetSpawnTime(numberToSpawn); BOSS_READY_TO_SPAWN = false; //after beating the boss, increase the spawn number threshold so that they can face normal enemies again SPAWN_NUMBER_THRESHOLD += 2; } } //if the boss is not ready to spawn, continue spawning regular enemies enemies else if (NextSpawn <= SPAWN_NUMBER_THRESHOLD && BOSS_READY_TO_SPAWN == false) { /* * Lograthmic spawn: * The number of enemies that spawns durig any given wave is the sum of the natural log of game time + the natural log of their score per second * Ensures that the number is dynamic based on player ability but has a baseline for each game */ numberToSpawn = (int)(MathHelper.Clamp(numberToSpawn, 0, 8)); lastSpawn = gameTimer.RawTime; for (int i = 0; i < numberToSpawn; i++) { //create new enemy int spawnType = randomGenerator.Next() % 100; Enemy e = new Enemy_Brig(); if (spawnType >= 0 && spawnType < 50) { e = new FireBoat(FIREBOAT_DATA, enemyFireBoat); } else if (spawnType >= 50 && spawnType < 75) { e = new Enemy_Brig(ENEMY_BRIG_DATA, enemyBrig, enemyCBTexture); } else if (spawnType >= 75 && spawnType < 90) { e = new Enemy_Frigate(ENEMY_FRIG_DATA, enemyFrigate, enemyCBTexture); } else { e = new Enemy_ManOfWar(ENEMY_MOW_DATA, enemyManOfWar, enemyCBTexture); } /*create random spawn points within the bounds of the screen.*/ int posX, posY; /* There are four regions around the edge of the map (left, right, top, bottom) * randomly choose where to spawn the enemy so that they spawn anywhere within one of those four regions */ int region = randomGenerator.Next(0, 3); switch (region) { //spawn left. X value should be between the lowest X bound and 50, and y can be from lower bound to buffer height case 0: posX = randomGenerator.Next(LOWER_SPAWN_X, 50); posY = randomGenerator.Next(LOWER_SPAWN_Y, graphics.PreferredBackBufferHeight); break; //spawn top. Y value is trapped between lower Y bound and 50, and x can be from lower X to buffer width case 1: posX = randomGenerator.Next(LOWER_SPAWN_X, graphics.PreferredBackBufferWidth); posY = randomGenerator.Next(LOWER_SPAWN_Y, 50); break; //spawn right. X is trapped between buffer width - 50, and buffer width. Y can be between lower bound and buffer height case 2: posX = randomGenerator.Next(graphics.PreferredBackBufferWidth - 50, graphics.PreferredBackBufferWidth); posY = randomGenerator.Next(LOWER_SPAWN_Y, graphics.PreferredBackBufferHeight); break; //spawn bottom. Y is trapped between buffer height - 50 and buffer height. X can be between lower bound and buffer width default: posX = randomGenerator.Next(LOWER_SPAWN_X, graphics.PreferredBackBufferWidth); posY = randomGenerator.Next(graphics.PreferredBackBufferHeight - 50, graphics.PreferredBackBufferHeight); break; } e.Position = new Vector2(posX, posY); //set the ship's angle such that it spans pointing towards the player float angle = Object.TurnToFace(e.Position, player.Position, e.Angle, MathHelper.TwoPi); e.Angle = angle; EnemyList.Add(e); //reset spawn time ResetSpawnTime(numberToSpawn); } } } private void ResetSpawnTime(int spawnNumber) { //if it is the first 10 seconds of the game, force the next spawn to happen at SPAWN_TIME_MAX if (gameTimer.RawTime.TotalSeconds <= 10) NextSpawn = SPAWN_TIME_MAX; //otherwise, just pick a spawn time between the min and max times else NextSpawn = (float)randomGenerator.Next((int)SPAWN_TIME_MIN, (int)SPAWN_TIME_MAX); } private bool SpawnBoss() { if (EnemyList.Count == 0) { Boss1 b = new Boss1(BOSS_DATA, BossTexture, enemyCBTexture, BOSS_POSITION); float posX, posY; posX = LOWER_SPAWN_X; posY = LOWER_SPAWN_Y; b.Position = (new Vector2(posX, posY)); EnemyList.Add(b); return true; } if (BOSS_SPAWN_SUCCESS == true) return true; return false; } #endregion #endregion //game updating #region Out of Bounds Check /// <summary> /// This function checks to see if a vector will be out of the GUI bounds, and if it is out of bounds, will set the vector so that it comes back in bounds /// </summary> /// <param name="v">the vector taken in to see if it is out of bounds. Passed by reference.</param> /// <param name="t">the texture that belongs to that vector. Since all objects are drawn with the origin at their middle, it is necesary to know what the width and height of the object are, otherwise, half the object will be allowed to leave the screen</param> /// <param name="lowerXBound">The vector's x value is not allowed to be less than this</param> /// <param name="lowerYBound">The vector's y value is not allowed to be less than this</param> /// <param name="upperXBound">The vector's x value is not allowed to be greater than this</param> /// <param name="upperYBound">The vector's y value is not allowed to be greater than this</param> private void OutOfBounds(ref Vector2 v, Texture2D t, float lowerXBound, float upperXBound, float lowerYBound, float upperYBound) { //out of bounds top if (v.Y - (t.Height / 2) < lowerYBound) { v.Y = lowerYBound + t.Height / 2; } //out of bounds bottom else if (v.Y + (t.Height / 2) > upperYBound) { v.Y = upperYBound - (t.Height / 2); } //out of bounds left else if (v.X - (t.Width / 2) < lowerXBound) { v.X = lowerXBound + t.Width / 2; } //out of bounds right else if (v.X + (t.Width / 2) > upperXBound) { v.X = upperXBound - (t.Width / 2); } else { return; } }//end OutOfBounds (vector2, texture) /// <summary> /// This function checks to see if a CannonBall is out of bounds. If it is, return true; else return false /// </summary> /// <param name="c">the cannon ball to be checked for out of boundsness.</param> private bool OutOfBounds(CannonBall c) { if (c.Position.X < 0 || c.Position.X > graphics.PreferredBackBufferWidth) return true; else if (c.Position.Y < 0 || c.Position.Y > graphics.PreferredBackBufferHeight) return true; else return false; }//outof bounds cannon private bool OutOfBounds(PlayerInteractable m) { if (m.Position.X < 0 || m.Position.X > graphics.PreferredBackBufferWidth) return true; else if (m.Position.Y < 0 || m.Position.Y > graphics.PreferredBackBufferHeight) return true; else return false; } #endregion #region Collision Detection /// <summary> /// Collision detection between two ships. Checks the cannon ball array of the first ship against the second ship to see if the first ship has hit the second. If it has, damage is dealt, and this function checks to see if the second ship has lost all its health and if it has removes the ship. Works for both player vs enemy and enemy vs player and handles all special cases /// </summary> /// <param name="s">The ship dealing damage</param> /// <param name="e">The ship having damage dealt against it</param> /// <param name="index">Only needs to be used if the function is being called from a loop iterating through a list. it allows the use of RemoveAt() which is O(1) over Remove() which is O(n)</param> private void CollisionDetection(Ship s, Ship e, int index) { //check cannon balls for (int j = s.CannonBalls.Count - 1; j >= 0; j--) { CannonBall cB = s.CannonBalls.ElementAt(j); if (cB.BoundingBox.Intersects(e.BoundingBox)) { //deal damage to enemy e.takeDamage(cB.Damage); //remove cannon ball s.CannonBalls.Remove(cB); }//end if collision //check if the ship should be sunk }//end for j //if s is the player, then check if it is a brig and has its ability activated if (s == player) { if (player.GetType() == typeof(Player_Brig) && player.getShipState() == Player.ShipState.AbilityActivated) if (s.BoundingBox.Intersects(e.BoundingBox)) { e.takeDamage(s.Damage); } } //if the ship is a fireboat, check if it has collided with the other ship. If it has, then do damage and remove it from the list and return if (s.GetType() == typeof(FireBoat)) { if (s.BoundingBox.Intersects(e.BoundingBox)) { EnemyList.RemoveAt(index); return; } } //check if the ship should be sunk if (e.Health <= 0) { if (e.GetType() == typeof(Player_Brig) || e.GetType() == typeof(Player_Frigate) || e.GetType() == typeof(Player_ManOfWar)) { gameState = GameState.GameOver; } else { //add score score += (((Enemy)(e)).getScore() * scoreMultiplier); //drop multipliers int numberOfMultis = ((Enemy)(e)).getScore() / 5; for (int m = 0; m < numberOfMultis; m++) { Multiplier mp = new Multiplier(MULTIPLIER_DATA, e.Position, e.Position, (float)(randomGenerator.Next(360)) * (float)(Math.PI / 180), multiplierTexture, gameTimer.RawTime); playerInteractableList.Add(mp); } //determine if this ship will drop a powerup DropPowerup((Enemy)e); //remove from list EnemyList.RemoveAt(index); } } } private void CollisionDetection(Player s, PlayerInteractable p, int index) { if (s.BoundingBox.Intersects(p.BoundingBox)) { if (p.GetType() == typeof(Multiplier)) scoreMultiplier++; else p.ActivateAbility(s); playerInteractableList.RemoveAt(index); } } #endregion } #endregion }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class InviteFriendPrefab : MonoBehaviour { public Text m_AvatarText; public Image m_CheckImage; bool m_IsSelected = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void SetInfo(string info) { m_AvatarText.text = info; } public void OnSelected() { m_IsSelected = !m_IsSelected; ShowSelected(m_IsSelected); //SceneManager.Instance.GetCanvasByID(CanvasID.CANVAS_NEWGAME).gameObject.GetComponent<UINewGame>().OnFriendSelected(gameObject); } public void ShowSelected(bool visible) { m_CheckImage.gameObject.SetActive(visible); } }
using Logs.Authentication.Contracts; using Logs.Models; using Logs.Providers.Contracts; using Logs.Services.Contracts; using Logs.Web.Controllers; using Logs.Web.Infrastructure.Factories; using Logs.Web.Models.Nutrition; using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TestStack.FluentMVCTesting; namespace Logs.Web.Tests.Controllers.NutritionControllerTests { [TestFixture] public class GetNutritionTests { [TestCase(1)] [TestCase(6)] [TestCase(1457)] [TestCase(13)] public void TestGetNutrition_ShouldCallSeasurementServiceGetById(int id) { // Arrange var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedNutritionService = new Mock<INutritionService>(); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); var controller = new NutritionController(mockedFactory.Object, mockedDateTimeProvider.Object, mockedNutritionService.Object, mockedAuthenticationProvider.Object); // Act controller.GetNutrition(id); // Assert mockedNutritionService.Verify(s => s.GetById(id), Times.Once); } [TestCase(1)] [TestCase(6)] [TestCase(1457)] [TestCase(13)] public void TestGetNutrition_ServiceReturnsNull_ShouldRenderPartialViewWithModelNull(int id) { // Arrange var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedNutritionService = new Mock<INutritionService>(); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); var controller = new NutritionController(mockedFactory.Object, mockedDateTimeProvider.Object, mockedNutritionService.Object, mockedAuthenticationProvider.Object); // Act, Assert controller .WithCallTo(c => c.GetNutrition(id)) .ShouldRenderPartialView("NutritionDetails"); } [TestCase(1)] [TestCase(6)] [TestCase(1457)] [TestCase(13)] public void TestGetNutrition_ServiceReturnsNutrition_ShouldCallFactoryCreateNutritionViewModel(int id) { // Arrange var date = new DateTime(1, 2, 3); var nutrition = new Nutrition { Date = date }; var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedNutritionService = new Mock<INutritionService>(); mockedNutritionService.Setup(s => s.GetById(It.IsAny<int>())).Returns(nutrition); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); var controller = new NutritionController(mockedFactory.Object, mockedDateTimeProvider.Object, mockedNutritionService.Object, mockedAuthenticationProvider.Object); // Act controller.GetNutrition(id); // Assert mockedFactory.Verify(f => f.CreateNutritionViewModel(nutrition, date), Times.Once); } [TestCase(1)] [TestCase(6)] [TestCase(1457)] [TestCase(13)] public void TestGetNutrition_ServiceReturnsNutrition_ShouldRenderPartialViewWithModel(int id) { // Arrange var date = new DateTime(1, 2, 3); var nutrition = new Nutrition { Date = date }; var model = new NutritionViewModel(); var mockedFactory = new Mock<IViewModelFactory>(); mockedFactory.Setup(f => f.CreateNutritionViewModel(It.IsAny<Nutrition>(), It.IsAny<DateTime>())) .Returns(model); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedNutritionService = new Mock<INutritionService>(); mockedNutritionService.Setup(s => s.GetById(It.IsAny<int>())).Returns(nutrition); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); var controller = new NutritionController(mockedFactory.Object, mockedDateTimeProvider.Object, mockedNutritionService.Object, mockedAuthenticationProvider.Object); // Act, Assert controller .WithCallTo(c => c.GetNutrition(id)) .ShouldRenderPartialView("NutritionDetails") .WithModel<NutritionViewModel>(model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PnrAnalysis.Model { /// <summary> /// 从混乱的字符串内容中分离出正确的数据内容 /// </summary> /// [Serializable] public class SplitPnrCon { /// <summary> /// 所有内容 /// </summary> public string ALLCon = string.Empty; /// <summary> /// 单独的RT内容 /// </summary> public string RTCon = string.Empty; /// <summary> /// 成人PAT内容 /// </summary> public string AdultPATCon = string.Empty; /// <summary> /// 儿童PAT内容 /// </summary> public string ChdPATCon = string.Empty; /// <summary> /// 婴儿PAT内容 /// </summary> public string INFPATCon = string.Empty; } }
using System; using System.Net.Http; using Acr.UserDialogs; using MvvmCross.Platform; using MvvmCross.Platform.IoC; using MvvmCross.Platform.Platform; using Refit; namespace VictimApplication.Core { public class App : MvvmCross.Core.ViewModels.MvxApplication { public override void Initialize() { CreatableTypes() .EndingWith("Service") .AsInterfaces() .RegisterAsLazySingleton(); RegisterNavigationServiceAppStart<ViewModels.LoginViewModel>(); } public App() { //API Mvx.RegisterType(() => { var client = "http://localhost:63082"; return RestService.For<Services.IApi>(client); }); //UserDialogs Mvx.RegisterSingleton<IUserDialogs>(() => UserDialogs.Instance); } } }
// <copyright file="Result.cs" company="Visualbean"> // Copyright (c) Visualbean. All rights reserved. // </copyright> namespace Visualbean.Pokemon { using System; /// <summary> /// A Result. /// </summary> public class Result { /// <summary> /// Initializes a new instance of the <see cref="Result" /> class. /// </summary> /// <param name="status">The status.</param> /// <param name="error">The error.</param> /// <exception cref="InvalidOperationException"></exception> protected Result(Status status, string error) { this.Status = status; this.Error = error; if ((this.IsSuccess && !string.IsNullOrWhiteSpace(error)) || (!this.IsSuccess && string.IsNullOrWhiteSpace(error))) { throw new InvalidOperationException(); } } /// <summary> /// Gets a value indicating whether this instance is success. /// </summary> /// <value> /// <c>true</c> if this instance is success; otherwise, <c>false</c>. /// </value> public bool IsSuccess => (int)this.Status < 10; /// <summary> /// Gets the status. /// </summary> /// <value> /// The status. /// </value> public Status Status { get; private set; } /// <summary> /// Gets the error. /// </summary> /// <value> /// The error. /// </value> public string Error { get; private set; } /// <summary> /// Gets a value indicating whether this instance is failure. /// </summary> /// <value> /// <c>true</c> if this instance is failure; otherwise, <c>false</c>. /// </value> public bool IsFailure => !this.IsSuccess; /// <summary> /// Fails the specified message. /// </summary> /// <param name="message">The message.</param> /// <returns>A result.</returns> public static Result Fail(string message) => new Result(Status.Error, message); /// <summary> /// Fails the specified message. /// </summary> /// <typeparam name="T">The type of data stored.</typeparam> /// <param name="message">The message.</param> /// <returns>A result.</returns> public static Result<T> Fail<T>(string message) => new Result<T>(default(T), Status.Error, message); /// <summary> /// Oks the specified value. /// </summary> /// <typeparam name="T">The type of data stored.</typeparam> /// <param name="value">The value.</param> /// <returns>A result.</returns> public static Result<T> Ok<T>(T value) => new Result<T>(value, Status.Ok, error: null); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ClassLearning { class Program { static void Main(string[] args) { Book book = new Book(); Book book1 = new Book(1, 3m, "a"); Console.WriteLine("{0} : {1} : {2} ", book.a, book.b, book.c); Console.WriteLine(book1.a + "" + book1.b + "" + book1.c); DemoExtends demoExtends = new DemoExtends();//静态构造函数被调用了一次 DemoStatic.a = 5;//不会再调用静态构造函数了 Console.WriteLine(DemoStatic.a); //因为其私有化了构造函数,所有需要通过静态成员变量来实例化该对象 //这种模式称之为工厂模式 PrivateClass privateClass = PrivateClass.ToPrivateClass(); ReadOnlyClass readOnlyClass = new ReadOnlyClass(1, 2, 3); Console.WriteLine(readOnlyClass.readOnly + readOnlyClass.readOnly1 + readOnlyClass.ReadOnly2); Console.WriteLine(Days.Friday); Demo demo = new Demo(); Console.WriteLine(Days.Friday + 0); demo = null; GC.Collect(); Person person1 = new Person("George",40); Person person2 = new Person(person1); person1.Age = 39; person2.Age = 41; person2.Name = "Charles"; Console.WriteLine(person1.Details()); Console.WriteLine(person2.Details()); Demo demoClone = (Demo)demo.Clone(); if(Regex.ReferenceEquals(demo,demoClone)) { Console.WriteLine("他们是相同的实例"); } Console.ReadKey(); } } public struct Book { public decimal a; public int b; public string c; public Book(int m, decimal n, string s) { a = n; b = m; c = s; } } abstract class BaseC { public int n; public void Invoke() { } public abstract void Invoke1(); } class DerivedC : BaseC { new public void Invoke() { } public override void Invoke1() { } } enum Days : int { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Staturday = 6 }; enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; }
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FeelingGoodApp.Models { //public record FoodViewModel(string FoodName); public class FoodViewModel { public string FoodName { get; set; } //public FoodViewModel(string foodName) //{ // FoodName = foodName; //} } }
using System.IO.Compression; namespace Frontend.Core.Common.Proxies { public class ZipFileProxy : IZipFileProxy { public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName) { ZipFile.ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName); } public ZipArchive Open(string archiveFileName, ZipArchiveMode mode) { return ZipFile.Open(archiveFileName, mode); } public void ExtractToFile(ZipArchiveEntry source, string destinationFileName, bool overwrite) { source.ExtractToFile(destinationFileName, overwrite); } } }
namespace CloneDeploy_Entities.DTOs.FormData { public class ImageIdDTO { public string imageId { get; set; } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_Skybox : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { Skybox o = new Skybox(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_material(IntPtr l) { int result; try { Skybox skybox = (Skybox)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, skybox.get_material()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_material(IntPtr l) { int result; try { Skybox skybox = (Skybox)LuaObject.checkSelf(l); Material material; LuaObject.checkType<Material>(l, 2, out material); skybox.set_material(material); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.Skybox"); LuaObject.addMember(l, "material", new LuaCSFunction(Lua_UnityEngine_Skybox.get_material), new LuaCSFunction(Lua_UnityEngine_Skybox.set_material), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Skybox.constructor), typeof(Skybox), typeof(Behaviour)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class TakeABreakTimer : MonoBehaviour { public GameObject TakeABreak; private bool done = false; void Update() { Debug.Log("checking"); if (Time.time >= 20 && !done) { TakeABreak.gameObject.SetActive(true); done = true; } } }
namespace SGDE.DataEFCoreSQL.Repositories { #region Using using System.Collections.Generic; using System.Linq; using Domain.Entities; using Domain.Repositories; using System; #endregion public class HourTypeRepository : IHourTypeRepository, IDisposable { private readonly EFContextSQL _context; public HourTypeRepository(EFContextSQL context) { _context = context; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _context.Dispose(); } } private bool HourTypeExists(int id) { return GetById(id) != null; } public List<HourType> GetAll() { return _context.HourType .ToList(); } public HourType GetById(int id) { return _context.HourType .FirstOrDefault(x => x.Id == id); } public HourType Add(HourType newHourType) { _context.HourType.Add(newHourType); _context.SaveChanges(); return newHourType; } public bool Update(HourType hourType) { if (!HourTypeExists(hourType.Id)) return false; _context.HourType.Update(hourType); _context.SaveChanges(); return true; } public bool Delete(int id) { if (!HourTypeExists(id)) return false; var toRemove = _context.HourType.Find(id); _context.HourType.Remove(toRemove); _context.SaveChanges(); return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameController : MonoBehaviour { public GameObject loadingScreen; public Slider slider; public GameObject pauseScreen; private bool isPaused; private string sceneName; [HideInInspector] public int currentLevelIndex = 1; private void Start() { sceneName = SceneManager.GetActiveScene().name; if (sceneName != "menu") { pauseScreen.SetActive(false); } } private void Update() { if (Input.GetKeyDown(KeyCode.P) && !sceneName.Equals("menu")) { Pause(); } } public void SaveGame() { Game.current = new global::Game(); SaveData.Save(); } void Pause() { isPaused = !pauseScreen.activeSelf; if (isPaused) { Time.timeScale = 0; pauseScreen.SetActive(true); } else { Time.timeScale = 1; pauseScreen.SetActive(false); } } public void LoadMenu() { StartCoroutine(LoadAsynchronously(0)); } public void LoadLevel() { StartCoroutine(LoadAsynchronously(currentLevelIndex)); } IEnumerator LoadAsynchronously(int sceneIndex) { AsyncOperation op = SceneManager.LoadSceneAsync(sceneIndex); loadingScreen.SetActive(true); while (!op.isDone) { float progress = Mathf.Clamp01(op.progress / .9f); slider.value = progress; yield return null; } } public void QuitGame() { Application.Quit(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Infra; namespace Console2.G_Code { public class G_021_Print2BST { /* * 2个BST,按大小顺序打印两棵树的所有节点。 * http://www.mitbbs.com/article_t/JobHunting/32266793.html * this question may not be a google question. */ public List<int> Print2BST(TreeNode root1, TreeNode root2) { List<int> res = new List<int>(); Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); s1.Push(root1); s2.Push(root2); bool isBackTrack1 = false; bool isBackTrack2 = false; while (s1.Count != 0 || s2.Count != 0) { TreeNode tmp1 = null; TreeNode tmp2 = null; if (s1.Count != 0) { tmp1 = s1.Peek(); if (!isBackTrack1 && tmp1.LeftChild != null) { s1.Push(tmp1.LeftChild); isBackTrack1 = false; continue; } } if (s2.Count != 0) { tmp2 = s2.Peek(); if (!isBackTrack2 && tmp2.LeftChild != null) { s2.Push(tmp2.LeftChild); isBackTrack2 = false; continue; } } if (tmp1 != null && tmp2 != null) { if (tmp1.Value <= tmp2.Value) { tmp1 = s1.Pop(); res.Add(tmp1.Value); isBackTrack1 = true; tmp2 = null; } else if (tmp1.Value > tmp2.Value) { tmp2 = s2.Pop(); res.Add(tmp2.Value); isBackTrack2 = true; tmp1 = null; } } else if (tmp1 != null && tmp2 == null) { tmp1 = s1.Pop(); res.Add(tmp1.Value); isBackTrack1 = true; tmp2 = null; } else if (tmp2 != null && tmp1 == null) { tmp2 = s2.Pop(); res.Add(tmp2.Value); isBackTrack2 = true; tmp1 = null; } if (tmp1 != null) { if (tmp1.RightChild != null) { s1.Push(tmp1.RightChild); isBackTrack1 = false; } } else { if (tmp2.RightChild != null) { s2.Push(tmp2.RightChild); isBackTrack2 = false; } } } return res; } } }
using Extension; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using Zenject; namespace Lonely.Editor { /// <summary> /// Editor에서는 GameObject 생성으로 Inject하는 것이 안됨. 그래서 Inject없이 강제 생성 /// </summary> public class SceneContextFactory : IFactory<SceneContext> { #region Explicit Interface SceneContext IFactory<SceneContext>.Create() { var scPrefab = AssetDatabase.LoadAssetAtPath<Object>(SCENE_CONTEXT_PREFAB_PATH); Debug.Assert(scPrefab.IsValid()); var scGO = PrefabUtility.InstantiatePrefab(scPrefab) as GameObject; Debug.Assert(scGO.IsValid()); var context = scGO.GetComponent<SceneContext>(); Debug.Assert(context.IsValid()); //Selection.activeGameObject = root.gameObject; EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); return context; } #endregion Explicit Interface private const string SCENE_CONTEXT_PREFAB_PATH = "Assets/MisticPuzzle/Prefabs/SceneContext.prefab"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MessingWithInterfaces { public interface IFlammable { bool IsOnFire { get; } void Burn(); } public class Paper : IFlammable { private bool _isOnFire; public bool IsOnFire { get { return _isOnFire; } } public Paper() { _isOnFire = false; } public void Burn() { _isOnFire = true; } } public class TrashBag : IFlammable { private bool _isOnFire; private List<IFlammable> _trashItems; public TrashBag() { _trashItems = new List<IFlammable>(); _isOnFire = false; } public bool IsOnFire { get { return _isOnFire; } } public void Add(IFlammable flammableItem) { _trashItems.Add(flammableItem); } public void Burn() { _isOnFire = true; foreach (IFlammable trashItem in _trashItems) { trashItem.Burn(); } } } public class Car : IFlammable { private bool _isOnFire; private List<IFlammable> _itemsInTrunk; public Car() { _itemsInTrunk = new List<IFlammable>(); _isOnFire = false; } public bool IsOnFire { get { return _isOnFire; } } public void ThrowInTrunk(IFlammable flammableItem) { _itemsInTrunk.Add(flammableItem); } public void Burn() { _isOnFire = true; foreach (IFlammable trashItem in _itemsInTrunk) { trashItem.Burn(); } } } public class Furnace { private List<IFlammable> _kindle; public Furnace() { _kindle = new List<IFlammable>(); } public void Add(IFlammable flammableItem) { _kindle.Add(flammableItem); } public void Light() { foreach (IFlammable flammableItem in _kindle) { flammableItem.Burn(); } } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Tff.Panzer.Models.Army; using System.Xml.Linq; using System.Linq; using System.Windows.Resources; using System.Windows.Media.Imaging; using System.Collections.Generic; using Tff.Panzer.Models.Scenario; using Tff.Panzer.Models; using Tff.Panzer.Models.Army.Unit; namespace Tff.Panzer.Factories.Army { public class UnitFactory { public EquipmentFactory EquipmentFactory { get; private set; } public UnitFactory() { EquipmentFactory = new EquipmentFactory(); } public IUnit CreateUnit(int unitId, ScenarioUnit scenarioUnit) { Equipment equipment = EquipmentFactory.GetEquipment(scenarioUnit.EquipmentId); switch(equipment.EquipmentGroupEnum) { case EquipmentGroupEnum.Land: if (equipment.MovementType.IsMotorized) { MotorizedLandCombatUnit motorizedLandCombatUnit = CreateMotorizedLandCombatUnit(unitId, scenarioUnit); if (scenarioUnit.TransportId != 0) { LandTransportUnit landTransportUnit = CreateLandTransport(unitId, scenarioUnit.TransportId, motorizedLandCombatUnit.Nation, motorizedLandCombatUnit.CoreIndicator,scenarioUnit.StartingScenarioTileId); landTransportUnit.LandCombatUnit = motorizedLandCombatUnit; motorizedLandCombatUnit.TransportUnit = landTransportUnit; } return motorizedLandCombatUnit; } else { LandCombatUnit landCombatUnit = CreateLandCombatUnit(unitId, scenarioUnit); if (scenarioUnit.TransportId != 0) { LandTransportUnit landTransportUnit = CreateLandTransport(unitId, scenarioUnit.TransportId, landCombatUnit.Nation, landCombatUnit.CoreIndicator, scenarioUnit.StartingScenarioTileId); landTransportUnit.LandCombatUnit = landCombatUnit; landCombatUnit.TransportUnit = landTransportUnit; } return landCombatUnit; } case EquipmentGroupEnum.Air: return CreateAirCombatUnit(unitId, scenarioUnit); case EquipmentGroupEnum.Sea: return CreateSeaCombatUnit(unitId, scenarioUnit); } return null; } public IUnit CreateDefaultUnit(int unitId, Int32 equipmentId, Int32 transportEquipmentId, Int32 nationId) { ScenarioUnit scenarioUnit = new ScenarioUnit(); scenarioUnit.EquipmentId = equipmentId; scenarioUnit.TransportId = transportEquipmentId; scenarioUnit.NationId = nationId; scenarioUnit.Strength = 10; return CreateUnit(unitId, scenarioUnit); } public LandCombatUnit CreateLandCombatUnit(int unitId, ScenarioUnit scenarioUnit) { LandCombatUnit unit = new LandCombatUnit(); unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(scenarioUnit.EquipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentExperience = scenarioUnit.Experience; unit.CurrentStrength = scenarioUnit.Strength; unit.CurrentAttackPoints = scenarioUnit.Strength; unit.Nation = Game.NationFactory.GetNation(scenarioUnit.NationId); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentAmmo = unit.Equipment.MaxAmmo; unit.CurrentEntrenchedLevel = 0; unit.CanMove = true; unit.CanAttack = true; unit.CurrentTileId = scenarioUnit.StartingScenarioTileId; return unit; } public MotorizedLandCombatUnit CreateMotorizedLandCombatUnit(int unitId, ScenarioUnit scenarioUnit) { MotorizedLandCombatUnit unit = new MotorizedLandCombatUnit(); unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(scenarioUnit.EquipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentExperience = scenarioUnit.Experience; unit.CurrentStrength = scenarioUnit.Strength; unit.CurrentAttackPoints = scenarioUnit.Strength; unit.Nation = Game.NationFactory.GetNation(scenarioUnit.NationId); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentAmmo = unit.Equipment.MaxAmmo; unit.CurrentFuel = unit.Equipment.MaxFuel; unit.CurrentEntrenchedLevel = 0; unit.CanMove = true; unit.CanAttack = true; unit.CurrentTileId = scenarioUnit.StartingScenarioTileId; return unit; } public SeaCombatUnit CreateSeaCombatUnit(int unitId, ScenarioUnit scenarioUnit) { SeaCombatUnit unit = new SeaCombatUnit(); unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(scenarioUnit.EquipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentExperience = scenarioUnit.Experience; unit.CurrentStrength = scenarioUnit.Strength; unit.CurrentAttackPoints = scenarioUnit.Strength; unit.Nation = Game.NationFactory.GetNation(scenarioUnit.NationId); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentAmmo = unit.Equipment.MaxAmmo; unit.CurrentFuel = unit.Equipment.MaxFuel; unit.CanMove = true; unit.CanAttack = true; unit.CurrentTileId = scenarioUnit.StartingScenarioTileId; return unit; } public AirCombatUnit CreateAirCombatUnit(int unitId, ScenarioUnit scenarioUnit) { AirCombatUnit unit = new AirCombatUnit(); unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(scenarioUnit.EquipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentExperience = scenarioUnit.Experience; unit.CurrentStrength = scenarioUnit.Strength; unit.CurrentAttackPoints = scenarioUnit.Strength; unit.Nation = Game.NationFactory.GetNation(scenarioUnit.NationId); unit.CoreIndicator = scenarioUnit.CordInd; unit.CurrentAmmo = unit.Equipment.MaxAmmo; unit.CurrentFuel = unit.Equipment.MaxFuel; unit.CanMove = true; unit.CanAttack = true; unit.CurrentTileId = scenarioUnit.StartingScenarioTileId; return unit; } public LandTransportUnit CreateLandTransport(int unitId, int equipmentId, Nation nation, bool coreInd, int startingTileId) { LandTransportUnit unit = new LandTransportUnit(); unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(equipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.CurrentStrength = 10; unit.CurrentExperience = 0; if (unit.Equipment.MaxFuel == 0) { unit.CurrentFuel = 99; } else { unit.CurrentFuel = unit.Equipment.MaxFuel; } unit.CoreIndicator = coreInd; unit.Nation = nation; unit.CanMove = true; unit.CurrentTileId = startingTileId; return unit; } public AirTransportUnit CreateAirTransportUnit(int unitId, Nation nation, int startingTileId) { int equipmentId = 0; AirTransportUnit unit = new AirTransportUnit(); switch (nation.NationEnum) { case NationEnum.German: equipmentId = 29; break; case NationEnum.GreatBritain: equipmentId = 178; break; case NationEnum.Italy: equipmentId = 309; break; case NationEnum.UnitedStates: equipmentId = 354; break; default: if (Game.NationFactory.SideFactory.GetSideForANation(nation.NationId).SideEnum == SideEnum.Axis) { equipmentId = 29; } else { equipmentId = 178; } break; } unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(equipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.Nation = nation; unit.CurrentStrength = 10; unit.CurrentExperience = 0; unit.CurrentFuel = 99; unit.CanMove = true; unit.CurrentTileId = startingTileId; return unit; } public SeaTransportUnit CreateSeaTransportUnit(int unitId, Nation nation, int startingTileId) { SeaTransportUnit unit = new SeaTransportUnit(); int equipmentId = 0; if (nation.SideEnum == SideEnum.Axis) { equipmentId = 299; } else { equipmentId = 291; } unit.UnitId = unitId; unit.Equipment = EquipmentFactory.GetEquipment(equipmentId); unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.Nation = nation; unit.CurrentStrength = 10; unit.CurrentExperience = 0; unit.CurrentFuel = 99; unit.CanMove = true; unit.CurrentTileId = startingTileId; return unit; } public LandCombatUnit CreateDefaultAntiTankUnit(int unitId, Nation nation, int startingTileId) { LandCombatUnit unit = new LandCombatUnit(); List<Equipment> equipments = EquipmentFactory.Equipments.Where(e => e.Nation == nation).ToList(); Equipment equipment = equipments.Where(eq => eq.UnitCost == equipments.Min(e => e.UnitCost)).FirstOrDefault(); unit.UnitId = unitId; unit.Equipment = equipment; unit.UnitName = String.Format("{0} {1}", unitId, unit.Equipment.EquipmentDescription); unit.Nation = nation; unit.CurrentStrength = 10; unit.CurrentExperience = 0; unit.CanMove = true; unit.CurrentTileId = startingTileId; if (unit.SideEnum == SideEnum.Axis) { Game.CurrentTurn.CurrentAxisPrestige = Game.CurrentTurn.CurrentAxisPrestige - unit.Equipment.UnitCost; } else { Game.CurrentTurn.CurrentAlliedPrestige = Game.CurrentTurn.CurrentAlliedPrestige - unit.Equipment.UnitCost; } return unit; } public void ResupplyUnit(IUnit unit) { if (unit is ICombatUnit) { ICombatUnit combatUnit = (ICombatUnit)unit; combatUnit.CurrentAmmo = unit.Equipment.MaxAmmo; } if (unit is IMotorizedUnit) { IMotorizedUnit motorizedUnit = (IMotorizedUnit)unit; motorizedUnit.CurrentFuel = unit.Equipment.MaxFuel; } } public void ReinforceUnit(IUnit unit, bool useEliteReplacements) { int numberOfStrengthDesiredToReinforce = 0; if (unit.CurrentStrength < 10) { numberOfStrengthDesiredToReinforce = 10 - unit.CurrentStrength; } else { numberOfStrengthDesiredToReinforce = 1; } int reinforceCost = unit.Equipment.UnitCost/10; if (useEliteReplacements) { reinforceCost = reinforceCost * 2; } int numberOfStrengthAvailableToReinforce = 0; if(unit.SideEnum == SideEnum.Axis) { numberOfStrengthAvailableToReinforce = Game.CurrentTurn.CurrentAxisPrestige/reinforceCost; } else { numberOfStrengthAvailableToReinforce = Game.CurrentTurn.CurrentAlliedPrestige/reinforceCost; } int numberOfStrengthToReinforce = 0; if (numberOfStrengthDesiredToReinforce >= numberOfStrengthAvailableToReinforce) { numberOfStrengthToReinforce = numberOfStrengthAvailableToReinforce; } else { numberOfStrengthToReinforce = numberOfStrengthDesiredToReinforce; } int totalCostToReinforce = numberOfStrengthToReinforce * reinforceCost; if (unit.SideEnum == SideEnum.Axis) { Game.CurrentTurn.CurrentAxisPrestige = Game.CurrentTurn.CurrentAxisPrestige - totalCostToReinforce; } else { Game.CurrentTurn.CurrentAlliedPrestige = Game.CurrentTurn.CurrentAlliedPrestige - totalCostToReinforce; } ResupplyUnit(unit); unit.CurrentStrength += numberOfStrengthToReinforce; if (useEliteReplacements == false) { int experienceUnit = unit.CurrentExperience / 10; int experienceCost = (Int32)numberOfStrengthToReinforce* experienceUnit; unit.CurrentExperience = unit.CurrentExperience - experienceCost; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.IO; namespace Fithome { public partial class Form1 : Form { public Form1() { InitializeComponent(); } OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Application.StartupPath+@"\data\data.mdb"); public void antrenman_gunlugu() { try { baglan.Open(); listView1.Items.Clear(); OleDbCommand komut = new OleDbCommand("select *from antrenman", baglan); OleDbDataReader oku = komut.ExecuteReader(); while (oku.Read()) { ListViewItem itemler = new ListViewItem(oku["gun"].ToString()); itemler.SubItems.Add(oku["omuz"].ToString()); itemler.SubItems.Add(oku["gogus"].ToString()); itemler.SubItems.Add(oku["sirt"].ToString()); itemler.SubItems.Add(oku["biceps"].ToString()); itemler.SubItems.Add(oku["triceps"].ToString()); itemler.SubItems.Add(oku["karin"].ToString()); itemler.SubItems.Add(oku["bacak"].ToString()); itemler.SubItems.Add(oku["protein"].ToString()); itemler.SubItems.Add(oku["kosu"].ToString()); itemler.SubItems.Add(oku["sorun"].ToString()); listView1.Items.Add(itemler); ListView lw = this.listView1; foreach (ListViewItem item in lw.Items) { for(int i=0; i<=item.SubItems.Count-1;i++) { item.UseItemStyleForSubItems = false; if (item.SubItems[i].Text.IndexOf("✗") > -1 && i <= 7 && item.SubItems[i].Text != "") item.SubItems[i].BackColor = Color.MistyRose; else if (item.SubItems[i].Text.IndexOf("✓") == -1 && i <= 7 && item.SubItems[i].Text != "") item.SubItems[i].BackColor = Color.LightGreen; else if (i == 8 && item.SubItems[i].Text != "") item.SubItems[i].BackColor = Color.FromArgb(255, 255, 160); else if (i == 9 && item.SubItems[i].Text != "") item.SubItems[i].BackColor = Color.LightBlue; else if (i >= 10 && item.SubItems[i].Text != "") item.UseItemStyleForSubItems = true; } string gun = item.Text.Remove(0, item.Text.IndexOf("-") + 1); if (gun == "Pazartesi") item.BackColor = Color.FromArgb(80, 90, 90); if (item.Text.IndexOf("Salı") > 0) item.BackColor = Color.FromArgb(90, 100, 110); if (item.Text.IndexOf("Çarşamba") > 0) item.BackColor = Color.FromArgb(120, 130, 140); if (item.Text.IndexOf("Perşembe") > 0) item.BackColor = Color.FromArgb(150, 160, 170); if (item.Text.IndexOf("Cuma") > 0) item.BackColor = Color.FromArgb(180, 190, 200); if (item.Text.IndexOf("Cumartesi") > 0) item.BackColor = Color.FromArgb(210, 220, 230); if (gun=="Pazar") item.BackColor = Color.FromArgb(240, 250, 250); } } gun_label.Text = "ANTRENMAN " + (listView1.Items.Count + 1).ToString(); baglan.Close(); } catch(Exception hata) { MessageBox.Show(hata.Message.ToString(), "Fithome", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Form1_Load(object sender, EventArgs e) { antrenman_gunlugu(); gun_label.Text = "ANTRENMAN " + (listView1.Items.Count + 1).ToString(); } private void yenidenBaşlatToolStripMenuItem_Click(object sender, EventArgs e) { Application.Restart(); } private void kapatToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void kaydet_button_Click(object sender, EventArgs e) { try { baglan.Open(); OleDbCommand komut = new OleDbCommand("insert into antrenman (gun,omuz,gogus,sirt,biceps,triceps,karin,bacak,protein,kosu) values(@gun,@omuz,@gogus,@sirt,@biceps,@triceps,@karin,@bacak,@protein,@kosu)", baglan); string gun = DateTime.Now.ToLongDateString(); for (int i = 0; i <= gun.Length - 1; i++) { gun = gun.Remove(0, gun.IndexOf(" ") + 1); } if(listView1.Items.Count==-1) komut.Parameters.AddWithValue("@gun","1-" + gun); else komut.Parameters.AddWithValue("@gun", (listView1.Items.Count+1).ToString() + "-" + gun); if(omuz_ok.Checked==true) komut.Parameters.AddWithValue("@omuz", omuz_tekrar.Value.ToString() + "x" + omuz_set.Value.ToString()); else komut.Parameters.AddWithValue("@omuz", "✗"); if (gogus_ok.Checked == true) komut.Parameters.AddWithValue("@gogus", gogus_tekrar.Value.ToString() + "x" + gogus_set.Value.ToString()); else komut.Parameters.AddWithValue("@gogus", "✗"); if (sirt_ok.Checked == true) komut.Parameters.AddWithValue("@sirt", sirt_tekrar.Value.ToString() + "x" + sirt_set.Value.ToString()); else komut.Parameters.AddWithValue("@sirt", "✗"); if (biceps_ok.Checked == true) komut.Parameters.AddWithValue("@biceps", biceps_tekrar.Value.ToString() + "x" + biceps_set.Value.ToString()); else komut.Parameters.AddWithValue("@biceps", "✗"); if (triceps_ok.Checked == true) komut.Parameters.AddWithValue("@triceps", triceps_tekrar.Value.ToString() + "x" + triceps_set.Value.ToString()); else komut.Parameters.AddWithValue("@omuz", "✗"); if (karin_ok.Checked == true) komut.Parameters.AddWithValue("@karin", karin_tekrar.Value.ToString() + "x" + karin_set.Value.ToString()); else komut.Parameters.AddWithValue("@karin", "✗"); if (bacak_ok.Checked == true) komut.Parameters.AddWithValue("@bacak", bacak_tekrar.Value.ToString() + "x" + bacak_set.Value.ToString()); else komut.Parameters.AddWithValue("@bacak", "✗"); komut.Parameters.AddWithValue("@protein", protein_takviyesi.Text); if (kosu_ok.Checked == true) komut.Parameters.AddWithValue("@kosu", kosu_km.Value.ToString()+ "," + kosu_mt.Value.ToString()+" km"); else komut.Parameters.AddWithValue("@kosu", "✗"); komut.ExecuteNonQuery(); baglan.Close(); antrenman_gunlugu(); } catch(Exception hata) { MessageBox.Show(hata.Message.ToString(), "Fithome", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void silToolStripMenuItem_Click(object sender, EventArgs e) { try { baglan.Open(); OleDbCommand komut = new OleDbCommand("Delete from antrenman where gun='" + listView1.SelectedItems[0].SubItems[0].Text + "'", baglan); komut.ExecuteNonQuery(); baglan.Close(); antrenman_gunlugu(); } catch(Exception hata) { MessageBox.Show(hata.Message.ToString(), "Fithome", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void sorun_button_Click(object sender, EventArgs e) { if (sorun_text.Text != "") { try { baglan.Open(); OleDbCommand komut = new OleDbCommand("insert into antrenman (gun,sorun) values(@gun,@sorun)", baglan); string gun = DateTime.Now.ToLongDateString(); for (int i = 0; i <= gun.Length - 1; i++) { gun = gun.Remove(0, gun.IndexOf(" ") + 1); } komut.Parameters.AddWithValue("@gun", (listView1.Items.Count - 1).ToString() + "-" + gun); komut.Parameters.AddWithValue("@sorun", sorun_text.Text); komut.ExecuteNonQuery(); baglan.Close(); antrenman_gunlugu(); } catch (Exception hata) { MessageBox.Show(hata.Message.ToString(), "Fithome", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { try { baglan.Open(); OleDbCommand komut = new OleDbCommand("insert into antrenman (gun,sorun) values(@gun,@sorun)", baglan); string gun = DateTime.Now.ToLongDateString(); for (int i = 0; i <= gun.Length - 1; i++) { gun = gun.Remove(0, gun.IndexOf(" ") + 1); } komut.Parameters.AddWithValue("@gun", (listView1.Items.Count - 1).ToString() + "-" + gun); komut.Parameters.AddWithValue("@sorun", "Belirtilmemiş"); komut.ExecuteNonQuery(); baglan.Close(); antrenman_gunlugu(); } catch(Exception hata) { MessageBox.Show(hata.Message.ToString(), "Fithome", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { try { if (listView1.SelectedItems[0].SubItems[0].Text != null && listView1.SelectedIndices[0] > -1) contextMenuStrip1.Enabled = true; else contextMenuStrip1.Enabled = false; } catch { contextMenuStrip1.Enabled = false; } } private void temizle_button_Click(object sender, EventArgs e) { } } }
//----------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> // <author>Mark Junker</author> //----------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System; using System.Timers; namespace CompressionStocking { public class AirCompression : ICompressionCtrl { private Pump _air_pump = new Pump(); private Timer _compression_timer = new Timer(); private Timer _decompression_timer = new Timer(); public AirCompression() { _compression_timer.Interval = 5000; _decompression_timer.Interval = 2000; _compression_timer.AutoReset = false; _decompression_timer.AutoReset = false; _compression_timer.Elapsed += compression_event; _decompression_timer.Elapsed += decompression_event; } public void compress() { _air_pump.forward(); } public void decompress() { _air_pump.backward(); } public void compression_event(object obj, EventArgs e) { _air_pump.stop(); Console.WriteLine("Compression is done"); } public void decompression_event(object obj, EventArgs e) { _air_pump.stop(); Console.WriteLine("Decompression is done"); } } }
using GigHub.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace GigHub.ViewModels { public class GigFormViewModel { [Required] public string Venue { get; set; } [Required] [FutureDate] public string Date { get; set; } [Required] [ValidTime] public string Time { get; set; } [Required] public byte Genre { get; set; } public IEnumerable<Genre> Genres { get; set; } //using Genre class from Model folder /* As per the condition it should not throw error. * when the model state isnot valid still its coming to GigFormViewModel and its showing error. * Because all properties inspects httprequest nad it needs a value fro each key.inorder to solve this we made it a method * public DateTime DateTime { get { return DateTime.Parse(string.Format("{0} {1}", Date, Time)); } } */ public DateTime GetDateTime() { { return DateTime.Parse(string.Format("{0} {1}", Date, Time)); } } } }
 namespace AlienEngine.Core.Physics.Paths { /// <summary> /// Wrapper around a 3d position curve that specifies a specific velocity at which to travel. /// </summary> public class ConstantLinearSpeedCurve : ConstantSpeedCurve<Vector3f> { /// <summary> /// Constructs a new constant speed curve. /// </summary> /// <param name="speed">Speed to maintain while traveling around a curve.</param> /// <param name="curve">Curve to wrap.</param> public ConstantLinearSpeedCurve(float speed, Curve<Vector3f> curve) : base(speed, curve) { } /// <summary> /// Constructs a new constant speed curve. /// </summary> /// <param name="speed">Speed to maintain while traveling around a curve.</param> /// <param name="curve">Curve to wrap.</param> /// <param name="sampleCount">Number of samples to use when constructing the wrapper curve. /// More samples increases the accuracy of the speed requirement at the cost of performance.</param> public ConstantLinearSpeedCurve(float speed, Curve<Vector3f> curve, int sampleCount) : base(speed, curve, sampleCount) { } protected override float GetDistance(Vector3f start, Vector3f end) { float distance; Vector3f.Distance(ref start, ref end, out distance); return distance; } } }
using System; using System.Collections.Generic; using System.Linq; public class ArrayStack<T> { private const int defaultCpacity = 16; private T[] elements; public int Count { get; private set; } public ArrayStack(int capacity = defaultCpacity) { this.elements = new T[capacity]; } public void Push(T element) { if (this.Count == this.elements.Length) this.Grow(); this.elements[this.Count] = element; this.Count++; } private void Grow() { T[] doubleArr = new T[this.Count * 2]; Array.Copy(this.elements, doubleArr, this.elements.Length); this.elements = doubleArr; } public T Pop() { if(this.Count == 0) { throw new InvalidOperationException("The stack is empty!"); } T lastElement = this.elements[this.Count - 1]; this.elements[this.Count - 1] = default(T); this.Count--; return lastElement; } public T[] ToArray() { T[] trimmedArray = new T[this.Count]; for (int i = 0; i < this.Count; i++) { trimmedArray[i] = this.elements[this.Count - 1 - i]; } return trimmedArray; } }
using UnityEngine; using System.Collections; using Pathfinding; using System.Collections.Generic; public class EnemyMovement : MonoBehaviour { public bool changedStates = false; public bool newPatrolPath = false; public int decimalRounding = 2; public int framesAllowedStationary = 10; public float normalSpeed = 1.0f; public float alertedSpeed = 2.0f; public float normalRotateSpeed = 1.0f; public float fastRotateSpeed = 4.0f; public float nextWaypointDistance = 1.0f; public float percentOfFOVToContinuePath = 0.3f; public string nameTouch; public string nameBump; public List<Transform> listTransPatrol = new List<Transform>(); public GameObject goSharedVariables; private bool calculatingPath = false; private int currentWaypoint = 0; private int patrolCounter = 0; private int stuckCounter; private string hot = "Hot"; private string cold = "Cold"; private Vector3 lastMyPosition; private GameObject goCharacter; private List<GameObject> listHotColdObjects = new List<GameObject>(); private CharacterController myCharContro; private Transform myTransform; private Transform currentHotColdTrans; private HeatControl scriptHeat; private Seeker scriptSeeker; private EnemyState scriptState; private EnemySight scriptSight; private EnemyBump scriptBump; private EnemyShared scriptShared; private Path myPath; private EnemyState.CurrentState lastState; // Use this for initialization void Start () { stuckCounter = framesAllowedStationary; myCharContro = this.GetComponent<CharacterController>(); myTransform = this.transform; goCharacter = GameObject.Find("Character"); if (!goSharedVariables) Debug.Log("Please assign the Enemy Shared Variables game object to the Enemy Movement script."); scriptState = GetComponentInChildren<EnemyState>(); scriptSeeker = GetComponent<Seeker>(); scriptSight = GetComponentInChildren<EnemySight>(); scriptBump = GetComponentInChildren<EnemyBump>(); scriptShared = goSharedVariables.GetComponent<EnemyShared>(); lastState = scriptState.nmeCurrentState; } void FixedUpdate () { if (lastState != scriptState.nmeCurrentState) { changedStates = true; print("Last state: " + lastState + " Current state: " + scriptState.nmeCurrentState); } switch (scriptState.nmeCurrentState) { case EnemyState.CurrentState.Patroling: Patrol(); break; case EnemyState.CurrentState.Chasing: Chasing(alertedSpeed); break; case EnemyState.CurrentState.Firing: Chasing(normalSpeed); break; case EnemyState.CurrentState.Turning: FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); break; case EnemyState.CurrentState.Padding: break; case EnemyState.CurrentState.Searching: Searching(); break; case EnemyState.CurrentState.Stationary: break; } lastState = scriptState.nmeCurrentState; lastMyPosition = myTransform.position; } void FaceTarget(Vector3 parTarget, float parRotateSpeed, bool parConstrainXZAxes) { Quaternion target = Quaternion.LookRotation(parTarget - myTransform.position); if (parConstrainXZAxes) { target.x = 0.0f; target.z = 0.0f; } myTransform.rotation = Quaternion.Slerp(myTransform.rotation, target, Time.deltaTime * parRotateSpeed); } void MoveTowards(Vector3 parTarget, float parMoveSpeed) { myCharContro.SimpleMove(new Vector3(parTarget.x, 0.0f, parTarget.z) * Time.fixedDeltaTime * parMoveSpeed); } Transform FindNearestHotOrColdObject() { listHotColdObjects.AddRange(GameObject.FindGameObjectsWithTag(hot)); //Put all the hot objects in the list listHotColdObjects.AddRange(GameObject.FindGameObjectsWithTag(cold)); //Put all the cold objects in the list float nearestSqr = Mathf.Infinity; Transform nearestTran = null; foreach (GameObject aGO in listHotColdObjects) { float distanceSqr = (aGO.transform.position - myTransform.position).sqrMagnitude; //print("Name: " + aGO.name + " Magnitude Squared: " + distanceSqr); if (distanceSqr < nearestSqr && aGO.transform != currentHotColdTrans) { nearestSqr = distanceSqr; nearestTran = aGO.transform; //print(true); } } return nearestTran; } void OnPathComplete(Path parPath) { if (parPath.error) { Debug.LogError(parPath.errorLog); } else { myPath = parPath; currentWaypoint = 0; calculatingPath = false; } } void Patrol() { if (calculatingPath) // If we are waiting on the pathfinding, don't do anything else until we have a path { return; } if (scriptSight.useSphericalHeatSensor) // If we are only patroling between objects that are currently out of the room temperature range, check to see if they are still in that range { if (RemoveLukewarmObjects()) // If removing the objects necessitates creating a new path, return { return; } } if (WeNeedANewPath()) { return; } FaceTarget(myPath.vectorPath[currentWaypoint], normalRotateSpeed, true); //Face the waypoint as we are going there Vector3 dir = (myPath.vectorPath[currentWaypoint] - myTransform.position).normalized; //Get the normalized direction to the next waypoint MoveTowards(dir, normalSpeed); //Move towards that waypoint if (IHaveBeenStuck(false)) return; if (Vector3.Distance(myPath.vectorPath[currentWaypoint], myTransform.position) < nextWaypointDistance) //If we are close enough to the current waypoint, start moving towards the next waypoint. { currentWaypoint++; //print("New Waypoint: " + currentWaypoint); } } void Chasing(float parChaseSpeed) { if (PathIsClear()) { Vector3 direction = goCharacter.transform.position - myTransform.position; FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); MoveTowards(direction.normalized, parChaseSpeed); } else if (GettingAPathToCharacter()) { return; } else { if (Vector3.Distance(myPath.vectorPath[currentWaypoint], myTransform.position) < nextWaypointDistance && ((currentWaypoint + 1) < myPath.vectorPath.Count)) // If we are close enough to the current waypoint and there is another waypoint left, start moving towards the next waypoint. { // I decided to put this before moving so that we don't move towards a waypoint unnecessarily currentWaypoint++; //print("New Waypoint: " + currentWaypoint); } FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); Vector3 dir = (myPath.vectorPath[currentWaypoint] - myTransform.position).normalized; MoveTowards(dir, parChaseSpeed); if (IHaveBeenStuck(true)) return; } } void GetANewPatrolPath() { currentHotColdTrans = listTransPatrol[patrolCounter]; // Assign the current target to the item in the array equal to the patrolCounter patrolCounter++; // Increment the patrolCounter if (patrolCounter >= listTransPatrol.Count) // If the patrolCounter is greater than or equal to the count, reset it to zero (since the counter and the array start at zero) { patrolCounter = 0; } if (currentHotColdTrans != null) { scriptSeeker.StartPath(myTransform.position, currentHotColdTrans.position, OnPathComplete); } } bool RemoveLukewarmObjects() { for (int i = 0; i < listTransPatrol.Count; i++) { scriptHeat = listTransPatrol[i].GetComponent<HeatControl>(); if (listTransPatrol[i].tag != hot && listTransPatrol[i].tag != cold && scriptHeat.inHeatSensorRange) { if (listTransPatrol[i] == currentHotColdTrans) // If the item in the list is no longer hot or cold, we need to remove it from the list { listTransPatrol.RemoveAt(i); //print("Patrol counter: " + patrolCounter + " List count: " + listTransPatrol.Count); if (patrolCounter != 0) // If it's not zero (e.g., if the last in the sequence got removed, so the counter would already be at zero) { patrolCounter--; // Decrement by one to get it to target the "next" transform } //print("Removed current target from list. Patrol counter = " + patrolCounter); GetANewPatrolPath(); calculatingPath = true; return true; // !@#$ What happens here when two objects need removing and only one gets removed because we calculate a new path? Would it be better or worse to do one at a time? } else { listTransPatrol.RemoveAt(i); if (patrolCounter >= listTransPatrol.Count) { patrolCounter = 0; } } } } return false; } bool WeNeedANewPath() { if (myPath == null) // If we have no path, get one { GetANewPatrolPath(); calculatingPath = true; return true; } else if (changedStates) { GetANewPatrolPath(); calculatingPath = true; changedStates = false; return true; } else if (currentWaypoint >= myPath.vectorPath.Count) //If we have reached the end of the path { GetANewPatrolPath(); calculatingPath = true; return true; } else if (newPatrolPath) //If we have touched the object we are trying to reach (but can't get close enough to the waypoint to have reached the end of the path) { GetANewPatrolPath(); print("Touching objective in the path."); calculatingPath = true; newPatrolPath = false; return true; } else if (scriptBump.isBumping) { if (nameBump != nameTouch) { scriptSeeker.StartPath(myTransform.position, currentHotColdTrans.position, OnPathComplete); // We don't want a new path based on the new, incremented patrol counter. Just use the current objective. print("Bumped into obstacle while patroling."); scriptBump.isBumping = false; return false; // So it doesn't hiccup when we change paths, don't return and don't set calculating path to true } else return false; } else return false; } bool PathIsClear() { RaycastHit hit; Vector3 direction = goCharacter.transform.position - myTransform.position; if (Physics.Raycast(myTransform.position, direction.normalized, out hit, Mathf.Infinity)) { if (hit.collider.gameObject == goCharacter) { return true; } } return false; } bool GettingAPathToCharacter() { if (calculatingPath) { FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); return true; } else if (changedStates) // We might have a path left over from another state, so clear the path and get a new one, but look at the character while we are waiting on the path { myPath = null; scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); changedStates = false; calculatingPath = true; FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); return true; } else if (myPath == null) { FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); calculatingPath = true; return true; } else if (currentWaypoint >= myPath.vectorPath.Count) //If we have reached the end of the path { FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); calculatingPath = true; return true; } else if (scriptBump.isBumping) { print("Bumped into obstacle while chasing."); FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); calculatingPath = true; scriptBump.isBumping = false; return true; } else if (WaypointPlayerAngle()) { print("Path end no longer leads to player."); FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); calculatingPath = true; return true; } return false; } public static float Round(float value, int digits) { float mult = Mathf.Pow(10.0f, (float)digits); return Mathf.Round(value * mult) / mult; } bool IHaveBeenStuck(bool parChasing) { if (new Vector3(Round(myTransform.position.x, decimalRounding), Round(myTransform.position.y, decimalRounding), Round(myTransform.position.z, decimalRounding)) == new Vector3(Round(lastMyPosition.x, decimalRounding), Round(lastMyPosition.y, decimalRounding), Round(lastMyPosition.z, decimalRounding))) //If we aren't moving, get a new path { stuckCounter--; if (stuckCounter <= 0) { if (parChasing) { FaceTarget(goCharacter.transform.position, fastRotateSpeed, true); scriptSeeker.StartPath(myTransform.position, goCharacter.transform.position, OnPathComplete); calculatingPath = true; stuckCounter = framesAllowedStationary; } else { GetANewPatrolPath(); calculatingPath = true; stuckCounter = framesAllowedStationary; } return true; } } else { stuckCounter = framesAllowedStationary; } return false; } bool WaypointPlayerAngle() { Vector3 pathDir = myPath.vectorPath[myPath.vectorPath.Count - 1] - myTransform.position; // Get a vector direction between myself and the final point of the path Vector3 playerDir = goCharacter.transform.position - myTransform.position; float pathPlayerAngle = Vector3.Angle(pathDir, playerDir); //print("Way X: " + pathDir.x + " Way Y: " + pathDir.y + " Way Z: " + pathDir.z + " Player X: " + playerDir.x + " Player Y: " + playerDir.y + " Player Z: " + playerDir.z + " Angle: " + pathPlayerAngle); if (pathPlayerAngle > scriptSight.fieldOfViewAngle * percentOfFOVToContinuePath) return true; else return false; } void Searching() { if (Vector3.Distance(myTransform.position, new Vector3(scriptShared.sharedLastKnownLocation.x, myTransform.position.y, scriptShared.sharedLastKnownLocation.z)) > nextWaypointDistance) // We don't want to check the difference in y's because the player might be above the enemy where it can't get. { FaceTarget(scriptShared.sharedLastKnownLocation, fastRotateSpeed, true); Vector3 direction = scriptShared.sharedLastKnownLocation - myTransform.position; MoveTowards(direction.normalized, alertedSpeed); } else { } } }
using CareerCup150.Chapter19_Medium; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace CareerCupTest { /// <summary> ///This is a test class for _19_05_MasterMindTest and is intended ///to contain all _19_05_MasterMindTest Unit Tests ///</summary> [TestClass()] public class _19_05_MasterMindTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for Response ///</summary> [TestMethod()] public void ResponseTest() { _19_05_MasterMind target = new _19_05_MasterMind(); // TODO: Initialize to an appropriate value string real = "RGGB"; string guess = "YRGB"; string expected = "Hits " + "2" + ", PseudoHits " + "1" + "."; string actual; actual = target.Response(real, guess); Assert.AreEqual(expected, actual); } } }
namespace Voronov.Nsudotnet.BuildingCompanyIS.DBClasses { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("bcis.VehicleAttributes")] public partial class VehicleAttribute { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public VehicleAttribute() { VehicleCategoryAttributes = new HashSet<VehicleCategoryAttributes>(); } public int Id { get; set; } [Required] [StringLength(25)] public string Name { get; set; } [StringLength(5)] public string ValueType { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<VehicleCategoryAttributes> VehicleCategoryAttributes { get; set; } } }
using Learn.IRepository; using Learn.IService; using Learn.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Learn.Service { public class CommentService:BaseService<CommentInfo>,ICommentService { private readonly ICommentRepository _iCommentRespository; public CommentService(ICommentRepository iCommentRespository) { base._iBaseRepository = iCommentRespository; _iCommentRespository = iCommentRespository; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tes4._3_Tier.DTO; using Tes4._3_Tier.DAL; namespace Tes4._3_Tier.BUS { class billItem_BUS { private billItem_DAL bill_ItemDAL; public billItem_BUS() { bill_ItemDAL = new billItem_DAL(); bill_ItemDAL.InitializeDB(); } public void Insert(int billId, String name, String un, int quan,String use, float pr) { bill_ItemDAL.Insert(billId, name, un, quan, use,pr); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoreComponents.Items { public sealed class ImmutableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IToDictionary<TKey, TValue> { readonly TKey[] myKeys; readonly TValue[] myValues; readonly int myCount; readonly IEqualityComparer<TKey> myKeyComparer; readonly IEqualityComparer<TValue> myValueComparer; public ImmutableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { int count = dictionary.Count; TKey[] keys = new TKey[count]; TValue[] values = new TValue[count]; if(count > 0) { int i = 0; foreach(var item in dictionary) { keys[i] = item.Key; values[i] = item.Value; } } if(keyComparer != null) myKeyComparer = keyComparer; else myKeyComparer = EqualityComparer<TKey>.Default; if(valueComparer != null) myValueComparer = valueComparer; else myValueComparer = EqualityComparer<TValue>.Default; myCount = keys.Length; myKeys = keys; myValues = values; } public ImmutableDictionary(IEnumerable<KeyValuePair<TKey, TValue>> items, IEqualityComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { int count = items.Count(); TKey[] keys = new TKey[count]; TValue[] values = new TValue[count]; if(count > 0) { int i = 0; foreach(var item in items) { keys[i] = item.Key; values[i] = item.Value; } } if(keyComparer != null) myKeyComparer = keyComparer; else myKeyComparer = EqualityComparer<TKey>.Default; if(valueComparer != null) myValueComparer = valueComparer; else myValueComparer = EqualityComparer<TValue>.Default; myCount = keys.Length; myKeys = keys; myValues = values; } public TValue this[TKey key] { get { int index = -1; for(int i = 0; i < myCount; i++) { if(object.Equals(key, myKeys[i])) { index = i; } } if(index < 0) throw new Exception(); return myValues[index]; } set { throw new NotSupportedException(); } } public int Count { get { return myCount; } } public bool IsReadOnly { get { return true; } } public ICollection<TKey> Keys { get { return new SList<TKey>(myKeys); } } public ICollection<TValue> Values { get { return new SList<TValue>(myValues); } } [NotSupported] public void Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } [NotSupported] public void Add(TKey key, TValue value) { throw new NotSupportedException(); } [NotSupported] public void Clear() { throw new NotSupportedException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { TKey key = item.Key; for(int i = 0; i < myCount; i++) { if(myKeyComparer.Equals(key, myKeys[i])) { if(myValueComparer.Equals(myValues[i], item.Value)) return true; else return false; } } return false; } public bool ContainsKey(TKey key) { for(int i = 0; i < myCount; i++) { if(object.Equals(key, myKeys[i])) return true; } return false; } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { int index = 0; int maxIndex = myCount - 1; while(index < maxIndex) { yield return new KeyValuePair<TKey, TValue>(myKeys[index], myValues[index]); index++; } } [NotSupported] public bool Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(); } [NotSupported] public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, out TValue value) { int index = -1; for(int i = 0; i < myCount; i++) { if(myKeyComparer.Equals(key, myKeys[i])) { index = i; } } if(index < 0) { value = default(TValue); return false; } value = myValues[index]; return true; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IDictionary<TKey, TValue> ToDictionary() { return new SDictionary<TKey, TValue>(this); } public SDictionary<TKey, TValue> ToSDictionary() { return new SDictionary<TKey, TValue>(this); } } }
using System; using System.Threading; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using System.Collections; using System.Windows.Forms; namespace TankBot { public enum Status { IN_HANGAR, QUEUING, COUNT_DOWN, PLAYING, DIE, SHOW_BATTLE_RESULTS, RESTARTING }; public class TankBot { #region Singleton static private TankBot instance = null; static public TankBot getInstance() { if (instance == null) instance = new TankBot(); return instance; } #endregion private TankBot() { Helper.LogInfo("TankBot initialization"); if (!CheckSetting.checkSetting()) { Helper.LogInfo("check setting fail"); Environment.Exit(0); } status = Status.IN_HANGAR; for (int i = 0; i < allyTank.Length; i++) allyTank[i] = new Vehicle(); for (int i = 0; i < enemyTank.Length; i++) enemyTank[i] = new Vehicle(); } #region definition public bool focusTargetHappen; //information about battle/hangar private Status _status; public Status status { get { return _status; } set { Helper.LogInfo("status change to " + value); _status = value; } } public string mapName = ""; public Point startPos = new Point();// tank start position on minimap public Point enemyBase = new Point();// enemy base's location on minimap public Vehicle myTank = new Vehicle(); // my tank public Vehicle[] allyTank = new Vehicle[14]; // 14 ally tank public Vehicle[] enemyTank = new Vehicle[15]; // 15 enemy tank public List<Point> route = new List<Point>(); public int nextRoutePoint = 0; public string penetration = ""; public bool penetrationPossible { get { return penetration == "green" || penetration == "yellow" || penetration == "orange"; } } public bool focusTarget = false; public bool focusTargetUpdated; public double mapSacle = 100; // 100 meter per 1 box on minimap. public int timeLeft = 0; string debugMoveForwardCount; MapMining mapMining; public DateTime aimStartTime; private bool routeLoaded; /// <summary> /// this id would be better if it is user id. /// level_6 is first one with aiming scope /// change sniper level from 0--8 /// </summary> public double[] mouseHorizonRatio = new double[9]; // degree per pixel mouse move public double[] meterPerPixel = new double[9]; // on screen if the icon is 1 pixel away from center, the tank is ?? meter away from center(on same distance circle/panel) public double gDegreeDiff; public int cannot_move = 0; private Thread aAimingThread; private Thread aShootingThread; private Thread aMovingThread; #endregion public void Clear() { Helper.LogDebug("tankbot clear"); mapName = ""; startPos.Clear(); enemyBase.Clear(); myTank.Clear(); foreach (Vehicle v in allyTank) v.Clear(); foreach (Vehicle v in enemyTank) v.Clear(); route.Clear(); nextRoutePoint = 0; penetration = ""; SniperMode.sniper_level = 0; mapSacle = 100; focusTarget = false; timeLeft = 100; cannot_move = 0; routeLoaded = false; timeLeft = 0; } /// <summary> /// check focusTarget status /// and check other stuff /// and do the click /// </summary> private void shootingThread() { DateTime lastclick = DateTime.Now; while (true) { if (status != Status.PLAYING) break; if (focusTarget) { Helper.LogDebug("focusTargetHappen set to true"); focusTargetHappen = true; focusTarget = false; } Helper.LogDebug(" penetrationPossible " + penetrationPossible); Helper.LogDebug(" (DateTime.Now - aimStartTime).Seconds " + (DateTime.Now - aimStartTime).Seconds); if (penetrationPossible && myTank.speed == 0 && (DateTime.Now - aimStartTime).Seconds > 5) { if ((DateTime.Now - lastclick).Seconds > 0.1) { lastclick = DateTime.Now; Helper.leftClick(); } } Thread.Sleep(1); } } Aim aim; private void aimingThread() { Thread.Sleep(2000); SniperMode.resetSniperLevel(); aim = new Aim(); while (true) { try { aim.aim(); } catch { break; } } } double cntMoveForward = 0; TimeSpan timeMovingForward = new TimeSpan(); private void movingThread() { Move aMove = new Move(); try { while (true) { DateTime before = DateTime.Now; aMove.aMovePiece(); timeMovingForward += DateTime.Now - before; cntMoveForward++; debugMoveForwardCount = "MoveForward function call " + cntMoveForward / timeMovingForward.TotalSeconds + "/s totalCnt: " + cntMoveForward; } } catch { } } #region route public void genNextRoutePoint() { nextRoutePoint = 0; Trace.WriteLine("" + myTank.pos.x + " " + myTank.pos.y); for (int i = 0; i < route.Count; i++) { Point p = route[i]; if (TBMath.distance(route[i], myTank.pos) < TBMath.distance(route[nextRoutePoint], myTank.pos) ) nextRoutePoint = i; } double degree_diff = TBMath.vehicleDegreeToPoint(route[nextRoutePoint], myTank); if (Math.Abs(degree_diff) > 90) nextRoutePoint++; } public void loadRouteToFirePos() { Trajectory t = mapMining.genRouteToFireposTagMap(myTank.pos); route.Clear(); foreach (Point p in t) { route.Add(p); } genNextRoutePoint(); } public void loadRouteToEnemyBase() { Trajectory t = mapMining.genRouteTagMap(myTank.pos, enemyBase); route.Clear(); foreach (Point p in t) { route.Add(p); } genNextRoutePoint(); } /// <summary> /// this load should be execute when down counting, i.e. when we know all the information about my location, ally team member, enemy team member; /// because the fucking algorithm runs slow.... /// </summary> private void loadRoute() { Helper.LogInfo("load route map name: " + mapName); Helper.LogInfo("load route myTank.pos: " + myTank.pos); if (TBConst.notMoveTank) { Helper.LogInfo("load route returns as notMoveTank=true"); return; } if (this.routeLoaded) { Helper.LogInfo("load route returns already loaded"); return; } this.routeLoaded = true; while (this.mapName == "") Thread.Sleep(1000); while (myTank.pos.x == 6 && myTank.pos.y == 6) Thread.Sleep(1000); Thread.Sleep(3000); this.mapSacle = MapDef.map_size[mapName]; mapMining = new MapMining(this.mapName); this.enemyBase = mapMining.enemyBase(myTank.pos); //if (myTank.vInfo.vClass == VehicleClass.HT) //always use a fire route if (TBConst.cheatSlaveMode && CheatClient.getInstance().cheatMasterOnOtherSide()) loadRouteToFirePos(); else if (TBConst.cheatSlaveMode) loadRouteToEnemyBase(); else if (myTank.vInfo.tier <= 3) loadRouteToEnemyBase(); else loadRouteToEnemyBase(); // HT choose a more far away route //else // loadRouteToEnemyBase(); this.startPos = myTank.pos; } #endregion public int support() { double dis2enemy = TBMath.distance(myTank.pos, enemyBase); int rtn = 0; for (int i = 0; i < 14; i++) { if (allyTank[i].visible_on_minimap) { double dis = TBMath.distance(allyTank[i].pos, myTank.pos); if (dis > 2) continue; dis = TBMath.distance(allyTank[i].pos, enemyBase); if (dis < dis2enemy) rtn++; } } return rtn; } /// <summary> /// initial argument based on the sensitivity /// </summary> private void initArgsInBattle() { this.Clear(); //for(int i=0; i<8; i++) //generate_arguments(i); mouseHorizonRatio[0] = 0.0413449417970914; mouseHorizonRatio[1] = mouseHorizonRatio[0]; mouseHorizonRatio[2] = mouseHorizonRatio[0]; mouseHorizonRatio[3] = mouseHorizonRatio[0]; mouseHorizonRatio[4] = mouseHorizonRatio[0]; mouseHorizonRatio[5] = mouseHorizonRatio[0]; meterPerPixel[0] = 0.181995463740876; meterPerPixel[1] = 0.174721947322232; meterPerPixel[2] = 0.167231465529456; meterPerPixel[3] = 0.160001291946903; meterPerPixel[4] = 0.152397002754927; meterPerPixel[5] = 0.14801988592115; // this is hard code parameter mouseHorizonRatio[6] = 0.02103390909437; mouseHorizonRatio[7] = mouseHorizonRatio[6] / 2; mouseHorizonRatio[8] = mouseHorizonRatio[6] / 4; meterPerPixel[6] = 0.0690675193529361; // at 100 meter meterPerPixel[7] = meterPerPixel[6] / 2; meterPerPixel[8] = meterPerPixel[6] / 4; return; } public bool noAimMove() { if (TBConst.cheatSlaveMode && CheatClient.getInstance().cheatMasterOnOtherSide()) return true; return false; } public void abortThread() { Helper.LogInfo("TankBot abortThread"); try { aAimingThread.Abort(); } catch { } try { aShootingThread.Abort(); } catch { } try { aMovingThread.Abort(); } catch { } this.Clear(); } public void actionHangar() { this.Clear(); if (TBConst.cheatSlaveMode) { Thread.Sleep(1000); return ; } Helper.LogInfo("click tank for battle"); TankAction.moveCarouselLeft(); foreach (int p in TankAction.clickOrder()) { //Console.WriteLine("click the tank " + p); TankAction.clickTank(p); TankAction.clickStart(); } Thread.Sleep(20000); } public void actionCountDown() { Thread.Sleep(1000); if (timeLeft > 60) { status = Status.PLAYING; return; } Thread.Sleep(5000); this.Clear(); Thread.Sleep(5000); loadRoute(); while (true) { if (timeLeft > 100 || timeLeft < 1) { status = Status.PLAYING; Thread.Sleep(1000); break; } } } public void startThread() { Helper.LogInfo("---------TankBot startThread------------"); //wait for connection establish while (XvmComm.getInstance().messageCnt < 100) Thread.Sleep(1000); initArgsInBattle(); while (true) { if (status == Status.IN_HANGAR) { actionHangar(); } else if (status == Status.QUEUING || status == Status.COUNT_DOWN) { actionCountDown(); } else if (status == Status.PLAYING) { actionPlaying(); } else if (status == Status.DIE) { actionDie(); } else if (status == Status.SHOW_BATTLE_RESULTS) { actionShowBattleResult(); } Thread.Sleep(1000); } } private void actionShowBattleResult() { Helper.LogInfo("press esc to eliminate battle results"); Thread.Sleep(5000); //ESC Helper.bringToFront(); Helper.keyPress("b", Helper.KEY_TYPE.PRESS); Thread.Sleep(1000); status = Status.IN_HANGAR; } private void actionDie() { if (TBConst.cheatSlaveMode && CheatClient.getInstance().cheatMasterOnOtherSide()) { Helper.LogInfo("DIE and left click to change view"); Helper.leftClickSlow(); Thread.Sleep(5000); return; } TankAction.exitToHangar(); } private void actionPlaying() { if (!TBConst.noAim) { Helper.LogInfo("start aimingThread"); aAimingThread = new Thread(new ThreadStart(this.aimingThread)); aShootingThread = new Thread(new ThreadStart(shootingThread)); aAimingThread.Start(); aShootingThread.Start(); } if (!TBConst.notMoveTank) { loadRoute(); Helper.LogInfo("start movingThread"); aMovingThread = new Thread(new ThreadStart(this.movingThread)); aMovingThread.Start(); } if (!TBConst.noAim) { aShootingThread.Join(); Helper.LogInfo("join aAimingHelperThread"); aAimingThread.Join(); Helper.LogInfo("join aimingThread"); } if (!TBConst.notMoveTank) { aMovingThread.Join(); Helper.LogInfo("join movingThread"); } } internal string debugString() { string str = ""; str += "\r\n" + debugMoveForwardCount; str += "\r\n" + "focusTargetUpdated: " + focusTargetUpdated; str += "\r\n" + "map_scale: " + mapSacle; str += "\r\n" + "support: " + support(); str += "\r\n" + "cannot_move: " + cannot_move; str += "\r\n" + "g_degree_diff: " + gDegreeDiff; str += "\r\n" + "Sniper Level: " + SniperMode.sniper_level; str += "\r\n" + "Status: " + status; str += "\r\n" + "Mytank Name: " + myTank.tankName + " " + myTank.vInfo.tier + " " + myTank.vInfo.vClass; str += "\r\n" + "Health: " + myTank.health; str += "\r\n" + "Speed: " + myTank.speed; str += "\r\n" + "Focus: " + focusTarget; str += "\r\n" + "time_left: " + timeLeft; if(aim!=null) str += aim.debugString(); return str; } } }
// ObjectBase.cs - Base class for Object types // // Authors: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2005 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program 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, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.Xml; public abstract class ObjectBase : HandleBase { protected ObjectBase (XmlElement ns, XmlElement elem) : base (ns, elem) {} public override string FromNative (string var, bool owned) { return "GLib.Object.GetObject(" + var + (owned ? ", true" : "") + ") as " + QualifiedName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.DataAnnotations; namespace SMSEntities.SMSDBEntities { public class Vehicles { //`identificationunit``platenumber``containernumber``description` //`trailernumber``contractor``length``capacity``securityguardname``authpersonic``authpersonname``imagepath` public int vehicleid { get; set; } public string identificationunit { get; set; } public string platenumber { get; set; } public string containernumber { get; set; } public string description { get; set; } public string trailernumber { get; set; } public string contractor { get; set; } public string length { get; set; } public string capacity { get; set; } public string securityguardname { get; set; } public string authpersonic { get; set; } public string authpersonname { get; set; } public string imagepath { get; set; } public int deploymentid { get; set; } public int vehicletypeid { get; set; } public string vehicletype { get; set; } //public int LocationId { get; set; } public string LocationName { get; set; } public string purpose { get; set; } public List<VehicleTypes> VehicleTypesList { get; set; } public List<Purpose> PurposeList { get; set; } //public List<Location> LocationList { get; set; } } }
 #region License // Copyright (c) 2007, James M. Curran // // 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. #endregion #region References using System; using System.Collections.Generic; using System.Text; using Castle.MonoRail.Framework; #endregion namespace Castle.MonoRail.ViewComponents { /// <summary> /// ViewComponent to build one item of a Frequently Asked Questions list. /// The generated markup displays the question, and using DHTML, displays &amp; hides /// the answer when the question text is clicked. /// </summary> /// <remarks><para> /// FaqItemComponent is one of two different components for creating FAQ pages. /// </para><para> /// It is intended for it format FAQ entries where the text in hard-coded in the view. /// To format FAQ entries where the text is comes from an external data source, see <seealso cref="FaqListComponent"/>. /// </para><para> /// FaqItem is a block component which has two required sections, /// <c>"question"</c> and <c>"answer"</c>, and four optional parameters. /// </para> /// <list type="table"> /// <listheader> /// <term>Section</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> #question </term> /// <description> /// /// Contains the text of a Frequently asked question. The text is /// always displayed on the page. Clicking this text will display the answer. /// /// /// </description> /// </item> /// <item> /// <term> #answer </term> /// <description> /// /// Contains the text of the answer to the FAQ. The text is initially hidden, /// and only displayed when the question is clicked. /// /// </description> /// </item> /// </list> /// <list type="table"> /// <listheader> /// <term>Parameter</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> QuestionCssClass </term> /// <description> /// /// CSS Class used for the DIV block holding the question. /// (Default: <b>Question</b>) /// /// </description> /// </item> /// <item> /// <term> AnswerCssClass </term> /// <description> /// /// CSS Class used for the DIV block holding the answer. /// (Default: <b>Answer</b>)</description> /// /// </item> /// <item> /// <term> WrapItems </term> /// <description> /// /// If set to "true", each question/answer block will be wrapped in a LI tags, /// so that a series of FaqItemComponents can be made a ordered (OL) or unordered (UL) list. /// (Default:<b>False</b>) /// /// </description> /// </item> /// <item> /// <term> Sticky </term> /// <description> /// /// If set to "True", the values given for the other parameters will be used for all /// subsequent FaqItemComponents on this page. If <i>explicitly</i> set to "False", /// previously save values are forgotten.(Default:<b>False</b>)</description> /// /// </item> /// </list> /// /// <b>NOTE:</b> This ViewComponent makes use of the prototype.js javascript librar by way of the JavascriptHelper object /// requires the following line appears in either the view which FaqItemComponent is used, or the layout /// template used by that view: /// <code> /// $AjaxHelper.GetJavascriptFunctions() /// </code> /// /// Copyright &#169; 2007, James M. Curran <br/> /// Licensed under the Apache License, Version 2.0 /// </remarks> /// <example> /// <code><![CDATA[ /// #blockcomponent (FaqItemComponent) /// #question /// Is MonoRail stable? Why it's not 1.0? /// #end /// /// #answer /// Yes, very stable, albeit there's always room for improvements. /// Check our issue tracker. /// /// We are not 1.0 because there are important features not /// implemented yet, like Caching and Logging support. /// #end /// #end /// ]]></code> /// will generate the following markup: /// <code><![CDATA[ /// <div id="Faq_Q1" onclick="Element.toggle('Faq_A1')" class="Question"> /// Is MonoRail stable? Why it's not 1.0? /// </div> /// <div id="Faq_A1" style="display:none" class="Answer"> /// <br/> /// Yes, very stable, albeit there's always room for improvements. /// Check our issue tracker. /// /// We are not 1.0 because there are important features not /// implemented yet, like Caching and Logging support. /// <hr/> /// </div> /// ]]></code> /// /// </example> [ViewComponentDetails("FaqItem", Sections="Question,Answer")] public class FaqItemComponent : ViewComponentEx { #region Private Variables private int? faqNum; private string questionCssClass; private string answerCssClass; private bool wrapItems; private string jsLibrary; #endregion /// <summary> /// Initializes a new instance of the FaqItemComponent class. /// </summary> public FaqItemComponent() { } /// <summary> /// Initializes this instance. /// </summary> public override void Initialize() { base.Initialize(); // FaqNum is used to assure that the ids used for the Question & Answer DIV blocks // are unique across a page, which is expected to have multiple FaqItemComponents. faqNum = (int?) Context.ContextVars["FaqNum"]; if (!faqNum.HasValue) faqNum = 0; faqNum++; Context.ContextVars["FaqNum"] = faqNum; // First retrieve saved "sticky" parameters, if any, or set defaults if not. questionCssClass = Context.ContextVars["QuestionCssClass"] as string ?? "Question"; answerCssClass = Context.ContextVars["AnswerCssClass"] as string ?? "Answer"; string strWrap = Context.ContextVars["WrapItems"] as string ?? "false"; jsLibrary = Context.ContextVars["JSLibrary"] as string ?? "proto"; questionCssClass = Context.ComponentParameters["QuestionCssClass"] as string ?? questionCssClass; answerCssClass = Context.ComponentParameters["AnswerCssClass"] as string ?? answerCssClass; jsLibrary = Context.ComponentParameters["JSLibrary"] as string ?? jsLibrary; strWrap = Context.ComponentParameters["WrapItems"] as string ?? strWrap; if (!Boolean.TryParse(strWrap, out wrapItems)) wrapItems = false; string strSticky = Context.ComponentParameters["Sticky"] as string; bool sticky = false; if (strSticky != null && Boolean.TryParse(strSticky, out sticky)) { if (sticky) { // If "Sticky" is given, and it's parsable, // and it's value is True, save values Context.ContextVars["QuestionCssClass"] = questionCssClass; Context.ContextVars["AnswerCssClass"] = answerCssClass; Context.ContextVars["JSLibrary"] = jsLibrary; Context.ContextVars["WrapItems"] = strWrap; } else { // If "Sticky" is given, and it's parsable, // and it's value is False, remove saved values Context.ContextVars.Remove("QuestionCssClass"); Context.ContextVars.Remove("AnswerCssClass"); Context.ContextVars.Remove("WrapItems"); Context.ContextVars.Remove("JSLibrary"); } } } /// <summary> /// Renders this instance. /// </summary> public override void Render() { ConfirmSectionPresent("question"); ConfirmSectionPresent("answer"); string question = GetSectionText("question"); string answer = GetSectionText("answer"); FaqParameters param = new FaqParameters(); param.AnswerCssClass = answerCssClass; param.QuestionCssClass = questionCssClass; param.Number = faqNum.Value; param.WrapItems = wrapItems; param.jsLibrary = Enum.IsDefined(typeof(Library), jsLibrary.ToLowerInvariant()) ? (Library) Enum.Parse(typeof(Library), jsLibrary.ToLowerInvariant()) : Library.proto; param.helper = new JavascriptHelper(Context, EngineContext, "FaqItemComponent"); switch (param.jsLibrary) { case Library.proto: param.helper.IncludeStandardScripts("Ajax"); break; case Library.jquery: param.helper.IncludeStandardScripts("jQuery"); break; } RenderText(FaqItemHelper.BuildItem(question, answer, param)); CancelView(); } } /// <summary> /// Simple class to hold a Question &amp; Answer pair. /// </summary> /// <remarks> /// <list type="table"> /// <listheader> /// <term>Section</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> Question </term> /// <description> /// /// Contains the text of a Frequently asked question. The text is /// always displayed on the page. Clicking this text will display the answer. /// /// /// </description> /// </item> /// <item> /// <term> Answer </term> /// <description> /// /// Contains the text of the answer to the FAQ. The text is initially hidden, /// and only displayed when the question is clicked. /// /// </description> /// </item> /// </list> /// </remarks> public class QnA { /// <summary> /// Holds the text of the Question. /// </summary> public string Question; // { get; set; } /// <summary> /// Holds the text of the Answer. /// </summary> public string Answer; // { get; set; } /// <summary> /// Initializes a new instance of the QnA class. /// </summary> /// <param name="question">Text of the Question</param> /// <param name="answer">Text of the Answer</param> public QnA(string question, string answer) { Question = question; Answer = answer; } /// <summary> /// Initializes a new instance of the QnA class. /// </summary> public QnA() { } } /// <summary> /// ViewComponent to build a list of Frequently Asked Questions. /// The generated markup displays the question, and using DHTML, displays &amp; hides /// the answer when the question text is clicked. /// </summary> /// <remarks><para> /// FaqItemComponent is one of two different components for creating FAQ pages. /// </para><para> /// It is intended to format FAQ entries where the text is comes from an external data source. <br/> /// To format FAQ entries where the text in hard-coded in the view, see <seealso cref="FaqItemComponent"/>. /// </para><para> /// FaqItem is a line component which has no subsections, one required and three optional parameters. /// </para> /// <list type="table"> /// <listheader> /// <term>Parameter</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> Elements </term> /// <description> /// /// An IEnumerable collection of <see cref="QnA"/> objects, holding the /// text of the FAQs to display. (Required, no default) /// /// </description> /// </item> /// <item> /// <term> QuestionCssClass </term> /// <description> /// /// CSS Class used for the DIV block holding the question. /// (Default: <b>Question</b>) /// /// </description> /// </item> /// <item> /// <term> AnswerCssClass </term> /// <description> /// /// CSS Class used for the DIV block holding the answer. /// (Default: <b>Answer</b>)</description> /// /// </item> /// <item> /// <term> ListType </term> /// <description> /// Indicates how the items should be formatted into alist. /// Must be one of values in the table below. (Default: <b>None</b>) /// /// </description> /// </item> /// </list> /// /// <list type="table"> /// <listheader> /// <term>ListType</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> None </term> /// <description> /// /// Items are rendered without any form of list structure. /// /// </description> /// </item> /// <item> /// <term> Ordered </term> /// <description> /// /// Items are numbered. ("OL" and "Numbered" are acceptable alternatives) /// /// </description> /// </item> /// <item> /// <term> Unordered </term> /// <description> /// /// Items are bulleted. ("UL" and "bullet" are acceptable alternatives) /// /// </description> /// </item> /// </list> /// <b>NOTE:</b> This ViewComponent makes use of the prototype.js javascript library, and therefore /// requires the following line appears in either the view which FaqItemComponent is used, or the layout /// template used by that view: /// <code> /// $AjaxHelper.GetJavascriptFunctions() /// </code> /// /// Copyright &#169; 2007, James M. Curran <br/> /// Licensed under the Apache License, Version 2.0 /// </remarks> /// <example><code><![CDATA[ /// #component (FaqListComponent with "Elements=$faqItems") /// ]]></code> /// See <see cref="FaqItemComponent"/> for example of markup generated. /// </example> public class FaqListComponent : ViewComponent { #region Private fields IEnumerable<QnA> faqList; String ListTag; FaqParameters param; #endregion #region Overridden Methods /// <summary> /// Called by the framework once the component instance /// is initialized /// </summary> public override void Initialize() { base.Initialize(); faqList = Context.ComponentParameters["elements"] as IEnumerable<QnA>; if (faqList == null) throw new ViewComponentException("FaqListComponent: required 'elements' parameter missing or empty."); param = new FaqParameters(); param.QuestionCssClass = Context.ComponentParameters["QuestionCssClass"] as string ?? "Question"; param.AnswerCssClass = Context.ComponentParameters["AnswerCssClass"] as string ?? "Answer"; param.helper = new JavascriptHelper(Context, EngineContext,"FaqListComponent"); param.helper.IncludeStandardScripts("Ajax"); string listType = Context.ComponentParameters["ListType"] as string ?? "none"; switch (listType.ToLower()) { case "none": param.WrapItems = false; ListTag = ""; break; case "ordered": case "numbered": case "ol": param.WrapItems = true; ListTag = "ol"; break; case "unordered": case "ul": case "bullet": param.WrapItems = true; ListTag = "ul"; break; default: throw new ViewComponentException("FaqListComponent: '"+listType+"' is not a acceptable ListType"); } } /// <summary> /// Called by the framework so the component can /// render its content /// </summary> public override void Render() { base.Render(); if (ListTag.Length > 0) RenderText("<" + ListTag + ">" + Environment.NewLine); foreach (QnA faq in faqList) { param.Number++; RenderText(FaqItemHelper.BuildItem(faq.Question, faq.Answer, param)); } if (ListTag.Length > 0) RenderText("</" + ListTag + ">" + Environment.NewLine); Context.ContextVars["FaqNum"] = new int?(param.Number); CancelView(); } #endregion } internal enum Library { proto, jquery}; /// <summary> /// Private class used to pass around parameter easily. /// </summary> internal class FaqParameters { public int Number; public string QuestionCssClass; public string AnswerCssClass; public bool WrapItems; public JavascriptHelper helper; public Library jsLibrary; } /// <summary> /// Private class to do the really work of FaqItemComponent &amp; FaqListComponent. /// </summary> internal static class FaqItemHelper { /// <summary> /// Builds the item. /// </summary> /// <remarks> This attempts to always "do the right thing", hence, if javascript is enabled, /// the answer is hidden, and clicking the question reveals it. However, if Javascript is disabled, /// that won't work, so the answer must always be display. But, at rendering time, we have no way of knowing /// if Javascript is enabled or not, and, when displayed in the browser, we cannot define a "no scripting" /// contingency option in Javascript, since it won't be run. /// To solve this, the answer is initially displayed, /// and then immediately hidden (via Javascript). If JS is enabled, the text is hidden before it is displayed, /// so the user never sees it. /// </remarks> /// <param name="question">The question.</param> /// <param name="answer">The answer.</param> /// <param name="param">The param.</param> /// <returns>The Html generated for this FAQ item.</returns> public static string BuildItem(string question, string answer, FaqParameters param) { string divFormat; string hideFormat; switch (param.jsLibrary) { case Library.proto: default: param.helper.IncludeStandardScripts("Ajax"); divFormat = @"<div id=""Faq_Q{0}"" onclick=""Element.toggle('Faq_A{0}')"" class=""{1}"">"; // hideFormat = @"<script>$(Faq_A{0}).style.display='none';</script>"; hideFormat = @"$(Faq_A{0}).style.display='none';"; break; case Library.jquery: param.helper.IncludeStandardScripts("jQuery"); divFormat = @"<div id=""Faq_Q{0}"" onclick=""jQuery('#Faq_A{0}').slideToggle()"" class=""{1}"">"; // hideFormat = @"<script>jQuery('#Faq_A{0}').hide();</script>"; hideFormat = "jQuery('#Faq_A{0}').hide();"; break; } StringBuilder sb = new StringBuilder(250); if (param.WrapItems) sb.Append("<li>"); sb.AppendFormat(divFormat, param.Number, param.QuestionCssClass); sb.Append(Environment.NewLine); sb.Append(question); sb.Append("</div>"); sb.Append(Environment.NewLine); sb.AppendFormat(@"<div id=""Faq_A{0}"" class=""{1}"">", param.Number, param.AnswerCssClass); sb.Append(Environment.NewLine); // sb.Append("<br/>"); sb.Append(answer); sb.Append("<hr/>"); sb.Append("</div>"); sb.Append(Environment.NewLine); if (param.WrapItems) sb.Append("</li>"); sb.Append(Environment.NewLine); // sb.AppendFormat(hideFormat, param.Number); // sb.Append(Environment.NewLine); param.helper.InsertSeparateText(string.Format(hideFormat, param.Number)); return sb.ToString(); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; using DotNetNuke.Framework; using DotNetNuke.Common.Lists; using DotNetNuke.Entities.Profile; using System.Linq; namespace DotNetNuke.Services.Registration { public class RegistrationProfileController : ServiceLocator<IRegistrationProfileController, RegistrationProfileController>, IRegistrationProfileController { public IEnumerable<string> Search(int portalId, string searchTerm) { var controller = new ListController(); ListEntryInfo imageType = controller.GetListEntryInfo("DataType", "Image"); List<string> results = new List<string>(); foreach (var definition in ProfileController.GetPropertyDefinitionsByPortal(portalId) .Cast<ProfilePropertyDefinition>() .Where(definition => definition.DataType != imageType.EntryID)) { AddProperty(results, definition.PropertyName, searchTerm); } AddProperty(results, "Email", searchTerm); AddProperty(results, "DisplayName", searchTerm); AddProperty(results, "Username", searchTerm); AddProperty(results, "Password", searchTerm); AddProperty(results, "PasswordConfirm", searchTerm); AddProperty(results, "PasswordQuestion", searchTerm); AddProperty(results, "PasswordAnswer", searchTerm); return results; } private void AddProperty(List<string> results, string field, string searchTerm) { if (field.ToLowerInvariant().Contains(searchTerm.ToLowerInvariant().Trim())) { results.Add(field); } } protected override Func<IRegistrationProfileController> GetFactory() { return () => new RegistrationProfileController(); } } }
using EsMo.iOS.WeiBo.Entity; using EsMo.Sina.SDK.Model; using Foundation; using MvvmCross.Binding.BindingContext; using MvvmCross.iOS.Views; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace EsMo.iOS.WeiBo.Entity { public class BaseView<T> : MvxViewController<T> where T:BaseViewModel { public BaseView() { } public BaseView(string nibName, NSBundle bundle):base(nibName,bundle) { } public override void ViewDidLoad() { base.ViewDidLoad(); this.CreateBinding<MvxViewController>(this).For(x=>x.Title).To<BaseViewModel>(x => x.Title).Apply(); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); this.ViewModel.Appearing(); } } }
using System; using System.Web.Mvc; namespace ZiZhuJY.Web.UI.Utility { public class MvcUtility { public static void ProcessInvalidModelState(ModelStateDictionary modelState) { foreach (ModelState ms in modelState.Values) { foreach (ModelError err in ms.Errors) { if (err.Exception != null) { throw err.Exception; } else { throw new Exception(err.ErrorMessage); } } } } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("BackButton")] public class BackButton : PegUIElement { public BackButton(IntPtr address) : this(address, "BackButton") { } public BackButton(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void OnOut(PegUIElement.InteractionState oldState) { object[] objArray1 = new object[] { oldState }; base.method_8("OnOut", objArray1); } public void OnOver(PegUIElement.InteractionState oldState) { object[] objArray1 = new object[] { oldState }; base.method_8("OnOver", objArray1); } public void OnPress() { base.method_8("OnPress", Array.Empty<object>()); } public void OnRelease() { base.method_8("OnRelease", Array.Empty<object>()); } public UberText m_backText { get { return base.method_3<UberText>("m_backText"); } } public GameObject m_highlight { get { return base.method_3<GameObject>("m_highlight"); } } } }
 namespace KRF.Core.Entities.AccessControl { public class Role { /// <summary> /// Hold the unique Identifier of a particular role /// </summary> public int RoleId { get; set; } /// <summary> /// Holds the name of a role. /// </summary> public string RoleName { get; set; } public bool Active { get; set; } } }
using System.Threading; using System.Threading.Tasks; using Grimoire.Game; using Grimoire.Game.Data; namespace Grimoire.Botting.Commands.Combat { public class CmdKill : IBotCommand { public string Monster { get; set; } public async Task Execute(IBotEngine instance) { await instance.WaitUntil(() => World.IsMonsterAvailable(Monster), null, 3); if (instance.Configuration.WaitForSkills) await instance.WaitUntil(() => Player.AllSkillsAvailable); if (!instance.IsRunning || !Player.IsAlive || !Player.IsLoggedIn) return; Player.AttackMonster(Monster); if (instance.Configuration.Skills.Count > 0) Task.Run(() => UseSkills(instance)); await instance.WaitUntil(() => !Player.HasTarget, null, 360); Player.CancelTarget(); _cts?.Cancel(false); } private CancellationTokenSource _cts; private int _skillIndex; private async Task UseSkills(IBotEngine instance) { _cts = new CancellationTokenSource(); _skillIndex = 0; while (!_cts.IsCancellationRequested && Player.IsLoggedIn && Player.IsAlive) { Skill s = instance.Configuration.Skills[_skillIndex]; if (s.Type == Skill.SkillType.Safe) { if (s.SafeMp) { if ((double) Player.Mana / Player.ManaMax * 100 <= s.SafeHealth) Player.UseSkill(s.Index); } else { if ((double)Player.Health / Player.HealthMax * 100 <= s.SafeHealth) Player.UseSkill(s.Index); } } else { Player.UseSkill(s.Index); } int count = instance.Configuration.Skills.Count - 1; _skillIndex = _skillIndex >= count ? 0 : ++_skillIndex; await Task.Delay(instance.Configuration.SkillDelay); } } public override string ToString() { return $"Kill {Monster}"; } } }
namespace VH.Core.Middleware.UnitTests.TestEntities { public class LoggingTestChildEntity { public string AdminUri { get; set; } public string JudgeUri { get; set; } public string ParticipantUri { get; set; } public string PexipNode { get; set; } public string TelephoneConferenceId { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace eLearning.Domain { public class Professor : BaseClass { public Professor() { Subjects = new List<Subject>(); } public string FirstName { get; set; } public string LastName { get; set; } [NotMapped] /// Employee's full name - not mapped - calculated public string FullName { get { return FirstName + " " + LastName; } } public string Email { get; set; } public string Phone { get; set; } public DateTime Birthday { get; set; } public string Faculty { get; set; } public string AboutMe { get; set; } public virtual IList<Subject> Subjects { get; set; } } }
using System; class Massiiv5{ static void Tryki(int[] mas){ for(int i=0; i<mas.Length; i++){ Console.WriteLine(mas[i]); } Console.WriteLine(); } public static void Main(string[] arg){ int[] m=new int[3]{40, 48, 33}; int[] m2=m; //Viide samale massiivile Tryki(m2); m[1]=32; Tryki(m2); int[] m3=(int[])m.Clone(); //Andmete koopia m[1]=20; Tryki(m3); Array.Clear(m3, 0, m3.Length); //Tühjendus Tryki(m3); Console.WriteLine(Array.IndexOf(m,33)); Console.WriteLine(Array.IndexOf(m,17)); //puuduv element } }
using System; using System.Collections.Generic; using TP_Groupe.Models; namespace TP_Groupe.Repository { public interface ISecteurRepository { void Insert(Secteur secteur); void Update(Secteur secteur); void Remove(Secteur secteur); IEnumerable<Secteur> GetAllSecteurs(); Secteur GetById(int Id); } }
/******************************************************************** * 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; namespace Framework.Metadata { using System.Collections.Generic; using Utils; public class CxEntityCustomizerLocalization { //------------------------------------------------------------------------- private CxEntityCustomizer m_Customizer; private Dictionary<string, string> m_LanguageSingleCaptionMap = new Dictionary<string, string>(); private Dictionary<string, string> m_LanguagePluralCaptionMap = new Dictionary<string, string>(); //------------------------------------------------------------------------- public Dictionary<string, string> LanguageSingleCaptionMap { get { return m_LanguageSingleCaptionMap; } set { m_LanguageSingleCaptionMap = value; } } //------------------------------------------------------------------------- public Dictionary<string, string> LanguagePluralCaptionMap { get { return m_LanguagePluralCaptionMap; } set { m_LanguagePluralCaptionMap = value; } } //------------------------------------------------------------------------- /// <summary> /// The customizer the data belongs to. /// </summary> public CxEntityCustomizer Customizer { get { return m_Customizer; } set { m_Customizer = value; } } //------------------------------------------------------------------------- public string NonLocalizedPluralCaption { get { return Customizer.Metadata.GetInitialProperty("plural_caption", false); } } //------------------------------------------------------------------------- public string CustomPluralCaption { get { if (!LanguagePluralCaptionMap.ContainsKey(Customizer.Context.CurrentLanguageCd)) Customizer.InitializeForLanguage(Customizer.Context.CurrentLanguageCd); return LanguagePluralCaptionMap[Customizer.Context.CurrentLanguageCd]; } set { LanguagePluralCaptionMap[Customizer.Context.CurrentLanguageCd] = value; } } //------------------------------------------------------------------------- public string NonLocalizedSingleCaption { get { return Customizer.Metadata.GetInitialProperty("single_caption", false); } } //------------------------------------------------------------------------- public string CustomSingleCaption { get { if (!LanguageSingleCaptionMap.ContainsKey(Customizer.Context.CurrentLanguageCd)) Customizer.InitializeForLanguage(Customizer.Context.CurrentLanguageCd); return LanguageSingleCaptionMap[Customizer.Context.CurrentLanguageCd]; } set { LanguageSingleCaptionMap[Customizer.Context.CurrentLanguageCd] = value; } } //------------------------------------------------------------------------- /// <summary> /// Ctor. /// </summary> /// <param name="customizer">the customizer object the data belongs to</param> public CxEntityCustomizerLocalization(CxEntityCustomizer customizer) { Customizer = customizer; } //------------------------------------------------------------------------- /// <summary> /// Compares the data with another. /// </summary> /// <param name="otherData">the object to compare with</param> /// <returns>true if equal</returns> public bool Compare(CxEntityCustomizerLocalization otherData) { bool result = CxCustomizationUtils.CompareLanguageDictionaries( LanguageSingleCaptionMap, otherData.LanguageSingleCaptionMap) && CxCustomizationUtils.CompareLanguageDictionaries( LanguagePluralCaptionMap, otherData.LanguagePluralCaptionMap); return result; } //------------------------------------------------------------------------- /// <summary> /// Clones the data object. /// </summary> /// <returns>the clone created</returns> public CxEntityCustomizerLocalization Clone() { CxEntityCustomizerLocalization clone = new CxEntityCustomizerLocalization(Customizer); clone.LanguageSingleCaptionMap = CxDictionary.CreateDictionary(new List<string>(LanguageSingleCaptionMap.Keys), new List<string>(LanguageSingleCaptionMap.Values)); clone.LanguagePluralCaptionMap = CxDictionary.CreateDictionary(new List<string>(LanguagePluralCaptionMap.Keys), new List<string>(LanguagePluralCaptionMap.Values)); return clone; } //------------------------------------------------------------------------- public bool GetIsInitializedForLanguage(string languageCd) { return (LanguagePluralCaptionMap.ContainsKey(languageCd)); } //------------------------------------------------------------------------- public void InitializeForLanguage(string languageCd) { if (string.IsNullOrEmpty(languageCd) || GetIsInitializedForLanguage(languageCd)) return; LanguageSingleCaptionMap[languageCd] = Customizer.Metadata.Holder.Multilanguage.GetLocalizedValue( languageCd, CxEntityUsageMetadata.LOCALIZATION_OBJECT_TYPE_CODE, "single_caption", Customizer.Metadata.Id, NonLocalizedSingleCaption) ?? NonLocalizedSingleCaption; LanguagePluralCaptionMap[languageCd] = Customizer.Metadata.Holder.Multilanguage.GetLocalizedValue( languageCd, CxEntityUsageMetadata.LOCALIZATION_OBJECT_TYPE_CODE, "plural_caption", Customizer.Metadata.Id, NonLocalizedPluralCaption) ?? NonLocalizedPluralCaption; } //------------------------------------------------------------------------- } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace DAL { public class DAL_BAN { Thaotac_CSDL thaotac = new Thaotac_CSDL(); //khai báo 2 mảng để truyền tên tham số và giá trị tham số vào Stored Procedures string[] name = { }; object[] value = { }; //phương thức này gọi phương thức SQL_Laydulieu ở lớp ThaoTac_CoSoDuLieu để thực hiện lấy dữ liệu public DataTable BAN_select() { //thaotac.KetnoiCSDL(); return thaotac.SQL_Laydulieu("BAN_Select"); } public DataTable BAN_select_where(string maban) { name = new string[1]; value = new object[1]; name[0] = "@MaBan"; value[0] = maban; return thaotac.SQL_Laydulieu_CoDK("BAN_Select_where", name, value, 1); } //phương thức này gọi phương thức SQL_Thuchien ở lớp ThaoTac_CoSoDuLieu để thực hiện insert public int BAN_insert(string maban, string tenban, string ghichu) { //thaotac.KetnoiCSDL(); name = new string[3]; value = new object[3]; name[0] = "@MaBan"; value[0] = maban;//@,... là các tham số phải giống với tham số khai báo ở Stores Procedures trong CSDL name[1] = "@TenBan"; value[1] = tenban; name[2] = "@GhiChu"; value[2] = ghichu; return thaotac.SQL_Thuchien("BAN_Insert", name, value, 3); } //phương thức này gọi phương thức SQL_Thuchien ở lớp ThaoTac_CoSoDuLieu để thực hiện update public int BAN_update(string maban,string tenban, string ghichu) { name = new string[3]; value = new object[3]; name[0] = "@MaBan"; value[0] = maban; name[1] = "@TenBan"; value[1] = tenban; name[2] = "@GhiChu"; value[2] = ghichu; return thaotac.SQL_Thuchien("BAN_Update", name, value, 3); } //phương thức này gọi phương thức SQL_Thuchien ở lớp ThaoTac_CoSoDuLieu để thực hiện delete public int BAN_delete(string maban) { name = new string[1]; value = new object[1]; name[0] = "@MaBan"; value[0] = maban; return thaotac.SQL_Thuchien("BAN_Delete", name, value, 1); } } }
 using MKService.Messages; using MKService.ModelUpdaters; using MKService.Queries; using MKService.Updates; namespace MKService.MessageHandlers { internal class UserCollectionAddedHandler : ServerMessageHandlerBase<UserCollectionAdd, UserCollectionQuery, IUpdatableUserCollection> { public UserCollectionAddedHandler(IModelUpdaterResolver modelUpdaterResolver) : base(modelUpdaterResolver) { } protected override IUpdatableUserCollection LocateQueryComponent(UserCollectionAdd message, UserCollectionQuery query) { return query; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AirCaddy.Data.Repositories { public interface IUserRepository { string GetUserIdFromUsername(string username); string GetUsernameFromUserId(string id); } public class UserRepository : BaseRepository, IUserRepository { public UserRepository() : base() { } public string GetUserIdFromUsername(string username) { var user = _dataEntities.AspNetUsers.FirstOrDefault(u => u.UserName.Contains(username)); return user.Id; } public string GetUsernameFromUserId(string id) { var user = _dataEntities.AspNetUsers.FirstOrDefault(u => u.Id.Contains(id)); return user.UserName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; namespace cMud2 { public class FullmeTextProcessor { public string Message { get; set; } public bool IsNeedGetNextMessage { get; set; } public void ProcessText(string text) { Regex regex = new Regex(@"http://mud.pkuxkx.net/antirobot/robot.php\?filename=\d+"); Match m = regex.Match(text); if (m.Length > 1) { App.Current.Dispatcher.BeginInvoke(new Action(() => { ShowRobotWindow(m.Value); })); } } private void ShowRobotWindow(string uri) { Window win = new Window(); win.Topmost = true; WebBrowser web = new WebBrowser(); win.Content = web; web.Navigate(uri); win.Show(); } } }
using LuaInterface; using System; namespace SLua { public abstract class LuaVar : IDisposable { protected LuaState state; protected int valueref; public IntPtr L { get { return this.state.L; } } public int Ref { get { return this.valueref; } } public LuaVar() { this.state = null; } public LuaVar(LuaState l, int r) { this.state = l; this.valueref = r; } public LuaVar(IntPtr l, int r) { this.state = LuaState.get(l); this.valueref = r; } ~LuaVar() { this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } public virtual void Dispose(bool disposeManagedResources) { if (this.valueref != 0) { LuaState.UnRefAction act = delegate(IntPtr l, int r) { LuaDLL.lua_unref(l, r); }; this.state.gcRef(act, this.valueref); this.valueref = 0; } } public void push(IntPtr l) { LuaDLL.lua_getref(l, this.valueref); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { return obj is LuaVar && this == (LuaVar)obj; } private static int Equals(LuaVar x, LuaVar y) { x.push(x.L); y.push(x.L); int result = LuaDLL.lua_equal(x.L, -1, -2); LuaDLL.lua_pop(x.L, 2); return result; } public static bool operator ==(LuaVar x, LuaVar y) { if (x == null || y == null) { return x == y; } return LuaVar.Equals(x, y) == 1; } public static bool operator !=(LuaVar x, LuaVar y) { if (x == null || y == null) { return x != y; } return LuaVar.Equals(x, y) != 1; } } }
namespace ns20 { using System; internal class Class162 { protected internal object object_0; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Washing_Machine { class GUI { //attributes private string turnedOn, hatchSecured; //for translation from bool too Strings private int selectInGui; //for your selection on washing public string TurnedOn { get { return this.turnedOn; } set { this.turnedOn = value; } } public string HatchSecured { get { return this.hatchSecured; } set { this.hatchSecured = value; } } Washer washer = new Washer(false, false, true); public void Translate() { //make sure it isnt true or false, in the console.writelines if (washer.OnOff == true) { turnedOn = "off"; } else if(washer.OnOff == false) { turnedOn = "on"; } if (washer.HatchClosed == true) { hatchSecured = "Open"; } else { hatchSecured = "Close"; } } public void guiForWasher() { //a default value on startup washer.SelectProgram(0); while (true) { Console.Clear(); washer.TurnedOffValuesSet(); Translate(); Console.WriteLine("1. Turn " + turnedOn + " | Program: " + washer.WashProgram[0]); Console.WriteLine("2. Start Program |"); Console.WriteLine("3. Basic Wash | Estimated time: " + washer.WashProgram[1] + " Seconds"); Console.WriteLine("4. Eco Wash | Estimated Water intake:" + washer.WashProgram[2]); Console.WriteLine("5. Quick Wash | Estimated Water Temperature: " + washer.WashProgram[3] + "°"); Console.WriteLine("6. Heavy Wash |"); Console.WriteLine("7. " + hatchSecured + " hatch"); Console.Write("Choice: "); Int32.TryParse(Console.ReadLine(), out selectInGui); //switch for turn on and turn off, start program, Washing program, and opening hatch switch (selectInGui) { case 1: washer.TurnOnOrOff(); break; case 2: washer.StartWash(); GuiForWhenWashing(); break; case 3: washer.SelectProgram(0); break; case 4: washer.SelectProgram(1 ); break; case 5: washer.SelectProgram(2); break; case 6: washer.SelectProgram(3); break; case 7: washer.OpenOrCloseHatch(); break; default: Console.WriteLine("Out of range"); Console.ReadKey(); break; } } } public void GuiForWhenWashing() { //For when the washer is washing and counting down, and so no action can be taking while it is washing if (washer.Running == true) { for (int i = Int32.Parse(washer.WashProgram[1]); i > 0; --i) { Console.Clear(); Translate(); Console.WriteLine("1. Turn " + turnedOn + " | Program: " + washer.WashProgram[0]); Console.WriteLine("2. Start Program | Program Startede"); Console.WriteLine("3. Basic Wash | Estimated time left: " + i + " Seconds"); Console.WriteLine("4. Eco Wash | Estimated Water intake: " + washer.WashProgram[2]); Console.WriteLine("5. Quick Wash | Estimated Water Temperature: " + washer.WashProgram[3]); Console.WriteLine("6. Heavy Wash |"); Console.WriteLine("7. " + hatchSecured + " hatch |"); Thread.Sleep(1000); } washer.washEnded(); } } } }
namespace CCCP.DAL.Entities { public class CoffeeCups { public int Id { get; set; } public int TotalSaved { get; set; } } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace TLP.UI { [RequireComponent(typeof(CanvasGroup))] public class Window : AnimatedPanel { #pragma warning disable 0649 [SerializeField] private string windowID; [SerializeField] private Selectable firstControl; [SerializeField] private Transform backgroundDenier; #pragma warning restore 0649 public string ID { get { return windowID; } } public Selectable FirstControl { get { return firstControl; } } public Transform BackgroundDenier { get { return backgroundDenier; } } public UnityEvent OnActivated; public UnityEvent OnDeactivated; public UnityEvent OnNextWindow; public UnityEvent OnPreviousWindow; public void ShowWindow(string id) { WindowManager.Instance.ShowWindow(id); } public void Back() { WindowManager.Instance.Back(); } protected override void Start() { base.Start(); if (string.IsNullOrEmpty(windowID)) Debug.LogWarning("Warning: window has no ID, this is probably unintended!", gameObject); else { if (WindowManager.Instance != null) WindowManager.Instance.RegisterWindow(this, windowID); } } } }
using System; using System.Collections; using System.Collections.Generic; using Assets.Scripts.Configs; using Assets.Scripts.Core.Scenarios; using Assets.Scripts.Units; using UnityEngine; namespace Assets.Scripts.Buildings { public class FountainController : MonoBehaviour, IInteractableObject { [SerializeField] private Transform resurrectionPoint; [SerializeField] private FountainConfig config; [SerializeField] private CapsuleCollider modelCollider; [SerializeField] private GameObject targetSign; public event Action OnTimeTillResurrectionChanged; public float TimeTillResurrection { get { return timeTillResurrection; } private set { timeTillResurrection = value; if (OnTimeTillResurrectionChanged != null) OnTimeTillResurrectionChanged(); } } private float timeTillResurrection; private IScenarioItem resurrectionScenario; private List<UnitController> units = new List<UnitController>(); public int PlayerId { get { return PlayerManager.Instance.UserPlayer.PlayerId; } } public bool IsAlive { get { return true; } } public bool IsVulnerable { get { return false; } } public Vector3 Position { get { return transform.position; } } public float BoundingRadius { get { return modelCollider.radius; } } public float Range { get { return 0; } } private void Awake() { MapController.Instance.RegisterFountain(this); targetSign.SetActive(false); } public void ResurrectHero(HeroController heroController) { heroController.gameObject.SetActive(false); heroController.transform.position = resurrectionPoint.position; TimeTillResurrection = (heroController.Unit as Hero).ResurrectionTime; resurrectionScenario = new Scenario( new IterateItem(TimeTillResurrection, (leftTime) => { TimeTillResurrection = leftTime; }), new ActionItem(() => { heroController.Unit.HP = heroController.Unit.MaxHP; heroController.gameObject.SetActive(true); }) ).Play(); } public void AddToSaveZone(UnitController unitController) { if (unitController.PlayerId != PlayerId) return; unitController.IsVulnerable = false; units.Add(unitController); MapController.Instance.RemoveUnit(unitController); } public void RemoveFromSaveZone(UnitController unitController) { if (unitController.PlayerId != PlayerId) return; units.Remove(unitController); MapController.Instance.AddUnit(unitController); } public void RemoveAll() { while (units.Count > 0) { RemoveFromSaveZone(units[0]); } } private void Update() { for (int i = 0; i < units.Count; i++) { units[i].Unit.HP += (units[i].Unit is Hero ? config.HeroHealingSpeed : config.MinionsHealingSpeed) * Time.deltaTime; } } private void OnTriggerEnter(Collider other) { UnitController unitController = other.GetComponent<UnitController>(); if (unitController) { AddToSaveZone(unitController); } } private void OnTriggerExit(Collider other) { UnitController unitController = other.GetComponent<UnitController>(); if (unitController) { RemoveFromSaveZone(unitController); } } public void SetTargeted(bool targeted) { targetSign.gameObject.SetActive(targeted); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CT.Data { public class ConstructionData { public readonly int ID; public GameTime time; public readonly GameTime startTime; public readonly BuildingInstanceData isUpgradeOf; public readonly BuildingData toConstruct; public readonly int x, y; public readonly int endX, endY; public readonly GameObject fx; public readonly Quaternion rotation; //New Building public ConstructionData(int id, BuildingData data, GameTime time, int x, int y) { ID = id; startTime = data.Original.buildTime; this.time = time; isUpgradeOf = null; toConstruct = data; this.x = x; this.y = y; endX = x + data.tileWidth - 1; endY = y + data.tileHeight - 1; fx = data.Original.constructionPrefab; rotation = Quaternion.identity; } //Upgrade Building public ConstructionData(BuildingInstanceData toUpgrade, GameTime time) { if (!toUpgrade.HasNextVersion) throw new System.ArgumentException($"Building with ID {toUpgrade.ID} doesn't have next version!"); ID = 0; // may do change up var nextLevel = toUpgrade.BaseNextData; startTime = nextLevel.buildTime; this.time = time; toConstruct = null; isUpgradeOf = toUpgrade; x = toUpgrade.tileX; y = toUpgrade.tileY; fx = nextLevel.constructionPrefab; rotation = Quaternion.identity; } } }
using System; using System.Collections.Generic; using System.Text; namespace Polymorphism { public abstract class Shape { public int Width { get; set; } public int Height { get; set; } public int X { get; set; } public int Y { get; set; } public virtual void Draw() { Console.WriteLine("Drawing in shape class"); } public abstract void Draw2(); } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class PlayMovie : MonoBehaviour { Renderer r; MovieTexture movie; void Start(){ r = GetComponent<Renderer>(); movie = (MovieTexture)r.material.mainTexture; //movie.Stop (); movie.Play(); movie.loop = true; } void Update () { if (Input.GetButtonDown ("Jump")) { movie.Stop (); SceneManager.LoadScene ("HubScene"); // if (movie.isPlaying) { // movie.Pause(); // } // else { // movie.Play(); // } } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Configuration; namespace DotNetNuke.Web.ConfigSection { public class AuthServicesConfiguration : ConfigurationSection { public static AuthServicesConfiguration GetConfig() { return ConfigurationManager.GetSection("dotnetnuke/authServices") as AuthServicesConfiguration; } [ConfigurationProperty("messageHandlers", IsRequired = true)] public MessageHandlersCollection MessageHandlers => this["messageHandlers"] as MessageHandlersCollection; } }
namespace Bridge.RealWorld { /// <summary> /// The advanced remote control. /// </summary> /// <seealso cref="Bridge.RealWorld.RemoteControl" /> class AdvancedRemoteControl : RemoteControl { /// <summary> /// Initializes a new instance of the <see cref="AdvancedRemoteControl"/> class. /// </summary> /// <param name="device">The device.</param> public AdvancedRemoteControl(IDevice device) : base(device) { } /// <summary> /// Mutes this instance. /// </summary> public void Mute() { this.device.SetVolume(0); } } }
using NUnit.Framework; namespace Logs.Models.Tests.SubscriptionTests { [TestFixture] public class ConstructorTests { [TestCase(1, "d547a40d-c45f-4c43-99de-0bfe9199ff95")] [TestCase(423, "99ae8dd3-1067-4141-9675-62e94bb6caaa")] public void TestConstructor_ShouldSetTrainingLogIdCorrectly(int logId, string userId) { // Arrange, Act var subscription = new Subscription(logId, userId); // Assert Assert.AreEqual(logId, subscription.TrainingLogId); } [TestCase(1, "d547a40d-c45f-4c43-99de-0bfe9199ff95")] [TestCase(423, "99ae8dd3-1067-4141-9675-62e94bb6caaa")] public void TestConstructor_ShouldSetUserIdCorrectly(int logId, string userId) { // Arrange, Act var subscription = new Subscription(logId, userId); // Assert Assert.AreEqual(userId, subscription.UserId); } } }
using System; namespace SLua { public enum LuaSvrFlag { LSF_BASIC, LSF_DEBUG, LSF_EXTLIB, LSF_3RDDLL = 4 } }
namespace Kit.WPF.Reportes { public enum FormatoReporte { PDF, EXCEL } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Webcorp.unite { public partial class Currency : IUnit<Currency> { public void SetChange(double value) { this.value = value; } public static Currency operator +(Currency x, double y) { return new Currency(x.value + y); } } }
using System; using Newtonsoft.Json; namespace MonoGame.Extended.Gui.Serialization { public class AlignmentConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (objectType == typeof(HorizontalAlignment)) { var value = reader.Value.ToString(); if (value == "Center" || string.Equals(value, "Centre", StringComparison.OrdinalIgnoreCase)) return HorizontalAlignment.Centre; HorizontalAlignment alignment; if (Enum.TryParse(value, true, out alignment)) return alignment; } if (objectType == typeof(VerticalAlignment)) { var value = reader.Value.ToString(); if (value == "Center" || string.Equals(value, "Centre", StringComparison.OrdinalIgnoreCase)) return VerticalAlignment.Centre; VerticalAlignment alignment; if (Enum.TryParse(value, true, out alignment)) return alignment; } throw new InvalidOperationException($"Invalid value for '{objectType.Name}'"); } public override bool CanConvert(Type objectType) { return objectType == typeof(HorizontalAlignment) || objectType == typeof(VerticalAlignment); } } }
using NuGet.Versioning; using Xunit; namespace NuGet.DependencyResolver.Tests { public class RemoteDependencyWalkerTests { [Fact] public void IsGreaterThanEqualTo_ReturnsTrue_IfLeftVersionIsUnbound() { // Arrange var leftVersion = VersionRange.All; var rightVersion = VersionRange.Parse("1.0.0"); // Act var isGreater = RemoteDependencyWalker.IsGreaterThanOrEqualTo(leftVersion, rightVersion); // Assert Assert.True(isGreater); } [Fact] public void IsGreaterThanEqualTo_ReturnsFalse_IfRightVersionIsUnbound() { // Arrange var leftVersion = VersionRange.Parse("3.1.0-*"); var rightVersion = VersionRange.All; // Act var isGreater = RemoteDependencyWalker.IsGreaterThanOrEqualTo(leftVersion, rightVersion); // Assert Assert.False(isGreater); } [Theory] [InlineData("3.0", "3.0")] [InlineData("3.0", "3.0.0")] [InlineData("3.1", "3.0.0")] [InlineData("3.1.2", "3.1.1")] [InlineData("3.1.2-beta", "3.1.2-alpha")] [InlineData("[3.1.2-beta, 4.0)", "[3.1.1, 4.3)")] [InlineData("[3.1.2-*, 4.0)", "3.1.2-alpha-1002")] [InlineData("3.1.2-prerelease", "3.1.2-alpha-*")] [InlineData("3.1.2-beta-*", "3.1.2-alpha-*")] [InlineData("3.1.*", "3.1.2-alpha-*")] [InlineData("*", "3.1.2-alpha-*")] [InlineData("*", "*")] [InlineData("1.*", "1.1.*")] [InlineData("1.*", "1.3.*")] [InlineData("1.8.*", "1.8.3.*")] [InlineData("1.8.3.5*", "1.8.3.4-*")] [InlineData("1.8.3.*", "1.8.3.4-*")] [InlineData("1.8.3.4-alphabeta-*", "1.8.3.4-alpha*")] [InlineData("1.8.5.4-alpha-*", "1.8.3.4-gamma*")] [InlineData("1.8.3.6-alpha-*", "1.8.3.4-gamma*")] [InlineData("1.8.3-*", "1.8.3-alpha*")] [InlineData("1.8.3-*", "1.8.3-*")] [InlineData("1.8.4-*", "1.8.3-*")] [InlineData("2.8.1-*", "1.8.3-*")] [InlineData("3.2.0-*", "3.1.0-beta-234")] [InlineData("3.*", "3.1.*")] public void IsGreaterThanEqualTo_ReturnsTrue_IfRightVersionIsSmallerThanLeft(string leftVersionString, string rightVersionString) { // Arrange var leftVersion = VersionRange.Parse(leftVersionString); var rightVersion = VersionRange.Parse(rightVersionString); // Act var isGreater = RemoteDependencyWalker.IsGreaterThanOrEqualTo(leftVersion, rightVersion); // Assert Assert.True(isGreater); } [Theory] [InlineData("1.3.4", "1.4.3")] [InlineData("3.0", "3.1")] [InlineData("3.0", "*")] [InlineData("3.0-*", "*")] [InlineData("3.2.4", "3.2.7")] [InlineData("3.2.4-alpha", "[3.2.4-beta, 4.0)")] [InlineData("2.2.4-alpha", "2.2.4-beta-*")] [InlineData("2.2.4-beta-1", "2.2.4-beta1*")] [InlineData("2.2.1.*", "2.3.*")] [InlineData("2.*", "3.1.*")] [InlineData("3.4.6.*", "3.6.*")] [InlineData("3.4.6-alpha*", "3.4.6-beta*")] [InlineData("3.4.6-beta*", "3.4.6-betb*")] [InlineData("3.1.0-beta-234", "3.2.0-*")] [InlineData("3.0.0-*", "3.1.0-beta-234")] public void IsGreaterThanEqualTo_ReturnsFalse_IfRightVersionIsLargerThanLeft(string leftVersionString, string rightVersionString) { // Arrange var leftVersion = VersionRange.Parse(leftVersionString); var rightVersion = VersionRange.Parse(rightVersionString); // Act var isGreater = RemoteDependencyWalker.IsGreaterThanOrEqualTo(leftVersion, rightVersion); // Assert Assert.False(isGreater); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace BPiaoBao.Common.Enums { /// <summary> /// web消息推送指令 /// </summary> public enum EnumMessageCommand:int { /// <summary> /// 支付等待出票 /// </summary> [Description("订单出票")] PayWaitIssueTicket=0, /// <summary> /// 申请售后 /// </summary> [Description("售后订单处理")] ApplyAfterSaleOrder=1, /// <summary> /// 公告通知 /// </summary> [Description("票宝公告")] Aannouncement=2 } }
using UnityEngine; using System.Collections; namespace ProjectV.ItemSystem{ [System.Serializable] public enum EQRange { Short, Mid, Long, Special } }
using System; using System.Collections.Generic; using ReadyGamerOne.Common; using SecondGame.Const; namespace SecondGame.Scripts { public class BagData : MonoSingleton<BagData> { public List<string> itemNames = new List<string>(); protected override void Awake() { base.Awake(); CEventCenter.AddListener<string>(Message.AddItem, (name) => itemNames.Add(name)); CEventCenter.AddListener<string>(Message.RemoveItem, (name) => itemNames.Remove(name)); } private void Start() { CEventCenter.BroadMessage(Message.AddItem, ItemName.aneng); CEventCenter.BroadMessage(Message.AddItem, ItemName.testItemName); } } }
namespace GameInputSystem { public enum XboxControllerButtons { None, A, B, X, Y, LeftStick, RightStick, View, Menu, LeftBumper, RightBumper } }
using bitirme.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.IO; using System.Linq; using System.Web; using System.Web.Helpers; using System.Web.Mvc; namespace bitirme.Controllers { public class HotelController : Controller { OurDbContext db = new OurDbContext(); // GET: Hotel public ActionResult Index() { var a = db.rezerves.Count(); for (int i = 1; i <a; i++) { var b = db.rezerves.Find(i); if (b.ctarih<DateTime.Now) { if (b.Durum==true) { b.Durum = false; db.SaveChanges(); } } } int id = Convert.ToInt32(Session["otelID"]); RezerveView rez = new RezerveView(); rez.rezerves = db.rezerves.Where(x => x.otelID == id).ToList(); rez.users = db.users.ToList(); rez.otelodas = db.otelodas.ToList(); return View(rez); } public ActionResult or() { ViewBag.otelID = new SelectList(db.otels, "otelID"); return View(); } [HttpPost] public ActionResult or(bitirme.Models.otel s, HttpPostedFileBase foto) { if (ModelState.IsValid) { if (foto != null) { WebImage img = new WebImage(foto.InputStream); FileInfo fotoinfo = new FileInfo(foto.FileName); string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension; img.Resize(600, 400); img.Save("~/Resimler/OtelImage" + newfoto); s.or = "~/Resimler/OtelImage" + newfoto; db.otels.Add(s); db.SaveChanges(); return RedirectToAction("HotelLogin"); } } return View(s); } public ActionResult HotelLogin() { return View(); } [ValidateAntiForgeryToken] [HttpPost] public ActionResult HotelLogin(bitirme.Models.otel otel) { using (OurDbContext db = new OurDbContext()) { var usr = db.otels.Single(u => u.otelkullaniciAdi == otel.otelkullaniciAdi && u.otelSifre == otel.otelSifre); if (usr != null) { Session["otelID"] = usr.otelID.ToString(); Session["otelkullaniciAdi"] = usr.otelkullaniciAdi.ToString(); ViewBag.otelad = usr.otelAdi; ViewBag.otelID = usr.otelID; return RedirectToAction("Index"); } else { ModelState.AddModelError("", "Kullanıcı Adı veya Şifre Hatalı"); } } return View(); } public ActionResult otelupdate(int otelid) { var ot = db.otels.Where(m => m.otelID == otelid).SingleOrDefault(); if (ot == null) { return HttpNotFound(); } return View(ot); } [ValidateAntiForgeryToken] [HttpPost] public ActionResult otelupdate(bitirme.Models.otel s, int otelid, HttpPostedFileBase foto) { var yeni = db.otels.Where(m => m.otelID == otelid).SingleOrDefault(); if (foto != null) { if (System.IO.File.Exists(Server.MapPath(yeni.or))) { System.IO.File.Delete(Server.MapPath(yeni.or)); } WebImage img = new WebImage(foto.InputStream); FileInfo fotoinfo = new FileInfo(foto.FileName); string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension; img.Resize(600, 400); img.Save("~/Resimler/OtelImage" + newfoto); s.or = "~/Resimler/OtelImage" + newfoto; yeni.adres = s.adres; yeni.otelaciklama = s.otelaciklama; yeni.otelAdi = s.otelAdi; yeni.otelEmail = s.otelEmail; yeni.otelkullaniciAdi = s.otelkullaniciAdi; yeni.otelSifre = s.otelSifre; yeni.otelTel = s.otelTel; yeni.sehir = s.sehir; db.SaveChanges(); } return View("otelupdate"); } public ActionResult oteldelete(int otelid) { var ot = db.otels.Where(m => m.otelID == otelid).SingleOrDefault(); if (ot == null) { return HttpNotFound(); } return View(ot); } [HttpPost] public ActionResult oteldelete(int otelid, FormCollection collection) { var sil = db.otels.Where(m => m.otelID == otelid).SingleOrDefault(); if (sil == null) { return HttpNotFound(); } if (System.IO.File.Exists(Server.MapPath(sil.or))) { System.IO.File.Delete(Server.MapPath(sil.or)); } db.otels.Remove(sil); db.SaveChanges(); return RedirectToAction("Index", "Home"); } public ActionResult otelodaliste(int otelid) { return View(db.otelodas.Where(m => m.otelID == otelid).ToList()); } public ActionResult otelodaEkle(int otelid) { //var x = db.otelodas.Where(m=>m.otelID==otelid).SingleOrDefault(); return View(); } [ValidateAntiForgeryToken] [HttpPost] public ActionResult otelodaEkle(bitirme.Models.oteloda s, HttpPostedFileBase foto) { if (ModelState.IsValid) { if (foto != null) { WebImage img = new WebImage(foto.InputStream); FileInfo fotoinfo = new FileInfo(foto.FileName); string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension; img.Resize(600, 400); img.Save("~/Resimler/OdaResims" + newfoto); s.odaresim = "~/Resimler/OdaResims" + newfoto; db.otelodas.Add(s); db.SaveChanges(); return RedirectToAction("Index"); } } return RedirectToAction("otelodaEkle"); } public ActionResult otelodaDuzenle(int odaid) { var ot = db.otelodas.Where(m => m.odaID == odaid).SingleOrDefault(); if (ot == null) { return HttpNotFound(); } return View(ot); } [HttpPost] public ActionResult otelodaDuzenle(bitirme.Models.oteloda s, HttpPostedFileBase foto) { var yeni = db.otelodas.Where(m => m.odaID == s.odaID).SingleOrDefault(); if (foto != null) { if (System.IO.File.Exists(Server.MapPath(yeni.odaresim))) { System.IO.File.Delete(Server.MapPath(yeni.odaresim)); } WebImage img = new WebImage(foto.InputStream); FileInfo fotoinfo = new FileInfo(foto.FileName); string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension; img.Resize(600, 400); img.Save("~/Resimler/OtelImage" + newfoto); s.odaresim = "~/Resimler/OtelImage" + newfoto; yeni.aciklama = s.aciklama; yeni.odaAdi = s.odaAdi; yeni.odakisi = s.odakisi; yeni.odaucret = s.odaucret; db.SaveChanges(); } return View("otelodaDuzenle"); } public ActionResult otelodaSil(int odaid) { var ot = db.otelodas.Where(m => m.odaID == odaid).SingleOrDefault(); if (ot == null) { return HttpNotFound(); } return View(ot); } [HttpPost] public ActionResult otelodaSil(int odaid, FormCollection collection) { var sil = db.otelodas.Where(m => m.odaID == odaid).SingleOrDefault(); if (sil == null) { return HttpNotFound(); } if (System.IO.File.Exists(Server.MapPath(sil.odaresim))) { System.IO.File.Delete(Server.MapPath(sil.odaresim)); } db.otelodas.Remove(sil); db.SaveChanges(); return RedirectToAction("Index", "Home"); } public ActionResult otelozellik(int id = 0) { ozellik oze = new ozellik(); using (OurDbContext db = new OurDbContext()) { if (id != 0) { oze.selectedID = oze.kategoriID.Split(',').ToArray(); } oze.kategoris = db.kategoris.ToList(); } return View(oze); } [ValidateAntiForgeryToken] [HttpPost] public ActionResult otelozellik(bitirme.Models.ozellik oz, int? otelid) { // oz.kategoriID = string.Join(",", oz.selectedID); using (OurDbContext db = new OurDbContext()) { if (oz.ozellikID == 0) { for (int i = 0; i < oz.selectedID.Length; i++) { var temp = oz.selectedID[i]; oz.kategoriID = temp; oz.otelID = otelid; db.ozelliks.Add(oz); db.SaveChanges(); } } } return RedirectToAction("otelozellik", new { id = 0 }); } public ActionResult otelresimEkle(int otelid) { return View(); } [HttpPost] public ActionResult otelresimEkle(bitirme.Models.otelresim s, HttpPostedFileBase foto) { if (ModelState.IsValid) { if (foto != null) { WebImage img = new WebImage(foto.InputStream); FileInfo fotoinfo = new FileInfo(foto.FileName); string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension; img.Resize(600, 400); img.Save("~/Resimler/OdaResims" + newfoto); s.otelresimAdi = "~/Resimler/OdaResims" + newfoto; db.otelresims.Add(s); db.SaveChanges(); return RedirectToAction("Index"); } } return View(s); } public ActionResult logout() { Session.Clear(); Session.Abandon(); return RedirectToAction("Index", "Home"); } } }
//======================================================================= // ClassName : ScrollRectExEvent // 概要 : スクロールレクトイベント // // // LiplisLive2D // Create 2018/03/11 // // Copyright(c) 2017-2018 sachin. All Rights Reserved. //======================================================================= using UnityEngine.Events; using UnityEngine.EventSystems; public class ScrollRectExEvent : UnityEvent<PointerEventData> { }
using System; using System.Collections.Generic; using System.Text; using Utils; using System.Linq; using ChaseHelper.ReportDataObjects; namespace ChaseHelper { public class ChaseProcessor { // todo sql load // todo transactions under/over forty // list highest hits over the last 30 days // total spending grouped by month intervals // highest from each 2 week interval (goes along with the paycheck pattern) // dumping into sql tables- raw data (with and without bills) // table: daily summary spending (bills/no bills) //table: bills only // table: weekly spending // table bi-weekly spending // table: highest 10 purchases each month // table: transactions over 40 // table: clothing transactions // table: all food transactions (including coffee, starbucks, etc..) // table: fast food transactions: starbucks, panera, etc.. // list fees, tickets, etc... // non bill spending going backwards from most recent week by week public List<Transaction> tl = new List<Transaction>();// starting unfiltered, may be filterd public string billsFile; public string csvFile; public StringBuilder sb = new StringBuilder();// command line output Dictionary<string, string> bills; public ChaseProcessor( string basePath, string csvFile, string billsFile ) { this.csvFile = basePath+csvFile; this.billsFile = basePath + billsFile; sb.Append(DateTime.Now.DayOfWeek.ToString() + ", " + DateTime.Now.ToString()); sb.Append(Environment.NewLine); if (this.billsFile != "") { bills=Utils.Jsoner.dnr(this.billsFile); } } public void runMainReport( bool applyBillsFilter) { if (applyBillsFilter) applyFilter(); daysDiscrete(-40); //weeksDiscrete(-8); //daysBack(); //monthlies(); //monthlyDetails(-8); } public void loadData() { List<string[]> ls = Utils.CSVHelper.csv2ListStringArray(csvFile); //string[] line; Transaction t; TransactionProcessor tp = new TransactionProcessor(); bool header = true; foreach (string[] line in ls) { if (!header) { t = tp.load(line); tl.Add(t); } else header = false; } } /* private void writePeriod (StringBuilder sb, int daysback) { sb.Append(Environment.NewLine); sb.Append("Days Back: " + daysback.ToString()); sb.Append(" \t"); sb.Append ("Spent: " + debitSum.ToString("C")); sb.Append(" \t "); sb.Append("Earned: " + creditSum.ToString("C")); sb.Append(" \t "); sb.Append("Surplus: " + (creditSum + debitSum).ToString()); } */ /* public void monthlyDetails (int monthsBack ) { sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("discrete monthly details"); sb.Append(Environment.NewLine); for (int i =0; i> monthsBack; i--) { sb.Append(Environment.NewLine); DateTime dt1 = DateTime.Now; DateTime dt2 = dt1.AddMonths(i); DateTime dt3 = new DateTime(dt2.Year, dt2.Month, 1); sb.Append(dt3.ToString("MMM")); sb.Append("\t"); for (int j=1; j<5; j++) { DateTime dt4 = dt3.AddDays(6); TransactionSum(dt3, dt4); sb.Append(j.ToString() + "\t"); sb.Append(debitSum.ToString("C") + "\t "); dt3 = dt4; } } } */ // rework this to show week by week instead of 7 day intervals, so that it's easier to compare the numbers. /* public void weeksDiscrete(int weeksback) { sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append("Weeks Discrete: "); sb.Append(Environment.NewLine); for (int i = 0; i >=weeksback; i--) { DateTime dt = DateTime.Now.AddDays(i*7); DateTime dt2 = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0); DateTime dt3 = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0); TransactionSum(dt2, dt3); sb.Append(Environment.NewLine); sb.Append(dt.ToShortDateString() + ": \t debits: " + debitSum.ToString("C") + " \t credits: " + creditSum.ToString("C")); } } */ // to do: rewrite days discrete // to do add a web api project that will call this and then return json from it and at least try to render the json public List<SpendingInterval> dailySpendingList = new List<SpendingInterval>(); public void daysDiscrete (int daysback ) { SpendingInterval si; for (int i=0; i>=daysback; i--) { DateTime dt = DateTime.Now.AddDays(i); si = new SpendingInterval(); DateTime dt2 = new DateTime(dt.Year, dt.Month, dt.Day); si.sdate = dt2; si.edate = dt2; TransactionSum(si); dailySpendingList.Add(si); } } /* public void monthlies () { for (int i = 0; i > -6; i--) { sb.Append(Environment.NewLine); DateInterval di = new DateInterval(i); TransactionSum(di.sdate, di.edate); sb.Append(di.sdate.ToString("MMM")); sb.Append(": \t "); sb.Append("debits: " + debitSum.ToString("C")); sb.Append(" \t credits: " + creditSum.ToString("C")); sb.Append(" \t" + "surplus: " + (creditSum + debitSum).ToString("C")); } } */ /* public void daysBack () { // money spent and earned over the last 7, 14, 21 and 30 days // also, money spent on bills, and other stuff int daysback = -7; TransactionSum(daysback); sb.Append("Money Report: " + DateTime.Now.ToShortDateString()); sb.Append(Environment.NewLine); sb.Append("Cumulatives: "); sb.Append(Environment.NewLine); writePeriod(sb, daysback); daysback = -14; TransactionSum(daysback); writePeriod(sb, daysback); daysback = -30; TransactionSum(daysback); writePeriod(sb, daysback); daysback = -60; TransactionSum(daysback); writePeriod(sb, daysback); daysback = -90; TransactionSum(daysback); writePeriod(sb, daysback); daysback = -180; TransactionSum(daysback); writePeriod(sb, daysback); sb.Append(Environment.NewLine); sb.Append("Monthlies:"); sb.Append(Environment.NewLine); } */ /* public void getLatestBills() { // divide water by 3 since the village charges per season - or just exclude it all together? // I feel like I should include it for a more compelete picture. // todo - turn this into linq calls List<Transaction> lb = new List<Transaction>(); foreach (var bill in bills) { foreach (Transaction t in tl) { if ( t._02_description.ToLower(). Contains(bill.Value.ToLower()) && t._04_type != "FEE_TRANSACTION" ) { var x = lb.Where(a => a._02_description.ToLower().Contains(bill.Value.ToLower())); if (x.Count()==0) lb.Add(new Transaction(t)); } } } decimal billSum = 0; foreach (var t in lb) { sb.Append(t.toTabbedString()); sb.Append(Environment.NewLine); billSum = billSum + t._03_amount; } sb.Append(Environment.NewLine); sb.Append ("Total bills: \t\t \t\t\t " + billSum.ToString()); } */ // to do - how to do an end with linq extension methods - if not, then use the syntax public void applyFilter () { foreach (var bill in bills) { if (bill.Value.Length > 2) { var c = tl .Where( f => f._02_description.ToLower() .Contains(bill.Value.ToLower()) == false ) .ToList(); tl = c; } } } public void TransactionSum (SpendingInterval si) { // filter the list with linq; // take out online transfer, smart llc and whatever else, and mom's deposits? var fl = tl.Where(f => f._02_description.ToLower().Contains("online transfer") == false) .Where(f => f._02_description.ToLower().Contains("atm checking transfer") == false) .Where(f => f._02_description.ToLower().Contains("atm savings transfer") == false) .Where(f => Utils.Dater.BetweenInclusive(si.sdate, si.edate, f.transDate)); foreach (var fll in fl) { if (0 > fll._03_amount) si.debit = si.debit + fll._03_amount; else si.credit = si.credit + fll._03_amount; } } } }
using System; namespace FreeUI.Anima { public class Zoom { // Atributos internos de controle private static int controlX; private static int controlY; private static int controlDestinoX; private static int controlDestinoT; private static bool maximizado = false; /// <summary> /// Aumenta o tamanho de um controle /// </summary> /// <param name="control">Controle alvo</param> /// <param name="zoom">Tamanho do zoom</param> public static void In(System.Windows.Forms.Control control, int zoom) { if (!maximizado) { controlX = control.Height; controlY = control.Width; int constantZoomX = Convert.ToInt32( Math.Round( zoom * 0.01 * controlX ) * 0.5 ); int constantZoomY = Convert.ToInt32( Math.Round( zoom * 0.01 * controlY ) * 0.5 ); int altura = controlX + constantZoomX * 2; int comprimento = controlY + constantZoomY * 2; controlDestinoX = constantZoomX; controlDestinoT = constantZoomY; control.Width = comprimento; control.Height = altura; control.Top -= controlDestinoX; control.Left -= controlDestinoT; maximizado = true; } } /// <summary> /// Restaura o controle para seu tamanho original /// </summary> /// <param name="controle">Cibtrike alvo</param> public static void Out(System.Windows.Forms.Control controle) { if (maximizado) { controle.SuspendLayout(); controle.Width = controlY; controle.Left += controlDestinoT; controle.Height = controlX; controle.Top += controlDestinoX; controle.ResumeLayout(); maximizado = false; } } } }
using AlienEngine.ASL; using AlienEngine.Core.Graphics.OpenGL; using System; namespace AlienEngine.Core.Graphics.Shaders.Samples { [Version(330)] internal class GrassVertexShader : VertexShader { #region VAO Objects [Layout(Location = GL.VERTEX_POSITION_LOCATION)] [In] vec3 in_position; [Layout(Location = GL.VERTEX_TEXTURE_COORD_LOCATION)] [In] vec2 in_uv; #endregion #region Fragment shader inputs [Out] vec2 uv; #endregion #region Transformation matrices // Transformation (model-view-projection) matrix [Uniform] mat4 wvp_matrix; #endregion void main() { // Setting texture coordinates uv = in_uv; // Output the position gl_Position = wvp_matrix * new vec4(in_position, 1); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace DotNetNuke.Services.Connections { public class ConnectorArgumentException : ApplicationException { public ConnectorArgumentException() { } public ConnectorArgumentException(string message) : base(message) { } public ConnectorArgumentException(string message, Exception innerException) : base(message, innerException) { } } }
namespace Newtonsoft.Json.Converters { using Newtonsoft.Json; using ns20; using System; using System.Globalization; public class JavaScriptDateTimeConverter : DateTimeConverterBase { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Type type = Class194.smethod_10(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType; if (reader.JsonToken_0 == JsonToken.Null) { if (!Class194.smethod_9(objectType)) { throw JsonSerializationException.smethod_1(reader, "Cannot convert null value to {0}.".smethod_0(CultureInfo.InvariantCulture, objectType)); } return null; } if ((reader.JsonToken_0 != JsonToken.StartConstructor) || !string.Equals(reader.Object_0.ToString(), "Date", StringComparison.Ordinal)) { throw JsonSerializationException.smethod_1(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".smethod_1(CultureInfo.InvariantCulture, reader.JsonToken_0, reader.Object_0)); } reader.Read(); if (reader.JsonToken_0 != JsonToken.Integer) { throw JsonSerializationException.smethod_1(reader, "Unexpected token parsing date. Expected Integer, got {0}.".smethod_0(CultureInfo.InvariantCulture, reader.JsonToken_0)); } long num = (long) reader.Object_0; DateTime dateTime = Class184.smethod_11(num); reader.Read(); if (reader.JsonToken_0 != JsonToken.EndConstructor) { throw JsonSerializationException.smethod_1(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".smethod_0(CultureInfo.InvariantCulture, reader.JsonToken_0)); } if (!(type == typeof(DateTimeOffset))) { return dateTime; } return new DateTimeOffset(dateTime); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long num; if (value is DateTime) { num = Class184.smethod_8(((DateTime) value).ToUniversalTime()); } else { if (!(value is DateTimeOffset)) { throw new JsonSerializationException("Expected date object value."); } DateTimeOffset offset = (DateTimeOffset) value; num = Class184.smethod_8(offset.ToUniversalTime().UtcDateTime); } writer.WriteStartConstructor("Date"); writer.WriteValue(num); writer.WriteEndConstructor(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using DBStore.DataAccess.Data.Repository.IRepository; using DBStore.Models.VModels; using DBStore.Paging; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace DBStore.Pages.Customer.Home { public class ReviewsModel : PageModel { private readonly IUnitOfWorkRepository _unitOfWork; public ReviewsModel(IUnitOfWorkRepository unitOfWork) { _unitOfWork = unitOfWork; } public IEnumerable<Models.Reviews> ProductReviews { get; set; } public IActionResult OnGet(int id) { const int pageSize = 5; if (id < 1) { id = 1; } int resCount = _unitOfWork.Reviews.GetAll().Count(); var pagers = new PagedList(resCount, id, pageSize); int recSkip = (id - 1) * pageSize; var data = _unitOfWork.Reviews.GetAll().Skip(recSkip).Take(pagers.PageSize).ToList(); ViewData["pager"] = pagers; ProductReviews = data; return Page(); } } }
using System; using System.Collections.Generic; using Mathml.Operations; namespace Mathml { /// <summary> /// Parse, execute, and print out operations. /// /// Load a list of valid operations from XML. Calculate the results of those operations. /// Print out the information and equation for each of those operations. /// </summary> class Program { /// <summary> /// Start the application here. /// </summary> static void Main() { List<Operation> operations = XmlParser.RetrieveOperations(); List<string> executionLogs = OperationExecuter.Execute(operations); PrintExecutionLogs(executionLogs); PauseForAcknowledgement(); } private static void PrintExecutionLogs(List<string> executionLogs) { foreach (string log in executionLogs) { Console.WriteLine(log); } } private static void PauseForAcknowledgement() { ConsoleKeyInfo pressedKey; do { pressedKey = Console.ReadKey(); } while (pressedKey.Key != ConsoleKey.Enter); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary4._5 { interface Interface1 { int Prop1 { get; set; } int Prop2 { get; set; } void Func1(); } }
using Prj.Respositories.Interfaces; using Prj.Respositories.UnitOfWork; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Prj.Respositories.Implementations { public class PermissionRepository : IPermissionRepository { private readonly IUnitOfWorkProvider _unitOfWorkProvider; public PermissionRepository(IUnitOfWorkProvider unitOfWorkProvider) { _unitOfWorkProvider = unitOfWorkProvider; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TardiRecords.Services.Helpers; namespace TardiRecords.Services.DataViewModels { public class EnumDropdownListVM { public int Id { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; namespace TDigest { public abstract class Digest { protected ScaleFunction Scale = new ScaleFunction.K2(); protected double Min = double.PositiveInfinity; protected double Max = double.NegativeInfinity; public abstract double Compression { get; set; } /** * Creates an {@link MergingDigest}. This is generally the best known implementation right now. * * @param compression The compression parameter. 100 is a common value for normal uses. 1000 is extremely large. * The number of centroids retained will be a smallish (usually less than 10) multiple of this number. * @return the MergingDigest */ public static Digest CreateMergingDigest(double compression) { return new MergingDigest(compression); } /** * Creates a TDigest of whichever type is the currently recommended type. MergingDigest is generally the best * known implementation right now. * * @param compression The compression parameter. 100 is a common value for normal uses. 1000 is extremely large. * The number of centroids retained will be a smallish (usually less than 10) multiple of this number. * @return the TDigest */ public static Digest CreateDigest(double compression) { return CreateMergingDigest(compression); } /** * Adds a sample to a histogram. * * @param x The value to add. * @param w The weight of this point. */ public abstract void Add(double x, int w); void CheckValue(double x) { if (double.IsNaN(x)) { throw new ArgumentException("Cannot add NaN"); } } public abstract void Add(IEnumerable<Digest> others); /** * Re-examines a t-digest to determine whether some centroids are redundant. If your data are * perversely ordered, this may be a good idea. Even if not, this may save 20% or so in space. * * The cost is roughly the same as adding as many data points as there are centroids. This * is typically &lt; 10 * compression, but could be as high as 100 * compression. * * This is a destructive operation that is not thread-safe. */ public abstract void Compress(); /** * Returns the number of points that have been added to this TDigest. * * @return The sum of the weights on all centroids. */ public abstract long Size(); /** * Returns the fraction of all points added which are &le; x. * * @param x The cutoff for the cdf. * @return The fraction of all data which is less or equal to x. */ public abstract double Cdf(double x); /** * Returns an estimate of the cutoff such that a specified fraction of the data * added to this TDigest would be less than or equal to the cutoff. * * @param q The desired fraction * @return The value x such that cdf(x) == q */ public abstract double Quantile(double q); /** * A {@link Collection} that lets you go through the centroids in ascending order by mean. Centroids * returned will not be re-used, but may or may not share storage with this TDigest. * * @return The centroids in the form of a Collection. */ public abstract IEnumerable<Centroid> Centroids(); /** * Returns the number of bytes required to encode this TDigest using #asBytes(). * * @return The number of bytes required. */ public abstract int ByteSize(); /** * Returns the number of bytes required to encode this TDigest using #asSmallBytes(). * * Note that this is just as expensive as actually compressing the digest. If you don't * care about time, but want to never over-allocate, this is fine. If you care about compression * and speed, you pretty much just have to overallocate by using allocating #byteSize() bytes. * * @return The number of bytes required. */ public abstract int SmallByteSize(); public void SetScaleFunction(ScaleFunction scaleFunction) { /* if (scaleFunction.toString().endsWith("NO_NORM")) { throw new ArgumentException( string.Format("Can't use %s as scale with %s", scaleFunction, getClass())); } */ Scale = scaleFunction; } /** * Serialize this TDigest into a byte buffer. Note that the serialization used is * very straightforward and is considerably larger than strictly necessary. * * @param buf The byte buffer into which the TDigest should be serialized. */ public abstract void AsBytes(BinaryWriter buf); /** * Serialize this TDigest into a byte buffer. Some simple compression is used * such as using variable byte representation to store the centroid weights and * using delta-encoding on the centroid means so that floats can be reasonably * used to store the centroid means. * * @param buf The byte buffer into which the TDigest should be serialized. */ public abstract void AsSmallBytes(BinaryWriter buf); /** * Tell this TDigest to record the original data as much as possible for test * purposes. * * @return This TDigest so that configurations can be done in fluent style. */ public abstract Digest RecordAllData(); public abstract bool IsRecording(); /** * Add a sample to this TDigest. * * @param x The data value to add */ public abstract void Add(double x); /** * Add all of the centroids of another TDigest to this one. * * @param other The other TDigest */ public abstract void Add(Digest other); public abstract int CentroidCount(); public double GetMin() { return Min; } public double GetMax() { return Max; } /** * Over-ride the min and max values for testing purposes */ protected void SetMinMax(double min, double max) { this.Min = min; this.Max = max; } } }