text stringlengths 13 6.01M |
|---|
using ParrisConnection.DataLayer.Entities.Profile;
using ParrisConnection.ServiceLayer.Data;
using System.Collections.Generic;
namespace ParrisConnection.ServiceLayer.Models
{
public class ProfileViewModel
{
public ProfilePhotoData ProfilePhoto { get; set; }
public IEnumerable<EmployerData> Employers { get; set; }
public IEnumerable<EducationData> Educations { get; set; }
public IEnumerable<QuoteData> Quotes { get; set; }
public IEnumerable<PhoneData> Phones { get; set; }
public IEnumerable<EmailData> Emails { get; set; }
public IEnumerable<PhoneTypeData> PhoneTypes { get; set; }
public List<EmailType> EmailTypes { get; set; }
public EmployerData NewEmployment { get; set; }
public EducationData NewEducation { get; set; }
public QuoteData NewQuote { get; set; }
public PhoneTypeData PhoneType { get; set; }
public PhoneData NewPhone { get; set; }
public EmailData NewEmail { get; set; }
public int? SelectedPhone { get; set; }
public int? SelectedEmail { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MapArcGIS
{
public class WorkSpaceWL : WorkSpace
{
private struct LineData
{
public int lineSum;
public int positionOffset;
public short lineType;
public byte assLineType;
public byte overrideType;
public int lineColorNumber;
public float lineWidth;
public byte lineKind;
public float argX;
public float argY;
public int assColor;
public int layer;
}
private struct LinePosition
{
public float X;
public float Y;
}
private struct NodeData
{
}
public override void LoadData(WorkSpaceInfo wsi)
{
base.LoadData(wsi);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace UnityStandardAssets.CrossPlatformInput
{
public class IceButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public UnityChanControlScriptWithRgidBody _unityChanControl;
public GameObject _ice;
public bool _isIceUse;
public Slider slider;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
slider.maxValue = _unityChanControl._maxEssence;
slider.value = _unityChanControl._CrystalEssence;
if (_unityChanControl._CrystalEssence < 1)
{
_ice.GetComponent<IceBallSpawner>()._shot = false;
_isIceUse = false;
}
}
public void OnPointerEnter(PointerEventData pointerEventData)
{
if (_unityChanControl._CrystalEssence >= 1)
{
_unityChanControl._CrystalEssence -= 1;
_isIceUse = true;
_ice.GetComponent<IceBallSpawner>()._shot = true;
}
}
public void OnPointerExit(PointerEventData pointerEventData)
{
_ice.GetComponent<IceBallSpawner>()._shot = false;
_isIceUse = false;
}
}
} |
using BHLD.Model.Models;
using BHLD.Services;
using BHLD.Web.Infrastructure.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace BHLD.Web.Api
{
[RoutePrefix("api/HuProvince")]
public class HuProvinceController : APIControllerBase
{
Ihu_provinceServices _ProvinceServices;
public HuProvinceController(IErrorService errorService, Ihu_provinceServices ihu_ProvinceServices) : base(errorService)
{
this._ProvinceServices = ihu_ProvinceServices;
}
[Route("Post")]
public HttpResponseMessage Post(HttpRequestMessage request, hu_province hu_Province)
{
return CreateHttpResponse(request, () =>
{
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
else
{
var district = _ProvinceServices.Add(hu_Province);
_ProvinceServices.SaveChanges();
response = request.CreateResponse(HttpStatusCode.Created, district);
}
return response;
}
);
}
[Route("Put")]
public HttpResponseMessage Put(HttpRequestMessage request, hu_province hu_Province)
{
return CreateHttpResponse(request, () =>
{
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
else
{
_ProvinceServices.Update(hu_Province);
_ProvinceServices.SaveChanges();
response = request.CreateResponse(HttpStatusCode.OK);
}
return response;
}
);
}
public HttpResponseMessage Delete(HttpRequestMessage request, int id)
{
return CreateHttpResponse(request, () =>
{
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
else
{
_ProvinceServices.Delete(id);
_ProvinceServices.SaveChanges();
response = request.CreateResponse(HttpStatusCode.OK);
}
return response;
}
);
}
[Route("getall")]
public HttpResponseMessage Get(HttpRequestMessage request)
{
return CreateHttpResponse(request, () =>
{
var listTitle = _ProvinceServices.GetAll();
HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, listTitle);
return response;
}
);
}
}
} |
namespace Codility
{
public class FrogRiverCrossing
{
public static int Find(int x, int[] A)
{
var river = new int?[x + 1];
int sum = 0;
for (int i = 1; i <= x; i++)
sum += i;
for (int minute = 0; minute < A.Length; minute++)
{
var riverPosition = A[minute];
if (!river[riverPosition].HasValue)
{
river[riverPosition] = minute;
sum -= riverPosition;
}
if (sum == 0)
{
return minute;
}
}
return -1;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab16
{
class RawDataItem
{
public string Name { get; set; }
public float Price { get; set; }
public int Count { get; set; }
public string Market { get; set; }
public float SumPrice { get; set; }
public RawDataItem(string Name, float Price, int Count, string Market)
{
this.Name = Name;
this.Price = Price;
this.Count = Count;
this.Market = Market;
this.SumPrice = Price * (float)Count;
}
public RawDataItem()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using IFKFormBase;
namespace FKFormBase
{
/// <summary>
/// 数据校验基类
/// </summary>
/// <typeparam name="V"></typeparam>
public class ValidateBase<V> : IValidateBase where V : class
{
public ValidateBase()
{
}
public ValidateBase(System.Web.HttpContext context)
{
this.Context = context;
}
static ValidateBase()
{
SetValidateInfoStaticList();
}
public string ErrorStr
{
get;
set;
}
public bool AutoSetValue { get; set; }
public List<ErrorItems> ErrorItemsList { get; set; }
public System.Web.HttpContext Context
{
get;
set;
}
public V ModelValidate
{
get;
set;
}
public List<string> ValueStrList
{
get;
set;
}
public static List<FKValidateModel.PropInfoWithValidte> ValidateInfoListStatic
{
get;
set;
}
public static string JavaScriptForWeb
{
get;
set;
}
public void SetModel(object model, bool autoSetValue)
{
this.ModelValidate = model as V;
this.AutoSetValue = autoSetValue;
SetValidateValues();
}
/// <summary>
/// 设置数值
/// </summary>
public void SetValidateValues()
{
if (AutoSetValue)
{
if (Context == null)
{
throw new ArgumentNullException("Context");
}
else
{
ValueStrList = new List<string>();
foreach (var validateItem in ValidateInfoListStatic)
{
string value = Context.Request[validateItem.PropInfo.Name];
string valueStr = GetFormatValueString(value);
ValueStrList.Add(valueStr);
}
}
}
else
{
ValueStrList = new List<string>();
foreach (var validateItem in ValidateInfoListStatic)
{
object value = validateItem.PropInfo.GetValue(ModelValidate);
string valueStr = GetFormatValueString(value == null ? null : value.ToString());
ValueStrList.Add(valueStr);
}
}
}
public virtual string GetFormatValueString(string value)
{
if (value != null)
{
return value.Trim();
}
else
{
return value;
}
}
public bool ValidForm(bool autoSetValue = true)
{
ErrorItemsList = new List<ErrorItems>();
bool valid = true;
foreach (var item in ValidateInfoListStatic)
{
foreach (var itemCheck in item.ControlAttrList)
{
ErrorItems errorItem = new ErrorItems();
if (!itemCheck.CheckValue(ValueStrList[item.Index]))
{
errorItem.ControlID = itemCheck.GetControlID();
errorItem.ErrorStr = itemCheck.GetErrorStr();
errorItem.ValidateType = itemCheck.GetControlType();
ErrorItemsList.Add(errorItem);
valid = false;
}
}
}
if (valid == true && autoSetValue)
{
SetModelValues(ModelValidate, ValidateInfoListStatic);
}
return valid;
}
/// <summary>
/// 赋值模型
/// </summary>
/// <param name="ModelValidate"></param>
/// <param name="validateInfoList"></param>
private void SetModelValues(V ModelValidate, List<FKValidateModel.PropInfoWithValidte> validateInfoList)
{
foreach (var item in validateInfoList)
{
string valueThis = ValueStrList[item.Index];
if (!string.IsNullOrEmpty(valueThis))
{
object value = ChangeTypeHelper.ChangeType(valueThis, item.PropInfo.PropertyType);
item.PropInfo.SetValue(ModelValidate, value);
}
}
}
/// <summary>
/// 生成JS校验代码
/// </summary>
/// <returns></returns>
public string RenderJavaScriptValidateString()
{
if (JavaScriptForWeb == null)
{
object obj = new object();
lock (obj)
{
if (JavaScriptForWeb == null)
{
StringBuilder sb = new StringBuilder(ValidateInfoListStatic.Sum(u => u.ControlAttrList.Count) * 20);
foreach (var item in ValidateInfoListStatic)
{
StringBuilder sbOne = new StringBuilder(item.ControlAttrList.Count * 20);
sbOne.Append("[");
foreach (var itemCheck in item.ControlAttrList)
{
if (sbOne.Length == 1)
{
sbOne.Append(itemCheck.RenderCheckScript());
}
else
{
sbOne.Append("," + itemCheck.RenderCheckScript());
}
}
sbOne.Append("]");
if (sb.Length == 0)
{
sb.Append(sbOne.ToString());
}
else
{
sb.Append("," + sbOne.ToString());
}
}
JavaScriptForWeb = string.Format(FormControlPublicValue.JavaScriptValidateObjTmp, sb.ToString());
}
}
}
return JavaScriptForWeb;
}
private static void SetValidateInfoStaticList()
{
if (ValidateInfoListStatic == null)
{
object o = new object();
lock (o)
{
if (ValidateInfoListStatic == null)
{
int index = 0;
ValidateInfoListStatic = new List<FKValidateModel.PropInfoWithValidte>();
Type t = typeof(V);
PropertyInfo[] propList = t.GetProperties();
foreach (var prop in propList)
{
List<IFormControl> iAttributeList = new List<IFormControl>();
object[] attrs = prop.GetCustomAttributes(typeof(IFormControl), true);
foreach (var attr in attrs)
{
IFormControl control = attr as IFormControl;
iAttributeList.Add(control);
}
FKValidateModel.PropInfoWithValidte items = new FKValidateModel.PropInfoWithValidte();
items.ControlAttrList = iAttributeList;
items.Index = index;
items.PropInfo = prop;
ValidateInfoListStatic.Add(items);
index++;
}
}
}
}
}
/// <summary>
/// 生成后台错误提示
/// </summary>
/// <returns></returns>
public string RenderBackJavaScriptValidateString()
{
string strJsonStr=RenderJsonItem();
return string.Format(FormControlPublicValue.JavaScriptServerValidateErrorArray, strJsonStr);
}
public string RenderBackJavaScriptAjaxValidateString()
{
string strJsonStr = RenderJsonItem();
return string.Format(FormControlPublicValue.JavaScriptServerValidateAjaxScript, strJsonStr);
}
public void SetContext(System.Web.HttpContext context)
{
this.Context = context;
}
private string RenderJsonItem()
{
StringBuilder sb = new StringBuilder(ErrorItemsList.Count * 20);
sb.Append("[");
foreach (var errorItem in ErrorItemsList)
{
if (sb.Length > 1)
{
sb.Append(",{\"ControlID\":\"" + errorItem.ControlID + "\",\"ValidateType\":\"" + errorItem.ValidateType + "\",\"ErrorStr\":\"" + errorItem.ErrorStr + "\"}");
}
else
{
sb.Append("{\"ControlID\":\"" + errorItem.ControlID + "\",\"ValidateType\":\"" + errorItem.ValidateType + "\",\"ErrorStr\":\"" + errorItem.ErrorStr + "\"}");
}
}
sb.Append("]");
return sb.ToString();
}
}
} |
using gView.Framework.Carto;
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.Geometry;
using gView.Framework.Globalisation;
using gView.Framework.IO;
using gView.Framework.system;
using gView.Framework.UI;
using gView.Framework.UI.Events;
using gView.Plugins.MapTools.Dialogs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Plugins.MapTools
{
[RegisterPlugInAttribute("F13D5923-70C8-4c6b-9372-0760D3A8C08C")]
public class Identify : gView.Framework.UI.ITool, gView.Framework.UI.IToolWindow, IPersistable
{
private IMapDocument _doc = null;
private FormIdentify _dlg = null;
private ToolType _type = ToolType.click;
private double _tolerance = 3.0;
public Identify()
{
//_dlg = new FormIdentify();
}
#region ITool Members
public string Name
{
get { return LocalizedResources.GetResString("Tools.Identify", "Identify"); }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return "Identify"; }
}
public ToolType toolType
{
get
{
if (_dlg == null)
{
return _type;
}
if (_type == ToolType.rubberband)
{
QueryThemeCombo combo = QueryCombo;
if (combo == null)
{
return _type;
}
if (combo.ThemeMode == QueryThemeMode.Default)
{
List<IDatasetElement> allQueryableElements = _dlg.AllQueryableLayers;
if (allQueryableElements == null)
{
return _type;
}
foreach (IDatasetElement element in allQueryableElements)
{
if (element.Class is IPointIdentify/* && queryPoint != null*/)
{
return ToolType.click;
}
}
}
return _type;
}
else
{
return _type;
}
}
set { _type = value; }
}
public object Image
{
get
{
return gView.Win.Plugin.Tools.Properties.Resources.info;
}
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
_dlg = new FormIdentify();
_dlg.MapDocument = _doc;
}
if (hook is Control)
{
}
}
async public Task<bool> OnEvent(object MapEvent)
{
if (_dlg == null || !(MapEvent is MapEvent))
{
return true;
}
Envelope envelope = null;
IMap map = null;
double tol = 0;
map = ((MapEvent)MapEvent).Map;
// 3 Pixel Toleranz
if (map is IDisplay)
{
tol = _tolerance * ((IDisplay)map).mapScale / (96 / 0.0254); // [m]
if (map.Display.SpatialReference != null &&
map.Display.SpatialReference.SpatialParameters.IsGeographic)
{
tol = (180.0 * tol / Math.PI) / 6370000.0;
}
}
ISpatialReference mapSR = (map.Display.SpatialReference != null) ? map.Display.SpatialReference.Clone() as ISpatialReference : null;
IPoint queryPoint = null;
if (MapEvent is MapEventClick)
{
MapEventClick ev = (MapEventClick)MapEvent;
map = ev.Map;
if (map == null || map.Display == null)
{
return true;
}
queryPoint = new Point(ev.x, ev.y);
envelope = new Envelope(ev.x - tol / 2, ev.y - tol / 2, ev.x + tol / 2, ev.y + tol / 2);
_dlg.Clear();
_dlg.SetLocation(ev.x, ev.y);
}
else if (MapEvent is MapEventRubberband)
{
MapEventRubberband ev = (MapEventRubberband)MapEvent;
map = ev.Map;
if (map == null || map.Display == null)
{
return true;
}
envelope = new Envelope(ev.minX, ev.minY, ev.maxX, ev.maxY);
if (envelope.Width < tol)
{
envelope.minx = 0.5 * envelope.minx + 0.5 * envelope.maxx - tol / 2.0;
envelope.maxx = 0.5 * envelope.minx + 0.5 * envelope.maxx + tol / 2.0;
}
if (envelope.Height < tol)
{
envelope.miny = 0.5 * envelope.miny + 0.5 * envelope.maxy - tol / 2.0;
envelope.maxy = 0.5 * envelope.miny + 0.5 * envelope.maxy + tol / 2.0;
}
_dlg.Clear();
//_dlg.setLocation(envelope.);
}
else
{
return true;
}
QueryThemeCombo combo = QueryCombo;
if (combo == null || combo.ThemeMode == QueryThemeMode.Default)
{
#region ThemeMode Default
IdentifyMode mode = _dlg.Mode;
int counter = 0;
List<IDatasetElement> allQueryableElements = _dlg.AllQueryableLayers;
if (allQueryableElements == null)
{
return true;
}
foreach (IDatasetElement element in allQueryableElements)
{
#region IPointIdentify
if (element.Class is IPointIdentify/* && queryPoint != null*/)
{
IPoint iPoint = null;
if (queryPoint != null)
{
iPoint = queryPoint;
}
else if (queryPoint == null && envelope != null)
{
if (envelope.Width < 3.0 * tol && envelope.Height < 3.0 * tol)
{
iPoint = new Point((envelope.minx + envelope.maxx) * 0.5, (envelope.miny + envelope.maxy) * 0.5);
}
}
if (iPoint != null)
{
using (var pointIdentifyContext = ((IPointIdentify)element.Class).CreatePointIdentifyContext())
using (ICursor cursor = await ((IPointIdentify)element.Class).PointQuery(map.Display, queryPoint, map.Display.SpatialReference, new UserData(), pointIdentifyContext))
{
if (cursor is IRowCursor)
{
IRow row;
while ((row = await ((IRowCursor)cursor).NextRow()) != null)
{
_dlg.AddFeature(new Feature(row), mapSR, null, element.Title);
counter++;
}
}
else if (cursor is ITextCursor)
{
_dlg.IdentifyText += ((ITextCursor)cursor).Text;
}
else if (cursor is IUrlCursor)
{
_dlg.IdentifyUrl = ((IUrlCursor)cursor).Url;
}
}
}
}
#endregion
if (!(element is IFeatureLayer))
{
continue;
}
IFeatureLayer layer = (IFeatureLayer)element;
IFeatureClass fc = layer.Class as IFeatureClass;
if (fc == null)
{
continue;
}
#region QueryFilter
SpatialFilter filter = new SpatialFilter();
filter.Geometry = envelope;
filter.FilterSpatialReference = map.Display.SpatialReference;
filter.FeatureSpatialReference = map.Display.SpatialReference;
filter.SpatialRelation = spatialRelation.SpatialRelationIntersects;
if (layer.FilterQuery != null)
{
filter.WhereClause = layer.FilterQuery.WhereClause;
}
IFieldCollection fields = layer.Fields;
if (fields == null)
{
filter.SubFields = "*";
}
else
{
foreach (IField field in fields.ToEnumerable())
{
if (!field.visible)
{
continue;
}
filter.AddField(field.name);
}
if (layer.Fields.PrimaryDisplayField != null)
{
filter.AddField(layer.Fields.PrimaryDisplayField.name);
}
}
#endregion
#region Layer Title
string primaryFieldName = (layer.Fields.PrimaryDisplayField != null) ? layer.Fields.PrimaryDisplayField.name : "";
string title = element.Title;
if (map.TOC != null)
{
ITOCElement tocElement = map.TOC.GetTOCElement(layer);
if (tocElement != null)
{
title = tocElement.Name;
}
}
#endregion
#region Query
using (IFeatureCursor cursor = (IFeatureCursor)await fc.Search(filter))
{
if (cursor != null)
{
IFeature feature;
while ((feature = await cursor.NextFeature()) != null)
{
_dlg.AddFeature(feature, mapSR, layer, title);
counter++;
}
cursor.Dispose();
}
}
#endregion
if (mode == IdentifyMode.topmost && counter > 0)
{
break;
}
}
#endregion
}
else if (combo.ThemeMode == QueryThemeMode.Custom)
{
#region ThemeMode Custom
foreach (QueryTheme theme in combo.UserDefinedQueries.Queries)
{
if (theme.Text == combo.Text)
{
foreach (QueryThemeTable table in theme.Nodes)
{
IFeatureLayer layer = table.GetLayer(_doc) as IFeatureLayer;
if (layer == null || !(layer.Class is IFeatureClass))
{
continue;
}
IFeatureClass fc = layer.Class as IFeatureClass;
#region Fields
IFieldCollection fields = null;
IField primaryDisplayField = null;
if (layer.Fields != null && table.VisibleFieldDef != null && table.VisibleFieldDef.UseDefault == false)
{
fields = new FieldCollection();
foreach (IField field in layer.Fields.ToEnumerable())
{
if (table.VisibleFieldDef.PrimaryDisplayField == field.name)
{
primaryDisplayField = field;
}
DataRow[] r = table.VisibleFieldDef.Select("Visible=true AND Name='" + field.name + "'");
if (r.Length == 0)
{
continue;
}
Field f = new Field(field);
f.visible = true;
f.aliasname = (string)r[0]["Alias"];
((FieldCollection)fields).Add(f);
}
}
else
{
fields = layer.Fields;
primaryDisplayField = layer.Fields.PrimaryDisplayField;
}
#endregion
#region QueryFilter
SpatialFilter filter = new SpatialFilter();
filter.Geometry = envelope;
filter.FilterSpatialReference = map.Display.SpatialReference;
filter.FeatureSpatialReference = map.Display.SpatialReference;
filter.SpatialRelation = spatialRelation.SpatialRelationIntersects;
if (layer.FilterQuery != null)
{
filter.WhereClause = layer.FilterQuery.WhereClause;
}
if (fields == null)
{
filter.SubFields = "*";
}
else
{
foreach (IField field in fields.ToEnumerable())
{
if (!field.visible)
{
continue;
}
filter.AddField(field.name);
}
if (primaryDisplayField != null)
{
filter.AddField(primaryDisplayField.name);
}
}
#endregion
#region Layer Title
string primaryFieldName = (layer.Fields.PrimaryDisplayField != null) ? layer.Fields.PrimaryDisplayField.name : "";
string title = layer.Title;
if (map.TOC != null)
{
ITOCElement tocElement = map.TOC.GetTOCElement(layer);
if (tocElement != null)
{
title = tocElement.Name;
}
}
#endregion
#region Query
using (IFeatureCursor cursor = (IFeatureCursor)await fc.Search(filter))
{
IFeature feature;
while ((feature = await cursor.NextFeature()) != null)
{
_dlg.AddFeature(feature, mapSR, layer, title, fields, primaryDisplayField);
}
cursor.Dispose();
}
#endregion
}
}
}
#endregion
}
_dlg.WriteFeatureCount();
_dlg.ShowResult();
if (_doc.Application is IGUIApplication)
{
IGUIApplication appl = (IGUIApplication)_doc.Application;
foreach (IDockableWindow win in appl.DockableWindows)
{
if (win == _dlg)
{
appl.ShowDockableWindow(win);
return true;
}
}
appl.AddDockableWindow(_dlg, null);
appl.ShowDockableWindow(_dlg);
}
return true;
}
private object ICursor(IPointIdentify iPointIdentify)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IToolWindow Members
public IDockableWindow ToolWindow
{
get { return _dlg; }
}
#endregion
public double Tolerance
{
get { return _tolerance; }
set { _tolerance = value; }
}
private QueryThemeCombo QueryCombo
{
get
{
if (_doc == null || !(_doc.Application is IGUIApplication))
{
return null;
}
return ((IGUIApplication)_doc.Application).Tool(new Guid("51A2CF81-E343-4c58-9A42-9207C8DFBC01")) as QueryThemeCombo;
}
}
private Find FindTool
{
get
{
if (_doc == null || !(_doc.Application is IGUIApplication))
{
return null;
}
return ((IGUIApplication)_doc.Application).Tool(new Guid("ED5B0B59-2F5D-4b1a-BAD2-3CABEF073A6A")) as Find;
}
}
internal QueryThemes UserDefinedQueries
{
get
{
QueryThemeCombo combo = QueryCombo;
if (combo == null)
{
return null;
}
return combo.UserDefinedQueries;
}
set
{
QueryThemeCombo combo = QueryCombo;
if (combo == null)
{
return;
}
combo.UserDefinedQueries = value;
}
}
internal QueryThemeMode ThemeMode
{
get
{
QueryThemeCombo combo = QueryCombo;
if (combo == null)
{
return QueryThemeMode.Default;
}
return combo.ThemeMode;
}
set
{
QueryThemeCombo combo = QueryCombo;
if (combo != null)
{
combo.ThemeMode = value;
combo.RebuildCombo();
}
Find find = FindTool;
if (find != null)
{
find.ThemeMode = value;
}
}
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
_type = (ToolType)stream.Load("ToolType", (int)ToolType.click);
_tolerance = (double)stream.Load("Tolerance", 3.0);
UserDefinedQueries = stream.Load("UserDefinedQueries", null, new QueryThemes(null)) as QueryThemes;
ThemeMode = (QueryThemeMode)stream.Load("QueryMode", (int)QueryThemeMode.Default);
}
public void Save(IPersistStream stream)
{
stream.Save("ToolType", (int)_type);
stream.Save("Tolerance", _tolerance);
if (UserDefinedQueries != null)
{
stream.Save("UserDefinedQueries", UserDefinedQueries);
}
stream.Save("QueryMode", (int)ThemeMode);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyDev.BL;
using System.Data;
using log4net;
namespace SQMS.Services
{
public class EmergencyEventService : GenericService
{
private static readonly ILog log = LogManager.GetLogger(typeof(EmergencyEventService));
public EnumerationService EnumService { get; private set; }
protected override void Initialize()
{
BOName = "EMERGENCYEVENT";
EnumService = ServiceManager.CreateService<EnumerationService>();
base.Initialize();
}
public DataTable GetEvent(string eventId)
{
string sql = this.getEventMainSql() + " AND E.EVENTID='"+eventId+"' AND E.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'";
DataTable dt = null;
try
{
dt = this.DefaultSession.GetDataSetFromCommand(sql).Tables[0];
}
catch (Exception e)
{
log.Error(e.ToString());
throw;
}
return dt;
}
public DataTable GetEventList()
{
return this.GetEventList("");
}
public DataTable GetEventList(string dateFilter)
{
string sql = this.getEventMainSql() + " {0} AND E.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'";
if (!String.IsNullOrEmpty(dateFilter))
{
sql = String.Format(sql, " AND E.MODIFIED = TO_DATE('"+dateFilter+"', 'yyyy-mm-dd')");
}
else
{
sql = String.Format(sql, "");
}
DataTable dt = null;
try
{
dt = this.DefaultSession.GetDataSetFromCommand(sql).Tables[0];
}
catch (Exception e)
{
log.Error(e.ToString());
throw;
}
return dt;
}
public DataTable GetEventVideoList(string eventId)
{
string sql = @"SELECT V.VIDEOID,
V.VIDEONAME,
V.MEMO,
V.VIDEOURL,
V.TRACE,
V.CREATED,
V.CREATEDBY,
V.MODIFIED,
V.MODIFIEDBY,
V.ORGANIZATIONID,
V.SUITEID,
V.ISVOID,
M.MPID
FROM EMERGENCYEVENT E
INNER JOIN MPASSIGNMENT M ON M.EVENTID = E.EVENTID
INNER JOIN MONITORPOINTINVIDEO MV ON MV.MPID = M.MPID
INNER JOIN VIDEO V ON V.VIDEOID = MV.VIDEOID
WHERE E.EVENTID = '" + eventId + @"'
AND V.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'
AND M.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'
AND E.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'";
DataTable dt = null;
try
{
dt = this.DefaultSession.GetDataSetFromCommand(sql).Tables[0];
}
catch (Exception e)
{
log.Error(e.ToString());
throw;
}
return dt;
}
private string getEventMainSql()
{
return @"SELECT E.EVENTID,
E.SCHEMAID,
E.EVENTNAME,
E.ISVOID,
E.CREATED,
E.CREATEDBY,
E.MODIFIED,
E.MODIFIEDBY,
E.ORGANIZATIONID,
E.CHECKTIME,
E.CHECKUNIT,
E.PRIVILIGE,
E.EMERGENCYCHARGEPERSON,
EMP.EMPNAME,
(SELECT M.MPID
FROM MPASSIGNMENT M
WHERE M.ISSTART = 'Y'
AND M.EVENTID = E.EVENTID
AND M.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"') AS STARTMPID
FROM EMERGENCYEVENT E
LEFT JOIN EMPLOYEE EMP ON EMP.EMPID = E.EMERGENCYCHARGEPERSON
AND EMP.ORGANIZATIONID = '" + this.CurrentUser.OrganizationID + @"'
WHERE 1=1";
}
}
} |
using System;
using System.Threading.Tasks;
namespace Howler.Blazor.Components
{
/// <summary>
/// See https://github.com/goldfire/howler.js
/// </summary>
public interface IHowl : IHowlEvents
{
#region Properties
TimeSpan TotalTime { get; }
#endregion
#region Methods
ValueTask<int> Play(params Uri[] locations);
ValueTask<int> Play(params string[] sources);
ValueTask<int> Play(byte[] audio, string mimeType);
ValueTask<int> Play(HowlOptions options);
ValueTask Play(int soundId);
ValueTask Stop(int soundId);
ValueTask Pause(int soundId);
ValueTask Seek(int soundId, TimeSpan position);
ValueTask Rate(int soundId, double rate);
/// <summary>
/// This is called by default, but if you set preload to false, you must call load before you can play any sounds.
/// </summary>
ValueTask Load(int soundId);
/// <summary>
/// Unload and destroy a Howl object. This will immediately stop all sounds attached to this sound and remove it from the cache.
/// </summary>
ValueTask Unload(int soundId);
ValueTask<double> GetRate(int soundId);
ValueTask<TimeSpan> GetCurrentTime(int soundId);
ValueTask<TimeSpan> GetTotalTime(int soundId);
ValueTask<bool> IsPlaying(int soundId);
#endregion
}
} |
using Framework.Core.Common;
using Framework.Core.Config;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
namespace Tests.Pages.Oberon.Tenant
{
public class TenantDetail : TenantBasePage
{
#region Page Objects
private static string _url = AppConfig.OberonBaseUrl + "/Tenant/Detail/1";
public string HeaderText = "Ngp";
public IWebElement AddLink { get { return _driver.FindElement(By.CssSelector(".add")); } }
public IWebElement ManageUsersLink { get { return _driver.FindElement(By.XPath("//a[contains(text(),'Manage Users')][2]")); } }
public IWebElement LogoutLink { get { return _driver.FindElement(By.XPath("//a[contains(text(),'Logout')]")); } }
#endregion
public TenantDetail(Driver driver) : base(driver) { }
#region Methods
/// <summary>
/// navigates directly to tenant detail page
/// </summary>
public void GoToThisPageDirectly()
{
_driver.GoToPage(_url);
}
/// <summary>
/// clicks add link
/// </summary>
public void ClickAddLink()
{
_driver.Click(AddLink);
}
/// <summary>
/// clicks manage users link
/// </summary>
public void ClickManageUsersLink()
{
_driver.Click(ManageUsersLink);
}
/// <summary>
/// clicks logout link
/// </summary>
public new void ClickLogoutLink()
{
_driver.Click(LogoutLink);
}
/// <summary>
/// navigates to tenant update page by passing in tenant id in url
/// </summary>
public void EditTenant(long tenantId)
{
_driver.GoToPage(AppConfig.OberonBaseUrl + "/Tenant/Update?tenantId=" + tenantId);
var edit = new TenantUpdate(_driver);
_driver.WaitForElementToDisplayBy(edit.HeaderLocator);
Assert.IsTrue(edit.Header.Text.Contains(edit.HeaderText));
}
#endregion
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using ContestsPortal.Domain.DataAccess;
using ContestsPortal.Domain.Models;
using ContestsPortal.WebSite.App_Start;
using ContestsPortal.WebSite.ViewModels.Account;
using Microsoft.AspNet.Identity.Owin;
namespace ContestsPortal.WebSite.Controllers
{
public class VerificationController : Controller
{
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> VerificateUserName(string username)
{
if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username");
if (!Request.IsAjaxRequest()) return null;
var um = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
bool isfree = await um.FindByNameAsync(username) == null;
return Json(isfree, JsonRequestBehavior.DenyGet);
}
[HttpPost]
[AllowAnonymous]
public Task<JsonResult> VerificateUserNickName(string nickname)
{
if (string.IsNullOrEmpty(nickname)) throw new ArgumentNullException("nickname");
if (!Request.IsAjaxRequest()) return null;
return Task<JsonResult>.Factory.StartNew(() =>
{
using (var context = HttpContext.GetOwinContext().Get<PortalContext>())
{
var uppernick = nickname.ToUpper();
var isFree = context.Users.SingleOrDefault(x => x.NickName.ToUpper().Equals(uppernick)) == null;
return Json(isFree, JsonRequestBehavior.DenyGet);
}
});
}
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> VerificateUserEmail(string email)
{
if (string.IsNullOrEmpty(email)) throw new ArgumentNullException("email");
if (!Request.IsAjaxRequest()) return null;
var um = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
bool isfree = await um.FindByEmailAsync(email) == null;
return Json(isfree, JsonRequestBehavior.DenyGet);
}
}
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SelectionCommittee.DAL.Entities
{
public class City
{
[Key]
public int Id { set; get; }
public string Name { get; set; }
[ForeignKey("Region")]
public int RegionId { get; set; }
public Region Region { get; set; }
public ICollection<Enrollee> Enrollees { set; get; }
public City()
{
Enrollees = new List<Enrollee>();
}
}
}
|
namespace Profiling2.Infrastructure.NHibernateMaps.Conventions
{
#region Using Directives
using FluentNHibernate.Conventions;
#endregion
public class TableNameConvention : IClassConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
{
//instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));
//instance.Table("PRF_" + instance.EntityType.Name);
// e.g. Profiling2.Domain.Scr.Proposed.RequestProposedPerson
string[] namespaces = instance.EntityType.Namespace.Split('.');
if (namespaces != null && namespaces.Length > 2)
{
// produces 'Scr_RequestProposedPerson'.
instance.Table(namespaces[2] + "_" + instance.EntityType.Name);
}
else
instance.Table(instance.EntityType.Name);
}
}
} |
using Mettes_Planteskole.Models.Linq;
using Mettes_Planteskole.Models.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Mettes_Planteskole
{
public partial class _default : CustomPage
{
protected void Page_Load(object sender, EventArgs e)
{
var kontakt = db.KontaktInfos.FirstOrDefault(i => i.id == 1);
if (kontakt != null)
{
LiteralKontaktInfo.Text = kontakt.Text;
}
var tider = db.Abningstiders.FirstOrDefault(i => i.id == 1);
if (tider != null)
{
LiteralTider.Text = tider.Text;
}
var forside = db.Forsides.FirstOrDefault(i => i.Id == 1);
if (forside != null)
{
forsideindhold.InnerHtml = forside.tekst;
}
}
}
} |
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Wallet.Win.Common;
using GFramework.BlankWindow;
using System.ComponentModel.Composition;
using System.Windows;
namespace FiiiCoin.Wallet.Win
{
/// <summary>
/// Shell.xaml 的交互逻辑
/// </summary>
[Export(typeof(IShell))]
public partial class Shell : BlankWindow, IShell
{
public Shell()
{
InitializeComponent();
}
public Window GetWindow()
{
return this;
}
private void Menu_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
if (sender is System.Windows.Controls.MenuItem)
{
e.Handled = true;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectorNode : Compositor {
NodeStatus[] nodeStats;
bool allNodesFailed = false;
public SelectorNode(BehaviorTreeController btController) : base(btController) {}
public override NodeStatus Tick()
{
nodeStats = new NodeStatus[children.Length];
NodeStatus nodeStatus = NodeStatus.RUNNING;
while (!allNodesFailed)
{
RunAllNodes(nodeStatus);
}
if (allNodesFailed)
{
nodeStatus = NodeStatus.FAILURE;
}
return nodeStatus;
}
private void RunAllNodes(NodeStatus nodeStatus)
{
int i = 0;
while (i < children.Length)
{
while (nodeStatus == NodeStatus.RUNNING)
{
nodeStatus = children[i].Tick(); //keep ticking in the children until something is not running
}
if (nodeStatus == NodeStatus.FAILURE)
{
nodeStats[i] = nodeStatus;
}
}
//we're through all nodes, now we need to either loop or if all failed return failure
foreach(NodeStatus ns in nodeStats)
{
if(ns == NodeStatus.SUCCESS)
{
RunAllNodes(nodeStatus); //run this function again until we get a failure on all nodes
}
}
// if we get out of this for loop then we've got all failures
allNodesFailed = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SnowBLL.Models.Users
{
public class UserFiltrationModel
{
public string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using ToChange.Models;
namespace ToChange.DB_Connections
{
public class DAL
{
public static ToChangeDBModelEntities entity = new ToChangeDBModelEntities();
public static DbSet<Customer> Customers { get { return entity.Customers; } }
public static DbSet<Exchange> Exchanges { get { return entity.Exchanges; } }
public static DbSet<Product> Products { get { return entity.Products; } }
public static DbSet<User> Users { get { return entity.Users; } }
public static DbSet<Category> Categories { get { return entity.Categories; } }
public static DbSet<Poke> Pokes { get { return entity.Pokes; } }
public static DbSet<SwapHandler> Swap { get { return entity.Swap; } }
}
} |
using Nac.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using Nac.Common.Control;
using System.Collections.Specialized;
using Nac.Wpf.Common.Control;
using static NacUtils;
using static NacWpfUtils;
using Nac.Wcf.Common;
using System.Collections;
using System.Windows.Data;
using System.IO;
using System.Windows;
using System.Collections.ObjectModel;
namespace Nac.Wpf.Common {
public class NacWpfEngine : NacWpfObjectWithChildren,/* ICollection<NacWpfObject>,*/ INacWpfChildrenOwner {
private const string _offline = "offline";
public NacWpfEngine(string host = _offline) : base(new NacObjectWithChildren()) {
Name = Host = host;
Path = $"net.tcp://{Host}:65456";
Catalog = new NacCatalog<NacWpfObject>();
Init();
}
public bool IsOffline { get { return Host == _offline; } }
private NacWcfEngineClient _client;
private NacWcfEngineClient Client {
get {
if (_client == null && !IsOffline) {
_client = new NacWcfEngineClient(Path);
_client.CallbackObject.NewEngineMessageEvent += _client_NewEngineMessageEvent;
}
return _client;
}
}
public event NewEngineMessageHandler NewEngineMessageEvent;
private void _client_NewEngineMessageEvent(string[] messages) {
NewEngineMessageEvent?.Invoke(messages);
}
public IEnumerable<NacWpfObject> Projects { get { return Children; } }
public string Host { get; set; }
private bool ChangeAllowed {
get {
return NacSecurity.CanChangeRemoteEngines;
}
}
private void Init() {
using (new NacWpfWaitCursor()) {
if (IsOffline) Catalog = new NacCatalog<NacWpfObject>();
else {
NacCatalog<NacObject> catalog = null;
if (Succeeds(() => Client.GetCatalog(), ref catalog, warn: true))
Catalog = new NacCatalog<NacWpfObject>(catalog.Select(nacObject => Create(nacObject)));
}
}
}
//WPF propagation to containers is in this class on collection catalog methods
public void Add(IEnumerable<NacObject> list) {
if (IsOffline || (ChangeAllowed && Succeeds(() => Client.Add(list), warn: true))) {
Add(list.Select(nacObject => Create(nacObject)).ToArray());
NacSecurity.Log(Name, "Add");
}
}
public void Add(NacObject obj) {
Add(new List<NacObject> { obj });
}
//WPF propagation to containers is in this class on collection catalog methods
public void Delete(string[] paths) {
if (IsOffline || (ChangeAllowed && Succeeds(() => Client.Delete(paths), warn: true)))
foreach (var path in paths) Remove(path);
NacSecurity.Log(Name, "Delete");
}
public void Delete(string path) {
Delete(new string[] { path });
}
public void Delete(NacWpfObject wpfObject) {
Delete(wpfObject.Flat().Select(nacObject => nacObject.Path).ToArray());
}
//WPF propagation occurs in the property set accessor of the NacWpfObject wrapper
public void Update(string path, string property, object value) {
Update(new string[] { path }, property, new object[] { value });
}
public void Update(string[] paths, string property, object[] values) {
if (IsOffline || (ChangeAllowed && Succeeds(() => Client.Update(paths, property, values.Select(v => new NacWcfObject(v)).ToArray()), warn: true))) {
for (int i = 0; i < Math.Min(paths.Length, values.Length); i++)
NacUtils.Update(Catalog[paths[i]], property, values[i]);
NacSecurity.Log(Name, "Update");
}
}
//WPF propagation occurs in the caller
public Dictionary<string, NacTagValue> GetValues(string[] tagPaths) {
return Protect(() => Client?.GetValues(tagPaths));
}
public Dictionary<string, NacTagValue> GetRTDBValues(string rtdbPath) {
return Protect(() => Client?.GetRDTBValues(rtdbPath));
}
public Dictionary<string, NacExecutionStatus> GetSectionStates(string sectionPath) {
return Protect(() => Client?.GetSectionStates(sectionPath));
}
//WPF propagation occurs in the caller
public void Connect(string blockPathSource, string blockPathDestination, string sourceConnector, string destinationConnector) {
if (IsOffline || (ChangeAllowed && Succeeds(() => Client.Connect(blockPathSource, blockPathDestination, sourceConnector, destinationConnector), warn: true))) {
var src = this[blockPathSource].Base as NacBlockSeq;
var dst = this[blockPathDestination].Base as NacBlockSeq;
src.ConnectNext(dst.Path, sourceConnector);
dst.ConnectPrev(src.Path, destinationConnector);
NacSecurity.Log(Name, "Connect");
}
}
public void Disconnect(string blockPathSource, string blockPathDestination, string sourceConnector, string destinationConnector) {
if (IsOffline || (ChangeAllowed && Succeeds(() => Client.Disconnect(blockPathSource, blockPathDestination, sourceConnector, destinationConnector), warn: true))) {
var src = this[blockPathSource].Base as NacBlockSeq;
var dst = this[blockPathDestination].Base as NacBlockSeq;
src.DisconnectNext(dst.Path, sourceConnector);
dst.DisconnectPrev(src.Path, destinationConnector);
NacSecurity.Log(Name, "Disconnect");
}
}
public void LoadProject() {
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".nacp";
dlg.Filter = "Nac projects (.nacp)|*.nacp";
if (!IsOffline && !ChangeAllowed) return;
var result = dlg.ShowDialog();
if (result == true) {
string filename = dlg.FileName;
var nacObjects = NacSerializer.Deserialize(File.ReadAllText(filename), typeof(IEnumerable<NacObject>)) as IEnumerable<NacObject>;
var newProjectPath = Guid.NewGuid().ToString();
foreach (var nacObject in nacObjects) {
nacObject.Path = NacPath.Replace(nacObject.Path, Path, newProjectPath);
if (nacObject is NacProject) {
var project = nacObject as NacProject;
project.Database.Path = NacPath.Replace(project.Database.Path, Path, newProjectPath);
}
else
if (nacObject is NacBlockSeq) {
var blockSeq = nacObject as NacBlockSeq;
var nexts = blockSeq.Next.ToArray(); blockSeq.Next.Clear();
foreach (var next in nexts) blockSeq.Next.Add(NacPath.Replace(next, Path, newProjectPath));
var prevs = blockSeq.Prev.ToArray(); blockSeq.Prev.Clear();
foreach (var prev in prevs) blockSeq.Prev.Add(NacPath.Replace(prev, Path, newProjectPath));
if (nacObject is NacBlockIf) {
var blockIf = nacObject as NacBlockIf;
var nextTrue = blockIf.NextTrue.ToArray(); blockIf.NextTrue.Clear();
foreach (var next in nextTrue) blockIf.NextTrue.Add(NacPath.Replace(next, Path, newProjectPath));
}
}
}
Add(nacObjects);
}
}
#region Catalog
private static NacWpfObject Create(NacObject obj) {
NacWpfObject ret = null;
if (obj is NacBlockCall) ret = new NacWpfBlockCall(obj as NacBlockCall);
else if (obj is NacBlockFuzzy) ret = new NacWpfBlockFuzzy(obj as NacBlockFuzzy);
else if (obj is NacBlockIf) ret = new NacWpfBlockIf(obj as NacBlockIf);
else if (obj is NacBlockTimer) ret = new NacWpfBlockTimer(obj as NacBlockTimer);
else if (obj is NacBlockSeq) ret = new NacWpfBlockSeq(obj as NacBlockSeq);
else if (obj is NacBlock) ret = new NacWpfBlock(obj as NacBlock);
else if (obj is NacSection) ret = new NacWpfSection(obj as NacSection);
else if (obj is NacTask) ret = new NacWpfTask(obj as NacTask);
else if (obj is NacTag) ret = new NacWpfTag(obj as NacTag);
else if (obj is NacProject) ret = new NacWpfProject(obj as NacProject);
return ret;
}
//private Dictionary<string, NacWpfObject> Catalog { get; set; }
private NacCatalog<NacWpfObject> Catalog { get; set; }
public NacWpfObject this[string path] {
get {
var nacPath = NacPath.Parse(path);
if (nacPath.IsRoot) return this;
else if (nacPath.IsDatabase) {
NacWpfObject project;
Catalog.TryGetValue(nacPath.ProjectPath, out project);
return (project as NacWpfProject)?.Database;
}
NacWpfObject ret;
return Catalog.TryGetValue(path, out ret) ? ret : null;
//return Catalog[path];
}
}
public void Move(NacWpfObject wpfObject, bool down = false) {
int i, j;
if (FindSiblingOf(wpfObject, out i, out j, down)) {
Swap(i, j);
GetParentOf(wpfObject)?.OnNotifyChildrenCollectionChanged(NotifyCollectionChangedAction.Move, new[] { wpfObject });
}
}
private bool FindSiblingOf(NacWpfObject wpfObject, out int i, out int j, bool forward = false) {
i = Catalog.IndexOf(wpfObject);
var parent = NacPath.GetParentOf(wpfObject.Path);
var type = wpfObject.GetType();
if (forward) {
var n = Catalog.Count;
for (j = i + 1; j < n; j++)
if (Catalog[j].GetType().Equals(type) && NacPath.GetParentOf(Catalog[j].Base) == parent)
return true;
} else {
for (j = i - 1; j >= 0; j--) {
if (Catalog[j].GetType().Equals(type) && NacPath.GetParentOf(Catalog[j].Base) == parent)
return true;
}
}
return false;
}
private void Swap(int ii, int jj) {
int i = ii > jj ? ii : jj;
int j = ii > jj ? jj : ii;
var tmpi = Catalog[i]; var tmpj = Catalog[j];
Catalog.RemoveAt(i); Catalog.RemoveAt(j);
Catalog.Insert(j, tmpi); Catalog.Insert(i, tmpj);
}
public INacWpfChildrenOwner GetParentOf(NacWpfObject wpfObject) {
var path = NacPath.Parse(wpfObject.Path);
return this[path.Parent] as INacWpfChildrenOwner;
//if (path.IsProject) return this;
//if (path.IsTag) {
// var project = Catalog[path.ProjectPath] as NacWpfProject;
// return project?.Database;
//}
}
public void Add(NacWpfObject[] wpfObjects) {
Catalog.Add(wpfObjects);
GetParentOf(wpfObjects[0])?.OnNotifyChildrenCollectionChanged(NotifyCollectionChangedAction.Add, wpfObjects);
}
private void Remove(string path) {
var wpfObject = Catalog[path];
Catalog.Remove(path);
wpfObject.Dispose();
GetParentOf(wpfObject)?.OnNotifyChildrenCollectionChanged(NotifyCollectionChangedAction.Remove, new[] { wpfObject });
}
public IEnumerable<NacWpfObject> ChildrenOf(string path) {
return Catalog.Values.Where(wpfObject => NacPath.GetParentOf(wpfObject.Path) == path);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PROnline.Models.Trainings;
using PROnline.Models;
namespace PROnline.Controllers.Trainings
{
public class TrainingVolunteerController : Controller
{
private PROnlineContext db = new PROnlineContext();
//志愿者出席
public ActionResult VolunteerAttend(Guid id)
{
TrainingVolunteer trainingvolunteer = db.TrainingVolunteer.Find(id);
trainingvolunteer.IsAttend = true;
db.Entry(trainingvolunteer).State = EntityState.Modified;
db.SaveChanges();
return Content("已签到");
}
//返回志愿者参与的所有培训
// GET: /TrainingVolunteer/
//参数:Volunteer=>VolunteerID
public List<TrainingVolunteer> Index(Guid volunteerId)
{
return db.TrainingVolunteer.Where(t=>t.VolunteerID==volunteerId).Where(t=>t.Training.State=="正常").Include(t => t.Training).ToList();
}
//
// GET: /TrainingVolunteer/Details/5
public ViewResult Details(Guid id)
{
TrainingVolunteer trainingvolunteer = db.TrainingVolunteer.Find(id);
return View(trainingvolunteer);
}
//
// GET: /TrainingVolunteer/Create
public ActionResult Create()
{
ViewBag.TrainingID = new SelectList(db.Training, "TrainingID", "Title");
return View();
}
//
// POST: /TrainingVolunteer/Create
[HttpPost]
public ActionResult Create(TrainingVolunteer trainingvolunteer)
{
if (ModelState.IsValid)
{
trainingvolunteer.TrainingVolunteerID = Guid.NewGuid();
db.TrainingVolunteer.Add(trainingvolunteer);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TrainingID = new SelectList(db.Training, "TrainingID", "Title", trainingvolunteer.TrainingID);
return View(trainingvolunteer);
}
//
// GET: /TrainingVolunteer/Edit/5
public ActionResult Edit(Guid id)
{
TrainingVolunteer trainingvolunteer = db.TrainingVolunteer.Find(id);
ViewBag.TrainingID = new SelectList(db.Training, "TrainingID", "Title", trainingvolunteer.TrainingID);
return View(trainingvolunteer);
}
//
// POST: /TrainingVolunteer/Edit/5
[HttpPost]
public ActionResult Edit(TrainingVolunteer trainingvolunteer)
{
if (ModelState.IsValid)
{
db.Entry(trainingvolunteer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TrainingID = new SelectList(db.Training, "TrainingID", "Title", trainingvolunteer.TrainingID);
return View(trainingvolunteer);
}
//
// GET: /TrainingVolunteer/Delete/5
public ActionResult Delete(Guid id)
{
TrainingVolunteer trainingvolunteer = db.TrainingVolunteer.Find(id);
return View(trainingvolunteer);
}
//
// POST: /TrainingVolunteer/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(Guid id)
{
TrainingVolunteer trainingvolunteer = db.TrainingVolunteer.Find(id);
db.TrainingVolunteer.Remove(trainingvolunteer);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
} |
//using System;
//using System.Collections.Generic;
//using System.Data;
//using System.Globalization;
//using System.Text;
//namespace ColumnStore
//{
// /*
// An Experimental Columnar DB using c#
// Author: Rajesh Pillai
// */
// class Database
// {
// public Dictionary<string, Table> Tables { get; set; }
// public Database()
// {
// this.Tables = new Dictionary<string, Table>();
// }
// public object Query(dynamic param)
// {
// var result = new Dictionary<int, string>();
// Console.WriteLine(param);
// var table = this.Tables[param.Table];
// var column = table.Columns[param.Field];
// var filterValue = param.Value;
// var select = param.Select;
// var selectColumn = table.Columns[select];
// Console.WriteLine(table.Columns.Keys);
// StringBuilder record = new StringBuilder();
// for (int row = 0; row < selectColumn.Values.Count; row++)
// {
// foreach (var col in table.Columns)
// {
// //Console.WriteLine(col.Value);
// record.Append(col.Value.Values[row] + ",");
// }
// record.AppendLine();
// }
// Console.WriteLine(record.ToString());
// /*
// foreach(var c in table.Columns) {
// Console.WriteLine(c.Key);
// foreach(var val in c.Value.Values) {
// if (val.Value.ToLower() == filterValue.ToLower()) {
// result.Add(val.Key, selectColumn.Values[val.Key]);
// }
// }
// }
// */
// return result;
// }
// }
// class Table
// {
// public Table(string name)
// {
// this.Name = name;
// this.Columns = new Dictionary<string, Column>();
// }
// public Dictionary<string, Column> Columns { get; set; }
// public string Name { get; set; }
// /*
// public string this[int i]
// {
// get {
// return names[i];
// }
// set {
// names[i] = value;
// }
// }
// */
// public DataTable ToDataTable()
// {
// DataTable result = new DataTable();
// if (Columns.Count == 0)
// return result;
// foreach (KeyValuePair<string, Column> col in this.Columns)
// {
// result.Columns.Add(col.Key);
// }
// bool processed = false;
// int i = 0;
// int cols = this.Columns.Count
// ;
// foreach (KeyValuePair<string, Column> col in this.Columns)
// {
// foreach (var value in col.Value.Values)
// {
// DataRow row = null;
// if (!processed)
// {
// row = result.NewRow();
// }
// else
// {
// row = result.Rows[i++];
// }
// row[col.Key] = value.Value;
// if (!processed) result.Rows.Add(row);
// }
// processed = true;
// i = 0;
// }
// return result;
// }
// }
// class Column
// {
// public string Name { get; set; }
// public Dictionary<int, string> Values { get; set; }
// public Column()
// {
// this.Values = new Dictionary<int, string>();
// }
// public Column(string Name) : this()
// {
// this.Name = Name;
// }
// public override string ToString()
// {
// StringBuilder sb = new StringBuilder();
// foreach (var col in this.Values)
// {
// sb.Append(col.Value);
// }
// return string.Format("{0}", sb.ToString());
// }
// }
// class Program
// {
// static Database db = new Database();
// static void Run()
// {
// db = new Database();
// var employees = BuildEmployeeTable();
// var skills = BuildSkillsTable();
// var query = new
// {
// Table = "employees",
// Field = "city",
// Operator = "=",
// Value = "chennai",
// Select = "ename"
// };
// var mumbai = db.Query(query);
// Console.WriteLine(mumbai);
// Console.ReadLine();
// }
// static Table BuildEmployeeTable()
// {
// var table = new Table("employees");
// db.Tables.Add("employees", table);
// table.Columns.Add("ename", new Column("ename"));
// table.Columns.Add("city", new Column("city"));
// table.Columns.Add("empid", new Column("empid"));
// for (int i = 0; i < 10; i++)
// {
// table.Columns["ename"].Values.Add(i, "name " + i.ToString());
// table.Columns["city"].Values.Add(i, (i % 2 == 0 ? "mumbai" : "chennai"));
// table.Columns["empid"].Values.Add(i, i.ToString());
// }
// return table;
// }
// static Table BuildSkillsTable()
// {
// var table = new Table("skills");
// db.Tables.Add("skills", table);
// table.Columns.Add("empid", new Column("empid"));
// table.Columns.Add("skill", new Column("skill"));
// for (int i = 0; i < 10; i++)
// {
// table.Columns["empid"].Values.Add(i, i.ToString());
// table.Columns["skill"].Values.Add(i, (i % 2 == 0 ? "nodejs" : ".net"));
// }
// return table;
// }
// }
//}
|
namespace _1.CookingProgram
{
using System;
using System.Linq;
class Carrot : IVegetable
{
//interface fields
private string kind;
private double size;
private double weight;
private bool isPeeled;
private bool isGoodToEat;
//properties
public bool IsGoodToEat
{
get
{
return this.isGoodToEat;
}
set
{
this.isGoodToEat = value;
}
}
public bool IsPeeled
{
get
{
return this.isPeeled;
}
set
{
this.isPeeled = value;
}
}
public double Weight
{
get
{
return this.weight;
}
set
{
this.weight = value;
}
}
public double Size
{
get
{
return this.size;
}
set
{
this.size = value;
}
}
public string Kind
{
get
{
return this.kind;
}
set
{
this.kind = value;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
[SerializeField] private GameObject enemyPrefab = null;
[SerializeField] private float delay = 3f;
private GameObject enemy;
public float timer = 0f;
void FixedUpdate() {
if (enemy == null) {
timer -= Time.fixedDeltaTime;
if (timer <= 0) Spawn();
}
}
void Spawn() {
enemy = Instantiate(enemyPrefab, transform.position, Quaternion.identity);
timer = delay;
}
}
|
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (UITexture) )]
public class AllyIndicator : MonoBehaviour {
[SerializeField]
private UITexture texture;
[SerializeField]
private Texture box;
[SerializeField]
private Texture arrow;
#region Transform Cache
private Transform thisTransform;
public new Transform transform{
get{
return thisTransform;
}
}
void Awake(){
thisTransform = base.transform;
}
#endregion
public void SetArrow(){
texture.mainTexture = arrow;
}
public void SetBox(){
texture.mainTexture = box;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int uitkomst = Rekensom.minSom(9, 2);
Rekensom som = new Rekensom();
int uitkomst2 = som.plusSom(9, 9);
Console.WriteLine("uitkomst 1 = " + uitkomst);
Console.WriteLine("uitkomst 2 = " + uitkomst2);
Console.WriteLine("first commit");
Console.WriteLine("and now");
Console.WriteLine("test");
Console.WriteLine("asdfasd");
Console.WriteLine("asdfasdfa");
Console.WriteLine( "asdfasd");
Console.WriteLine("laatste");
}
}
}
|
/* Author: Mitchell Spryn (mitchell.spryn@gmail.com)
* There is no warranty with this code. I provide it with the intention of being interesting/helpful, but make no
* guarantees about its correctness or robustness.
* This code is free to use as you please, as long as this header comment is left in all of the files and credit is attributed to me for the original content that I have created.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NNGen
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm()); //The main application
//Application.Run(new Form1()); //Tests
}
}
}
|
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.ML;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.ML.Data;
using PredictFunctionsApp;
[assembly: WebJobsStartup(typeof(Startup))]
namespace PredictFunctionsApp
{
class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services.AddPredictionEnginePool<ModelInput, ModelOutput>()
.FromFile("model/model.zip");
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WziumStars.Data;
using WziumStars.Models.ViewModels;
namespace WziumStars.ViewComponents
{
public class MenuViewComponent : ViewComponent
{
private readonly ApplicationDbContext _db;
public MenuViewComponent(ApplicationDbContext db)
{
_db = db;
}
public async Task<IViewComponentResult> InvokeAsync()
{
PodkategoriaAndKategoriaViewModel podkategoriaAndKategoriaViewModel = new PodkategoriaAndKategoriaViewModel()
{
KategoriaList = await _db.Kategoria.ToListAsync(),
PodkategoriaList = await _db.Podkategoria.ToListAsync()
};
return View(podkategoriaAndKategoriaViewModel);
}
}
}
|
using DChild.Gameplay.Player;
namespace DChild.Gameplay.Environment.Item
{
public class GlidePickup : SkillPickup
{
protected override void ApplySkill(IPlayerSkillEnabler playerSkill)
{
playerSkill.EnableSkill<PlayerGlide>(true);
}
}
} |
using System;
namespace Class02_Problem_of_selection
{
class Program
{
/// <summary>
/// Algorithm about problem of selection.
/// </summary>
/// <param name="a">Array of number</param>
/// <param name="k">The rank of k-number minimum</param>
/// <returns>The k minimum</returns>
public static int ProblemOfSelection(int[] a, int k)
{
int temp;
if (k <= (a.Length / 2))
{
int min = 0;
for (int i = 0; i < k; i++)
{
for(int j = i; j < a.Length; j++)
{
if( a[j] < a[min])
{
min = j;
}
}
//Swap
temp = a[i];
a[i] = a[min];
a[min] = temp;
foreach(int e in a)
{
Console.Write(e + ",");
}
Console.Write("\n");
}
return a[k-1];
}
else
{
int max =a.Length-1;
for(int i = a.Length-1; i >= k; i--)
{
for(int j = 1; j < i; j++)
{
if(a[max] < a[j])
{
max = j;
}
}
//Swap
temp = a[i];
a[i] = a[max];
a[max] = temp;
foreach (int e in a)
{
Console.Write(e + ",");
}
Console.Write("\n");
}
return a[k];
}
}
static void Main(string[] args)
{
int[] f = { 5, 13, 4, 12, 7, 23, 9, 1, 29 };
Console.WriteLine(ProblemOfSelection(f, 1));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Translate : MonoBehaviour
{
[SerializeField]
float push = -0.0001f;
[SerializeField]
float maxDist = 5;
public bool movesHorizontally = false;
float startX;
float startY;
void Start() {
startX = transform.position.x;
startY = transform.position.y;
}
// Update is called once per frame
void Update()
{
if (movesHorizontally)
StartCoroutine(HorizontalTranslate());
else
StartCoroutine(VerticalTranslate());
}
IEnumerator HorizontalTranslate() {
Vector3 pos = transform.position;
if (pos.x >= startX + maxDist || pos.x <= startX - maxDist)
push = -push;
pos.x += push;
transform.position = pos;
yield return new WaitForSeconds(5f);
}
IEnumerator VerticalTranslate() {
Vector3 pos = transform.position;
if (pos.y >= startY + maxDist || pos.y <= startY - maxDist)
push = -push;
pos.y += push;
transform.position = pos;
yield return new WaitForSeconds(5f);
}
}
|
// ===============================
// AUTHOR : Guillaume Vachon Bureau
// CREATE DATE : 2018-08-29
//==================================
using System.Collections.Generic;
namespace BehaviourTree
{
/// <summary>
/// Like sequencetask, but randomise the task order
/// </summary>
public class RandomSequenceTask : SequencesTask
{
public RandomSequenceTask(List<Task> tasks, BlackBoard blackBoard) : base(tasks, blackBoard)
{
}
protected override bool CheckConditions()
{
return base.CheckConditions();
}
protected override TaskStatus BodyLogic()
{
return base.BodyLogic();
}
protected override void EndLogic()
{
base.EndLogic();
}
public override void ResetTask()
{
base.ResetTask();
}
protected override void StartLogic()
{
IListExtensions.Shuffle(_tasks);
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
} |
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CYJ.Base.Service.Http.Filters
{
public class BaseExceptionFilterAttribute : ExceptionFilterAttribute, IExceptionFilter
{
public override void OnException(ExceptionContext context)
{
ProcessException(context);
}
public override Task OnExceptionAsync(ExceptionContext context)
{
return ProcessException(context);
}
private Task ProcessException(ExceptionContext context)
{
//context.ExceptionHandled = true;
////日志基本信息
//var urlPath = context.HttpContext.Request.Path;
//var method = context.HttpContext.Request.Method;
//var body = HttpContextHelper.GetJsonRequestBody(context.HttpContext);
//var parmas = context.HttpContext.Request.Query.Select(m => m.Key + "=" + m.Value).ToList();
//var query = string.Join(",", parmas);
////日志StringBuilder
//var sb = new StringBuilder();
//sb.AppendLine($"Url请求地址:{urlPath}");
//sb.AppendLine($"请求方式:{method}");
//sb.AppendLine($"请求的Query:{query}");
//sb.AppendLine($"请求Json入参:{body}");
////返回模型构建
//var model = new ApiResult(ApiResultCode.Failed);
//if (context.Exception is BaseApiException baseEx)
//{
// model.Msg = baseEx.Message;
// model.Code = baseEx.ExceptionCode;
//}
//else
//{
// model.Msg = _isDev ? context.Exception.Message : "服务器异常请联系管理员";
//}
//var returnMsg = model.ToJson();
//sb.AppendLine($"返回结果:{returnMsg}");
//AquariumLogManager.GetInstance().Error(sb.ToString(), context.Exception, tags: "异常拦截器日志");
//// var result = new JsonResult(model, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }) { StatusCode = 200 };
//var result = new ContentResult { Content = returnMsg, StatusCode = 200, ContentType = "application/json" };
//context.Result = result;
return Task.CompletedTask;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
[RequireComponent(typeof(Button))]
public class PlayUI : MonoBehaviour
{
public Button playBtn;
public TMP_InputField seedInput;
public string SceneToLoad;
// Start is called before the first frame update
void Awake()
{
playBtn = GetComponent<Button>();
playBtn.onClick.AddListener(() =>
{
if (seedInput.text.Length > 0)
{
int.TryParse(seedInput.text, out int seed);
Random.InitState(seed);
}
LevelManager.instance.LoadScene(SceneToLoad);
});
}
}
|
using CarsIsland.MailSender.Infrastructure.Configuration.Interfaces;
using CarsIsland.MailSender.Infrastructure.Services.Mail;
using CarsIsland.MailSender.Infrastructure.Services.Mail.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using SendGrid.Extensions.DependencyInjection;
namespace CarsIsland.MailSender.FuncApp.Core.DependencyInjection
{
internal static class MailDeliveryServiceCollectionExtensions
{
public static IServiceCollection AddMailDeliveryServices(this IServiceCollection services)
{
services.AddSendGrid((sp, options) =>
{
var mailDeliveryServiceConfiguration = sp.GetRequiredService<IMailDeliveryServiceConfiguration>();
options.ApiKey = mailDeliveryServiceConfiguration.ApiKey;
});
services.AddScoped<IMailDeliveryService, MailDeliveryService>();
return services;
}
}
}
|
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.OverlappingTrainingDateRequest;
using SFA.DAS.ProviderCommitments.Web.Models.OveralppingTrainingDate;
using System.Threading.Tasks;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class DraftApprenticeshipOverlapOptionViewModelToCreateOverlappingTrainingDateRequestMapper : IMapper<DraftApprenticeshipOverlapOptionViewModel, CreateOverlappingTrainingDateApimRequest>
{
public Task<CreateOverlappingTrainingDateApimRequest> Map(DraftApprenticeshipOverlapOptionViewModel source)
{
return Task.FromResult(new CreateOverlappingTrainingDateApimRequest
{
DraftApprenticeshipId = source.DraftApprenticeshipId.Value,
ProviderId = source.ProviderId
});
}
}
}
|
using System;
using TraceWizard.Entities;
using TraceWizard.Classification;
using TraceWizard.Entities.Adapters.Arff;
using TraceWizard.Environment;
namespace TraceWizard.Classification.Classifiers.NearestNeighbor {
public abstract class NearestNeighborClassifier : Classifier {
public NearestNeighborClassifier() { }
public Analysis Exemplars {get;set;}
public string ExemplarsDataSource { get; set; }
protected double? volumePercent { get; set; }
protected double? peakPercent { get; set; }
protected double? durationPercent { get; set; }
protected double? modePercent { get; set; }
public override FixtureClass Classify(Event @event) {
LazyInitialize();
if (Exemplars == null || Exemplars.Events == null)
return FixtureClasses.Unclassified;
FixtureClass fixtureClass;
double? minVolume = @event.Decrease(@event.Volume, volumePercent);
double? maxVolume = @event.Increase(@event.Volume, volumePercent);
double? minPeak = @event.Decrease(@event.Peak, peakPercent);
double? maxPeak = @event.Increase(@event.Peak, peakPercent);
TimeSpan? minDuration = @event.DecreaseDuration(@event.Duration, durationPercent);
TimeSpan? maxDuration = @event.IncreaseDuration(@event.Duration, durationPercent);
double? minMode = @event.Decrease(@event.Mode, modePercent);
double? maxMode = @event.Increase(@event.Mode, modePercent);
var fixtureSummaries = new FixtureSummaries(Exemplars.Events);
foreach (Event exemplar in Exemplars.Events) {
if (exemplar.IsSimilar(@event.FixtureClass, minVolume, maxVolume, minPeak, maxPeak, minDuration, maxDuration, minMode, maxMode))
fixtureSummaries[exemplar.FixtureClass].Count++;
}
fixtureClass = fixtureSummaries.MaximumFixtureClass();
return fixtureClass;
}
void LazyInitialize() {
if (string.IsNullOrEmpty(ExemplarsDataSource))
ExemplarsDataSource = TwEnvironment.TwExemplars;
if (Exemplars == null && System.IO.File.Exists(ExemplarsDataSource)) {
Exemplars = (new ArffAnalysisAdapter()).Load(ExemplarsDataSource);
}
}
}
public class NearestNeighborv15p18d25m18Classifier : NearestNeighborClassifier {
public NearestNeighborv15p18d25m18Classifier()
: base() {
volumePercent = 0.15;
peakPercent = 0.18;
durationPercent = 0.25;
modePercent = 0.18;
}
public override string Name { get { return "Nearest Neighbor Classifier"; } }
public override string Description { get { return "Classifies using Nearest Neighbor algorithm (exemplars.twdb file must be installed)"; } }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Empresa.DesignPatterns.Vendas;
namespace Empresa.DesignPatterns.Impostos
{
public class IHIT : TemplateImposto
{
public IHIT(Imposto outroImposto) : base(outroImposto) { }
public IHIT() : base() { }
protected override bool DeveUsarTaxaMaxima(Orcamento orcamento)
{
IList<string> noOrcamento = new List<string>();
foreach (var item in orcamento.Itens)
{
if (noOrcamento.Contains(item.Nome))
{
return true;
}
noOrcamento.Add(item.Nome);
}
return false;
}
protected override double TaxacaoMaxima(Orcamento orcamento)
{
return orcamento.Valor * 0.13 + 100;
}
protected override double TaxacaoMinima(Orcamento orcamento)
{
return (orcamento.Itens.Count * 0.01) * orcamento.Valor;
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using ServiceDesk.Ticketing.Domain.TaskAggregate;
namespace ServiceDesk.Ticketing.DataAccess.Mappings
{
public class TaskStateMap : EntityTypeConfiguration<TaskState>
{
public TaskStateMap()
{
ToTable("Tasks");
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace BenefitDeduction.Employees.FamilyMembers
{
public interface IEmployeeSpouse: IFamilyMember
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Activity.Models;
using Uintra.Core.Controls.LightboxGallery;
using Uintra.Features.Comments.Services;
using Uintra.Features.Likes;
using Uintra.Features.Tagging.UserTags.Models;
namespace Uintra.Features.News.Models
{
public class NewsViewModel : IntranetActivityViewModelBase
{
public Guid OwnerId { get; set; }
public string Description { get; set; }
public DateTime? EndPinDate { get; set; }
public DateTime PublishDate { get; set; }
public DateTime? UnpublishDate { get; set; }
public IEnumerable<string> Media { get; set; } = Enumerable.Empty<string>();
public ILikeable LikesInfo { get; set; }
public ICommentable CommentsInfo { get; set; }
public LightboxPreviewModel LightboxPreviewModel { get; set; }
public IEnumerable<UserTag> Tags { get; set; } = Enumerable.Empty<UserTag>();
public IEnumerable<UserTag> AvailableTags { get; set; } = Enumerable.Empty<UserTag>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace URl_Project.Models
{
public class UrlContext : DbContext
{
public DbSet<UrlModel> UrlModels { get; set; }
public UrlContext(DbContextOptions<UrlContext> options):base(options)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using TripLog.Models;
using TripLog.Views;
using Xamarin.Forms;
namespace TripLog.ViewModels
{
public class MainPageViewModel : ViewModelBase
{
private ObservableCollection<TripLogEntry> entries;
public ObservableCollection<TripLogEntry> Entries
{
get
{
return entries;
}
set
{
if(entries != value)
{
entries = value;
NotifyPropertyChanged(nameof(Entries));
}
}
}
private ICommand newCommand;
public ICommand NewCommand
{
get
{
if (newCommand == null)
{
newCommand = new Command(NewProcedure);
}
return newCommand;
}
}
private TripLogEntry detailSelectItem;
public TripLogEntry DetailSelectedItem
{
get
{
return detailSelectItem;
}
set
{
if(detailSelectItem != value)
{
detailSelectItem = value;
DetailProcedure(detailSelectItem);
detailSelectItem = null;
}
}
}
private readonly ITripLogFactory factory;
public MainPageViewModel(ITripLogFactory factory)
{
this.factory = factory;
}
private void NewProcedure()
{
this.factory.NavigateToNewPage();
}
public void DetailProcedure(TripLogEntry entry)
{
this.factory.NavigateToDetailPage(entry);
}
public void Init()
{
// Pull list from the backend....
// Then remove the hard-coded list....
var hardCodedList = GetHardCodedList();
Entries = new ObservableCollection<TripLogEntry>(hardCodedList);
}
private IList<TripLogEntry> GetHardCodedList()
{
var items = new List<TripLogEntry>
{
new TripLogEntry
{
Title = "Washington Monument",
Notes = "Amazing!",
Rating = 3,
Date = new DateTime(2017, 2, 5),
Latitude = 38.8895,
Longitude = -77.0352
},
new TripLogEntry
{
Title = "Statue of Liberty",
Notes = "Inspiring!",
Rating = 4,
Date = new DateTime(2017, 4, 13),
Latitude = 40.6892,
Longitude = -74.0444
},
new TripLogEntry
{
Title = "Golden Gate Bridge",
Notes = "Foggy, but beautiful.",
Rating = 5,
Date = new DateTime(2017, 4, 26),
Latitude = 37.8268,
Longitude = -122.4798
}
};
return items;
}
}
}
|
using System;
using System.Globalization;
using System.Text;
using JetBrains.Annotations;
namespace iSukces.Code
{
public static class StringExtensions
{
public static string Capitalize(this string x) => x.Substring(0, 1).ToUpper() + x.Substring(1);
/// <summary>
/// Koduje string do postaci stałej C#
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static string CsEncode(this string x)
{
const string quote = "\"";
const string backslash = "\\";
if (x is null)
return "null";
var sb = new StringBuilder();
sb.Append(quote);
foreach (var i in x)
{
var c = i.CsEncode();
sb.Append(c);
}
sb.Append(quote);
return sb.ToString();
}
public static string CsEncode(this char i)
{
const string backslash = "\\";
const string quote = "\"";
switch (i)
{
case '\\':
return backslash + backslash;
case '\r':
return backslash + "r";
case '\n':
return backslash + "n";
case '\t':
return backslash + "t";
case '\"':
return backslash + quote;
case '„':
case '“':
case '≥':
case '≤':
case '≈':
return i.ToString();
default:
if (i < '\u2000')
{
return i.ToString();
}
else
{
var ord = ((int)i).ToString("x4", CultureInfo.InvariantCulture);
return "\\u" + ord;
}
}
}
/// <summary>
/// Koduje string do postaci stałej C#
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static string CsVerbatimEncode(this string x)
{
if (x is null)
return "null";
const string quote = "\"";
const string backslash = "\\";
var sb = new StringBuilder();
sb.Append("@");
sb.Append(quote);
foreach (var c in x)
if (c == '\"')
sb.Append(quote + quote);
else
sb.Append(c);
sb.Append(quote);
return sb.ToString();
}
public static string Decamelize(this string name)
{
if (name is null)
return null;
var s = new StringBuilder();
foreach (var i in name.Trim())
if (s.Length == 0)
{
s.Append(i);
}
else if (char.ToUpper(i) == i)
{
s.Append(" ");
s.Append(char.ToLower(i));
}
else
{
s.Append(i);
}
return s.ToString();
}
public static string FirstLower([NotNull] this string name) // !!!!!!
{
if (name == null) throw new ArgumentNullException(nameof(name));
return name.Substring(0, 1).ToLower() + name.Substring(1);
}
public static string FirstUpper(this string name) => name.Substring(0, 1).ToUpper() + name.Substring(1);
public static string GetUntilSeparator(this string x, string separator, out string rest)
{
var idx = x.IndexOf(separator);
if (idx < 0)
{
rest = string.Empty;
return x;
}
rest = x.Substring(idx + separator.Length);
return x.Substring(0, idx);
}
public static string UnCapitalize(this string x) => x.Substring(0, 1).ToLower() + x.Substring(1);
/// <summary>
/// Adds escape to { and }
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
public static string XamlEncode(this string x)
{
var sb = new StringBuilder(Math.Max(x.Length, 64));
foreach (var i in x)
if (i == '{')
sb.Append("{}{");
else
sb.Append(i);
return sb.ToString();
}
}
}
// Console.Write(""); |
using System.Collections.Generic;
namespace CollectionsUtility
{
public interface IReadOnlyUniqueList<T>
: IReadOnlyList<T>
{
int IndexOf(T item);
T ItemAt(int index);
}
}
|
using System;
using System.Drawing;
using System.Media;
using System.Windows.Forms;
using AxisPosCore;
namespace AxiPos
{
public partial class FormLogOn : Form, ILogOnView
{
public delegate void dlgSetText(string text);
public FormLogOn(bool showTouchInput)
{
InitializeComponent();
InitView();
touchInputControl1.Visible = showTouchInput;
if (showTouchInput)
Height = 348;
else
Height = 129;
}
public bool ShowNumPad { get; set; }
public event EventHandler OnConfirm;
public event EventHandler OnCancel;
public void RefreshView()
{
throw new NotImplementedException();
}
public void InitView()
{
btnOk.Click += btnOk_Click;
}
public void SetInput(string value)
{
throw new NotImplementedException();
}
public void SetFocus()
{
throw new NotImplementedException();
}
public event ParamEventArgsDelegate OnPasswordEnter;
private void btnOk_Click(object sender, EventArgs e)
{
if (OnPasswordEnter != null)
OnPasswordEnter(mtbPassword.Text);
}
public string GetInput()
{
throw new NotImplementedException();
}
private void mtbPassword_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
if (OnPasswordEnter != null)
{
if (OnPasswordEnter(mtbPassword.Text))
{
DialogResult = DialogResult.OK;
Close();
}
else
{
mtbPassword.SelectAll();
SystemSounds.Beep.Play();
}
}
}
if (e.KeyData == Keys.Escape)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
private void mtbPassword_Validated(object sender, EventArgs e)
{
}
public void model_BarcodeReceived(string barcode)
{
if (mtbPassword.InvokeRequired)
mtbPassword.Invoke(new dlgSetText(SetTextMethod), new object[] {barcode});
else
mtbPassword.Text = barcode;
}
public void SetTextMethod(string text)
{
mtbPassword.Text = text;
}
private void touchInputControl1_OnEnterInput(object sender, EventArgs e)
{
btnOk.PerformClick();
}
private void touchInputControl1_OnTextChanged(object sender, EventArgs e)
{
mtbPassword.Text = touchInputControl1.EditText;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Rectangle rect = panel1.ClientRectangle;
rect.X = 2;
rect.Y = 2;
rect.Width = rect.Width - 5;
rect.Height = Height - 5;
e.Graphics.DrawRectangle(Pens.White, rect);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
using SFA.DAS.ProviderRelationships.Api.Client;
using SFA.DAS.ProviderRelationships.Types.Dtos;
using SFA.DAS.ProviderRelationships.Types.Models;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice
{
[TestFixture]
public class SelectEmployerViewModelMapperTests
{
[Test]
public async Task ThenCallsProviderRelationshipsApiClient()
{
var fixture = new SelectEmployerViewModelMapperFixture();
await fixture.Act();
fixture.Verify_ProviderRelationshipsApiClientWasCalled_Once();
}
[Test]
public async Task ThenCallsCommitmentsApiClient()
{
var fixture = new SelectEmployerViewModelMapperFixture();
await fixture.Act();
fixture.Verify_CommitmentApiClientWasCalled_Once();
}
[Test]
public async Task ThenCorrectlyMapsApiResponseToViewModel()
{
var fixture = new SelectEmployerViewModelMapperFixture();
var result = await fixture.Act();
fixture.Assert_SelectEmployerViewModelCorrectlyMapped(result);
}
[Test]
public async Task ThenDontReturnTheExistingEmployer()
{
var fixture = new SelectEmployerViewModelMapperFixture();
var result = await fixture.Act();
fixture.Assert_SelectEmployerViewModelCorrectlyMapped(result);
}
[Test]
public async Task ThenCorrectlyMapsEmptyApiResponseToViewModel()
{
var fixture = new SelectEmployerViewModelMapperFixture().WithNoMatchingEmployers();
var result = await fixture.Act();
fixture.Assert_ListOfEmployersIsEmpty(result);
}
}
public class SelectEmployerViewModelMapperFixture
{
private readonly SelectEmployerViewModelMapper _sut;
private readonly Mock<IProviderRelationshipsApiClient> _providerRelationshipsApiClientMock;
private readonly Mock<ICommitmentsApiClient> _commitmentApiClientMock;
private readonly SelectEmployerRequest _request;
private readonly long _providerId;
private readonly long _accountLegalEntityId;
private readonly long _apprenticeshipId;
private readonly GetAccountProviderLegalEntitiesWithPermissionResponse _apiResponse;
public GetApprenticeshipResponse GetApprenticeshipApiResponse { get; }
public SelectEmployerViewModelMapperFixture()
{
_providerId = 123;
_accountLegalEntityId = 457;
_apprenticeshipId = 1;
_request = new SelectEmployerRequest { ProviderId = _providerId, ApprenticeshipId = _apprenticeshipId };
_apiResponse = new GetAccountProviderLegalEntitiesWithPermissionResponse
{
AccountProviderLegalEntities = new List<AccountProviderLegalEntityDto>
{
new AccountProviderLegalEntityDto
{
AccountId = 123,
AccountLegalEntityPublicHashedId = "DSFF23",
AccountLegalEntityName = "TestAccountLegalEntityName",
AccountPublicHashedId = "DFKFK66",
AccountName = "TestAccountName",
AccountLegalEntityId = 456,
AccountProviderId = 234
},
new AccountProviderLegalEntityDto
{
AccountId = 124,
AccountLegalEntityPublicHashedId = "DSFF24",
AccountLegalEntityName = "TestAccountLegalEntityName2",
AccountPublicHashedId = "DFKFK67",
AccountName = "TestAccountNam2",
AccountLegalEntityId = _accountLegalEntityId,
AccountProviderId = 235
}
}
};
GetApprenticeshipApiResponse = new CommitmentsV2.Api.Types.Responses.GetApprenticeshipResponse
{
AccountLegalEntityId = _accountLegalEntityId,
EmployerName = "TestName"
};
_providerRelationshipsApiClientMock = new Mock<IProviderRelationshipsApiClient>();
_providerRelationshipsApiClientMock
.Setup(x => x.GetAccountProviderLegalEntitiesWithPermission(
It.IsAny<GetAccountProviderLegalEntitiesWithPermissionRequest>(),
CancellationToken.None))
.ReturnsAsync(_apiResponse);
_commitmentApiClientMock = new Mock<ICommitmentsApiClient>();
_commitmentApiClientMock.Setup(x => x.GetApprenticeship(_apprenticeshipId, It.IsAny<CancellationToken>()))
.ReturnsAsync(GetApprenticeshipApiResponse);
_sut = new SelectEmployerViewModelMapper(_providerRelationshipsApiClientMock.Object, _commitmentApiClientMock.Object);
}
public async Task<SelectEmployerViewModel> Act() => await _sut.Map(_request);
public SelectEmployerViewModelMapperFixture WithNoMatchingEmployers()
{
_providerRelationshipsApiClientMock
.Setup(x => x.GetAccountProviderLegalEntitiesWithPermission(
It.IsAny<GetAccountProviderLegalEntitiesWithPermissionRequest>(),
CancellationToken.None))
.ReturnsAsync(new GetAccountProviderLegalEntitiesWithPermissionResponse());
return this;
}
public void Verify_ProviderRelationshipsApiClientWasCalled_Once()
{
_providerRelationshipsApiClientMock.Verify(x => x.GetAccountProviderLegalEntitiesWithPermission(
It.Is<GetAccountProviderLegalEntitiesWithPermissionRequest>(y =>
y.Ukprn == _request.ProviderId &&
y.Operation == Operation.CreateCohort), CancellationToken.None), Times.Once);
}
public void Verify_CommitmentApiClientWasCalled_Once()
{
_commitmentApiClientMock.Verify(x => x.GetApprenticeship(_apprenticeshipId, CancellationToken.None), Times.Once);
}
public void Assert_SelectEmployerViewModelCorrectlyMapped(Web.Models.Apprentice.SelectEmployerViewModel result)
{
var filteredLegalEntities = _apiResponse.AccountProviderLegalEntities.Where(x => x.AccountLegalEntityId != _accountLegalEntityId);
Assert.AreEqual(GetApprenticeshipApiResponse.EmployerName, result.LegalEntityName);
Assert.AreEqual(filteredLegalEntities.Count(), result.AccountProviderLegalEntities.Count());
foreach (var entity in filteredLegalEntities)
{
Assert.True(result.AccountProviderLegalEntities.Any(x =>
x.EmployerAccountLegalEntityName == entity.AccountLegalEntityName &&
x.EmployerAccountLegalEntityPublicHashedId == entity.AccountLegalEntityPublicHashedId &&
x.EmployerAccountName == entity.AccountName &&
x.EmployerAccountPublicHashedId == entity.AccountPublicHashedId));
}
}
public void Assert_ListOfEmployersIsEmpty(SelectEmployerViewModel result)
{
Assert.AreEqual(0, result.AccountProviderLegalEntities.Count());
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TC
{
public partial class Form1 : Form
{
TC tc = new TC();
public Form1()
{
InitializeComponent();
}
private void btn_afiliado_Click(object sender, EventArgs e)
{
afiliado afiliado = new afiliado();
List<string> telefono = new List<string>();telefono.Add( "222-22222");telefono.Add("213-123123");
List<string> celular = new List<string>();celular.Add( "99-9999");celular.Add( "9913-1223" );
afiliado.primerNombre = "dany"; afiliado.primerApellido = "acosta"; afiliado.segundoNombre = "eduardo"; afiliado.segundoApellido = "carbajal";
afiliado.identidad = "0801-0900-1231"; afiliado.genero = "masc"; afiliado.estadoCivil = "casado"; afiliado.direccion = "ksa"; afiliado.fechaNacimiento = "14/12/2001";
afiliado.telefonoPersonal = telefono; afiliado.celular = celular; afiliado.CorreoElectronico = "dany@sca.com"; afiliado.NombreEmpresa = "mi kasa";afiliado.lugarDeNacimiento="ksa";
afiliado.TelefonoEmpresa = "8765-23123"; afiliado.DireccionEmpresa = "esquina"; afiliado.fechaIngresoCooperativa = "02/12/2100"; afiliado.DepartamentoEmpresa = "IT";
afiliado.Ocupacion = "Estudiante"; afiliado.Password = "afiliado";
afiliado.BeneficiarioCont.primerNombre = "dany2"; afiliado.BeneficiarioCont.primerApellido = "acosta2";
afiliado.BeneficiarioCont.segundoNombre = "eduardo2"; afiliado.BeneficiarioCont.segundoApellido = "carbajal2";
afiliado.BeneficiarioCont.identidad = "0801-0920-1231"; afiliado.BeneficiarioCont.genero = "masculino";
afiliado.BeneficiarioCont.estadoCivil = "casado"; afiliado.BeneficiarioCont.fechaNacimiento = "14/02/2001";
afiliado.BeneficiarioCont.direccion = "llegando aki"; afiliado.BeneficiarioCont.parentesco = "padre";
BeneficiarioNormal normal = new BeneficiarioNormal();
normal.primerNombre = "dany3"; normal.primerApellido = "acosta3"; normal.parentesco = "primo"; normal.porcentajeAportaciones = 59;
normal.segundoNombre = "eduardo3"; normal.segundoApellido = "carbajal3"; normal.porcentajeSeguros = 60;
normal.identidad = "0801-0920-0931"; normal.genero = "masculino";
normal.estadoCivil = "casado"; normal.fechaNacimiento = "14/05/2001"; normal.direccion = "mi ksa";
BeneficiarioNormal [] normal2= new BeneficiarioNormal[1];
normal2[0] = normal;
afiliado.bensNormales = normal2;
tc.AgregarPeticion(peticion.ingresar_afiliado, afiliado);
}
private void btn_empleado_Click(object sender, EventArgs e)
{
Empleado empleado = new Empleado();
string[] telefono = { "222-22222", "213-123123" };
string[] celular = { "99-9999", "9913-123123" };
empleado.primerNombre = "dany"; empleado.primerApellido = "acosta"; empleado.segundoNombre = "eduardo"; empleado.segundoApellido = "carbajal";
empleado.identidad = "0801-0900-1231"; empleado.genero = "masc"; empleado.estadoCivil = "casado"; empleado.direccion = "ksa"; empleado.fechaNacimiento = "14/12/2001";
//empleado.telefonoPersonal = telefono; empleado.celular = celular;
//empleado.PuestoEmpresaLabora = "Estudiante"; empleado.CorreoElectronico = "dany@sca.com";
tc.AgregarPeticion(peticion.ingresar_empleado, empleado);
}
private void btn_interes_Click(object sender, EventArgs e)
{
Interes inter = new Interes();
inter.Nombre = "ISV"; inter.Tasa = Convert.ToInt64(this.txtb_ingresar.Text); inter.Aplica_obligatoria = false; inter.Aplica_obligatoria_especial = false;
inter.Aplica_voluntaria = false; inter.Aplica_voluntaria_arriba = true; inter.Monto_voluntaria = 20000;
tc.AgregarPeticion(peticion.ingresar_interes, inter);
}
private void btn_ocupacion_Click(object sender, EventArgs e)
{
tc.AgregarPeticion(peticion.ingresar_ocupacion, this.txtb_ingresar.Text);
}
private void btn_motivo_Click(object sender, EventArgs e)
{
tc.AgregarPeticion(peticion.ingresar_motivo, this.txtb_ingresar.Text);
}
private void btn_monto_Click(object sender, EventArgs e)
{
tc.AgregarPeticion(peticion.ingresar_monto_AO, this.txtb_ingresar.Text);
}
private void btn_login_Click(object sender, EventArgs e)
{
string [] valores = new string [2];
valores[0] = "adds.cosecol@gmail.com"; valores[1] = "kouta07";
tc.AgregarPeticion(peticion.login, valores);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CsvHelper;
using OrderLibrary.Models;
namespace OrderLibrary
{
public class OrdersProvider : IOrdersFromCsvProvider
{
public IEnumerable<Order> GetOrdersFromCsv(IReader reader)
{
return reader.GetRecords<Order>();
}
public IAsyncEnumerable<Order> GetOrdersFromCsvAsync(IReader reader)
{
return reader.GetRecordsAsync<Order>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Snow
{
//Creates a ToolStripMenuItem to include all the history of visited links
public class HistoryToolStrip : ToolStripMenuItem
{
private Form1 form;
//Constructor
//Accessing the url parameter from the base class
public HistoryToolStrip(string url, Form1 fm): base(url)
{
this.form = fm;
//Create a new event on mouse click
Click += new System.EventHandler(History_Click);
}
public void History_Click(object sender, EventArgs e)
{
//On click visit the selected link
TabsHandler tab = (TabsHandler)form.tabControl2.TabPages[form.tabControl2.SelectedIndex];
tab.GoToPage(Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Snake_Moves
{
class Program
{
static void Main(string[] args)
{
var rowsAndCols = Console.ReadLine().Split().Select(int.Parse).ToArray();
var rows = rowsAndCols[0];
var cols = rowsAndCols[1];
var matrix = new char[rows,cols];
var snake = Console.ReadLine();
var snakeCopy = new Queue<char>(snake);
for (int row = 0; row < rows; row++)
{
if (row % 2 == 0)
{
for (int col = 0; col < cols; col++)
{
if (snakeCopy.Count == 0)
{
snakeCopy = new Queue<char>(snake);
matrix[row, col] = snakeCopy.Dequeue();
}
else
{
matrix[row, col] = snakeCopy.Dequeue();
}
}
}
else
{
for (int col = cols - 1; col >= 0 ; col--)
{
if (snakeCopy.Count == 0)
{
snakeCopy = new Queue<char>(snake);
matrix[row, col] = snakeCopy.Dequeue();
}
else
{
matrix[row, col] = snakeCopy.Dequeue();
}
}
}
}
PrintMatrix(matrix);
}
private static void PrintMatrix(char[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j]);
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OverloadingOperators
{
class EighthEx
{
private int[] Arr;
public EighthEx(int[] arr)
{
Arr = arr;
}
public static explicit operator string (EighthEx obj)
{
string txt = "";
for(int i =0; i < obj.Arr.Length; i++)
{
txt += obj.Arr[i];
}
txt += " - this is text";
return txt;
}
public static explicit operator int (EighthEx obj)
{
int sum = 0;
for(int i =0; i<obj.Arr.Length; i++)
{
sum += obj.Arr[i];
}
return sum;
}
public static explicit operator EighthEx (int num)
{
int[] arr = new int[num];
EighthEx T = new EighthEx(arr);
for (int i = 0; i < T.Arr.Length; i++)
{
T.Arr[i] = 0;
}
return T;
}
public static void EighthExs()
{
int[] arr = new int[] { 4, 3, 8, 5 };
EighthEx A = new EighthEx(arr);
string text = (string)A;
Console.WriteLine(text);
int sum = (int)A;
Console.WriteLine(sum);
A = (EighthEx)3;
}
}
}
|
using ChipmunkSharp;
using CocosSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChipmunkExample
{
class shatterLayer : ChipmunkDemoLayer
{
public struct WorleyContex
{
public int seed;
public float cellSize;
public int width, height;
public cpBB bb;
public cpVect focus;
public WorleyContex(int seed, float cellSize, int width, int height, cpBB bb, cpVect focus)
{
// TODO: Complete member initialization
this.seed = seed;
this.cellSize = cellSize;
this.width = width;
this.height = height;
this.bb = bb;
this.focus = focus;
}
}
const float DENSITY = (1f / 10000f);
const int MAX_VERTEXES_PER_VORONOI = 16;
static cpVect HashVect(int x, int y, int seed)
{
// cpfloat border = 0.21f;
float border = 0.05f;
long h = (x * 1640531513 ^ y * 2654435789) + seed;
return new cpVect(
cp.cpflerp(border, 1.0f - border, (h & 0xFFFF) / 0xFFFF),
cp.cpflerp(border, 1.0f - border, ((h >> 16) & 0xFFFF) / 0xFFFF)
);
}
cpVect WorleyPoint(int i, int j, ref WorleyContex context)
{
float size = context.cellSize;
int width = context.width;
int height = context.height;
cpBB bb = context.bb;
// cpVect fv = cpv(0.5, 0.5);
cpVect fv = HashVect(i, j, context.seed);
return new cpVect(
cp.cpflerp(bb.l, bb.r, 0.5f) + size * (i + fv.x - width * 0.5f),
cp.cpflerp(bb.b, bb.t, 0.5f) + size * (j + fv.y - height * 0.5f)
);
}
int ClipCell(cpShape shape, cpVect center, int i, int j, WorleyContex context, cpVect[] verts, cpVect[] clipped, int count)
{
cpVect other = WorleyPoint(i, j, ref context);
// printf(" other %dx%d: (% 5.2f, % 5.2f) ", i, j, other.x, other.y);
cpPointQueryInfo queryInfo = null;
if (shape.PointQuery(other, ref queryInfo) > 0.0f)
{
for (int x = 0; x < count; x++)
clipped[x] = new cpVect(verts[x]);
return count;
}
else
{
// printf("clipped\n");
}
cpVect n = cpVect.cpvsub(other, center);
float dist = cpVect.cpvdot(n, cpVect.cpvlerp(center, other, 0.5f));
int clipped_count = 0;
for (j = 0, i = count - 1; j < count; i = j, j++)
{
cpVect a = verts[i];
float a_dist = cpVect.cpvdot(a, n) - dist;
if (a_dist <= 0.0f)
{
clipped[clipped_count] = a;
clipped_count++;
}
cpVect b = verts[j];
float b_dist = cpVect.cpvdot(b, n) - dist;
if (a_dist * b_dist < 0.0f)
{
float t = cp.cpfabs(a_dist) / (cp.cpfabs(a_dist) + cp.cpfabs(b_dist));
clipped[clipped_count] = cpVect.cpvlerp(a, b, t);
clipped_count++;
}
}
return clipped_count;
}
public void ShatterShape(cpPolyShape shape, float cellSize, cpVect focus)
{
space.RemoveShape(shape);
space.RemoveBody(shape.GetBody());
cpBB bb = shape.bb;
int width = (int)((bb.r - bb.l) / cellSize) + 1;
int height = (int)((bb.t - bb.b) / cellSize) + 1;
// printf("Splitting as %dx%d\n", width, height);
WorleyContex context = new WorleyContex((int)RandomHelper.frand(), cellSize, width, height, bb, focus);
for (int i = 0; i < context.width; i++)
{
for (int j = 0; j < context.height; j++)
{
cpVect cell = WorleyPoint(i, j, ref context);
cpPointQueryInfo cp = null;
if (shape.PointQuery(cell, ref cp) < 0.0f)
{
ShatterCell(shape, cell, i, j, ref context);
}
}
}
//cpBodyFree(cpShapeGetBody(shape));
//cpShapeFree(shape);
}
public override void OnEnter()
{
base.OnEnter();
SetSubTitle("Right click something to shatter it.");
space.SetIterations(30);
space.SetGravity(new cpVect(0, -500));
space.SetSleepTimeThreshold(0.5f);
space.SetCollisionSlop(0.5f);
cpBody body, staticBody = space.GetStaticBody();
cpShape shape;
// Create segments around the edge of the screen.
shape = space.AddShape(new cpSegmentShape(staticBody, new cpVect(-1000, -240), new cpVect(1000, -240), 0.0f));
shape.SetElasticity(1.0f);
shape.SetFriction(1.0f);
shape.SetFilter(NOT_GRABBABLE_FILTER);
float width = 200.0f;
float height = 200.0f;
float mass = width * height * DENSITY;
float moment = cp.MomentForBox(mass, width, height);
body = space.AddBody(new cpBody(mass, moment));
shape = space.AddShape(cpPolyShape.BoxShape(body, width, height, 0.0f));
shape.SetFriction(0.6f);
Schedule();
}
public override void Update(float dt)
{
base.Update(dt);
space.Step(dt);
if (CCMouse.Instance.rightclick || CCMouse.Instance.dblclick)
{
cpPointQueryInfo info = null;
if (space.PointQueryNearest(CCMouse.Instance.Position, 0, GRAB_FILTER, ref info) != null)
{
cpBB bb = info.shape.GetBB();// cpShapeGetBB();
float cell_size = cp.cpfmax(bb.r - bb.l, bb.t - bb.b) / 5.0f;
if (cell_size > 5)
{
ShatterShape(info.shape as cpPolyShape, cell_size, CCMouse.Instance.Position);
}
else
{
//printf("Too small to splinter %f\n", cell_size);
}
}
}
}
public void ShatterCell(cpPolyShape shape, cpVect cell, int cell_i, int cell_j, ref WorleyContex context)
{
// printf("cell %dx%d: (% 5.2f, % 5.2f)\n", cell_i, cell_j, cell.x, cell.y);
cpBody body = shape.body;// cpShapeGetBody(shape);
cpVect[] ping = new cpVect[MAX_VERTEXES_PER_VORONOI]; // cpVect[ (cpVect*)alloca( * sizeof(cpVect));
cpVect[] pong = new cpVect[MAX_VERTEXES_PER_VORONOI]; //(cpVect*)alloca(MAX_VERTEXES_PER_VORONOI * sizeof(cpVect));
int count = shape.Count;// cpPolyShapeGetCount();
count = (count > MAX_VERTEXES_PER_VORONOI ? MAX_VERTEXES_PER_VORONOI : count);
for (int i = 0; i < count; i++)
{
ping[i] = body.LocalToWorld(shape.GetVert(i));
}
cpPointQueryInfo info = null;
for (int i = 0; i < context.width; i++)
{
for (int j = 0; j < context.height; j++)
{
if (
!(i == cell_i && j == cell_j) &&
shape.PointQuery(cell, ref info) < 0
)
{
count = ClipCell(shape, cell, i, j, context, ping, pong, count);
for (int u = 0; u < pong.Length; u++)
if (pong[u] != null)
ping[u] = new cpVect(pong[u]);
}
}
}
cpVect centroid = cp.CentroidForPoly(count, ping);
float mass = cp.AreaForPoly(count, ping, 0) * DENSITY;
float moment = cp.MomentForPoly(mass, count, ping, cpVect.cpvneg(centroid), 0);
cpBody new_body = space.AddBody(new cpBody(mass, moment));
new_body.SetPosition(centroid);
new_body.SetPosition(centroid);
new_body.SetVelocity(body.GetVelocityAtLocalPoint(centroid));
new_body.SetAngularVelocity(body.GetAngularVelocity());
cpTransform transform = cpTransform.Translate(cpVect.cpvneg(centroid));
cpShape new_shape = space.AddShape(new cpPolyShape(new_body, count, ping, transform, 0));
// Copy whatever properties you have set on the original shape that are important
new_shape.SetFriction(shape.GetFriction());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ProjekatZdravoKorporacija.ModelDTO
{
class ExaminationDTO
{
public int Id { get; set; }
public string Doctor { get; set; }
public string Patient { get; set; }
public string Room { get; set; }
public string TypeOfExamination { get; set; }
public string Time { get; set; }
public string Date { get; set; }
public ExaminationDTO(int id, string doctor,string patient,string room,string type,string date,string time)
{
this.Id = id;
this.Doctor = doctor;
this.Patient = patient;
this.Room = room;
this.TypeOfExamination = type;
this.Time = time;
this.Date = date;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Rwd.Framework.Utility
{
public static class Attributes
{
/// <summary>
/// Gets all custom attributes for a property within the given type
/// </summary>
/// <param name="type"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
private static Dictionary<string, object> GetAllCustomAttributes(Type type, string propertyName)
{
return type.GetProperty(propertyName)
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
}
/// <summary>
///
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static Dictionary<string, object> GetACustomAttributesByName(Type type, string propertyName, string attributeName)
{
return type.GetProperty(propertyName)
.GetCustomAttributes(false)
.Where(p => p.GetType().ToString() == attributeName)
.ToDictionary(a => a.GetType().Name, a => a);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OrchardCore.Security.Permissions;
namespace DFC.ServiceTaxonomy.ContentApproval.Permissions
{
public class RequestReviewPermissions : IPermissionProvider
{
public static readonly Permission RequestReviewPermission = new Permission(nameof(RequestReviewPermission), "Request review");
public Task<IEnumerable<Permission>> GetPermissionsAsync() =>
Task.FromResult(new[]
{
RequestReviewPermission,
}
.AsEnumerable());
public IEnumerable<PermissionStereotype> GetDefaultStereotypes() =>
new[]
{
new PermissionStereotype
{
Name = "Administrator",
Permissions = GetPermissionsAsync().Result
},
};
}
}
|
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Mapping.Contractual
{
/// <summary>
/// Implementación del mapeo de la entidad Flujo Aprobacion
/// </summary>
/// <remarks>
/// Creación: GMD 20150511 <br />
/// Modificación: <br />
/// </remarks>
public class FlujoAprobacionMapping : BaseEntityMapping<FlujoAprobacionEntity>
{
public FlujoAprobacionMapping()
:base()
{
HasKey(x => x.CodigoFlujoAprobacion).ToTable("FLUJO_APROBACION", "CTR");
Property(u => u.CodigoFlujoAprobacion).HasColumnName("CODIGO_FLUJO_APROBACION");
Property(u => u.CodigoUnidadOperativa).HasColumnName("CODIGO_UNIDAD_OPERATIVA");
Property(u => u.IndicadorAplicaMontoMinimo).HasColumnName("INDICADOR_APLICA_MONTO_MINIMO");
Property(u => u.CodigoPrimerFirmante).HasColumnName("CODIGO_PRIMER_FIRMANTE");
Property(u => u.CodigoSegundoFirmante).HasColumnName("CODIGO_SEGUNDO_FIRMANTE");
Property(u => u.CodigoPrimerFirmanteOriginal).HasColumnName("CODIGO_PRIMER_FIRMANTE_ORIGINAL");
Property(u => u.CodigoSegundoFirmanteOriginal).HasColumnName("CODIGO_SEGUNDO_FIRMANTE_ORIGINAL");
Property(u => u.EstadoRegistro).HasColumnName("ESTADO_REGISTRO");
Property(u => u.UsuarioCreacion).HasColumnName("USUARIO_CREACION");
Property(u => u.FechaCreacion).HasColumnName("FECHA_CREACION");
Property(u => u.TerminalCreacion).HasColumnName("TERMINAL_CREACION");
Property(u => u.UsuarioModificacion).HasColumnName("USUARIO_MODIFICACION");
Property(u => u.FechaModificacion).HasColumnName("FECHA_MODIFICACION");
Property(u => u.TerminalModificacion).HasColumnName("TERMINAL_MODIFICACION");
Property(u => u.CodigoPrimerFirmanteVinculada).HasColumnName("CODIGO_PRIMER_FIRMANTE_VINCULADA");
Property(u => u.CodigoSegundoFirmanteVinculada).HasColumnName("CODIGO_SEGUNDO_FIRMANTE_VINCULADA");
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TerminalPilot : ShipControl {
protected virtual void Start(){
SortAndTrimWeapons();
}
protected virtual void Update(){
//Back out if our mouse isn't locked
//HACK This might need to be changed later
if ( !Screen.lockCursor ) return;
//HACK Fix later
if (Input.GetButtonDown ("Dock")) {
GetComponent<Terminal>().InitiateDocking();
}
ResolveWeaponSwitch ();
ResolveWeaponFire ();
}
#region Fire Control
//Our list of active weapons
List<TerminalWeapon> activeWeaponList = new List<TerminalWeapon>();
//Our current weapon
int currentWeapon = 0;
//Scrolling mousewheel cooldown counter
bool weaponSwitchCooldown = false;
[SerializeField]
//Weapon Switch cooldown time
float weaponSwitchCooldownTime = 0.3f;
void SortAndTrimWeapons(){
if (activeWeaponList.Count < 1) {
Debug.LogError( "What? This terminal has no usable weapons? Check if this is right." );
}
//TODO Sort the weapons list
activeWeaponList.TrimExcess ();
}
//All active weapons will call this to register themselves
public void RegisterWeapon( TerminalWeapon weapon ){
activeWeaponList.Add (weapon);
}
void ResolveWeaponSwitch(){
//To switch weapons, first check check if we activated the switch, then check if we're in cooldown
if ( Input.GetAxis ( "Mouse ScrollWheel" ) != 0f && !weaponSwitchCooldown ) {
//Do switch
if( Input.GetAxis( "Mouse ScrollWheel" ) > 0f ){
currentWeapon++;
//Overflow check
if( currentWeapon > activeWeaponList.Count - 1){
currentWeapon = 0;
}
} else if( Input.GetAxis( "Mouse ScrollWheel") < 0f ){
currentWeapon--;
//Overflow Check
if( currentWeapon < 0 ){
currentWeapon = activeWeaponList.Count - 1;
}
}
//Activate cooldown
StartCoroutine( Cooldown() );
}
}
IEnumerator Cooldown(){
weaponSwitchCooldown = true;
yield return new WaitForSeconds( weaponSwitchCooldownTime );
weaponSwitchCooldown = false;
}
void ResolveWeaponFire(){
//Fire the current weapon
if( Input.GetButton( "Fire Weapon" ) && !stats.hyperThurst && !weaponSwitchCooldown ){
activeWeaponList[currentWeapon].Fire();
}
}
#endregion
public virtual void OnLaunch( Quaternion facing ){}
}
|
namespace Calculator.Logic.Operations.MyOperations
{
public class Division : DoubleOperation
{
public Division(IOperation operationClass) : base(operationClass)
{
StringToFile = "Division";
Tag = "/";
}
public override void Run()
{
OperationClass.ActualNumber = FirstNumber / OperationClass.ActualNumber;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AppCenter;
using Plugin.Connectivity;
using Welic.App.Helpers.Resources;
using Welic.App.Models.Usuario;
using Welic.App.Services;
using Welic.App.Services.Criptografia;
using Welic.App.ViewModels.Base;
using Xamarin.Forms;
namespace Welic.App.ViewModels
{
public class EditProfileViewModel: BaseViewModel
{
#region Fields and properts
public Command ReturnToMenuCommand => new Command(async () => await ReturnToMenu());
public Command SaveInfosCommand => new Command(async () => await SaveInfos());
private string _nickName;
public string NickName
{
get => _nickName;
set => SetProperty(ref _nickName, value);
}
private string _firstName;
public string FirstName
{
get => _firstName;
set => SetProperty(ref _firstName, value);
}
private string _lastName;
public string LastName
{
get => _lastName;
set => SetProperty(ref _lastName , value);
}
private string _identity;
public string Identity
{
get => _identity;
set => SetProperty(ref _identity , value);
}
private string _phoneNumber;
public string PhoneNumber
{
get => _phoneNumber;
set => SetProperty(ref _phoneNumber , value);
}
private string _email;
public string Email
{
get => _email;
set => SetProperty(ref _email , value);
}
private string _password;
public string Password
{
get { return _password; }
set
{
CharEspecial = false;
CharMaiusculo = false;
CharMinusculo = false;
CharNumberLength = false;
SetProperty(ref _password, value);
if (Password != null || Password.Length < 0)
{
//TODO: Validar as senhas
//if (Regex.IsMatch(Password, (@"[!""#$%&'()*+,-./:;?@[\\\]_`{|}~]")))
if (Regex.IsMatch(Password, (@"[^a-zA-Z0-9]")))
CharEspecial = true;
if (Regex.IsMatch(Password, (@"[A-Z]")))
CharMaiusculo = true;
if (Regex.IsMatch(Password, (@"[a-z]")))
CharMinusculo = true;
if (Regex.IsMatch(Password, (@"[0-9]")) && Password.Length >= 8)
CharNumberLength = true;
}
}
}
private string _confirmPassword;
public string ConfirmPassword
{
get { return _confirmPassword; }
set { _confirmPassword = value; }
}
private bool _CharEspecial;
public bool CharEspecial
{
get => _CharEspecial;
set
{
SetProperty(ref _CharEspecial, value);
}
}
private bool _CharMaiusculo;
public bool CharMaiusculo
{
get => _CharMaiusculo;
set
{
SetProperty(ref _CharMaiusculo, value);
}
}
private bool _CharMinusculo;
public bool CharMinusculo
{
get => _CharMinusculo;
set
{
SetProperty(ref _CharMinusculo, value);
}
}
private bool _CharNumberLength;
public bool CharNumberLength
{
get => _CharNumberLength;
set
{
SetProperty(ref _CharNumberLength, value);
}
}
private UserDto UserDto { get; set; }
private string _image;
public string Image
{
get => _image;
set => SetProperty(ref _image, value);
}
private List<string> _ItemsRoles;
public List<string> ItemsRoles
{
get => _ItemsRoles;
set => SetProperty(ref _ItemsRoles, value);
}
private List<string> _ItemsGender;
public List<string> ItemsGender
{
get => _ItemsGender;
set => SetProperty(ref _ItemsGender, value);
}
private string SelectedGender;
int genderSelectedIndex;
public int GenderSelectedIndex
{
get => genderSelectedIndex;
set
{
if (genderSelectedIndex == value) return;
genderSelectedIndex = value;
// trigger some action to take such as updating other labels or fields
OnPropertyChanged(nameof(GenderSelectedIndex));
SelectedGender = _ItemsGender[genderSelectedIndex];
}
}
private int SelectedRole;
int roleSelectedIndex;
public int RoleSelectedIndex
{
get
{
return roleSelectedIndex;
}
set
{
if (roleSelectedIndex != value)
{
roleSelectedIndex = value;
// trigger some action to take such as updating other labels or fields
OnPropertyChanged(nameof(RoleSelectedIndex));
SelectedRole = roleSelectedIndex;
}
}
}
private DateTime? _DateBirthday;
public DateTime? DateBirthday
{
get => _DateBirthday;
set => SetProperty(ref _DateBirthday, value);
}
#endregion
public EditProfileViewModel()
{
//add itens roles
ItemsRoles = new List<string>();
ItemsRoles.Add(AppResources.Teacher);
ItemsRoles.Add(AppResources.Student);
ItemsRoles.Add($"{AppResources.Student} {AppResources.And} {AppResources.Teacher}");
//Add Itens Gender
_ItemsGender = new List<string>();
_ItemsGender.Add(AppResources.Male);
_ItemsGender.Add(AppResources.Female);
_ItemsGender.Add(AppResources.Undefined);
Image = null;
if (LoadingUser())
{
try
{
_image = UserDto.ImagePerfil?? "https://welic.app/Arquivos/Icons/perfil_Padrao.png";
Email = UserDto.Email;
FirstName = UserDto.FirstName;
LastName = UserDto.LastName;
PhoneNumber = UserDto.PhoneNumber;
Email = UserDto.Email;
Password = UserDto.Password.Substring(0,15);
ConfirmPassword = UserDto.Password.Substring(0,15);
NickName = UserDto.NickName;
DateBirthday = UserDto.DateOfBirth;
SelectedGender = UserDto.Gender ;
SelectedRole = UserDto.Profession;
}
catch (System.Exception e)
{
Console.WriteLine(e);
return;
}
}
}
private bool LoadingUser()
{
UserDto = (new UserDto()).LoadAsync();
return UserDto.Email != null;
}
private async Task ReturnToMenu()
{
await NavigationService.ReturnModalToAsync(true);
}
private async Task SaveInfos()
{
if (IsBusy)
return;
this.IsBusy = true;
if (CrossConnectivity.Current.IsConnected)
{
if (string.IsNullOrEmpty(Password))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Require_Password, "OK");
return;
}
if (!Password.Equals(ConfirmPassword))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Password_not_Match, "OK");
return;
}
if (!Util.IsPasswordStrong(Password))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Password_Weak, "OK");
return;
}
if (string.IsNullOrEmpty(FirstName))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Require_FirstName, "OK");
return;
}
if (string.IsNullOrEmpty(LastName))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Require_LastName, "OK");
return;
}
if (string.IsNullOrEmpty(Email))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Require_Email, "OK");
return;
}
if (string.IsNullOrEmpty(PhoneNumber))
{
await App.Current.MainPage.DisplayAlert(AppResources.Error, AppResources.Requite_phone, "OK");
return;
}
SaveInfosCommand.ChangeCanExecute();
UserDto.NickName = NickName;
UserDto.FullName = $"{FirstName} {LastName}";
UserDto.FirstName = _firstName;
UserDto.LastName = _lastName;
UserDto.DateOfBirth = DateBirthday;
UserDto.Gender = SelectedGender;
UserDto.Profession = SelectedRole;
UserDto.Email = _email;
UserDto.PhoneNumber = PhoneNumber;
UserDto.Password = Password;
await UserDto.RegisterUserManager(UserDto);
await MessageService.ShowOkAsync(AppResources.Success_Change);
await NavigationService.ReturnModalToAsync(true);
}
IsBusy = false;
}
}
}
|
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace RU.Tinkoff.Acquiring.Sdk {
// Metadata.xml XPath class reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']"
[global::Android.Runtime.Register ("ru/tinkoff/acquiring/sdk/Card", DoNotGenerateAcw=true)]
public partial class Card : global::Java.Lang.Object, global::Java.IO.ISerializable {
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("ru/tinkoff/acquiring/sdk/Card", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Card); }
}
protected Card (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/constructor[@name='Card' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public unsafe Card ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero)
return;
try {
if (((object) this).GetType () != typeof (Card)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (((object) this).GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (((global::Java.Lang.Object) this).Handle, class_ref, id_ctor);
} finally {
}
}
static Delegate cb_getCardId;
#pragma warning disable 0169
static Delegate GetGetCardIdHandler ()
{
if (cb_getCardId == null)
cb_getCardId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetCardId);
return cb_getCardId;
}
static IntPtr n_GetCardId (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.CardId);
}
#pragma warning restore 0169
static Delegate cb_setCardId_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSetCardId_Ljava_lang_String_Handler ()
{
if (cb_setCardId_Ljava_lang_String_ == null)
cb_setCardId_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetCardId_Ljava_lang_String_);
return cb_setCardId_Ljava_lang_String_;
}
static void n_SetCardId_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.CardId = p0;
}
#pragma warning restore 0169
static IntPtr id_getCardId;
static IntPtr id_setCardId_Ljava_lang_String_;
public virtual unsafe string CardId {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='getCardId' and count(parameter)=0]"
[Register ("getCardId", "()Ljava/lang/String;", "GetGetCardIdHandler")]
get {
if (id_getCardId == IntPtr.Zero)
id_getCardId = JNIEnv.GetMethodID (class_ref, "getCardId", "()Ljava/lang/String;");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getCardId), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCardId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='setCardId' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("setCardId", "(Ljava/lang/String;)V", "GetSetCardId_Ljava_lang_String_Handler")]
set {
if (id_setCardId_Ljava_lang_String_ == IntPtr.Zero)
id_setCardId_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setCardId", "(Ljava/lang/String;)V");
IntPtr native_value = JNIEnv.NewString (value);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setCardId_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setCardId", "(Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static Delegate cb_getPan;
#pragma warning disable 0169
static Delegate GetGetPanHandler ()
{
if (cb_getPan == null)
cb_getPan = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPan);
return cb_getPan;
}
static IntPtr n_GetPan (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.Pan);
}
#pragma warning restore 0169
static Delegate cb_setPan_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSetPan_Ljava_lang_String_Handler ()
{
if (cb_setPan_Ljava_lang_String_ == null)
cb_setPan_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetPan_Ljava_lang_String_);
return cb_setPan_Ljava_lang_String_;
}
static void n_SetPan_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Pan = p0;
}
#pragma warning restore 0169
static IntPtr id_getPan;
static IntPtr id_setPan_Ljava_lang_String_;
public virtual unsafe string Pan {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='getPan' and count(parameter)=0]"
[Register ("getPan", "()Ljava/lang/String;", "GetGetPanHandler")]
get {
if (id_getPan == IntPtr.Zero)
id_getPan = JNIEnv.GetMethodID (class_ref, "getPan", "()Ljava/lang/String;");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getPan), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getPan", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='setPan' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("setPan", "(Ljava/lang/String;)V", "GetSetPan_Ljava_lang_String_Handler")]
set {
if (id_setPan_Ljava_lang_String_ == IntPtr.Zero)
id_setPan_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setPan", "(Ljava/lang/String;)V");
IntPtr native_value = JNIEnv.NewString (value);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setPan_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setPan", "(Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static Delegate cb_getRebillId;
#pragma warning disable 0169
static Delegate GetGetRebillIdHandler ()
{
if (cb_getRebillId == null)
cb_getRebillId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetRebillId);
return cb_getRebillId;
}
static IntPtr n_GetRebillId (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.RebillId);
}
#pragma warning restore 0169
static Delegate cb_setRebillId_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSetRebillId_Ljava_lang_String_Handler ()
{
if (cb_setRebillId_Ljava_lang_String_ == null)
cb_setRebillId_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetRebillId_Ljava_lang_String_);
return cb_setRebillId_Ljava_lang_String_;
}
static void n_SetRebillId_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.RebillId = p0;
}
#pragma warning restore 0169
static IntPtr id_getRebillId;
static IntPtr id_setRebillId_Ljava_lang_String_;
public virtual unsafe string RebillId {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='getRebillId' and count(parameter)=0]"
[Register ("getRebillId", "()Ljava/lang/String;", "GetGetRebillIdHandler")]
get {
if (id_getRebillId == IntPtr.Zero)
id_getRebillId = JNIEnv.GetMethodID (class_ref, "getRebillId", "()Ljava/lang/String;");
try {
if (((object) this).GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getRebillId), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getRebillId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='setRebillId' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("setRebillId", "(Ljava/lang/String;)V", "GetSetRebillId_Ljava_lang_String_Handler")]
set {
if (id_setRebillId_Ljava_lang_String_ == IntPtr.Zero)
id_setRebillId_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setRebillId", "(Ljava/lang/String;)V");
IntPtr native_value = JNIEnv.NewString (value);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setRebillId_Ljava_lang_String_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setRebillId", "(Ljava/lang/String;)V"), __args);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static Delegate cb_getStatus;
#pragma warning disable 0169
static Delegate GetGetStatusHandler ()
{
if (cb_getStatus == null)
cb_getStatus = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetStatus);
return cb_getStatus;
}
static IntPtr n_GetStatus (IntPtr jnienv, IntPtr native__this)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Status);
}
#pragma warning restore 0169
static Delegate cb_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_;
#pragma warning disable 0169
static Delegate GetSetStatus_Lru_tinkoff_acquiring_sdk_CardStatus_Handler ()
{
if (cb_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_ == null)
cb_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetStatus_Lru_tinkoff_acquiring_sdk_CardStatus_);
return cb_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_;
}
static void n_SetStatus_Lru_tinkoff_acquiring_sdk_CardStatus_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::RU.Tinkoff.Acquiring.Sdk.Card __this = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.Card> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::RU.Tinkoff.Acquiring.Sdk.CardStatus p0 = global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.CardStatus> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Status = p0;
}
#pragma warning restore 0169
static IntPtr id_getStatus;
static IntPtr id_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_;
public virtual unsafe global::RU.Tinkoff.Acquiring.Sdk.CardStatus Status {
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='getStatus' and count(parameter)=0]"
[Register ("getStatus", "()Lru/tinkoff/acquiring/sdk/CardStatus;", "GetGetStatusHandler")]
get {
if (id_getStatus == IntPtr.Zero)
id_getStatus = JNIEnv.GetMethodID (class_ref, "getStatus", "()Lru/tinkoff/acquiring/sdk/CardStatus;");
try {
if (((object) this).GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.CardStatus> (JNIEnv.CallObjectMethod (((global::Java.Lang.Object) this).Handle, id_getStatus), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::RU.Tinkoff.Acquiring.Sdk.CardStatus> (JNIEnv.CallNonvirtualObjectMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getStatus", "()Lru/tinkoff/acquiring/sdk/CardStatus;")), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
// Metadata.xml XPath method reference: path="/api/package[@name='ru.tinkoff.acquiring.sdk']/class[@name='Card']/method[@name='setStatus' and count(parameter)=1 and parameter[1][@type='ru.tinkoff.acquiring.sdk.CardStatus']]"
[Register ("setStatus", "(Lru/tinkoff/acquiring/sdk/CardStatus;)V", "GetSetStatus_Lru_tinkoff_acquiring_sdk_CardStatus_Handler")]
set {
if (id_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_ == IntPtr.Zero)
id_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_ = JNIEnv.GetMethodID (class_ref, "setStatus", "(Lru/tinkoff/acquiring/sdk/CardStatus;)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (value);
if (((object) this).GetType () == ThresholdType)
JNIEnv.CallVoidMethod (((global::Java.Lang.Object) this).Handle, id_setStatus_Lru_tinkoff_acquiring_sdk_CardStatus_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (((global::Java.Lang.Object) this).Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setStatus", "(Lru/tinkoff/acquiring/sdk/CardStatus;)V"), __args);
} finally {
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.Windows.Forms.Design;
namespace Kingdee.CAPP.Common.DataGridViewHelp
{
/// <summary>
/// 类型说明:DataGridViewCellStyle属性框扩展
/// 作 者:jason.tang
/// 完成时间:2013-01-17
/// </summary>
public class CustomerCellStyleEditor : UITypeEditor
{
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
/// <summary>
/// 重写属性编辑值方法
/// </summary>
/// <param name="context"></param>
/// <param name="provider"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (edSvc != null)
{
DataGridViewCellStyleFrm f = new DataGridViewCellStyleFrm();
if (value != null)
{
f.CustomerCellStyle = (List<DataGridViewCustomerCellStyle>)value;
}
edSvc.ShowDialog(f);
value = f.CustomerCellStyle;
}
return value;
}
public override bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context)
{
return false;
}
}
}
|
using C1.Win.C1FlexGrid;
using Clients.AirMaster;
using Common;
using Common.Log;
using Common.Presentation;
using LFP.Printing;
using SessionSettings;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
namespace AirMaster
{
public partial class AMFailedControl : UserControl
{
#region Private Fields
private ClientPresentation mClientPresentation = new ClientPresentation();
private int mId = -1;
private DateTime mLastClickTime = DateTime.MinValue;
private AMFailedForm mParent = null;
private AirMasterProxy mProxy = null;
#endregion
#region Constructors
public AMFailedControl()
{
InitializeComponent();
Logging.ConnectionString = Settings.ConnectionString;
}
#endregion
#region Internal Properties
internal AMFailedForm ControlParent
{
set { mParent = value; }
}
internal int Id
{
get { return mId; }
set { mId = value; }
}
#endregion
#region Internal Methods
internal void CleanUpResources()
{
CloseProxy();
}
#endregion
#region Private Methods
private void AddId(int id, C1FlexGrid grid)
{
int rowIndex = -1;
using (DataTable table = mProxy.GetAMFailInfo(id))
{
foreach (DataRow dr in table.Rows)
{
Row row = grid.Rows.Add();
rowIndex = row.Index;
grid.SetData(row.Index, "ID", id);
grid.SetData(row.Index, "Title", dr["title"].ToString());
string xxx = mProxy.GetRatingText(Convert.ToInt32(dr["xxx"]));
grid.SetData(row.Index, "Rating", xxx);
if (!grid.Styles.Contains("hdYes"))
{
CellStyle cs = grid.Styles.Add("hdYes");
cs.BackColor = ClientPresentation.GridColors[1];
cs.ForeColor = ClientPresentation.GridColors[15];
}
if (!grid.Styles.Contains("hdNo"))
{
CellStyle cs = grid.Styles.Add("hdNo");
cs.BackColor = ClientPresentation.GridColors[15];
cs.ForeColor = ClientPresentation.GridColors[1];
}
if (Convert.ToInt32(dr["hd"]) == 1)
{
grid.SetData(row.Index, "HD", "Y");
grid.SetCellStyle(row.Index, grid.Cols["HD"].Index, "hdYes");
}
else
{
grid.SetData(row.Index, "HD", "N");
grid.SetCellStyle(row.Index, grid.Cols["HD"].Index, "hdNo");
}
grid.Cols["Type"].AllowEditing = true;
string type = dr["type"].ToString();
grid.SetData(row.Index, "Type", type);
grid.Cols["Type"].AllowEditing = false;
string nad = mProxy.GetNAD2(id, type, DateTime.Now);
grid.SetData(row.Index, "NAD", nad);
DateTime date = new DateTime(1900, 1, 1);
DateTime dateB = mProxy.HasRights(id, "17-0,");
DateTime dateV = mProxy.HasRights(id, "16-0,");
DateTime dateI = mProxy.HasRights(id, "18-0,");
if (dateB > date)
date = dateB;
if (dateV > date)
date = dateV;
if (dateI > date)
date = dateI;
grid.SetData(row.Index, "Rights", date);
}
}
Tuple<string, string> am = mProxy.GetStatusLocation(id);
if (am == null)
grid.SetData(rowIndex, "Status", "No D.A.M.");
else
{
grid.SetData(rowIndex, "Location", am.Item2);
grid.SetData(rowIndex, "Status", "N/A");
if (!grid.Styles.Contains("past"))
{
CellStyle cs = grid.Styles.Add("past");
cs.ForeColor = ClientPresentation.GridColors[15];
cs.BackColor = ClientPresentation.GridColors[6];
}
if (!grid.Styles.Contains("pass"))
{
CellStyle cs = grid.Styles.Add("pass");
cs.ForeColor = ClientPresentation.GridColors[15];
cs.BackColor = ClientPresentation.GridColors[2];
}
if (!grid.Styles.Contains("fail"))
{
CellStyle cs = grid.Styles.Add("fail");
cs.ForeColor = ClientPresentation.GridColors[15];
cs.BackColor = ClientPresentation.GridColors[4];
}
switch (am.Item1)
{
case "Pass":
grid.SetData(rowIndex, "Status", "Passed");
grid.SetCellStyle(rowIndex, grid.Cols["Status"].Index, "pass");
//Check QC date.
DateTime? qcDate = mProxy.GetQCContentDateB(id);
if (qcDate.HasValue)
{
if (qcDate.Value < DateTime.Now.Subtract(new TimeSpan(450, 0, 0, 0, 0)))
grid.SetCellStyle(rowIndex, grid.Cols["Status"].Index, "past");
else
{
DateTime? bqcDate = mProxy.GetQCContentDateBQC(id);
if (bqcDate.Value < DateTime.Now.Subtract(new TimeSpan(450, 0, 0, 0, 0)))
grid.SetCellStyle(rowIndex, grid.Cols["Status"].Index, "past");
}
if (grid.GetCellStyle(rowIndex, grid.Cols["Status"].Index).BackColor
.Equals(ClientPresentation.GridColors[2])) //If we are still showing the "Pass" style,
//check the QC history.
{
DateTime? historyDate = mProxy.GetTrackBHistoryDate(id);
if (historyDate.Value < DateTime.Now.Subtract(new TimeSpan(450, 0, 0, 0, 0)))
grid.SetCellStyle(rowIndex, grid.Cols["Status"].Index, "past");
}
}
break;
case "Fail":
case "Under Review":
if (am.Item1.Equals("Fail"))
grid.SetData(rowIndex, "Status", "Failed");
else
grid.SetData(rowIndex, "Status", "Under Review");
grid.SetCellStyle(rowIndex, grid.Cols["Status"].Index, "fail");
break;
default:
grid.SetData(rowIndex, "Status", am.Item1);
break;
}
}
}
private void AMFailedControl_Load(object sender, EventArgs e)
{
if (DesignMode)
return;
LoadControl();
}
private void CloseProxy()
{
if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted)
{
Thread.Sleep(30);
mProxy.Close();
}
mProxy = null;
}
private void Export_Click(object sender, EventArgs e)
{
bool isRelated = ((Button)sender).Name.Contains("Related");
Export(isRelated);
}
private void Export(bool related)
{
Cursor = Cursors.AppStarting;
try
{
bool success = false;
string fileName = "Failed Air Masters";
string message = "The file '{0}' has {1}been created.";
if (related)
{
fileName += "-Related";
success = ImportExport.Export(relatedGrid, "Excel", ref fileName);
}
else
{
fileName += "-Other";
success = ImportExport.Export(otherGrid, "Excel", ref fileName);
}
message = String.Format(message, fileName, (success ? "" : "not "));
Console.Beep();
MessageBox.Show(message, "Save List to File");
}
catch(Exception e)
{
mClientPresentation.ShowError(e.Message +"\n" + e.StackTrace);
Logging.Log(e, "AirMaster", "AMFailedControl.Export");
}
finally
{
Cursor = Cursors.Default;
}
}
private void Grid_DoubleClick(object sender, EventArgs e)
{
SendIdToMain((C1FlexGrid)sender);
}
private void LoadControl()
{
Cursor = Cursors.AppStarting;
relatedGrid.BeginUpdate();
relatedGrid.Redraw = false;
relatedGrid.AutoResize = false;
otherGrid.BeginUpdate();
otherGrid.Redraw = false;
otherGrid.AutoResize = false;
OpenProxy();
try
{
int masterId = 0;
Tuple<int, string, string> tuple = mProxy.GetMovieRatingContractTitleType(mId);
int rating = tuple.Item1;
string type = tuple.Item3;
reminder.Visible = false;
if (type.Equals("Clip") || type.Equals("Wireless Clip"))
reminder.Visible = true;
//Get directly related IDs.
if (type.Contains("Clip"))
{
masterId = mId;
AddId(masterId, relatedGrid);
}
else
{
masterId = mProxy.GetMasterId(mId);
List<Tuple<int, string>> list = mProxy.GetDerivativesByMasterId(masterId, rating);
foreach (Tuple<int, string> item in list)
{
AddId(item.Item1, relatedGrid);
if ((type.Equals("Clip") || type.Equals("Wireless Clip")) && item.Item2.Equals("Movie"))
reminder.LabelText += " (ID: " + item.Item1.ToString() + ")";
}
}
//Get other IDs.
if (type.Contains("Clip"))
{
List<int> ids = mProxy.GetOtherRelatedIds(masterId);
foreach (int id in ids)
{
AddId(id, otherGrid);
}
}
//Set the last click time to the current time minus one second.
mLastClickTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 1));
}
catch (Exception e)
{
mClientPresentation.ShowError(e.Message +"\n" + e.StackTrace);
Logging.Log(e, "AirMaster", "AMFailedForm.LoadControl");
}
finally
{
CloseProxy();
relatedGrid.Redraw = true;
relatedGrid.AutoResize = true;
relatedGrid.EndUpdate();
otherGrid.Redraw = true;
otherGrid.AutoResize = true;
otherGrid.BeginUpdate();
Cursor = Cursors.Default;
}
}
/// <summary>
/// Creates the synchronous proxy.
/// </summary>
private void OpenProxy()
{
if (mProxy == null || mProxy.State == CommunicationState.Closed)
{
mProxy = new AirMasterProxy(Settings.Endpoints["AirMaster"]);
mProxy.Open();
mProxy.CreateAirMasterMethods(Settings.ConnectionString, Settings.UserName);
}
}
private void Print(bool related)
{
Cursor = Cursors.AppStarting;
FlexGridPrintDocument doc = null;
try
{
if (related)
doc = new FlexGridPrintDocument(relatedGrid);
else
doc = new FlexGridPrintDocument(otherGrid);
doc.PrintHeader = true;
doc.PrintFooter = true;
doc.HeaderText = "AM Failed";
doc.FooterText = "Page /p/";
doc.Print();
}
catch (Exception e)
{
mClientPresentation.ShowError(e.Message +"\n" + e.StackTrace);
Logging.Log(e, "AirMaster", "AMFailedControl.Print");
}
finally
{
doc.Dispose();
Cursor = Cursors.Default;
}
}
private void Print_Click(object sender, EventArgs e)
{
bool isRelated = ((Button)sender).Name.Contains("Related");
Print(isRelated);
}
private void SendIdToMain(C1FlexGrid grid)
{
HitTestInfo hti = grid.HitTest(grid.PointToClient(new Point(MousePosition.X, MousePosition.Y)));
if (hti.Row < 1)
return;
if (DateTime.Now.Subtract(mLastClickTime).TotalSeconds < 10)
return;
mLastClickTime = DateTime.Now;
int id = Convert.ToInt32(grid.GetData(hti.Row, 0));
mParent.SendId(id);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lux.Framework
{
/// <summary>
/// Represents a two-dimensional vector
/// </summary>
public struct Vector2
{
internal OpenTK.Vector2d OpenTKEquivalent { get { return new OpenTK.Vector2d(X, Y); } }
/// <summary>
/// The X-compontent of the vector
/// </summary>
public double X { get; set; }
/// <summary>
/// The Y-compontent of the vector
/// </summary>
public double Y { get; set; }
/// <summary>
/// The squared length of the vector. This operation is much faster than the (unsquared) length.
/// </summary>
public double LengthSquared { get { return X * X + Y * Y; } }
/// <summary>
/// The length of the vector. This operation might be slow, consider using LengthSquared.
/// </summary>
public double Length { get { return Math.Sqrt(LengthSquared); } }
/// <summary>
/// A new vector [ 0, 0 ]
/// </summary>
static public Vector2 Zero { get { return new Vector2(0, 0); } }
/// <summary>
/// A new vector [ 1, 1 ]
/// </summary>
static public Vector2 One { get { return new Vector2(1, 1); } }
/// <summary>
/// A new vector [ 1, 0 ]
/// </summary>
static public Vector2 PosX { get { return new Vector2(1, 0); } }
/// <summary>
/// A new vector [ -1, 0 ]
/// </summary>
static public Vector2 NegX { get { return new Vector2(-1, 0); } }
/// <summary>
/// A new vector [ 0, 1 ]
/// </summary>
static public Vector2 PosY { get { return new Vector2(0, 1); } }
/// <summary>
/// A new vector [ 0, -1 ]
/// </summary>
static public Vector2 NegY { get { return new Vector2(0, -1); } }
/// <summary>
/// A new vector pointing right
/// </summary>
static public Vector2 Right { get { return Vector2.PosX; } }
/// <summary>
/// A new vector pointing left
/// </summary>
static public Vector2 Left { get { return Vector2.NegX; } }
/// <summary>
/// A new vector pointing up
/// </summary>
static public Vector2 Up { get { return Vector2.PosY; } }
/// <summary>
/// A new vector pointing down
/// </summary>
static public Vector2 Down { get { return Vector2.NegY; } }
/// <summary>
/// Creates a new two-dimensional vector from a set of double-precision floating-point numbers.
/// </summary>
/// <param name="x">The X-component of the vector.</param>
/// <param name="y">The Y-component of the vector.</param>
public Vector2(double x, double y)
: this()
{
X = x;
Y = y;
}
/// <summary>
/// Creates a new two-dimensional vector from a set of integers.
/// </summary>
/// <param name="x">The X-component of the vector.</param>
/// <param name="y">The Y-component of the vector.</param>
public Vector2(int x, int y)
: this()
{
X = x;
Y = y;
}
/// <summary>
/// Adds to vectors together.
/// </summary>
/// <param name="in1">The first addend.</param>
/// <param name="in2">The second addend.</param>
/// <returns>The sum of two vectors.</returns>
static public Vector2 operator +(Vector2 in1, Vector2 in2)
{
return new Vector2(in1.X + in2.X, in1.Y + in2.Y);
}
/// <summary>
/// Subracts one vector from another.
/// </summary>
/// <param name="in1">The minuend.</param>
/// <param name="in2">The subtrahend.</param>
/// <returns>The difference between two vectors.</returns>
static public Vector2 operator -(Vector2 in1, Vector2 in2)
{
return new Vector2(in1.X - in2.X, in1.Y - in2.Y);
}
/// <summary>
/// Component-wise multiplication of two vectors. Use DotProduct() for other multiplication operations.
/// </summary>
/// <param name="in1">The first factor.</param>
/// <param name="in2">The second factor.</param>
/// <returns>The component-wise multiplication of two vectors.</returns>
static public Vector2 operator *(Vector2 in1, Vector2 in2)
{
return new Vector2(in1.X * in2.X, in1.Y * in2.Y);
}
/// <summary>
/// Component-wise division of two vectors.
/// </summary>
/// <param name="in1">The dividend.</param>
/// <param name="in2">The divisor</param>
/// <returns>The component-wise division of two vectors.</returns>
static public Vector2 operator /(Vector2 in1, Vector2 in2)
{
return new Vector2(in1.X / in2.X, in1.Y / in2.Y);
}
/// <summary>
/// Component-wise modulo of two vectors.
/// </summary>
/// <param name="in1">The dividend.</param>
/// <param name="in2">The divisor</param>
/// <returns>The component-wise modulo of two vectors.</returns>
static public Vector2 operator %(Vector2 in1, Vector2 in2)
{
return new Vector2(in1.X % in2.X, in1.Y % in2.Y);
}
/// <summary>
/// Multiplication of a vector and a scalar
/// </summary>
/// <param name="in1">The vector.</param>
/// <param name="in2">The scalar.</param>
/// <returns>A scaled vector.</returns>
static public Vector2 operator *(Vector2 in1, double in2)
{
return new Vector2(in1.X * in2, in1.Y * in2);
}
/// <summary>
/// Divison of a vector and a scalar
/// </summary>
/// <param name="in1">The vector.</param>
/// <param name="in2">The scalar.</param>
/// <returns>A scaled vector.</returns>
static public Vector2 operator /(Vector2 in1, double in2)
{
return in1 * (1 / in2);
}
/// <summary>
/// Performs the dot product operation on two vectors.
/// </summary>
/// <param name="vec1">The first vector.</param>
/// <param name="vec2">The second vector.</param>
/// <returns>A double-precision floating-point number which is the dot product of the two vectors.</returns>
static public double Dot(Vector2 vec1, Vector2 vec2)
{
return vec1.X * vec2.X + vec1.Y * vec2.Y;
}
/// <summary>
/// Performs the dot product operation on two vectors.
/// </summary>
/// <param name="vec">The second vector.</param>
/// <returns>A double-precision floating-point number which is the dot product of the two vectors.</returns>
public double Dot(Vector2 vec)
{
return Vector2.Dot(this, vec);
}
/// <summary>
/// Returns a nicely formatted string form the vector.
/// </summary>
/// <returns>A nicely formatte string.</returns>
public override string ToString()
{
return "[ " + X + ", " + Y + " ]";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Ninject;
using NUnit.Framework;
using SeMo;
using SHA3;
namespace Tests
{
public class WhenAttemptingToGenerateHash : TestContext
{
[Test]
public void GeneratedHashShouldBeCorrect()
{
const string source = "";
var bytes = Encoding.ASCII.GetBytes(source);
var generator = Kernel.Get<HashAlgorithm>();
var str = BitConverter.ToString(generator.ComputeHash(bytes)).Replace("-", "").ToLower();
Assert.That(str, Is.EqualTo("0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e"));
}
}
}
|
using System.Collections.Generic;
using System.ServiceModel;
using Project2ObjectWCF.DTO;
namespace Project2ObjectWCF.Interfaces
{
[ServiceContract]
interface TagInterface {
[OperationContract]
void AddTag(TagDTO tag);
[OperationContract]
void DeleteCustomTag(string tag);
[OperationContract]
List<FileDTO> GetFilesByTagKey(string key);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// using UnityEngine.Random;
// using System.Random;
public class GameManager : MonoBehaviour
{
[SerializeField] Transform playerHandTransform,
playerFieldTransform,
enemyHandTransform,
enemyFieldTransform;
[SerializeField] CardController cardPrefab;
bool isPlayerTurn;
List<int> playerDeck = new List<int>() {1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10},
enemyDeck = new List<int>() {1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10};
[SerializeField] Text playerHeroHpText;
[SerializeField] Text enemyHeroHpText;
int playerHeroHp;
int enemyHeroHp;
[SerializeField] Text playerHeroManaText;///
[SerializeField] Text enemyHeroManaText;///
int playerHeroMana;///
int enemyHeroMana; ///
[SerializeField] Text ResultText;///
string resultText;///
public GameObject ResultPanel;///
//シングルトン化(どこからでもアクセス可能)
public static GameManager instance;
private void Awake()
{
if(instance == null)
{
instance = this;
}
}
void Start()
{
StartGame();
isPlayerTurn = true;
TurnCalc();
}
void StartGame()
{
ResultPanel.SetActive (false);
playerHeroHp = 30;
enemyHeroHp = 30;
playerHeroMana = 4; ///
enemyHeroMana = 4; ///
ShowHeroHp();
ShowHeroMana();///
SettingInHand();
}
void ReStart()
{
Start();
}
void SettingInHand()
{
//カードそれぞれを4枚敵と自分に配る
for(int x = 0; x<4; x++)
{
GiveCardToHand(playerDeck, playerHandTransform);
GiveCardToHand(enemyDeck, enemyHandTransform);
}
}
void GiveCardToHand(List<int> deck, Transform hand)
{
if(deck.Count == 0)
{
return;
}
int cardID = deck[0];
deck.RemoveAt(0);
CreateCard(cardID, hand);
}
void CreateCard(int cardID, Transform hand)
{
CardController card = Instantiate(cardPrefab, hand, false);
card.Init(cardID);
}
void TurnCalc()
{
if(isPlayerTurn)
{
PlayerTurn();
}
else
{
EnemyTurn();
}
}
public void ChangeTurn()
{
isPlayerTurn = !isPlayerTurn;
if(isPlayerTurn)
{
GiveCardToHand(playerDeck, playerHandTransform);
}
else
{
GiveCardToHand(enemyDeck, enemyHandTransform);
}
TurnCalc();
}
void PlayerTurn()
{
Debug.Log("あなたのターン");
//フィールドのカードを攻撃可能にする
CardController[] playerFieldCardList = playerFieldTransform.GetComponentsInChildren<CardController>();
foreach (CardController card in playerFieldCardList)
{
card.SetCanAttack(true); // cardを攻撃可能にする
}
}
void EnemyTurn()
{
Debug.Log("敵のターン");
//手札のカードリストを取得
CardController[] handCardList = enemyHandTransform.GetComponentsInChildren<CardController>();
//場に出すカードを選択
CardController enemyCard = handCardList[0];
//カードを移動
enemyCard.movement.SetCardTransform(enemyFieldTransform);
/*攻撃*/
//敵フィールドのカードリストを取得
CardController[] enemyFieldCardList = enemyFieldTransform.GetComponentsInChildren<CardController>();
//攻撃可能カードを取得
CardController[] enemyCanAttackCardList = Array.FindAll(enemyFieldCardList, card => card.model.canAttack);
CardController[] playerFieldCardList = playerFieldTransform.GetComponentsInChildren<CardController>();
if(enemyCanAttackCardList.Length > 0 && playerFieldCardList.Length > 0)
{
//attackerカードを選択
CardController attacker = enemyCanAttackCardList[0];
//defenderカードを選択
CardController defender = playerFieldCardList[0];
//attackerとdefenderを戦わせる
CardsBattle(attacker, defender);
}
ChangeTurn();
}
public void CardsBattle(CardController attacker, CardController defender)
{
Debug.Log("CardsBattle");
attacker.Attack(defender);
attacker.CheckAlive();
defender.CheckAlive();
ShowHeroHp();
//反撃の実装は1部のカードのみ適用
// defender.model.Attack(attacker);
}
void ShowHeroHp()
{
playerHeroHpText.text = playerHeroHp.ToString();
enemyHeroHpText.text = enemyHeroHp.ToString();
}
void ShowHeroMana() ///
{
playerHeroManaText.text = playerHeroMana.ToString();
enemyHeroManaText.text = enemyHeroMana.ToString();
} ///
void ShowResultText()///
{
if(enemyHeroHp <= 0)
{
resultText = "WIN";
ResultText.text = resultText.ToString();
}
else
{
resultText = "ROSE";
ResultText.text = resultText.ToString();
}
}///
public void AttackToHero(CardController attacker, bool isPlayerCard)
{
if(isPlayerCard)
{
enemyHeroHp -= attacker.model.at;
if(enemyHeroHp <= 0) //ここから追加
{
enemyHeroHp = 0;
ResultPanel.SetActive (true);
ShowResultText();
} //ここまで追加
}
else
{
playerHeroHp -= attacker.model.at;
if(playerHeroHp <= 0) ///ここから追加
{
playerHeroHp = 0;
ResultPanel.SetActive (true);
ShowResultText();
} ///ここまで追加
}
attacker.SetCanAttack(false);
ShowHeroHp();
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Lab16
{
class DataStorage
{
public bool isReady
{
get
{
if (rawData == null) return false;
else return true;
}
}
public List<RawDataItem> rawData;
public List<AverageDataItem> averageData;
private char devider = '/';
private DataStorage() { }
private void BuildAverage()
{
//Dictionary<int, float> Shops = new Dictionary<int, float>();
List<AverageDataItem> markets = new List<AverageDataItem>();
foreach (RawDataItem rawDataItem in rawData)
{
if (!markets.Exists(m => m.MarketName == rawDataItem.Market))
markets.Add(new AverageDataItem(rawDataItem.Market));
}
foreach (RawDataItem rawDataItem in rawData)
{
foreach(AverageDataItem market in markets)
{
if (rawDataItem.Market == market.MarketName)
{
market.CountProducts += rawDataItem.Count;
market.CountUnicProducts++;
market.SumPrices += rawDataItem.Price;
}
}
}
foreach (AverageDataItem market in markets)
{
market.AveragePrice = market.SumPrices / market.CountUnicProducts;
}
averageData = markets;
/*foreach (var item in rawData)
{
if (tmp.ContainsKey(item.Market))
tmp[item.Market] += item.Price;
else
tmp[item.Market] = item.Price;
}
averageData = new List<AverageDataItem>();
foreach (var item in averageData)
{
if (averageData.Exists(i => i.MarketName == item.MarketName))
item.CountProducts += rawData
averageData.Add(new AverageDataItem() {
MarketName = Utils.GetGroupByNumber(item.Key),
CountProducts +=
AveragePrice = item.Value,
});
}*/
}
private bool InitData(string datapath)
{
rawData = new List<RawDataItem>();
try
{
StreamReader sr = new StreamReader(datapath, Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
string[] items = line.Split(devider);
RawDataItem item = new RawDataItem();
item.Name = items[0];
item.Price = Convert.ToSingle(items[1]);
item.Count = Convert.ToInt32(items[2]);
item.Market = items[3];
item.SumPrice = item.Price * item.Count;
rawData.Add(item);
}
sr.Close();
BuildAverage();
} catch (IOException ex) { return false; }
return true;
}
public static DataStorage DataCreator(string path)
{
DataStorage d = new DataStorage();
if (d.InitData(path))
return d;
else return null;
}
public List<RawDataItem> GetRawData()
{
if (this.isReady)
return rawData;
else
return null;
}
public List<AverageDataItem> GetSummaryData()
{
if (this.isReady)
return averageData;
else return null;
}
}
}
|
using UnityEngine;
using System.Collections;
public class WargScript : CoboldoScript {
}
|
using log4net;
using NippoPaymentsApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
namespace NippoPaymentsApi.Identity
{
public class DatabaseUserLoginProvider : ILoginProvider
{
public bool ValidateCredentials(string userName, string password, out ClaimsIdentity identity)
{
this.dbctx = new DataBaseAuthContext();
Usuario user = null;
bool isValid = dbctx.ValidateCredentials(userName, password, out user);
if (isValid)
{
identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
Log.Debug("Aqui " + (identity == null));
Log.Debug("Aqui " + (user == null));
identity.AddClaim(new Claim(ClaimTypes.Name, user.Usuario1));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Nombre));
string adminUSer = Utils.Util.getValueFromWebConfig("user:admin").ToUpper();
Log.Debug("adminUSer " + adminUSer);
Log.Debug("adminUSer " + userName.ToUpper().Equals(adminUSer));
if (userName.ToUpper().Equals(adminUSer))
{
identity.AddClaim(new Claim(ClaimTypes.Role, "Administrador"));
}
else
{
identity.AddClaim(new Claim(ClaimTypes.Role, "Usuario"));
}
}
else
{
identity = null;
}
return isValid;
}
public DatabaseUserLoginProvider()
{
}
private DataBaseAuthContext dbctx;
private static readonly ILog Log = LogManager.GetLogger(typeof(DatabaseUserLoginProvider));
}
} |
using UnityEngine;
/// <summary>
/// TODO
/// Provides attributes and information of portal
/// </summary>
public class PortalSpawn : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task7_Andrey_and_billiard
{
public class task7_Andrey_and_billiard
{
public static void Main()
{
Dictionary<string, double> menu = ReadProducts();
var input = Console.ReadLine();
var allCustomer = new List<Customer>();
while (input != "end of clients")
{
var line = input.Split('-', ',');
var customerName = line[0];
var productOrdered = line[1];
double quantity = double.Parse(line[2]);
if (menu.ContainsKey(productOrdered))
{
Customer client = new Customer();
client.ShopList = new Dictionary<string, double>();
client.Name = customerName;
client.ShopList.Add(productOrdered, quantity);
if (allCustomer.Any(c => c.Name == customerName))
{
var existingCustomer = allCustomer.First(c => c.Name == customerName);
if (existingCustomer.ShopList.ContainsKey(productOrdered))
{
existingCustomer.ShopList[productOrdered] += quantity;
}
else
{
existingCustomer.ShopList[productOrdered] = quantity;
}
}
else
{
allCustomer.Add(client);
}
}
input = Console.ReadLine();
}
// make bill:
foreach (var customer in allCustomer)
{
foreach (var item in customer.ShopList)
{
foreach (var product in menu)
{
if (item.Key == product.Key)
{
customer.Bill += item.Value * product.Value;
}
}
}
}
var ordered = allCustomer
.OrderBy(x => x.Name)
.ThenBy(x => x.Bill)
.ToList();
foreach (var customer in ordered)
{
Console.WriteLine(customer.Name);
foreach (var item in customer.ShopList)
{
Console.WriteLine($"-- {item.Key} - {item.Value}");
}
Console.WriteLine("Bill: {0:f2}", customer.Bill);
}
Console.WriteLine("Total bill: {0:F2}", allCustomer.Sum(c => c.Bill));
}
public static Dictionary<string,double> ReadProducts()
{
int n = int.Parse(Console.ReadLine());
var listOfProducts = new Dictionary<string, double>();
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine().Split('-');
var nameProduct = input.First();
var priceProduct = double.Parse(input.Last());
if (!listOfProducts.ContainsKey(nameProduct))
{
listOfProducts.Add(nameProduct, priceProduct);
}
listOfProducts[nameProduct] = priceProduct;
}
return listOfProducts;
}
public class Customer
{
public string Name { get; set; }
public Dictionary<string, double> ShopList { get; set; }
public double Bill { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using FactionCombinationAnalysis.FactionCombine.Combiner;
namespace FactionCombinationAnalysis.FactionCombine.Setting
{
public class CombinationProviderSetting_A : CombinationProviderSetting
{
public CombinationProviderSetting_A()
{
Combiners.Add(new Combiner_A(), 0.5);
Combiners.Add(new Combiner_B(), 0.5);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using Pixelplacement;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI.Extensions;
[RequireComponent(typeof(Image), typeof(NicerOutline))]
public class ImageGlow : MonoBehaviour
{
[SerializeField] Color color;
[SerializeField] float minimum;
[SerializeField] float maximum;
[SerializeField] float speed;
[SerializeField] float interval;
[SerializeField] AnimationCurve pulseCurve;
void Start()
{
Image image = GetComponent<Image>();
NicerOutline outline = GetComponent<NicerOutline>();
Color startColor = new Color(color.r, color.g, color.b, color.a * minimum);
Color endColor = new Color(color.r, color.g, color.b, color.a * maximum);
Tween.Value(startColor, endColor, (val) => outline.effectColor = val, speed, interval, pulseCurve, Tween.LoopType.PingPong, obeyTimescale: false);
}
}
|
using AudioText.Models.DataModels;
using AudioText.Models;
using AudioText.Services;
using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using AudioText.Models.ViewModels;
namespace AudioText.Controllers
{
public class EmailController : Controller
{
[HttpPost]
public async Task<ActionResult> sendContactEmail(ContactModel model)
{
bool sentSuccessfully = await EmailService.SendMessageFromCustomer(model);
if (sentSuccessfully)
{
return View("_resultPage", new ResultViewModel("Thank you for your feedback",
String.Format("Thank you {0} for getting in contact with us. We appreciate what you have to say.", model.FirstName)));
}
else
{
return View("_resultPage", new ResultViewModel("Something went wrong while trying to send your message.",
"We apologize for the inconvenience. We still want to hear from you, try sending an independent e-mail or try again at later."));
}
}
[HttpPost]
public async Task<ActionResult> registerEmail(AccountInformation information)
{
bool registeredSuccessfully = await EmailService.saveEmail(information.Email);
if (registeredSuccessfully)
{
return View("_resultPage", new ResultViewModel(
"Thank you for registering!",
"We look forward to sharing our new releases and promotions with you! "));
}
else
{
return View("_resultPage", new ResultViewModel(
"E-mail is already registered...",
"Sorry, it appears that your e-mail is already registered with us. If you haven't been getting our news letter then please let us know"));
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Крестики_Нолики
{
public partial class Form1 : Form
{
bool xTurn = true;
bool NoWin = false;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button senderB = (Button)sender;
if (xTurn)
{
senderB.Text = "X";
}
else
{
senderB.Text = "O";
}
xTurn = !xTurn;
senderB.Enabled = false;
CheckWin(senderB);
}
void CheckWin(Button pressedButton)
{
if(button1.Text==button2.Text&&button2.Text==button3.Text && button1.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button4.Text == button5.Text && button5.Text == button6.Text && button5.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button7.Text == button8.Text && button8.Text == button9.Text && button8.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button1.Text == button4.Text && button4.Text == button7.Text && button4.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button2.Text == button5.Text && button5.Text == button8.Text && button8.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button3.Text == button6.Text && button6.Text == button9.Text && button9.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button1.Text == button5.Text && button5.Text == button9.Text && button5.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (button3.Text == button5.Text && button5.Text == button7.Text && button5.Enabled == false)
{
MessageBox.Show("Winner Chicken Diner: " + pressedButton.Text);
NoWin = true;
Reset();
}
if (NoWin == false && button1.Enabled == false && button2.Enabled == false && button3.Enabled == false &&button4.Enabled == false && button5.Enabled == false && button6.Enabled == false && button7.Enabled == false && button8.Enabled == false && button9.Enabled == false)
{
MessageBox.Show("No Winners :(");
Reset();
}
}
private void aboutAllToolStripMenuItem_Click_1(object sender, EventArgs e)
{
MessageBox.Show("My First Game!");
}
private void button10_Click(object sender, EventArgs e)
{
Reset();
}
void Reset()
{
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
xTurn = true;
}
private void xToolStripMenuItem_Click(object sender, EventArgs e)
{
xTurn = true;
Reset();
}
private void oToolStripMenuItem_Click(object sender, EventArgs e)
{
xTurn = false;
Reset();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using PatientsRegistry.Domain;
using PatientsRegistry.Domain.Validation;
namespace PatientsRegistry.Registry
{
public sealed class PatientCreate
{
[Required]
[Name]
public string Name { get; set; }
[Required]
[Name]
public string Lastname { get; set; }
[Name]
public string Patronymic { get; set; }
[Required]
[Birthdate]
public DateTime? Birthdate { get; set; }
[Required]
[EnumDataType(typeof(Gender))]
public string Gender { get; set; }
[Required]
[CellPhone]
public string Phone { get; set; }
}
}
|
using System.Collections.Generic;
using PizzaMore.Data;
using PizzaMore.Utility;
namespace Home
{
class Home
{
private static IDictionary<string, string> RequestParameters;
private static Session Session;
private static Header Header = new Header();
private static string Language;
static void Main()
{
AddDefaultLanguageCookie();
if (WebUtil.IsGet())
{
RequestParameters = WebUtil.RetrieveGetParameters();
TryLogOut();
Language = WebUtil.GetCookies()["lang"].Value;
}
else if (WebUtil.IsPost())
{
RequestParameters = WebUtil.RetrievePostParameters();
Header.AddCookie(new Cookie("lang", RequestParameters["language"]));
Language = RequestParameters["language"];
}
ShowPage();
}
private static void TryLogOut()
{
if (RequestParameters.ContainsKey("logout"))
{
if (RequestParameters["logout"] == "true")
{
Session = WebUtil.GetSession();
using (var pizzaMoreContext = new PizzaMoreContext())
{
var seesion = pizzaMoreContext.Sessions.Find(Session.Id);
pizzaMoreContext.Sessions.Remove(seesion);
pizzaMoreContext.SaveChanges();
}
}
}
}
private static void AddDefaultLanguageCookie()
{
if (!WebUtil.GetCookies().ContainsKey("lang"))
{
Header.AddCookie(new Cookie("lang", "EN"));
Language = "EN";
ShowPage();
}
}
private static void ShowPage()
{
Header.Print();
if (Language.Equals("DE"))
{
ServeHtmlBg();
}
else
{
ServeHtmlEn();
}
}
private static void ServeHtmlEn()
{
WebUtil.PrintFileContent(Constants.HomeEn);
}
private static void ServeHtmlBg()
{
WebUtil.PrintFileContent(Constants.HomeDe);
}
}
}
|
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using ApartmentApps.Client.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
namespace ApartmentApps.Client.Models
{
public partial class MaintenanceBindingModel
{
private IList<string> _acceptableCheckinCodes;
/// <summary>
/// Optional.
/// </summary>
public IList<string> AcceptableCheckinCodes
{
get { return this._acceptableCheckinCodes; }
set { this._acceptableCheckinCodes = value; }
}
private string _buildingName;
/// <summary>
/// Optional.
/// </summary>
public string BuildingName
{
get { return this._buildingName; }
set { this._buildingName = value; }
}
private IList<MaintenanceCheckinBindingModel> _checkins;
/// <summary>
/// Optional.
/// </summary>
public IList<MaintenanceCheckinBindingModel> Checkins
{
get { return this._checkins; }
set { this._checkins = value; }
}
private string _message;
/// <summary>
/// Optional.
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
private string _name;
/// <summary>
/// Optional.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private bool? _permissionToEnter;
/// <summary>
/// Optional.
/// </summary>
public bool? PermissionToEnter
{
get { return this._permissionToEnter; }
set { this._permissionToEnter = value; }
}
private int? _petStatus;
/// <summary>
/// Optional.
/// </summary>
public int? PetStatus
{
get { return this._petStatus; }
set { this._petStatus = value; }
}
private IList<string> _photos;
/// <summary>
/// Optional.
/// </summary>
public IList<string> Photos
{
get { return this._photos; }
set { this._photos = value; }
}
private DateTimeOffset? _scheduleDate;
/// <summary>
/// Optional.
/// </summary>
public DateTimeOffset? ScheduleDate
{
get { return this._scheduleDate; }
set { this._scheduleDate = value; }
}
private string _status;
/// <summary>
/// Optional.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
private string _unitName;
/// <summary>
/// Optional.
/// </summary>
public string UnitName
{
get { return this._unitName; }
set { this._unitName = value; }
}
private UserBindingModel _user;
/// <summary>
/// Optional.
/// </summary>
public UserBindingModel User
{
get { return this._user; }
set { this._user = value; }
}
private string _userId;
/// <summary>
/// Optional.
/// </summary>
public string UserId
{
get { return this._userId; }
set { this._userId = value; }
}
private string _userName;
/// <summary>
/// Optional.
/// </summary>
public string UserName
{
get { return this._userName; }
set { this._userName = value; }
}
/// <summary>
/// Initializes a new instance of the MaintenanceBindingModel class.
/// </summary>
public MaintenanceBindingModel()
{
this.AcceptableCheckinCodes = new LazyList<string>();
this.Checkins = new LazyList<MaintenanceCheckinBindingModel>();
this.Photos = new LazyList<string>();
}
/// <summary>
/// Deserialize the object
/// </summary>
public virtual void DeserializeJson(JToken inputObject)
{
if (inputObject != null && inputObject.Type != JTokenType.Null)
{
JToken acceptableCheckinCodesSequence = ((JToken)inputObject["AcceptableCheckinCodes"]);
if (acceptableCheckinCodesSequence != null && acceptableCheckinCodesSequence.Type != JTokenType.Null)
{
foreach (JToken acceptableCheckinCodesValue in ((JArray)acceptableCheckinCodesSequence))
{
this.AcceptableCheckinCodes.Add(((string)acceptableCheckinCodesValue));
}
}
JToken buildingNameValue = inputObject["BuildingName"];
if (buildingNameValue != null && buildingNameValue.Type != JTokenType.Null)
{
this.BuildingName = ((string)buildingNameValue);
}
JToken checkinsSequence = ((JToken)inputObject["Checkins"]);
if (checkinsSequence != null && checkinsSequence.Type != JTokenType.Null)
{
foreach (JToken checkinsValue in ((JArray)checkinsSequence))
{
MaintenanceCheckinBindingModel maintenanceCheckinBindingModel = new MaintenanceCheckinBindingModel();
maintenanceCheckinBindingModel.DeserializeJson(checkinsValue);
this.Checkins.Add(maintenanceCheckinBindingModel);
}
}
JToken messageValue = inputObject["Message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
this.Message = ((string)messageValue);
}
JToken nameValue = inputObject["Name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
this.Name = ((string)nameValue);
}
JToken permissionToEnterValue = inputObject["PermissionToEnter"];
if (permissionToEnterValue != null && permissionToEnterValue.Type != JTokenType.Null)
{
this.PermissionToEnter = ((bool)permissionToEnterValue);
}
JToken petStatusValue = inputObject["PetStatus"];
if (petStatusValue != null && petStatusValue.Type != JTokenType.Null)
{
this.PetStatus = ((int)petStatusValue);
}
JToken photosSequence = ((JToken)inputObject["Photos"]);
if (photosSequence != null && photosSequence.Type != JTokenType.Null)
{
foreach (JToken photosValue in ((JArray)photosSequence))
{
this.Photos.Add(((string)photosValue));
}
}
JToken scheduleDateValue = inputObject["ScheduleDate"];
if (scheduleDateValue != null && scheduleDateValue.Type != JTokenType.Null)
{
this.ScheduleDate = ((DateTimeOffset)scheduleDateValue);
}
JToken statusValue = inputObject["Status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
this.Status = ((string)statusValue);
}
JToken unitNameValue = inputObject["UnitName"];
if (unitNameValue != null && unitNameValue.Type != JTokenType.Null)
{
this.UnitName = ((string)unitNameValue);
}
JToken userValue = inputObject["User"];
if (userValue != null && userValue.Type != JTokenType.Null)
{
UserBindingModel userBindingModel = new UserBindingModel();
userBindingModel.DeserializeJson(userValue);
this.User = userBindingModel;
}
JToken userIdValue = inputObject["UserId"];
if (userIdValue != null && userIdValue.Type != JTokenType.Null)
{
this.UserId = ((string)userIdValue);
}
JToken userNameValue = inputObject["UserName"];
if (userNameValue != null && userNameValue.Type != JTokenType.Null)
{
this.UserName = ((string)userNameValue);
}
}
}
}
}
|
using ClaimDi.DataAccess.Entity;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ClaimDi.DataAccess
{
public class MyContext : DbContext
{
public MyContext(string configurationName)
: base(configurationName) { }
public MyContext()
: base(Configurator.CrmSqlConnection) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Conventions.Remove<TypeNameForeignKeyDiscoveryConvention>();
modelBuilder.Conventions.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
modelBuilder.Configurations.Add(new AccountProfileConfig());
modelBuilder.Configurations.Add(new AccountDeviceConfig());
modelBuilder.Configurations.Add(new AccountTypeConfig());
modelBuilder.Configurations.Add(new CarBrandConfig());
modelBuilder.Configurations.Add(new CarColorConfig());
modelBuilder.Configurations.Add(new CarInfoConfig());
modelBuilder.Configurations.Add(new CarModelConfig());
modelBuilder.Configurations.Add(new CarPolicyConfig());
modelBuilder.Configurations.Add(new CarTypeConfig());
modelBuilder.Configurations.Add(new InsurerConfig());
modelBuilder.Configurations.Add(new UserTokenConfig());
modelBuilder.Configurations.Add(new ConfigFeatureConfig());
modelBuilder.Configurations.Add(new EmailConfigConfig());
modelBuilder.Configurations.Add(new FeatureConfig());
modelBuilder.Configurations.Add(new CauseOfLossConfig());
modelBuilder.Configurations.Add(new ClaimItemConfig());
modelBuilder.Configurations.Add(new PartyAtFaultConfig());
modelBuilder.Configurations.Add(new PictureTypeConfig());
modelBuilder.Configurations.Add(new RequestK4KLogConfig());
modelBuilder.Configurations.Add(new RunningConfig());
modelBuilder.Configurations.Add(new ProvinceConfig());
modelBuilder.Configurations.Add(new TaskConfig());
modelBuilder.Configurations.Add(new TaskPictureConfig());
modelBuilder.Configurations.Add(new TaskProcessConfig());
modelBuilder.Configurations.Add(new TaskProcessLogConfig());
modelBuilder.Configurations.Add(new TaskTypeConfig());
modelBuilder.Configurations.Add(new ClaimCauseOfLossConfig());
modelBuilder.Configurations.Add(new AppSecretConfig());
modelBuilder.Configurations.Add(new TemplateESlipConfig());
modelBuilder.Configurations.Add(new RoleConfig());
modelBuilder.Configurations.Add(new ILertULogConfig());
modelBuilder.Configurations.Add(new ILertUMapServiceConfig());
modelBuilder.Configurations.Add(new PictureGroupConfig());
modelBuilder.Configurations.Add(new ApplicationKeyConfig());
modelBuilder.Configurations.Add(new AccountDeviceLogConfig());
modelBuilder.Configurations.Add(new MappingCarTaskBikeConfig());
base.OnModelCreating(modelBuilder);
}
}
} |
namespace Sentry.Tests.Protocol;
public class DebugImageTests
{
private readonly IDiagnosticLogger _testOutputLogger;
public DebugImageTests(ITestOutputHelper output)
{
_testOutputLogger = new TestOutputDiagnosticLogger(output);
}
[Fact]
public void SerializeObject_AllPropertiesSetToNonDefault_SerializesValidObject()
{
var sut = new DebugImage
{
Type = "elf",
ImageAddress = "0xffffffff",
ImageSize = 1234,
DebugId = "900f7d1b868432939de4457478f34720",
DebugFile = "libc.debug",
CodeId = "900f7d1b868432939de4457478f34720",
CodeFile = "libc.so"
};
var actual = sut.ToJsonString(_testOutputLogger, indented: true);
Assert.Equal("""
{
"type": "elf",
"image_addr": "0xffffffff",
"image_size": 1234,
"debug_id": "900f7d1b868432939de4457478f34720",
"debug_file": "libc.debug",
"code_id": "900f7d1b868432939de4457478f34720",
"code_file": "libc.so"
}
""",
actual);
var parsed = Json.Parse(actual, DebugImage.FromJson);
parsed.Should().BeEquivalentTo(sut);
}
}
|
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class ChangeScenePress : MonoBehaviour
{
public string scene = "Zona0";
private void Awake()
{
}
public void OnSubmit()
{
SceneManager.LoadScene(scene);
}
}
|
using Plugin.Settings;
using System;
using System.Collections.Generic;
using System.Text;
namespace NetheusLibrary.Helper
{
public static class LocalStorageHelper
{
public static void StoreInLocalSetting(string key, string val)
{
try
{
CrossSettings.Current.AddOrUpdateValue(key, val);
}
catch (Exception Ex)
{
System.Diagnostics.Debug.WriteLine("Error in storing in local settings", Ex.Message);
}
}
public static string RetriveFromLocalSetting(string key)
{
string retVal = null;
try
{
var serializedUser = CrossSettings.Current.GetValueOrDefault(key, string.Empty, null);
if (serializedUser != null)
{
retVal = serializedUser;
}
return retVal;
}
catch (Exception Ex)
{
System.Diagnostics.Debug.WriteLine("Error in retrieving from local settings", Ex.Message);
return retVal;
}
}
}
}
|
using System;
using FirstCode;
using SecondCode;
using SecondCode.BetterExceptions;
using ThirdCode;
namespace TestApp
{
public class Program
{
public static void Main(string[] args)
{
FirstExamples();
SecondExamples();
ThirdExamples();
FourthExamples();
}
private static void FirstExamples()
{
var utility = new FirstUtility();
var even = utility.IsEven(40);
//var average = utility.Average(20, 0);
//var increased = utility.IncreaseValue(int.MaxValue);
//var increasedMore = utility.IncreaseValueMore(100);
}
private static void SecondExamples()
{
var utility2 = new Utility2();
var averageA = utility2.Average(20, 10);
var averageB = utility2.Average(20, 0);
var utility3 = new Utility3();
var averageC = utility3.Average(20, 10);
//var averageD = utility3.Average(20, 0);
var utility4 = new Utility4();
var averageE = utility4.Average(20, 10);
//var averageF = utility4.Average(20, 0);
var utility5 = new Utility5();
var averageG = utility5.Average(20, 10);
//var averageH = utility5.Average(20, 0);
try
{
var averageToCatch1 = utility5.Average(20, 0);
}
catch (InvalidQuantityException ex)
{
Console.WriteLine($"Exception! Message: {ex.Message} (Quantity is {ex.Quantity})");
}
try
{
var averageToCatch2 = utility5.Average(20, 0);
}
catch (Exception ex)
{
Console.WriteLine($"Exception! Message: {ex.Message}");
}
}
private static void ThirdExamples()
{
// Empty
}
private static void FourthExamples()
{
// Empty
}
}
}
|
using FluentNHibernate.Mapping;
using Sind.Model;
namespace Sind.DAL.Mappings
{
public class GrupoVisaoMap : ClassMap<GrupoVisao>
{
public GrupoVisaoMap()
{
Table("GrupoVisao");
Id(g => g.Id, "Id_GrupoVisao");
Map(g => g.Nome, "Nome");
Map(g => g.Ativo, "Ativo").CustomSqlType("typeof(Int32)");
HasManyToMany(g => g.Visoes)
.Table("Visao_GrupoVisao")
.ParentKeyColumn("Id_GrupoVisao")
.ChildKeyColumn("Id_Visao")
.Not.LazyLoad()
.Cascade.SaveUpdate();
}
}
}
|
using System;
using System.Collections.Generic;
using SignInCheckIn.Models.DTO;
namespace SignInCheckIn.Services.Interfaces
{
public interface ISiteService
{
List<CongregationDto> GetAll();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _3Layer.BLL;
using _3Layer.DTO;
using System.Threading;
using System.Media;
namespace _3Layer.GUI
{
public partial class GameForm : Form
{
GameBLL game;
SoundBLL sound;
private Color COLOR_ANSWER = Color.FromArgb(4, 99, 128);
private Color COLOR_ANSWER_SELECTED = Color.FromArgb(255, 152, 0);
private Color COLOR_ANSWER_CORRECT = Color.FromArgb(133, 219, 24);
public GameForm()
{
InitializeComponent();
Player currentPlayer = new Player("Nghia");
game = new GameBLL(currentPlayer);
sound = new SoundBLL();
}
//Load câu hỏi đầu tiên
private void GameForm_Load(object sender, EventArgs e)
{
game.OnNextQuestion += new EventHandler(OnNextQuestion);
game.OnShowResult += new EventHandler(OnShowResult);
game.OnEndGame += new EventHandler(OnEndGame);
}
private void OnEndGame(object sender, EventArgs e) {
Thread.Sleep(500);
if (this.InvokeRequired)
{
try
{
this.Invoke(new MethodInvoker(delegate()
{
pnlSidebar.Visible = false;
pnlQuestion.Visible = false;
pnlResult.Visible = true;
sound.SoundThankYou();
}));
}
catch (Exception)
{
}
}
else {
pnlSidebar.Visible = false;
pnlQuestion.Visible = false;
pnlResult.Visible = true;
sound.SoundThankYou();
}
}
private void OnShowResult(object sender, EventArgs e) {
if (this.InvokeRequired) {
try
{
this.Invoke(new MethodInvoker(delegate() {
switch (game.CurrentQuestion.Correct)
{
case 'A': btnA.BackColor = COLOR_ANSWER_CORRECT;
break;
case 'B': btnB.BackColor = COLOR_ANSWER_CORRECT;
break;
case 'C': btnC.BackColor = COLOR_ANSWER_CORRECT;
break;
case 'D': btnD.BackColor = COLOR_ANSWER_CORRECT;
break;
}
}));
}
catch (Exception)
{
}
}
}
private void OnNextQuestion(object sender, EventArgs e)
{
Question question = game.CurrentQuestion;
if (this.InvokeRequired)
{
try
{
this.Invoke(new MethodInvoker(delegate()
{
lblContent.Text = question.Content;
btnA.Text = "A. " + question.A;
btnB.Text = "B. " + question.B;
btnC.Text = "C. " + question.C;
btnD.Text = "D. " + question.D;
btnA.BackColor = COLOR_ANSWER;
btnB.BackColor = COLOR_ANSWER;
btnC.BackColor = COLOR_ANSWER;
btnD.BackColor = COLOR_ANSWER;
GetLabelQuestion(game.CurrentLevel).BackColor = Color.Yellow;
}));
}
catch (Exception)
{
}
}
else {
lblContent.Text = question.Content;
btnA.Text = "A. " + question.A;
btnB.Text = "B. " + question.B;
btnC.Text = "C. " + question.C;
btnD.Text = "D. " + question.D;
btnA.BackColor = COLOR_ANSWER;
btnB.BackColor = COLOR_ANSWER;
btnC.BackColor = COLOR_ANSWER;
btnD.BackColor = COLOR_ANSWER;
GetLabelQuestion(game.CurrentLevel).BackColor = Color.Yellow;
}
}
//Lây ra label câu hỏi theo index
private Label GetLabelQuestion(int index) {
return (Label)pnlSidebar.Controls["lblQuestion"+index];
}
private void btn_ChoiceAnswer(object sender, EventArgs e) {
Button btn = (Button)sender;
if (btn.Text != "") {
char answer = btn.Text[0];
if (game.ChoiceAnswer(answer))
{
btn.BackColor = COLOR_ANSWER_SELECTED;
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnStart.Visible = false;
sound.SoundRule(delegate() {
game.Play();
});
}
private void tmrTimePlay_Tick(object sender, EventArgs e)
{
if (game.IsPlay())
{
game.CountDownTimePlay();
lblCountDown.Text = game.CurrentTimePlay + "";
lblCountDown.Visible = true;
}
else {
lblCountDown.Visible = false;
}
}
private void btn50_Click(object sender, EventArgs e)
{
if (game.IsPlay()) {
btn50.Enabled = false;
sound.SoundHelp50();
switch (game.CurrentQuestion.Correct) {
case 'A': btnB.Text = "";
btnC.Text = "";
break;
case 'B': btnA.Text = "";
btnC.Text = "";
break;
case 'C': btnB.Text = "";
btnD.Text = "";
break;
case 'D': btnA.Text = "";
btnB.Text = "";
break;
}
}
}
private void btnCall_Click(object sender, EventArgs e)
{
if (game.IsPlay()) {
btnCall.Enabled = false;
game.CurrentTimePlay = 30;
HelpCallForm help = new HelpCallForm(game.CurrentQuestion);
help.Show();
}
}
private void btnHelp_Click(object sender, EventArgs e)
{
if (game.IsPlay()) {
btnHelp.Enabled = false;
game.CurrentTimePlay = 30;
HelpAskForm help = new HelpAskForm(game.CurrentQuestion);
help.Show();
}
}
private void btnStart_Click_1(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnStart.Visible = false;
pnlSidebar.Visible = true;
sound.SoundRule(delegate()
{
try
{
pnlQuestion.Invoke(new MethodInvoker(delegate() {
pnlQuestion.Visible = true;
}));
}
catch (Exception)
{
}
game.Play();
});
}
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult rs = MessageBox.Show("Bạn có chắc chắn muốn thoát!", "Xác nhận", MessageBoxButtons.OKCancel);
if (rs != DialogResult.OK)
{
e.Cancel = true;
}
else {
game.sound.Stop();
sound.Stop();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (game.IsPlay()) {
btnStop.Enabled = false;
game.Stop();
}
}
}
}
|
using JT808.Protocol.Attributes;
using JT808.Protocol.Extensions;
using JT808.Protocol.Formatters;
using JT808.Protocol.Interfaces;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 数据上行透传
/// </summary>
public class JT808_0x0900 : JT808Bodies, IJT808MessagePackFormatter<JT808_0x0900>, IJT808_2019_Version
{
public override ushort MsgId { get; } = 0x0900;
/// <summary>
/// 透传消息类型
/// </summary>
public byte PassthroughType { get; set; }
/// <summary>
/// 透传数据
/// </summary>
public byte[] PassthroughData { get; set; }
/// <summary>
/// 透传消息内容
/// </summary>
public JT808_0x0900_BodyBase JT808_0x0900_BodyBase { get; set; }
public JT808_0x0900 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x0900 jT808_0X0900 = new JT808_0x0900();
jT808_0X0900.PassthroughType = reader.ReadByte();
jT808_0X0900.PassthroughData = reader.ReadContent().ToArray(); ;
return jT808_0X0900;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x0900 value, IJT808Config config)
{
writer.WriteByte(value.PassthroughType);
object obj = config.GetMessagePackFormatterByType(value.JT808_0x0900_BodyBase.GetType());
JT808MessagePackFormatterResolverExtensions.JT808DynamicSerialize(obj, ref writer, value.JT808_0x0900_BodyBase, config);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace testMonogame.Commands
{
class NextItemCommand : ICommand
{
IPlayer p;
public NextItemCommand(GameManager g)
{
p = g.getPlayer();
}
public void Execute()
{
p.NextItem();
}
}
}
|
using eMAM.Data;
using eMAM.Data.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace eMAM.Service.Utills
{
public static class DataSeed
{
public static async Task SeedDatabaseWithSuperAdminAsync(IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (dbContext.Roles.Any(u => u.Name == "SuperAdmin"))
{
return;
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
var rolemanager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
await rolemanager.CreateAsync(new IdentityRole { Name = "SuperAdmin" });
await rolemanager.CreateAsync(new IdentityRole { Name = "Admin" });
await rolemanager.CreateAsync(new IdentityRole { Name = "Operator" });
await rolemanager.CreateAsync(new IdentityRole { Name = "Manager" });
await rolemanager.CreateAsync(new IdentityRole { Name = "User" });
var superAdminUser = new User { UserName= "super@admin.user", Email = "super@admin.user" };
await userManager.CreateAsync(superAdminUser, "Admin123!");
await userManager.AddToRoleAsync(superAdminUser, "SuperAdmin");
}
}
public static async Task SeedDatabaseWithStatus(IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (dbContext.Statuses.Any())
{
return;
}
Status notReviewed = new Status
{
Text = "Not Reviewed"
};
Status invalidApplication = new Status
{
Text = "Invalid Application"
};
Status newStat = new Status
{
Text = "New"
};
Status open = new Status
{
Text = "Open"
};
Status aproved = new Status
{
Text = "Aproved"
};
Status rejected = new Status
{
Text = "Rejected"
};
await dbContext.Statuses.AddAsync(notReviewed);
await dbContext.Statuses.AddAsync(invalidApplication);
await dbContext.Statuses.AddAsync(newStat);
await dbContext.Statuses.AddAsync(open);
await dbContext.Statuses.AddAsync(aproved);
await dbContext.Statuses.AddAsync(rejected);
await dbContext.SaveChangesAsync();
}
}
public static async Task SeedToken(IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (dbContext.GmailUserData.Any())
{
return;
}
var tokenData = new GmailUserData
{
AccessToken = "ya29.GlwfB1dRZP7g9yaz5sYZF5CaGwZaWMBlv7p9GTd8fktr4UQkbP2YRMF_hJCba6e7_IuRbMq0pWmdBzhaBXo4RldV8PvcOs7wngP1De7oPw343R1833QBr0tf3prAlw",
RefreshToken = "1/BHFfhoG1zZqGPqn8bNB8q6d79zs_MChxVPx2OYP_-m6wJSJ9_XzAXNTlGsqkv9xE",
ExpiresAt = DateTime.Parse("2019-06-05 21:48:05.503351")
};
await dbContext.GmailUserData.AddAsync(tokenData);
await dbContext.SaveChangesAsync();
}
}
}
}
|
using System;
using Chapter1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Tester
{
[TestClass]
public class TestChapter1
{
bool expected;
bool actual;
[TestMethod]
public void Testq1_1()
{
Q1dot1 obj = new Q1dot1();
//expected = false;
//actual = obj.StringIsUnique(null);
//Assert.AreEqual(expected, actual);
expected = false;
actual = obj.StringIsUnique("shaurya");
Assert.AreEqual(expected, actual);
expected = true;
actual = obj.StringIsUnique("shaur");
Assert.AreEqual(expected, actual);
expected = true;
actual = obj.StringIsUnique("");
Assert.AreEqual(expected, actual);
expected = false;
actual = obj.StringIsUnique("ss");
Assert.AreEqual(expected, actual);
expected = true;
actual = obj.StringIsUnique("sa");
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Testq1_2()
{
Q1dot2 obj = new Q1dot2();
string expected = "cba\0";
string actual = obj.ReverseString("abc\0");
Assert.AreEqual(expected,actual);
expected = "cbba\0";
actual = obj.ReverseString("abbc\0");
Assert.AreEqual(expected, actual);
}
}
}
|
using System.Data.Entity;
using LearningSystem.Models.EntityModels;
using Microsoft.AspNet.Identity.EntityFramework;
namespace LearningSystem.Data
{
public class LearningSystemContext : IdentityDbContext<ApplicationUser>
{
public LearningSystemContext()
: base("LearningSystem")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Article> Articles { get; set; }
public static LearningSystemContext Create()
{
return new LearningSystemContext();
}
}
} |
using Comp;
using Dapper;
using Model.IntelligenceDiningTable;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.IntelligenceDiningTable
{
/// <summary>
/// 菜品原料详情
/// </summary>
public class D_DishInfo
{
/// <summary>
/// 获取列表
/// </summary>
public List<E_DishInfo> GetList(E_DishInfo model)
{
List<E_DishInfo> list = new List<E_DishInfo>();
//查询语句
StringBuilder strwhere = new StringBuilder();
if (model.DID > 0) //菜品ID
{
strwhere.AddWhere($"DID={model.DID}");
}
if (model.numcontent == 1)
{
strwhere.AddWhere("numcontent is null");
}
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat(@"select A.[id],A.[DID],B.RAWName as DName,A.[Content],A.[RawID],C.Name as zs ,
(select top 1 Content from NutrientComposition where NutritionElementsID=1 and RawID=A.RawID ) as Re,
B.IsAccessories
from DishInfo as A
left join RawMaterial as B on A.RawID=B.id
left join RawMaterialsType as C on B.RAWZS=C.id {0}", strwhere.ToString());
string key = "Cache_DishInfo_"+ model.DID;
list = Utils.Cache(key) as List<E_DishInfo>;
if (list == null)
{
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
list = conn.Query<E_DishInfo>(search.ToString(), model)?.ToList();
}
Utils.Cache(key, list, DateTime.Now.AddDays(1));
}
return list;
}
/// <summary>
/// 添加
/// </summary>
public int Add(E_DishInfo model)
{
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat(@"INSERT INTO [dbo].[DishInfo]
([DID],[Content],[RawID])
VALUES
(@DID,@Content,@RawID);select @@IDENTITY;");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
return Convert.ToInt32(conn.ExecuteScalar(search.ToString(), model));
}
}
/// <summary>
/// 删除
/// </summary>
public bool Del(E_DishInfo model)
{
//查询语句
StringBuilder strwhere = new StringBuilder();
if (model.id > 0) //记录ID
{
strwhere.AddWhere($"id={model.id}");
}
if (model.DID > 0) //菜品ID
{
strwhere.AddWhere($"DID={model.DID}");
}
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat($@"delete from DishInfo {strwhere.ToString()}");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
return conn.Execute(search.ToString(), model) > 0;
}
}
public bool Update(E_DishInfo model)
{
//查询语句
StringBuilder strwhere = new StringBuilder();
if (model.id > 0) //记录ID
{
strwhere.AddWhere($"id={model.id}");
}
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat($@"update DishInfo set numcontent=@numcontent {strwhere.ToString()}");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
return conn.Execute(search.ToString(), model) > 0;
}
}
}
}
|
using System;
using System.Collections.Generic;
using Fbtc.Domain.Entities;
using Fbtc.Domain.Interfaces.Services;
using Fbtc.Application.Interfaces;
using prmToolkit.Validation;
using Fbtc.Application.Helper;
namespace Fbtc.Application.Services
{
public class DescontoAnuidadeAtcApplication : IDescontoAnuidadeAtcApplication
{
private readonly IDescontoAnuidadeAtcService _descontoAnuidadeAtcService;
public DescontoAnuidadeAtcApplication(IDescontoAnuidadeAtcService descontoAnuidadeAtcService)
{
_descontoAnuidadeAtcService = descontoAnuidadeAtcService;
}
public IEnumerable<DescontoAnuidadeAtcDao> FindByFilters(int anuidadeId, string nomePessoa, bool? ativo, bool? comDesconto)
{
string _nome;
_nome = nomePessoa == "0" ? "" : nomePessoa;
if (_nome.IndexOf("%20") > 0)
_nome = _nome.Replace("%20", " ");
return _descontoAnuidadeAtcService.FindByFilters(anuidadeId, _nome, ativo, comDesconto);
}
public IEnumerable<DescontoAnuidadeAtc> GetAll()
{
return _descontoAnuidadeAtcService.GetAll();
}
public DescontoAnuidadeAtc GetDescontoAnuidadeAtcById(int id)
{
return _descontoAnuidadeAtcService.GetDescontoAnuidadeAtcById(id);
}
public DescontoAnuidadeAtcDao GetDescontoAnuidadeAtcDaoById(int id)
{
return _descontoAnuidadeAtcService.GetDescontoAnuidadeAtcDaoById(id);
}
public DescontoAnuidadeAtcDao GetDescontoAnuidadeAtcDaoByPessoaId(int pessoaId)
{
return _descontoAnuidadeAtcService.GetDescontoAnuidadeAtcDaoByPessoaId(pessoaId);
}
public IEnumerable<DescontoAnuidadeAtcDao> GetDescontoAnuidadeAtcDaoByAnuidadeId(int anuidadeId)
{
return _descontoAnuidadeAtcService.GetDescontoAnuidadeAtcDaoByAnuidadeId(anuidadeId);
}
public string Save(DescontoAnuidadeAtcDao d)
{
DescontoAnuidadeAtc _d = new DescontoAnuidadeAtc() {
DescontoAnuidadeAtcId = d.DescontoAnuidadeAtcId,
AssociadoId = d.AssociadoId,
ColaboradorId = d.ColaboradorId,
AnuidadeId = d.AnuidadeId,
AtcId = d.AtcId,
Observacao = Functions.AjustaTamanhoString(d.Observacao, 500),
NomeArquivoComprovante = Functions.AjustaTamanhoString(d.NomeArquivoComprovante, 100),
DtDesconto = d.DtDesconto,
DtCadastro = d.DtCadastro,
Ativo = d.Ativo
};
try
{
if (_d.DescontoAnuidadeAtcId == 0)
{
return _descontoAnuidadeAtcService.Insert(_d);
}
else
{
return _descontoAnuidadeAtcService.Update(_d.DescontoAnuidadeAtcId, _d);
}
}
catch (Exception ex)
{
throw ex;
}
}
public DescontoAnuidadeAtcDao GetDadosNovoDescontoAnuidadeAtcDao(int associadoId, int anuidadeId, int colaboradorPessoaId)
{
return _descontoAnuidadeAtcService.GetDadosNovoDescontoAnuidadeAtcDao(associadoId, anuidadeId, colaboradorPessoaId);
}
}
}
|
using UnityEngine;
public class Music : MonoBehaviour
{
Animator animator;
AudioSource mPlay;
float musicOn = 100.0F;
float musicOff = 0.0F;
private void Start()
{
mPlay = GetComponent<AudioSource>();
}
public void MusicOff()
{
mPlay.volume = musicOff;
}
public void MusicOn()
{
mPlay.volume = musicOn;
}
}
|
namespace Puppeteer.Core.Configuration
{
public enum ConfiguratorValueType
{
BOOL,
INT,
FLOAT,
STRING,
VECTOR2,
VECTOR3,
VECTOR2INT,
VECTOR3INT,
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using LeanEngine.Business;
using LeanEngine.Entity;
namespace Testing.Business
{
[TestFixture]
public class BidItemFlowTest
{
private BidItemFlow bidItemFlow;
private List<ItemFlow> itemFlows;
[SetUp]
public void SetUp()
{
bidItemFlow = new BidItemFlow();
itemFlows = new List<ItemFlow>();
ItemFlow itemFlow = new ItemFlow();
//测试时间过滤
itemFlow.Flow = new Flow();
itemFlow.ID = 1;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(2);//未到订单时间,过滤
itemFlows.Add(itemFlow);
//测试0需求过滤
itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 2;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 0;//需求为0,过滤
itemFlows.Add(itemFlow);
//测试无竞标规则时,默认返回第一行
itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 3;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 20;
itemFlows.Add(itemFlow);
itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 4;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 20;
itemFlows.Add(itemFlow);
//其它新增ID从5开始,在各自方法内执行
}
/// <summary>
/// 测试无竞标规则时,默认返回结果
/// </summary>
[Test]
public void getWinBidItemFlowTest1()
{
ItemFlow winBidItemFlow = bidItemFlow.getWinBidItemFlow(itemFlows);
//3、4行并列,3行在前,返回3
Assert.AreEqual(3, winBidItemFlow.ID);
}
/// <summary>
/// 测试配额竞标策略:1)首次执行时
/// </summary>
[Test]
public void getWinBidItemFlowTest2()
{
this.addNewBidItemFlows();
itemFlows[4].AcmlOrderedQty = 0;
itemFlows[5].AcmlOrderedQty = 0;
itemFlows[6].AcmlOrderedQty = 0;
ItemFlow winBidItemFlow = bidItemFlow.getWinBidItemFlow(itemFlows);
//首次执行时,返回配额比例最大的ID=5
Assert.AreEqual(5, winBidItemFlow.ID);
}
/// <summary>
/// 测试配额竞标策略:2)主算法,返回最能拉近平衡点
/// </summary>
[Test]
public void getWinBidItemFlowTest3()
{
this.addNewBidItemFlows();
itemFlows[4].AcmlOrderedQty = 60;
itemFlows[5].AcmlOrderedQty = 30;
itemFlows[6].AcmlOrderedQty = 8;//10为平衡点,故中标
ItemFlow winBidItemFlow = bidItemFlow.getWinBidItemFlow(itemFlows);
//主算法,返回最能拉近平衡点
Assert.AreEqual(7, winBidItemFlow.ID);
}
private void addNewBidItemFlows()
{
ItemFlow itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 5;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 20;
itemFlow.SupplyingRate = 60;//60%
itemFlows.Add(itemFlow);
itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 6;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 20;
itemFlow.SupplyingRate = 30;//30%
itemFlows.Add(itemFlow);
itemFlow = new ItemFlow();
itemFlow.Flow = new Flow();
itemFlow.ID = 7;
itemFlow.Flow.OrderTime = DateTime.Now.AddHours(-2);
itemFlow.ReqQty = 20;
itemFlow.SupplyingRate = 10;//10%
itemFlows.Add(itemFlow);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Web.Models.SearchModels.MD;
using com.Sconit.Web.Models;
using com.Sconit.Entity.MD;
using com.Sconit.Service;
namespace com.Sconit.Web.Controllers.MD
{
public class ItemKitController : WebAppBaseController
{
//
// GET: /ItemDiscontinue/
#region Properties
/// <summary>
/// Gets or sets the this.GeneMgr which main consider the address security
/// </summary>
//public IGenericMgr genericMgr { get; set; }
#endregion
#region hql
private static string ItemKitCountStatement = "select count(*) from ItemKit as i";
private static string selectStatement = "select i from ItemKit as i";
private static string isExistsStatement = @"select count(*) from ItemKit as i where i.KitItem=? and ChildItem=?";
#endregion
#region View
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult Index()
{
return View();
}
/// <summary>
/// List action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">ItemDiscontinue Search model</param>
/// <returns>return the result view</returns>
[GridAction]
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult List(GridCommand command, ItemKitSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
if (searchCacheModel.isBack == true)
{
ViewBag.Page = searchCacheModel.Command.Page==0 ? 1 : searchCacheModel.Command.Page;
}
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
/// <summary>
/// AjaxList action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel">ItemDiscontinue Search Model</param>
/// <returns>return the result Model</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult _AjaxList(GridCommand command, ItemKitSearchModel searchModel)
{
this.GetCommand(ref command, searchModel);
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel);
return PartialView(GetAjaxPageData<ItemKit>(searchStatementModel, command));
}
#endregion
#region Edit
public ActionResult New()
{
return View();
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult New(ItemKit itemKit)
{
itemKit.ChildItem = itemKit.ChildItemCode != null ? this.genericMgr.FindById<Item>(itemKit.ChildItemCode) : null;
if (itemKit.ChildItem != null) ModelState.Remove("ChildItem");
if (ModelState.IsValid)
{
itemKit.IsActive = true;
if (this.genericMgr.FindAll<long>(isExistsStatement, new object[] { itemKit.KitItem, itemKit.ChildItem })[0] > 0)
{
SaveErrorMessage(Resources.EXT.ControllerLan.Con_TheKitAlreadyExists);
}
else if (string.IsNullOrEmpty(itemKit.KitItem) || itemKit.ChildItem == null || itemKit.Qty==null )
{
SaveErrorMessage(Resources.EXT.ControllerLan.Con_PleaseFillCanNotBeEmpty);
}
else
{
genericMgr.CreateWithTrim(itemKit);
SaveSuccessMessage(Resources.EXT.ControllerLan.Con_KitCreatedSuccessfully);
return RedirectToAction("Edit/" + itemKit.Id);
}
}
// TempData["ItemDiscontinue"] = itemKit;
return View(itemKit);
}
[HttpGet]
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult Edit(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
return HttpNotFound();
}
ItemKit itemKit = this.genericMgr.FindById<ItemKit>(int.Parse(id));
return View(itemKit);
}
[SconitAuthorize(Permissions = "Url_ItemKit_View")]
public ActionResult _UpdateSave(ItemKit itemKit)
{
itemKit.ChildItem = itemKit.ChildItemCode != null ? this.genericMgr.FindById<Item>(itemKit.ChildItemCode) : null;
if (ModelState.IsValid)
{
if (this.genericMgr.FindAll<long>(isExistsStatement, new object[] { itemKit.KitItem, itemKit.ChildItem })[0] > 0)
{
SaveErrorMessage(Resources.EXT.ControllerLan.Con_TheKitAlreadyExists);
}
else
{
this.genericMgr.UpdateWithTrim(itemKit);
SaveSuccessMessage(Resources.EXT.ControllerLan.Con_KitUpdatedSuccessfully);
return RedirectToAction("List");
}
}
return RedirectToAction("Edit/" + itemKit.Id);
}
#endregion
#region private
private SearchStatementModel PrepareSearchStatement(GridCommand command, ItemKitSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddEqStatement("KitItem", searchModel.KitItem, "i", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("ChildItem.Code", searchModel.ChildItem, "i", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("CreateUserName", searchModel.CreateUserName, "i", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("IsActive", searchModel.IsActive, "i", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = ItemKitCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
}
}
|
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.Interfaces
{
public interface IAppServicoServentiasOutras : IAppServicoBase<ServentiasOutras>
{
ServentiasOutras ObterServentiaPorCodigo(int codigo);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.