text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Delivery.WebApi.Services;
using Inventory.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Delivery.WebApi.Controllers
{
//[Authorize]
[Route("api/[controller]")]
[ApiController]
public class MarkController : ControllerBase
{
private readonly MarkService _service;
private readonly LogWebApiService _log;
public MarkController(MarkService service, LogWebApiService log)
{
_service = service;
_log = log;
}
// GET: api/Mark
[HttpGet("Guid")]
public async Task<ActionResult<Mark>> GetMarkAsync(Guid rowGuid)
{
Mark rez = await _service.GetMarkAsync(rowGuid);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Mark
[HttpGet]
public async Task<ActionResult<IList<Mark>>> GetMarksAsync()
{
IList<Mark> rez = await _service.GetMarksAsync();
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// POST: api/Mark
[HttpPost("New")]
public async Task<ActionResult<Mark>> Post(Mark model)
{
Mark insertDish = await _service.GetMarkAsync(model.RowGuid);
if (insertDish != null)
{
_log.LogError("Mark", "New", "Особенность блюда уже есть в списке.", $"RowGuid='{model.RowGuid}'");
return BadRequest();
}
int rez = await _service.UpdateMarkAsync(model);
if (rez > 0)
{
Mark rezMark = await _service.GetMarkAsync(model.RowGuid);
_log.LogInformation("Mark", "New", "Особенность добавлена.", $"особенность RowGuid={rezMark.RowGuid} добавлена.");
return Ok(rezMark);
}
return BadRequest();
}
// PUT: api/Mark
[HttpPut("Update")]
public async Task<ActionResult<Mark>> Put(Mark model)
{
Mark updateDish = await _service.GetMarkAsync(model.RowGuid);
if (updateDish == null)
{
_log.LogError("Mark", "Update", "Особенность для изменения не найдена.", $"RowGuid='{model.RowGuid}'");
return NotFound();
}
int rez = await _service.UpdateMarkAsync(model);
if (rez > 0)
{
Mark rezMark = await _service.GetMarkAsync(model.RowGuid);
_log.LogInformation("Mark", "Update", "Особенность изменена", $"особенность RowGuid={model.RowGuid} изменена.");
return Ok(rezMark);
}
return BadRequest();
}
// DELETE: api/Mark
[HttpDelete("Guid")]
public async Task<ActionResult> Delete(Guid MarkGuid)
{
Mark delMark = await _service.GetMarkAsync(MarkGuid);
if (delMark == null)
{
_log.LogError("Mark", "Delete", "Особенность для удаления не найдена.", $"RowGuid={MarkGuid}");
return NotFound();
}
int rez = await _service.DeleteMarksAsync(delMark);
_log.LogInformation("Mark", "Delete", "Особенность удалена", $"особенность RowGuid={delMark.RowGuid} удалена.");
return Ok();
}
}
} |
namespace com.Sconit.Web.Controllers.WMS
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.SYS;
using com.Sconit.Service;
using Telerik.Web.Mvc;
using System.Web.Routing;
using com.Sconit.Web.Models;
using com.Sconit.Utility;
using com.Sconit.Web.Models.SearchModels.WMS;
using com.Sconit.Entity.WMS;
using com.Sconit.Entity.Exception;
using com.Sconit.Service.Impl;
public class PickTaskController : WebAppBaseController
{
#region 拣货任务
private static string selectCountStatement = "select count(*) from PickTask as p";
private static string selectStatement = "select p from PickTask as p";
public IPickTaskMgr pickTaskMgr { get; set; }
#region 查询
[SconitAuthorize(Permissions = "Url_PickTask_View")]
public ActionResult Index()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="searchModel"></param>
/// <returns></returns>
[GridAction]
[SconitAuthorize(Permissions = "Url_PickTask_View")]
public ActionResult List(GridCommand command, PickTaskSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="searchModel"></param>
/// <returns></returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_PickTask_View")]
public ActionResult _AjaxList(GridCommand command, PickTaskSearchModel searchModel)
{
SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<PickTask>(searchStatementModel, command));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[SconitAuthorize(Permissions = "Url_PickTask_Edit")]
public ActionResult New()
{
return View();
}
/// <summary>
///
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[HttpGet]
[SconitAuthorize(Permissions = "Url_PickTask_Edit")]
public ActionResult Edit(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
PickTask pickSchedule = base.genericMgr.FindById<PickTask>(id);
return View(pickSchedule);
}
}
#endregion
#region 创建
[SconitAuthorize(Permissions = "Url_PickTask_New")]
public ActionResult _ShipPlanList(string flow, string orderNo)
{
ViewBag.isManualCreateDetail = false;
ViewBag.flow = flow;
ViewBag.orderNo = orderNo;
return PartialView();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_PickTask_New")]
public ActionResult _SelectBatchEditing(string orderNo, string flow)
{
IList<ShipPlan> shipPlanList = new List<ShipPlan>();
String sqlStatement = String.Empty;
if (!string.IsNullOrEmpty(flow) || !string.IsNullOrEmpty(orderNo))
{
if (!string.IsNullOrEmpty(orderNo))
{
sqlStatement = "select p from ShipPlan as p where p.OrderNo = '" + orderNo + "' ";
}
if (!string.IsNullOrEmpty(flow))
{
if (String.IsNullOrEmpty(sqlStatement))
{
sqlStatement = "select p from ShipPlan as p where p.Flow = '" + flow + "' ";
}
else
{
sqlStatement += " and p.Flow = '" + flow + "' ";
}
}
sqlStatement += " and p.PickQty < p.OrderQty";
shipPlanList = genericMgr.FindAll<ShipPlan>(sqlStatement);
}
return View(new GridModel(shipPlanList));
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
[SconitAuthorize(Permissions = "Url_PickTask_New")]
public JsonResult Create(String checkedShipPlans)
{
try
{
IDictionary<int, decimal> shipPlanIdAndQtyDic = new Dictionary<int, decimal>();
if (!string.IsNullOrEmpty(checkedShipPlans))
{
string[] idArray = checkedShipPlans.Split(',');
for (int i = 0; i < idArray.Count(); i++)
{
ShipPlan sp = genericMgr.FindById<ShipPlan>(Convert.ToInt32(idArray[i]));
shipPlanIdAndQtyDic.Add(sp.Id, sp.ToPickQty);
}
}
pickTaskMgr.CreatePickTask(shipPlanIdAndQtyDic);
//SaveSuccessMessage(Resources.WMS.PickTask.PickTask_Created);
object obj = new { SuccessMessage = string.Format(Resources.WMS.PickTask.PickTask_Created), SuccessData = checkedShipPlans };
return Json(obj);
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
return Json(null);
}
}
#endregion
#region 分派
[SconitAuthorize(Permissions = "Url_PickTask_Assign")]
public ActionResult Assign()
{
return View();
}
[SconitAuthorize(Permissions = "Url_PickTask_Assign")]
public ActionResult _PickTaskList(string pickGroupCode)
{
ViewBag.pickGroupCode = pickGroupCode;
return PartialView();
}
[GridAction]
[SconitAuthorize(Permissions = "Url_PickTask_Assign")]
public ActionResult _SelectAssignBatchEditing(string pickGroupCode)
{
IList<PickTask> pickTaskList = new List<PickTask>();
if (!string.IsNullOrEmpty(pickGroupCode))
{
string pickGroupSql = "select r from PickRule as r where r.PickGroupCode = ?";
IList<PickRule> pickRuleList = genericMgr.FindAll<PickRule>(pickGroupSql, pickGroupCode);
if (pickRuleList != null && pickRuleList.Count > 0)
{
string pickRuleSql = string.Empty;
IList<object> param = new List<object>();
foreach (PickRule r in pickRuleList)
{
if (string.IsNullOrEmpty(pickRuleSql))
{
pickRuleSql += "select p from PickTask as p where p.PickUserId is null and p.IsActive = ? and p.Location in (?";
param.Add(true);
param.Add(r.Location);
}
else
{
pickRuleSql += ",?";
param.Add(r.Location);
}
}
if (!string.IsNullOrEmpty(pickRuleSql))
{
pickRuleSql += ")";
}
pickTaskList = genericMgr.FindAll<PickTask>(pickRuleSql, param.ToList());
}
}
return View(new GridModel(pickTaskList));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
[SconitAuthorize(Permissions = "Url_PickTask_Assign")]
public ActionResult AssignPickTask(String checkedPickTasks, String assignUser)
{
try
{
//if (String.IsNullOrEmpty(checkedPickTasks))
//{
//}
//if(String.IsNullOrEmpty(assignUser))
//{
//}
IList<PickTask> pickTaskList = new List<PickTask>();
if (!string.IsNullOrEmpty(checkedPickTasks))
{
string[] idArray = checkedPickTasks.Split(',');
for (int i = 0; i < idArray.Count(); i++)
{
PickTask pt = genericMgr.FindAll<PickTask>("from PickTask where Id = ?", Convert.ToInt32(idArray[i])).SingleOrDefault();
pickTaskList.Add(pt);
}
}
pickTaskMgr.AssignPickTask(pickTaskList, assignUser);
SaveSuccessMessage(Resources.WMS.PickTask.PickTask_Assigned);
object obj = new { SuccessMessage = string.Format(Resources.WMS.PickTask.PickTask_Assigned, checkedPickTasks), SuccessData = checkedPickTasks };
return Json(obj);
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
return Json(null);
}
}
#endregion
#region private method
private SearchStatementModel PrepareSearchStatement(GridCommand command, PickTaskSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddEqStatement("PickUser", searchModel.PickUser, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Location", searchModel.Location, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "p", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("IsActive", searchModel.IsActive, "p", ref whereStatement, param);
if (searchModel.DateFrom != null)
{
HqlStatementHelper.AddGeStatement("CreateDate", searchModel.DateFrom, "p", ref whereStatement, param);
}
if (searchModel.DateTo != null )
{
HqlStatementHelper.AddLtStatement("CreateDate", searchModel.DateTo.Value.AddDays(1), "p", ref whereStatement, param);
}
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
private SearchStatementModel PrepareAssignSearchStatement(GridCommand command, PickTaskSearchModel searchModel)
{
string whereStatement = " where p.PickUserId is null ";
IList<object> param = new List<object>();
HqlStatementHelper.AddEqStatement("PickGroupCode", searchModel.PickGroup, "p", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
#endregion
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.LWRP;
using UnityEngine.Serialization;
namespace UnityEngine.Rendering.LWRP
{
public class pLab_Blit : ScriptableRendererFeature
{
[System.Serializable]
public class pLab_BlitSettings
{
public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
public Material material = null;
public int materialPassIndex = 0;
public string textureId = "_BlitPassTexture";
}
public pLab_BlitSettings settings = new pLab_BlitSettings();
RenderTargetHandle m_RenderTextureHandle;
pLab_BlitPass blitPass;
public override void Create(){
blitPass = new pLab_BlitPass(settings.renderPassEvent, settings.material);
}
public override void AddRenderPasses(ScriptableRenderer aRenderer, ref RenderingData aRenderinData) {
var source = aRenderer.cameraColorTarget;
var destination = RenderTargetHandle.CameraTarget;
blitPass.Setup(source, destination);
aRenderer.EnqueuePass(blitPass);
}
}
} |
using System.Collections.Generic;
using Chess.Data.Entities;
namespace ChessSharp.Web.Models
{
public class GameModel
{
public long Id { get; set; }
public BoardViewModel Board { get; set; }
public PlayerViewModel PlayerLight { get; set; }
public PlayerViewModel PlayerDark { get; set; }
public PlayerViewModel Winner { get; set; }
public string Name { get; set; }
public int LightScore { get; set; }
public int DarkScore { get; set; }
public int MoveCount { get; set; }
public bool IsCurrentPlayersMove { get; set; }
public bool Complete { get; set; }
public List<Move> Moves { get; set; }
public GameModel()
{
Board = new BoardViewModel();
Moves = new List<Move>();
}
}
} |
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.VariablePlantilla
{
/// <summary>
/// Modelo de vista Variable Plantilla Lista Formulario
/// </summary>
/// <remarks>
/// Creación: GMD 20150709
/// Modificación:
/// </remarks>
public class VariablePlantillaListaFormulario : GenericViewModel
{
#region Propiedades
/// <summary>
/// Lista de opciones de Variable
/// </summary>
public VariableListaResponse VariableLista { get; set; }
#endregion
/// <summary>
/// Constructor de la Clase
/// </summary>
public VariablePlantillaListaFormulario(string codigoVariable)
{
this.VariableLista = new VariableListaResponse();
if (codigoVariable != null && codigoVariable != "" && codigoVariable != "00000000-0000-0000-0000-000000000000")
{
this.VariableLista.CodigoVariable = new Guid(codigoVariable);
}
}
/// <summary>
/// Constructor de la Clase
/// </summary>
public VariablePlantillaListaFormulario(VariableListaResponse variableListaResponse)
{
this.VariableLista = variableListaResponse;
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AHAO.TPLMS.Entitys
{
public class Module
{
public Module()
{
this.CascadeId = string.Empty;
this.Name = string.Empty;
this.Url = string.Empty;
this.HotKey = string.Empty;
this.ParentId = 0;
this .IconName = string.Empty;
this.Status = 0;
this .ParentName = string.Empty;
this .Vector = string.Empty;
this.SortNo = 0;
}
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(255)]
public string CascadeId { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[StringLength(255)]
public string Url { get; set; }
[StringLength(255)]
public string HotKey { get; set; }
public int ParentId { get; set; }
public bool IsLeaf { get; set; }
public bool IsAutoExpand { get; set; }
[StringLength(255)]
public string IconName { get; set; }
public int Status { get; set; }
[Required]
[StringLength(255)]
public string ParentName { get; set; }
[StringLength(255)]
public string Vector { get; set; }
public int SortNo { get; set; }
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.Core;
namespace MyLoadTest.LoadRunnerSvnAddin.Commands
{
public class UnignoreCommand : SubversionCommand
{
protected override void Run(string fileName)
{
using (var client = new SvnClientWrapper())
{
var propertyValue = client.GetPropertyValue(Path.GetDirectoryName(fileName), "svn:ignore");
if (propertyValue != null)
{
var watcher = WatchProjects();
var shortFileName = Path.GetFileName(fileName);
var b = new StringBuilder();
using (var r = new StringReader(propertyValue))
{
string line;
while ((line = r.ReadLine()) != null)
{
if (!string.Equals(line, shortFileName, StringComparison.OrdinalIgnoreCase))
{
b.AppendLine(line);
}
}
}
client.SetPropertyValue(Path.GetDirectoryName(fileName), "svn:ignore", b.ToString());
MessageService.ShowMessageFormatted("${res:AddIns.Subversion.ItemRemovedFromIgnoreList}", shortFileName);
watcher.Callback();
}
}
}
}
} |
using Podemski.Musicorum.Dao.Entities;
using Podemski.Musicorum.Interfaces.Entities;
using Podemski.Musicorum.Interfaces.Factories;
namespace Podemski.Musicorum.Dao.Factories
{
internal sealed class ArtistFactory : IArtistFactory
{
public IArtist Create(string name)
{
return new Artist { Name = name };
}
}
}
|
using System;
namespace Task_1
{
class Matrix2
{
public double A11 { get; set; }
public double A12 { get; set; }
public double A21 { get; set; }
public double A22 { get; set; }
public Matrix2(double a11, double a12, double a21, double a22)
{
A11 = a11;
A12 = a12;
A21 = a21;
A22 = a22;
}
public Matrix2(double a11, double a22)
{
A11 = a11;
A12 = 0;
A21 = 0;
A22 = a22;
}
public Matrix2(Matrix2 matrix2)
{
A11 = matrix2.A11;
A12 = matrix2.A12;
A21 = matrix2.A21;
A22 = matrix2.A22;
}
public Matrix2() { }
public static double Det(Matrix2 matrix2)
{
return matrix2.A11 * matrix2.A22 - matrix2.A12 * matrix2.A21;
}
public static Matrix2 Inverse(Matrix2 matrix2)
{
return Transpose(new Matrix2(matrix2.A22, -matrix2.A21, -matrix2.A12, matrix2.A11)) / Det(matrix2);
}
public static Matrix2 Transpose(Matrix2 matrix2)
{
return new Matrix2(matrix2.A11, matrix2.A21, matrix2.A12, matrix2.A22);
}
public static Matrix2 operator +(Matrix2 first, Matrix2 second)
{
return new Matrix2(first.A11 + second.A11, first.A12 + second.A12, first.A21 + second.A21, first.A22 + second.A22);
}
public static Matrix2 operator -(Matrix2 first, Matrix2 second)
{
return new Matrix2(first.A11 - second.A11, first.A12 - second.A12, first.A21 - second.A21, first.A22 - second.A22);
}
public static Matrix2 operator *(Matrix2 first, Matrix2 second)
{
Matrix2 result = new Matrix2()
{
A11 = first.A11 * second.A11 + first.A12 * second.A21,
A12 = first.A11 * second.A12 + first.A12 * second.A22,
A21 = first.A21 * second.A11 + first.A22 * second.A21,
A22 = first.A21 * second.A12 + first.A22 * second.A22
};
return result;
}
public static Matrix2 operator /(Matrix2 first, Matrix2 second)
{
return first * Inverse(second);
}
public static Matrix2 operator *(Matrix2 matrix2, double value)
{
return new Matrix2(matrix2.A11 * value, matrix2.A12 * value, matrix2.A21 * value, matrix2.A22 * value);
}
public static Matrix2 operator /(Matrix2 matrix2, double value)
{
if (value == 0)
throw new DivideByZeroException();
return new Matrix2(matrix2.A11 / value, matrix2.A12 / value, matrix2.A21 / value, matrix2.A22 / value);
}
public static Matrix2 operator *(double value, Matrix2 matrix2)
{
return new Matrix2(matrix2.A11 * value, matrix2.A12 * value, matrix2.A21 * value, matrix2.A22 * value);
}
public override string ToString()
{
return $"{A11}\t{A12}\n{A21}\t{A22}";
}
public static bool operator true(Matrix2 matrix2)
{
return Det(matrix2) > 0;
}
public static bool operator false(Matrix2 matrix2)
{
return Det(matrix2) <= 0;
}
public static bool operator |(Matrix2 first, Matrix2 second)
{
return Det(first) > 0 | Det(second) > 0;
}
public static bool operator &(Matrix2 first, Matrix2 second)
{
return Det(first) > 0 & Det(second) > 0;
}
}
} |
using IRAP.Global;
namespace IRAP.Entities.FVS
{
/// <summary>
/// 生产工单监控信息
/// </summary>
public class PWOSurveillance
{
Quantity pwOrderQuantity = new Quantity();
Quantity wipQuantity = new Quantity();
Quantity scrapedQuantity = new Quantity();
/// <summary>
/// 生产工单号
/// </summary>
public string PWONo { get; set; }
/// <summary>
/// 制造订单号
/// </summary>
public string MONumber { get; set; }
/// <summary>
/// 制造订单行号
/// </summary>
public int MOLineNo { get; set; }
/// <summary>
/// 产品编号
/// </summary>
public string ProductNo { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 生产批号
/// </summary>
public string LotNumber { get; set; }
/// <summary>
/// 生产工单数量
/// </summary>
public long PWOrderQty
{
get { return pwOrderQuantity.IntValue; }
set { pwOrderQuantity.IntValue = value; }
}
/// <summary>
/// 在制品数量
/// </summary>
public long WIPQty
{
get { return wipQuantity.IntValue; }
set { wipQuantity.IntValue = value; }
}
/// <summary>
/// 在制品容器编号
/// </summary>
public string ContainerNo { get; set; }
/// <summary>
/// 工位累计加工时间(min)
/// </summary>
public int StationMFGTime { get; set; }
/// <summary>
/// 工段制程时间(min)
/// </summary>
public int ThroughPutTime { get; set; }
/// <summary>
/// 累计制造周期时间(min)
/// </summary>
public int AccumMCT { get; set; }
/// <summary>
/// 废品数量
/// </summary>
public long ScrapedQty
{
get { return scrapedQuantity.IntValue; }
set { scrapedQuantity.IntValue = value; }
}
/// <summary>
/// 一次性通过率(%)
/// </summary>
public double FPYPercentage { get; set; }
/// <summary>
/// 滞在工位代码
/// </summary>
public string AtStationCode { get; set; }
/// <summary>
/// 滞在工位名称
/// </summary>
public string AtStationName { get; set; }
/// <summary>
/// 放大数量级
/// </summary>
public int Scale
{
get { return pwOrderQuantity.Scale; }
set
{
pwOrderQuantity.Scale = value;
wipQuantity.Scale = value;
scrapedQuantity.Scale = value;
}
}
/// <summary>
/// 计量单位
/// </summary>
public string UnitOfMeasure
{
get { return pwOrderQuantity.UnitOfMeasure; }
set
{
pwOrderQuantity.UnitOfMeasure = value;
wipQuantity.UnitOfMeasure = value;
scrapedQuantity.UnitOfMeasure = value;
}
}
/// <summary>
/// 滞在工位叶标识
/// </summary>
public int T107LeafID { get; set; }
/// <summary>
/// 产品实体标识
/// </summary>
public int T102EntityID { get; set; }
/// <summary>
/// 产品叶标识
/// </summary>
public int T102LeafID { get; set; }
/// <summary>
/// 工序叶标识
/// </summary>
public int T216LeafID { get; set; }
public PWOSurveillance Clone()
{
PWOSurveillance rlt = MemberwiseClone() as PWOSurveillance;
rlt.pwOrderQuantity = pwOrderQuantity.Clone();
rlt.wipQuantity = wipQuantity.Clone();
rlt.scrapedQuantity = scrapedQuantity.Clone();
return rlt;
}
}
} |
using System.Collections.Generic;
using Discord;
using Discord.WebSocket;
using JhinBot.DiscordObjects;
using JhinBot.Utils;
namespace JhinBot.Services
{
public class UserAuditLogService : IUserAuditLogService
{
private readonly DiscordSocketClient _client;
private readonly IEmbedService _embedService;
private readonly IResourceService _resourceService;
private readonly IBotConfig _botConfig;
public EmbedBuilder UserJoinedEmbed(SocketGuildUser guildUser)
{
return _embedService.CreateInfoEmbed(
"event_user_joined_title",
"event_user_info_desc",
guildUser,
guildUser.Username,
guildUser.Discriminator,
guildUser.Id.ToString()
);
}
public EmbedBuilder UserLeftEmbed(SocketGuildUser guildUser)
{
return _embedService.CreateInfoEmbed(
"event_user_left_title",
"event_user_info_desc",
guildUser,
guildUser.Username,
guildUser.Discriminator,
guildUser.Id.ToString()
);
}
public EmbedBuilder UserBannedEmbed(SocketUser guildUser)
{
return _embedService.CreateInfoEmbed(
"event_user_banned_title",
"event_user_info_desc",
guildUser,
guildUser.Username,
guildUser.Discriminator,
guildUser.Id.ToString()
);
}
public EmbedBuilder UserUnbannedEmbed(SocketUser guildUser)
{
return _embedService.CreateInfoEmbed(
"event_user_unbanned_title",
"event_user_info_desc",
guildUser,
guildUser.Username,
guildUser.Discriminator,
guildUser.Id.ToString()
);
}
public EmbedBuilder MessageReceivedEmbed(SocketMessage message)
{
var list = new List<(string, string)>
{
("Message content", message.Content)
};
return _embedService.CreateEmbedWithList(
"event_msg_received_title",
_botConfig.InfoColor,
list,
message.Author,
"event_user_with_msg_info_desc",
"",
message.Author.Username,
message.Author.Discriminator,
message.Author.Id.ToString(),
message.Id.ToString(),
message.Channel.Id.ToString(),
message.Content
);
}
public EmbedBuilder MessageDeletedEmbed(IMessage message, SocketGuildChannel channel)
{
var list = new List<(string, string)>
{
("Deleted message", message.Content)
};
return _embedService.CreateEmbedWithList(
"event_msg_deleted_title",
_botConfig.InfoColor,
list,
message.Author,
"event_user_with_msg_info_desc",
"",
message.Author.Username,
message.Author.Discriminator,
message.Author.Id.ToString(),
message.Id.ToString(),
channel.Id.ToString()
);
}
public EmbedBuilder MessageUpdatedEmbed(IMessage oldMessage, SocketMessage updatedMessage, SocketGuildChannel channel)
{
var list = new List<(string, string)>
{
("Previous message", oldMessage.Content),
("Updated message", updatedMessage.Content)
};
return _embedService.CreateEmbedWithList(
"event_msg_updated_title",
_botConfig.InfoColor,
list,
updatedMessage.Author,
"event_user_with_msg_info_desc",
"",
updatedMessage.Author.Username,
updatedMessage.Author.Discriminator,
updatedMessage.Author.Id.ToString(),
updatedMessage.Id.ToString(),
channel.Id.ToString()
);
}
public EmbedBuilder NicknameUpdatedEmbed(SocketGuildUser oldUser, SocketGuildUser updatedUser)
{
var list = new List<(string, string)>
{
("Previous nickname", oldUser.Nickname),
("Updated nickname", updatedUser.Nickname)
};
return _embedService.CreateEmbedWithList(
"event_nickname_updated_title",
_botConfig.InfoColor,
list,
updatedUser,
"event_variable_updated_desc",
"",
updatedUser.Username,
updatedUser.Discriminator,
updatedUser.Id.ToString(),
"nickname"
);
}
public EmbedBuilder UsernameUpdatedEmbed(SocketUser updatedUser, SocketUser oldUser)
{
var list = new List<(string, string)>
{
("Previous username", oldUser.Username),
("Updated username", updatedUser.Username)
};
return _embedService.CreateEmbedWithList(
"event_username_updated_title",
_botConfig.InfoColor,
list,
updatedUser,
"event_variable_updated_desc",
"",
updatedUser.Username,
updatedUser.Discriminator,
updatedUser.Id.ToString(),
"username"
);
}
public EmbedBuilder UserAvatarUpdatedEmbed(SocketUser updatedUser, SocketUser oldUser)
{
var list = new List<(string, string)>
{
("Previous avatar", oldUser.GetAvatarUrl()),
("Updated avatar", updatedUser.GetAvatarUrl())
};
return _embedService.CreateEmbedWithList(
"event_avatar_updated_title",
_botConfig.InfoColor,
list,
updatedUser,
"event_variable_updated_desc",
"",
updatedUser.Username,
updatedUser.Discriminator,
updatedUser.Id.ToString(),
"avatar"
);
}
public UserAuditLogService(DiscordSocketClient client, IEmbedService embedService, IResourceService resourceService, IBotConfig botConfig)
{
_client = client;
_embedService = embedService;
_resourceService = resourceService;
_botConfig = botConfig;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ppedv.Planner.Logic;
using ppedv.Planner.Model;
using ppedv.Planner.UI.Web.Models;
namespace ppedv.Planner.UI.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MitarbeiterAPIController : ControllerBase
{
Core core = new Core();
// GET: api/MitarbeiterAPI
[HttpGet]
public IEnumerable<MitarbeiterAPI> Get()
{
foreach (var m in core.Repository.GetAll<Mitarbeiter>())
{
yield return new MitarbeiterAPI() { Id = m.Id, Name = m.Name, PNummer = m.PersonalNummer };
}
}
// GET: api/MitarbeiterAPI/5
[HttpGet("{id}", Name = "Get")]
public MitarbeiterAPI Get(int id)
{
var m = core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id);
return new MitarbeiterAPI() { Id = m.Id, Name = m.Name, PNummer = m.PersonalNummer };
}
// POST: api/MitarbeiterAPI
[HttpPost]
public void Post([FromBody] MitarbeiterAPI m)
{
core.Repository.Add(new Mitarbeiter() { Name = m.Name, PersonalNummer = m.PNummer });
core.Repository.SaveChanges();
}
// PUT: api/MitarbeiterAPI/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] MitarbeiterAPI m)
{
var update = new Mitarbeiter() {Id =m.Id, Name = m.Name, PersonalNummer = m.PNummer };
core.Repository.Update(update);
core.Repository.SaveChanges();
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
var m = core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id);
core.Repository.Delete(m);
core.Repository.SaveChanges();
}
}
}
|
namespace iPhoneController.Deployment
{
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iPhoneController.Diagnostics;
using iPhoneController.Extensions;
using iPhoneController.Models;
using iPhoneController.Utils;
public class AppDeployer
{
#region Variables
private static readonly IEventLogger _logger = EventLogger.GetLogger("IPA-DEPLOY");
private readonly string _developer;
private readonly string _provisioningProfile;
#endregion
#region Properties
public string SignedReleaseFileName { get; private set; }
public bool ResignApp { get; set; }
#endregion
#region Events
internal event EventHandler<DeployEventArgs> DeployCompleted;
private void OnDeployCompleted(Device device, bool success)
{
DeployCompleted?.Invoke(this, new DeployEventArgs(device, success));
}
#endregion
#region Constructor
public AppDeployer(string developer, string provisioningProfile)
{
if (string.IsNullOrEmpty(developer))
{
throw new ArgumentNullException(developer, "Developer cannot be empty");
}
_developer = developer;
if (string.IsNullOrEmpty(provisioningProfile))
{
throw new ArgumentNullException(provisioningProfile, "provisioning profile cannot be empty");
}
_provisioningProfile = provisioningProfile;
ResignApp = true;
}
#endregion
#region Public Methods
public bool Resign(string megaLink, string version)
{
var fileName = $"J{version}.ipa";
var releaseName = Path.Combine(Strings.ReleasesFolder, fileName);
var releaseNameSigned = Path.Combine(
Strings.ReleasesFolder,
Path.GetFileNameWithoutExtension(fileName) + "Signed.ipa"
);
SignedReleaseFileName = releaseNameSigned;
if (File.Exists(releaseName))
{
// Already exists
_logger.Info($"Latest ipa already downloaded, skipping...");
}
else
{
// Download new version
_logger.Info($"Downloading IPA from {megaLink} to {releaseName}");
if (!DownloadFile(megaLink, releaseName))
{
_logger.Warn($"Failed to download IPA from {megaLink}, is megatools installed?");
return false;
}
}
if (File.Exists(releaseNameSigned))
{
_logger.Info($"Signed IPA of latest already exists!");
// Already exists
return true;
}
var result = InternalResignApp(releaseName, releaseNameSigned);
if (!result)
{
_logger.Error($"Unknown error occurred while resigning ipa file {releaseName}");
}
//Deploy(releaseNameSigned, Strings.All);
return result;
}
public void Deploy(string appPath, string deviceNames = Strings.All)
{
var successful = new List<string>();
var failed = new List<string>();
var devices = Device.GetAll();
var deployAppDevices = new List<string>(deviceNames.RemoveSpaces());
if (string.Compare(deviceNames, Strings.All, true) == 0)
{
deployAppDevices = devices.Keys.ToList();
}
_logger.Info($"Deploying app {appPath} to {string.Join(", ", deployAppDevices)}");
Parallel.ForEach(deployAppDevices, deviceName =>
{
if (!devices.ContainsKey(deviceName))
{
_logger.Warn($"{deviceName} does not exist in device list, skipping deploy pogo.");
}
else
{
var device = devices[deviceName];
var args = $"--id {device.Uuid} --bundle {appPath}";
_logger.Info($"Deploying to device {device.Name} ({device.Uuid})...");
var output = Shell.Execute("ios-deploy", args, out var exitCode, true);
var success = output.ToLower().Contains($"[100%] installed package {appPath}") ||
output.ToLower().Contains("100%");
OnDeployCompleted(device, success);
}
});
}
public static string GetLatestAppPath()
{
var files = Directory.GetFiles(Strings.ReleasesFolder, "*.ipa", SearchOption.TopDirectoryOnly)
.Where(x => x.ToLower().Contains("signed"))
.ToList();
// Sort descending
files.Sort((a, b) => b.CompareTo(a));
return files.FirstOrDefault();
}
#endregion
#region Private Methods
private bool InternalResignApp(string ipaPath, string ipaPathSigned)
{
_logger.Info($"Beginning to resign {ipaPath}");
var outDir = Path.Combine(Path.GetTempPath(), "app");
var payloadDir = Path.Combine(outDir, "Payload");
// Create temp directory we'll be doing everything in
CreateTempDirectory(outDir);
// Unzip ipa file
ZipFile.ExtractToDirectory(ipaPath, outDir, true);
var appDir = Directory.GetDirectories(payloadDir, "*.app").FirstOrDefault();
var appDirName = Path.GetFileName(appDir);
var pogoDir = Path.Combine(payloadDir, appDirName);
var pogoInfoPlist = Path.Combine(pogoDir, "Info.plist");
// Delete __MACOSX folder
var macosxFolder = Path.Combine(outDir, "__MACOSX");
DeleteMacOsxFolder(macosxFolder);
// Remove NSAllowsArbitraryLoadsInWebContent
if (!RemoveNSAllowsArbitraryLoadsInWebContent(pogoInfoPlist))
{
_logger.Warn($"Failed to remove NSAllowsArbitraryLoadsInWebContent plist entry from Info.plist");
}
// Copy provisioning profile to payload folder
_logger.Info($"Copying provisioning profile to payload folder");
var provisioningProfilePath = Path.Combine(Strings.ProfilesFolder, _provisioningProfile);
File.Copy(provisioningProfilePath, $"{pogoDir}/embedded.mobileprovision", true);
// Extra provisioning profile entitlements
_logger.Info($"Signing mobile provisioning profile...");
var provisioningPath = Path.Combine(Path.GetDirectoryName(outDir), "provisioning.plist");
var provisioningData = Shell.Execute("/usr/bin/security", $"cms -D -i {pogoDir}/embedded.mobileprovision", out var _);
File.WriteAllText(provisioningPath, provisioningData);
_logger.Info($"Extracting entitlements from mobileprovisioning profile...");
var entitlementsPath = Path.Combine(Path.GetDirectoryName(outDir), "entitlements.plist");
var entitlementsData = Shell.Execute(Strings.PlistBuddyPath, $@"-x -c ""Print:Entitlements"" {provisioningPath}", out var _);
File.WriteAllText(entitlementsPath, entitlementsData);
// Get list of compenents for resigning
_logger.Info($"Getting list of compenents for resigning with {_developer}");
SignComponents(outDir, entitlementsPath);
// Copy custom config
var configPath = Path.Combine(Strings.ReleasesFolder, "config/config.json");
var destinationConfigPath = Path.Combine(pogoDir, "config.json");
CopyConfig(configPath, destinationConfigPath);
// Sign frameworks and dynamic libraries
var frameworksPath = Path.Combine(pogoDir, "Frameworks");
SignFrameworks(frameworksPath);
// Zip payload folder
_logger.Info("Zipping payload folder...");
var signedPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".zip");
ZipFile.CreateFromDirectory(outDir, signedPath);
// Move signed IPA to releases folder
_logger.Info($"Moving signed IPA file to releases folder...");
File.Move(signedPath, ipaPathSigned);
// Cleanup and remove temp folder
_logger.Info($"Deleting temp folder {outDir}...");
Directory.Delete(outDir, true);
File.Delete(provisioningPath);
File.Delete(entitlementsPath);
_logger.Info($"Your ipa has been signed into {ipaPathSigned}");
return true;
}
private void Codesign(string file, bool isContinued = false, string entitlementsPath = null)
{
var sb = new StringBuilder();
if (isContinued) sb.Append("--continue ");
sb.Append("-f -s ");
sb.Append($@"""{_developer}"" ");
sb.Append("--generate-entitlement-der ");
if (!string.IsNullOrEmpty(entitlementsPath))
sb.Append($"--entitlements {entitlementsPath} ");
sb.Append(file);
var result = Shell.Execute(Strings.CodesignPath, sb.ToString(), out var _);
//_logger.Debug($"Codesign result for {file}: {result}");
}
private void SignComponents(string appPath, string entitlementsPath)
{
var files = GetComponentFiles(appPath);
foreach (var file in files)
{
_logger.Debug($"Signing component {file}...");
Codesign(file, true, entitlementsPath);
}
}
private void SignFrameworks(string frameworksPath)
{
var frameworkFiles = Directory.GetFiles(frameworksPath);
_logger.Info($"Signing frameworks...");
foreach (var frameworkFile in frameworkFiles)
{
_logger.Debug($"Signing framework {frameworkFile}");
Codesign(frameworkFile);
}
}
private static void DeleteMacOsxFolder(string macosxFolder)
{
if (Directory.Exists(macosxFolder))
{
Directory.Delete(macosxFolder, true);
}
}
private static void CopyConfig(string sourcePath, string destinationPath)
{
if (File.Exists(sourcePath))
{
_logger.Info($"Copying custom config to payload folder.");
File.Copy(sourcePath, destinationPath);
}
else
{
_logger.Warn($"No custom config.json file found at {sourcePath}");
}
}
private static bool DownloadFile(string megaLink, string destinationPath)
{
var result = Shell.Execute("megadl", $"{megaLink} --path={destinationPath}", out var megadlExitCode);
return megadlExitCode == 0 || (result?.ToLower().Contains("downloaded") ?? false);
}
private static bool RemoveNSAllowsArbitraryLoadsInWebContent(string infoPlist)
{
try
{
var allowsArbitraryLoadsResult = Shell.Execute(Strings.PlistBuddyPath, $@"-c ""Delete :NSAppTransportSecurity"" {infoPlist}", out var _);
_logger.Debug($"Remove 'AllowsArbitraryLoadsInWebContent result: {allowsArbitraryLoadsResult}");
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
return false;
}
}
private static List<string> GetComponentFiles(string path)
{
var frameworkFiles = Directory.GetDirectories(path, "*.framework", SearchOption.AllDirectories);
var dylibFiles = Directory.GetFiles(path, "*.dylib", SearchOption.AllDirectories);
var appFiles = Directory.GetDirectories(path, "*.app", SearchOption.AllDirectories);
var appexFiles = Directory.GetDirectories(path, "*.appex", SearchOption.AllDirectories);
var list = new List<string>();
list.AddRange(frameworkFiles);
list.AddRange(dylibFiles);
list.AddRange(appFiles);
list.AddRange(appexFiles);
return list;
}
private static void CreateTempDirectory(string tempDir)
{
if (!Directory.Exists(tempDir))
{
_logger.Info($"Creating temp build directory: {tempDir}");
Directory.CreateDirectory(tempDir);
}
}
#endregion
}
internal class DeployEventArgs : EventArgs
{
public Device Device { get; set; }
public bool Success { get; set; }
internal DeployEventArgs(Device device, bool success)
{
Device = device;
Success = success;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ubicacion.Domain.ModelS
{
public class Punto
{
public int ID { get; set; }
public string Latitud { get; set; }
public string Longitud { get; set; }
public string Descripcion { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace PlanMGMT.View
{
/// <summary>
/// TaskRunLog.xaml 的交互逻辑
/// </summary>
public partial class TaskRunLog : Window
{
public Int64 ID { get; set; }
public TaskRunLog()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window_Loaded);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
((ViewModel.SysLogViewModel)base.DataContext).LoadCommand.Execute(ID);
}
/// <summary>
/// 窗体移动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
this.DragMove();
}
}
/// <summary>
/// 窗体关闭
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Menu : MonoBehaviour {
public static bool isTutorial = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (OVRInput.GetDown(OVRInput.RawButton.Y))
{
LoadGame();
}
if (OVRInput.GetDown(OVRInput.RawButton.X))
{
QuitGame();
}
if (OVRInput.GetDown(OVRInput.RawButton.A))
{
TutorialMode();
}
}
public void LoadGame()
{
Debug.Log("Loading Game...");
isTutorial = false;
Tutorial.isTutorial3 = true;
Time.timeScale = 1f;
Score.scoreValue = 0;
GameOver.isGameOver = false;
SceneManager.LoadScene("CS498HW4");
}
public void TutorialMode()
{
Debug.Log("Loading Tutorial Mode");
isTutorial = true;
Tutorial.isTutorial3 = false;
Time.timeScale = 1f;
Score.scoreValue = 0;
GameOver.isGameOver = false;
SceneManager.LoadScene("CS498HW4");
}
public void QuitGame()
{
Debug.Log("Quiting Game...");
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
|
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CronScheduler.Extensions.Scheduler;
using Microsoft.Extensions.Hosting;
namespace CronScheduler.Extensions.Internal;
/// <summary>
/// The implementation for <see cref="BackgroundService"/> service.
/// </summary>
internal class SchedulerHostedService : BackgroundService
{
private readonly TaskFactory _taskFactory = new TaskFactory(TaskScheduler.Current);
private readonly ISchedulerRegistration _registrations;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerHostedService"/> class.
/// </summary>
/// <param name="registrations"></param>
public SchedulerHostedService(ISchedulerRegistration registrations)
{
_registrations = registrations ?? throw new ArgumentNullException(nameof(registrations));
}
public event EventHandler<UnobservedTaskExceptionEventArgs>? UnobservedTaskException;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ExecuteOnceAsync(stoppingToken);
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
private async Task ExecuteOnceAsync(CancellationToken stoppingToken)
{
var referenceTime = DateTimeOffset.UtcNow;
var scheduledTasks = _registrations.Jobs.Values;
var tasksThatShouldRun = scheduledTasks.Where(t => t.ShouldRun(referenceTime)).ToList();
foreach (var taskThatShouldRun in tasksThatShouldRun)
{
taskThatShouldRun.Increment();
#pragma warning disable CA2008 // Do not create tasks without passing a TaskScheduler
await _taskFactory.StartNew(
async () =>
{
try
{
await taskThatShouldRun.ScheduledJob.ExecuteAsync(stoppingToken);
}
catch (Exception ex)
{
var args = new UnobservedTaskExceptionEventArgs(
ex as AggregateException ?? new AggregateException(ex));
UnobservedTaskException?.Invoke(this, args);
if (!args.Observed)
{
throw;
}
}
},
stoppingToken);
#pragma warning restore CA2008 // Do not create tasks without passing a TaskScheduler
}
}
}
|
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Infra.Data.EntityConfig
{
public class ProcuracaoEscrituraConfig: EntityTypeConfiguration<ProcuracaoEscritura>
{
public ProcuracaoEscrituraConfig()
{
HasKey(p => p.ProcuracaoEscrituraId);
Property(p => p.ProcuracaoEscrituraId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.IdEscritura)
.IsOptional();
Property(p => p.Data)
.HasColumnType("Date");
Property(p => p.Livro)
.HasMaxLength(20);
Property(p => p.Folhas)
.HasMaxLength(10);
Property(p => p.Ato)
.HasMaxLength(10);
Property(p => p.Selo)
.HasMaxLength(9);
Property(p => p.Aleatorio)
.HasMaxLength(3);
Property(p => p.Outorgantes)
.HasMaxLength(600);
Property(p => p.Outorgados)
.HasMaxLength(600);
Property(p => p.Lavrado)
.HasMaxLength(1);
Property(p => p.Serventia)
.HasMaxLength(150);
Property(p => p.UfOrigem)
.HasMaxLength(2);
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using VoxelSpace.Resources;
namespace VoxelSpace.UI {
public class TileFont : IDisposable {
public Texture2D Texture { get; private set; }
public TileFontMaterial Material { get; private set; }
public float CharSpacing { get; private set; }
public float SpaceWidth { get; private set; }
public float Baseline { get; private set; }
public float LineSpacing {get; private set; }
public int _tileWidth;
public int _tileHeight;
int[] _charWidth;
Vector2 _tileSize;
static readonly Vector2 _tileUVSize = new Vector2(1 / 16f, 1 / 8f);
public TileFont(Texture2D texture, float charSpacing, float spaceWidth, float baseline, float lineSpacing) {
Texture = texture;
Material = new TileFontMaterial();
Material.Texture = Texture;
_charWidth = new int[128];
_tileSize.X = _tileWidth = Texture.Width / 16;
_tileSize.Y = _tileHeight = Texture.Height / 8;
Material.Size = _tileSize;
SpaceWidth = spaceWidth;
CharSpacing = charSpacing;
Baseline = baseline;
LineSpacing = lineSpacing;
var pixels = new Color[Texture.Width * Texture.Height];
Texture.GetData(pixels);
int j = _tileHeight - 1;
for (int ti = 0; ti < 16; ti ++) {
for (int tj = 0; tj < 8; tj ++) {
int charWidth = 0;
for (int i = 0; i < _tileWidth; i ++) {
var color = pixels[ti * _tileWidth + i + (tj * _tileHeight + j) * Texture.Width];
if (color.A == 0) {
break;
}
else {
charWidth ++;
}
}
_charWidth[ti + tj * 16] = charWidth;
}
}
}
public void DrawString(UI ui, Matrix projection, Vector2 position, string text, Color color, HorizontalAlign halign = HorizontalAlign.Left, VerticalAlign valign = VerticalAlign.Top) {
position.Floor();
Material.ProjectionMatrix = projection;
Material.Tint = color;
if (valign != VerticalAlign.Top) {
float height = getTextHeight(text);
if (valign == VerticalAlign.Middle) {
height = (int) height / 2;
}
position.Y -= height;
}
int i = 0;
while (i < text.Length) {
drawLine(ui, position, text, ref i, halign);
position.Y += Baseline + LineSpacing;
}
}
void drawLine(UI ui, Vector2 position, string text, ref int i, HorizontalAlign halign) {
if (halign != HorizontalAlign.Left) {
int wi = i;
var width = getLineWidth(text, ref wi);
if (halign == HorizontalAlign.Center) {
width = (int) width / 2;
}
position.X -= width;
}
while (i < text.Length) {
var c = GetCharacterIndex(text[i]);
if (c == -1) {
i ++;
break;
}
else {
if (c == 32) {
// space
position.X += SpaceWidth;
}
else {
Material.Position = position;
var uv = new Vector2(1/16f, 1/8f);
uv.X *= c % 16;
uv.Y *= c / 16;
Material.UVOffset = uv;
position.X += CharSpacing + _charWidth[c];
Material.Bind();
Primitives.DrawQuad();
}
}
i ++;
}
}
float getTextHeight(string text) {
float height = 1;
for (int i = 0; i < text.Length; i ++) {
if (text[i] == '\n'){
height ++;
}
}
return height * Baseline + (height - 1) * LineSpacing;
}
float getLineWidth(string text, ref int i, int end = - 1) {
float width = 0;
if (end == -1) {
end = text.Length;
}
while (i < end) {
var c = GetCharacterIndex(text[i]);
if (c == -1) {
i ++;
break;
}
else {
if (c == 32) {
width += SpaceWidth;
}
else {
width += CharSpacing + _charWidth[c];
}
}
i ++;
}
return width;
}
public float GetLineWidth(string text, int start = 0, int end = -1) {
return getLineWidth(text, ref start, end);
}
public Rect GetCharacterRect(Vector2 position, string text, int index, HorizontalAlign halign, VerticalAlign valign) {
Rect r = new Rect();
r.Position = getCharacterPosition(position, text, index, halign, valign);
r.Size.Y = Baseline;
if (index == text.Length) {
r.Size.X = _charWidth[0];
}
else {
if (text[index] == ' ') {
r.Size.X = SpaceWidth;
}
else {
int ci = GetCharacterIndex(text[index]);
if (ci == -1) {
ci = 0;
}
r.Size.X = _charWidth[ci];
}
}
return r;
}
/// <summary>
/// Get the position of the upper left corner of a glyph when drawing text at a certain position with a certain alignment
/// </summary>
/// <param name="position">The position to draw the text</param>
/// <param name="text">The text to draw</param>
/// <param name="index">The index of the character in question</param>
/// <returns></returns>
Vector2 getCharacterPosition(Vector2 position, string text, int index, HorizontalAlign halign, VerticalAlign valign) {
int line = 0;
int lineStart = 0;
for (int i = 0; i <= index && i < text.Length; i ++) {
if (text[i] == '\n') {
line ++;
lineStart = i + 1;
}
}
float height = getTextHeight(text);
int start = lineStart;
float width = getLineWidth(text, ref start, index);
start = lineStart;
float lineWidth = getLineWidth(text, ref start);
position.Y += line * (Baseline + LineSpacing);
switch (valign) {
case VerticalAlign.Middle:
position.Y -= (int) height / 2;
break;
case VerticalAlign.Bottom:
position.Y -= height;
break;
}
position.X += width;
switch (halign) {
case HorizontalAlign.Center:
position.X -= (int) lineWidth / 2;
break;
case HorizontalAlign.Right:
position.X -= lineWidth;
break;
}
return position;
}
/// <summary>
/// Get the index that will be drawn for a specific character.
/// </summary>
/// <param name="c"></param>
/// <returns>ASCII value of <c>c</c> if it is a visible ASCII character. 0 if unicode or invisible, -1 if newline</returns>
public int GetCharacterIndex(char c) {
if (c == '\n') {
return -1;
}
else {
var i = Convert.ToUInt32(c);
if (i > 127 || i < 32) {
return 0;
}
else {
return (int) i;
}
}
}
public void Dispose() {
Texture.Dispose();
}
}
public enum HorizontalAlign {
Left, Center, Right
}
public enum VerticalAlign {
Top, Middle, Bottom
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DojoSurvey.Models;
namespace DojoSurvey.Controllers
{
public class HomeController : Controller
{
[Route("/")]
[HttpGet]
public IActionResult Index()
{
Survey newSurvey = new Survey();
return View("Index", newSurvey);
}
[Route("/result")]
[HttpPost]
public IActionResult Result(Survey submitted_survey)
{
if (ModelState.IsValid)
{
return View("Result", submitted_survey);
}
else
{
return View("Index");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoutingControllerBeta
{
class Link
{
Router sourceRouter;
byte sourceInterface;
Router destinationRouter;
byte destinationInterface;
double capacity;
double weight;
public Link (string sourceCallSign, string sourceSubNetworkCallSign, string sourceAutonomicNetworkCallSign, byte sourceInterface,
string destinationCallSign, string destinationSubNetworkCallSign, string destinationAutonomicNetworkCallSign, byte destinationInterface,
double capacity)
{
this.sourceRouter = new Router(sourceCallSign, sourceSubNetworkCallSign, sourceAutonomicNetworkCallSign);
this.sourceInterface = sourceInterface;
this.destinationRouter = new Router(destinationCallSign, destinationSubNetworkCallSign, destinationAutonomicNetworkCallSign);
this.destinationInterface = destinationInterface;
this.capacity = capacity;
this.weight = 1 / capacity;
}
public Link(string sourceCallSign, string sourceSubNetworkCallSign, string sourceAutonomicNetworkCallSign, byte sourceInterface,
string destinationCallSign, string destinationSubNetworkCallSign, string destinationAutonomicNetworkCallSign, byte destinationInterface,
double capacity, double weight)
{
this.sourceRouter = new Router(sourceCallSign, sourceSubNetworkCallSign, sourceAutonomicNetworkCallSign);
this.sourceInterface = sourceInterface;
this.destinationRouter = new Router(destinationCallSign, destinationSubNetworkCallSign, destinationAutonomicNetworkCallSign);
this.destinationInterface = destinationInterface;
this.capacity = capacity;
this.weight = weight;
}
public double getWeight()
{
return weight;
}
public double getCapacity()
{
return capacity;
}
public Router getSourceRouter()
{
return sourceRouter;
}
public Router getDestinationRouter()
{
return destinationRouter;
}
public byte getSourceInterface()
{
return sourceInterface;
}
public byte getDestinationInterface()
{
return destinationInterface;
}
public Link copy()
{
return new Link(sourceRouter.getCallSign(), sourceRouter.getSubNetworkCallSign(), sourceRouter.getAutonomicNetworkCallSign(), sourceInterface, destinationRouter.getCallSign(), destinationRouter.getSubNetworkCallSign(), destinationRouter.getAutonomicNetworkCallSign(), destinationInterface, capacity, weight);
}
public void write()
{
Console.Write(sourceRouter.getCallSign() + destinationRouter.getCallSign() + weight);
}
public Link(LRMRCCommunications.LinkStateUpdate update)
{
this.sourceRouter = new Router(update.beginNode.id, update.beginNode.snId, update.beginNode.asId);
this.sourceInterface = update.beginSNPP;
this.destinationRouter = new Router(update.endNode.id, update.endNode.snId, update.endNode.asId);
this.destinationInterface = update.endSNPP;
this.capacity = update.capacity;
this.weight = (1/(double)update.capacity);
}
public Link(LRMRCCommunications.Link update)
{
this.sourceRouter = new Router(update.beginNode.id, update.beginNode.snId, update.beginNode.asId);
this.sourceInterface = update.beginSNPP;
this.destinationRouter = new Router(update.endNode.id, update.endNode.snId, update.endNode.asId);
this.destinationInterface = update.endSNPP;
this.capacity = update.capacity;
this.weight = (1 / (double)update.capacity);
}
public bool isEqual(Link linkToCompare)
{
if (!this.sourceRouter.isEqual(linkToCompare.getSourceRouter()))
return false;
if (!this.destinationRouter.isEqual(linkToCompare.getDestinationRouter()))
return false;
if (this.sourceInterface != linkToCompare.getSourceInterface())
return false;
if (this.destinationInterface != linkToCompare.getDestinationInterface())
return false;
if (this.capacity != linkToCompare.getCapacity())
return false;
if (this.weight != linkToCompare.getWeight())
return false;
return true;
}
public bool updateCapacity(Link linkToCompare)
{
if(this.sourceRouter.isEqual(linkToCompare.getSourceRouter()) && this.destinationRouter.isEqual(linkToCompare.getDestinationRouter()) && this.sourceInterface == linkToCompare.getSourceInterface() && this.destinationInterface == linkToCompare.getDestinationInterface())
{
this.capacity = linkToCompare.getCapacity();
this.weight = linkToCompare.getWeight();
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _04_Academy_Graduation
{
public class _04_Academy_Graduation
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
var result = new SortedDictionary<string, double>();
for (int i = 0; i < n; i++)
{
var name = Console.ReadLine();
var grades = Console.ReadLine().Split(new[] { ' '}, StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToArray();
var averageScore = grades.Average();
result.Add(name, averageScore);
}
foreach (var item in result)
{
Console.WriteLine($"{item.Key} is graduated with {item.Value}");
}
}
}
}
|
using HHY.Models;
using HHY.Models;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace HHY_NETCore.Extension
{
public class AuthorizationExtension
{
readonly HHYContext _context;
public AuthorizationExtension(HHYContext context)
{
_context = context;
}
public string LoginUser(string strEmail, string strPassword)
{
//Get user details for the user who is trying to login
var member = _context.Members.SingleOrDefault(r => r.Email == strEmail && r.Password == strPassword);
//Authenticate User, Check if it’s a registered user in Database
if (member != null)
{
//Authentication successful, Issue Token with user credentials
//Provide the security key which was given in the JWToken configuration in Startup.cs
var key = Encoding.ASCII.GetBytes
("YourKey-2374-OFFKDI940NG7:56753253-tyuw-5769-0921-kfirox29zoxv");
//Generate Token for user
var JWToken = new JwtSecurityToken(
issuer: "http://localhost:45092/",
audience: "http://localhost:45092/",
claims: GetUserClaims(member),
notBefore: new DateTimeOffset(DateTime.Now).DateTime,
expires: new DateTimeOffset(DateTime.Now.AddDays(1)).DateTime,
//Using HS256 Algorithm to encrypt Token
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
);
var token = new JwtSecurityTokenHandler().WriteToken(JWToken);
return token;
}
else
{
return null;
}
}
private List<Claim> GetUserClaims(Members member)
{
List<Claim> claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, member.Name),
new Claim("Email", member.Email),
};
return claims;
}
}
}
|
using System;
using System.Windows.Forms;
namespace _6PigLatin
{
public partial class Form1 : Form
{
PigLatin thisTranslation = new PigLatin();
public Form1()
{
InitializeComponent();
}
private void btn_Translate_Click(object sender, EventArgs e)
{
Translate();
}
private void Translate()
{
string[] noSpaces = tB_EnglishFrase.Text.Split(' '); //User input is taken split by spaces and stored in noSpaces
//Loops through the user input to translate each word then added back into the textbox
for (int i = 0; i < noSpaces.Length; i++)
{
string translation = "";
thisTranslation.Phrase = noSpaces[i];
translation += PigLatin.VowelCheck(thisTranslation.Phrase);
rTBPigFrase.Text += translation + " ";
}
}
}
}
|
namespace gView.Framework.Azure.Storage
{
public enum QueryComparer
{
Equal, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, NotEqual
}
}
|
using UnityEngine;
public class CardScript : MonoBehaviour {
public Card Card { get; set; }
private bool shiftOn;
private bool enlargedCard;
private Quaternion newRotation;
void Start () {
shiftOn = false;
enlargedCard = false;
}
void Update () {
if (this.transform.rotation != newRotation) {
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, newRotation, 0.1f);
}
if (Input.GetKey(KeyCode.LeftShift)) {
shiftOn = true;
} else {
shiftOn = false;
}
}
public void OnMouseDown() {
if (enlargedCard == false) {
Debug.Log("Clicked on card in " + this.transform.parent.name + " zone.");
this.transform.parent.SendMessage("OnMouseDown", null, SendMessageOptions.DontRequireReceiver);
}
if ((Card.IsTappable() == true) && (Card.IsTapped() == false)) {
TapCard();
} else if ((Card.IsTappable()) && (Card.IsTapped() == true)) {
UntapCard();
}
}
public void OnMouseOver() {
if (shiftOn && enlargedCard == false) {
this.transform.localScale = new Vector3(this.transform.localScale.x * 4f, this.transform.localScale.y * 4f, 1f);
this.transform.localPosition = new Vector3(this.transform.localPosition.x, 3f, -1f);
enlargedCard = true;
} else if (shiftOn == false && enlargedCard == true) {
this.transform.localScale = new Vector3(this.transform.localScale.x / 4f, this.transform.localScale.y / 4f, 1f);
this.transform.localPosition = new Vector3(this.transform.localPosition.x, 0f, 0);
enlargedCard = false;
}
}
public void OnMouseExit() {
if (enlargedCard == true) {
this.transform.localScale = new Vector3(this.transform.localScale.x / 4f, this.transform.localScale.y / 4f, 1f);
this.transform.localPosition = new Vector3(this.transform.localPosition.x, 0f, 0);
enlargedCard = false;
}
}
private void TapCard() {
//this.transform.rotation = Quaternion.Euler(0, 0, 90);
newRotation = Quaternion.Euler(0, 0, 90);
Card.Tap();
}
private void UntapCard() {
newRotation = Quaternion.Euler(0, 0, 0);
//this.transform.rotation = Quaternion.Euler(0, 0, 0);
Card.UnTap();
}
}
|
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Security.Claims;
namespace UserDetails
{
public static class CurrentUser
{
[FunctionName("CurrentUser")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var result = new Dictionary<string, string>();
result.Add("source", "Authenticated Azure Function!");
//Current user claims
foreach (Claim claim in ClaimsPrincipal.Current.Claims)
{
if (!result.ContainsKey(claim.Type))
{
result.Add(claim.Type, claim.Value);
}
}
return req.CreateResponse(HttpStatusCode.OK, result, JsonMediaTypeFormatter.DefaultMediaType);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
namespace RobotWizard.Models
{
public class ArrangeGame
{
public string[] correctOrder;
public string[] currentOrder;
public ArrangeObject[] objects;
public string[] winList;
public string[] failList;
public string[] additionalInfo;
public string title;
public string instructions;
public string background;
public string nextGame;
public ArrangeGame(Dictionary<string, string[]> variables)
{
try
{
winList = System.IO.File.ReadLines("C:/Content/lists/win.txt").ToArray();
failList = System.IO.File.ReadLines("C:/Content/lists/fail.txt").ToArray();
correctOrder = variables["correctOrder"];
title = String.Join("", variables["title"]);
background = @"../Content/images/backgrounds/" + variables["background"][0];
instructions = String.Join("", variables["instructions"]);
if (variables.ContainsKey("nextGame"))
{
nextGame = variables["nextGame"][0];
}
List<ArrangeObject> objectsList = new List<ArrangeObject>();
foreach (var obj in variables["objects"])
{
objectsList.Add(new ArrangeObject(obj.Substring(0, obj.IndexOf(".")), obj));
}
if (variables.ContainsKey("additionalInfo"))
{
additionalInfo = variables["additionalInfo"];
}
objects = objectsList.ToArray();
mixObjectsUp();
}
catch (Exception e)
{
string What = e.Message;
}
}
private void mixObjectsUp()
{
List<string> tempList = new List<string>();
RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
objects = objects.OrderBy(x => GetNextInt32(rnd)).ToArray();
foreach (var obj in objects)
{
tempList.Add(obj.name);
}
currentOrder = tempList.ToArray();
}
static int GetNextInt32(RNGCryptoServiceProvider rnd)
{
byte[] randomInt = new byte[4];
rnd.GetBytes(randomInt);
return Convert.ToInt32(randomInt[0]);
}
}
public class ArrangeObject
{
public string name;
public string image;
public ArrangeObject(string name, string image)
{
this.name = name;
this.image = image;
}
}
} |
using System;
using Microsoft.EntityFrameworkCore;
using CRMApp.Data;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace CRMApp.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new CRMAppContext(serviceProvider.GetRequiredService<DbContextOptions<CRMAppContext>>()))
{
if (context.User.Any())
{
return;
}
context.User.AddRange(
new User
{
Name = "Jan",
Surname = "Kowalski",
DateOfBirth = DateTime.Parse("1982-2-12"),
Login = "jank123",
IdDeleted = false
},
new User
{
Name = "Adam",
Surname = "Nowak",
DateOfBirth = DateTime.Parse("1992-4-5"),
Login = "nowaq1",
IdDeleted = false
},
new User
{
Name = "Hubert",
Surname = "Stozek",
DateOfBirth = DateTime.Parse("1982-10-22"),
Login = "TakiDuzy",
IdDeleted = false
},
new User
{
Name = "Kacper",
Surname = "Kaczmarek",
DateOfBirth = DateTime.Parse("2000-12-1"),
Login = "kackacz",
IdDeleted = false
});
context.SaveChanges();
}
}
}
}
|
namespace ControleEstacionamento.Persistence.Entity.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AlterandoFinal : DbMigration
{
public override void Up()
{
AddColumn("dbo.tbl_movimentacao_veiculo", "mov_horas_permanencia", c => c.Int());
AddColumn("dbo.tbl_movimentacao_veiculo", "mov_minuto_permanenia", c => c.Int());
AlterColumn("dbo.tbl_movimentacao_veiculo", "mov_valor_total", c => c.Double());
DropColumn("dbo.tbl_movimentacao_veiculo", "mov_tempo_permanencia");
DropColumn("dbo.tbl_movimentacao_veiculo", "mov_hora_adicional");
}
public override void Down()
{
AddColumn("dbo.tbl_movimentacao_veiculo", "mov_hora_adicional", c => c.DateTime(nullable: false));
AddColumn("dbo.tbl_movimentacao_veiculo", "mov_tempo_permanencia", c => c.DateTime(nullable: false));
AlterColumn("dbo.tbl_movimentacao_veiculo", "mov_valor_total", c => c.Double(nullable: false));
DropColumn("dbo.tbl_movimentacao_veiculo", "mov_minuto_permanenia");
DropColumn("dbo.tbl_movimentacao_veiculo", "mov_horas_permanencia");
}
}
}
|
#region OneFilePicker
// OneFilePicker
// Abstract (extensible) file picker
// https://github.com/picrap/OneFilePicker
// Released under MIT license http://opensource.org/licenses/mit-license.php
#endregion
namespace OneFilePicker.File.Default
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Media;
using Services;
[DebuggerDisplay("{Path}")]
public class FileNode : INode
{
public INode Parent { get; private set; }
public INode[] Children
{
get
{
var children = new INode[0];
if (IsFolder)
{
try
{
children = Directory.EnumerateFileSystemEntries(Path + @"\").Where(IsVisible).Select(CreateChild).ToArray();
}
catch (UnauthorizedAccessException)
{ }
}
return children;
}
}
private static bool IsVisible(string path)
{
var attributes = File.GetAttributes(path);
if (attributes.HasFlag(FileAttributes.System))
return false;
return true;
}
private INode CreateChild(string path)
{
var name = System.IO.Path.GetFileName(path);
var displayName = ShellInfo.GetDisplayName(path);
return new FileNode(this, path, name, displayName);
}
public INode[] FolderChildren
{
get { return Children.Where(c => c.IsFolder).ToArray(); }
}
private ImageSource _icon;
public ImageSource Icon
{
get
{
if (_icon == null)
_icon = ShellInfo.GetIcon(Path, false);
return _icon;
}
}
public bool IsFolder { get; private set; }
public string Name { get; private set; }
public string DisplayName { get; private set; }
public string Path { get; private set; }
public DateTime LastWriteTime { get; private set; }
public string DisplayType { get; private set; }
public long? LengthKB { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="FileNode" /> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="path">The path.</param>
/// <param name="name">The name.</param>
/// <param name="displayName">The display name.</param>
public FileNode(INode parent, string path, string name, string displayName = null)
{
Parent = parent;
Path = path;
Name = name;
DisplayName = displayName ?? System.IO.Path.GetFileName(path);
DisplayType = ShellInfo.GetFileType(path);
IsFolder = Directory.Exists(path);
if (IsFolder)
LastWriteTime = new DirectoryInfo(path).LastWriteTime;
else
{
var fileInfo = new FileInfo(path);
LengthKB = (fileInfo.Length + 1023) >> 10;
LastWriteTime = fileInfo.LastWriteTime;
}
}
}
}
|
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit;
using SFA.DAS.ProviderCommitments.Web.Validators;
using SFA.DAS.Testing.AutoFixture;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Validators.Apprentice
{
[TestFixture]
public class ChangeOptionViewModelValidatorTests
{
[Test, MoqAutoData]
public void When_OptionSelected_Then_ReturnValid(
ChangeOptionViewModel viewModel,
ChangeOptionViewModelValidator validator)
{
var result = validator.Validate(viewModel);
Assert.True(result.IsValid);
}
[Test, MoqAutoData]
public void When_SelectedOptionIsNull_Then_ReturnInvalid(
ChangeOptionViewModel viewModel,
ChangeOptionViewModelValidator validator)
{
viewModel.SelectedOption = null;
var result = validator.Validate(viewModel);
Assert.False(result.IsValid);
}
[Test, MoqAutoData]
public void When_OnlyChangingOption_And_CurrentOptionIsSelected_Then_ReturnInvalid(
ChangeOptionViewModel viewModel,
ChangeOptionViewModelValidator validator)
{
viewModel.ReturnToEdit = false;
viewModel.ReturnToChangeVersion = false;
viewModel.SelectedOption = viewModel.CurrentOption;
var result = validator.Validate(viewModel);
Assert.False(result.IsValid);
}
}
}
|
using UnityEngine;
using System.Collections;
public class TipConfig {
public string tipID;
public string tipTextIdentifier;
public string explicitText;
public string previousTipID;
public TipConfig(string explicitText) {
this.tipID = null;
this.tipTextIdentifier = null;
this.previousTipID = null;
this.explicitText = explicitText;
}
public TipConfig(string tipID,
string tipTextIdentifier) {
this.tipID = tipID;
this.tipTextIdentifier = tipTextIdentifier;
this.previousTipID = null;
}
public TipConfig(string tipID,
string tipTextIdentifier,
string previousTipID) {
this.tipID = tipID;
this.tipTextIdentifier = tipTextIdentifier;
this.previousTipID = previousTipID;
}
}
public class TipController : MonoBehaviour {
bool registeredForEvents;
public GameObject tipDialogPrototype;
IEnumerator enqueuedTip;
public static TipController instance;
public float timeBetweenTips = 4;
void Awake() {
instance = this;
registeredForEvents = false;
}
// Use this for initialization
void Start () {
RegisterForEvents ();
}
void OnDestroy() {
UnregisterForEvents ();
}
void RegisterForEvents() {
GamePhaseState.instance.GamePhaseChanged +=
new GamePhaseState.GamePhaseChangedEventHandler (OnPhaseChanged);
registeredForEvents = true;
}
void UnregisterForEvents() {
if (registeredForEvents) {
GamePhaseState.instance.GamePhaseChanged -=
new GamePhaseState.GamePhaseChangedEventHandler (OnPhaseChanged);
}
}
void OnPhaseChanged() {
if (GamePhaseState.instance.IsPlaying ()) {
EnqueueTipForLevel ();
}
if (GamePhaseState.instance.gamePhase != GamePhaseState.GamePhaseType.LEVEL_PLAY &&
GamePhaseState.instance.gamePhase != GamePhaseState.GamePhaseType.PENDING) {
ClearEnqueuedTips ();
}
}
void EnqueueTipForLevel () {
LevelDescription ld = LevelConfig.instance.GetCurrentLevelDescription ();
if (ld.tipConfig == null) {
return;
}
EnqueueTip (ld.tipConfig,
ld.tipPause);
}
public void EnqueueTip(TipConfig tipConfig,
float tipPause) {
if (DidShowTip(tipConfig.tipID)) {
return;
}
enqueuedTip = PlayTipWithPause (tipConfig,
tipPause);
StartCoroutine (enqueuedTip);
}
public void EnqueueAnytimeTip(string message) {
TipConfig tipConfig = new TipConfig (message);
EnqueueTip (tipConfig, 0.001f);
}
IEnumerator PlayTipWithPause(TipConfig tipConfig,
float tipPause) {
yield return new WaitForSeconds (tipPause);
MaybeShowTip (tipConfig);
enqueuedTip = null;
}
void ClearEnqueuedTips() {
if (enqueuedTip != null) {
StopCoroutine (enqueuedTip);
enqueuedTip = null;
}
}
bool DidShowTip(string tipID) {
if (tipID == null) {
return false;
}
return PersistentStorage.instance.GetBoolValue ("tip." + tipID,
false);
}
public bool MaybeShowTip(TipConfig tipConfig) {
if (DidShowTip(tipConfig.tipID)) {
return false;
}
if (tipConfig.previousTipID != null) {
if (!DidShowTip(tipConfig.previousTipID)) {
return false;
}
}
if (DialogController.instance.IsDialogShowing ()) {
return false;
}
GameObject tipDialogObject = Instantiate (tipDialogPrototype,
new Vector3 (0f, 0f, 0f),
Quaternion.identity) as GameObject;
tipDialogObject.transform.localScale = new Vector3 (1f, 1f, 1f);
tipDialogObject.transform.localPosition = new Vector2 (0,
GoogleAdController.GetBannerHeight ()/2);
TipDialog td = tipDialogObject.GetComponent<TipDialog> ();
string message;
if (tipConfig.explicitText != null) {
message = tipConfig.explicitText;
} else {
message = LazyAngusStrings.inst.Str (tipConfig.tipTextIdentifier);
}
td.ConfigureDialog (message);
DialogController.instance.ShowDialog (td);
if (tipConfig.tipID != null) {
PersistentStorage.instance.SetBoolValue ("tip." + tipConfig.tipID,
true);
}
return true;
}
}
|
using Godot;
using System;
using System.Collections.Generic;
public class PnlControls : Panel
{
public new bool Visible {
get{
return base.Visible;
}
set{
base.Visible = value;
GetNode<Label>("LblInfo").Text = "";
}
}
public void RefreshBtnMapText()
{
foreach (Node n in GetChildren())
{
foreach (Node m in n.GetChildren())
{
BtnRemap btnRemap = m.GetNode<BtnRemap>("BtnRemap");
btnRemap.DisplayCurrentKey();
}
}
GetNode<Label>("LblInfo").Text = "";
}
public void OnOtherBtnRemapped(string oldAction, string newAction)
{
string oldEvText = BtnRemap.GetReadableStringFromActionEvent((InputEvent)InputMap.GetActionList(oldAction)[0]); // this is now what the new action used to be
string newEvText = BtnRemap.GetReadableStringFromActionEvent((InputEvent)InputMap.GetActionList(newAction)[0]); // this is now the new input (what the old action used to be)
GetNode<Label>("LblInfo").Text = string.Format("{0} now bound to {1}", oldAction, oldEvText);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProxyExample
{
class Program
{
static void Main(string[] args)
{
/*
There's a couple use cases for the proxy.
Here I'm going to use the proxy pattern
to defer a mock DB call only after the
user is verified to be part of the system.
in the logic here, if you're not authenticated
an empty list is sent.
*/
int userId = 3;
var cusDao = new ProxyCustomerDataAccessObject(userId);
var customers = cusDao.GetActiveCustomer();
foreach (var cus in customers)
{
Console.WriteLine(cus.CustomerName);
}
}
}
}
|
using _7DRL_2021.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021.Results
{
class ActionTurn : IActionHasOrigin, ITickable, ISlider
{
public bool Done => Frame.Done;
public ICurio Origin { get; set; }
public float TurnAngle;
private Slider Frame;
public float Slide => Frame.Slide;
public ActionTurn(ICurio origin, float turnAngle, float time)
{
Origin = origin;
TurnAngle = turnAngle;
Frame = new Slider(time);
}
public void Run()
{
var tile = Origin.GetMainTile();
var orientable = Origin.GetBehavior<BehaviorOrientable>();
orientable.TurnTo(orientable.Angle + TurnAngle, LerpHelper.QuadraticIn, this);
}
public void Tick(SceneGame scene)
{
Frame += scene.TimeModCurrent;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public struct MirrorPath
{
public bool loops;
public Transform[] nodes;
}
public class MirrorObject : MonoBehaviour
{
public bool moving;
public float moveSpeed;
public float turnSpeed;
public MirrorPath mirrorPath;
private bool movingInPositiveDirection;
private float startTime;
private float journeyLength;
private int currentIndex;
private int targetIndex;
private Vector3 lastPosition;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Start()
{
movingInPositiveDirection = true;
startTime = Time.time;
if (mirrorPath.nodes != null && mirrorPath.nodes.Length >= 2)
{
journeyLength = Vector3.Distance(mirrorPath.nodes[0].position, mirrorPath.nodes[1].position);
transform.position = mirrorPath.nodes[0].position;
currentIndex = 0;
targetIndex = 1;
}
}
public void FixedUpdate()
{
if (moving && mirrorPath.nodes.Length >= 2)
{
Lerp();
Vector3 movementDelta = lastPosition - transform.position;
TurnToward(transform.position - movementDelta);
}
lastPosition = transform.position;
}
void Lerp()
{
float dstCovered = (Time.time - startTime) * moveSpeed;
float fracJourney = dstCovered / journeyLength;
transform.position = Vector3.Lerp(mirrorPath.nodes[currentIndex].position,
mirrorPath.nodes[targetIndex].position,
fracJourney);
if (fracJourney >= 1f)
SetNextTarget();
}
public void TurnToward(Vector3 target)
{
Quaternion newRotation = new Quaternion();
newRotation.eulerAngles = new Vector3(0f, 0f, rb.rotation + Vector2.SignedAngle(transform.up, target - transform.position) * turnSpeed * Time.fixedDeltaTime);
transform.rotation = newRotation;
}
void SetNextTarget()
{
currentIndex = targetIndex;
targetIndex++;
if (targetIndex >= mirrorPath.nodes.Length)
{
if (mirrorPath.loops)
targetIndex = 0;
else
{
movingInPositiveDirection = false;
targetIndex = mirrorPath.nodes.Length - 2;
}
}
startTime = Time.time;
journeyLength = Vector3.Distance(mirrorPath.nodes[currentIndex].position, mirrorPath.nodes[targetIndex].position);
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.Tilemaps;
public class CageBreaker : MonoBehaviour {
[SerializeField] protected Tilemap _groundTileMap;
[SerializeField] protected Tilemap _foregroundTileMap;
[SerializeField] protected Vector3Int _breakTilePosition;
[SerializeField] protected Tile[] _groundSteps;
[SerializeField] protected Tile[] _foregroundSteps;
[SerializeField] protected float[] _stepTimers;
[SerializeField] protected AudioClip _cageBreakAudio;
public void Break() => StartCoroutine(DoBreak());
private IEnumerator DoBreak() {
AudioManager.Sfx.Play(_cageBreakAudio);
for (var nextIndex = 0; nextIndex < _groundSteps.Length + _foregroundSteps.Length; nextIndex++) {
var delayBeforeNextStep = _stepTimers[nextIndex];
while (delayBeforeNextStep > 0) {
yield return null;
delayBeforeNextStep -= Time.deltaTime;
}
_groundTileMap.SetTile(_breakTilePosition, _groundSteps.Length > nextIndex ? _groundSteps[nextIndex] : null);
_foregroundTileMap.SetTile(_breakTilePosition, _groundSteps.Length > nextIndex ? null : _foregroundSteps[nextIndex - _groundSteps.Length]);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Data.SqlClient;
using System.Data;
namespace AxisPosUtil
{
/// <summary>
/// Загрузка настроек из xml
/// </summary>
internal static class Settings
{
public static NameValueCollection m_settings;
private static string m_settingsPath;
private static string m_execPath;
public static string AppDir
{
get { return m_execPath; }
}
//Сервер
public static string ServerHost
{
get { return m_settings.Get("ServerHost"); }
set { m_settings.Set("ServerHost", value); }
}
public static string ServerUser
{
get { return m_settings.Get("ServerUser"); }
set { m_settings.Set("ServerUser", value); }
}
public static string ServerPassword
{
get { return m_settings.Get("ServerPassword"); }
set { m_settings.Set("ServerPassword", value); }
}
public static string ServerDBase
{
get { return m_settings.Get("ServerDBase"); }
set { m_settings.Set("ServerDBase", value); }
}
//Хост
public static string Server
{
get { return m_settings.Get("Server"); }
set { m_settings.Set("Server", value); }
}
public static string User
{
get { return m_settings.Get("User"); }
set { m_settings.Set("User", value); }
}
public static string Password
{
get { return m_settings.Get("Password"); }
set { m_settings.Set("Password", value); }
}
public static string DBase
{
get { return m_settings.Get("DBase"); }
set { m_settings.Set("DBase", value); }
}
/// <summary>
/// Строка подключение
/// </summary>
public static string ConStr
{
get
{
return @"server="+ServerHost+"; database="+ServerDBase+"; user="+ServerUser+"; password="+ServerPassword+";";
}
}
public static string GetExecPath()
{
return m_execPath;
}
public static string serverType
{
get
{
if (m_settings.Get("serverType")==null) return "Firebird";
else
return Convert.ToString(m_settings.Get("serverType")); }
set { m_settings.Set("serverType", value.ToString()); }
}
/// <summary>
/// Загрузка настроек
/// </summary>
/// <param name="fileName"></param>
/// <param name="fileName2">Файл настроек dklinkfo, dkpos.cfg</param>
/// <returns></returns>
public static bool LoadSettings(string fileName, string fileName2)
{
try
{
m_settings = new NameValueCollection();
m_settingsPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
m_execPath = m_settingsPath;
m_execPath = m_execPath.Replace(@"file:\", "");
m_settingsPath += @"\" + /*System.Reflection.Assembly.GetExecutingAssembly().GetName().Name*/Path.GetFileName(fileName);
m_settingsPath = m_settingsPath.Replace(@"file:\", "");
m_settings.Add("ServerHost", "");
m_settings.Add("ServerUser", "");
m_settings.Add("ServerPassword", "");
m_settings.Add("ServerDBase", "");
m_settings.Add("ServerType", "Firebird");
m_settings.Add("Server", "localhost");
m_settings.Add("User", "");
m_settings.Add("Password", "");
m_settings.Add("DBase", "");
//Конфигурация своя
System.Xml.XmlDocument xdoc = new XmlDocument();
xdoc.Load(m_settingsPath);
XmlElement root = xdoc.DocumentElement;
System.Xml.XmlNodeList nodeList = root.ChildNodes.Item(0).ChildNodes;
for (int i = 0; i < nodeList.Count; i++)
{
ProcessNode(nodeList.Item(i));
}
//Конфигурация DkLink FO
if (File.Exists(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace(@"file:\", "") + "\\" + fileName2))
{
System.Xml.XmlDocument xdoc1 = new XmlDocument();
xdoc1.Load(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\" + fileName2);
XmlElement root1 = xdoc1.DocumentElement;
System.Xml.XmlNodeList nodeList1 = root1.ChildNodes.Item(0).ChildNodes;
for (int i = 0; i < nodeList1.Count; i++)
{
ProcessNode(nodeList1.Item(i));
}
}
return true;
}
catch (Exception)
{
return false;
}
}
private static void ProcessNode(XmlNode node)
{
if (node.Attributes == null) return;
string key = node.Attributes["key"].Value,
val = node.Attributes["value"].Value;
for (int i = 0; i < m_settings.Count; i++)
{
if (string.Compare(key, m_settings.GetKey(i), true) == 0)
{
m_settings.Set(key, val);
break;
}
}
}
public static void SetPrefs()
{
XmlTextWriter tw = new XmlTextWriter(m_settingsPath, System.Text.UTF8Encoding.UTF8);
tw.WriteStartDocument();
tw.WriteStartElement("configuration");
tw.WriteStartElement("appSettings");
for (int i = 0; i < m_settings.Count; ++i)
{
tw.WriteStartElement("add");
tw.WriteStartAttribute("key", string.Empty);
tw.WriteRaw(m_settings.GetKey(i));
tw.WriteEndAttribute();
tw.WriteStartAttribute("value", string.Empty);
tw.WriteRaw(m_settings.Get(i));
tw.WriteEndAttribute();
tw.WriteEndElement();
}
tw.WriteEndElement();
tw.WriteEndElement();
tw.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SupersonicEvents : MonoBehaviour
{
private const string ERROR_CODE = "error_code";
private const string ERROR_DESCRIPTION = "error_description";
public static string uniqueUserId = "ZB_PF_DEV";
public static string appKey = "5689cd1d";
public static bool trackNetworkState = true;
public static event Action<RewardAdActivityResponse> OnAdRewarded;
public static AdPlacementDetails queuedAd;
public static bool isRewardedVideoPlacementCapped(string placement)
{
return Supersonic.Agent.isRewardedVideoPlacementCapped(placement);
}
public static bool rewardedVideoAvailability
{
get
{
return Supersonic.Agent.isRewardedVideoAvailable();
}
}
#region ****** UNITY EVENTS & METHODS *****
void Awake()
{
gameObject.name = "SupersonicEvents"; //Change the GameObject name to SupersonicEvents.
DontDestroyOnLoad(gameObject);
//Supersonic.m //Makes the object not be destroyed automatically when loading a new scene.
}
// general show ad feature?
public static void ShowRewardedVideo(AdPlacementDetails ad)
{
//if (rewardedVideoAvailability) {
//Supersonic.Agent.showRewardedVideo("placementName");
queuedAd = ad;
Supersonic.Agent.showRewardedVideo(ad.PlacementName);
// } else {
// Debug.Log ("RewardedVideo was not available.");
// queuedAd = null;
// }
}
void OnEnable()
{
SupersonicEvents.onRewardedVideoInitSuccessEvent += RewardedVideoInitSuccessEvent;
SupersonicEvents.onRewardedVideoInitFailEvent += RewardedVideoInitFailEvent;
SupersonicEvents.onRewardedVideoAdOpenedEvent += RewardedVideoAdOpenedEvent;
SupersonicEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
SupersonicEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
SupersonicEvents.onVideoAvailabilityChangedEvent += VideoAvailabilityChangedEvent;
SupersonicEvents.onVideoStartEvent += VideoStartEvent;
SupersonicEvents.onVideoEndEvent += VideoEndEvent;
}
void OnDisable()
{
SupersonicEvents.onRewardedVideoInitSuccessEvent -= RewardedVideoInitSuccessEvent;
SupersonicEvents.onRewardedVideoInitFailEvent -= RewardedVideoInitFailEvent;
SupersonicEvents.onRewardedVideoAdOpenedEvent -= RewardedVideoAdOpenedEvent;
SupersonicEvents.onRewardedVideoAdRewardedEvent -= RewardedVideoAdRewardedEvent;
SupersonicEvents.onRewardedVideoAdClosedEvent -= RewardedVideoAdClosedEvent;
SupersonicEvents.onVideoAvailabilityChangedEvent -= VideoAvailabilityChangedEvent;
SupersonicEvents.onVideoStartEvent -= VideoStartEvent;
SupersonicEvents.onVideoEndEvent -= VideoEndEvent;
}
void Start()
{
Supersonic.Agent.start();
//Set the unique id of your end user.
//Init Rewarded Video
Supersonic.Agent.initRewardedVideo(SupersonicEvents.appKey, SupersonicEvents.uniqueUserId);
//track the network state:
Supersonic.Agent.shouldTrackNetworkState(trackNetworkState);
}
#endregion
#region ****** PLAYFAB CALLBACKS ******
public static void RouteActivityToPlayFab(string placement, string reward)
{
PF_Advertising.RewardAdActivity(new RewardAdActivityRequest() { PlacementId = placement, RewardId = reward }, OnReportAdActivitySuccess, PF_Bridge.PlayFabErrorCallback);
}
public static void OnReportAdActivitySuccess(RewardAdActivityResponse result)
{
Debug.Log("OnReportAdActivitySuccess!");
Debug.Log(string.Format("Retrieved {0} items and {1} VCs.", result.RewardResults.GrantedItems.Count, result.RewardResults.GrantedVirtualCurrencies.Count));
var gotItems = false;
var gotVc = false;
var output = "Congratulations! ";
List<string> itemGifts = new List<string>();
if (result.RewardResults.GrantedItems != null && result.RewardResults.GrantedItems.Count > 0)
{
gotItems = true;
output += "You received: " + result.RewardResults.GrantedItems.Count + " new items";
foreach (var item in result.RewardResults.GrantedItems)
{
itemGifts.Add(item.ItemId);
}
}
if (result.RewardResults.GrantedVirtualCurrencies != null && result.RewardResults.GrantedVirtualCurrencies.Count > 0)
{
gotVc = true;
var count = 0;
foreach (var grant in result.RewardResults.GrantedVirtualCurrencies)
{
if (gotItems || count > 0)
{
output += "; ";
}
else
{
output += "You received: ";
}
output += string.Format("{1}({0})", grant.Key, grant.Value);
count++;
}
output += " in Virtual Currencies";
}
if (result.RewardResults.IncrementedStatistics != null && result.RewardResults.IncrementedStatistics.Count > 0)
{
var count = 0;
foreach (var stat in result.RewardResults.IncrementedStatistics)
{
if (gotItems || gotVc || count > 0)
{
output += "; ";
}
output += string.Format(" Your \"{0}\" increased by {1}", stat.Key, stat.Value);
count++;
}
}
if (gotItems)
output += ".\n Click the check mark to view your new items.";
if (OnAdRewarded != null)
OnAdRewarded(result);
DialogCanvasController.RequestConfirmationPrompt("You were granted a gift!", output, response =>
{
if (response && gotItems)
DialogCanvasController.RequestItemViewer(itemGifts);
});
}
#endregion
#region ******* SUPERSONIC CALLBACKS *******
//Invoked when initialization of RewardedVideo has finished successfully.
public void RewardedVideoInitSuccessEvent()
{
Debug.Log("RewardedVideoInitSuccessEvent");
//PF_Advertising.ReportAdActivity(new ReportAdActivityRequest(){ PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdActivity }, null, PF_Bridge.PlayFabErrorCallback);
}
//Invoked when RewardedVideo initialization process has failed.
//SupersonicError contains the reason for the failure.
public void RewardedVideoInitFailEvent(SupersonicError error)
{
Debug.Log("Init rewarded video error ");
//PF_Advertising.ReportAdActivity(new ReportAdActivityRequest(){ PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdAc }, null, PF_Bridge.PlayFabErrorCallback);
}
//Invoked when the RewardedVideo ad view has opened.
//Your Activity will lose focus. Please avoid performing heavy
//tasks till the video ad will be closed.
public void RewardedVideoAdOpenedEvent()
{
Debug.Log("RewardedVideoAdOpenedEvent");
PF_Advertising.ReportAdActivity(new ReportAdActivityRequest() { PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdActivity.Opened }, null, PF_Bridge.PlayFabErrorCallback);
}
//Invoked when the RewardedVideo ad view is about to be closed.
//Your activity will now regain its focus.
public void RewardedVideoAdClosedEvent()
{
Debug.Log("RewardedVideoAdClosedEvent");
PF_Advertising.ReportAdActivity(new ReportAdActivityRequest() { PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdActivity.Closed }, null, PF_Bridge.PlayFabErrorCallback);
queuedAd = null;
}
//Invoked when there is a change in the ad availability status.
//@param - available - value will change to true when rewarded videos are available.
//You can then show the video by calling showRewardedVideo().
//Value will change to false when no videos are available.
public void VideoAvailabilityChangedEvent(bool available)
{
//Change the in-app 'Traffic Driver' state according to availability.
// rewardedVideoAvailability = available; // Actually does nothing
}
//Invoked when the video ad starts playing.
public void VideoStartEvent()
{
Debug.Log("VideoStartEvent");
PF_Advertising.ReportAdActivity(new ReportAdActivityRequest() { PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdActivity.Start }, null, PF_Bridge.PlayFabErrorCallback);
}
//Invoked when the video ad finishes playing.
public void VideoEndEvent()
{
Debug.Log("VideoEndEvent");
PF_Advertising.ReportAdActivity(new ReportAdActivityRequest() { PlacementId = SupersonicEvents.queuedAd.PlacementId, RewardId = SupersonicEvents.queuedAd.RewardId, Activity = AdActivity.End }, null, PF_Bridge.PlayFabErrorCallback);
}
//Invoked when the user completed the video and should be rewarded.
//If using server-to-server callbacks you may ignore this events and wait for
//the callback from the Supersonic server.
//@param - placement - placement object which contains the reward data
public void RewardedVideoAdRewardedEvent(SupersonicPlacement ssp)
{
//TODO - here you can reward the user according to the reward name and amount
Debug.Log("RewardedVideoAdRewardedEvent");
//string adResult = string.Format ("Ad Complete: {0} -- {1} -- {2}", ssp.getPlacementName (), ssp.getRewardName (), ssp.getRewardAmount ());
//Debug.Log (adResult);
//var grantable = PF_GameData.catalogItems.Find((item) => { });
//PF_Bridge.RaiseCallbackError(string.Format("Completed {0}, attempted to grant ({1}x){2}, but this functionality must be performed on the Server.", ssp.getPlacementName(), ssp.getRewardAmount(), ssp.getRewardName()) , PlayFabAPIMethods.Generic, MessageDisplayStyle.error);
Debug.Log(string.Format("PlacementId:{0} -- RewardId:{1}", queuedAd.PlacementId, queuedAd.RewardId));
RouteActivityToPlayFab(queuedAd.PlacementId, queuedAd.RewardId);
}
#endregion
#region ******************************* RewardedVideoEvents *******************************
private static event Action _onRewardedVideoInitSuccessEvent;
public static event Action onRewardedVideoInitSuccessEvent
{
add
{
if (_onRewardedVideoInitSuccessEvent == null || !_onRewardedVideoInitSuccessEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoInitSuccessEvent += value;
}
}
remove
{
if (_onRewardedVideoInitSuccessEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoInitSuccessEvent -= value;
}
}
}
public void onRewardedVideoInitSuccess(string empty)
{
if (_onRewardedVideoInitSuccessEvent != null)
{
_onRewardedVideoInitSuccessEvent();
}
}
private static event Action<SupersonicError> _onRewardedVideoInitFailEvent;
public static event Action<SupersonicError> onRewardedVideoInitFailEvent
{
add
{
if (_onRewardedVideoInitFailEvent == null || !_onRewardedVideoInitFailEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoInitFailEvent += value;
}
}
remove
{
if (_onRewardedVideoInitFailEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoInitFailEvent -= value;
}
}
}
public void onRewardedVideoInitFail(string description)
{
if (_onRewardedVideoInitFailEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onRewardedVideoInitFailEvent(sse);
}
}
private static event Action<SupersonicError> _onRewardedVideoShowFailEvent;
public static event Action<SupersonicError> onRewardedVideoShowFailEvent
{
add
{
if (_onRewardedVideoShowFailEvent == null || !_onRewardedVideoShowFailEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoShowFailEvent += value;
}
}
remove
{
if (_onRewardedVideoShowFailEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoShowFailEvent -= value;
}
}
}
public void onRewardedVideoShowFail(string description)
{
if (_onRewardedVideoShowFailEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onRewardedVideoShowFailEvent(sse);
}
}
private static event Action _onRewardedVideoAdOpenedEvent;
public static event Action onRewardedVideoAdOpenedEvent
{
add
{
if (_onRewardedVideoAdOpenedEvent == null || !_onRewardedVideoAdOpenedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdOpenedEvent += value;
}
}
remove
{
if (_onRewardedVideoAdOpenedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdOpenedEvent -= value;
}
}
}
public void onRewardedVideoAdOpened(string empty)
{
if (_onRewardedVideoAdOpenedEvent != null)
{
_onRewardedVideoAdOpenedEvent();
}
}
private static event Action _onRewardedVideoAdClosedEvent;
public static event Action onRewardedVideoAdClosedEvent
{
add
{
if (_onRewardedVideoAdClosedEvent == null || !_onRewardedVideoAdClosedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdClosedEvent += value;
}
}
remove
{
if (_onRewardedVideoAdClosedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdClosedEvent -= value;
}
}
}
public void onRewardedVideoAdClosed(string empty)
{
if (_onRewardedVideoAdClosedEvent != null)
{
_onRewardedVideoAdClosedEvent();
}
}
private static event Action _onVideoStartEvent;
public static event Action onVideoStartEvent
{
add
{
if (_onVideoStartEvent == null || !_onVideoStartEvent.GetInvocationList().Contains(value))
{
_onVideoStartEvent += value;
}
}
remove
{
if (_onVideoStartEvent.GetInvocationList().Contains(value))
{
_onVideoStartEvent -= value;
}
}
}
public void onVideoStart(string empty)
{
if (_onVideoStartEvent != null)
{
_onVideoStartEvent();
}
}
private static event Action _onVideoEndEvent;
public static event Action onVideoEndEvent
{
add
{
if (_onVideoEndEvent == null || !_onVideoEndEvent.GetInvocationList().Contains(value))
{
_onVideoEndEvent += value;
}
}
remove
{
if (_onVideoEndEvent.GetInvocationList().Contains(value))
{
_onVideoEndEvent -= value;
}
}
}
public void onVideoEnd(string empty)
{
if (_onVideoEndEvent != null)
{
_onVideoEndEvent();
}
}
private static event Action<SupersonicPlacement> _onRewardedVideoAdRewardedEvent;
public static event Action<SupersonicPlacement> onRewardedVideoAdRewardedEvent
{
add
{
if (_onRewardedVideoAdRewardedEvent == null || !_onRewardedVideoAdRewardedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdRewardedEvent += value;
}
}
remove
{
if (_onRewardedVideoAdRewardedEvent.GetInvocationList().Contains(value))
{
_onRewardedVideoAdRewardedEvent -= value;
}
}
}
public void onRewardedVideoAdRewarded(string description)
{
if (_onRewardedVideoAdRewardedEvent != null)
{
SupersonicPlacement ssp = getPlacementFromString(description);
_onRewardedVideoAdRewardedEvent(ssp);
}
}
private static event Action<bool> _onVideoAvailabilityChangedEvent;
public static event Action<bool> onVideoAvailabilityChangedEvent
{
add
{
if (_onVideoAvailabilityChangedEvent == null || !_onVideoAvailabilityChangedEvent.GetInvocationList().Contains(value))
{
_onVideoAvailabilityChangedEvent += value;
}
}
remove
{
if (_onVideoAvailabilityChangedEvent.GetInvocationList().Contains(value))
{
_onVideoAvailabilityChangedEvent -= value;
}
}
}
public void onVideoAvailabilityChanged(string stringAvailable)
{
bool isAvailable = (stringAvailable == "true") ? true : false;
if (_onVideoAvailabilityChangedEvent != null)
_onVideoAvailabilityChangedEvent(isAvailable);
}
#endregion
#region ******************************* InterstitialEvents *******************************
private static event Action _onInterstitialInitSuccessEvent;
public static event Action onInterstitialInitSuccessEvent
{
add
{
if (_onInterstitialInitSuccessEvent == null || !_onInterstitialInitSuccessEvent.GetInvocationList().Contains(value))
{
_onInterstitialInitSuccessEvent += value;
}
}
remove
{
if (_onInterstitialInitSuccessEvent.GetInvocationList().Contains(value))
{
_onInterstitialInitSuccessEvent -= value;
}
}
}
public void onInterstitialInitSuccess(string empty)
{
if (_onInterstitialInitSuccessEvent != null)
{
_onInterstitialInitSuccessEvent();
}
}
private static event Action<SupersonicError> _onInterstitialInitFailedEvent;
public static event Action<SupersonicError> onInterstitialInitFailedEvent
{
add
{
if (_onInterstitialInitFailedEvent == null || !_onInterstitialInitFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialInitFailedEvent += value;
}
}
remove
{
if (_onInterstitialInitFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialInitFailedEvent -= value;
}
}
}
public void onInterstitialInitFailed(string description)
{
if (_onInterstitialInitFailedEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onInterstitialInitFailedEvent(sse);
}
}
private static event Action _onInterstitialReadyEvent;
public static event Action onInterstitialReadyEvent
{
add
{
if (_onInterstitialReadyEvent == null || !_onInterstitialReadyEvent.GetInvocationList().Contains(value))
{
_onInterstitialReadyEvent += value;
}
}
remove
{
if (_onInterstitialReadyEvent.GetInvocationList().Contains(value))
{
_onInterstitialReadyEvent -= value;
}
}
}
public void onInterstitialReady()
{
if (_onInterstitialReadyEvent != null)
_onInterstitialReadyEvent();
}
private static event Action<SupersonicError> _onInterstitialLoadFailedEvent;
public static event Action<SupersonicError> onInterstitialLoadFailedEvent
{
add
{
if (_onInterstitialLoadFailedEvent == null || !_onInterstitialLoadFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialLoadFailedEvent += value;
}
}
remove
{
if (_onInterstitialLoadFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialLoadFailedEvent -= value;
}
}
}
public void onInterstitialLoadFailed(string description)
{
if (_onInterstitialLoadFailedEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onInterstitialLoadFailedEvent(sse);
}
}
private static event Action _onInterstitialOpenEvent;
public static event Action onInterstitialOpenEvent
{
add
{
if (_onInterstitialOpenEvent == null || !_onInterstitialOpenEvent.GetInvocationList().Contains(value))
{
_onInterstitialOpenEvent += value;
}
}
remove
{
if (_onInterstitialOpenEvent.GetInvocationList().Contains(value))
{
_onInterstitialOpenEvent -= value;
}
}
}
public void onInterstitialOpen(string empty)
{
if (_onInterstitialOpenEvent != null)
{
_onInterstitialOpenEvent();
}
}
private static event Action _onInterstitialCloseEvent;
public static event Action onInterstitialCloseEvent
{
add
{
if (_onInterstitialCloseEvent == null || !_onInterstitialCloseEvent.GetInvocationList().Contains(value))
{
_onInterstitialCloseEvent += value;
}
}
remove
{
if (_onInterstitialCloseEvent.GetInvocationList().Contains(value))
{
_onInterstitialCloseEvent -= value;
}
}
}
public void onInterstitialClose(string empty)
{
if (_onInterstitialCloseEvent != null)
{
_onInterstitialCloseEvent();
}
}
private static event Action _onInterstitialShowSuccessEvent;
public static event Action onInterstitialShowSuccessEvent
{
add
{
if (_onInterstitialShowSuccessEvent == null || !_onInterstitialShowSuccessEvent.GetInvocationList().Contains(value))
{
_onInterstitialShowSuccessEvent += value;
}
}
remove
{
if (_onInterstitialShowSuccessEvent.GetInvocationList().Contains(value))
{
_onInterstitialShowSuccessEvent -= value;
}
}
}
public void onInterstitialShowSuccess(string empty)
{
if (_onInterstitialShowSuccessEvent != null)
{
_onInterstitialShowSuccessEvent();
}
}
private static event Action<SupersonicError> _onInterstitialShowFailedEvent;
public static event Action<SupersonicError> onInterstitialShowFailedEvent
{
add
{
if (_onInterstitialShowFailedEvent == null || !_onInterstitialShowFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialShowFailedEvent += value;
}
}
remove
{
if (_onInterstitialShowFailedEvent.GetInvocationList().Contains(value))
{
_onInterstitialShowFailedEvent -= value;
}
}
}
public void onInterstitialShowFailed(string description)
{
if (_onInterstitialShowFailedEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onInterstitialShowFailedEvent(sse);
}
}
private static event Action _onInterstitialClickEvent;
public static event Action onInterstitialClickEvent
{
add
{
if (_onInterstitialClickEvent == null || !_onInterstitialClickEvent.GetInvocationList().Contains(value))
{
_onInterstitialClickEvent += value;
}
}
remove
{
if (_onInterstitialClickEvent.GetInvocationList().Contains(value))
{
_onInterstitialClickEvent -= value;
}
}
}
public void onInterstitialClick(string empty)
{
if (_onInterstitialClickEvent != null)
{
_onInterstitialClickEvent();
}
}
#endregion
#region ******************************* OfferwallEvents *******************************
private static event Action _onOfferwallInitSuccessEvent;
public static event Action onOfferwallInitSuccessEvent
{
add
{
if (_onOfferwallInitSuccessEvent == null || !_onOfferwallInitSuccessEvent.GetInvocationList().Contains(value))
{
_onOfferwallInitSuccessEvent += value;
}
}
remove
{
if (_onOfferwallInitSuccessEvent.GetInvocationList().Contains(value))
{
_onOfferwallInitSuccessEvent -= value;
}
}
}
public void onOfferwallInitSuccess(string empty)
{
if (_onOfferwallInitSuccessEvent != null)
{
_onOfferwallInitSuccessEvent();
}
}
private static event Action<SupersonicError> _onOfferwallInitFailEvent;
public static event Action<SupersonicError> onOfferwallInitFailEvent
{
add
{
if (_onOfferwallInitFailEvent == null || !_onOfferwallInitFailEvent.GetInvocationList().Contains(value))
{
_onOfferwallInitFailEvent += value;
}
}
remove
{
if (_onOfferwallInitFailEvent.GetInvocationList().Contains(value))
{
_onOfferwallInitFailEvent -= value;
}
}
}
public void onOfferwallInitFail(string description)
{
if (_onOfferwallInitFailEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onOfferwallInitFailEvent(sse);
}
}
private static event Action _onOfferwallOpenedEvent;
public static event Action onOfferwallOpenedEvent
{
add
{
if (_onOfferwallOpenedEvent == null || !_onOfferwallOpenedEvent.GetInvocationList().Contains(value))
{
_onOfferwallOpenedEvent += value;
}
}
remove
{
if (_onOfferwallOpenedEvent.GetInvocationList().Contains(value))
{
_onOfferwallOpenedEvent -= value;
}
}
}
public void onOfferwallOpened(string empty)
{
if (_onOfferwallOpenedEvent != null)
{
_onOfferwallOpenedEvent();
}
}
private static event Action<SupersonicError> _onOfferwallShowFailEvent;
public static event Action<SupersonicError> onOfferwallShowFailEvent
{
add
{
if (_onOfferwallShowFailEvent == null || !_onOfferwallShowFailEvent.GetInvocationList().Contains(value))
{
_onOfferwallShowFailEvent += value;
}
}
remove
{
if (_onOfferwallShowFailEvent.GetInvocationList().Contains(value))
{
_onOfferwallShowFailEvent -= value;
}
}
}
public void onOfferwallShowFail(string description)
{
if (_onOfferwallShowFailEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onOfferwallShowFailEvent(sse);
}
}
private static event Action _onOfferwallClosedEvent;
public static event Action onOfferwallClosedEvent
{
add
{
if (_onOfferwallClosedEvent == null || !_onOfferwallClosedEvent.GetInvocationList().Contains(value))
{
_onOfferwallClosedEvent += value;
}
}
remove
{
if (_onOfferwallClosedEvent.GetInvocationList().Contains(value))
{
_onOfferwallClosedEvent -= value;
}
}
}
public void onOfferwallClosed(string empty)
{
if (_onOfferwallClosedEvent != null)
{
_onOfferwallClosedEvent();
}
}
private static event Action<SupersonicError> _onGetOfferwallCreditsFailEvent;
public static event Action<SupersonicError> onGetOfferwallCreditsFailEvent
{
add
{
if (_onGetOfferwallCreditsFailEvent == null || !_onGetOfferwallCreditsFailEvent.GetInvocationList().Contains(value))
{
_onGetOfferwallCreditsFailEvent += value;
}
}
remove
{
if (_onGetOfferwallCreditsFailEvent.GetInvocationList().Contains(value))
{
_onGetOfferwallCreditsFailEvent -= value;
}
}
}
public void onGetOfferwallCreditsFail(string description)
{
if (_onGetOfferwallCreditsFailEvent != null)
{
SupersonicError sse = getErrorFromErrorString(description);
_onGetOfferwallCreditsFailEvent(sse);
}
}
private static event Action<Dictionary<string, object>> _onOfferwallAdCreditedEvent;
public static event Action<Dictionary<string, object>> onOfferwallAdCreditedEvent
{
add
{
if (_onOfferwallAdCreditedEvent == null || !_onOfferwallAdCreditedEvent.GetInvocationList().Contains(value))
{
_onOfferwallAdCreditedEvent += value;
}
}
remove
{
if (_onOfferwallAdCreditedEvent.GetInvocationList().Contains(value))
{
_onOfferwallAdCreditedEvent -= value;
}
}
}
public void onOfferwallAdCredited(string json)
{
if (_onOfferwallAdCreditedEvent != null)
_onOfferwallAdCreditedEvent(SupersonicJSON.Json.Deserialize(json) as Dictionary<string, object>);
}
#endregion
public SupersonicError getErrorFromErrorString(string description)
{
SupersonicError sse;
if (!String.IsNullOrEmpty(description))
{
Dictionary<string, object> error = SupersonicJSON.Json.Deserialize(description) as Dictionary<string, object>;
// if there is a supersonic error
if (error != null)
{
int eCode = Convert.ToInt32(error[ERROR_CODE].ToString());
string eDescription = error[ERROR_DESCRIPTION].ToString();
sse = new SupersonicError(eCode, eDescription);
}
// else create an empty one
else
{
sse = new SupersonicError(-1, "");
}
}
else
{
sse = new SupersonicError(-1, "");
}
return sse;
}
public SupersonicPlacement getPlacementFromString(string jsonPlacement)
{
Dictionary<string, object> placementJSON = SupersonicJSON.Json.Deserialize(jsonPlacement) as Dictionary<string, object>;
SupersonicPlacement ssp;
int rewardAmount = Convert.ToInt32(placementJSON["placement_reward_amount"].ToString());
string rewardName = placementJSON["placement_reward_name"].ToString();
string placementName = placementJSON["placement_name"].ToString();
ssp = new SupersonicPlacement(placementName, rewardName, rewardAmount);
return ssp;
}
}
|
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CODE.Framework.Wpf.Layout;
namespace CODE.Framework.Wpf.TestBench
{
/// <summary>
/// Interaction logic for PropertySheetTest.xaml
/// </summary>
public partial class PropertySheetTest : Window
{
public PropertySheetTest()
{
InitializeComponent();
Loaded += (s, e) =>
{
var exampleType = GetType();
var properties = exampleType.GetProperties();
var categories = new List<string> { string.Empty };
foreach (var property in properties)
{
var categoryName = GetCategory(property);
if (!string.IsNullOrEmpty(categoryName) && !categories.Contains(categoryName))
categories.Add(categoryName);
}
categories = categories.OrderBy(c => c).ToList();
foreach (var category in categories)
{
var first = true;
foreach (var property in properties.OrderBy(p => p.Name))
{
if (GetCategory(property) != category) continue;
var text = new TextBlock { Text = property.Name };
SimpleView.SetGroupTitle(text, !string.IsNullOrEmpty(category) ? category : " -- Uncategorized");
if (first) SimpleView.SetGroupBreak(text, true);
first = false;
var nativeValue = property.GetValue(this, null);
var editText = nativeValue == null ? string.Empty : nativeValue.ToString();
var edit = new TextBox { Text = editText };
PropertySheet.Children.Add(text);
PropertySheet.Children.Add(edit);
}
}
};
}
private string GetCategory(PropertyInfo property)
{
var attributes = property.GetCustomAttributes(typeof(CategoryAttribute), true);
if (attributes.Length > 0)
{
var categoryAttribute = attributes[0] as CategoryAttribute;
if (categoryAttribute != null)
return categoryAttribute.Category;
}
return string.Empty;
}
private void PropertySheetMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
var ps = sender as PropertySheet;
if (ps == null) return;
ps.ShowGroupHeaders = !ps.ShowGroupHeaders;
}
}
}
}
|
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PromoServiceCosmos.DataAccess.Utility
{
public interface ICosmosConnection
{
Task<DocumentClient> InitializeAsync(string collectionId);
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Lego.Ev3.Core;
using Lego.Ev3.Desktop;
namespace Hein.MindCuber.ConsoleProgram
{
class Program
{
private static Brick _brick;
private static readonly uint _oneFourthTurn = 900;
private static ColorSensor _colorSensor;
static async Task Main(string[] args)
{
await Connect();
await OneFourthTurn();
//await _colorSensor.MoveToPiece(ColorSensorPosition.MiddlePiece);
//Console.WriteLine($"Middle color: {_colorSensor.GetColor()}");
//await _colorSensor.MoveToPiece(ColorSensorPosition.Base);
Console.ReadLine();
}
private async static Task OneFourthTurn()
{
await _brick.DirectCommand.TurnMotorAtPowerForTimeAsync(OutputPort.C, 30, _oneFourthTurn, false);
Thread.Sleep(1000);
await _brick.DirectCommand.TurnMotorAtPowerForTimeAsync(OutputPort.C, -30, _oneFourthTurn, false);
Thread.Sleep(1000);
await _brick.DirectCommand.TurnMotorAtPowerForTimeAsync(OutputPort.C, 30, _oneFourthTurn / 2, false);
Thread.Sleep(1000);
await _brick.DirectCommand.TurnMotorAtPowerForTimeAsync(OutputPort.C, -30, _oneFourthTurn / 2, false);
}
private async static Task Connect()
{
_brick = new Brick(new UsbCommunication());
_colorSensor = new ColorSensor(_brick);
_colorSensor.ColorChanged += ColorSensorChanged;
await _brick.ConnectAsync();
Console.WriteLine($"color: {_colorSensor.GetColor()}");
}
private static void ColorSensorChanged(object sender, ColorSensorEventArgs e)
{
Console.WriteLine($"color: {e.Value}");
}
//private static void BrickChanged(object sender, BrickChangedEventArgs e)
//{
// float distance = e.Ports[InputPort.Four].SIValue;
// if (distance <= 20)
// {
// Console.WriteLine($"start: {distance}");
// }
// else
// {
// Console.WriteLine($"nope : {distance}");
// }
//}
}
}
|
using Alabo.Cloud.Cms.TeamIntro.Domain.Services;
using Alabo.Extensions;
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Alabo.Framework.Core.WebApis.Service;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using ZKCloud.Open.ApiBase.Models;
namespace Alabo.Cloud.Cms.TeamIntro.Controllers
{
[ApiExceptionFilter]
[Route("Api/Team/[action]")]
public class ApiTeamIntroController : ApiBaseController<Domain.Entities.TeamIntro, ObjectId>
{
public ApiTeamIntroController()
{
BaseService = Resolve<ITeamIntroService>();
}
/// <summary>
/// 获取团队成员列表
/// </summary>
/// <returns></returns>
[HttpGet]
[Display(Description = "获取团队成员列表")]
public ApiResult<IList<Domain.Entities.TeamIntro>> List()
{
try
{
var apiService = Resolve<IApiService>();
var ret = Resolve<ITeamIntroService>().GetList();
ret.Foreach(teamintro => teamintro.Image = apiService.ApiImageUrl(teamintro.Image));
return ApiResult.Success(ret);
}
catch (Exception e)
{
return ApiResult.Failure<IList<Domain.Entities.TeamIntro>>(e.Message);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculator
{
public static class StringExtension
{
public static string GetUserString(this OperationTypes oper)
{
switch (oper)
{
case OperationTypes.Unassigned:
return "unknown";
case OperationTypes.Plus:
return "+";
case OperationTypes.Substact:
return "-";
case OperationTypes.Multiply:
return "*";
case OperationTypes.Devide:
return "/";
default:
return "unknown";
}
}
}
}
|
using Rotativa.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
namespace CEMAPI.Controllers
{
public class PDFController : Controller
{
// GET: PDF
public ActionResult Index()
{
return View();
}
public ActionResult PDF()
{
return View();
}
public string PrintIndex()
{
var actionResult = new Rotativa.ActionAsPdf("PDF") //some route values)
{
FileName = "Test.pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Portrait,
PageMargins = { Left = 10, Right = 10 }, // it's in millimeters
PageWidth = 210, // it's in millimeters
PageHeight = 297
};
string filePath = HostingEnvironment.MapPath("~/UploadDocs/");
string filename = string.Empty;
filename = DateTime.Now.ToString();
filename = Regex.Replace(filename, @"[\[\]\\\^\$\.\|\?\*\+\(\)\{\}%,;: ><!@#&\-\+]", "");
var byteArray = actionResult.BuildPdf(ControllerContext);
var fileStream = new FileStream(filePath + "\\pdf-" + filename + ".pdf", FileMode.Create, FileAccess.Write);
fileStream.Write(byteArray, 0, byteArray.Length);
fileStream.Close();
string base64String = Convert.ToBase64String(byteArray, 0, byteArray.Length);
return base64String;
}
}
} |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.AppCenter;
using Welic.App.Models.Course;
using Welic.App.Models.Search;
using Welic.App.Services;
using Welic.App.ViewModels.Base;
using Xamarin.Forms;
namespace Welic.App.ViewModels
{
public class SearchViewModel : BaseViewModel
{
public ICommand SearchCommand { get; private set; }
public ObservableCollection<SearchDto> SearchFind { get; private set; }
public string ISearch{get ;}
public SearchViewModel()
{
ISearch = Util.ImagePorSistema("iFind");
SearchCommand = new Command<string>(async (text) => await Search(text));
SearchFind = new ObservableCollection<SearchDto>();
}
public async Task Search(string text)
{
try
{
SearchFind.Clear();
IsBusy = true;
var searchResults = await (new SearchDto()).SearchClient(text);
if (searchResults.Count > 0)
{
foreach (SearchDto search in searchResults)
{
SearchFind.Add(new SearchDto {Image = search.Image, Name = search.Name, Description = search.Description, Location = search.Location});
}
}
else
{
SearchFind.Clear();
}
}
catch (FormatException ex)
{
Console.WriteLine(ex);
IsBusy = false;
return;
}
catch (System.Exception e)
{
Console.WriteLine(e);
IsBusy = false;
return;
}
}
public async Task ClearSearch()
{
SearchFind.Clear();
IsBusy = false;
}
public async Task<ObservableCollection<SearchDto>> SearchCursos(string text)
{
try
{
SearchFind.Clear();
IsBusy = true;
return await (new SearchDto()).SearchCursos(text);
//if (searchResults.Count > 0)
//{
// foreach (SearchDto search in searchResults)
// {
// SearchFind.Add(new SearchDto { Image = search.Image, Name = search.Name, Description = search.Description, Location = search.Location });
// }
// return SearchFind;
//}
//return null;
}
catch (FormatException ex)
{
Console.WriteLine(ex);
IsBusy = false;
return null;
}
catch (System.Exception e)
{
Console.WriteLine(e);
IsBusy = false;
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Newtonsoft.Json;
using PluginDevelopment.Helper;
using PluginDevelopment.Helper.Dapper.NET;
using PluginDevelopment.Model;
namespace PluginDevelopment.DAL
{
public class TreeDocumentOperation
{
private static readonly DbBase Dbbase = new DbBase("DefaultConnectionString");
/// <summary>
/// 获取树形文档列表
/// </summary>
/// <returns></returns>
public static string GetTreeDocument()
{
var sqlStr = "select * from menu a group by a.sort";
IList<Menu> menuList;
var result = new List<object>();
using (var conDbconnection = Dbbase.DbConnecttion)
{
menuList = conDbconnection.Query<Menu>(sqlStr).ToList();
}
//获取根节点
foreach (var org in menuList.Where(x => string.IsNullOrEmpty(x.ParentId)))
{
result.Add(new
{
Parent = 0,
Key = org.Id,
Name = org.Name,
Icon = org.Icon,
Url = org.Url
});
//根据根节点查询该根节点下的所有子节点
FeatchMenuChildren(result, menuList, org);
}
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 递归填充菜单下的子菜单
/// </summary>
/// <param name="result">返回前台的菜单集合</param>
/// <param name="menus">所有的菜单列表</param>
/// <param name="menu">当前菜单</param>
public static void FeatchMenuChildren(List<object> result, IList<Menu> menus, Menu menu)
{
//根据节点ID获取该查询子节点list集合
var childrenMenus = menus.Where(x => x.ParentId.Equals(menu.Id));
var childMenus = childrenMenus as Menu[] ?? childrenMenus.ToArray();
if (!childMenus.Any()) return;
foreach (var childMenu in childMenus)
{
result.Add(new
{
Parent = menu.Id,
Key = childMenu.Id,
Name = childMenu.Name,
Icon = childMenu.Icon,
Url = childMenu.Url
});
FeatchMenuChildren(result, menus, childMenu);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aula02_ExMultiplicacao
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite o primeiro Numero: ");
Double N1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Digite o segundo Número: ");
Double N2 = Convert.ToDouble(Console.ReadLine());
double Resultado = N1 * N2;
string menagem = "Resultado";
menagem += string.Format(" {0} * {1} = {2} " , N1 , N2 ,Resultado);
Console.WriteLine(menagem);
Console.ReadLine();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using EventSystem;
public class UnitDisplay : MB
{
public Unit unit;
public Text rentAmount;
public GameObject repairGroup;
public GameObject rentEditGroup;
public InputField rentInput;
void Awake() {
repairGroup.SetActive(false);
rentEditGroup.SetActive(false);
}
void Start() {
rentAmount.text = string.Format("${0}", unit.Rent.ToDisplay());
}
public void Ignore() {
unit.IgnoreRepair();
Events.instance.Raise(new IgnoreRepairUnitEvent(unit));
repairGroup.SetActive(false);
}
public void Repair() {
unit.Repair();
Events.instance.Raise(new RepairUnitEvent(unit));
repairGroup.SetActive(false);
}
public void IncreaseRent() {
rentInput.text = (int.Parse(rentInput.text) + 100).ToString();
unit.Rent = int.Parse(rentInput.text);
}
public void ReduceRent() {
rentInput.text = (int.Parse(rentInput.text) - 100).ToString();
unit.Rent = int.Parse(rentInput.text);
}
protected override void AddListeners() {
Events.instance.AddListener<NewMonthEvent>(OnNewMonthEvent);
Events.instance.AddListener<EndYearEvent>(OnEndYearEvent);
Events.instance.AddListener<BeginYearEvent>(OnBeginYearEvent);
}
void OnNewMonthEvent(NewMonthEvent e) {
if (unit.RepairNeeded) {
repairGroup.SetActive(true);
}
}
void OnEndYearEvent(EndYearEvent e) {
rentEditGroup.SetActive(true);
rentAmount.gameObject.SetActive(false);
}
void OnBeginYearEvent(BeginYearEvent e) {
rentEditGroup.SetActive(false);
rentAmount.gameObject.SetActive(true);
rentAmount.text = string.Format("${0}", unit.Rent.ToDisplay());
}
}
|
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Media.Ocr;
using Windows.Storage;
using Windows.Storage.Streams;
namespace RegularIntervalOCR
{
public class OCR
{
private static string folder;
public OCR()
{
folder = Directory.GetCurrentDirectory();
}
public void SaveText(string txt)
{
//var fileName = "ocr_result.txt";
var fileName = "output.html";
// 文字コードを指定
Encoding enc = Encoding.GetEncoding("utf-8");
// ファイルを開く
StreamWriter writer = new StreamWriter($@"{folder}\{fileName}", false, enc);
// テキストを書き込む
writer.WriteLine(txt);
// ファイルを閉じる
writer.Close();
}
public async Task<SoftwareBitmap> ConvertToSoftwareBitmap(Bitmap bmp)
{
// 取得したキャプチャ画像をファイルとして保存
var fileName = "screenshot.bmp";
bmp.Save($@"{folder}\{fileName}", ImageFormat.Bmp);
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(@folder);
var bmpFile = await appFolder.GetFileAsync(fileName);
// 保存した画像をSoftwareBitmap形式で読み込み
SoftwareBitmap softwareBitmap;
using (IRandomAccessStream stream = await bmpFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
softwareBitmap = await decoder.GetSoftwareBitmapAsync();
}
return softwareBitmap;
}
public async Task<OcrResult> RecognizeText(Bitmap bmp)
{
var sbmp = await ConvertToSoftwareBitmap(bmp);
Windows.Globalization.Language language = new Windows.Globalization.Language("en");
OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(language);
//OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
var ocrResult = await ocrEngine.RecognizeAsync(sbmp);
return ocrResult;
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Eevee.Models
{
public class Playlist
{
public int PlaylistID { get; set; }
[Required]
public string Name { get; set; } = "Playlist";
[Required]
public User User { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nata_lab5
{
class Program
{
static void Main(string[] args)
{
int a=0;
int[] masiv = new int[10];//Обявлення масиву данних на 10 чисел
Console.WriteLine("Vvedi 10 chsisel");
for(int i = 0; i < 10; i++)
{
masiv[i] = Convert.ToInt32(Console.ReadLine());//введення данних за доп масиву
Console.Clear(); //функц очистки екрану
Console.WriteLine(" Danni vvedeni vvodite dalshe");//вивід повідомлення на екран
}
for (int i = 0; i < 10; i++)//цикл з лічильником
{
a = a + masiv[i]; //сумування чисел в циклі
}
Console.Clear();
Console.WriteLine(" Suma:{0}",a);//Вивід суми на екран
Console.ReadKey(); //функц натискання на кнопку для продовження
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using OccBooking.Common.Types;
namespace OccBooking.Domain.Events
{
public class EmptyHallReservationMade : IEvent
{
public EmptyHallReservationMade(Guid hallId)
{
HallId = hallId;
}
public Guid HallId { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
namespace Microsoft.master2
{
public class VSCommandInterceptor : IDisposable
{
private IServiceProvider serviceProvider;
private Guid guid;
private int id;
private bool isDisposed;
public VSCommandInterceptor(IServiceProvider serviceProvider, Guid commandGuid, int commandId)
{
this.serviceProvider = serviceProvider;
this.guid = commandGuid;
this.id = commandId;
if (CommandEvents != null)
{
CommandEvents.AfterExecute += new _dispCommandEvents_AfterExecuteEventHandler(OnAfterExecute);
CommandEvents.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(OnBeforeExecute);
}
}
public event EventHandler<EventArgs> AfterExecute;
public event EventHandler<EventArgs> BeforeExecute;
private CommandEvents commandEvents;
protected CommandEvents CommandEvents
{
get
{
if (commandEvents == null)
{
DTE dte = this.serviceProvider.GetService(typeof(DTE)) as DTE;
if (dte != null)
{
commandEvents = dte.Events.get_CommandEvents(guid.ToString("B"), id) as CommandEvents;
}
}
return commandEvents;
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.isDisposed && disposing)
{
if (CommandEvents != null)
{
CommandEvents.AfterExecute -= OnAfterExecute;
CommandEvents.BeforeExecute -= OnBeforeExecute;
}
this.isDisposed = true;
}
}
private void OnAfterExecute(string Guid, int ID, object CustomIn, object CustomOut)
{
if (AfterExecute != null)
{
AfterExecute(this, new EventArgs());
}
}
private void OnBeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
{
if (BeforeExecute != null)
{
BeforeExecute(this, new EventArgs());
}
}
}
}
|
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UPractice.Dbcontext;
namespace UPractice.Model
{
class AddChairModel : BindableBase
{
public ReadOnlyObservableCollection<Teacher> Teachers { get; }
public AddChairModel()
{
using (var db = new MyDbcontext())
{
ObservableCollection<Teacher> teachers = new ObservableCollection<Teacher>(db.Teachers);
Teachers = new ReadOnlyObservableCollection<Teacher>(teachers);
}
}
public void AddChair(string name, string shortname, Teacher teacher)
{
Chair chair = new Chair()
{
NameChair = name,
ShortNameChair = shortname,
};
using (var db = new MyDbcontext())
{
db.Chairs.Add(chair);
db.SaveChanges();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
public partial class pages_pass : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod()]
public static string AjaxMethodck(string admin, string psw0, string psw1)
{
MySqlConnection _sqlConnect;//Mysql连接对象
MySqlCommand _sqlCommand;//Mysql命令对象
string _strConnectString;//连接字符串
_strConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlhuaian"].ToString();
_sqlConnect = new MySqlConnection(_strConnectString);
_sqlCommand = new MySqlCommand("", _sqlConnect);
_sqlConnect.Open();
_sqlCommand.Parameters.AddWithValue("@admin", admin);
_sqlCommand.Parameters.AddWithValue("@password", psw0);
_sqlCommand.Parameters.AddWithValue("@Cpassword", psw1);
_sqlCommand.CommandText = "SELECT * FROM t_haadmin WHERE admin_id=@admin AND admin_password=@password";
if (_sqlCommand.Connection == null)
{
_sqlCommand.Connection = _sqlConnect;
}
try
{
_sqlCommand.ExecuteScalar().ToString();
}
catch
{
_sqlConnect.Close();
return "0";
}
_sqlCommand.CommandText = "UPDATE t_haadmin SET admin_password=@Cpassword WHERE admin_id=@admin";
_sqlCommand.ExecuteScalar();
_sqlConnect.Close();
return "1";
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.SYS;
namespace com.Sconit.Entity.ORD
{
[Serializable]
public partial class OrderDetail : EntityBase, IAuditable
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 20)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 10)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 10)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 10)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 10)]
[Display(Name = "OrderDetail_OrderNo", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string OrderNo { get; set; }
public com.Sconit.CodeMaster.OrderType OrderType { get; set; }
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 130)]
//[Export(ExportName = "DistributionOrderDetail", ExportSeq = 130)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 120)]
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.OrderType, ValueField = "OrderType")]
[Display(Name = "OrderMaster_Type", ResourceType = typeof(Resources.ORD.OrderMaster))]
public string OrderTypeDescription { get; set; }
public com.Sconit.CodeMaster.OrderSubType OrderSubType { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 10)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 20)]
//[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 40)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 20)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 30)]
[Display(Name = "OrderDetail_Sequence", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Int32 Sequence { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 40)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 30)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 30)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 30)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 20)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "OrderDetail_Item", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Item { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 60)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 50)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 60)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 50)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 50)]
[Display(Name = "OrderDetail_ItemDescription", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ItemDescription { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 50)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 40)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 50)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 40)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 40)]
[Display(Name = "OrderDetail_ReferenceItemCode", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ReferenceItemCode { get; set; }
public string BaseUom { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 80)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 70)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 80)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 60)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 70)]
[Display(Name = "OrderDetail_Uom", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Uom { get; set; }
//[Export(ExportName = "OrderDetail", ExportSeq =125)]
//[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 140)]
[Display(Name = "OrderDetail_PartyFrom", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string PartyFrom { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 70)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 60)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 60)]
[Display(Name = "OrderDetail_UnitCount", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal UnitCount { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 90)]
//[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 90)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 70)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 80)]
[Display(Name = "OrderDetail_UnitCountDescription", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string UnitCountDescription { get; set; }
//[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 70)]
[Display(Name = "OrderDetail_MinUnitCount", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal MinUnitCount { get; set; }
[Display(Name = "OrderDetail_QualityType", ResourceType = typeof(Resources.ORD.OrderDetail))]
public com.Sconit.CodeMaster.QualityType QualityType { get; set; }
[Display(Name = "OrderDetail_ManufactureParty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ManufactureParty { get; set; }
[Display(Name = "OrderDetail_RequiredQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal RequiredQty { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 120)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 100)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 130, ExportTitle = "OrderDetail_OrderedQtyReturn", ExportTitleResourceType = typeof(@Resources.ORD.OrderDetail))]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 90)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 110)]
[Display(Name = "OrderDetail_OrderedQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal OrderedQty { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 130)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 110)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 120)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 110)]
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 100)]
[Display(Name = "OrderDetail_ShippedQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal ShippedQty { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 140)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 120)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 120)]
[Display(Name = "OrderDetail_ReceivedQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal ReceivedQty { get; set; }
[Display(Name = "OrderDetail_RejectedQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal RejectedQty { get; set; }
[Display(Name = "OrderDetail_ScrapQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal ScrapQty { get; set; }
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 100)]
[Display(Name = "OrderDetail_PickedQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal PickedQty { get; set; }
[Display(Name = "OrderDetail_UnitQty", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal UnitQty { get; set; }
[Display(Name = "OrderDetail_ReceiveLotSize", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal? ReceiveLotSize { get; set; }
[Display(Name = "OrderDetail_LocationFrom", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string LocationFrom { get; set; }
[Display(Name = "OrderDetail_LocationFromName", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string LocationFromName { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 110)]
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 80)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 110)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 80)]
//[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 90)]
[Display(Name = "OrderDetail_LocationTo", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string LocationTo { get; set; }
[Display(Name = "OrderDetail_LocationToName", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string LocationToName { get; set; }
[Display(Name = "OrderDetail_IsInspect", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Boolean IsInspect { get; set; }
//[Display(Name = "OrderDetail_InspectLocation", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public string InspectLocation { get; set; }
//[Display(Name = "OrderDetail_InspectLocationName", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public string InspectLocationName { get; set; }
//[Display(Name = "OrderDetail_RejectLocation", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public string RejectLocation { get; set; }
//[Display(Name = "OrderDetail_RejectLocationName", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public string RejectLocationName { get; set; }
[Display(Name = "OrderDetail_BillAddress", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string BillAddress { get; set; }
[Display(Name = "OrderDetail_BillAddressDescription", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string BillAddressDescription { get; set; }
[Display(Name = "OrderDetail_PriceList", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string PriceList { get; set; }
[Display(Name = "OrderDetail_UnitPrice", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Decimal? UnitPrice { get; set; }
[Display(Name = "OrderDetail_IsProvisionalEstimate", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Boolean IsProvisionalEstimate { get; set; }
[Display(Name = "OrderDetail_Tax", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Tax { get; set; }
[Display(Name = "OrderDetail_IsIncludeTax", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Boolean IsIncludeTax { get; set; }
[Display(Name = "OrderDetail_Bom", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Bom { get; set; }
[Display(Name = "OrderDetail_Routing", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Routing { get; set; }
//[Display(Name = "OrderDetail_ProductionScan", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public string ProductionScan { get; set; }
//[Display(Name = "OrderDetail_HuLotSize", ResourceType = typeof(Resources.ORD.OrderDetail))]
//public Decimal? HuLotSize { get; set; }
[Display(Name = "OrderDetail_BillTerm", ResourceType = typeof(Resources.ORD.OrderDetail))]
public com.Sconit.CodeMaster.OrderBillTerm BillTerm { get; set; }
public string ZOPWZ { get; set; }
public string ZOPID { get; set; }
public string ZOPDS { get; set; }
public Int32 CreateUserId { get; set; }
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 120)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 140)]
[Display(Name = "OrderDetail_CreateUserName", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string CreateUserName { get; set; }
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 130)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 150)]
[Display(Name = "OrderDetail_CreateDate", ResourceType = typeof(Resources.ORD.OrderDetail))]
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
[Display(Name = "OrderDetail_LastModifyUserName", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string LastModifyUserName { get; set; }
[Display(Name = "OrderDetail_LastModifyDate", ResourceType = typeof(Resources.ORD.OrderDetail))]
public DateTime LastModifyDate { get; set; }
[Display(Name = "OrderDetail_Version", ResourceType = typeof(Resources.ORD.OrderDetail))]
public Int32 Version { get; set; }
[Display(Name = "OrderDetail_Container", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Container { get; set; }
[Display(Name = "OrderDetail_ContainerDescription", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ContainerDescription { get; set; }
public string Currency { get; set; }
public string PickStrategy { get; set; }
public string ExtraDemandSource { get; set; }
public Boolean IsScanHu { get; set; }
[Export(ExportName = "ProcumentOrderDetail", ExportSeq = 15)]
[Export(ExportName = "DistributionOrderDetail", ExportSeq = 15)]
[Display(Name = "OrderDetail_ExternalOrderNo", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string ExternalOrderNo { get; set; }
public string ExternalSequence { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
//
public CodeMaster.ScheduleType ScheduleType { get; set; }
public string ReserveNo { get; set; }
public string ReserveLine { get; set; }
public string BinTo { get; set; }
[Export(ExportName = "OrderDetail", ExportSeq = 30)]
[Export(ExportName = "ProcumentReturnOrderDetail", ExportSeq = 20)]
[Display(Name = "OrderDetail_WMSSeq", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string WMSSeq { get; set; }
public Boolean IsChangeUnitCount { get; set; }
public string AUFNR { get; set; }
public string ICHARG { get; set; }
public string BWART { get; set; }
[Display(Name = "OrderDetail_Direction", ResourceType = typeof(Resources.ORD.OrderDetail))]
public string Direction { get; set; }
[Export(ExportName = "DistributionReturnOrderDetail", ExportSeq = 140)]
[Display(Name = "Hu_Remark", ResourceType = typeof(Resources.INV.Hu))]
public string Remark { get; set; }
public string PalletCode { get; set; }
public Decimal PalletLotSize { get; set; }
public Decimal PackageVolume { get; set; }
public Decimal PackageWeight { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
OrderDetail another = obj as OrderDetail;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using Backend.Model.Users;
using GraphicalEditorServer.DTO;
namespace GraphicalEditorServer.Mappers
{
public class PatientMapper
{
public static PatientBasicDTO PatientAndPatientCardToPatientBasicDTO(Patient patient, PatientCard patientCard)
{
return new PatientBasicDTO(patient.Name, patient.Surname, patient.Jmbg, patientCard.Id);
}
public static PatientBasicDTO PatientToPatientBasicDTO(Patient patient)
{
return new PatientBasicDTO(patient.Name, patient.Surname, patient.Jmbg, patient.PatientCard.Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace upSight.CartaoCorp.Identificacao.ACSOIDTS
{
public class Portador
{
public virtual string TpRegistro { get; set; }
//= dr["TpPanProxy"].ToString();
public virtual string TpIdentif { get; set; }
//string panProxy = dr["PanProxy"].ToString();
[Required]
public virtual string Identificacao { get; set; }
[Required]
public virtual string CPF { get; set; }
[Required]
public virtual string Nome { get; set; }
public virtual string NomeFacial { get; set; }
public virtual DateTime? DtNascimento { get; set; }
public virtual string Sexo { get; set; }
public virtual string CnpjFilial { get; set; }
public virtual string Grupo { get; set; }
public virtual string Email { get; set; }
public virtual string DDDCel { get; set; }
public virtual string Celular { get; set; }
public virtual string NomeMae { get; set; }
public int? IdRegistro { get; set; }
public virtual string CodConvenio { get; set; }
public virtual int IdEntidade { get; set; }
}
public class MapaColunaPortador
{
public int TpIdentif { get; set; }
public int Identificacao { get; set; }
public int CPF { get; set; }
public int Nome { get; set; }
public int NomeFacial { get; set; }
public int DtNascimento { get; set; }
public int Sexo { get; set; }
public int CnpjFilial { get; set; }
public int Grupo { get; set; }
public int Email { get; set; }
public int DDDCel { get; set; }
public int Celular { get; set; }
public int NomeMae { get; set; }
public int IdRegistro { get; set; }
public int CodConvenio { get; set; }
public int IdEntidade { get; set; }
}
}
|
namespace Sentry.Internal;
/// <summary>
/// Provides a keyed set of counters that can be incremented, read, and reset atomically.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
internal class ThreadsafeCounterDictionary<TKey> : IReadOnlyDictionary<TKey, int>
where TKey : notnull
{
private class CounterItem
{
private int _value;
public int Value => _value;
public void Add(int quantity) => Interlocked.Add(ref _value, quantity);
public void Increment() => Interlocked.Increment(ref _value);
public int ReadAndReset() => Interlocked.Exchange(ref _value, 0);
}
private readonly ConcurrentDictionary<TKey, CounterItem> _items = new();
/// <summary>
/// Atomically adds to a counter based on the key provided, creating the counter if necessary.
/// </summary>
/// <param name="key">The key of the counter to increment.</param>
/// <param name="quantity">The amount to add to the counter.</param>
public void Add(TKey key, int quantity) => _items.GetOrAdd(key, new CounterItem()).Add(quantity);
/// <summary>
/// Atomically increments a counter based on the key provided, creating the counter if necessary.
/// </summary>
/// <param name="key">The key of the counter to increment.</param>
public void Increment(TKey key) => _items.GetOrAdd(key, new CounterItem()).Increment();
/// <summary>
/// Gets a single counter's value while atomically resetting it to zero.
/// </summary>
/// <param name="key">The key to the counter.</param>
/// <returns>The previous value of the counter.</returns>
/// <remarks>If no counter with the given key has been set, this returns zero.</remarks>
public int ReadAndReset(TKey key) => _items.TryGetValue(key, out var item) ? item.ReadAndReset() : 0;
/// <summary>
/// Gets the keys and values of all of the counters while atomically resetting them to zero.
/// </summary>
/// <returns>A read-only dictionary containing the key and the previous value for each counter.</returns>
public IReadOnlyDictionary<TKey, int> ReadAllAndReset()
{
// Read all the counters while atomically resetting them to zero
var counts = _items.ToDictionary(
x => x.Key,
x => x.Value.ReadAndReset());
return new ReadOnlyDictionary<TKey, int>(counts);
}
/// <summary>
/// Gets an enumerator over the keys and values of the counters.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<KeyValuePair<TKey, int>> GetEnumerator() => _items
.Select(x => new KeyValuePair<TKey, int>(x.Key, x.Value.Value))
.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Gets the number of counters currently being tracked.
/// </summary>
public int Count => _items.Count;
/// <summary>
/// Tests whether or not a counter with the given key exists.
/// </summary>
/// <param name="key">The key to check.</param>
/// <returns>True if the counter exists, false otherwise.</returns>
public bool ContainsKey(TKey key) => _items.ContainsKey(key);
/// <summary>
/// Gets the current value of the counter specified.
/// </summary>
/// <param name="key">The key of the counter.</param>
/// <param name="value">The value of the counter, or zero if the counter does not yet exist.</param>
/// <returns>Returns <c>true</c> in all cases.</returns>
public bool TryGetValue(TKey key, out int value)
{
value = this[key];
return true;
}
/// <summary>
/// Gets the current value of the counter specified, returning zero if the counter does not yet exist.
/// </summary>
/// <param name="key">The key of the counter.</param>
public int this[TKey key] => _items.TryGetValue(key, out var item) ? item.Value : 0;
/// <summary>
/// Gets all of the current counter keys.
/// </summary>
public IEnumerable<TKey> Keys => _items.Keys;
/// <summary>
/// Gets all of the current counter values.
/// </summary>
/// <remarks>
/// Useless, but required by the IReadOnlyDictionary interface.
/// </remarks>
public IEnumerable<int> Values => _items.Values.Select(x => x.Value);
}
|
using System.Windows.Media;
namespace Crystal.Plot2D
{
public static class BrushHelper
{
/// <summary>
/// Creates a SolidColorBrush with random hue of its color.
/// </summary>
/// <returns>
/// A SolicColorBrush with random hue of its color.
/// </returns>
public static SolidColorBrush CreateBrushWithRandomHue()
{
return new SolidColorBrush { Color = ColorHelper.CreateColorWithRandomHue() };
}
/// <summary>
/// Makes SolidColorBrush transparent.
/// </summary>
/// <param name="brush">
/// The brush.
/// </param>
/// <param name="alpha">
/// The alpha, [0..255]
/// </param>
/// <returns></returns>
public static SolidColorBrush MakeTransparent(this SolidColorBrush brush, int alpha)
{
Color color = brush.Color;
color.A = (byte)alpha;
return new SolidColorBrush(color);
}
/// <summary>
/// Makes SolidColorBrush transparent.
/// </summary>
/// <param name="brush">
/// The brush.
/// </param>
/// <param name="alpha">
/// The alpha, [0.0 .. 1.0].
/// </param>
/// <returns></returns>
public static SolidColorBrush MakeTransparent(this SolidColorBrush brush, double opacity)
{
return MakeTransparent(brush, (int)(opacity * 255));
}
public static SolidColorBrush ChangeLightness(this SolidColorBrush brush, double lightnessFactor)
{
var color = brush.Color;
var hsbColor = HsbColor.FromArgbColor(color);
hsbColor.Brightness *= lightnessFactor;
if (hsbColor.Brightness > 1.0)
{
hsbColor.Brightness = 1.0;
}
var result = new SolidColorBrush(hsbColor.ToArgbColor());
return result;
}
public static SolidColorBrush ChangeSaturation(this SolidColorBrush brush, double saturationFactor)
{
var color = brush.Color;
var hsbColor = HsbColor.FromArgbColor(color);
hsbColor.Saturation *= saturationFactor;
if (hsbColor.Saturation > 1.0)
{
hsbColor.Saturation = 1.0;
}
var result = new SolidColorBrush(hsbColor.ToArgbColor());
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace _10_Population_Counter
{
public class _10_Population_Counter
{
public static void Main()
{
var result = new Dictionary<string, Dictionary<string, int>>();
var countryPopulation = new Dictionary<string, long>();
var input = Console.ReadLine();
while (input != "report")
{
var line = input.Split('|');
var town = line[0];
var country = line[1];
var population = int.Parse(line[2]);
if (!result.ContainsKey(country))
{
result[country] = new Dictionary<string, int>();
countryPopulation[country] = 0;
}
var towns = result[country];
if (!towns.ContainsKey(town))
{
towns[town] = 0;
}
towns[town] = population;
countryPopulation[country] += population;
input = Console.ReadLine();
}
foreach (var country in countryPopulation.OrderByDescending(x => x.Value))
{
Console.WriteLine($"{country.Key} (total population: {country.Value})");
var currentTown = result.First(x => x.Key == country.Key);
var towns = currentTown.Value;
foreach (var item in towns.OrderByDescending(x => x.Value))
{
Console.WriteLine($"=>{item.Key}: {item.Value}");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace WpfApp1
{
public class MainWindowViewModel : INotifyPropertyChanged
{
private int count;
public int Count
{
get => this.count;
set => this.SetProperty(ref this.count, value);
}
private string pluginDir;
public string PluginDir
{
get => this.pluginDir;
set => this.SetProperty(ref this.pluginDir, value);
}
private string input;
public string Input
{
get => this.input;
set => this.SetProperty(ref this.input, value);
}
private string outstring;
public string OutString
{
get => this.outstring;
set => this.SetProperty(ref this.outstring, value);
}
private ObservableCollection<PluginBase.ModPlugin> plugins = new ObservableCollection<PluginBase.ModPlugin>();
public ObservableCollection<PluginBase.ModPlugin> Plugins
{
get => this.plugins;
set => this.SetProperty(ref this.plugins, value);
}
protected void SetProperty<T>(ref T property, T value, [CallerMemberName]string propertyName = "")
{
property = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
namespace Assets.Scripts.AISystem
{
public class AIBrain : MonoBehaviour
{
public AIAction currentAction;
public AIAction initialAction;
public float? currenActionStarted = null;
private void Awake()
{
if(initialAction != null)
{
currentAction = initialAction;
}
}
private void FixedUpdate()
{
if (currenActionStarted == null)
{
currenActionStarted = Time.time;
}
currentAction.Action();
foreach (var current in currentAction.transitions)
{
var result = current.decision.Decide();
if (result && current.toTrue != null)
{
currenActionStarted = Time.time;
currentAction.ExitAction();
currentAction = current.toTrue;
}
else if (!result && current.toFalse != null)
{
currenActionStarted = Time.time;
currentAction.ExitAction();
currentAction = current.toFalse;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Query.DTO
{
public class AdjustStorePriceItemDto
{
public int ProductId { get; set; }
/// <summary>
/// 品名
/// </summary>
public string ProductName { get; set; }
/// <summary>
/// 商品编码
/// </summary>
public string ProductCode { get; set; }
public string BarCode { get; set; }
public string Specification { get; set; }
public string Unit { get; set; }
/// <summary>
/// 最新进价
/// </summary>
public decimal LastCostPrice { get; set; }
/// <summary>
/// 总部指导价
/// </summary>
public decimal SalePrice { get; set; }
/// <summary>
/// 门店售价
/// </summary>
public decimal StoreSalePrice { get; set; }
/// <summary>
/// 调整价
/// </summary>
public decimal AdjustPrice { get; set; }
/// <summary>
/// 毛利
/// </summary>
public decimal Profit { get {
var result = AdjustPrice - LastCostPrice;
return result;
} }
/// <summary>
/// 毛利率
/// </summary>
public decimal ProfitMargin { get {
if (this.AdjustPrice == 0)
{
return 0;
}
return Math.Round(this.Profit / this.AdjustPrice, 2);
} }
}
}
|
using OrgMan.Common.DynamicSearchService.DynamicSearchModel.Enums;
using System.Collections.Generic;
namespace OrgMan.Common.DynamicSearchService.DynamicSearchModel
{
public class SearchCriteriaDomainModel
{
public string Title { get; set; }
public string FieldName { get; set; }
public List<object> Values { get; set; }
public SearchCriteriaDataTypeDomainModelEnum DataType { get; set; }
public SearchCriteriaOperationTypeDomainModelEnum OperationType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace DAL.Contracts
{
public interface IBaseRepository<T> where T : class
{
IEnumerable<T> Get(Expression<Func<T, bool>> filter = null,
Func< IQueryable<T>, IOrderedQueryable<T> > orderBy = null,
string includeProperties = "");
T GetById(object id);
void Insert(T entity);
void Delete(object id);
void Delete(T entity);
void Update(T entity);
void Save();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Airelax.Application.Messages.Response;
using Airelax.Application.Messages;
using Airelax.Application.Messages.Request;
namespace Airelax.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class MessagesController : ControllerBase
{
private readonly IMessageService _messageService;
public MessagesController(IMessageService messageService)
{
_messageService = messageService;
}
[HttpGet]
[Route("{memberId}")]
public async Task<List<MessageDto>> Get(string memberId)
{
return await _messageService.GetMessage(memberId);
}
[HttpPut]
[Route("{memberId}/content")]
public IActionResult UpdateContent(string memberId, MessageInupt messageInupt)
{
var message = _messageService.UpdateContent(memberId, messageInupt);
return Ok(message);
}
[HttpPost]
[Route("{memberId}/create")]
public IActionResult CreateContent(string memberId, CreateMessageInput messageInupt)
{
var message = _messageService.CreateContent(memberId, messageInupt);
return Ok(message);
}
[HttpPut]
[Route("{memberId}/status")]
public IActionResult UpdateStatus(string memberId, UpdateStatusInput statusInupt)
{
var message = _messageService.UpdateStatus(memberId, statusInupt);
return Ok(message);
}
[HttpPut]
[Route("{memberId}/ontime")]
public IActionResult UpdateOnTime(string memberId, UpdateStatusInput statusInupt)
{
var message = _messageService.UpdateOnTime(memberId, statusInupt);
return Ok(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ChessDotNetBackend
{
public class TranspositionTable
{
Dictionary<long, double> m_leafScores = new Dictionary<long, double>();
internal bool ContainsLeafScore(ZobristHash hash) => m_leafScores.ContainsKey(hash.Hash);
internal double LeafScore(ZobristHash hash) => m_leafScores[hash.Hash];
internal void UpdateLeafScore(ZobristHash hash, double whitesScore) => m_leafScores[hash.Hash] = whitesScore;
}
}
|
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using CODE.Framework.Wpf.Utilities;
namespace CODE.Framework.Wpf.Layout
{
/// <summary>
/// This panel can lay out primary/secondary element views in a horizontal fashion, with added features, such as collapsing the secondary part.
/// </summary>
public class PrimarySecondaryHorizontalPanel : Panel
{
/// <summary>
/// Defines whether the secondary part of the UI can be collapsed
/// </summary>
/// <value><c>true</c> if this instance can collapse secondary; otherwise, <c>false</c>.</value>
public bool CanCollapseSecondary
{
get { return (bool) GetValue(CanCollapseSecondaryProperty); }
set { SetValue(CanCollapseSecondaryProperty, value); }
}
/// <summary>
/// Defines whether the secondary part of the UI can be collapsed
/// </summary>
public static readonly DependencyProperty CanCollapseSecondaryProperty = DependencyProperty.Register("CanCollapseSecondary", typeof (bool), typeof (PrimarySecondaryHorizontalPanel), new PropertyMetadata(true));
/// <summary>
/// Indicates whether the secondary element is currently collapsed
/// </summary>
/// <value><c>true</c> if this instance is secondary element collapsed; otherwise, <c>false</c>.</value>
public bool IsSecondaryElementCollapsed
{
get { return (bool) GetValue(IsSecondaryElementCollapsedProperty); }
set { SetValue(IsSecondaryElementCollapsedProperty, value); }
}
/// <summary>
/// Indicates whether the secondary element is currently collapsed
/// </summary>
public static readonly DependencyProperty IsSecondaryElementCollapsedProperty = DependencyProperty.Register("IsSecondaryElementCollapsed", typeof (bool), typeof (PrimarySecondaryHorizontalPanel), new PropertyMetadata(false, OnIsSecondaryElementCollapsedChanged));
/// <summary>
/// Fires when the collapse state of the secondary element changes
/// </summary>
/// <param name="d">The panel object</param>
/// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnIsSecondaryElementCollapsedChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
var panel = d as PrimarySecondaryHorizontalPanel;
if (panel == null) return;
panel.InvalidateMeasure();
panel.InvalidateArrange();
panel.InvalidateVisual();
}
/// <summary>
/// Spacing between primary and secondary elements
/// </summary>
/// <value>The element spacing.</value>
public double ElementSpacing
{
get { return (double) GetValue(ElementSpacingProperty); }
set { SetValue(ElementSpacingProperty, value); }
}
/// <summary>
/// Spacing between primary and secondary elements
/// </summary>
public static readonly DependencyProperty ElementSpacingProperty = DependencyProperty.Register("ElementSpacing", typeof (double), typeof (PrimarySecondaryHorizontalPanel), new PropertyMetadata(3d));
/// <summary>
/// Width available to the secondary element
/// </summary>
/// <value>The width of the secondary element.</value>
public double SecondaryElementWidth
{
get { return (double) GetValue(SecondaryElementWidthProperty); }
set { SetValue(SecondaryElementWidthProperty, value); }
}
/// <summary>
/// Width available to the secondary element
/// </summary>
public static readonly DependencyProperty SecondaryElementWidthProperty = DependencyProperty.Register("SecondaryElementWidth", typeof (double), typeof (PrimarySecondaryHorizontalPanel), new PropertyMetadata(200d));
/// <summary>
/// Header renderer used to render visual aspects of the panel
/// </summary>
/// <value>The header renderer.</value>
public IPrimarySecondaryHorizontalPanelHeaderRenderer HeaderRenderer
{
get { return (IPrimarySecondaryHorizontalPanelHeaderRenderer)GetValue(HeaderRendererProperty); }
set { SetValue(HeaderRendererProperty, value); }
}
/// <summary>
/// Header renderer used to render visual aspects of the panel
/// </summary>
public static readonly DependencyProperty HeaderRendererProperty = DependencyProperty.Register("HeaderRenderer", typeof(IPrimarySecondaryHorizontalPanelHeaderRenderer), typeof(PrimarySecondaryHorizontalPanel), new PropertyMetadata(null));
/// <summary>
/// Defines the desired location of the secondary element
/// </summary>
/// <value>The secondary area location.</value>
public SecondaryAreaLocation SecondaryAreaLocation
{
get { return (SecondaryAreaLocation)GetValue(SecondaryAreaLocationProperty); }
set { SetValue(SecondaryAreaLocationProperty, value); }
}
/// <summary>
/// Defines the desired location of the secondary element
/// </summary>
public static readonly DependencyProperty SecondaryAreaLocationProperty = DependencyProperty.Register("SecondaryAreaLocation", typeof(SecondaryAreaLocation), typeof(PrimarySecondaryHorizontalPanel), new PropertyMetadata(SecondaryAreaLocation.Left));
/// <summary>
/// Background brush for the primary area
/// </summary>
/// <value>The primary area background.</value>
public Brush PrimaryAreaBackground
{
get { return (Brush)GetValue(PrimaryAreaBackgroundProperty); }
set { SetValue(PrimaryAreaBackgroundProperty, value); }
}
/// <summary>
/// Background brush for the primary area
/// </summary>
public static readonly DependencyProperty PrimaryAreaBackgroundProperty = DependencyProperty.Register("PrimaryAreaBackground", typeof(Brush), typeof(PrimarySecondaryHorizontalPanel), new PropertyMetadata(null, OnPrimaryAreaBackgroundChanged));
/// <summary>
/// Fires when the primary area background brush changes
/// </summary>
/// <param name="d">The panel object</param>
/// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnPrimaryAreaBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
var panel = d as PrimarySecondaryHorizontalPanel;
if (panel == null) return;
panel.InvalidateVisual();
}
/// <summary>
/// Background brush for the secondary area
/// </summary>
/// <value>The secondary area background.</value>
public Brush SecondaryAreaBackground
{
get { return (Brush)GetValue(SecondaryAreaBackgroundProperty); }
set { SetValue(SecondaryAreaBackgroundProperty, value); }
}
/// <summary>
/// Background brush for the secondary area
/// </summary>
public static readonly DependencyProperty SecondaryAreaBackgroundProperty = DependencyProperty.Register("SecondaryAreaBackground", typeof(Brush), typeof(PrimarySecondaryHorizontalPanel), new PropertyMetadata(null, OnSecondaryAreaBackgroundChanged));
/// <summary>
/// Fires when the secondary area background color changes
/// </summary>
/// <param name="d">The d.</param>
/// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnSecondaryAreaBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
var panel = d as PrimarySecondaryHorizontalPanel;
if (panel == null) return;
panel.InvalidateVisual();
}
private Rect _currentPrimaryArea;
private Rect _currentSecondaryArea;
/// <summary>
/// When overridden in a derived class, measures the size in layout required for child elements and determines a size for the <see cref="T:System.Windows.FrameworkElement" />-derived class.
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements. Infinity can be specified as a value to indicate that the element will size to whatever content is available.</param>
/// <returns>The size that this element determines it needs during layout, based on its calculations of child element sizes.</returns>
protected override Size MeasureOverride(Size availableSize)
{
if (HeaderRenderer == null)
HeaderRenderer = new StandardPrimarySecondaryHorizontalPanelHeaderRenderer();
foreach (var element in Children.OfType<UIElement>().Where(e => e.Visibility != Visibility.Collapsed))
if (SimpleView.GetUIElementType(element) == UIElementTypes.Primary)
{
if (CanCollapseSecondary && IsSecondaryElementCollapsed)
{
var minimumCollapsedWidth = 0d;
var mainAreaLeft = 0d;
if (HeaderRenderer != null)
{
minimumCollapsedWidth = HeaderRenderer.GetMinimumCollapsedAreaWidth(this);
if (SecondaryAreaLocation == SecondaryAreaLocation.Left) mainAreaLeft = minimumCollapsedWidth + (minimumCollapsedWidth > 0d ? ElementSpacing : 0d);
}
var primaryArea = GeometryHelper.NewRect(mainAreaLeft, 0d, availableSize.Width - minimumCollapsedWidth - (minimumCollapsedWidth > 0d ? ElementSpacing : 0d), availableSize.Height);
if (HeaderRenderer != null) primaryArea = HeaderRenderer.GetPrimaryClientArea(primaryArea, this);
element.Measure(primaryArea.Size);
}
else
{
var currentX = 0d;
if (SecondaryAreaLocation == SecondaryAreaLocation.Left) currentX = SecondaryElementWidth + ElementSpacing;
var primaryArea = GeometryHelper.NewRect(currentX, 0d, Math.Max(availableSize.Width - SecondaryElementWidth - ElementSpacing, 0), availableSize.Height);
if (HeaderRenderer != null) primaryArea = HeaderRenderer.GetPrimaryClientArea(primaryArea, this);
element.Measure(primaryArea.Size);
}
}
else
{
if (CanCollapseSecondary && IsSecondaryElementCollapsed)
element.Measure(GeometryHelper.NewSize(0, availableSize.Height));
else
{
var secondaryArea = SecondaryAreaLocation == SecondaryAreaLocation.Left ? GeometryHelper.NewRect(0d, 0d, SecondaryElementWidth, availableSize.Height) : GeometryHelper.NewRect(availableSize.Width - SecondaryElementWidth, 0d, SecondaryElementWidth, availableSize.Height);
if (HeaderRenderer != null) secondaryArea = HeaderRenderer.GetSecondaryClientArea(secondaryArea, this);
element.Measure(secondaryArea.Size);
}
}
return base.MeasureOverride(availableSize);
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines a size for a <see cref="T:System.Windows.FrameworkElement" /> derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
foreach (var element in Children.OfType<UIElement>().Where(e => e.Visibility != Visibility.Collapsed))
if (SimpleView.GetUIElementType(element) == UIElementTypes.Primary)
{
if (CanCollapseSecondary && IsSecondaryElementCollapsed)
{
var minimumCollapsedWidth = 0d;
var mainAreaLeft = 0d;
if (HeaderRenderer != null)
{
minimumCollapsedWidth = HeaderRenderer.GetMinimumCollapsedAreaWidth(this);
if (SecondaryAreaLocation == SecondaryAreaLocation.Left) mainAreaLeft = minimumCollapsedWidth + (minimumCollapsedWidth > 0d ? ElementSpacing : 0d);
}
var primaryArea = GeometryHelper.NewRect(mainAreaLeft, 0d, finalSize.Width - minimumCollapsedWidth - (minimumCollapsedWidth > 0d ? ElementSpacing : 0d), finalSize.Height);
if (HeaderRenderer != null) primaryArea = HeaderRenderer.GetPrimaryClientArea(primaryArea, this);
_currentPrimaryArea = primaryArea;
element.Arrange(primaryArea);
}
else
{
var currentX = 0d;
if (SecondaryAreaLocation == SecondaryAreaLocation.Left) currentX = SecondaryElementWidth + ElementSpacing;
var primaryArea = GeometryHelper.NewRect(currentX, 0d, Math.Max(finalSize.Width - SecondaryElementWidth - ElementSpacing, 0), finalSize.Height);
if (HeaderRenderer != null) primaryArea = HeaderRenderer.GetPrimaryClientArea(primaryArea, this);
_currentPrimaryArea = primaryArea;
element.Arrange(primaryArea);
}
}
else
{
if (CanCollapseSecondary && IsSecondaryElementCollapsed)
{
_currentSecondaryArea = GeometryHelper.NewRect(-100000d, -100000d, 0d, finalSize.Height);
element.Arrange(_currentSecondaryArea);
}
else
{
var secondaryArea = SecondaryAreaLocation == SecondaryAreaLocation.Left ? GeometryHelper.NewRect(0d, 0d, SecondaryElementWidth, finalSize.Height) : GeometryHelper.NewRect(finalSize.Width - SecondaryElementWidth, 0d, SecondaryElementWidth, finalSize.Height);
if (HeaderRenderer != null) secondaryArea = HeaderRenderer.GetSecondaryClientArea(secondaryArea, this);
_currentSecondaryArea = secondaryArea;
element.Arrange(secondaryArea);
}
}
return base.ArrangeOverride(finalSize);
}
/// <summary>
/// Draws the content of a <see cref="T:System.Windows.Media.DrawingContext" /> object during the render pass of a <see cref="T:System.Windows.Controls.Panel" /> element.
/// </summary>
/// <param name="dc">The <see cref="T:System.Windows.Media.DrawingContext" /> object to draw.</param>
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (PrimaryAreaBackground != null) dc.DrawRectangle(PrimaryAreaBackground, null, GeometryHelper.NewRect(_currentPrimaryArea.X, 0, _currentPrimaryArea.Width, ActualHeight));
if (SecondaryAreaBackground != null) dc.DrawRectangle(SecondaryAreaBackground, null, GeometryHelper.NewRect(_currentSecondaryArea.X, 0, _currentSecondaryArea.Width, ActualHeight));
if (HeaderRenderer != null)
HeaderRenderer.Render(dc, _currentPrimaryArea,_currentSecondaryArea, this);
}
/// <summary>
/// Invoked when an unhandled Mouse Down attached event reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
/// </summary>
/// <param name="e">The <see cref="T:System.Windows.Input.MouseButtonEventArgs" /> that contains the event data. This event data reports details about the mouse button that was pressed and the handled state.</param>
protected override void OnMouseDown(MouseButtonEventArgs e)
{
if (HeaderRenderer != null)
{
if (HeaderRenderer.Click(e.GetPosition(this), _currentPrimaryArea, _currentSecondaryArea, this))
{
e.Handled = true;
return;
}
}
base.OnMouseDown(e);
}
}
/// <summary>
/// Interface for a stylable header renderer used by the PrimarySecondaryHorizontalPanel
/// </summary>
public interface IPrimarySecondaryHorizontalPanelHeaderRenderer
{
/// <summary>
/// determines the size of the client area for the primary element, based on the overall area allocated to it
/// </summary>
/// <param name="totalPrimaryArea">The total primary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>The client size (area usable by the contained element, which excludes areas needed for header information)</returns>
Rect GetPrimaryClientArea(Rect totalPrimaryArea, PrimarySecondaryHorizontalPanel parentPanel);
/// <summary>
/// determines the size of the client area for the secondary element, based on the overall area allocated to it
/// </summary>
/// <param name="totalSecondaryArea">The total secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>The client size (area usable by the contained element, which excludes areas needed for header information)</returns>
Rect GetSecondaryClientArea(Rect totalSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel);
/// <summary>
/// Renders additional graphical elements
/// </summary>
/// <param name="dc">The dc.</param>
/// <param name="currentPrimaryArea">The current primary area.</param>
/// <param name="currentSecondaryArea">The current secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
void Render(DrawingContext dc, Rect currentPrimaryArea, Rect currentSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel);
/// <summary>
/// Returns the minimum width of a collapsed secondary area
/// </summary>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>Minimum width of the area</returns>
double GetMinimumCollapsedAreaWidth(PrimarySecondaryHorizontalPanel parentPanel);
/// <summary>
/// Called when a click on the panel background happens
/// </summary>
/// <param name="location">The location of the click.</param>
/// <param name="currentPrimaryArea">The current primary area.</param>
/// <param name="currentSecondaryArea">The current secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>True if the click event has been handled and no further processing is needed</returns>
bool Click(Point location, Rect currentPrimaryArea, Rect currentSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel);
}
/// <summary>
/// Standard renderer for the primary/secondary horizontal panel
/// </summary>
public class StandardPrimarySecondaryHorizontalPanelHeaderRenderer : FrameworkElement, IPrimarySecondaryHorizontalPanelHeaderRenderer
{
/// <summary>
/// Brush used to render a collapsed state icon for a collapsed primary area
/// </summary>
/// <value>The collapsed secondary area icon.</value>
public Brush CollapsedSecondaryAreaIcon
{
get { return (Brush)GetValue(CollapsedSecondaryAreaIconProperty); }
set { SetValue(CollapsedSecondaryAreaIconProperty, value); }
}
/// <summary>
/// Brush used to render a collapsed state icon for a collapsed primary area
/// </summary>
public static readonly DependencyProperty CollapsedSecondaryAreaIconProperty = DependencyProperty.Register("CollapsedSecondaryAreaIcon", typeof(Brush), typeof(StandardPrimarySecondaryHorizontalPanelHeaderRenderer), new PropertyMetadata(null));
/// <summary>
/// Brush used to render an expanded state icon for an expanded primary area
/// </summary>
/// <value>The expanded secondary area icon.</value>
public Brush ExpandedSecondaryAreaIcon
{
get { return (Brush)GetValue(ExpandedSecondaryAreaIconProperty); }
set { SetValue(ExpandedSecondaryAreaIconProperty, value); }
}
/// <summary>
/// Brush used to render an expanded state icon for an expanded primary area
/// </summary>
public static readonly DependencyProperty ExpandedSecondaryAreaIconProperty = DependencyProperty.Register("ExpandedSecondaryAreaIcon", typeof(Brush), typeof(StandardPrimarySecondaryHorizontalPanelHeaderRenderer), new PropertyMetadata(null));
/// <summary>
/// Size of the expand/collapse icon
/// </summary>
/// <value>The size of the expand collapse icon.</value>
public Size ExpandCollapseIconSize
{
get { return (Size)GetValue(ExpandCollapseIconSizeProperty); }
set { SetValue(ExpandCollapseIconSizeProperty, value); }
}
/// <summary>
/// Size of the expand/collapse icon
/// </summary>
public static readonly DependencyProperty ExpandCollapseIconSizeProperty = DependencyProperty.Register("ExpandCollapseIconSize", typeof(Size), typeof(StandardPrimarySecondaryHorizontalPanelHeaderRenderer), new PropertyMetadata(new Size(16, 16)));
/// <summary>
/// Defines the margin around the header icon
/// </summary>
/// <value>The icon margin.</value>
public Thickness IconMargin
{
get { return (Thickness)GetValue(IconMarginProperty); }
set { SetValue(IconMarginProperty, value); }
}
/// <summary>
/// Defines the margin around the header icon
/// </summary>
public static readonly DependencyProperty IconMarginProperty = DependencyProperty.Register("IconMargin", typeof(Thickness), typeof(StandardPrimarySecondaryHorizontalPanelHeaderRenderer), new PropertyMetadata(null));
/// <summary>
/// Indicates whether the icon size and placement is to be considered and reserved when laying out other objects,
/// or whether the icon will simply overlap other elements
/// </summary>
/// <value><c>true</c> if the icon is to be ignored for layout, otherwise, <c>false</c>.</value>
public bool IgnoreIconSizeForLayout
{
get { return (bool)GetValue(IgnoreIconSizeForLayoutProperty); }
set { SetValue(IgnoreIconSizeForLayoutProperty, value); }
}
/// <summary>
/// Indicates whether the icon size and placement is to be considered and reserved when laying out other objects,
/// or whether the icon will simply overlap other elements
/// </summary>
public static readonly DependencyProperty IgnoreIconSizeForLayoutProperty = DependencyProperty.Register("IgnoreIconSizeForLayout", typeof(bool), typeof(StandardPrimarySecondaryHorizontalPanelHeaderRenderer), new PropertyMetadata(false));
/// <summary>
/// determines the size of the client area for the primary element, based on the overall area allocated to it
/// </summary>
/// <param name="totalPrimaryArea">The total primary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>The client size (area usable by the contained element, which excludes areas needed for header information)</returns>
public Rect GetPrimaryClientArea(Rect totalPrimaryArea, PrimarySecondaryHorizontalPanel parentPanel)
{
return totalPrimaryArea;
}
/// <summary>
/// determines the size of the client area for the secondary element, based on the overall area allocated to it
/// </summary>
/// <param name="totalSecondaryArea">The total secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>The client size (area usable by the contained element, which excludes areas needed for header information)</returns>
public Rect GetSecondaryClientArea(Rect totalSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel)
{
if (IgnoreIconSizeForLayout)
return GeometryHelper.NewRect(totalSecondaryArea.X, totalSecondaryArea.Y, totalSecondaryArea.Width, totalSecondaryArea.Height);
return GeometryHelper.NewRect(totalSecondaryArea.X, totalSecondaryArea.Y + ExpandCollapseIconSize.Height + 4, totalSecondaryArea.Width, totalSecondaryArea.Height - ExpandCollapseIconSize.Height - 4);
}
/// <summary>
/// Renders additional graphical elements
/// </summary>
/// <param name="dc">The dc.</param>
/// <param name="currentPrimaryArea">The current primary area.</param>
/// <param name="currentSecondaryArea">The current secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
public void Render(DrawingContext dc, Rect currentPrimaryArea, Rect currentSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel)
{
if (parentPanel.CanCollapseSecondary)
{
if (parentPanel.IsSecondaryElementCollapsed)
{
if (CollapsedSecondaryAreaIconProperty != null)
dc.DrawRectangle(CollapsedSecondaryAreaIcon, null, GeometryHelper.NewRect(new Point(parentPanel.ActualWidth - ExpandCollapseIconSize.Width + IconMargin.Left, IconMargin.Top), GeometryHelper.NewSize(ExpandCollapseIconSize.Width - IconMargin.Left - IconMargin.Right, ExpandCollapseIconSize.Height - IconMargin.Top - IconMargin.Bottom)));
}
else
{
if (ExpandedSecondaryAreaIcon != null)
dc.DrawRectangle(ExpandedSecondaryAreaIcon, null, GeometryHelper.NewRect(new Point(currentSecondaryArea.X + IconMargin.Left, IconMargin.Top), GeometryHelper.NewSize(ExpandCollapseIconSize.Width - IconMargin.Left - IconMargin.Right, ExpandCollapseIconSize.Height - IconMargin.Top - IconMargin.Bottom)));
}
}
}
/// <summary>
/// Returns the minimum width of a collapsed secondary area
/// </summary>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>Minimum width of the area</returns>
public double GetMinimumCollapsedAreaWidth(PrimarySecondaryHorizontalPanel parentPanel)
{
return ExpandCollapseIconSize.Width;
}
/// <summary>
/// Called when a click on the panel background happens
/// </summary>
/// <param name="location">The location of the click.</param>
/// <param name="currentPrimaryArea">The current primary area.</param>
/// <param name="currentSecondaryArea">The current secondary area.</param>
/// <param name="parentPanel">The parent panel.</param>
/// <returns>True if the click event has been handled and no further processing is needed</returns>
/// <exception cref="System.NotImplementedException"></exception>
public bool Click(Point location, Rect currentPrimaryArea, Rect currentSecondaryArea, PrimarySecondaryHorizontalPanel parentPanel)
{
if (location.Y > ExpandCollapseIconSize.Height + 4) return false;
if (parentPanel.IsSecondaryElementCollapsed)
{
if (parentPanel.SecondaryAreaLocation == SecondaryAreaLocation.Left)
{
if (location.X <= ExpandCollapseIconSize.Width)
{
parentPanel.IsSecondaryElementCollapsed = !parentPanel.IsSecondaryElementCollapsed;
return true;
}
}
else
{
if (location.X >= parentPanel.ActualWidth - ExpandCollapseIconSize.Width)
{
parentPanel.IsSecondaryElementCollapsed = !parentPanel.IsSecondaryElementCollapsed;
return true;
}
}
}
else
{
if (location.X >= currentSecondaryArea.Left && location.X <= currentSecondaryArea.Right)
{
parentPanel.IsSecondaryElementCollapsed = !parentPanel.IsSecondaryElementCollapsed;
return true;
}
}
return false;
}
}
/// <summary>
/// Defines where the secondary area should be placed by the layout engine
/// </summary>
public enum SecondaryAreaLocation
{
/// <summary>
/// Docked on the left
/// </summary>
Left,
/// <summary>
/// Docked on the right
/// </summary>
Right
}
}
|
#region LICENSE
// Funkshun.Core 1.0.0.0
//
// Copyright 2011, see AUTHORS.txt
//
// 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
using Funkshun.Core.Decorators;
namespace Funkshun.Core.Extensions
{
/// <summary>
/// Static (extension) class for extending the types:
/// <see cref="IFunction{TResult}"/>,
/// <see cref="IFunction{T, TResult}"/>,
/// <see cref="IFunction{T1,T2, TResult}"/>,
/// <see cref="IFunction{T1,T2,T3, TResult}"/>,
/// <see cref="IFunction{T1,T2,T3,T4, TResult}"/>,
/// <see cref="IFunction{T1,T2,T3,T4,T5, TResult}"/>
/// </summary>
public static partial class FunctionExtensions
{
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<TResult> CollectResults<TResult>(this IFunction<TResult> function)
{
ResultCollectorDecorator<TResult> decorator;
if (function is ResultCollectorDecorator<TResult>)
{
decorator = (ResultCollectorDecorator<TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<TResult>(function);
}
return decorator;
}
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <typeparam name="T">The type of the first parameter.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<T, TResult> CollectResults<T, TResult>(this IFunction<T, TResult> function)
{
ResultCollectorDecorator<T, TResult> decorator;
if (function is ResultCollectorDecorator<T, TResult>)
{
decorator = (ResultCollectorDecorator<T, TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<T, TResult>(function);
}
return decorator;
}
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<T1, T2, TResult> CollectResults<T1, T2, TResult>(this IFunction<T1, T2, TResult> function)
{
ResultCollectorDecorator<T1, T2, TResult> decorator;
if (function is ResultCollectorDecorator<T1, T2, TResult>)
{
decorator = (ResultCollectorDecorator<T1, T2, TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<T1, T2, TResult>(function);
}
return decorator;
}
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<T1, T2, T3, TResult> CollectResults<T1, T2, T3, TResult>(this IFunction<T1, T2, T3, TResult> function)
{
ResultCollectorDecorator<T1, T2, T3, TResult> decorator;
if (function is ResultCollectorDecorator<T1, T2, T3, TResult>)
{
decorator = (ResultCollectorDecorator<T1, T2, T3, TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<T1, T2, T3, TResult>(function);
}
return decorator;
}
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <typeparam name="T4">The type of the fourth parameter.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<T1, T2, T3, T4, TResult> CollectResults<T1, T2, T3, T4, TResult>(this IFunction<T1, T2, T3, T4, TResult> function)
{
ResultCollectorDecorator<T1, T2, T3, T4, TResult> decorator;
if (function is ResultCollectorDecorator<T1, T2, T3, T4, TResult>)
{
decorator = (ResultCollectorDecorator<T1, T2, T3, T4, TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<T1, T2, T3, T4, TResult>(function);
}
return decorator;
}
/// <summary>
/// Collects results returned by the Run method of a function.
/// </summary>
/// <typeparam name="TResult">The type of the return value of the function result.</typeparam>
/// <typeparam name="T1">The type of the first parameter.</typeparam>
/// <typeparam name="T2">The type of the second parameter.</typeparam>
/// <typeparam name="T3">The type of the third parameter.</typeparam>
/// <typeparam name="T4">The type of the fourth parameter.</typeparam>
/// <typeparam name="T5">The type of the fifth parameter.</typeparam>
/// <param name="function">The function for which you want to collect results.</param>
/// <returns>A <see cref="ResultCollectorDecorator{TResult}"/> which decorates the function by collecting results from the Run method.</returns>
public static ResultCollectorDecorator<T1, T2, T3, T4, T5, TResult> CollectResults<T1, T2, T3, T4, T5, TResult>(this IFunction<T1, T2, T3, T4, T5, TResult> function)
{
ResultCollectorDecorator<T1, T2, T3, T4, T5, TResult> decorator;
if (function is ResultCollectorDecorator<T1, T2, T3, T4, T5, TResult>)
{
decorator = (ResultCollectorDecorator<T1, T2, T3, T4, T5, TResult>) function;
}
else
{
decorator = new ResultCollectorDecorator<T1, T2, T3, T4, T5, TResult>(function);
}
return decorator;
}
}
} |
namespace Domain.Entities
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class BeerEntity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public BeerEntity()
{
BeerBottles = new HashSet<BeerBottle>();
}
public int ID { get; set; }
public string Name { get; set; }
public double Alcohol { get; set; }
public double Breadness { get; set; }
public int? BeerKindId { get; set; }
public int? TradeMarkId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<BeerBottle> BeerBottles { get; set; }
public virtual BeerKind BeerKind { get; set; }
public virtual TradeMark TradeMark { get; set; }
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using DuckingAround.Items.Potions;
using DuckingAround.Items.Placeable;
using DuckingAround.Items.Materials;
using DuckingAround.Items.SpawnItems;
using DuckingAround.Items.Accessories;
using DuckingAround.Items.Weapons.Guns;
using DuckingAround.Items.Weapons.Melee;
using DuckingAround.Items.Weapons.Yoyos;
using DuckingAround.Items.Weapons.Duckies;
namespace DuckingAround
{
public class DuckingItem : GlobalItem
{
public override void Update(Item item, ref float gravity, ref float maxFallSpeed)
{
if (item.type == ItemID.PlatinumCoin || item.type == ItemID.GoldCoin || item.type == ItemID.SilverCoin || item.type == ItemID.CopperCoin
|| item.type == ItemID.Feather || item.type == ItemID.GiantHarpyFeather || item.type == ItemID.WyvernBanner || item.type == ItemID.HarpyBanner)
{
ItemID.Sets.ItemNoGravity[item.type] = true;
}
}
public override void SetDefaults(Item item)
{
if (item.type == ItemID.GuideVoodooDoll)
{
item.consumable = true;
item.useAnimation = 15;
item.useTime = 15;
item.useStyle = ItemUseStyleID.SwingThrow;
}
}
public override bool UseItem(Item item, Player player)
{
if (item.type == ItemID.GuideVoodooDoll)
{
player.DropSelectedItem();
ItemID.Sets.ItemNoGravity[item.type] = false;
return true;
}
else
{
return false;
}
}
public override void AddRecipes()
{
//accessory crafting recipes
ModRecipe recipe = new ModRecipe(mod);
recipe.AddRecipeGroup("DuckingAround:IronBars", 20);
recipe.AddRecipeGroup("DuckingAround:SilverBars", 2);
recipe.AddRecipeGroup("DuckingAround:GoldBars", 2);
recipe.AddRecipeGroup("DuckingAround:CopperBars", 2);
recipe.AddIngredient(ItemID.Wire, 50);
recipe.AddTile(TileID.TinkerersWorkbench);
recipe.SetResult(ItemID.MetalDetector);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.LunarBar, 20);
recipe.AddIngredient(ItemID.SoulofFlight, 20);
recipe.AddIngredient(ItemID.GravityGlobe);
recipe.AddIngredient(ItemID.Hoverboard);
recipe.AddTile(TileID.LunarCraftingStation);
recipe.SetResult(ModContent.ItemType<Hoverboard>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.LunarBar, 25);
recipe.AddIngredient(ItemID.GravitationPotion, 15);
recipe.AddIngredient(ItemID.FeatherfallPotion, 15);
recipe.AddTile(TileID.LunarCraftingStation);
recipe.SetResult(ItemID.GravityGlobe);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.SoulofFlight, 100);
recipe.AddIngredient(ItemID.WingsNebula);
recipe.AddIngredient(ItemID.WingsSolar);
recipe.AddIngredient(ItemID.WingsStardust);
recipe.AddIngredient(ItemID.WingsNebula);
recipe.AddIngredient(ItemID.GiantHarpyFeather);
recipe.AddIngredient(ItemID.BrokenBatWing);
recipe.AddIngredient(ItemID.FireFeather);
recipe.AddTile(TileID.LunarCraftingStation);
recipe.SetResult(ModContent.ItemType<InfiniteFlightAccessory>());
recipe.AddRecipe();
//duck crafting recipes
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.MallardDuck, 25);
recipe.AddTile(TileID.WorkBenches);
recipe.SetResult(ItemID.Duck, 25);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Explosives);
recipe.AddIngredient(ItemID.Duck, 20);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<NukeDucky>(), 20);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.RocketIII, 20);
recipe.AddIngredient(ModContent.ItemType<NukeDucky>(), 5);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<NukeDuckyItem>(), 20);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Duck);
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<Ducky>(), 50);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Duck);
recipe.AddIngredient(ItemID.IronBar, 5);
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<IronDucky>(), 50);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Duck);
recipe.AddIngredient(ItemID.MeteoriteBar, 5);
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<MeteorDucky>(), 50);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Duck);
recipe.AddIngredient(ModContent.ItemType<Rubber>());
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<RubberDucky>(), 50);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Duck);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumBar>());
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<PlatyrhynchiumDucky>(), 50);
recipe.AddRecipe();
//material crafting
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<Items.Placeable.PlatyrhynchiumOre>(), 6);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<PlatyrhynchiumBar>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<Sap>(), 3);
recipe.AddIngredient(ModContent.ItemType<Acid>(), 1);
recipe.AddTile(ModContent.TileType<Tiles.Coagulator>());
recipe.SetResult(ModContent.ItemType<Rubber>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofSight, 5);
recipe.AddIngredient(ItemID.SoulofFright, 5);
recipe.AddTile(ModContent.TileType<Tiles.Coagulator>());
recipe.SetResult(ModContent.ItemType<AmalgamatedSoul>(), 5);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<AmalgamatedSoul>());
recipe.AddTile(ModContent.TileType<Tiles.Electrolyzer>());
recipe.SetResult(ItemID.SoulofSight, 3);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<AmalgamatedSoul>());
recipe.AddTile(ModContent.TileType<Tiles.Electrolyzer>());
recipe.SetResult(ItemID.SoulofFright, 3);
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<AmalgamatedSoul>());
recipe.AddTile(ModContent.TileType<Tiles.Electrolyzer>());
recipe.SetResult(ItemID.SoulofMight, 3);
recipe.AddRecipe();
//tile item crafting recipes
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.VortexMonolith, 1);
recipe.AddIngredient(ItemID.NebulaMonolith, 1);
recipe.AddIngredient(ItemID.StardustMonolith, 1);
recipe.AddIngredient(ItemID.SolarMonolith, 1);
recipe.AddIngredient(ItemID.SoulofMight, 15);
recipe.AddIngredient(ItemID.SoulofFright, 15);
recipe.AddIngredient(ItemID.SoulofSight, 15);
recipe.AddIngredient(ItemID.LunarBar, 15);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumBar>(), 15);
recipe.AddIngredient(ModContent.ItemType<IronDucky>(), 150);
recipe.AddIngredient(ModContent.ItemType<RubberDucky>(), 150);
recipe.AddIngredient(ModContent.ItemType<MeteorDucky>(), 150);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<Items.Placeable.DuckyTotemItem>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Wire, 50);
recipe.AddIngredient(ModContent.ItemType<MachineParts>(), 25);
recipe.AddIngredient(ModContent.ItemType<Rubber>(), 15);
recipe.AddIngredient(ItemID.EmptyBucket, 3);
recipe.AddIngredient(ItemID.HoneyDispenser);
recipe.AddRecipeGroup("DuckingAround:IronBars", 15);
recipe.AddRecipeGroup("DuckingAround:GoldBars", 10);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<Items.Placeable.CoagulatorItem>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.Wire, 50);
recipe.AddIngredient(ModContent.ItemType<MachineParts>(), 25);
recipe.AddIngredient(ModContent.ItemType<Rubber>(), 15);
recipe.AddIngredient(ItemID.BottomlessBucket);
recipe.AddIngredient(ItemID.SteampunkBoiler);
recipe.AddRecipeGroup("DuckingAround:IronBars", 15);
recipe.AddRecipeGroup("DuckingAround:GoldBars", 10);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<Items.Placeable.ElectrolyzerItem>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.AdamantiteForge, 1);
recipe.AddIngredient(ItemID.MythrilAnvil, 1);
recipe.AddIngredient(ItemID.CrystalBall, 1);
recipe.AddIngredient(ItemID.SoulofMight, 15);
recipe.AddIngredient(ItemID.SoulofFright, 15);
recipe.AddIngredient(ItemID.SoulofSight, 15);
recipe.AddIngredient(ItemID.LunarBar, 25);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumOre>(), 35);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<HephaestusForge>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.TitaniumForge, 1);
recipe.AddIngredient(ItemID.OrichalcumAnvil, 1);
recipe.AddIngredient(ItemID.CrystalBall, 1);
recipe.AddIngredient(ItemID.SoulofMight, 15);
recipe.AddIngredient(ItemID.SoulofFright, 15);
recipe.AddIngredient(ItemID.SoulofSight, 15);
recipe.AddIngredient(ItemID.LunarBar, 25);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumOre>(), 35);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<HephaestusForge>());
recipe.AddRecipe();
//potion crafting recipes
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.BottledWater);
recipe.AddIngredient(ItemID.Deathweed);
recipe.AddIngredient(ItemID.IronPickaxe);
recipe.AddIngredient(ItemID.Wood);
recipe.AddTile(TileID.AlchemyTable);
recipe.SetResult(ModContent.ItemType<ChugJug>());
recipe.AddRecipe();
//spawn item crafting recipes
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.AdamantiteBar, 30);
recipe.AddIngredient(ItemID.MythrilBar, 30);
recipe.AddIngredient(ItemID.CobaltBar, 30);
recipe.AddIngredient(ItemID.SoulofLight, 10);
recipe.AddIngredient(ItemID.SoulofNight, 10);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<EnemySpawnerSpawn>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.TitaniumBar, 30);
recipe.AddIngredient(ItemID.OrichalcumBar, 30);
recipe.AddIngredient(ItemID.PalladiumBar, 30);
recipe.AddIngredient(ItemID.SoulofLight, 10);
recipe.AddIngredient(ItemID.SoulofNight, 10);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<EnemySpawnerSpawn>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.LunarOre, 20);
recipe.AddIngredient(ItemID.SpectreBar, 20);
recipe.AddIngredient(ItemID.HallowedBar, 15);
recipe.AddIngredient(ItemID.ShroomiteBar, 10);
recipe.AddIngredient(ItemID.SoulofMight, 10);
recipe.AddIngredient(ItemID.SoulofFright, 10);
recipe.AddIngredient(ItemID.SoulofSight, 10);
recipe.AddIngredient(ItemID.SoulofLight, 15);
recipe.AddIngredient(ItemID.SoulofNight, 15);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<PsionSpawn>());
recipe.AddRecipe();
//yoyo crafting recipes
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.ChlorophyteBar, 25);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.CorruptYoyo);
recipe.AddIngredient(ItemID.HelFire);
recipe.AddIngredient(ItemID.Chik);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<DestinyYoYo>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.ChlorophyteBar, 25);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.CrimsonYoyo);
recipe.AddIngredient(ItemID.HelFire);
recipe.AddIngredient(ItemID.Chik);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<DestinyYoYo>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.ChlorophyteBar, 25);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.Amarok);
recipe.AddIngredient(ItemID.Kraken);
recipe.AddIngredient(ItemID.Code1);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<BountyHunterYoYo>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.ChlorophyteBar, 25);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.WoodYoyo);
recipe.AddIngredient(ItemID.Gradient);
recipe.AddIngredient(ItemID.Yelets);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<FreedomYoYo>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.ChlorophyteBar, 25);
recipe.AddIngredient(ItemID.SoulofMight, 5);
recipe.AddIngredient(ItemID.SoulofLight, 5);
recipe.AddIngredient(ItemID.TheEyeOfCthulhu);
recipe.AddIngredient(ItemID.FormatC);
recipe.AddIngredient(ItemID.Rally);
recipe.AddTile(TileID.MythrilAnvil);
recipe.SetResult(ModContent.ItemType<PegasusYoYo>());
recipe.AddRecipe();
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<PegasusYoYo>());
recipe.AddIngredient(ModContent.ItemType<DestinyYoYo>());
recipe.AddIngredient(ModContent.ItemType<FreedomYoYo>());
recipe.AddIngredient(ModContent.ItemType<BountyHunterYoYo>());
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumBar>(), 14);
recipe.AddIngredient(ItemID.Terrarian, 1);
recipe.AddIngredient(ItemID.YoyoBag, 1);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<QuackYo>());
recipe.AddRecipe();
//melee weapon crafting
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumBar>(), 18);
recipe.AddIngredient(ItemID.SoulofMight, 12);
recipe.AddIngredient(ItemID.SoulofLight, 12);
recipe.AddIngredient(ItemID.LunarBar, 10);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<DuckyWrath>());
recipe.AddRecipe();
//ranged weapon crafting
recipe = new ModRecipe(mod);
recipe.AddIngredient(ModContent.ItemType<PlatyrhynchiumBar>(), 15);
recipe.AddIngredient(ModContent.ItemType<NukeDucky>(), 15);
recipe.AddIngredient(ItemID.LunarBar, 15);
recipe.AddIngredient(ItemID.FireworksLauncher);
recipe.AddIngredient(ItemID.RocketLauncher);
recipe.AddTile(ModContent.TileType<Tiles.HephaestusForge>());
recipe.SetResult(ModContent.ItemType<FowlPlay>());
recipe.AddRecipe();
//tool crafting recipes
recipe = new ModRecipe(mod);
recipe.AddRecipeGroup("DuckingAround:IronBars", 5);
recipe.AddIngredient(ItemID.Wood, 10);
recipe.AddIngredient(ItemID.EmptyBucket);
recipe.AddTile(TileID.Anvils);
recipe.SetResult(ModContent.ItemType<Items.Tools.SapTap>());
recipe.AddRecipe();
}
}
} |
namespace MySurveys.Web.Areas.Surveys.Controllers.Base
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Models;
using MvcTemplate.Web.Infrastructure.Mapping;
using Services.Contracts;
using ViewModels.Filling;
using Web.Controllers.Base;
public abstract class BaseScrollController : BaseController
{
public const int RecordsPerPage = 10;
public BaseScrollController(IUserService userService, ISurveyService surveyService)
: base(userService)
{
this.SurveyService = surveyService;
}
protected ISurveyService SurveyService { get; set; }
//// GET: Surveys/Surveys/Index
public ActionResult Index()
{
ViewBag.RecordsPerPage = RecordsPerPage;
return this.RedirectToAction("GetSurveys");
}
public ActionResult GetSurveys(int? pageNum)
{
pageNum = pageNum ?? 0;
ViewBag.IsEndOfRecords = false;
if (Request.IsAjaxRequest())
{
var surveys = this.GetRecordsForPage(pageNum.Value);
ViewBag.IsEndOfRecords = surveys.Any() && ((pageNum.Value * RecordsPerPage) >= surveys.Last().Key);
return this.PartialView("_SurveysPartial", surveys);
}
else
{
this.LoadAllSurveysToSession();
ViewBag.Surveys = this.GetRecordsForPage(pageNum.Value);
return this.View("Index");
}
}
public Dictionary<int, SurveyViewModel> GetRecordsForPage(int pageNum)
{
Dictionary<int, SurveyViewModel> surveys = Session["Surveys"] as Dictionary<int, SurveyViewModel>;
int from = pageNum * RecordsPerPage;
int to = from + RecordsPerPage;
return surveys
.Where(x => x.Key > from && x.Key <= to)
.OrderBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Value);
}
public void LoadAllSurveysToSession()
{
var surveys = this.GetData()
.To<SurveyViewModel>();
int surveyIndex = 1;
this.Session["Surveys"] = surveys.ToDictionary(x => surveyIndex++, x => x);
ViewBag.TotalNumberCustomers = surveys.Count();
}
protected abstract IQueryable<Survey> GetData();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JDWinService.Model
{
public class ICItemCustom
{
/// </summary>
public int FItemID { get; set; }
/// <summary>
///
/// </summary>
public string F_108 { get; set; }
/// <summary>
///
/// </summary>
public string F_109 { get; set; }
/// <summary>
///
/// </summary>
public int F_111 { get; set; }
/// <summary>
///
/// </summary>
public string F_112 { get; set; }
/// <summary>
///
/// </summary>
public int F_113 { get; set; }
/// <summary>
///
/// </summary>
public string F_114 { get; set; }
/// <summary>
///
/// </summary>
public string F_115 { get; set; }
/// <summary>
///
/// </summary>
public double F_116 { get; set; }
/// <summary>
///
/// </summary>
public string F_117 { get; set; }
/// <summary>
///
/// </summary>
public int F_118 { get; set; }
/// <summary>
///
/// </summary>
public double F_119 { get; set; }
/// <summary>
///
/// </summary>
public string F_120 { get; set; }
/// <summary>
///
/// </summary>
public int F_121 { get; set; }
/// <summary>
///
/// </summary>
public double F_122 { get; set; }
}
}
|
namespace Tennis
{
public class Score
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021.Behaviors
{
class BehaviorHeartless : Behavior
{
public ICurio Curio;
public BehaviorHeartless()
{
}
public BehaviorHeartless(ICurio curio)
{
Curio = curio;
}
public override void Apply()
{
Curio.AddBehavior(this);
}
public override void Clone(ICurioMapper mapper)
{
var curio = mapper.Map(Curio);
Apply(new BehaviorHeartless(curio), Curio);
}
}
}
|
using System;
using System.Windows.Forms;
namespace Skyrim_Background_Injector
{
public partial class DarkProgressBar : UserControl
{
public DarkProgressBar()
{
InitializeComponent();
}
private void DarkProgressBar_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
namespace BlazorShared.Models.Schedule
{
public class UpdateScheduleRequest : BaseRequest
{
public Guid Id { get; set; }
public int ClinicId { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
private List<Guid> AppointmentIds { get; set; } = new List<Guid>();
}
}
|
using kata_payslip_v2.DataObjects;
namespace kata_payslip_v2.Interfaces
{
public interface IInputHandler
{
UserInputInformation GetNextUserInputInformation();
}
} |
using System.Collections.Generic;
namespace EddiDataDefinitions
{
public class StationModel : ResourceBasedLocalizedEDName<StationModel>
{
static StationModel()
{
// Note: The same station may use the model "Ocellus" for one event and "Bernal" for another.
resourceManager = Properties.StationModels.ResourceManager;
resourceManager.IgnoreCase = true;
missingEDNameHandler = (edname) => new StationModel(edname);
}
public static readonly StationModel None = new StationModel("None");
public static readonly StationModel AsteroidBase = new StationModel("AsteroidBase");
public static readonly StationModel Bernal = new StationModel("Bernal");
public static readonly StationModel Coriolis = new StationModel("Coriolis");
public static readonly StationModel Megaship = new StationModel("Megaship");
public static readonly StationModel MegaShipCivilian = new StationModel("MegaShipCivilian");
public static readonly StationModel Ocellus = new StationModel("Ocellus");
public static readonly StationModel Orbis = new StationModel("Orbis");
public static readonly StationModel Outpost = new StationModel("Outpost");
public static readonly StationModel SurfaceStation = new StationModel("SurfaceStation"); // No longer used in the player journal
public static readonly StationModel CraterOutpost = new StationModel("CraterOutpost");
public static readonly StationModel CraterPort = new StationModel("CraterPort");
public static readonly StationModel OutpostScientific = new StationModel("OutpostScientific");
public static readonly StationModel FleetCarrier = new StationModel("FleetCarrier");
public static readonly StationModel OnFootSettlement = new StationModel("OnFootSettlement");
// dummy used to ensure that the static constructor has run
public StationModel() : this("")
{ }
private StationModel(string edname) : base(edname, edname.Replace(" Starport", ""))
{ }
public static new StationModel FromName(string from)
{
if (from == null)
{
return null;
}
// Translate from EDSM / EDDB station model names if these are present
Dictionary<string, StationModel> modelTranslations = new Dictionary<string, StationModel>()
{
{ "Coriolis Starport", Coriolis },
{ "Bernal Starport", Bernal }, // Ocellus starports are described by the journal as either "Bernal" or "Ocellus"
{ "Ocellus Starport", Ocellus },
{ "Orbis Starport", Orbis },
// The journal doesn't provide details on the type of outpost (military, civilian, scientific, etc.)
// Types are likely derived from the station primary economy, but mixing these into the model name does not add value.
{ "Civilian Outpost", Outpost },
{ "Commercial Outpost", Outpost },
{ "Industrial Outpost", Outpost },
{ "Military Outpost", Outpost },
{ "Mining Outpost", Outpost },
{ "Scientific Outpost", Outpost },
{ "Unknown Outpost", Outpost },
{ "Planetary Outpost", CraterOutpost },
{ "Planetary Port", CraterPort },
{ "Planetary Settlement", SurfaceStation }, // Planetary settlements are not dockable and require manual edits on ROSS to add to EDDB
{ "Planetary Engineer Base", CraterOutpost },
{ "Unknown Planetary", SurfaceStation },
{ "Asteroid base", AsteroidBase },
{ "Mega ship", Megaship },
{ "Odyssey Settlement", OnFootSettlement },
};
foreach (var model in modelTranslations)
{
if (from == model.Key)
{
return model.Value;
}
}
return ResourceBasedLocalizedEDName<StationModel>.FromName(from);
}
}
}
|
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using System.Threading.Tasks;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class FileUploadAmendedFileRequestToViewModel : IMapper<FileUploadAmendedFileRequest, FileUploadAmendedFileViewModel>
{
public Task<FileUploadAmendedFileViewModel> Map(FileUploadAmendedFileRequest source)
{
return Task.FromResult(new FileUploadAmendedFileViewModel
{
CacheRequestId = source.CacheRequestId,
ProviderId = source.ProviderId
});
}
}
}
|
using Grpc.Net.Client;
using Microsoft.AspNetCore.Hosting;
using Sentry.AspNetCore.TestUtils;
namespace Sentry.AspNetCore.Grpc.Tests;
// Allows integration tests the include the background worker and mock only the gRPC bits
public class SentryGrpcSdkTestFixture : SentrySdkTestFixture
{
protected Action<SentryAspNetCoreOptions> Configure;
protected Action<WebHostBuilder> AfterConfigureBuilder;
public GrpcChannel Channel { get; set; }
public IReadOnlyCollection<GrpcRequestHandler<TestRequest, TestResponse>> GrpcHandlers { get; set; } = new[]
{
new GrpcRequestHandler<TestRequest, TestResponse>
{
Method = TestService.Descriptor.FindMethodByName("Test"), Response = new TestResponse()
},
new GrpcRequestHandler<TestRequest, TestResponse>
{
Method = TestService.Descriptor.FindMethodByName("TestThrow"),
Handler = (_, _) => throw new Exception("test error")
}
};
protected override void ConfigureBuilder(WebHostBuilder builder)
{
var sentry = FakeSentryGrpcServer.CreateServer<GrpcTestService, TestRequest, TestResponse>(GrpcHandlers);
var sentryHttpClient = sentry.CreateClient();
_ = builder.UseSentry(sentryBuilder =>
{
sentryBuilder.AddGrpc();
sentryBuilder.AddSentryOptions(options =>
{
options.Dsn = ValidDsn;
options.SentryHttpClientFactory = new DelegateHttpClientFactory(_ => sentryHttpClient);
Configure?.Invoke(options);
});
});
Channel = GrpcChannel.ForAddress("http://test-server",
new GrpcChannelOptions { HttpClient = sentryHttpClient });
AfterConfigureBuilder?.Invoke(builder);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JMusic.Models
{
class ResultStringTwo
{
public string Error { get; set; }
public string Result { get; set; }
}
}
|
namespace LINQ101MVC.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Production.ProductCategory")]
public partial class ProductCategory : IProductCategory
{
public int ProductCategoryID { get; set; }
[StringLength(50)]
[Required]
public string Name { get; set; }
public Guid rowguid { get; set; } = Guid.NewGuid();
[Display(Name = "Modified Date")]
public DateTime ModifiedDate { get; set; } = DateTime.Now;
public virtual ICollection<ProductSubcategory> ProductSubcategories { get; set; } = new HashSet<ProductSubcategory>();
}
public interface IProductCategory
{
int ProductCategoryID { get; set; }
string Name { get; set; }
Guid rowguid { get; set; }
DateTime ModifiedDate { get; set; }
}
/*
public class ProductCategoryDto : IProductCategory
{
public int ProductCategoryID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public Guid rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
}
*/
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjekatZdravoKorporacija.ModelDTO
{
class TimeDTO
{
public string Time { get; set; }
public TimeDTO(string time)
{
this.Time = time;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab2.Services.Statistic
{
public class StatisticService
{
// кількість ітерацій під час симуляції
public int Iterations { get; private set; }
// максимальний вік Травоїдних за весь час моделювання
public int MaxAgeHerbivirous { get; private set; }
// максимальний вік Хижаків за весь час моделювання
public int MaxAgePredators { get; private set; }
// кількість Травоїдних на кожній 100-тій ітерації
public Dictionary<int, int> HerbivirousCount { get; private set; }
// кількість Хижаків на кожній 100-тій ітерації
public Dictionary<int, int> PredatorCount { get; private set; }
// кількість розмножень Травоїдних
public int HerbivirousReproductionCount { get; private set; }
// кількість розмножень Хижаків
public int PredatorReproductionCount { get; private set; }
// Відсоток Травоїдних на кожній 100-тій ітерації
public Dictionary<int, double> HerbivirousRate { get; private set; }
// Відсоток Хижаків на кожній 100-тій ітерації
public Dictionary<int, double> PredatorRate { get; private set; }
// час роботи алгоритму у мілісекундах
public long AlgorithmTime { get; set; }
public StatisticService()
{
AlgorithmTime = 0;
Iterations = 0;
MaxAgeHerbivirous = 0;
MaxAgePredators = 0;
HerbivirousReproductionCount = 0;
PredatorReproductionCount = 0;
HerbivirousCount = new Dictionary<int, int>();
PredatorCount = new Dictionary<int, int>();
HerbivirousRate = new Dictionary<int, double>();
PredatorRate = new Dictionary<int, double>();
}
public void SetMaxAge(List<Agent> agents)
{
int currentMaxHerbivirousAge = agents.Where(a => a.AgentType == AgentTypes.Herbivorous).Max(h => h.GetAge());
int currentMaxPredatorsAge = agents.Where(a => a.AgentType == AgentTypes.Predator).Max(p => p.GetAge());
if (MaxAgeHerbivirous < currentMaxHerbivirousAge)
MaxAgeHerbivirous = currentMaxHerbivirousAge;
if (MaxAgePredators < currentMaxPredatorsAge)
MaxAgePredators = currentMaxPredatorsAge;
}
public void AddAgentsCount(List<Agent> allAgents, int currentIteration)
{
var herbivirous = allAgents.Where(a => a.AgentType == AgentTypes.Herbivorous).Count();
var predators = allAgents.Where(a => a.AgentType == AgentTypes.Predator).Count();
HerbivirousCount.Add(currentIteration, herbivirous);
PredatorCount.Add(currentIteration, predators);
}
public void IncreaseIterations()
{
Iterations += 1;
}
public void IncreaseReproduction(Agent current)
{
if (current.AgentType == AgentTypes.Herbivorous)
HerbivirousReproductionCount += 1;
else
PredatorReproductionCount += 1;
}
public void AddAgentsRate(List<Agent> allAgents, int currentIteration)
{
var herbivirous = allAgents.Where(a => a.AgentType == AgentTypes.Herbivorous).Count();
var predators = allAgents.Where(a => a.AgentType == AgentTypes.Predator).Count();
double herbivirousRate = (double)herbivirous / (double)allAgents.Count();
double predatorsRate = (double)predators / (double)allAgents.Count();
HerbivirousRate.Add(currentIteration, herbivirousRate);
PredatorRate.Add(currentIteration, predatorsRate);
}
}
}
|
using System;
namespace OnlineClinic.Core.DTOs
{
public class SpecializationGetDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StringReplicator.Core.Helpers;
using StringReplicator.Core.Infrastructure;
using StringReplicator.Core.Infrastructure.Providers;
using StringReplicator.Core.Operations;
namespace StringReplicator.Tests.Infrastructure.Providers
{
[TestClass()]
public class ProviderFactoryTests
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
public ProviderFactoryTests()
{
var config = new TestConfig(TestContext);
Config.RegisterConfig(config);
}
[TestMethod()]
public void GetSqlProviderTest()
{
var request = new DatabaseRequest
{
DataBaseType = DataBaseType.SqlServer,
ConnectionType = ConnectionType.WindowsAuthentication,
DatabaseName = "master",
ServerName = "."
};
var provider = ProviderFactory.GetProvider(request);
using (var connection = provider.GetConnection())
{
using (var command = provider.GetUnsafeCommand(connection, "Select * from sys.databases"))
{
var ds = new DataSet();
provider.GetDataAdapter(command).Fill(ds);
Assert.AreEqual(1, ds.Tables.Count);
var dt = ds.Tables[0];
Assert.AreNotEqual(0, dt.Rows.Count);
}
}
}
[TestMethod()]
public void GetNotSqlProvider_FunkyPath_Test()
{
var request = new DatabaseRequest
{
UdlFile = Path.Combine(Config.Current.GetRootPath(), @"Data\Path With Spaces", "test.udl"),
DataBaseType = DataBaseType.NotSqlServer
};
invokeNotSqlProvider(request);
}
[TestMethod()]
public void GetNotSqlProvider_NormalPath_Test()
{
var request = new DatabaseRequest
{
UdlFile = Config.Current.GetUdlPath(),
DataBaseType = DataBaseType.NotSqlServer
};
invokeNotSqlProvider(request);
}
private static void invokeNotSqlProvider(DatabaseRequest request)
{
var provider = ProviderFactory.GetProvider(request);
using (var connection = provider.GetConnection())
{
using (var command = provider.GetUnsafeCommand(connection, "Select * from sys.databases"))
{
var ds = new DataSet();
provider.GetDataAdapter(command).Fill(ds);
Assert.AreEqual(1, ds.Tables.Count);
var dt = ds.Tables[0];
Assert.AreNotEqual(0, dt.Rows.Count);
}
}
}
}
}
|
using NetheusLibrary.Helper;
using NetheusLibrary.Model;
using NetheusLibrary.Service;
using NetheusLibrary.Views;
using Newtonsoft.Json;
using Plugin.Media;
using Rg.Plugins.Popup.Contracts;
using Rg.Plugins.Popup.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Xamarin.Essentials;
using Xamarin.Forms;
using System.Linq;
using Xamarin.Forms.Internals;
namespace NetheusLibrary.ViewModel
{
public class LibraryViewModel : LibraryModel
{
public LibraryViewModel()
{
IsBusy = true;
LibraryListCollection = new System.Collections.ObjectModel.ObservableCollection<LibraryList>();
string LoaclListData = LocalStorageHelper.RetriveFromLocalSetting(AppConstant.ListKey);
if (!String.IsNullOrEmpty(LoaclListData))
{
var DesrilizedData = JsonConvert.DeserializeObject<ObservableCollection<LibraryList>>(LoaclListData);
foreach (var item in DesrilizedData)
{
if(item.ImageIsVisible==true)
LibraryListCollection.Add(item);
}
// LibraryListCollection=DesrilizedData;
}
else {
for (int i = 0; i < 5; i++)
{
int id = i + 1;
LibraryListCollection.Add(new LibraryList { imagePath = "Image.jpg" ,ImageIsVisible = true, ImageId = id });
}
var SerilizedData = JsonConvert.SerializeObject(LibraryListCollection);
LocalStorageHelper.StoreInLocalSetting(AppConstant.ListKey, SerilizedData);
}
ImageClicked = new Commands.DelegateCommand<int>(ImageClicked_function);
AddClicked = new Commands.DelegateCommand(AddClicked_function);
ImageLongPressed = new Commands.DelegateCommand<int>(ImageLongPressed_Function);
Cancel = new Commands.DelegateCommand(Cancel_Function);
DeleteCommand = new Commands.DelegateCommand(DeleteCommand_Function);
IsBusy = false;
}
private void DeleteCommand_Function()
{
IsBusy = true;
var data = (from a in LibraryListCollection where a.IsSelected == true select a).FirstOrDefault();
data.ImageIsVisible = false;
LibraryListCollection.Remove(data);
var SerilizedData = JsonConvert.SerializeObject(LibraryListCollection);
LocalStorageHelper.StoreInLocalSetting(AppConstant.ListKey, SerilizedData);
HeaderVisibility = true;
FooterVisibility = false;
IsBusy = false ;
}
private void Cancel_Function()
{
HeaderVisibility = true;
FooterVisibility = false;
}
private void ImageLongPressed_Function(int obj)
{
var data = (from a in LibraryListCollection where a.ImageId == obj select a).FirstOrDefault();
data.IsSelected = true;
HeaderVisibility = false;
FooterVisibility = true;
}
private async void AddClicked_function()
{
IsBusy = true;
int LastImageId = 0;
var status = await Permissions.RequestAsync<Permissions.Photos>();
if (LibraryListCollection.Count > 0) {
LastImageId = LibraryListCollection.Last().ImageId;
}
if (status == PermissionStatus.Granted)
{
var file =await CrossMedia.Current.PickPhotosAsync();
if (file != null)
{
foreach (var item in file)
{
LibraryListCollection.Add(new LibraryList { imagePath = item.Path , ImageIsVisible=true,ImageId= LastImageId+1 });
LastImageId++;
}
}
var SerilizedData = JsonConvert.SerializeObject(LibraryListCollection);
LocalStorageHelper.StoreInLocalSetting(AppConstant.ListKey, SerilizedData);
}
IsBusy = false;
}
private async void ImageClicked_function(int obj)
{
// var data = (from a in LibraryListCollection where a.ImageId == obj select a).IndexOf(a)
int index= LibraryListCollection.IndexOf(a => a.ImageId == obj);
// index++;
await PopupNavigation.PushAsync(new ImagePopup(index));
}
}
}
|
using System;
using System.Collections.Generic;
namespace Euler_Logic.Problems {
public class Problem151 : ProblemBase {
private Dictionary<int, Dictionary<int, int>> _papers = new Dictionary<int, Dictionary<int, int>>();
private decimal _totalProbability = 0;
/*
If you brute force every possible variation, there are only 40,040 unique ways to play out a week. However, not every way has the same probability.
If you imagine a tree starting at size A1 and branching out, the probability would start at 100% and divide by the count at each branch as you
travel down. For example, after cutting A1, you are left with four papers. Therefore each branch following A1 has a 25% of ocurring. Suppose you
then cut A2 - that now leaves you with two A3's, two A4's, and two A5's. With six papers, each paper would then be 25% / 6, or 4.167%. However,
since there are duplicates of paper sizes, you only need to consider the resulting branch of cutting an additional size. Since there are
three sizes, that yields three branches where each branch is 25% / (2 / 6), or 8.333%. Follow the unique branches, count the times you are left
with just one paper, and add the final probability once you reach the last job. Return the final probability round up to six digits.
*/
public override string ProblemName {
get { return "151: Paper sheets of standard sizes: an expected-value problem"; }
}
public override string GetAnswer() {
Initialize();
Solve(0, 1, 1);
return Math.Round(_totalProbability, 6).ToString();
}
private void Initialize() {
for (int job = 1; job <= 15; job++) {
_papers.Add(job, new Dictionary<int, int>());
for (int index = 1; index <= 5; index++) {
_papers[job].Add(index, 0);
}
}
_papers[1][1] = 1;
}
private void Solve(decimal currentSum, int currentJob, decimal currentProbability) {
decimal paperCount = 0;
for (int paper = 1; paper <= 5; paper++) {
paperCount += _papers[currentJob][paper];
}
currentSum += (paperCount == 1 ? 1 : 0);
if (currentJob == 15) {
_totalProbability += (currentSum - 1) * currentProbability;
} else {
for (int paper = 1; paper <= 5; paper++) {
if (_papers[currentJob][paper] > 0) {
for (int nextJobPaper = 1; nextJobPaper <= 5; nextJobPaper++) {
int offset = 0;
if (nextJobPaper == paper) {
offset = -1;
} else if (nextJobPaper > paper) {
offset += 1;
}
_papers[currentJob + 1][nextJobPaper] = _papers[currentJob][nextJobPaper] + offset;
}
Solve(currentSum, currentJob + 1, (currentProbability * _papers[currentJob][paper]) / paperCount);
}
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyOnlineShop.Models
{
public class Inventory
{
public int Id { get; set; }
public int ProductId { get; set; }
public int StocksRemaining { get; set; }
public int StocksQuantity { get; set; }
public DateTime DateAdded { get; set; }
public int ConsigneeEmployeeID { get; set; }
}
}
|
using System.Collections.Generic;
using System.Net.Http;
namespace BusinessSuitMVC.ModelClasses
{
internal class asyncService
{
private static readonly HttpClient client = new HttpClient();
public static string responseString = "";
public static string responseStringFull = "";
public asyncService()
{
}
public async void sendSingleSmsMethod2()//,string token
{
//environment.newline counts '\n' as 2 character. which is same to sms gateway
// or we can use \r\n and this is same as using environment.newline
//string message = "প্রিয় শিক্ষার্থীবৃন্দ," + Environment.NewLine + "সাময়িক অসুবিধার কারণে শনিবার(০৩/০৩/২০১৮) স্কুলে আইডি কার্ড বিতরণ করা হবে না।" + Environment.NewLine + "-সালাহউদ্দিন আহমেদ উচ্চ বিদ্যালয়";
string token = "9b8a6934e6c7e83dc79728274677b8f2";
string number = "01676797123";
string message = "test";
Dictionary<string, string> values = new Dictionary<string, string>(){
{ "token", token },
{ "to", number },
{ "message", message }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://sms.greenweb.com.bd/api.php?", content);
responseString = await response.Content.ReadAsStringAsync();
}
}
} |
using System.Collections.Generic;
using Union.Gateway.Abstractions;
namespace IotGatewayServer.Services
{
/// <summary>
/// 设备服务
/// </summary>
public class DefaultDeviceService: IDeviceService
{
/// <summary>
/// 设备授权校验
/// </summary>
/// <param name="terminalPhoneNo"></param>
/// <param name="Extras"></param>
/// <returns></returns>
public OperateResult Validation(string terminalPhoneNo, Dictionary<string, object> Extras = null)
{
return new OperateResult(0);
}
/// <summary>
/// 设备注册校验
/// </summary>
/// <param name="terminalPhoneNo"></param>
/// <param name="isUpdateRegisterInfo">是否更新设备信息</param>
/// <param name="Extras"></param>
/// <returns></returns>
public OperateResult RegionValidation(string terminalPhoneNo,bool isUpdateRegisterInfo=true, Dictionary<string, object> Extras = null)
{
return new OperateResult(0);
}
}
}
|
using System.Collections;
using UnityEngine;
public class Boulder : MonoBehaviour
{
public float rumbleTime;
public float rumbleDelta;
private float initRumbleTime;
private Rigidbody rb;
private bool activated = false;
private IEnumerator Rumble()
{
Vector3 initPosition = transform.position;
while (0.0f < rumbleTime)
{
rumbleTime -= Time.deltaTime;
transform.position = new Vector3(
initPosition.x + Random.Range(-rumbleDelta, rumbleDelta),
initPosition.y + Random.Range(-rumbleDelta, rumbleDelta),
initPosition.z + Random.Range(-rumbleDelta, rumbleDelta)
);
yield return new WaitForSeconds(0.01f);
transform.position = initPosition;
}
activated = true;
rb.useGravity = true;
}
public void Activate()
{
StartCoroutine(Rumble());
}
private void Awake()
{
initRumbleTime = rumbleTime;
rb = GetComponent<Rigidbody>();
}
private void Start()
{
rb.velocity = Vector3.zero;
rb.useGravity = false;
}
private void FixedUpdate()
{
if (!activated)
{
rb.velocity = Vector3.zero;
rb.useGravity = false;
}
}
private void OnCollisionEnter( Collision collision )
{
if ( collision.transform.tag == "Player" )
{
Destroy( collision.transform.gameObject );
}
}
}
|
using RabbitMQ.Client.Service.Options;
using System;
using System.Collections.Generic;
namespace RabbitMQ.Client.Service.Interfaces
{
public interface IPublisher
{
void PublishMessage(ExchangeOptions exchangeOptions,
string message,
Dictionary<string, object> messageAttributes,
string timeToLive = "30000");
}
}
|
using System;
using Pe.Stracon.Politicas.Infraestructura.QueryModel.Base;
namespace Pe.Stracon.Politicas.Infraestructura.QueryModel.General
{
/// <summary>
/// Representa los datos generales de la unidad operativa
/// </summary>
/// <remarks>
/// Creación: GMD 22150326 <br />
/// Modificación: <br />
/// </remarks>
public class UnidadOperativaLogic : Logic
{
/// <summary>
/// Código de unidad operativa
/// </summary>
public Guid? CodigoUnidadOperativa { get; set; }
/// <summary>
/// Código de identificación de la unidad operativa
/// </summary>
public string CodigoIdentificacion { get; set; }
/// <summary>
/// Nombre
/// </summary>
public string Nombre { get; set; }
/// <summary>
/// Código de Nivel de Jerarquía
/// </summary>
public string CodigoNivelJerarquia { get; set; }
/// <summary>
/// Descripción de Nivel de Jerarquía
/// </summary>
public string DescripcionNivelJerarquia { get; set; }
/// <summary>
/// Valor del Nivel de Jerarquía
/// </summary>
public int? NivelJerarquia { get; set; }
/// <summary>
/// Código de unidad operativa padre
/// </summary>
public Guid? CodigoUnidadOperativaPadre { get; set; }
/// <summary>
/// Nombre de unidad operativa padre
/// </summary>
public string NombreUnidadOperativaPadre { get; set; }
/// <summary>
/// Tipo de unidad operativa
/// </summary>
public string CodigoTipoUnidadOperativa { get; set; }
/// <summary>
/// Indicador de activación
/// </summary>
public bool? IndicadorActiva { get; set; }
/// <summary>
/// Código del responsable
/// </summary>
public Guid? CodigoResponsable { get; set; }
/// <summary>
/// Nombre del responsable
/// </summary>
public string NombreResponsable { get; set; }
/// <summary>
/// Código del primer representante
/// </summary>
public Guid? CodigoPrimerRepresentante { get; set; }
/// <summary>
/// Nombre del primer representante
/// </summary>
public string NombrePrimerRepresentante { get; set; }
/// <summary>
/// Código del segundo representante
/// </summary>
public Guid? CodigoSegundoRepresentante { get; set; }
/// <summary>
/// Nombre del segundo representante
/// </summary>
public string NombreSegundoRepresentante { get; set; }
/// <summary>
/// Código del tercer representante
/// </summary>
public Guid? CodigoTercerRepresentante { get; set; }
/// <summary>
/// Nombre del tercer representante
/// </summary>
public string NombreTercerRepresentante { get; set; }
/// <summary>
/// Código del cuarto representante
/// </summary>
public Guid? CodigoCuartoRepresentante { get; set; }
/// <summary>
/// Nombre del cuarto representante
/// </summary>
public string NombreCuartoRepresentante { get; set; }
/// <summary>
/// Dirección
/// </summary>
public string Direccion { get; set; }
/// <summary>
/// Logo Unidad Operativo
/// </summary>
public string LogoUnidadOperativa { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Services.Transaction;
using com.Sconit.Web.Models.MRP;
using com.Sconit.Service;
using com.Sconit.Web.Models;
using com.Sconit.Web.Models.SearchModels.CUST;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Entity.SCM;
using System.Reflection;
namespace com.Sconit.Web.Controllers.MRP
{
public class FlowClassifyController : WebAppBaseController
{
[SconitAuthorize(Permissions = "URl_MRP_FlowClassify_View")]
public ActionResult Index()
{
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "URl_MRP_FlowClassify_View")]
public ActionResult _SelectFlowClassifyList()
{
//IList<FlowClassify> newsflowClassifyList = new List<FlowClassify>();
var mrpFlowClassifys = genericMgr.FindAll<Entity.MRP.MD.FlowClassify>();
var flowMasterList = genericMgr.FindAll<FlowMaster>(" from FlowMaster as f where f.Type=? and f.ResourceGroup=? ",
new object[] { CodeMaster.OrderType.Production, CodeMaster.ResourceGroup.EX });
var flowClassifys = new List<FlowClassify>();
//如果FlowClassify中没有而flowMasterList有的增加进来
foreach (var flowMaster in flowMasterList)
{
var flowClassify = new FlowClassify();
flowClassify.Flow = flowMaster.Code;
flowClassifys.Add(flowClassify);
}
Type tClass = typeof(FlowClassify);
PropertyInfo[] pClass = tClass.GetProperties();
foreach (var mrpFlowClassify in mrpFlowClassifys)
{
var flowClassify = flowClassifys.FirstOrDefault(p => p.Flow == mrpFlowClassify.Flow);
if (flowClassify != null)
{
foreach (PropertyInfo pc in pClass)
{
try
{
if (pc.Name == mrpFlowClassify.Code)
{
pc.SetValue(flowClassify, true, null);
break;
}
}
catch
{
}
}
}
}
return PartialView(new GridModel(flowClassifys));
}
[HttpPost]
[SconitAuthorize(Permissions = "URl_MRP_FlowClassify_View")]
public string _SavaFlowClassify(string flows, string classify01s, string classify02s, string classify03s, string classify04s, string classify05s,
string classify06s, string classify07s, string classify08s, string classify09s, string classify10s)
{
try
{
genericMgr.Delete<Entity.MRP.MD.FlowClassify>(genericMgr.FindAll<Entity.MRP.MD.FlowClassify>());
string[] flowArray = flows.Split(',');
string[] classify01Array = classify01s.Split(',');
string[] classify02Array = classify02s.Split(',');
string[] classify03Array = classify03s.Split(',');
string[] classify04Array = classify04s.Split(',');
string[] classify05Array = classify05s.Split(',');
string[] classify06Array = classify06s.Split(',');
string[] classify07Array = classify07s.Split(',');
string[] classify08Array = classify08s.Split(',');
string[] classify09Array = classify09s.Split(',');
string[] classify10Array = classify10s.Split(',');
for (int i = 0; i < flowArray.Length; i++)
{
if (Convert.ToBoolean(classify01Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify01";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify02Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify02";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify03Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify03";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify04Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify04";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify05Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify05";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify06Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify06";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify07Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify07";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify08Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify08";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify09Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify09";
genericMgr.CreateWithTrim(flowClassify);
}
if (Convert.ToBoolean(classify10Array[i]))
{
var flowClassify = new Entity.MRP.MD.FlowClassify();
flowClassify.Flow = flowArray[i];
flowClassify.Code = "Classify10";
genericMgr.CreateWithTrim(flowClassify);
}
}
return Resources.EXT.ControllerLan.Con_ExtrusionFlowFunctionClassificationSavedSuccessfully;
}
catch (Exception ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write((ex.InnerException).InnerException);
return string.Empty;
}
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using Sitecore.Globalization;
using Sitecore.Mvc.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Helpers;
namespace SCHackathon.Feature.Form.CustomActions
{
public class SaveToAzure : SubmitActionBase<FormDataModel>
{
public SaveToAzure(ISubmitActionData submitActionData) : base(submitActionData)
{
}
/// <param name="data"></param>
/// <param name="formSubmitContext"></param>
/// <returns></returns>
protected override bool Execute(FormDataModel data, FormSubmitContext formSubmitContext)
{
Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));
try
{
var value = string.Empty;
var formFieldName = string.Empty;
var dict = new Dictionary<string, string>();
var fields = formSubmitContext.Fields.ToList();
foreach (var item in fields)
{
formFieldName = item.Name;
value = GetFieldValue(formSubmitContext, formFieldName);
dict.Add(formFieldName, value);
}
var formDetails = JsonConvert.SerializeObject(dict);
var queueClient = Translate.Text("clouddictionary");
var a=queueClient.Split(new string[] { "||" }, StringSplitOptions.None);
var cloudQueueClient = new Azure.Storage.Queues.QueueClient(a[0],a[1]);
cloudQueueClient.CreateIfNotExists();
cloudQueueClient.SendMessage(formDetails);
return true;
}
catch (Exception e)
{
Log.Error($"Error sending data to azure", e, this);
return false;
}
}
/// <summary>
/// To get Field values
/// </summary>
/// <param name="formSubmitContext"></param>
/// <param name="fieldName"></param>
/// <returns></returns>
private string GetFieldValue(FormSubmitContext formSubmitContext, string fieldName)
{
var fieldValue = string.Empty;
try
{
var valueField = formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals(fieldName));
var property = valueField?.GetType().GetProperty("Value");
if (property != null)
{
var postedId = property.GetValue(valueField);
if (valueField.GetType().Name == "DropDownListViewModel")
{
var result = ((IEnumerable)postedId).Cast<object>().ToList();
fieldValue = result.FirstOrDefault()?.ToString();
}
else if (valueField.GetType().Name == "ListViewModel")
{
var listField = (ListViewModel)postedId;
var array = listField?.Value?.ToArray();
if (array == null)
{
return string.Empty;
}
return String.Join(",", array);
}
else if (valueField.GetType().Name == "DateViewModel")
{
var dateField = (DateViewModel)postedId;
return dateField.Value.HasValue ? dateField.Value.Value.ToShortDateString() : string.Empty;
}
else if (valueField.GetType().Name == "NumberViewModel")
{
var numberField = (NumberViewModel)postedId;
return numberField.Value.HasValue ? numberField.Value.ToString() : string.Empty;
}
else if (valueField.GetType().Name == "CheckBoxListViewModel")
{
var checkbox = ((IEnumerable)postedId).Cast<object>().ToList();
var array = checkbox.ToArray();
return String.Join(",", array);
}
else if (valueField.GetType().Name == "TextViewModel")
{
var textField = (TextViewModel)postedId;
return (string)(object)textField.Text;
}
else
{
fieldValue = postedId.ToString();
}
}
}
catch (Exception ex)
{
Log.Error($"Error Getting FieldValue for {fieldName}", ex, this);
}
return fieldValue;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.