text stringlengths 13 6.01M |
|---|
using jaytwo.Common.Extensions;
using jaytwo.Common.Parse;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace jaytwo.Common.Test.Parse
{
[TestFixture]
public partial class ParseUtilityTests
{
private static IEnumerable<TestCaseData> ParseDateTimeAllTestValues()
{
yield return new TestCaseData("6/1/2012").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("6-1-2012").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("2012-06-01").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("2012-06-01T02:03:04").Returns(new DateTime(2012, 6, 1, 2, 3, 4));
yield return new TestCaseData("June 1, 2012").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("Jun 1, 2012").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("Jun 1 2012").Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("June 1 2012 02:03:04").Returns(new DateTime(2012, 6, 1, 2, 3, 4));
yield return new TestCaseData("June 1 2012 02:03:04 PM").Returns(new DateTime(2012, 6, 1, 14, 3, 4));
yield return new TestCaseData("Fri Jun 1 2012 02:03:04 PM").Returns(new DateTime(2012, 6, 1, 14, 3, 4));
yield return new TestCaseData("Friday June 1 2012 02:03:04 PM").Returns(new DateTime(2012, 6, 1, 14, 3, 4));
yield return new TestCaseData("Friday, June 1, 2012 02:03:04 PM").Returns(new DateTime(2012, 6, 1, 14, 3, 4));
yield return new TestCaseData("0").Throws(typeof(FormatException));
yield return new TestCaseData(null).Throws(typeof(ArgumentNullException));
yield return new TestCaseData("").Throws(typeof(FormatException));
yield return new TestCaseData("foo").Throws(typeof(FormatException));
yield return new TestCaseData("06-01-2012", DateTimeStyles.AssumeLocal).Returns(new DateTime(2012, 6, 1, 0, 0, 0, DateTimeKind.Local));
yield return new TestCaseData("01-06-2012", new CultureInfo("pt-BR")).Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("06-01-2012", new CultureInfo("en-US")).Returns(new DateTime(2012, 6, 1));
yield return new TestCaseData("01-06-2012 02:03:04", DateTimeStyles.AssumeLocal, new CultureInfo("pt-BR")).Returns(new DateTime(2012, 6, 1, 2, 3, 4, DateTimeKind.Local));
//yield return new TestCaseData("06-01-2012 02:03:04", DateTimeStyles.AssumeUniversal, new CultureInfo("en-US")).Returns(new DateTime(2012, 6, 1, 2, 3, 4, DateTimeKind.Utc));
}
private static IEnumerable<TestCaseData> ParseDateTimeGoodTestValues()
{
foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseDateTimeAllTestValues()))
if (testCase.HasExpectedResult)
yield return testCase;
}
private static IEnumerable<TestCaseData> ParseDateTimeBadTestValues()
{
foreach (var testCase in TestUtility.GetTestCasesWithArgumentTypes<string>(ParseDateTimeAllTestValues()))
if (testCase.ExpectedException != null)
yield return testCase;
}
private static IEnumerable<TestCaseData> TryParseDateTimeBadTestValues()
{
foreach (var testCase in ParseDateTimeBadTestValues())
yield return new TestCaseData(testCase.Arguments).Returns(null);
}
private static IEnumerable<TestCaseData> ParseDateTime_With_styles_GoodTestValues()
{
return TestUtility.GetTestCasesWithArgumentTypes<string, DateTimeStyles>(ParseDateTimeAllTestValues());
}
private static IEnumerable<TestCaseData> ParseDateTime_With_formatProvider_GoodTestValues()
{
return TestUtility.GetTestCasesWithArgumentTypes<string, IFormatProvider>(ParseDateTimeAllTestValues());
}
private static IEnumerable<TestCaseData> ParseDateTime_With_styles_formatProvider_GoodTestValues()
{
return TestUtility.GetTestCasesWithArgumentTypes<string, DateTimeStyles, IFormatProvider>(ParseDateTimeAllTestValues());
}
[Test]
[TestCaseSource("ParseDateTimeGoodTestValues")]
public DateTime ParseUtility_ParseDateTime(string stringValue)
{
return ParseUtility.ParseDateTime(stringValue);
}
[Test]
[ExpectedException]
[TestCaseSource("ParseDateTimeBadTestValues")]
public DateTime ParseUtility_ParseDateTime_Exceptions(string stringValue)
{
return ParseUtility.ParseDateTime(stringValue);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_formatProvider_GoodTestValues")]
public DateTime ParseUtility_ParseDateTime_With_styles_formatProvider(string stringValue, DateTimeStyles styles, IFormatProvider formatProvider)
{
return ParseUtility.ParseDateTime(stringValue, styles, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_GoodTestValues")]
public DateTime ParseUtility_ParseDateTime_With_styles(string stringValue, DateTimeStyles styles)
{
return ParseUtility.ParseDateTime(stringValue, styles);
}
[Test]
[TestCaseSource("ParseDateTime_With_formatProvider_GoodTestValues")]
public DateTime ParseUtility_ParseDateTime_With_formatProvider(string stringValue, IFormatProvider formatProvider)
{
return ParseUtility.ParseDateTime(stringValue, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTimeGoodTestValues")]
[TestCaseSource("TryParseDateTimeBadTestValues")]
public DateTime? ParseUtility_TryParseDateTime(string stringValue)
{
return ParseUtility.TryParseDateTime(stringValue);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_formatProvider_GoodTestValues")]
public DateTime? ParseUtility_TryParseDateTime_With_styles_formatProvider(string stringValue, DateTimeStyles styles, IFormatProvider formatProvider)
{
return ParseUtility.TryParseDateTime(stringValue, styles, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_GoodTestValues")]
public DateTime? ParseUtility_TryParseDateTime_With_styles(string stringValue, DateTimeStyles styles)
{
return ParseUtility.TryParseDateTime(stringValue, styles);
}
[Test]
[TestCaseSource("ParseDateTime_With_formatProvider_GoodTestValues")]
public DateTime? ParseUtility_TryParseDateTime_With_formatProvider(string stringValue, IFormatProvider formatProvider)
{
return ParseUtility.TryParseDateTime(stringValue, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTimeGoodTestValues")]
public DateTime StringExtensions_ParseDateTime(string stringValue)
{
return stringValue.ParseDateTime();
}
[Test]
[ExpectedException]
[TestCaseSource("ParseDateTimeBadTestValues")]
public DateTime StringExtensions_ParseDateTime_Exceptions(string stringValue)
{
return stringValue.ParseDateTime();
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_formatProvider_GoodTestValues")]
public DateTime StringExtensions_ParseDateTime_With_styles_formatProvider(string stringValue, DateTimeStyles styles, IFormatProvider formatProvider)
{
return stringValue.ParseDateTime(styles, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_GoodTestValues")]
public DateTime StringExtensions_ParseDateTime_With_styles(string stringValue, DateTimeStyles styles)
{
return stringValue.ParseDateTime(styles);
}
[Test]
[TestCaseSource("ParseDateTime_With_formatProvider_GoodTestValues")]
public DateTime StringExtensions_ParseDateTime_With_formatProvider(string stringValue, IFormatProvider formatProvider)
{
return stringValue.ParseDateTime(formatProvider);
}
[Test]
[TestCaseSource("ParseDateTimeGoodTestValues")]
[TestCaseSource("TryParseDateTimeBadTestValues")]
public DateTime? StringExtensions_TryParseDateTime(string stringValue)
{
return stringValue.TryParseDateTime();
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_formatProvider_GoodTestValues")]
public DateTime? StringExtensions_TryParseDateTime_With_styles_formatProvider(string stringValue, DateTimeStyles styles, IFormatProvider formatProvider)
{
return stringValue.TryParseDateTime(styles, formatProvider);
}
[Test]
[TestCaseSource("ParseDateTime_With_styles_GoodTestValues")]
public DateTime? StringExtensions_TryParseDateTime_With_styles(string stringValue, DateTimeStyles styles)
{
return stringValue.TryParseDateTime(styles);
}
[Test]
[TestCaseSource("ParseDateTime_With_formatProvider_GoodTestValues")]
public DateTime? StringExtensions_TryParseDateTime_With_formatProvider(string stringValue, IFormatProvider formatProvider)
{
return stringValue.TryParseDateTime(formatProvider);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CTCI.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Web.Script.Serialization;
namespace CTCI.Controllers
{
public class FieldController : Controller
{
private CtciMachineEntities db = new CtciMachineEntities();
private CtciMachineCMSEntities db_CMS = new CtciMachineCMSEntities();
public class FieldQ
{
public int FieldID { get; set; }
public string ProjectNo { get; set; }
public string FieldState { get; set; }
public string FieldName { get; set; }
public string FieldManager { get; set; }
public string StartDate { get; set; }
public DateTime StartDate_ { get; set; }
public string EndDate { get; set; }
public DateTime EndDate_ { get; set; }
public string ControlEngineer { get; set; }
}
public class FieldModel
{
public int FieldID { get; set; }
public string ProjectNo { set; get; }
public string FieldName { set; get; }
public string FieldManager { set; get; }
public DateTime? StartDate { set; get; }
public DateTime? EndDate { set; get; }
public string ControlEngineer { set; get; }
public string ControlEngineerName { set; get; }
}
string Get_Field_State(DateTime start, DateTime end)
{
DateTime now = DateTime.Now;
if (now < start)
return "未開工";
else if (now > end.AddDays(1))
return "已結案";
else
return "工作中";
}
[HttpPost]
[Authorize]
public JsonResult Search(JQueryDataTablesModel jQueryDataTablesModel)
{
var startIndex = jQueryDataTablesModel.iDisplayStart;
var pageSize = jQueryDataTablesModel.iDisplayLength;
var sortedColumns = jQueryDataTablesModel.GetSortedColumns();
var totalRecordCount = 0;
var searchRecordCount = 0;
var searchString = jQueryDataTablesModel.sSearch;
var repo = from i in db.c_Field
select new FieldQ()
{
FieldID = i.FieldID,
ProjectNo = i.ProjectNo,
FieldName = i.FieldName,
FieldManager = i.FieldManager,
StartDate_ = i.StartDate,
EndDate_ = i.EndDate,
ControlEngineer = i.ControlEngineer
};
var data = repo.ToList();
foreach (var o in data)
{
o.FieldState = Get_Field_State(o.StartDate_, o.EndDate_);
o.StartDate = o.StartDate_.ToString("yyyy-MM-dd");
o.EndDate = o.EndDate_.ToString("yyyy-MM-dd");
}
//欄位搜尋
if (jQueryDataTablesModel.sSearch_[2] != "")
data = data.Where(x => x.ProjectNo == jQueryDataTablesModel.sSearch_[2]).ToList();
if (jQueryDataTablesModel.sSearch_[3] != "")
data = data.Where(x => x.FieldState == jQueryDataTablesModel.sSearch_[3]).ToList();
string sStartDate = jQueryDataTablesModel.sSearch_[5];
string sEndDate = jQueryDataTablesModel.sSearch_[6];
if (sStartDate != "")
{
data = data.Where(x => x.StartDate_ > Convert.ToDateTime(sStartDate)).ToList();
}
if (sEndDate != "")
{
data = data.Where(x => x.EndDate_ < Convert.ToDateTime(sEndDate)).ToList();
}
totalRecordCount = data.Count();
if (!string.IsNullOrWhiteSpace(searchString))
{
data = data.Where(c =>
c.ProjectNo.ToLower().Contains(searchString.ToLower()) ||
c.StartDate.ToLower().Contains(searchString.ToLower()) ||
c.EndDate.ToLower().Contains(searchString.ToLower()) ||
c.FieldState.ToLower().Contains(searchString.ToLower())
).ToList();
}
searchRecordCount = data.Count();
if (sortedColumns != null && sortedColumns.Count() > 0)
{
var sortedColumn = sortedColumns[0];
if (sortedColumn.Direction == SortingDirection.Ascending)
{
data = data.OrderBy(r => r.GetType().GetProperty(sortedColumn.PropertyName).GetValue(r, null)).ToList();
}
else
{
data = data.OrderByDescending(r => r.GetType().GetProperty(sortedColumn.PropertyName).GetValue(r, null)).ToList();
}
}
else
{
data = data.OrderBy(x => x.ProjectNo).ToList();
}
data = data.Skip(startIndex).Take(pageSize).ToList();
return Json(new JQueryDataTablesResponse<FieldQ>(
items: data,
totalRecords: totalRecordCount,
totalDisplayRecords: searchRecordCount,
sEcho: jQueryDataTablesModel.sEcho)
);
}
[Authorize]
public ActionResult Index()
{
ViewBag.UserName = User.Identity.Name;
ViewBag.addEnable = User.IsInRole("系統管理者");
return View();
}
[Authorize(Roles = "系統管理者")]
public ActionResult Create()
{
ViewBag.UserName = User.Identity.Name;
return View();
}
[Authorize]
public ActionResult Edit(int? id)
{
var Field = db.c_Field.FirstOrDefault(x => x.FieldID == id);
if (Field == null)
return RedirectToAction("Index");
FieldModel FieldModel = new FieldModel()
{
FieldID = Field.FieldID,
ProjectNo = Field.ProjectNo,
FieldName = Field.FieldName,
FieldManager = Field.FieldManager,
StartDate = Field.StartDate,
EndDate = Field.EndDate,
ControlEngineer = Field.ControlEngineer,
ControlEngineerName = db.AspNetUsers.First(x => x.UserName == Field.ControlEngineer).NickName
};
ViewBag.UserName = User.Identity.Name;
ViewBag.editEnable = User.IsInRole("系統管理者");
return View(FieldModel);
}
private bool CheckModel(FieldModel model, out string reason)
{
reason = "";
if (model.StartDate == null || model.EndDate == null)
reason += reason == "" ? "缺少有效期限" : ";\n" + "缺少有效期限";
if (string.IsNullOrEmpty(model.FieldManager))
reason += reason == "" ? "缺少工地經理" : ";\n" + "缺少工地經理";
if (string.IsNullOrEmpty(model.FieldName))
reason += reason == "" ? "缺少工地名稱" : ";\n" + "缺少工地名稱";
if (string.IsNullOrEmpty(model.FieldName))
reason += reason == "" ? "缺少工地名稱" : ";\n" + "缺少工地名稱";
if (string.IsNullOrEmpty(model.ControlEngineer))
reason += reason == "" ? "缺少調度工程師" : ";\n" + "缺少調度工程師";
if(model.FieldID == 0 && db.c_Field.Any(x => x.ProjectNo == model.ProjectNo))
reason += reason == "" ? "Project No已存在" : ";\n" + "Project No已存在";
//todo 驗證CMS
if (false)
reason += reason == "" ? "Project No驗證失敗" : ";\n" + "Project No驗證失敗";
if (reason != "")
return false;
return true;
}
[HttpPost]
[Authorize(Roles = "系統管理者")]
public async System.Threading.Tasks.Task<ActionResult> AddField(FieldModel model)
{
string check_false = "";
if (!CheckModel(model, out check_false))
return Json(new { Success = false, Message = check_false });
//確保調度工程師存在Local User與權限
var result = await new FieldManageController().CreateUserAccount(model.ControlEngineer, model.ControlEngineerName);
if (!result.Succeed)
return Json(new { Success = false, Message = "調度工程師驗證失敗" });
new FieldManageController().UpdateRole(model.ControlEngineer, model.ControlEngineerName);
//insert field
c_Field Field = new c_Field()
{
ProjectNo = model.ProjectNo,
FieldName = model.FieldName,
FieldManager = model.FieldManager,
StartDate = (DateTime)model.StartDate,
EndDate = (DateTime)model.EndDate,
ControlEngineer = model.ControlEngineer,
};
db.c_Field.Add(Field);
db.SaveChanges();
string powedId = db.c_Power.First(x => x.PowerName == "調度工程師").PowerID;
c_FieldUser FieldUser = new c_FieldUser()
{
PowerID = powedId,
UserName = model.ControlEngineer,
FieldID = Field.FieldID,
IsEnable = 1
};
db.c_FieldUser.Add(FieldUser);
db.SaveChanges();
return Json(new { Success = true, Message = "OK" });
}
[HttpPost]
[Authorize(Roles = "系統管理者")]
public async System.Threading.Tasks.Task<ActionResult> UpdateField(FieldModel model)
{
string check_false = "";
if (!CheckModel(model, out check_false))
return Json(new { Success = false, Message = check_false });
c_Field Field = db.c_Field.FirstOrDefault(x => x.FieldID == model.FieldID);
if(Field == null)
return Json(new { Success = false, Message = "查無此工地" });
////確保調度工程師存在Local User與權限
var result = await new FieldManageController().CreateUserAccount(model.ControlEngineer, model.ControlEngineerName);
if (!result.Succeed)
return Json(new { Success = false, Message = "調度工程師驗證失敗" });
new FieldManageController().UpdateRole(model.ControlEngineer, model.ControlEngineerName);
//insert field
Field.FieldName = model.FieldName;
Field.FieldManager = model.FieldManager;
Field.StartDate = (DateTime)model.StartDate;
Field.EndDate = (DateTime)model.EndDate;
Field.ControlEngineer = model.ControlEngineer;
db.SaveChanges();
//update fielduser
string powedId = db.c_Power.First(x => x.PowerName == "調度工程師").PowerID;
if (!db.c_FieldUser.Any(x => x.PowerID != powedId && x.FieldID == model.FieldID && x.UserName == model.ControlEngineer)) {
db.c_FieldUser.RemoveRange(
db.c_FieldUser.Where(x =>
x.UserName == model.ControlEngineer &&
x.FieldID == model.FieldID &&
x.PowerID != powedId)
);
db.SaveChanges();
var FieldUser = db.c_FieldUser.FirstOrDefault(x => x.FieldID == model.FieldID && x.PowerID == powedId);
if (FieldUser != null)
{
FieldUser.UserName = model.ControlEngineer;
FieldUser.FieldGroupID = null;
FieldUser.IsEnable = 1;
}
else
{
c_FieldUser newFieldUser = new c_FieldUser()
{
PowerID = powedId,
UserName = model.ControlEngineer,
FieldID = Field.FieldID,
IsEnable = 1
};
db.c_FieldUser.Add(newFieldUser);
}
db.SaveChanges();
}
return Json(new { Success = true, Message = "OK" });
}
[HttpPost]
[Authorize(Roles = "系統管理者")]
public ActionResult GetProjectNo(string ProjectNo)
{
if(string.IsNullOrEmpty(ProjectNo))
return Json(new { Success = false, Message = "請輸入Project No" });
if (db.c_Field.Any(x => x.ProjectNo == ProjectNo))
return Json(new { Success = false, Message = "已有此工地" });
//todo CMS
var CMS = db_CMS.View_CMS_Project.FirstOrDefault(x => x.PrjNo == ProjectNo);
if (CMS == null)
return Json(new { Success = false, Message = "查無此工地" });
var CMSdata = new
{
ProNo = CMS.PrjNo,
FieldName = CMS.Prj_CName,
FieldManager = CMS.PrjMagName,
StartDate = CMS.ConBegDate == null ? "" : ((DateTime)CMS.ConBegDate).ToString("yyyy-MM-dd"),
EndDate = CMS.ConEndDate == null ? "" : ((DateTime)CMS.ConEndDate).ToString("yyyy-MM-dd")
};
//var CMSdata = new
//{
// ProNo = "ProjectA",
// FieldName = "test",
// FieldManager = "test",
// StartDate = "2016-01-01",
// EndDate = "2016-02-02"
//};
return Json(new { Success = true, Message = "OK" , data = CMSdata });
}
[HttpPost]
[Authorize(Roles = "系統管理者")]
public ActionResult GetCE(string UserName)
{
if(string.IsNullOrEmpty(UserName))
return Json(new { Success = false, Message = "請輸入職編", data = "" });
var local_user = db.AspNetUsers.FirstOrDefault(x => x.UserName == UserName);
if (local_user != null)
{
var CE = new
{
username = local_user.UserName,
nickname = local_user.NickName
};
return Json(new { Success = true, Message = "OK", data = CE });
}
SystemManageController.UserRole UserRole = new SystemManageController.UserRole();
UserRole.UserName = UserName;
var j = new SystemManageController().QueryRole_(UserRole);
if(j == null)
{
return Json(new { Success = false, Message = "驗證AD帳號失敗", data = "" });
}
else
{
var CE = new
{
username = UserName,
nickname = j.Name
};
return Json(new { Success = true, Message = "OK", data = CE });
}
}
}
}
|
using System;
namespace Petar.IFMO.sem_2.programming.lab_1
{
class Book
{
public String name;
public String author;
public String annotation;
public String ISBN;
public String publicationDate;
public Book(String name, String author, String annotation, String ISBN, String publicationDate)
{
this.name = name;
this.author = author;
this.annotation = annotation;
this.ISBN = ISBN;
this.publicationDate = publicationDate;
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley.Tools;
using StardewValley;
using StardewValley.Menus;
namespace MultitoolMod.Framework
{
public class PickaxeBlade : Pickaxe
{
public PickaxeBlade()
{
}
public override void DoFunction(GameLocation location, int x, int y, int power, Farmer who)
{
int x_pixels = (int)Game1.currentCursorTile.X * Game1.tileSize;
int y_pixels = (int)Game1.currentCursorTile.Y * Game1.tileSize;
base.DoFunction(location, x_pixels, y_pixels, power, who);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace CRL
{
public partial class DBExtend
{
#region delete
/// <summary>
/// 按条件删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="where"></param>
/// <returns></returns>
public int Delete<T>(string where) where T : IModel,new()
{
CheckTableCreated<T>();
string table = TypeCache.GetTableName(typeof(T));
string sql = _DBAdapter.GetDeleteSql(table, where);
sql = _DBAdapter.SqlFormat(sql);
int n = helper.Execute(sql);
ClearParame();
return n;
}
/// <summary>
/// 按主键删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <returns></returns>
public int Delete<T>(int id) where T : IModelBase, new()
{
return Delete<T>(b => b.Id == id);
}
/// <summary>
/// 指定条件删除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression"></param>
/// <returns></returns>
public int Delete<T>(Expression<Func<T, bool>> expression) where T : IModel, new()
{
LambdaQuery<T> query = new LambdaQuery<T>(this,false);
string condition = query.FormatExpression(expression);
query.FillParames(this);
return Delete<T>(condition);
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CanvasGroup))]
public class PanelManager : MonoBehaviour
{
private Panel[] _panels;
public Panel mainPanel;
private Stack<Panel> openedPanels = new Stack<Panel>();
private CanvasGroup _canvasGroup;
private float lastBack;
private void Awake()
{
_canvasGroup = GetComponent<CanvasGroup>();
_panels = GetComponentsInChildren<Panel>();
foreach (var panel in _panels)
{
panel.onOpen.AddListener(()=>OnPanelOpened(panel));
}
_canvasGroup.enabled = true;
_canvasGroup.alpha = 1;
}
public void OnPanelOpened(Panel panel)
{
//print($"Panel {panel.name} opened ");
if(panel.saveInHistory)
openedPanels.Push(panel);
foreach (var p in _panels)
{
if(p == panel)
continue;
p.ManagerClose();
}
PrintStack();
}
public void OpenMainPanel()
{
if(!mainPanel)
return;
mainPanel.Open();
}
public void Back()
{
if(Time.time - lastBack < 0.1f)
return;
lastBack = Time.time;
print("Back");
if(openedPanels.Count>=1){}
openedPanels.Pop().Close();
if(openedPanels.Count ==0)
return;
openedPanels.Pop().Open();
PrintStack();
}
public void CloseAll()
{
foreach (var p in _panels)
{
p.Close();
}
}
public void PrintStack()
{
Panel[] panels = openedPanels.ToArray();
string panelsInStack = "Panels in Stack: ";
foreach (var panel in panels)
{
panelsInStack += panel.name + ", ";
}
print(panelsInStack);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace ScriptableObjectFramework.Systems.ApplicationManager
{
[CreateAssetMenu(fileName = "NewApplicationManager", menuName = "Scriptable Objects/Systems/ApplicationManager")]
public class ApplicationManager : ScriptableObject
{
public UnityEvent OnApplicationWantsToQuit;
public UnityEvent OnApplicationQuitting;
public float TimeScale
{
get
{
return Time.timeScale;
}
set
{
Time.timeScale = value;
}
}
public bool CursorVisible
{
get
{
return Cursor.visible;
}
set
{
Cursor.visible = value;
}
}
public CursorLockMode CursorLockMode
{
get
{
return Cursor.lockState;
}
set
{
Cursor.lockState = value;
}
}
private void OnEnable()
{
Application.wantsToQuit += Application_wantsToQuit;
Application.quitting += Application_quitting;
}
private bool Application_wantsToQuit()
{
OnApplicationWantsToQuit.Invoke();
return true;
}
private void Application_quitting()
{
OnApplicationQuitting.Invoke();
}
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}
|
using System.Collections.Generic;
using AtomosZ.Cubeshots.MusicCommander;
using AtomosZ.Cubeshots.Waves;
using AtomosZ.Cubeshots.WeaponSystems;
using UnityEngine;
namespace AtomosZ.Cubeshots.PlayerLibs
{
public class PlayerCube : MonoBehaviour, IShmupActor
{
private const int BASIC_BULLET_STORE_SIZE = 100;
public float speed = 10f;
public GameObject bulletPrefab;
[HideInInspector]
public Vector2 inputVector;
[HideInInspector]
public bool fireDown;
[HideInInspector]
public PlayerController controller;
private Queue<BasicBullet> bulletStore;
private bool isEighthBeat;
private bool isQuarterBeat;
private bool isHalfBeat;
private bool isFullBeat;
private Rigidbody2D body;
private MusicalCommander musicCommander;
private Health health;
void Start()
{
body = GetComponent<Rigidbody2D>();
musicCommander = MusicalCommander.instance;
health = GetComponent<Health>();
health.Reset();
bulletStore = new Queue<BasicBullet>();
for (int i = 0; i < BASIC_BULLET_STORE_SIZE; ++i)
{
GameObject bulletGO = Instantiate(
bulletPrefab, transform.position,
Quaternion.identity, musicCommander.bulletStore);
bulletGO.tag = Tags.PLAYER_BULLET;
BasicBullet bullet = bulletGO.GetComponent<BasicBullet>();
bullet.SetOwner(this);
bulletStore.Enqueue(bullet);
}
}
public void SetColor(Color color)
{
GetComponent<SpriteRenderer>().color = color;
}
public void TakeDamage(int damage)
{
if (health.TakeDamage(damage))
{
gameObject.SetActive(false);
}
}
public void BulletBecameInactive(BasicBullet bullet)
{
bullet.transform.localPosition = Wave.storePosition;
bulletStore.Enqueue(bullet);
}
public void IsEighthBeat()
{
isEighthBeat = true;
}
public void IsQuarterBeat()
{
isQuarterBeat = true;
}
public void IsHalfBeat()
{
isHalfBeat = true;
}
public void IsFullBeat()
{
isFullBeat = true;
}
void Update()
{
controller.UpdateCommands();
if (fireDown)
{
if (isEighthBeat)
{
BasicBullet bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Vector2.up, 0);
}
if (isQuarterBeat)
{
BasicBullet bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, 15) * Vector2.up, 0);
bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, -15) * Vector2.up, 0);
}
if (isHalfBeat)
{
BasicBullet bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, 45) * Vector2.up, 0);
bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, -45) * Vector2.up, 0);
}
if (isFullBeat)
{
BasicBullet bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, 90) * Vector2.up, 0);
bullet = GetNextBullet();
if (bullet != null)
bullet.Fire(transform.position, Quaternion.Euler(0, 0, -90) * Vector2.up, 0);
}
fireDown = false;
}
isEighthBeat = false;
isQuarterBeat = false;
isHalfBeat = false;
isFullBeat = false;
}
void FixedUpdate()
{
controller.FixedUpdateCommands();
body.velocity = inputVector * Time.deltaTime * speed;
inputVector = Vector2.zero;
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("Trigger");
}
private BasicBullet GetNextBullet()
{
if (bulletStore.Count == 0)
Debug.LogError(name + " needs a larger bullet store!!");
return bulletStore.Dequeue();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Otiport.API.Contract.Request.Medicines
{
public class AddMedicineRequest : RequestBase
{
public string Title { get; set; }
public string Description { get; set; }
}
}
|
using System.Net;
namespace Net.UdpServer
{
/// <summary>
/// Default request context factory
/// </summary>
public class DefaultRequestContextFactory : IRequestContextFactory
{
/// <inheritdoc/>
public RequestContext Create(IPEndPoint remote, byte[] payload, string contextId)
{
return new RequestContext(remote, payload, contextId);
}
}
}
|
using System;
using UnityEngine.Events;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// None generic Unity Event of type `BoolPair`. Inherits from `UnityEvent<BoolPair>`.
/// </summary>
[Serializable]
public sealed class BoolPairUnityEvent : UnityEvent<BoolPair> { }
}
|
using System;
using SharpArch.Domain.DomainModel;
using Profiling2.Domain.Prf;
namespace Profiling2.Domain.Scr.PersonRecommendation
{
public class ScreeningRequestPersonRecommendationHistory : Entity
{
public virtual ScreeningRequestPersonRecommendation ScreeningRequestPersonRecommendation { get; set; }
public virtual ScreeningStatus ScreeningStatus { get; set; }
public virtual DateTime DateStatusReached { get; set; }
public virtual bool Archive { get; set; }
public virtual string Notes { get; set; }
public virtual AdminUser AdminUser { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(Rigidbody))]
public class PlayerManager : MonoBehaviour
{
[SerializeField] private Transform _spellBag;
private GameObject[] _spells;
void UpdateSpells()
{
int i = 0;
foreach (Transform child in _spellBag)
{
_spells[i] = child.gameObject;
Debug.Log(i);
i++;
}
}
void Start()
{
}
void Update()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
namespace MemoryLeakSample
{
public class DammyViewController : UIViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
var dismissViewButton = new UIButton();
dismissViewButton.TouchUpInside += DismissViewButton_TouchUpInside;
}
void DismissViewButton_TouchUpInside(object sender, EventArgs e)
=> DismissViewController(true, null);
}
} |
using Terraria.ID;
using Terraria.ModLoader;
namespace Intalium.Items.Materials
{
public class GreatAlloy : ModItem //Zielony
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Great Alloy");
Tooltip.SetDefault("Magical steel, sealed by the ancestors of the Patapon race that flourished in ancient times.");
}
public override void SetDefaults()
{
item.value = 30000;
item.rare = 4;
item.maxStack = 999;
item.width = 34;
item.height = 39;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.HallowedBar, 1);
recipe.AddIngredient(ItemID.ChlorophyteBar, 1);
recipe.AddIngredient(ItemID.SpectreBar, 1);
recipe.AddIngredient(ItemID.ShroomiteBar, 1);
recipe.AddIngredient(null, "Shine", 1);
recipe.AddTile(TileID.AdamantiteForge);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
using NotSoSmartSaverAPI.DTO.IncomeDTO;
using NotSoSmartSaverAPI.ModelsGenerated;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace NotSoSmartSaverAPI.Interfaces
{
public interface IIncomeProcessor
{
public Task<List<Income>> GetAllIncomes(GetAllDTO data);
public Task<List<IncomeSumByOwnerDTO>> GetSumOfIncomesByOwner(IncomesByOwnerDTO data);
public Task<string> AddIncome(NewIncomeDTO data);
public Task<bool> RemoveIncome(string incomeId);
public Task<bool> ModifyIncome(ModifyIncomeDTO data);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using VEE.Models;
using VEE.Models.BasedeDatos;
namespace VEE.Controllers
{
public class DetallePlanillasController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: DetallePlanillas
public async Task<ActionResult> Index()
{
return View(await db.DetallePlanillas.ToListAsync());
}
// GET: DetallePlanillas/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DetallePlanilla detallePlanilla = await db.DetallePlanillas.FindAsync(id);
if (detallePlanilla == null)
{
return HttpNotFound();
}
return View(detallePlanilla);
}
// GET: DetallePlanillas/Create
public ActionResult Create()
{
return View();
}
// POST: DetallePlanillas/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id")] DetallePlanilla detallePlanilla)
{
if (ModelState.IsValid)
{
db.DetallePlanillas.Add(detallePlanilla);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(detallePlanilla);
}
// GET: DetallePlanillas/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DetallePlanilla detallePlanilla = await db.DetallePlanillas.FindAsync(id);
if (detallePlanilla == null)
{
return HttpNotFound();
}
return View(detallePlanilla);
}
// POST: DetallePlanillas/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id")] DetallePlanilla detallePlanilla)
{
if (ModelState.IsValid)
{
db.Entry(detallePlanilla).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(detallePlanilla);
}
// GET: DetallePlanillas/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DetallePlanilla detallePlanilla = await db.DetallePlanillas.FindAsync(id);
if (detallePlanilla == null)
{
return HttpNotFound();
}
return View(detallePlanilla);
}
// POST: DetallePlanillas/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
DetallePlanilla detallePlanilla = await db.DetallePlanillas.FindAsync(id);
db.DetallePlanillas.Remove(detallePlanilla);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TaskManager_2._1
{
public class Proc
{
public string Name { get; set; }
public string Memory { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using StardewModdingAPI;
namespace Entoarox.AdvancedLocationLoader.Configs
{
internal class Compound
{
/*********
** Accessors
*********/
public IDictionary<IContentPack, Tilesheet[]> SeasonalTilesheets { get; }
public Tile[] DynamicTiles { get; }
public Property[] DynamicProperties { get; }
public Warp[] DynamicWarps { get; }
public Conditional[] Conditionals { get; }
public TeleporterList[] Teleporters { get; }
public ShopConfig[] Shops { get; }
/*********
** Public methods
*********/
public Compound(IDictionary<IContentPack, Tilesheet[]> seasonalTilesheets, IEnumerable<Tile> dynamicTiles, IEnumerable<Property> dynamicProperties, IEnumerable<Warp> dynamicWarps, IEnumerable<Conditional> conditionals, IEnumerable<TeleporterList> teleporters, IEnumerable<ShopConfig> shops)
{
this.SeasonalTilesheets = seasonalTilesheets;
this.DynamicTiles = dynamicTiles.ToArray();
this.DynamicProperties = dynamicProperties.ToArray();
this.DynamicWarps = dynamicWarps.ToArray();
this.Conditionals = conditionals.ToArray();
this.Teleporters = teleporters.ToArray();
this.Shops = shops.ToArray();
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using UBaseline.Core.Media;
using UBaseline.Core.Node;
using Uintra.Core.Controls.LightboxGallery;
using Uintra.Core.Member.Entities;
using Uintra.Core.Member.Services;
using Uintra.Features.Groups.Links;
using Uintra.Features.Groups.Models;
using Uintra.Features.Groups.Services;
using Uintra.Features.Media;
using Uintra.Features.Media.Images.Helpers.Contracts;
using Uintra.Features.Permissions;
using Uintra.Features.Permissions.Interfaces;
using Uintra.Features.Permissions.Models;
using Uintra.Infrastructure.Constants;
using Uintra.Infrastructure.Extensions;
namespace Uintra.Features.Groups.Helpers
{
public class GroupHelper : IGroupHelper
{
private readonly IGroupService _groupService;
private readonly IGroupLinkProvider _groupLinkProvider;
private readonly IGroupMemberService _groupMemberService;
private readonly IIntranetMemberService<IntranetMember> _memberService;
private readonly IImageHelper _imageHelper;
private readonly IMediaModelService _mediaModelService;
private readonly ILightboxHelper _lightboxHelper;
private readonly INodeModelService _nodeModelService;
private readonly IPermissionsService _permissionsService;
public GroupHelper(
IGroupService groupService,
IGroupLinkProvider groupLinkProvider,
IGroupMemberService groupMemberService,
IIntranetMemberService<IntranetMember> memberService,
IImageHelper imageHelper,
IMediaModelService mediaModelService,
ILightboxHelper lightboxHelper,
INodeModelService nodeModelService,
IPermissionsService permissionsService)
{
_groupService = groupService;
_groupLinkProvider = groupLinkProvider;
_groupMemberService = groupMemberService;
_memberService = memberService;
_groupLinkProvider = groupLinkProvider;
_imageHelper = imageHelper;
_mediaModelService = mediaModelService;
_groupService = groupService;
_lightboxHelper = lightboxHelper;
_nodeModelService = nodeModelService;
_permissionsService = permissionsService;
}
public GroupHeaderViewModel GetHeader(Guid groupId)
{
var group = _groupService.Get(groupId);
var canEdit = _groupService.CanEdit(group);
var links = _groupLinkProvider.GetGroupLinks(groupId, canEdit);
return new GroupHeaderViewModel
{
Title = group.Title,
RoomPageLink = links.GroupRoomPage,
GroupLinks = links
};
}
public async Task<GroupHeaderViewModel> GetHeaderAsync(Guid groupId)
{
var group = await _groupService.GetAsync(groupId);
var canEdit = await _groupService.CanEditAsync(group);
var links = _groupLinkProvider.GetGroupLinks(groupId, canEdit);
return new GroupHeaderViewModel
{
Title = group.Title,
RoomPageLink = links.GroupRoomPage,
GroupLinks = links
};
}
public GroupViewModel GetGroupViewModel(Guid groupId)
{
var group = _groupService.Get(groupId);
var currentMemberId = _memberService.GetCurrentMemberId();
var groupModel = group.Map<GroupViewModel>();
groupModel.IsMember = _groupMemberService.IsGroupMember(group.Id, currentMemberId);
groupModel.IsCreator = group.CreatorId == currentMemberId;
groupModel.MembersCount = _groupMemberService.GetMembersCount(group.Id);
groupModel.Creator = _memberService.Get(group.CreatorId).ToViewModel();
groupModel.GroupUrl = _groupLinkProvider.GetGroupRoomLink(group.Id);
if (groupModel.HasImage)
{
groupModel.GroupImageUrl = _imageHelper.GetImageWithPreset(_mediaModelService.Get(group.ImageId.Value).Url, UmbracoAliases.ImagePresets.GroupImageThumbnail);
}
return groupModel;
}
public async Task<GroupViewModel> GetGroupViewModelAsync(Guid groupId)
{
var group = await _groupService.GetAsync(groupId);
var currentMemberId = await _memberService.GetCurrentMemberIdAsync();
var groupModel = group.Map<GroupViewModel>();
groupModel.IsMember = await _groupMemberService.IsGroupMemberAsync(group.Id, currentMemberId);
groupModel.IsCreator = group.CreatorId == currentMemberId;
groupModel.MembersCount = await _groupMemberService.GetMembersCountAsync(group.Id);
groupModel.Creator = (await _memberService.GetAsync(group.CreatorId)).ToViewModel();
groupModel.GroupUrl = _groupLinkProvider.GetGroupRoomLink(group.Id);
if (groupModel.HasImage)
{
groupModel.GroupImageUrl = _imageHelper.GetImageWithPreset(_mediaModelService.Get(group.ImageId.Value).Url, UmbracoAliases.ImagePresets.GroupImageThumbnail);
}
return groupModel;
}
public GroupInfoViewModel GetInfoViewModel(Guid groupId)
{
var group = _groupService.Get(groupId);
var groupInfo = group.Map<GroupInfoViewModel>();
groupInfo.CanHide = _groupService.CanHide(group);
if (group.ImageId.HasValue)
{
_lightboxHelper.FillGalleryPreview(groupInfo, Enumerable.Repeat(group.ImageId.Value, 1));
}
return groupInfo;
}
public async Task<GroupInfoViewModel> GetInfoViewModelAsync(Guid groupId)
{
var group = await _groupService.GetAsync(groupId);
var groupInfo = group.Map<GroupInfoViewModel>();
groupInfo.CanHide = await _groupService.CanHideAsync(group);
if (group.ImageId.HasValue)
{
_lightboxHelper.FillGalleryPreview(groupInfo, Enumerable.Repeat(group.ImageId.Value, 1));
}
return groupInfo;
}
public GroupLeftNavigationMenuViewModel GroupNavigation()
{
var rootGroupPage = _nodeModelService.AsEnumerable().OfType<UintraGroupsPageModel>().First();
var groupPageChildren = _nodeModelService.AsEnumerable().Where(x =>
x is IGroupNavigationComposition navigation && navigation.GroupNavigation.ShowInMenu &&
x.ParentId == rootGroupPage.Id);
groupPageChildren = groupPageChildren.Where(x =>
{
if (x is UintraGroupsCreatePageModel)
{
return _permissionsService.Check(new PermissionSettingIdentity(PermissionActionEnum.Create,
PermissionResourceTypeEnum.Groups));
}
return true;
});
var menuItems = groupPageChildren.OrderBy(x => ((IGroupNavigationComposition)x).GroupNavigation.SortOrder.Value).Select(x => new GroupLeftNavigationItemViewModel
{
Title = ((IGroupNavigationComposition)x).GroupNavigation.NavigationTitle,
Link = x.Url.ToLinkModel()
});
var result = new GroupLeftNavigationMenuViewModel
{
Items = menuItems,
GroupPageItem = new GroupLeftNavigationItemViewModel
{
Link = rootGroupPage.Url.ToLinkModel(),
Title = ((IGroupNavigationComposition)rootGroupPage).GroupNavigation.NavigationTitle
}
};
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Delivery.WebApi.Services;
using Inventory.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Delivery.WebApi.Controllers
{
//[Authorize]
[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
private readonly OrderService _service;
private readonly LogWebApiService _log;
public OrderController(OrderService service, LogWebApiService log)
{
_service = service;
_log = log;
}
#region Order
// GET: api/Order/orderId?4
[HttpGet("orderId")]
public async Task<ActionResult<Order>> GetOrderIdAsync(int orderId)
{
Order rez = await _service.GetOrderAsync(orderId);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/Guid?698a16e2-e878-11e6-80cb-6431504f2928
[HttpGet("Guid")]
public async Task<ActionResult<Order>> GetOrderGuidAsync(Guid orderGuid)
{
Order rez = await _service.GetOrderAsync(orderGuid);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/today
[HttpGet("today")]
public async Task<ActionResult<IList<Order>>> GetOrdersToday()
{
IList<Order> rez = await _service.GetOrdersTodayAsync();
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/today/restaurant
[HttpGet("today/restaurant")]
public async Task<ActionResult<IList<Order>>> GetRestauranOrdersToday(int restaurantId)
{
IList<Order> rez = await _service.GetRestauantOrdersTodayAsync(restaurantId);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/today/restaurant/status
[HttpGet("today/restaurant/status")]
public async Task<ActionResult<IList<Order>>> GetRestauranOrdersStatusToday(int restaurantID,int statusId)
{
IList<Order> rez = await _service.GetRestauantOrdersTodayAsync(restaurantID, statusId);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/
[HttpGet("quantity")]
public async Task<ActionResult<IList<Order>>> GetOrders(int quantity)
{
IList<Order> rez = await _service.GetOrdersAsync(0, quantity);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order
[HttpGet("range")]
public async Task<ActionResult<IList<Order>>> GetOrdersRange(int skip, int take)
{
IList<Order> rez = await _service.GetOrdersAsync(skip, take);
if (rez == null)
{
await _log.WriteAsync(LogType.Warning, nameof(OrderController), nameof(GetOrdersRange), "Orders is null", "Items count");
return NotFound();
}
else
{
await _log.WriteAsync(LogType.Information, nameof(OrderController), nameof(GetOrdersRange), rez.Count.ToString(), "Items count");
return Ok(rez);
}
}
// GET: api/Order/
[HttpGet("CustomerOrders")]
public async Task<ActionResult<IList<Order>>> GetCustomerOrders(Guid customerGuid,int skip, int take)
{
IList<Order> rez = await _service.GetCustomerOrdersAsync(customerGuid, skip, take);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// POST: api/Order
[HttpPost("New")]
public async Task<ActionResult<Order>> Post(Order model)
{
Order insertOrder = await _service.GetOrderAsync(model.RowGuid);
if (insertOrder != null)
{
_log.LogError("Order", "New", "Заказ для добавления уже есть в базе.", $"RowGuid='{model.RowGuid}'");
return BadRequest();
}
Order[] models = new Order[] { model };
int rez = await _service.PostOrderAsync(models);
if (rez > 0)
{
Order rezOrder = await _service.GetOrderAsync(model.RowGuid);
_log.LogInformation("Order", "New", "Заказ добавлен", $"Заказ RowGuid={rezOrder.RowGuid} добавлен.");
return Ok(rezOrder);
}
return BadRequest();
}
// PUT: api/Order/
[HttpPut("Update")]
public async Task<ActionResult<Order>> Put(Order model)
{
Order updateOrder = await _service.GetOrderAsync(model.RowGuid);
if (updateOrder == null)
{
_log.LogError("Order", "Update", "Заказ для изменения не найден.", $"RowGuid='{model.RowGuid}'");
return NotFound();
}
Order[] models = new Order[] { model };
int rez = await _service.PostOrderAsync(models);
if (rez > 0)
{
_log.LogInformation("Order", "Update", "Заказ изменен", $"Заказ RowGuid={model.RowGuid} изменен.");
Order rezOrder = await _service.GetOrderAsync(model.RowGuid);
return Ok(rezOrder);
}
return BadRequest();
}
// DELETE: api/Order/5
[HttpDelete("Guid")]
public async Task<ActionResult> Delete(Guid orderGuid)
{
Order delOrder = await _service.GetOrderAsync(orderGuid);
if (delOrder == null)
{
_log.LogError("Order", "Delete", "Заказ для удаления не найден.", $"RowGuid={orderGuid}");
return NotFound();
}
Order[] models = new Order[] { delOrder };
int rez = await _service.DeleteOrdersAsync(models);
_log.LogInformation("Order", "Delete", "Заказ удален", $"Заказ RowGuid={delOrder.RowGuid} удален.");
return Ok();
}
#endregion Order
#region OrderDish
// GET: api/Order/OrderDishes/698a16e2-e878-11e6-80cb-6431504f2928
[HttpGet("OrderDishes")]
public async Task<ActionResult<OrderDish>> GetOrderDishesAsync(Guid orderGuid)
{
IList<OrderDish> rez = await _service.GetOrderDishesAsync(orderGuid);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/OrderDishGarnishes/698a16e2-e878-11e6-80cb-6431504f2928
[HttpGet("OrderDishGarnishes")]
public async Task<ActionResult<OrderDishGarnish>> GetOrderDishGarnishesAsync(int orderDishID)
{
IList<OrderDishGarnish> rez = await _service.GetOrderDishGarnishesAsync(orderDishID);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
// GET: api/Order/OrderDishGarnishes/698a16e2-e878-11e6-80cb-6431504f2928
[HttpGet("OrderDishIngredients")]
public async Task<ActionResult<OrderDishIngredient>> GetOrderDishIngredientsAsync(int orderDishID)
{
IList<OrderDishIngredient> rez = await _service.GetOrderDishIngredientsAsync(orderDishID);
if (rez == null)
{
return NotFound();
}
else
{
return Ok(rez);
}
}
#endregion OrderDish
}
}
|
/* using UnityEngine;
using System.Collections;
public class ShopScroll : MonoBehaviour
{
public GameObject Page;
private GameObject SecondPage;
private bool isTransitioning = false;
void Awake ()
{
SecondPage = (GameObject)Instantiate(Page);
SecondPage.transform.parent = Page.transform.parent;
SecondPage.transform.localScale = Page.transform.localScale;
SecondPage.gameObject.SetActive(false);
}
public void ScrollFromRight()
{
Scroll(1);
}
public void ScrollFromLeft()
{
Scroll(-1);
}
private void Scroll(int direction)
{
if(isTransitioning)
return;
float panelWidth = Page.transform.parent.GetComponent<UIPanel>().width;
isTransitioning = true;
SecondPage.gameObject.SetActive(true);
SecondPage.transform.localPosition = new Vector3(direction * panelWidth, 0, 0);
TweenPosition.Begin(SecondPage, 0.3f, new Vector3(0,0,0));
TweenPosition.Begin(Page, 0.3f, new Vector3(-direction * panelWidth,0,0));
SecondPage.GetComponent<TweenPosition>().SetOnFinished(() => {
isTransitioning = false;
var oldPage = Page;
Page = SecondPage;
SecondPage = oldPage;
SecondPage.gameObject.SetActive(false);
});
}
}*/
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace StreamTest
{
public static class FileStreamRead
{
public static void ReadAndWriteUsingFileStream()
{
string pathSource = @"..\..\..\source.txt";
string pathNew = @"..\..\..\newfile.txt";
try
{
byte[] bytes = new byte[1024];
using (var stream = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
{
int bytesRead;
do
{
bytesRead = stream.Read(bytes, 0, bytes.Length);
} while (bytesRead > 0);
}
using (var stream = new FileStream(pathNew, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
stream.Write(bytes, 0, bytes.Length);
}
}
catch (IOException ioEx)
{
Console.WriteLine(ioEx.Message);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace decorator.console
{
class ConcreteDecoratorB : Decorator
{
public ConcreteDecoratorB(Component comp) : base(comp)
{
}
public override string Operation()
{
return $"ConcreteDecoratorB({base.Operation()})";
}
}
}
|
using Alabo.Domains.Entities.Core;
using System.Threading.Tasks;
namespace Alabo.Datas.Stores.Distinct {
public interface IDistinctAsyncStore<TEntity, in TKey> where TEntity : class, IKey<TKey>, IVersion, IEntity {
Task<bool> DistinctAsync(string filedName);
}
} |
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
[SerializeField] Transform target = null;
[SerializeField] float moveRangeMax = 20f;
[SerializeField] float moveRangeMin = -20f;
[SerializeField] float moveSpeed = 1f;
[Space]
[SerializeField] NavMeshAgent agent = null;
bool isMoving = false;
void Update()
{
UpdateMove();
}
void UpdateMove()
{
if (!isMoving)
{
var path = new NavMeshPath();
agent.CalculatePath(new Vector3(Random.Range(-WorldEnvironment.MapSize.x * 0.5f, WorldEnvironment.MapSize.x * 0.5f), 0f, Random.Range(-WorldEnvironment.MapSize.z * 0.5f, WorldEnvironment.MapSize.z * 0.5f)), path);
agent.SetPath(path);
isMoving = true;
}
if (agent.velocity.magnitude <= 0.1f)
isMoving = false;
}
}
|
namespace Assets.Scripts.Models.ResourceObjects
{
public class Manure : ResourceObject
{
public Manure()
{
LocalizationName = "manure";
IconName = "manure_icon";
CanBuy = true;
ShopPrice = 2;
}
}
}
|
using UnityEngine;
using TMPro;
using System;
using UnityEngine.UI;
//focused on 1 player
public class SavingsManager : MonoBehaviour
{
private double percentage;
private float myGold,myFortune;
public TMP_Text savingsText,totalSavings;
public Button yesButton, noButton;
public static bool BeginProcess,updateSavings;
public GameObject savingsObject;
// Start is called before the first frame update
private void Update()
{
if(BeginProcess)
{
myGold = MoneyManager.PLAYER_GOLD;
myFortune = MoneyManager.PLAYER_FORTUNE;
SetSavingsText();
BeginProcess = false;
}
if(updateSavings)
{
updateSavings = false;
totalSavings.text = MoneyManager.PLAYER_SAVINGS.ToString() + " G";
}
}
private void SetSavingsText()
{
percentage = Math.Round(myGold * .15f, MidpointRounding.AwayFromZero);
string text = $"You can place 15% of your gold to your savings." +
$"It represents {percentage.ToString()} Gold."+
$"Do you want to ?";
savingsText.text = text;
yesButton.interactable = true;
noButton.interactable = true;
}
public void Accept()
{
if (MoneyManager.PLAYER_SAVINGS==0)
{
float oldPercentage = MoneyManager.PLAYER_SAVINGS;
float newPercentage = oldPercentage + (float)percentage;
MoneyManager.PLAYER_SAVINGS =newPercentage;
}
else
{
MoneyManager.PLAYER_SAVINGS=(float)percentage;
}
totalSavings.text = MoneyManager.PLAYER_SAVINGS.ToString()+ " G";
float newGold = myGold - (float)percentage;
MoneyManager.PLAYER_GOLD= newGold;
MoneyManager.instance.UpdateFortuneInGame();
}
public void Done()
{
savingsObject.SetActive(true);
BoardManager.NextTurn();
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dboEF6.EF;
namespace dboEF6
{
class GetData<T> where T : class
{
private DbSet<T> _table;
private AutoEntities _db;
public GetData()
{
_db = new AutoEntities();
_table = _db.Set<T>();
}
public List<T> getTable()
{
using (var _db = new AutoEntities())
{
return _table.ToList();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class CRLExpressionTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int m = 10;
var query = new CRL.LambdaQuery.CRLExpressionVisitor<Code.ProductData>();
//var re = query.Where(b => b.ProductName.Contains("22"));
var re = query.Where(b => b.ProductName.Substring(2)=="22");
//var re = query.Where(b => b.ProductName.IndexOf("22")==1);
var obj = CRL.LambdaQuery.CRLQueryExpression.FromJson(re);
var expression = query.CreateLambda(obj.Expression);
//re = CRL.CacheServer.CacheServer.Query(obj);
Response.Write(re);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace _3_Properties
{
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
for (int i = 0; i < 2; i++)
{
Console.Write("Name: ");
string name = Console.ReadLine();
Console.Write("ID: ");
string id = Console.ReadLine();
students.Add(new Student(name, id));
}
foreach (Student student in students)
{
Console.WriteLine($"{student.Id}: {student.Name} -- {student.RegisterDate}");
}
}
}
}
|
using MenuFramework;
using System;
using System.Collections.Generic;
using System.Text;
using TenmoClient.Data;
namespace TenmoClient.Views
{
class UserSelectionMenu : ConsoleMenu
{
private MainMenu parent;
private int transferType;
public UserSelectionMenu(Dictionary<int, API_User> names, string username, MainMenu mainMenu, int transferType)
{
parent = mainMenu;
this.transferType = transferType;
foreach (KeyValuePair<int, API_User> kvp in names)
{
if (kvp.Value.Username != username)
{
AddOption<int>(kvp.Value.Username, ReturnName, kvp.Key);
}
}
AddOption("Exit", ExitSelect);
}
protected override void OnBeforeShow()
{
if (transferType == 2)
{
Console.WriteLine("Please Select the Recipient\n");
}
else
{
Console.WriteLine("Please Select a User to Request from\n");
}
}
private MenuOptionResult ReturnName(int selection)
{
parent.selectionId = selection;
return MenuOptionResult.CloseMenuAfterSelection;
}
private MenuOptionResult ExitSelect()
{
parent.selectionId = 0;
return MenuOptionResult.CloseMenuAfterSelection;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OnlineClinic.Core.DTOs;
namespace OnlineClinic.Core.Services
{
public interface IPersonService
{
Task<int> Create(PersonCreateDto createDto);
bool Exists(int id);
bool Exists(string firstName, string middleName, string lastName, DateTime dob, string address);
bool Exists(int id, string firstName, string middleName, string lastName, DateTime dob, string address);
Task UpdateAsync(PersonEditDto editDto);
IEnumerable<PersonGetDto> GetAll(bool asNoTracking = true);
PersonGetDto GetById(int id);
Dictionary<int, string> GetPersonIdAndNames();
}
} |
using Alabo.Datas.Stores.Update.Mongo;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
namespace Alabo.Datas.Stores {
/// <summary>
/// Mongodb数据库查询器
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
public abstract class MongoStore<TEntity, TKey> : UpdateMongoStore<TEntity, TKey>, IStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
/// <summary>
/// 初始化查询存储器
/// </summary>
/// <param name="unitOfWork">工作单元</param>
protected MongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core;
namespace GUI
{
public partial class ParallelepipedForm : Form
{
public ParallelepipedForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBoxV.Clear();
if ((textBoxA.Text == "") || (textBoxB.Text == "") || (textBoxC.Text == ""))
{
MessageBox.Show("Поля пусты");
return;
}
int a, b, c;
double V = 0;
if ((int.TryParse(textBoxA.Text, out a))
&& (int.TryParse(textBoxB.Text, out b))
&& (int.TryParse(textBoxC.Text, out c)))
{
Parallelepiped parallelepiped = new Parallelepiped(a, b, c);
V = parallelepiped.ReturnVolume();
textBoxV.AppendText(V.ToString());
}
}
}
}
|
///////////////////////////////////////////////////////////////////////////////////////////////////
/// @Name: IProcessProgressObserver.cs
/// @Description: 订阅数据处理进度的接口,对处理进度的改变实时的做出相应
/// @Author: Shaofeng Wang
/// @Created Date: 2010-03-11
/// @Copyright: All Rights Reserved by Sensor Networks and Applications Research Center (2010-2015)
///////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Colin.Forms.Logic
{
public interface IProcessProgressObserver
{
/// <summary>
/// 获取已经处理的ECG点数并更新进度
/// </summary>
/// <param name="point">已经处理的点数</param>
void UpdateProgress(int point);
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using testMonogame.Rooms;
using testMonogame.Interfaces;
using testMonogame.Commands.SpecialMoves;
using System.Diagnostics;
namespace testMonogame
{
public class GameManager
{
Game1 game;
GameTime gameTime;
IPlayer player;
HUD hud;
ItemSelectionScreen itemScreen;
PauseScreen pause;
GameOverScreen gameOver;
WinScreen win;
StartMenuScreen start;
private RoomLoader roomLoad;
Dictionary<String, IRoom> rooms = new Dictionary<string, IRoom>();
String roomKey = "";
RoomTransition transitioner;
int doorCollideCountdown = 0;
int difficulty; //0=easy, 1=normal, 2=hard
bool isHordeMode;
int gameOverWinScreenCooldown = 0;//This will ensure that the player sees the game over or victory screen without immediately skipping
enum GameState {PLAYING,//0
ITEMSELECTION,//1
PAUSE,//2
LOSE, //3
WIN, //4
ROOMTRANSITION, //5
START //6
};
GameState state;
Sounds sound;
Dictionary<String, Texture2D> sprites = new Dictionary<string, Texture2D>();
//collision detectors
EnemyObjectCollision EOCol = new EnemyObjectCollision();
PlayerWallCollision PWCol = new PlayerWallCollision();
EnemyWallCollision EWCol = new EnemyWallCollision();
PlayerProjectileWallCollision PPWCol = new PlayerProjectileWallCollision();
PlayerProjectileEnemyCollision PPECol = new PlayerProjectileEnemyCollision();
PlayerObjectCollision POCol = new PlayerObjectCollision();
PlayerEnemyCollision PECol = new PlayerEnemyCollision();
EnemyProjectileCollisionHandler EPCol;
//cheat codes
Dictionary<String, ICommand> cheatCodes;
Dictionary<String, ICommand> specialMoves;
public GameManager(Game1 game, Dictionary<String, Texture2D> spriteSheet, SpriteFont font, SpriteFont header, Sounds sounds)
{
GameplayConstants.Initialize(1);//initialize constants to normal mode, just at the start so constants are somehting
this.game = game;
sprites = spriteSheet;
state = GameState.START;
difficulty = 1;
isHordeMode = false;
//load room 17 first
sound = sounds;
roomLoad = new RoomLoader(sprites, this);
rooms.Add("Room17", roomLoad.Load("Room17.txt"));
roomKey = "Room17";
transitioner = new RoomTransition();
//initialize player
player = new Player(spriteSheet["playersheet"], new Vector2(500, 200), spriteSheet["PlayerProjectiles"], sound);
//initailize screens
hud = new HUD(spriteSheet["hudSheet"], font);
itemScreen = new ItemSelectionScreen(spriteSheet["ItemSelection"]);
pause = new PauseScreen(spriteSheet["MenuScreens"], font, header);
gameOver = new GameOverScreen(spriteSheet["MenuScreens"], font, header);
win = new WinScreen(spriteSheet["MenuScreens"]);
start = new StartMenuScreen(spriteSheet["StartMenu"], font, header,this);
EPCol = new EnemyProjectileCollisionHandler(this);
//initailize cheat code dictionary
cheatCodes = new Dictionary<string, ICommand>();
//initailize cheat codes
ICommand extraHealth = new ExtraHealth(player);
ICommand extraRupees = new ExtraRupees(player);
ICommand invinc = new Invincibility(player);
ICommand bombs = new UnlimitedBombs(player);
cheatCodes.Add("NBKJH", extraHealth);
cheatCodes.Add("MNBVX", extraRupees);
cheatCodes.Add("ZZKNL", invinc);
cheatCodes.Add("GFGFG", bombs);
//initailize special move code dictionary
specialMoves = new Dictionary<string, ICommand>();
//initailize special moves
ICommand fireSpin = new FireSpinSpecialMove(this);
ICommand reapingArrow = new ReapingArrowSpecialMove(this);
ICommand rupeeShied = new RupeeShieldSpecialMove(this);
specialMoves.Add("TYHGT", fireSpin);
specialMoves.Add("JKJKJ", reapingArrow);
specialMoves.Add("KJHGF", rupeeShied);
}
public bool IsWaitingWinLossState()
{
return (gameOverWinScreenCooldown > 0);
}
public int GetDifficulty() { return difficulty; }
//set difficulty depending on prior difficulty. accounts for wraparound
public void ChangeDifficulty(int difference) {
difficulty += difference;
if (difficulty < 0) difficulty = 2;
if (difficulty > 2) difficulty = 0;
}
public bool IsHorde() { return isHordeMode; }
public void SetHorde(bool b) { isHordeMode = b;}
//interfacing with start menu so that it can be controlled via commands
public int GetStartMenuSelectedBox(){return start.getSelectedBox();}
public void NextStartMenuBox() { start.nextOption(); }
public void PreviouStartMenuBox() { start.previousOption(); }
public void Update()
{
//don't update when rooms are transitioning
if (transitioner.transitioning())
{
return;
}
//PLAYING
if (state == GameState.PLAYING)
{
hud.Update(this);
player.Update(this);
rooms[roomKey].Update(this, gameTime);
EOCol.detectCollision(rooms[roomKey].GetEnemies(), rooms[roomKey].GetBlocks());
PWCol.detectCollision(player, rooms[roomKey].GetWallDestRect(), rooms[roomKey].GetFloorDestRect());
EWCol.detectCollision(rooms[roomKey].GetEnemies(), rooms[roomKey].GetWallDestRect(), rooms[roomKey].GetFloorDestRect());
PPWCol.detectCollision(rooms[roomKey].GetPlayerProjectiles(), rooms[roomKey].GetWallDestRect(), rooms[roomKey].GetFloorDestRect(), this);
PPECol.detectCollision(rooms[roomKey].GetPlayerProjectiles(), rooms[roomKey].GetEnemies(), this, rooms[roomKey], sound);
PECol.playerEnemyDetection(player, rooms[roomKey].GetEnemies(), rooms[roomKey], sound);
EPCol.handleEnemyProjCollision(rooms[roomKey], player);
if (doorCollideCountdown <= 0)
{
POCol.detectCollision(player, rooms[roomKey].GetItems(), rooms[roomKey].GetBlocks(), rooms[roomKey], this);
}
else
{
doorCollideCountdown--;
}
}
//START
else if(state == GameState.START)
{
start.Update(this);
}
//Item selection
else if (state == GameState.ITEMSELECTION)
{
hud.Update(this);
player.Update(this);
itemScreen.Update(this);
}
//NO UPDATES FOR PAUSE OR GAME OVER
else if (state == GameState.WIN)
{
player.Update(this);
}
if (gameOverWinScreenCooldown > 0) gameOverWinScreenCooldown=gameOverWinScreenCooldown-1;
}
public void Draw(SpriteBatch spriteBatch)
{
//use transitioner for drawing during rooom transition
if (transitioner.transitioning())
{
transitioner.Draw(spriteBatch);
return;
}
//NORMAL STUFF
if (state == GameState.PLAYING)
{
if (hud.hudY != 0) hud.hudY = 0;
hud.Draw(spriteBatch);
rooms[roomKey].Draw(spriteBatch);
player.Draw(spriteBatch);
}
//START
else if (state == GameState.START)
{
start.Draw(spriteBatch);
}
//item selection
else if (state == GameState.ITEMSELECTION)
{
if(hud.hudY!= (176 * 2)) hud.hudY = (176 * 2);
hud.Draw(spriteBatch);
itemScreen.Draw(spriteBatch, rooms.Keys);
}
//Pause Screen
else if (state == GameState.PAUSE)
{
pause.Draw(spriteBatch);
}
//game over
else if (state == GameState.LOSE)
{
//sound.pDies();
gameOver.Draw(spriteBatch);
}
else if (state == GameState.WIN)
{
win.Draw(spriteBatch);
player.Draw(spriteBatch);
}
//decrement delay if we are waiting on win or lose screen
//if (gameOverWinScreenCooldown > 0) gameOverWinScreenCooldown--;
}
public void AddEnemyProjectile(IEnemyProjectile projectile) { rooms[roomKey].AddEnemyProjectile(projectile); }
public void RemoveEnemyProjectile(IEnemyProjectile projectile) { rooms[roomKey].RemoveEnemyProjectile(projectile); }
public void AddPlayerProjectile(IPlayerProjectile projectile) { rooms[roomKey].AddPlayerProjectile(projectile); }
public void RemovePlayerProjectile(IPlayerProjectile projectile) { rooms[roomKey].RemovePlayerProjectile(projectile); }
public void LoadRoom(int roomNum)
{
String name = "Room" + roomNum;
//test if room is already loaded
if (rooms.ContainsKey(name))
{
ChangeRoom(roomNum);
}
else
{
//load room if it hasn't been loaded then change room
rooms.Add(name, roomLoad.Load(name + ".txt"));
ChangeRoom(roomNum);
}
}
public void ChangeRoom(int roomNum)
{
String curRoom = roomKey;
String name = "Room" + roomNum;
roomKey = name;
int direction = -1;
doorCollideCountdown = 5;
foreach (IObject block in rooms[curRoom].GetBlocks())
{
if ((block is CaveDoor || block is ClosedDoor || block is OpenDoor || block is LockedDoor || block is StairsBlock || block is SolidBlockDoor))
{
IDoor door = (IDoor)block;
if (door.getNextRoom() == roomNum)
{
direction = door.getSide();
break;
}
}
}
if (direction != -1)
{
//make sure the door on other side is opened
unlockNextDoor(direction);
//transition if rooms are adjacent
transitioner.transtion(rooms[curRoom], rooms[roomKey], direction);
}
}
public void unlockNextDoor(int direction)
{
switch (direction)
{
case 0:
foreach (IObject block in rooms[roomKey].GetBlocks())
{
if ((block is CaveDoor || block is ClosedDoor || block is OpenDoor || block is LockedDoor))
{
IDoor door = (IDoor)block;
//make sure door on the other side of the other room is also open
if (door.getSide() == 3)
{
door.openDoor();
}
}
}
break;
case 1:
foreach (IObject block in rooms[roomKey].GetBlocks())
{
if ((block is CaveDoor || block is ClosedDoor || block is OpenDoor || block is LockedDoor))
{
IDoor door = (IDoor)block;
//make sure door on the other side of the other room is also open
if (door.getSide() == 2)
{
door.openDoor();
}
}
}
break;
case 2:
foreach (IObject block in rooms[roomKey].GetBlocks())
{
if ((block is CaveDoor || block is ClosedDoor || block is OpenDoor || block is LockedDoor))
{
IDoor door = (IDoor)block;
//make sure door on the other side of the other room is also open
if (door.getSide() == 1)
{
door.openDoor();
}
}
}
break;
case 3:
foreach (IObject block in rooms[roomKey].GetBlocks())
{
if ((block is CaveDoor || block is ClosedDoor || block is OpenDoor || block is LockedDoor))
{
IDoor door = (IDoor)block;
//make sure door on the other side of the other room is also open
if (door.getSide() == 0)
{
door.openDoor();
}
}
}
break;
}
}
public IPlayer getPlayer()
{
return player;
}
public HUD getHUD()
{
return hud;
}
public void Exit()
{
game.Exit();
}
public void s2reset()
{
//for sprint 2 reset
game.s2reset();
}
public int getState()
{
return (int)state ;
}
public void SetState(int inState) {
int prevState = (int)state;
state = (GameState)inState;
if (prevState!=inState&&(state == GameState.LOSE || state == GameState.WIN))
{
//Debug.WriteLine("a");
gameOverWinScreenCooldown = 180;//3 sec delay
}
if (state == GameState.PLAYING && prevState == 6)
{
GameplayConstants.Initialize(difficulty);
player.InitializeFromConstants();
}
}
public void specialMove(string code)
{
//checks if code recieved is usable
if (specialMoves.ContainsKey(code))
{
specialMoves[code].Execute();
}
return;
}
public void cheatCode(string code)
{
//checks if code recieved is usable
if (cheatCodes.ContainsKey(code))
{
cheatCodes[code].Execute();
}
return;
}
}
}
|
namespace BettingSystem.Domain.Betting.Factories.Gamblers
{
using Exceptions;
using Models.Gamblers;
internal class GamblerFactory : IGamblerFactory
{
private string gamblerName = default!;
private string gamblerUserId = default!;
private bool isNameSet = false;
private bool isUserIdSet = false;
public IGamblerFactory WithName(string name)
{
this.gamblerName = name;
this.isNameSet = true;
return this;
}
public IGamblerFactory FromUser(string userId)
{
this.gamblerUserId = userId;
this.isUserIdSet = true;
return this;
}
public Gambler Build()
{
if (!this.isNameSet || !this.isUserIdSet)
{
throw new InvalidGamblerException("Name and User Id must have a value");
}
return new Gambler(
this.gamblerName,
this.gamblerUserId,
balance: decimal.Zero);
}
}
}
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
namespace SpotifyTracks
{
public class Client
{
public HttpClient PassToken()
{
string token = "BQBQCsLkym20j4Xy7-NfZ-V1q6T33goHeAODIgTnvIThJiplQVyyiHrQLSf80fBfeBu4axnYcDnmsbh38ybqe24iuwNsZXT4YNQ19apsfCKaJiPXgFnmrCSAXUFDaocQ6KM9C3Plkdpkb5RCjFBxnXI0MyYRW1FmpVyOCbesxuxWaXEzSOGINfDRAGzLcXaCFxbuX5HRw1sb7w7mf9oc8sgaBnVeJYkRDx-cznMgaeqq71NZ0ye5AKo8ZxBCoqg9kz0APFc0UVbGTKmpOg";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
}
}
|
using GisSharpBlog.NetTopologySuite.Geometries;
using NUnit.Framework;
namespace NetTopologySuite.Tests.Geometry
{
[TestFixture]
public class LineStringTest
{
[Test]
public void GetHashCodeMustBeComputed()
{
var lineString = new LineString(new[] { new Coordinate(1.0, 2.0), new Coordinate(3.0, 4.0) });
Assert.AreEqual(2024009049, lineString.GetHashCode());
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using FTLibrary.Time;
using UnityGUI;
using UnityEngine;
using System.Threading;
using System.IO;
class SelfCheckingModalProcess : UniProcessModalEvent
{
public override ModalProcessType processType { get { return ModalProcessType.Process_SelfChecking; } }
public SelfCheckingModalProcess()
: base()
{
}
/// <summary>
/// 字符串
/// </summary>
private string str = "";
/// <summary>
/// 最大的行数
/// </summary>
public static int MaxLineCount = 40;
/// <summary>
/// 当前的行数
/// </summary>
private int currentLineCount = 0;
/// <summary>
/// 界面group
/// </summary>
public GuiModule guiModule;
/// <summary>
/// 文字
/// </summary>
private GuiLabelTextDoc textdoc;
//显示输出信息
void ShowMessage(string msg)
{
if (str == "")
{
currentLineCount = 1;
str = msg;
}
else
{
if (currentLineCount >= MaxLineCount)
{
int idx = str.IndexOf('\n');
//去掉最顶上一行
str = str.Substring(idx + 1);
}
else
{
currentLineCount++;
}
str += "\n" + msg;
}
textdoc.Text = str;
}
enum CheckedEvent
{
Eve_Noting, //没有开始
Eve_Start, //开始自检
Eve_ProduceActivateInfo, //汇报产品激活情况
Eve_ProduceVersion, //汇报产品版本情况
Eve_InputDeviceResponse, //输入设备响应
Eve_InputDeviceResponseOver,//输入设备响应完成
Eve_InputDeviceOut, //输入设备输出
Eve_InputDeviceOutOver, //完成
Eve_GameResolution, //调整游戏分辨率
Eve_GameResolution1, //调整游戏分辨率
Eve_IntoControlPanel, //控制界面
Eve_IntoGame, //进入游戏
Eve_IntoGameOk
}
private CheckedEvent checkedEvent = CheckedEvent.Eve_Noting;
//初始化函数
public override void Initialization()
{
//首先在启动过程中先查看是否出现了错误,如果出现了错误需要显示错误信息
//然后就不进行下面的过程了
if (ErrMessageBox.IsShowErrMessageBox)
{
ErrMessageBox.ShowErrMessage("游戏启动发生错误,停止自检过程!");
return;
}
//进入游戏待机画面
base.Initialization();
guiModule=GameRoot.gameResource.LoadResource_Prefabs("SelfCheckingWindows.prefab").GetComponent<GuiModule>();
//创建出来自检画面
guiModule.mainGroup.AutoWidth = new GuiVector2(1.0f, 0.0f);
guiModule.mainGroup.AutoHeight = new GuiVector2(1.0f, 0.0f);
guiModule.mainGroup.BackgroupSeting = new GuiBackgroup(guiModule.skin.box);
textdoc = guiModule.RegisterGuiLableTextDoc("", "", 0.1f, 0.1f, guiModule.skin.label, Color.white, int.MaxValue);
textdoc.AutoWidth = new GuiVector2(1.0f, 0.0f);
textdoc.AutoHeight = new GuiVector2(1.0f, 0.0f);
//再次加载游戏配置信息,因为从控制台退出后也是会重新开始这个过程的
UniGameOptionsDefine.LoadGameOptionsDefine();
//显示非致命错误
if (GameRoot.non_fatal_error_list != null)
{
ShowMessage("发生非致命错误:");
for (int i = 0; i < GameRoot.non_fatal_error_list.Count; i++)
{
ShowMessage(GameRoot.non_fatal_error_list[i]);
}
GameRoot.non_fatal_error_list = null;
ShowMessage("");
ShowMessage("");
}
checkedEvent = CheckedEvent.Eve_Start;
SelfCheckingProcess(null);
}
//释放函数
public override void Dispose()
{
if (guiModule != null)
{
GameObject.DestroyImmediate(guiModule.gameObject);
guiModule = null;
}
}
private const long EveDelayTime = 1000;
private const string PartingLine = "-----------------------------------------------------";
void SelfCheckingProcess(object[] parameters)
{
switch (checkedEvent)
{
case CheckedEvent.Eve_Start:
{
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str1"));//开始系统自检...
checkedEvent = CheckedEvent.Eve_ProduceActivateInfo;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_ProduceActivateInfo:
{
ShowMessage(PartingLine);
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str2"));//产品激活成功!
ShowMessage(string.Format(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str3"),
GameRoot.produceActivateId.activateId,
GameRoot.produceActivateId.activateDate));//产品编码:{0} 激活日期:{1}
checkedEvent = CheckedEvent.Eve_ProduceVersion;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_ProduceVersion:
{
FTLibrary.Produce.ProduceVersionInformation.VersionInfo version = GameRoot.gameResource.produceVersion.mainVersion;
ShowMessage(string.Format(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str4"),
version.version,
version.compiledate,
version.issuedate));//产品版本:{0} 生产日期:{1} 发布日期:{2}
checkedEvent = CheckedEvent.Eve_InputDeviceResponse;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_InputDeviceResponse:
{
ShowMessage(PartingLine);
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str5"));//输入设备自检...
checkedEvent = CheckedEvent.Eve_InputDeviceResponseOver;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_InputDeviceResponseOver:
{
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str6"));//输入设备自检完成
checkedEvent = CheckedEvent.Eve_InputDeviceOut;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_InputDeviceOut:
{
ShowMessage(PartingLine);
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str7"));//输出设备自检...
checkedEvent = CheckedEvent.Eve_InputDeviceOutOver;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_InputDeviceOutOver:
{
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str8"));//输出设备自检完成!
checkedEvent = CheckedEvent.Eve_GameResolution;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_GameResolution:
{
ShowMessage(PartingLine);
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str9"));//调整游戏最佳分辨率
if (UniGameOptionsDefine.gameResolution != UniGameOptionsFile.GameResolution.Resolution_Default)
{
UnityEngine.Resolution resolution = UniGameOptionsDefine.gameResolutionUnity;
Screen.SetResolution(resolution.width, resolution.height, true);
}
//Resolution now = Screen.currentResolution;
//Debug.Log(string.Format("{0},{1},{2}", now.width, now.height, now.refreshRate));
//Resolution[] resolutions = Screen.GetResolution;
//for (int i = 0; i < resolutions.Length;i++ )
//{
// Debug.Log(string.Format("{0},{1},{2}", resolutions[i].width, resolutions[i].height, resolutions[i].refreshRate));
//}
checkedEvent = CheckedEvent.Eve_GameResolution1;
TimerCall(SelfCheckingProcess, 3000, false);
}
break;
case CheckedEvent.Eve_GameResolution1:
{
Resolution current=Screen.currentResolution;
ShowMessage(string.Format(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str9_1"),
current.width, current.height, current.refreshRate));
ShowMessage(string.Format(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str9_2"),
Screen.width, Screen.height));
checkedEvent = CheckedEvent.Eve_IntoControlPanel;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_IntoControlPanel:
{
ShowMessage(PartingLine);
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str10"));
checkedEvent = CheckedEvent.Eve_IntoGame;
TimerCall(SelfCheckingProcess, 10000, false);
}
break;
case CheckedEvent.Eve_IntoGame:
{
ShowMessage(GameRoot.gameResource.LoadLanguageResource_Text("Check_Str11"));
checkedEvent = CheckedEvent.Eve_IntoGameOk;
TimerCall(SelfCheckingProcess, EveDelayTime, false);
}
break;
case CheckedEvent.Eve_IntoGameOk:
{
//在这里预载入声音资源
MusicPlayer.LoadAllUnloadAudioClip();
//进入公司LOGO过程
processControl.ActivateProcess(typeof(CompanyLogoProcess));
}
break;
}
}
//public override void OnLateUpdate()
//{
// if (checkedEvent == CheckedEvent.Eve_IntoGame)
// {
// if (InputDevice.SystemButton)
// {
// checkedEvent = CheckedEvent.Eve_Noting;
// //进入控制台过程
// processControl.ActivateProcess(typeof(GameOptionsProcess));
// return;
// }
// }
// if (InputDevice.SystemButton)
// {
// Debug.Log("这么快就进控制台啦!");
// checkedEvent = CheckedEvent.Eve_Noting;
// //进入控制台过程
// processControl.ActivateProcess(typeof(GameOptionsProcess));
// }
//}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace AEBNDashboard
{
public class DashElements
{
private Globals GlobalData = new Globals();
public string dashDate { get; set; }
public string dashDateWithDay { get; set; }
public string dashDateRaw { get; set; }
public string salesLineGraph { get; set; }
public string consumptionLineGraph { get; set; }
public string salesHtml { get; set; }
public string mainHtml { get; set; }
public string newHtml { get; set; }
public string newClientsHtml { get; set; }
public string consumptionHmtl { get; set; }
public DataSet rawDataSet { get; set; }
public DashElements(string sproc, DateTime date, double kpiHigh, double kpiLow)
{
DataSet ds = getDashElementDataset(sproc, date);
string column, section, outerSection;
string previousSalesCount, salesCount;
string previousCount, metricCount;
string salesDollars, previousSalesDollars;
string metricDefinition, metricLabel;
int previousCountValue, previousSalesDollarsValue, previousSalesCountValue;
rawDataSet = ds;
salesHtml = "";
if (sproc != "")
{
//if (ds.Tables[0].Rows.Count > 0)
//{
foreach (DataTable t in ds.Tables)
{
switch (t.Rows[0]["ds"].ToString())
{
#region Switch for Graph
case "Timeline":
break;
case "Graph":
//salesLineGraph = t.Rows[0]["Trending"].ToString();
//consumptionLineGraph = t.Rows[1]["Trending"].ToString();
/*Sales Line*/
column = "";
section = "";
section += divWrap(t.Rows[0]["ActivityDate"].ToString(), "", "date");
section += divWrap(t.Rows[0]["Label"].ToString(), "", "title");
section += divWrap("Sales", "", "hoverLabel");
section += divWrap("#b9d2ef,#e6e9ed", "", "colors");
string[] dataForDateArraySales;
string[] dataForDateArrayConsumption;
string dataToDateArraySales = "";
string dataToDateArrayConsumption = "";
DateTime lineDate = new DateTime();
lineDate = Convert.ToDateTime(t.Rows[0]["ActivityDate"]);//.AddDays(-20);
TimeSpan ts;
int timestamp;
dataForDateArraySales = t.Rows[0]["Trending"].ToString().Split(',');
dataForDateArrayConsumption = t.Rows[1]["Trending"].ToString().Split(',');
lineDate = lineDate.AddDays(-dataForDateArraySales.Length);
for (int i = 0; i < dataForDateArraySales.Length; i++)
{
lineDate = lineDate.AddDays(1);
//Make UNIX TIME//////////
ts = (lineDate - new DateTime(1970, 1, 1).ToUniversalTime());
timestamp = (int)ts.TotalSeconds;
//DK WHY I HAD TO ADD 000 to the UNIX TIME, but it works (it was a pain to figure this one out)
dataToDateArrayConsumption += "[" + timestamp + "000 , " + dataForDateArraySales[i].ToString() + "] ,";
dataToDateArraySales += "[" + timestamp + "000 , " + dataForDateArrayConsumption[i].ToString() + "] ,";
}
dataToDateArraySales = dataToDateArraySales.TrimEnd(',');
dataToDateArrayConsumption = dataToDateArrayConsumption.TrimEnd(',');
section += divWrap("[" + dataToDateArraySales + "]", "", "data");
section += divWrap("[" + dataToDateArrayConsumption + "]", "", "data2");
salesLineGraph = "<div class=\"renderStockLineGraph\" id=\"salesGraph\" style=\"height: 380px; margin: 0 auto; overflow:hidden;display:none;\">" + section + "</div>";
/*Consumption Line*/
/*column = "";
section = "";
section += divWrap(t.Rows[1]["ActivityDate"].ToString(), "", "date");
section += divWrap(t.Rows[1]["Label"].ToString(), "", "title");
section += divWrap("Consumption", "", "hoverLabel");
section += divWrap("#b9d2ef,#e6e9ed", "", "colors");
section += divWrap("[" + t.Rows[1]["Trending"].ToString() + "]", "", "data");
consumptionLineGraph = "<div class=\"renderScalingLineGraph\" id=\"consumptionGraph\" style=\"height: 160px; margin: 0 auto; overflow:hidden;\">" + section + "</div>";
*/
break;
#endregion
#region Switch for GraphOLD
case "GraphOLD":
//salesLineGraph = t.Rows[0]["Trending"].ToString();
//consumptionLineGraph = t.Rows[1]["Trending"].ToString();
/*Sales Line*/
column = "";
section = "";
section += divWrap(t.Rows[0]["ActivityDate"].ToString(), "", "date");
section += divWrap(t.Rows[0]["Label"].ToString(), "", "title");
section += divWrap("Sales", "", "hoverLabel");
section += divWrap("#b9d2ef,#e6e9ed", "", "colors");
section += divWrap("[" + t.Rows[0]["Trending"].ToString() + "]", "", "data");
salesLineGraph = "<div class=\"renderScalingLineGraph\" id=\"salesGraph\" style=\"height: 240px; margin: 0 auto; overflow:hidden;\">" + section + "</div>";
/*Consumption Line*/
column = "";
section = "";
section += divWrap(t.Rows[1]["ActivityDate"].ToString(), "", "date");
section += divWrap(t.Rows[1]["Label"].ToString(), "", "title");
section += divWrap("Consumption", "", "hoverLabel");
section += divWrap("#b9d2ef,#e6e9ed", "", "colors");
section += divWrap("[" + t.Rows[1]["Trending"].ToString() + "]", "", "data");
consumptionLineGraph = "<div class=\"renderScalingLineGraph\" id=\"consumptionGraph\" style=\"height: 180px; margin: 0 auto; overflow:hidden;\">" + section + "</div>";
break;
#endregion
#region Switch for Gauges
case "Gauge":
int numberOfGauges = t.Rows.Count;
newClientsHtml = "";
if (numberOfGauges > 5) numberOfGauges = 5;
string columnSize = "";
switch (numberOfGauges)
{
case 1: columnSize = "100%"; break;
case 2: columnSize = "50%"; break;
case 3: columnSize = "33%"; break;
case 4: columnSize = "25%"; break;
case 5: columnSize = "20%"; break;
}
int idNumber = 682; //random number for html ID
foreach (DataRow r in t.Rows)
{
section = "";
double avg = Convert.ToDouble(r["AvgCount"]);
double avgLow = avg * .80;
//string metricCount = r["MetricCount"].ToString().Replace(",","");
int dataValue = Convert.ToInt32(r["MetricCount"].ToString().Replace(",", ""));
int prevDataValue = Convert.ToInt32(r["PreviousCount"]);
int highest = Convert.ToInt32(r["MaxCount"]);
string gaugeRange = "0," + avgLow.ToString() + "," + avg.ToString() + "," + highest;
string title = r["MetricLabel"].ToString();
string percentage = r["MetricCountDifference"].ToString();
section += divWrap(gaugeRange, "", "fourRanges");
section += divWrap("#C02316,none,green", "", "threeRangeColor");//#CO2316
section += divWrap(title, "", "title");
section += divWrap(percentage, "", "percentage");
section += divWrap("[" + dataValue + "]", "", "data");
section = "<div class=\"renderMediumGauge\" id=\"a" + idNumber.ToString() + "\" style=\"float:left;width:" + columnSize + ";\">" + section + "</div>";
idNumber += 4;
newClientsHtml += section;
}
/*
<div style="float:left;width:20%;">
<!-- First Two Gauge Graphs -->
<div class="renderMediumGauge" id="a760876" style="margin: 0 auto; overflow:hidden;">
<div class="fourRanges">0,8,15,20</div>
<div class="threeRangeColor">#C02316,none,green</div>
<div class="title">RTi Signups</div>
<div class="percentage">-4%</div>
<div class="data">[12]</div>
</div>
</div>
*/
break;
#endregion
#region Switch for Main
case "Main":
salesDollars = t.Rows[0]["SalesDollars"].ToString();
previousSalesDollars = t.Rows[0]["PreviousSalesDollars"].ToString();
previousSalesDollarsValue = Convert.ToInt32(t.Rows[0]["PreviousSalesDollarsValue"]);
// DateTime dr = new DateTime( Convert.ToInt32(t.Rows[0]["ActivityDate"].ToString()), new DateTimeKind("Utc"));
// dashDateWithDay = dr.DayOfWeek.ToString() + " " + t.Rows[0]["ActivityDate"].ToString();
dashDate = t.Rows[0]["ActivityDate"].ToString();
dashDateRaw = Convert.ToDateTime(t.Rows[0]["ActivityDate"]).DayOfWeek.ToString() + " - " + dashDate.Substring(0, dashDate.IndexOf(' '));
//dashDate = dashDate.Substring(0, dashDate.IndexOf(' ')); /*dayOfweek.DayOfWeek + " - " +*/
outerSection = "";
column = "";
section = "";
outerSection += divWrap(t.Rows[0]["MetricLabel"].ToString(), "", "title");
column += divWrap(t.Rows[0]["SalesDollars"].ToString(), "", "value");
column += divWrap(t.Rows[0]["AvgSalesDollars"].ToString() + " AVG", "", "avg");
section += divWrap(column, "", "data");
column = "";
column += divWrap(returnDirectionArrow(previousSalesDollarsValue, salesDollars.ToString(), kpiHigh, kpiLow), "", "");
column += divWrap(previousSalesDollars.ToString(), "", "count");
column += divWrap(t.Rows[0]["SalesDollarsDifference"].ToString(), "", "percent");
section += divWrap(column, "", returnDirectionCSS(previousSalesDollarsValue, salesDollars.ToString(), kpiHigh, kpiLow));
section = divWrap(section, "", "");
outerSection += section;
mainHtml += divWrap(outerSection, "", "moduleMain");
mainHtml += "<div class=\"clr\" ></div>";
break;
#endregion
#region Switch for Purchases
case "Purchases":
//bool isFirstDollorRow = true;
foreach (DataRow r in t.Rows)
{
column = "";
section = "";
outerSection = "";
salesCount = r["SalesCount"].ToString();
salesDollars = r["SalesDollars"].ToString();
previousSalesCount = r["PreviousSalesCount"].ToString();
previousSalesDollars = r["PreviousSalesDollars"].ToString();
previousSalesDollarsValue = Convert.ToInt32(r["PreviousSalesDollarsValue"]);
previousSalesCountValue = Convert.ToInt32(r["PreviousSalesCountValue"]);
if ("" != r["DetailReportLink"].ToString()) metricLabel = aWrap(r["MetricLabel"].ToString(), r["DetailReportLink"].ToString());
else metricLabel = r["MetricLabel"].ToString();
#region first row of item is used with a different style
//if (isFirstDollorRow)
//{
// //dashDate is the global date for the page
// dashDate = r["ActivityDate"].ToString();
// //DateTime dayOfweek = new DateTime(Convert.ToInt32(r["ActivityDate"]), DateTimeKind.Utc);
// dashDateRaw = dashDate;
// dashDate = dashDate.Substring(0, dashDate.IndexOf(' ')); /*dayOfweek.DayOfWeek + " - " +*/
// outerSection = "";
// column = "";
// section = "";
// outerSection += divWrap(metricLabel, "", "title");
// column += divWrap(r["SalesDollars"].ToString(), "", "value");
// column += divWrap(r["AvgSalesDollars"].ToString() + " AVG", "", "avg");
// section += divWrap(column, "", "data");
// //section += divWrap(r["TrendingSalesDollars"].ToString(), "", "sparkline");
// column = "";
// column += divWrap(returnDirectionArrow(previousSalesDollarsValue, salesDollars.ToString(), kpiHigh, kpiLow), "", "");
// column += divWrap(previousSalesDollars.ToString(), "", "count");
// column += divWrap(r["SalesDollarsDifference"].ToString(), "", "percent");
// section += divWrap(column, "", returnDirectionCSS(previousSalesDollarsValue, salesDollars.ToString(), kpiHigh, kpiLow));
// section = divWrap(section, "", "");
// outerSection += section;
// salesHtml += divWrap(outerSection, "", "moduleMain");
// salesHtml += "<div class=\"clr\" ></div>";
// isFirstDollorRow = false;
//}
#endregion
# region items in rows other than the first row
//else
//{
outerSection = divWrap(metricLabel, "", "title");
column += divWrap(returnDirectionArrow(previousSalesCountValue, salesCount.ToString(), kpiHigh, kpiLow), "", "");
column += divWrap(previousSalesCount.ToString(), "", "count");
column += divWrap(r["SalesCountDifference"].ToString(), "", "percent");
section += divWrap(column, "", returnDirectionCSS(previousSalesCountValue, salesCount.ToString(), kpiHigh, kpiLow));
column = "";
column += divWrap(r["SalesCount"].ToString(), "", "value");
column += divWrap(r["AvgSalesCount"].ToString() + " AVG", "", "avg");
section += divWrap(column, "", "data");
section += divWrap(r["TrendingSalesCount"].ToString(), "", "sparkline");
section = divWrap(section, "", "moduleElement");
outerSection += section;
column = "";
section = "";
column += divWrap(returnDirectionArrow(previousSalesDollarsValue, salesDollars, kpiHigh, kpiLow), "", "");
column += divWrap(previousSalesDollars.ToString(), "", "count");
column += divWrap(r["SalesDollarsDifference"].ToString(), "", "percent");
section += divWrap(column, "", returnDirectionCSS(previousSalesDollarsValue, salesDollars, kpiHigh, kpiLow));
column = "";
column += divWrap(r["SalesDollars"].ToString(), "", "value");
column += divWrap(r["AvgSalesDollars"].ToString() + " AVG", "", "avg");
section += divWrap(column, "", "data");
section += divWrap(r["TrendingSalesDollars"].ToString(), "", "sparkline");
section = divWrap(section, "", "moduleElement");
outerSection += section;
salesHtml += divWrap(outerSection, "", "moduleA");
salesHtml += "<div class=\"clr\" ></div>";
}
#endregion
//}
break;
#endregion
#region Switch for Consumption
case "Count":
foreach (DataRow r in t.Rows)
{
column = "";
section = "";
outerSection = "";
previousCount = r["PreviousCount"].ToString();
metricCount = r["MetricCount"].ToString();
previousCountValue = Convert.ToInt32(r["PreviousCountValue"]);
if ("" != r["DetailReportLink"].ToString()) metricLabel = aWrap(r["MetricLabel"].ToString(), r["DetailReportLink"].ToString());
else metricLabel = r["MetricLabel"].ToString();
outerSection = divWrap(metricLabel, "", "title");
column += divWrap(returnDirectionArrow(previousCountValue, metricCount.ToString(), kpiHigh, kpiLow), "", "");
column += divWrap(previousCount.ToString(), "", "count");
//column += divWrap(r["SalesCountDifference"].ToString(), "", "percent");
section += divWrap(column, "", returnDirectionCSS(previousCountValue, metricCount.ToString(), kpiHigh, kpiLow));
column = "";
column += divWrap(r["MetricCount"].ToString(), "", "value");
column += divWrap(r["AvgCount"].ToString() + " AVG", "", "avg");
section += divWrap(column, "", "data");
section += divWrap(r["TrendingCount"].ToString(), "", "sparkline");
section = divWrap(section, "", "");
outerSection += section;
consumptionHmtl += divWrap(outerSection, "", "moduleB");
//salesHtml += "<div class=\"clr\" ></div>";
}
break;
#endregion
#region Switch for Gauge2??
case "Gauge2":
foreach (DataRow r in t.Rows)
{
column = "";
section = "";
outerSection = "";
previousCount = r["PreviousCount"].ToString();
metricCount = r["MetricCount"].ToString();
previousCountValue = Convert.ToInt32(r["PreviousCountValue"]);
if ("" != r["DetailReportLink"].ToString()) metricLabel = aWrap(r["MetricLabel"].ToString(), r["DetailReportLink"].ToString());
else metricLabel = r["MetricLabel"].ToString();
outerSection = divWrap(metricLabel, "", "title");
column += divWrap(returnDirectionArrow(previousCountValue, metricCount.ToString(), kpiHigh, kpiLow), "", "");
column += divWrap(previousCount.ToString(), "", "count");
//column += divWrap(r["SalesCountDifference"].ToString(), "", "percent");
section += divWrap(column, "", returnDirectionCSS(previousCountValue, metricCount.ToString(), kpiHigh, kpiLow));
column = "";
column += divWrap(r["MetricCount"].ToString(), "", "value");
column += divWrap(r["AvgCount"].ToString() + " AVG", "", "avg");
section += divWrap(column, "", "data");
section += divWrap(r["TrendingCount"].ToString(), "", "sparkline");
section = divWrap(section, "", "");
outerSection += section;
//consumptionHmtl += divWrap(outerSection, "", "moduleB");
//salesHtml += "<div class=\"clr\" ></div>";
}
break;
#endregion
}
}
//}
//else { }
}
}
#region SQL Connection
private static SqlConnection rptConn = new SqlConnection("Data Source=74.81.187.221,6970;Initial Catalog=Report;User ID=Report;Password=numb3rs");
public static DataSet getDashElementDataset(string sproc, DateTime dt)
{
SqlConnection conn = rptConn;
SqlCommand cmd = new SqlCommand(sproc, conn);
if (dt > Convert.ToDateTime("01/01/2010") && dt < DateTime.Now.AddMinutes(-5))
{
SqlParameter param1 = new SqlParameter("@ipActivityDate", SqlDbType.DateTime);
param1.Value = dt;
cmd.Parameters.Add(param1);
}
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
DataSet ds = new DataSet();
try
{
da.Fill(ds);
}
catch { }
conn.Close();
return ds;
}
#endregion
private string returnDirectionArrow(int prevValue, string value, double variantHigh, double variantLow){
value = value.Replace("$", "");
value = value.Replace(",", "");
int valueInt = Convert.ToInt32(value);
variantHigh = prevValue * (1 + variantHigh); //offsetting the difference ex Add 5% of $3000 = $3150
variantLow = prevValue * (1 - variantLow); //offsetting the difference ex Subtract 5% of $3000 = $2850
if (variantHigh < valueInt) return "<img src=\"/up2.png\" />";
else if (variantLow > valueInt) return "<img src=\"/down2.png\" />";
else return "<img src=\"/neutral2.png\" />";
//if (prevValue > 0) return "<img src=\"up2.png\" />";
//else return "<img src=\"down2.png\" />";
//return "<img src=\"up2.png\" />";
}
private string returnDirectionCSS(int prevValue, string value, double variantHigh, double variantLow)
{
value = value.Replace("$", "");
value = value.Replace(",", "");
int valueInt = Convert.ToInt32(value);
variantHigh = prevValue * (1 + variantHigh); //offsetting the difference ex Add 5% of $3000 = $3150
variantLow = prevValue * (1 - variantLow); //offsetting the difference ex Subtract 5% of $3000 = $2850
if (variantHigh < valueInt) return "directionUp";
else if (variantLow > valueInt) return "directionDown";
else return "directionNone";
//return "directionNone";
}
private static string divWrap(string data, string idName, string className) {
if (idName != "") idName = " id=\"" + idName + "\" ";
if (className != "") className = " class=\"" + className + "\" ";
return "<div"+idName+className+">"+data+"</div>\n";
}
private static string aWrap(string label, string link) {
return "<a href=\""+link+"\">"+label+"</a>";
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using DelftTools.Utils;
using DelftTools.Utils.Data;
using GeoAPI.Extensions.Feature;
using GeoAPI.Geometries;
using NetTopologySuite.Extensions.Coverages;
using NUnit.Framework;
using SharpMap.Data.Providers;
namespace SharpMap.Tests.Data.Providers
{
[TestFixture]
public class FeatureCollectionTest
{
[Test]
[ExpectedException(typeof(ArgumentException))]
public void AddingInvalidTypeGivesArgumentException()
{
IList list = new List<IFeature>();
FeatureCollection featureCollection = new FeatureCollection(list,typeof(string));
// TODO: WHERE ARE ASSERTS????!~?!?!?!#@$!@#
}
[Test]
public void AddingValidTypeIsOk()
{
IList list = new List<IFeature>();
FeatureCollection featureCollection = new FeatureCollection(list, typeof(NetworkLocation));
// TODO: WHERE ARE ASSERTS????!~?!?!?!#@$!@#
}
[Test]
public void FeatureCollectionTimesMustBeExtractedFromFeature()
{
var features = new[]
{
new TimeDependentFeature {Time = new DateTime(2000, 1, 1)},
new TimeDependentFeature {Time = new DateTime(2001, 1, 1)},
new TimeDependentFeature {Time = new DateTime(2002, 1, 1)}
};
var featureCollection = new FeatureCollection(features, typeof (TimeDependentFeature));
featureCollection.Times
.Should().Have.SameSequenceAs(new[]
{
new DateTime(2000, 1, 1),
new DateTime(2001, 1, 1),
new DateTime(2002, 1, 1)
});
}
[Test]
public void FilterFeaturesUsingStartTime()
{
var features = new[]
{
new TimeDependentFeature {Time = new DateTime(2000, 1, 1)},
new TimeDependentFeature {Time = new DateTime(2001, 1, 1)}
};
var featureCollection = new FeatureCollection(features, typeof(TimeDependentFeature));
featureCollection.SetCurrentTimeSelection(new DateTime(2001, 1, 1), null);
featureCollection.Features.Count
.Should().Be.EqualTo(1);
}
[Test]
public void FilterFeaturesUsingTimeRange()
{
var features = new[]
{
new TimeDependentFeature {Time = new DateTime(2000, 1, 1)},
new TimeDependentFeature {Time = new DateTime(2001, 1, 1)},
new TimeDependentFeature {Time = new DateTime(2002, 1, 1)}
};
var featureCollection = new FeatureCollection(features, typeof (TimeDependentFeature));
featureCollection.SetCurrentTimeSelection(new DateTime(2001, 1, 1), new DateTime(2001, 2, 1));
featureCollection.Features.Count
.Should().Be.EqualTo(1);
}
public class TimeDependentFeature : Unique<long>, IFeature, ITimeDependent
{
public object Clone()
{
throw new NotImplementedException();
}
public IGeometry Geometry { get; set; }
public IFeatureAttributeCollection Attributes { get; set; }
public DateTime Time { get; set; }
}
}
}
|
namespace BuhtigIssueTracker.DataProviders
{
using Enums;
using Interfaces;
using Utilities;
public class Dispatcher
{
public Dispatcher(IIssueTracker tracker)
{
this.Tracker = tracker;
}
public Dispatcher() : this(new IssueTracker())
{
}
public IIssueTracker Tracker { get; }
public string DispatchAction(IEndpoint endpoint)
{
switch (endpoint.ActionName)
{
case "RegisterUser":
return this.Tracker
.RegisterUser(
endpoint.Parameters["username"],
endpoint.Parameters["password"],
endpoint.Parameters["confirmPassword"]);
case "LoginUser":
return this.Tracker
.LoginUser(
endpoint.Parameters["username"],
endpoint.Parameters["password"]);
case "LogoutUser":
return this.Tracker.LogoutUser();
case "CreateIssue":
return this.Tracker
.CreateIssue(
endpoint.Parameters["title"],
endpoint.Parameters["description"],
endpoint.Parameters["priority"].GetStringValueAsEnumType<IssuePriority>(),
endpoint.Parameters["tags"].Split('|'));
case "RemoveIssue":
return this.Tracker.RemoveIssue(int.Parse(endpoint.Parameters["id"]));
case "AddComment":
return this.Tracker.AddComment(
int.Parse(endpoint.Parameters["id"]),
endpoint.Parameters["text"]);
case "MyIssues":
return this.Tracker.GetMyIssues();
case "MyComments":
return this.Tracker.GetMyComments();
case "Search":
return this.Tracker.SearchForIssues(endpoint.Parameters["tags"].Split('|'));
default:
return $"Invalid action: {endpoint.Parameters}";
}
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Conditions;
using Conditions.Guards;
using Properties.Core.Interfaces;
using Properties.Core.Objects;
using Properties.Factories;
using Properties.Helper;
using Properties.Models;
using Swashbuckle.Swagger.Annotations;
using CaselistEntry = Properties.Models.CaselistEntry;
using PropertyItem = Properties.Models.PropertyItem;
using PropertySummary = Properties.Models.PropertySummary;
namespace Properties.Controllers
{
public class PropertyCaselistController : ApiController
{
private readonly ICaselistService _caselistService;
private readonly IPropertyServiceFacade _propertyService;
public PropertyCaselistController(ICaselistService caselistService, IPropertyServiceFacade propertyService)
{
_caselistService = caselistService;
_propertyService = propertyService;
}
[HttpGet, Route("api/caselists")]
public CaselistSummary GetSummary([FromUri]string[] areas)
{
Check.If(areas).IsNotNull();
var summary = new CaselistSummary();
var result = _caselistService.GetPropertiesForAreas(areas.ToList()).Select(Mapper.Map<CaselistEntry>).ToList();
var tabs = result.Select(x => x.PipelinePosition).Distinct().ToList();
for (var i = 0; i < tabs.Count; i++)
{
summary.TabSummary.Add(TabFactory.BuildTab(i, tabs[i], result.Count(x => x.PipelinePosition == tabs[i])));
}
return summary;
}
[HttpGet, Route("api/caselists/tab", Name = "GetCasesByTab")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<CaselistEntry>))]
public HttpResponseMessage Get([FromUri]string[] areas, string tabName, string orderBy = "Date Modified", int pageNumber = 0, int pageSize = 25)
{
var result =
_caselistService.GetPropertyCaselistEntryForAreaAndStatus(areas.Distinct().ToList(), EnumHelper<PipelinePosition>.Parse(tabName),
EnumHelper<Ordering>.Parse(orderBy), PageFactory.CreatePage(pageNumber, pageSize)).Select(Mapper.Map<CaselistEntry>).ToList();
if (result.IsEmpty())
return Request.CreateResponse(new List<CaselistEntry>());
var response = Request.CreateResponse(result);
response.Headers.Add("Link", $@"<{Url.Link("GetCasesByTab", new { })}?{QueryStringHelper.BuildQueryString(areas, tabName, pageNumber, pageSize)}>; rel=""Next""");
return response;
}
[HttpGet, Route("api/caselists/tab/properties", Name = "GetPropertiesByTab")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<PropertySummary>))]
public HttpResponseMessage GetSummaries([FromUri]string[] areas, string tabName, string orderBy = "Date Modified", int pageNumber = 0, int pageSize = 25)
{
var properties =
_caselistService.GetPropertySummariesForAreaAndStatus(areas.Distinct().ToList(), EnumHelper<PipelinePosition>.Parse(tabName),
EnumHelper<Ordering>.Parse(orderBy), PageFactory.CreatePage(pageNumber, pageSize)).Select(Mapper.Map<PropertySummary>).ToList();
if (properties.IsEmpty())
return Request.CreateResponse(new List<PropertySummary>());
var response = Request.CreateResponse(properties);
response.Headers.Add("Link", $@"<{Url.Link("GetCasesByTab", new { })}?{QueryStringHelper.BuildQueryString(areas, tabName, pageNumber, pageSize)}>; rel=""Next""");
return response;
}
[HttpPost, Route("api/caselist/propertyitems", Name = "GetPropertySummariesByPropertyItems")]
public HttpResponseMessage GetSummaries(List<PropertyItem> propertyItems)
{
Check.If(propertyItems).IsNotNull();
var summaries = Mapper.Map<List<PropertySummary>>(_propertyService.GetPropertySummariesByPropertyItems(Mapper.Map<List<Core.Objects.PropertyItem>>(propertyItems)));
if (summaries.Count < 1)
return new HttpResponseMessage(HttpStatusCode.NotFound);
var response = Request.CreateResponse(summaries);
return response;
}
}
}
|
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 PIBP
{
public partial class Treneri : Form
{
public Treneri()
{
InitializeComponent();
}
private void Treneri_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataTreneri.TRENERI' table. You can move, or remove it, as needed.
this.tRENERITableAdapter.Fill(this.dataTreneri.TRENERI);
}
private void tRENERIBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
this.tRENERITableAdapter.Update(this.dataTreneri);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FightManager : MonoBehaviour
{
public PlayerController player1;
public PlayerController player2;
public SoundCombo[] startFightSounds;
public SoundCombo[] endFightSounds;
private void Awake()
{
Init();
}
private void Init()
{
player1.onHitTry += x => TryHit(player1, x);
player2.onHitTry += x => TryHit(player2, x);
}
public void Switch(bool isOn)
{
player1.gameObject.SetActive(isOn);
player2.gameObject.SetActive(isOn);
if(isOn)
{
player1.Reset();
player2.Reset();
SoundManager.PlaySound(startFightSounds);
}
}
public void End(PlayerController wonPlayer)
{
player1.active = false;
player2.active = false;
SoundManager.PlaySound(endFightSounds);
UIManager.ShowGameOver(wonPlayer);
}
private void TryHit(PlayerController player, Anims anim)
{
if (player1.transform.position.x > player2.transform.position.x)
{
if (Vector3.Distance(player1.transform.position, player2.transform.position) <= anim.anim.hitDistance)
{
if (player == player1)
{
if (player2.Hit(anim.hitAmount * Random.Range(0.5f, 1.5f)))
{
End(player1);
}
}
else
{
if (player1.Hit(anim.hitAmount * Random.Range(0.5f, 1.5f)))
{
End(player2);
}
}
}
}
}
}
|
using fileCrawlerWPF.Exceptions;
using fileCrawlerWPF.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
namespace fileCrawlerWPF.Media
{
public sealed class MediaCollection
{
private readonly object _lock = new object();
private readonly Dictionary<Guid, ProbeFile> _cache;
public MediaCollection()
{
_cache = new Dictionary<Guid, ProbeFile>();
Directories = new ObservableCollection<FileDirectory>();
}
public ObservableCollection<FileDirectory> Directories { get; private set; }
public IReadOnlyCollection<ProbeFile> CachedFiles { get => _cache.Values; }
private ProbeFile Cache(Guid id, string path)
{
if (_cache.ContainsKey(id))
{
return _cache[id];
}
else
{
var pf = new ProbeFile(path, id);
_cache.Add(pf.ID, pf);
return pf;
}
}
public ProbeFile GetFile(FileDirectory item)
=> Cache(item.ID, item.Path);
public ProbeFile GetFile(Guid id)
=> Cache(id, string.Empty);
public void ProcessDirectory(string path)
{
lock (_lock)
{
if (Directories.Any(x => x.Path == path))
throw new DirectoryAlreadyExistsException(path);
try
{
using (new WaitCursor())
{
if (File.Exists(path))
{
if (!Directories.Any(x => x.Path == path))
Directories.Add(new FileDirectory(path, Path.GetFileName(path)));
}
else if (Directory.Exists(path))
{
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
files.ToList().ForEach(x =>
{
if (!Directories.Any(y => y.Path == x))
Directories.Add(new FileDirectory(x, Path.GetFileName(x)));
});
}
}
}
catch (Exception)
{
// attempt to remove this directory from the list.
var logged = Directories.FirstOrDefault(x => x.Path == path);
if (!(logged.Name is null))
Directories.Remove(logged);
throw;
}
}
}
public void CacheAll()
{
foreach (var item in Directories)
{
Cache(item.ID, item.Path);
}
}
public void RemoveFile(Guid id)
{
lock (_lock)
{
if (!Directories.Any(x => x.ID == id)) throw new ArgumentException("id is not recognised");
var dir = Directories.First(x => x.ID == id);
Directories.Remove(dir);
_cache.Remove(id);
}
}
public void Reset()
{
lock(_lock)
{
_cache.Clear();
Directories.Clear();
}
}
}
} |
using Orleans;
using OrleansR.GrainInterfaces;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Concurrency;
namespace OrleansR.Grains
{
[Reentrant]
public class PubSubGrain : Orleans.Grain, IPubSubGrain
{
ObserverSubscriptionManager<IMessageObserver> observers;
IPubSubGrain[] otherGrains;
ulong index = 0;
public async override Task ActivateAsync()
{
this.observers = new ObserverSubscriptionManager<IMessageObserver>();
this.otherGrains = new IPubSubGrain[] { };
var manager = PubSubManagerFactory.GetGrain(0);
this.otherGrains = await manager.Register(this);
await base.ActivateAsync();
}
public async Task Publish(Microsoft.AspNet.SignalR.Messaging.Message[] messages)
{
await Task.WhenAll(this.otherGrains.Select(x => x.Notify(messages)).ToArray());
}
public Task Subscribe(IMessageObserver observer)
{
this.observers.Subscribe(observer);
return TaskDone.Done;
}
public async Task Unsubscribe(IMessageObserver observer)
{
this.observers.Unsubscribe(observer);
if (this.observers.Count == 0)
{
var manager = PubSubManagerFactory.GetGrain(0);
await manager.Unregister(this);
this.DeactivateOnIdle(); // remove this grain
}
}
public Task Notify(Microsoft.AspNet.SignalR.Messaging.Message[] messages)
{
foreach (var message in messages)
{
message.MappingId = index++;
}
this.observers.Notify(x => x.Send(messages));
return TaskDone.Done;
}
public Task TopologyChange(IPubSubGrain[] otherGrains)
{
this.otherGrains = otherGrains;
return TaskDone.Done;
}
public override Task DeactivateAsync()
{
var manager = PubSubManagerFactory.GetGrain(0);
return manager.Unregister(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryProject
{
class Organisation
{
public List<Factory> Factories { get; set; }
public List<Store> Stores { get; set; }
public List<Contract> ContractsConducted { get; set; }
public List<Supplier> Suppliers { get; set; }
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private double moneyBalance;
public double MoneyBalance
{
get
{
double profit = 0;
foreach (var factory in Factories)
{
profit -= factory.Expenses;
}
foreach (var store in Stores)
{
profit += store.Income;
}
return moneyBalance + profit;
}
private set
{
moneyBalance = value;
}
}
public Organisation(string name)
{
Name = name;
Factories = new List<Factory>();
Stores = new List<Store>();
ContractsConducted = new List<Contract>();
Suppliers = new List<Supplier>();
}
public Contract ProduceContract(Factory factoryRequesting)
{
List<RawMaterialOffer> offers = RequestOffers();
RawMaterialOffer offerForContract = BestOffer(offers);
return new Contract(offerForContract, this, offerForContract.SupplierRelated, factoryRequesting, DateTime.Now);
}
public List<RawMaterialOffer> RequestOffers()
{
return null;
}
public static RawMaterialOffer BestOffer(List<RawMaterialOffer> offers)
{
List<double> quality = new List<double>() { };
List<double> price = new List<double>() { };
List<double> quantity = new List<double>() { };
List<double> gradesOfOffers = new List<double>() { };
double maxQuality, maxPrice, maxQuantity;
//Populating lists of quality, price etc
foreach (var offer in offers)
{
quality.Add(offer.Quality);
price.Add(Math.Pow(offer.PricePerKilo, -1));
quantity.Add(Math.Pow(offer.RawMaterialAmount, -1));
}
//finding max values
maxPrice = price.Max();
maxQuality = quality.Max();
maxQuantity = quantity.Max();
//Making all values relational to max
//Creating grades for each offer
for (int i = 0; i < quality.Count; i++)
{
quality[i] = quality[i] / maxQuality * 100;
quantity[i] = quantity[i] / maxQuantity * 100;
price[i] = price[i] / maxPrice * 100;
gradesOfOffers.Add(price[i] * 1.7 + quality[i] * 1 + quantity[i] * 0.3);
}
//chosing the best offer based on score
int indexBestOffer = gradesOfOffers.IndexOf(gradesOfOffers.Max());
return offers[indexBestOffer];
}
}
}
|
using System;
namespace Alabo.UI.Design.AutoTasks {
public class AutoTask {
public AutoTask() {
}
public AutoTask(string name, Guid moduleId, Type serviceType, string method) {
Name = name;
Method = method;
ModuleId = moduleId;
ServcieType = serviceType;
}
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 模块Id
/// </summary>
public Guid ModuleId { get; set; }
/// <summary>
/// 集成后台服务的Type
/// </summary>
public Type ServcieType { get; set; }
/// <summary>
/// 方法
/// </summary>
public string Method { get; set; }
}
} |
using Microsoft.Xna.Framework;
namespace BuildingGame
{
class Wohnhaus : Building
{
public Wohnhaus()
{
//Sprite = Sprites.Wohnhaus;
Cost = new Item(Item.ItemType.Holz, 20);
}
}
} |
using System.Collections.Generic;
using ServiceDeskSVC.DataAccess.Models;
namespace ServiceDeskSVC.DataAccess
{
public interface IHelpDeskTicketStatusRepository
{
List<HelpDesk_TicketStatus> GetAllStatuses();
bool DeleteStatusById(int id);
int CreateStatus(HelpDesk_TicketStatus status);
int EditStatusById(int id, HelpDesk_TicketStatus status);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MileCode {
[ExecuteInEditMode]
public class LBP_Settings : MonoBehaviour {
public int lightmapIndex;
public Vector4 lightmapScaleAndOffset = new Vector4(1, 1, 0, 0);
public Texture2D lightmap;
private new Renderer renderer;
private MaterialPropertyBlock propBlock;
void SetLightmapValues(int index, Vector4 scaleAndOffset) {
this.lightmapIndex = index;
this.lightmapScaleAndOffset = scaleAndOffset;
}
private void Awake() {
this.propBlock = new MaterialPropertyBlock();
this.renderer = GetComponent<Renderer>();
}
private void Update() {
if(propBlock != null) {
renderer.GetPropertyBlock(propBlock);
propBlock.SetVector("_Lightmap_ST", lightmapScaleAndOffset);
if(lightmap != null) {
propBlock.SetTexture("_Lightmap", lightmap);
}
renderer.SetPropertyBlock(propBlock);
}
}
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BinaryFog.NameParser.Tests {
/// <summary>
///This is a test class for FullNameParserTest and is intended
///to contain all FullNameParserTest Unit Tests
///</summary>
[TestClass]
public class FullNameParserTest {
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
[ExcludeFromCodeCoverage]
public TestContext TestContext { get; set; }
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for Parse
///</summary>
[TestMethod]
public void Parse_JackJohnson() {
var fullName = "Jack Johnson";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Jack Johnson", target.DisplayName);
Assert.IsNull(target.Title);
}
[TestMethod]
public void Parse_MrDotJackJohnson() {
var fullName = "Mr. Jack Johnson";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Jack Johnson", target.DisplayName);
Assert.AreEqual("Mr.", target.Title);
}
[TestMethod]
public void Parse_MrJackJohnson() {
var fullName = "Mr Jack Johnson";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Jack Johnson", target.DisplayName);
Assert.AreEqual("Mr", target.Title);
}
[TestMethod]
public void Parse_MrJackJohnsonJrDOT() {
var fullName = "Mr Jack Johnson Jr.";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Jack Johnson", target.DisplayName);
Assert.AreEqual("Mr", target.Title);
}
[TestMethod]
public void Parse_MrJayJPositano() {
var fullName = "Mr Jay J Positano";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jay", target.FirstName);
Assert.AreEqual("Positano", target.LastName);
Assert.AreEqual("Jay Positano", target.DisplayName);
Assert.AreEqual("Mr", target.Title);
}
[TestMethod]
public void Parse_MrJayJDOTPositano() {
var fullName = "Mr Jay J. Positano";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Jay", target.FirstName);
Assert.AreEqual("Positano", target.LastName);
Assert.AreEqual("Jay Positano", target.DisplayName);
Assert.AreEqual("Mr", target.Title);
}
[TestMethod]
public void Parse_MrJackJohnsonJr() {
var fullName = "Mr Jack Johnson Jr";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr", target.Title);
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Jack Johnson", target.DisplayName);
}
[TestMethod]
public void Parse_AffiliatedForkliftServices() {
var fullName = "AFFILIATED FORKLIFT SERVICES";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("AFFILIATED FORKLIFT SERVICES", target.DisplayName);
Assert.IsNull(target.FirstName);
Assert.IsNull(target.LastName);
Assert.IsNull(target.Title);
Assert.IsNull(target.NickName);
}
[TestMethod]
public void Parse_AkContractingSCOPEKenoraSCOPELtd() {
var fullName = "AK CONTRACTING (KENORA) LTD.";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("AK CONTRACTING (KENORA) LTD.", target.DisplayName);
}
[TestMethod]
public void Parse_PasqualeSCOPEPatSCOPEJohnson() {
var fullName = "Pasquale (Pat) Johnson";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Pasquale", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Pasquale Johnson", target.DisplayName);
Assert.AreEqual("Pat", target.NickName);
}
[TestMethod]
public void Parse_MrDOTPasqualeSCOPEPatSCOPEJohnson() {
var fullName = "Mr. Pasquale (Pat) Johnson";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr.", target.Title);
Assert.AreEqual("Pasquale", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Pasquale Johnson", target.DisplayName);
Assert.AreEqual("Pat", target.NickName);
}
[TestMethod]
public void Parse_MrDOTPasqualeSCOPEPatSCOPEJohnsonJr() {
var fullName = "Mr. Pasquale (Pat) Johnson Jr";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr.", target.Title);
Assert.AreEqual("Pasquale", target.FirstName);
Assert.AreEqual("Johnson", target.LastName);
Assert.AreEqual("Pasquale Johnson", target.DisplayName);
Assert.AreEqual("Pat", target.NickName);
Assert.AreEqual("Jr", target.Suffix);
}
[TestMethod]
public void Parse_CompanyNamesAsPersonNames() {
string[] companyNamesAsPersonNames = { "AL HUGHES (MARINE)", "HI TECH HYDRAULICS (1985) LT", "ALFALFA BEEKEEPERS LTD",
"ALAA SALAH AELSAYAD@TORCC."};
foreach (var item in companyNamesAsPersonNames) {
Console.WriteLine(item);
var fullName = item;
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual(fullName, target.DisplayName);
Assert.IsNull(target.FirstName);
Assert.IsNull(target.LastName);
Assert.IsNull(target.Title);
Assert.IsNull(target.NickName);
}
}
[TestMethod]
public void Parse_ATTNMrEricKing() {
var fullName = "ATTN: MR. ERIC KING";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("ERIC KING", target.DisplayName);
Assert.AreEqual("ERIC", target.FirstName);
Assert.AreEqual("KING", target.LastName);
Assert.AreEqual("MR.", target.Title);
}
[TestMethod]
public void Parse_Catalin() {
var fullName = "Catalin";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Catalin", target.FirstName);
}
[TestMethod]
public void Parse_Arroyo() {
var fullName = "Arroyo";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Arroyo", target.LastName);
}
[TestMethod]
public void Parse_MrGiocomoVanExan() {
var fullName = "Mr Giocomo Van Exan";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr", target.Title);
Assert.AreEqual("Giocomo", target.FirstName);
Assert.AreEqual("Van Exan", target.LastName);
}
[TestMethod]
public void Parse_GiovanniVanDerHutte() {
var fullName = "Giovanni Van Der Hutte";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Giovanni", target.FirstName);
Assert.AreEqual("Van Der Hutte", target.LastName);
}
[TestMethod]
public void Parse_MsSandyAccountsReceivable() {
var fullName = "Ms Sandy Accounts Receivable";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Ms", target.Title);
Assert.AreEqual("Sandy", target.FirstName);
Assert.AreEqual("Sandy Accounts Receivable", target.DisplayName);
}
[TestMethod]
public void Parse_SandyAccountsReceivable() {
var fullName = "Sandy Accounts Receivable";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Sandy", target.FirstName);
}
[TestMethod]
public void Parse_MrJackFrancisVanDerWaalSr() {
var fullName = "Mr. Jack Francis Van Der Waal Sr.";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr.", target.Title);
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Francis", target.MiddleName);
Assert.AreEqual("Van Der Waal", target.LastName);
Assert.AreEqual("Sr.", target.Suffix);
Assert.AreEqual("Jack Van Der Waal", target.DisplayName);
}
[TestMethod]
public void Parse_MrJackFrancisMarionVanDerWaalSr() {
var fullName = "Mr. Jack Francis Marion Van Der Waal Sr.";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual("Mr.", target.Title);
Assert.AreEqual("Jack", target.FirstName);
Assert.AreEqual("Francis Marion", target.MiddleName);
Assert.AreEqual("Van Der Waal", target.LastName);
Assert.AreEqual("Sr.", target.Suffix);
}
[TestMethod]
public void Parse_Null() {
string fullName = null;
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual(null, target.Title);
Assert.AreEqual(null, target.FirstName);
Assert.AreEqual(null, target.MiddleName);
Assert.AreEqual(null, target.LastName);
Assert.AreEqual(null, target.Suffix);
}
[TestMethod]
public void Parse_Blank() {
var fullName = "";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual(null, target.Title);
Assert.AreEqual(null, target.FirstName);
Assert.AreEqual(null, target.MiddleName);
Assert.AreEqual(null, target.LastName);
Assert.AreEqual(null, target.Suffix);
}
[TestMethod]
public void Parse_Space() {
var fullName = " ";
var target = new FullNameParser(fullName);
target.Parse();
Assert.AreEqual(null, target.Title);
Assert.AreEqual(null, target.FirstName);
Assert.AreEqual(null, target.MiddleName);
Assert.AreEqual(null, target.LastName);
Assert.AreEqual(null, target.Suffix);
}
[TestMethod]
public void Parse_Static() {
var fullName = "";
var target = FullNameParser.Parse(fullName);
Assert.IsNotNull(target);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace solmates {
public class FriendlySoul : MonoBehaviour {
[SerializeField]
Color[] colors;
public Color finalcolor;
public Transform player;
public float SizeCategory;
public bool threeSizeChoses = true;
public float minSize=.5f;
public float maxSize=3f;
public float spriteAlpha = .5f;
private void Awake() {
if (threeSizeChoses) {
//only 3 sizes
SizeCategory = Random.Range(1, 4);
}
else {
//more than 3 sizes
SizeCategory = Random.Range(minSize, maxSize);
}
int colorchosen = Random.Range(0, colors.Length);
finalcolor = colors[colorchosen];
foreach (SpriteRenderer sr in GetComponentsInChildren<SpriteRenderer>()) {
finalcolor.a = spriteAlpha;
sr.color = finalcolor;
}
}
void Start() {
player = GameObject.FindGameObjectWithTag("Player").transform;
transform.LookAt(player, transform.up);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.InterfaceImplementation
{
class Program
{
static void Main(string[] args)
{
var fooSide3 = new Polygon3(8);
Console.WriteLine($"Perimeter: {fooSide3.GetPerimeter()}");
Console.WriteLine($"Area: {fooSide3.GetArea()}");
var fooSide4 = new Polygon4(8);
Console.WriteLine($"Perimeter: {fooSide4.GetPerimeter()}");
Console.WriteLine($"Area: {fooSide4.GetArea()}");
Console.WriteLine("Press any key for continuing...");
Console.ReadKey();
}
}
public interface IPolygon
{
int Side { get; set; }
double Length { get; set; }
double GetPerimeter();
double GetArea();
}
public class Polygon3 : IPolygon
{
public int Side { get; set; }
public double Length { get; set; }
public Polygon3(double length)
{
Side = 3;
Length = length;
}
public double GetPerimeter() => Side * Length;
public double GetArea() => Length * Length * Math.Sqrt(3) / 4;
}
public class Polygon4 : IPolygon
{
public int Side { get; set; }
public double Length { get; set; }
public Polygon4(double length)
{
Side = 4;
Length = length;
}
public double GetPerimeter() => Side * Length;
public double GetArea() => Length * Length;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccessLayer.Repository;
using DataAccessLayer;
using System.Data.Entity;
using System.Data.Entity.Validation;
namespace DataAccessLayer
{
public class UnitOfWork
{
TaskManagementContext _dbContext;
DbContextTransaction _transaction;
public UnitOfWork()
{
_dbContext = new TaskManagementContext();
//_transaction = _dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
}
private StateRepository _stateRepo;
public StateRepository StateRepository
{
get
{
if (_stateRepo==null)
{
_stateRepo = new StateRepository(_dbContext);
}
return _stateRepo;
}
}
private ProjectRepository _projectRepo;
public ProjectRepository ProjectRepository
{
get
{
if (_projectRepo==null)
{
_projectRepo = new ProjectRepository(_dbContext);
}
return _projectRepo;
}
}
private EmployeeRepository _employeeRepo;
public EmployeeRepository EmployeeRepository
{
get
{
if (_employeeRepo==null)
{
_employeeRepo = new EmployeeRepository(_dbContext);
}
return _employeeRepo;
}
}
private WorkRepository _workRepo;
public WorkRepository WorkRepository
{
get
{
if (_workRepo==null)
{
_workRepo = new WorkRepository(_dbContext);
}
return _workRepo;
}
}
private RequestRepository _requestRepo;
public RequestRepository RequestRepository
{
get
{
if (_requestRepo==null)
{
_requestRepo = new RequestRepository(_dbContext);
}
return _requestRepo;
}
}
private CustomerRepository _customerRepo;
public CustomerRepository CustomerRepository
{
get
{
if (_customerRepo==null)
{
_customerRepo = new CustomerRepository(_dbContext);
}
return _customerRepo;
}
}
private LoginRepository _loginRepo;
public LoginRepository LoginRepository
{
get
{
if (_loginRepo==null)
{
_loginRepo = new LoginRepository(_dbContext);
}
return _loginRepo;
}
}
private RoleRepository _roleRepo;
public RoleRepository RoleRepository
{
get
{
if (_roleRepo==null)
{
_roleRepo = new RoleRepository(_dbContext);
}
return _roleRepo;
}
}
public bool ApplyChanges()
{
bool isSuccess = false;
_transaction= _dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
try
{
_dbContext.SaveChanges();
_transaction.Commit();
isSuccess = true;
}
catch (Exception ex)
{
_transaction.Rollback();
isSuccess = false;
}
finally
{
_transaction.Dispose();
}
return isSuccess;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
public class CustomBehaviorReader
{
private const string CommentPrefix = "#";
private const string MappingsArgKey = "mappings";
private readonly ILineParser parser = new RegexLineParser();
private string indent;
public TaskSpec BuildRoot(Stream source)
{
return this.BuildRoot(source, new Stack<TaskSpec>());
}
private TaskSpec BuildRoot(Stream source, Stack<TaskSpec> stack)
{
using (source)
{
using (var reader = new StreamReader(source))
{
var lastIndent = -1;
stack.Clear();
stack.Push(new TaskSpec("ROOT"));
while (!reader.EndOfStream)
{
Debug.Assert(stack.Count > 0, "Task stack should not be empty");
var line = reader.ReadLine();
this.EnsureIndentDetected(line);
var trimmedLine = this.TrimIndentation(line);
// Skip comments.
if (trimmedLine.Length == 0 || trimmedLine.StartsWith(CommentPrefix))
continue;
var task = this.BuildTask(line);
var currentIndent = this.CountIndent(line);
if (currentIndent > lastIndent)
{
// We're adding the first child of a task.
this.AddToParent(task, stack);
stack.Push(task);
}
else if (currentIndent == lastIndent)
{
// We're adding a sibling, so first pop the previous child from the stack.
stack.Pop();
this.AddToParent(task, stack);
stack.Push(task);
}
else
{
// Pop stack to the corresponding indent level. We add 1 to the indent to account for the RootTask.
while (stack.Count > (currentIndent + 1))
{
stack.Pop();
}
this.AddToParent(task, stack);
stack.Push(task);
}
lastIndent = currentIndent;
}
// Pop stack to get back to the root task.
while (stack.Count > 1)
{
stack.Pop();
}
var root = stack.Peek();
stack.Clear();
return root;
}
}
}
private void EnsureIndentDetected(string line)
{
if (!string.IsNullOrEmpty(this.indent))
return;
if (line.Length == 0)
return;
switch (line[0])
{
case '\t':
this.indent = "\t";
break;
case ' ':
this.indent = line.Substring(0, line.Length - line.TrimStart(' ').Length);
break;
}
}
private string TrimIndentation(string line)
{
if (string.IsNullOrEmpty(this.indent)) return line;
while (line.StartsWith(this.indent))
{
line = line.Substring(this.indent.Length);
}
return line;
}
private int CountIndent(string line)
{
if (string.IsNullOrEmpty(this.indent)) return 0;
return Regex.Matches(line, this.indent).Count;
}
private TaskSpec BuildTask(string line)
{
string name;
IDictionary<string, string> args;
this.parser.Parse(line, out name, out args);
var spec = new TaskSpec(name);
foreach (var item in args) spec.Args.Add(item);
return spec;
}
private void AddToParent(TaskSpec task, Stack<TaskSpec> stack)
{
if (stack.Count == 0)
throw new InvalidOperationException(string.Format("Cannot add the task {0} to its parent as the task stack is empty and no parent can be found", task));
var parent = stack.Peek();
parent.Children.Add(task);
}
} |
namespace Alabo.Test.Base.Core.Model
{
/// <summary>
/// 控制测试方法基类
/// </summary>
public abstract class BaseControllerTest : CoreTest
{
}
} |
using System;
using System.Text;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using GK.Core;
namespace GK.Api.Core
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeXApiAttribute : TypeFilterAttribute
{
public AuthorizeXApiAttribute()
: base(typeof(AuthorizeXApiFilter))
{
}
}
public class AuthorizeXApiFilter : IAuthorizationFilter
{
private readonly IWebHostEnvironment _env;
private readonly IConfiguration _configuration;
public AuthorizeXApiFilter(IWebHostEnvironment env, IConfiguration configuration)
{
_env = env ?? throw new GKFriendlyException(HttpStatusCode.InternalServerError, nameof(env));
_configuration = configuration ?? throw new GKFriendlyException(HttpStatusCode.InternalServerError, nameof(configuration));
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (_env.IsDevelopment())
return;
string xApiKey = context.HttpContext.Request.Headers["x-api-key"];
if (xApiKey != null)
{
if (xApiKey == _configuration["XApiKey"]
|| xApiKey == _configuration.GetSection(ConfigSections.Configuration)["XApiKey"])
return;
}
context.HttpContext.Response.Headers["WWW-Authenticate"] = "x-api-key";
context.Result = new UnauthorizedResult();
}
}
}
|
namespace kindergarden.Models
{
public class galleryImage
{
public int Id { get; set; }
public string filePath { get; set; }
public int galleryId { get; set; }
public gallery gallery { get; set; }
}
} |
using System;
using System.Threading;
namespace OMKServer
{
class Program
{
static void Main(string[] args)
{
var serverOption = ParseCommandLine(args);
if (serverOption == null)
{
return;
}
var serverApp = new MainServer();
serverApp.InitConfig(serverOption);
serverApp.CreateStartServer();
MainServer.MainLogger.Info("Press q to shut down the server");
while (true)
{
Thread.Sleep(50);
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.KeyChar == 'q')
{
Console.WriteLine("Server Terminate~~");
serverApp.StopServer();
break;
}
}
}
}
static OMKServerOption ParseCommandLine(string[] args)
{
var result =
CommandLine.Parser.Default.ParseArguments<OMKServerOption>(args) as
CommandLine.Parsed<OMKServerOption>;
if (result == null)
{
Console.WriteLine("Failed Command Line");
return null;
}
return result.Value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Configuration;
using BPMInterfaceModel;
namespace BPMInterfaceToolkit
{
public class EmailHelper
{
//static string MailFrom = "AttendanceAdmin@shry.net";
//static string Password = "91338720";
//static string smtp = "smtp.ee-post.com";
//static int port = 25;
static string MailFrom = ConfigurationManager.AppSettings["EmailAccount"].Trim();
static string Password = Des.Decrypt(ConfigurationManager.AppSettings["EmailPWD"].Trim(), "91338720");
static string smtp = ConfigurationManager.AppSettings["SMTPServer"].Trim();
static int port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPort"].Trim());
/// <summary>
/// 发送邮件(单人)
/// </summary>
/// <param name="EmailAddress">邮件地址</param>
/// <param name="Subject">主题</param>
/// <param name="Body">内容</param>
public static bool SendMail(string EmailAddress, string Subject, string Body)
{
bool _b = false;
string[] emails = EmailAddress.Split(';');
foreach (string email in emails)
{
//邮件信息
MailAddress ma = new MailAddress(MailFrom, "考勤辅助系统");
MailMessage mail = new MailMessage();
mail.From = ma;
//验证电子邮件格式是否正确
Regex regExp = new Regex("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
Match m = regExp.Match(email);
if (m.Success)
{
mail.To.Add(email);
//邮件Title
mail.Subject = Subject.Trim();
//邮件主体
mail.Body = Body.Trim();
mail.IsBodyHtml = true;
SmtpClient sc = new SmtpClient(smtp.Trim(), port);
sc.Credentials = new NetworkCredential(MailFrom.Trim(), Password.Trim());
try
{
sc.Send(mail);
_b = true;
Log.WriteLog(mail.To.ToString().Trim() + "发送成功!");
//File.AppendAllText("C:\\AutoSendMail.txt", string.Format("{0}邮件发送成功!\r\n", dr_mailaddress[0]["姓名"].ToString().Trim()));
}
catch (Exception ee)
{
Log.WriteLog("邮件发送失败," + ee.ToString());
//File.AppendAllText("C:\\AutoSendMail.txt", "发送失败!" + ee.ToString());
}
finally
{
sc.Dispose();
mail.Dispose();
GC.Collect();
}
}
else
{
Log.WriteLog("电子邮件格式不正确!");
}
}
return _b;
}
/// <summary>
/// 群发邮件
/// </summary>
/// <param name="emailto">收件人地址</param>
/// <param name="emailcc">抄送地址</param>
/// <param name="subject">主题</param>
/// <param name="body">内容</param>
/// <param name="displayname">显示信息</param>
/// <returns></returns>
public static bool SendMails(string emailto, string emailcc,string subject, string body, string displayname)
{
bool _b = false;
//邮件信息
MailAddress ma = new MailAddress(MailFrom, displayname);
MailMessage mail = new MailMessage();
mail.From = ma;
emailto = CheckEmailAddress(emailto);
emailcc = CheckEmailAddress(emailcc);
if (!emailto.Trim().Equals("") && !emailcc.Trim().Equals(""))
{
foreach (string str in emailto.Trim().Split(';'))
{
mail.To.Add(str);
}
foreach (string str_cc in emailcc.Trim().Split(';'))
{
mail.CC.Add(str_cc);
}
}
else if (emailto.Trim().Equals("") && !emailcc.Trim().Equals(""))
{
foreach (string str in emailcc.Trim().Split(';'))
{
mail.To.Add(str);
}
}
else if (!emailto.Trim().Equals("") && emailcc.Trim().Equals(""))
{
foreach (string str in emailto.Trim().Split(';'))
{
mail.To.Add(str);
}
}
else
{
Log.WriteLog("收件人、抄送人地址都为空");
return false;
}
//邮件Title
mail.Subject = subject.Trim();
//邮件主体
mail.Body = body.Trim();
mail.IsBodyHtml = true;
SmtpClient sc = new SmtpClient(smtp.Trim(), port);
sc.Credentials = new NetworkCredential(MailFrom.Trim(), Password.Trim());
try
{
sc.Send(mail);
_b = true;
Log.WriteLog(mail.To.ToString().Trim() + "发送成功!");
}
catch (Exception ee)
{
Log.WriteLog("邮件发送失败," + ee.ToString());
}
finally
{
sc.Dispose();
mail.Dispose();
GC.Collect();
}
return _b;
}
private static string CheckEmailAddress(string emails)
{
string emailadd = "";
string[] emailadds = emails.Trim().Split(';');
foreach (string str_email in emailadds)
{
//验证电子邮件格式是否正确
Regex regExp = new Regex("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
Match m = regExp.Match(str_email);
if (m.Success)
{
emailadd += str_email + ";";
}
else
{
Log.WriteLog(string.Format("{0}不是有效的email地址!", str_email));
}
}
if (!emailadd.Trim().Equals(""))
{
emailadd = emailadd.Trim().Substring(0, emailadd.Length - 1);
}
return emailadd;
}
/// <summary>
/// 生成邮件内容
/// </summary>
/// <param name="billtype">单据类型</param>
/// <param name="errortype">错误类型</param>
/// <param name="showmessage">需显示的内容</param>
/// <param name="errordata">错误数据提示</param>
/// <returns></returns>
public static string CreateEmailBody(string billtype, int errortype, string showmessage, string errordata)
{
string body = "";
switch (billtype)
{
case "用款申请单":
switch (errortype)
{
case GlobalInfoModel.error_Type_CreateError:
body = string.Format(@"<p>
<span style='font - size:16px;'>{0}:<span style='color:#E53333;font-size:24px;'>{1}</span> 生成支付单失败!</span>
</p>
<p>
<span style = 'font-size:16px;'> 失败原因: {2} </ span >
</p><br/>
<p>
<span style = 'color:#337FE5;'> --------系统邮件,请勿回复-------- </span >
</p>", billtype.Trim(), showmessage.Trim(), errordata.Trim());
break;
case GlobalInfoModel.error_Type_JsonAnalysisEroor:
body = string.Format(@"<p>
<span style='font - size:16px;'>{0}生成支付单失败</span>
</p>
<p>
<span style = 'font-size:16px;'> 失败原因:{1}<br/> {2} </ span >
</p><br/>
<p>
<span style = 'color:#337FE5;'> --------系统邮件,请勿回复-------- </span >
</p>", billtype.Trim(), showmessage.Trim(), errordata.Trim());
break;
default:
break;
}
break;
default:
break;
}
body = string.Format(@"<html><head></head><body>{0}</body></html>",body.Trim());
return body;
}
}
}
|
namespace GameOfGame
{
public enum CellType
{
NullType = 0,
OType = 1,
XType = 2,
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Appnotics.PCBackupLib
{
public class BackupConfig
{
public bool IsLoaded { get; set; }
public string Name { get; set; }
[XmlIgnore]
public string FileName { get; set; }
public string RunAsUser { get; set; }
public string RunAsPassword { get; set; }
public string RunAsDomain { get; set; }
public bool RunAsLoggedIn { get; set; }
public bool UseShadowCopy { get; set; } = false;
public List<string> SourceFolders { get; set; }
public string TargetFolder { get; set; }
public List<string> ExcludeMask { get; set; }
public bool VerifyAfterCopy { get; set; }
public BackupType BackupType { get; set; }
public OverwriteType OverwriteType { get; set; }
public BackupConfig()
{
SourceFolders = new List<string>();
ExcludeMask = new List<string>();
IsLoaded = false;
}
public bool Load(string fileName)
{
if (File.Exists(fileName) == false)
return false;
FileName = fileName;
IsLoaded = true;
return true;
}
}
}
|
using System;
using com.Sconit.Entity.SYS;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Runtime.Serialization;
//TODO: Add other using statements here
namespace com.Sconit.Entity.ORD
{
public partial class ShipmentMaster
{
#region Non O/R Mapping Properties
public IList<ShipmentDetail> ShipmentDetails { get; set; }
public string FlowDescription { get; set; }
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.BillMasterStatus, ValueField = "Status")]
[Display(Name = "ShipmentMaster_Status", ResourceType = typeof(Resources.ORD.ShipmentMaster))]
public string StatusDescription { get; set; }
public IList<IpMaster> ipMasters { get; set; }
#endregion
}
} |
using System;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace TLSReport
{
public static class Extensions
{
public static X509Certificate Clone(this X509Certificate Cert)
{
return new X509Certificate(Cert.Export(X509ContentType.Cert));
}
public static IPEndPoint ToEndpoint(this string Source)
{
if (!Source.Contains(':'))
{
return null;
}
int Port = 0;
string IP = Source.Substring(0, Source.LastIndexOf(':'));
if (int.TryParse(Source.Split(':').Last(), out Port) && Port > ushort.MinValue && Port < ushort.MaxValue)
{
IPAddress Temp = IPAddress.Any;
if (IPAddress.TryParse(IP, out Temp) && Temp!=IPAddress.Any && Temp!=IPAddress.IPv6Any)
{
return new IPEndPoint(Temp, Port);
}
}
return null;
}
public static void Abort(this Thread T, bool RaiseException)
{
try
{
if (T.IsAlive)
{
T.Abort();
}
}
catch (Exception ex)
{
if (RaiseException)
{
throw;
}
}
}
}
}
|
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace TechEval.Core
{
public class CommandDispatcher : ICommandDispatcher
{
private readonly IServiceProvider _resolver;
private readonly ILogger<CommandDispatcher> _log;
public CommandDispatcher(IServiceProvider resolver, ILogger<CommandDispatcher> logger)
{
_resolver = resolver;
_log = logger;
}
public async Task<CommandResult<TEntity>> Dispatch<TParameter, TEntity>(TParameter command)
{
var type2Search = typeof(ICommandHandler<,>)
.MakeGenericType(command.GetType(), typeof(TEntity));
var handler = (ICommandHandler<TParameter, TEntity>)_resolver.GetService(type2Search);
if (handler == null)
{
var errMessage = $"Command handler for {typeof(TParameter)} command not registered";
_log.LogError(errMessage);
throw new NullReferenceException(errMessage);
}
try
{
_log.LogDebug($"Executing command handler for {typeof(TParameter)}");
return await handler.Execute(command);
}
catch (Exception ex)
{
var errMessage = $"Error occured during execution of command handler for {typeof(TParameter)}";
_log.LogError(ex, errMessage);
throw;
}
}
}
}
|
using LogicaNegocio;
using ProyectoLP2;
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 Formularios
{
public partial class GestionPedidos : Form
{
private BindingList<Pedido> listaPedidosRegistrados;
public GestionPedidos()
{
InitializeComponent();
listaPedidosRegistrados = new BindingList<Pedido>();
dgvPedidos.AutoGenerateColumns = false;
PedidoBL p = new PedidoBL();
listaPedidosRegistrados = p.listarPedidos();
dgvPedidos.DataSource = listaPedidosRegistrados;
rbtnBusqRuc.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
frmAddPedido ventaAddPedio = new frmAddPedido();
if (ventaAddPedio.ShowDialog() == DialogResult.OK)
{
//Pedido pedidoAgregado = ventaAddPedio.PedidoRegistrar;
//listaPedidosRegistrados.Add(pedidoAgregado);
dgvPedidos.DataSource = null;
PedidoBL p = new PedidoBL();
listaPedidosRegistrados = p.listarPedidos();
dgvPedidos.DataSource = listaPedidosRegistrados;
}
// AgregarPedido ventanaAgregarpedido = new AgregarPedido();
//this.Hide();
//ventanaAgregarpedido.ShowDialog();
//this.ShowDialog(); // esto si tenog dudas bueno de casi todo xd
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void btnCancelarPedido_Click(object sender, EventArgs e)
{
Close();
}
private void btnElimPedido_Click(object sender, EventArgs e)
{
//confirmarEliminarPedido v = new confirmarEliminarPedido();
//v.ShowDialog();
var v = MessageBox.Show("¿Desea eliminar el pedido?", "Confirmacion", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (v == DialogResult.OK)
{
Pedido pedidoAEliminar = (Pedido)dgvPedidos.CurrentRow.DataBoundItem;
if(pedidoAEliminar.Etapa == EtapaPedido.pendiente)
{
PedidoBL p = new PedidoBL();
p.eliminarPedido(pedidoAEliminar.IdVenta); // se elimino en la base de datos
listaPedidosRegistrados.Remove(pedidoAEliminar);
dgvPedidos.Refresh();
}
else
{
MessageBox.Show("ETAPA DEL PEDIDO DEBE ESTAR EN PENDIENTE", "ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
}
}
// se actualiza la tabla
}
private void btnModPedido_Click(object sender, EventArgs e)
{
Pedido pedidoAModificar = new Pedido();
pedidoAModificar = (Pedido)dgvPedidos.CurrentRow.DataBoundItem;
frmAddPedido ventana = new frmAddPedido(pedidoAModificar);
if(ventana.ShowDialog() == DialogResult.OK)
{
/*
listaPedidosRegistrados.Remove(pedidoAModificar);
listaPedidosRegistrados.Add(ventana.PedidoRegistrar);
dgvPedidos.Update();
dgvPedidos.Refresh();*/
PedidoBL p = new PedidoBL();
listaPedidosRegistrados = p.listarPedidos();
dgvPedidos.DataSource = listaPedidosRegistrados;
}
}
private void GestionPedidos_Load(object sender, EventArgs e)
{
}
private void btnVer_Click(object sender, EventArgs e)
{
verPedido ventana = new verPedido((Pedido)dgvPedidos.CurrentRow.DataBoundItem);
ventana.ShowDialog();
}
private void rbtnBusqRuc_CheckedChanged(object sender, EventArgs e)
{
}
private void btnBusquedaPedido_Click(object sender, EventArgs e)
{
if(txtBusqPedido.Text == "")
{
dgvPedidos.DataSource = listaPedidosRegistrados;
}
else
{
BindingList<Pedido> listaBusqueda = new BindingList<Pedido>();
String criterio;
criterio = txtBusqPedido.Text;
if (rbtnBusqRuc.Checked == true)
{
foreach(Pedido p in listaPedidosRegistrados)
{
if (p.ClienteRUC.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgvPedidos.DataSource = listaBusqueda;
}
if(rbtnRazonSocial.Checked == true)
{
foreach(Pedido p in listaPedidosRegistrados)
{
if (p.Cliente.Nombre.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgvPedidos.DataSource = listaBusqueda;
}
if(rbtnVendedor.Checked == true)
{
foreach(Pedido p in listaPedidosRegistrados)
{
if (p.Vendedor.Nombre.Contains(criterio))
{
Pedido aux = new Pedido();
aux = p;
listaBusqueda.Add(p);
}
}
dgvPedidos.DataSource = listaBusqueda;
}
}
}
private void txtBusqPedido_KeyUp(object sender, KeyEventArgs e)
{
}
}
}
|
using System;
namespace Uintra.Features.Groups
{
public interface IGroupActivity
{
Guid Id { get; set; }
Guid? GroupId { get; set; }
Guid CreatorId { get; set; }
}
}
|
using System.Collections.Generic;
namespace ComLib
{
/// <summary>
/// 値変換
/// </summary>
public class ValueConverter<T1, T2>
{
#region メンバ変数
/// <summary>
/// ディクショナリ
/// </summary>
private Dictionary<T1, T2> vMdic = new Dictionary<T1, T2>();
#endregion
#region コンストラクタ
/// <summary>
/// コンストラクタ
/// </summary>
public ValueConverter()
{
}
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="key">配列 元の値</param>
/// <param name="value">配列 変換後の値</param>
public ValueConverter(T1[] key, T2[] value)
{
if (key.Length != value.Length)
{
return;
}
for (int i = 0; i < key.Length; i++)
{
vMdic.Add(key[i], value[i]);
}
}
#endregion
#region [public]メソッド
/// <summary>
/// 追加
/// </summary>
/// <param name="key">元の値</param>
/// <param name="value">変換後の値</param>
public void Add(T1 key, T2 value)
{
vMdic.Add(key, value);
}
/// <summary>
/// 値変換
/// </summary>
/// <param name="key">元の値</param>
/// <param name="value">変換後の値</param>
/// <returns>変換結果</returns>
public bool TryParse(T1 key, ref T2 value)
{
if (vMdic.ContainsKey(key) == true)
{
value = vMdic[key];
return true;
}
else
{
return false;
}
}
#endregion
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Collections;
/// <summary>Script to apply to game object to set default resolution and
/// handle scene loading as well as quit</summary>
/// <author>Robert McDonnell</author>
public class ChangeScene : MonoBehaviour
{
void Start()
{
Screen.SetResolution(1366,768, true, 60);
}
//Checks for Esc key, takes user back to main menu if pressed
public void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
SceneManager.LoadScene("MainMenu", LoadSceneMode.Single);
}
}
//Loads next screen based on button selected and destroys current scene
public void Load(string levelName)
{
SceneManager.LoadScene(levelName, LoadSceneMode.Single);
}
//Clean up scene
//Removes all objects, keeping GUI and camera positions
public void ResetScene(GameObject prefab)
{
Destroy(GameObject.Find("Scene"));
Destroy(GameObject.Find("Scene(Clone)"));
//Resets spawned shock wave
GameObject handler = GameObject.FindGameObjectWithTag("ShockWaveHandler");
handler.GetComponent<ShockWaveHandler>().shockWave.Reset();
//Reset pause button
GameObject play = GameObject.Find("Play");
PausePlay script = play.GetComponent<PausePlay>();
script.reset();
Instantiate(prefab);
}
//Exits application
public void QuitClick()
{
Application.Quit();
}
} |
using NUnit.Framework;
using System;
namespace Library_Task.Tests
{
public class ArraysTests
{
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, -28)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, -1)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, -11)]
public void FindMinimumNumberInArrayTests(int[] arr, int expected)
{
int actual = Arrays.FindMinimumNumberInArray(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void FindMinimumNumberInArray_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.FindMinimumNumberInArray(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, 100)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, 2)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, -11)]
public void FindMaximumNumberInArrayTests(int[] arr, int expected)
{
int actual = Arrays.FindMaximumNumberInArray(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void FindMaximumNumberInArray_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.FindMaximumNumberInArray(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, 1)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, 4)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, 0)]
public void FindIndexOfMinimumNumberInArrayTests(int[] arr, int expected)
{
int actual = Arrays.FindIndexOfMinimumNumberInArray(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void FindIndexOfMinimumNumberInArray_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.FindIndexOfMinimumNumberInArray(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, 2)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, 5)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, 0)]
public void FindIndexOfMaximumNumberInArrayTests(int[] arr, int expected)
{
int actual = Arrays.FindIndexOfMaximumNumberInArray(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void FindIndexOfMaximumNumberInArray_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.FindIndexOfMaximumNumberInArray(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, -2)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, 2)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, -33)]
public void SumArrayElementsWithOddIndex(int[] arr, int expected)
{
int actual = Arrays.SumArrayElementsWithOddIndex(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void SumArrayElementsWithOddIndex_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.SumArrayElementsWithOddIndex(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, new int[] { 2, 25, 0, 1, 100, -28, -7 })]
[TestCase(new int[] { 0 }, new int[] { 0 })]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, new int[] { 2, -1, 0, 1, 0, 1 })]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, new int[] { -11, -11, -11, -11, -11, -11 })]
public void GetArrayReverseTests(int[] arr, int[] expected)
{
int[] actual = Arrays.GetArrayReverse(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void GetArrayReverse_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.GetArrayReverse(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, 3)]
[TestCase(new int[] { 0 }, 0)]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, 3)]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, 6)]
public void SumNumberOddArrayElementsTests(int[] arr, int expected)
{
int actual = Arrays.SumNumberOddArrayElements(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void SumNumberOddArrayElements_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.SumNumberOddArrayElements(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, new int[] { 0, 25, 2, 1, -7, -28, 100 })]
[TestCase(new int[] { 0 }, new int[] { 0 })]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, new int[] { 0, -1, 2, 1, 0, 1 })]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, new int[] { -11, -11, -11, -11, -11, -11 })]
public void GetArrayChangeHalfNumberTests(int[] arr, int[] expected)
{
int[] actual = Arrays.GetArrayChangeHalfNumber(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void GetArrayChangeHalfNumber_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.GetArrayChangeHalfNumber(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, new int[] { -28, -7, 0, 1, 2, 25, 100 })]
[TestCase(new int[] { 0 }, new int[] { 0 })]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, new int[] { -1, 0, 0, 1, 1, 2 })]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, new int[] { -11, -11, -11, -11, -11, -11 })]
public void SortArrayBubbleUpTests(int[] arr, int[] expected)
{
int[] actual = Arrays.SortArrayBubbleUp(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void SortArrayBubbleUp_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.SortArrayBubbleUp(arr));
}
[TestCase(new int[] { -7, -28, 100, 1, 0, 25, 2 }, new int[] { 100, 25, 2, 1, 0, -7, -28 })]
[TestCase(new int[] { 0 }, new int[] { 0 })]
[TestCase(new int[] { 1, 0, 1, 0, -1, 2 }, new int[] { 2, 1, 1, 0, 0, -1 })]
[TestCase(new int[] { -11, -11, -11, -11, -11, -11 }, new int[] { -11, -11, -11, -11, -11, -11 })]
public void SortArraySelectDownTests(int[] arr, int[] expected)
{
int[] actual = Arrays.SortArraySelectDown(arr);
Assert.AreEqual(expected, actual);
}
[TestCase(new int[0])]
public void SortArraySelectDown_EmptyArray__ShouldArgumentException(int[] arr)
{
Assert.Throws<ArgumentException>(() => Arrays.SortArraySelectDown(arr));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MyClassLibrary;
namespace Les2Exercise4
{
class Program
{
/*4. Реализовать метод проверки логина и пароля.
На вход метода подается логин и пароль.
На выходе истина, если прошел авторизацию, и ложь, если не прошел (Логин: root, Password: GeekBrains).
Используя метод проверки логина и пароля, написать программу: пользователь вводит логин и пароль,
программа пропускает его дальше или не пропускает. С помощью цикла do while ограничить ввод пароля тремя попытками.*/
static void Main(string[] args)
{
bool Autorization(string userLogin, string userPassword)
{
string login = "root";
string password = "GeekBrains";
if (userLogin.ToLower() == login && userPassword == password)
{
return true;
}
else
return false;
}
//string login = "root";
//string password = "GeekBrains";
int count = 1; // 1 т.к. использован цикл do while
int tryCount = 3;
do
{
MyMetods.Print("Введите логин.");
string userLogin = Console.ReadLine();
MyMetods.Print("Введите пароль.");
string userPassword = Console.ReadLine();
if (Autorization(userLogin, userPassword))
{
MyMetods.Print("Вы вошли в систему.");
//count = trycount;
break;
}
else
{
if (count == tryCount)
MyMetods.Print("Вы ввели неверный логин или пароль.\nВсе попытки использованы.\n");
else
{
string str;
if (tryCount - count == 2)
str = "ки";
else
str = "ка";
MyMetods.Print($"Вы ввели неверный логин или пароль.\nПопробуйте еще раз. У вас осталось {tryCount - count} попыт{str}.\n");
}
}
} while (count++ < tryCount) ;
MyMetods.Pause();
}
}
}
|
using System;
using Flux.src.Flux.Renderer;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace Flux.src.Platform.OpenGL
{
public class OpenGLPyramid : IShape
{
readonly float[] vertices =
{
//Position Texture coordinates
-0.5f, -0.5f, -0.5f, 1f, 0f, 0f, // top right
+0.5f, -0.5f, -0.5f, 0f, 1f, 0f, // bottom right
+0.5f, -0.5f, +0.5f, 0f, 0f, 1f, // bottom left
-0.5f, -0.5f, +0.5f, 0f, 1f, 1f, // top left
+0.0f, +0.5f, +0.0f, 1f, 1f, 0f
};
readonly uint[] indices =
{
// Base
0, 2, 1,
0, 2, 3,
// Sides
4, 0, 1,
4, 1, 2,
4, 2, 3,
4, 3, 0
};
public VertexArray vao;
public OpenGLPyramid()
{
Init();
}
public void Init()
{
vao = VertexArray.Create();
VertexBuffer vbo = VertexBuffer.Create(vertices);
BufferLayout bl = new BufferLayout
{
{ShaderDataType.Float3, "Position" },
{ShaderDataType.Float3, "Color" }
};
bl.CalculateOffsetsAndStride();
vbo.SetLayout(bl);
vao.AddVertexBuffer(vbo);
IndexBuffer ibo = IndexBuffer.Create(indices);
vao.SetIndexBuffer(ibo);
}
public void Draw()
{
vao.Bind();
GL.DrawElements(PrimitiveType.Triangles, vao.GetIndexBuffer().GetCount(), DrawElementsType.UnsignedInt, 0);
}
}
}
|
using BusinessObjects;
using DataAccess.IRepository;
using DataAccess.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlyFundsWeb.Controllers
{
public class CommentController : Controller
{
private ICommentRepository cmtRepo = new CommentRepository();
public IActionResult Index()
{
return View();
}
[HttpPost]
public void Add(int postid, string content)
{
if (HttpContext.Session.GetString("user") == null)
{
/*return RedirectToAction("Index", "User");*/
}
try
{
Comment cmt = new Comment();
cmt.CommentId = cmtRepo.GetMaxCommentId() + 1;
cmt.PostId = postid;
cmt.CommentDate = DateTime.Now;
cmt.Content = content;
cmt.Username = HttpContext.Session.GetString("user");
cmtRepo.AddComment(cmt);
/*return RedirectToAction("Details", "Posts", new { id = postid });*/
}
catch (Exception ex)
{
ViewBag.Error = ex.Message;
/*return View("Error");*/
}
}
[HttpPost]
public IActionResult Edit(int id, string newContent, int postid)
{
if (string.IsNullOrWhiteSpace(newContent))
{
return RedirectToAction("Details", "Posts", new { id = postid });
}
try
{
Comment cmt = cmtRepo.GetComment(id);
if (cmt == null)
throw new Exception("Comment not found");
cmt.Content = newContent;
cmtRepo.EditComment(cmt);
return RedirectToAction("Details", "Posts", new { id = postid });
}
catch (Exception ex)
{
ViewBag.error = ex.Message;
return View("Error");
}
}
[HttpPost]
public IActionResult Delete(int id, int postid)
{
if (HttpContext.Session.GetString("user") == null)
return RedirectToAction("Index", "User");
try
{
Comment cmt = cmtRepo.GetComment(id);
if (cmt == null)
throw new Exception("Comment not found");
cmtRepo.DeleteComment(cmt);
return RedirectToAction("Details", "Posts", new { id = postid });
}
catch (Exception ex)
{
ViewBag.error = ex.Message;
return View("Error");
}
}
}
} |
using Newtonsoft.Json;
using StackExchange.Redis;
using StackExchange.Redis.Extensions.Core.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisPSR
{
class Menu
{
private IDatabase conn;
private ConnectionMultiplexer redis;
private int UserNumber => Convert.ToInt32(Console.ReadLine());
public Menu(IDatabase conn, ConnectionMultiplexer redis)
{
this.conn = conn;
this.redis = redis;
}
public Menu(IDatabase conn)
{
this.conn = conn;
}
public void PrintMenu()
{
var helper = new Helper(conn);
Console.WriteLine("[1] - Pobierz\n" +
"[2] - Dodaj\n" +
"[3] - Aktualizuj\n" +
"[4] - Kasuj\n" +
"[5] - Oblicz ?redni? pensj? wg rang\n" +
"[6] - Wy?wietl komendy powiatowe\n" +
"[7] - Zako?cz");
var input = UserNumber;
while (true)
{
if (input == 1)
{
Console.WriteLine("[1] - Wszystkie dane\t" +
"[2] - Policjanci\t" +
"[3] - Komendy\t" +
"[4] - Rangi");
input = UserNumber;
var keys = redis.GetServer(redis.GetEndPoints().First()).Keys();
if (input == 1)
{
helper.GetValues<Policeman>("policjant:", keys);
helper.GetValues<Department>("komenda:", keys);
helper.GetValues<Rank>("ranga:", keys);
PrintMenu();
}
else if (input == 2)
{
helper.GetValues<Policeman>("policjant:", keys);
PrintMenu();
}
else if (input == 3)
{
helper.GetValues<Department>("komenda:", keys);
PrintMenu();
}
else
{
helper.GetValues<Rank>("ranga:", keys);
PrintMenu();
}
}
else if (input == 2)
{
Console.WriteLine("[1] - Policjanta\t" +
"[2] - Komend?\t" +
"[3] - Rang?");
input = UserNumber;
if (input == 1)
{
helper.AddPoliceman();
PrintMenu();
}
else if (input == 2)
{
helper.AddDepartment();
PrintMenu();
}
else if (input == 3)
{
helper.AddRank();
PrintMenu();
}
else
{
Console.WriteLine("Z?y numer!");
PrintMenu();
}
}
else if (input == 3)
{
Console.WriteLine("Podaj klucz, którego watro?? chcesz edytowa?:");
var key = Console.ReadLine();
if (!conn.KeyExists(key))
{
Console.WriteLine("Klucz nie isnieje!");
PrintMenu();
}
if (key.Contains("policjant"))
{
helper.UpdatePoliceman(key);
}
else if (key.Contains("komenda"))
{
helper.UpdateDepartment(key);
}
else
helper.UpdateRank(key);
PrintMenu();
}
else if (input == 4)
{
Console.WriteLine("Podaj klucz do usuni?cia: ");
var key = Console.ReadLine();
if (conn.KeyDelete(key))
{
Console.WriteLine("Usuni?to pomy?lnie!");
}
PrintMenu();
}
else if (input == 5)
{
//?rednia pensja
var keys = redis.GetServer(redis.GetEndPoints().First()).Keys();
var ranks = helper.GetAllRanks(keys);
var avarageSalary = ranks.Select(x => x.Value.Salary).Average();
Console.WriteLine($"?rednia pensja wynosi: {avarageSalary}");
PrintMenu();
}
else if (input == 6)
{
//komendy powiatowe
var keys = redis.GetServer(redis.GetEndPoints().First()).Keys();
var departments = helper.GetAllDistrictDepartments(keys);
helper.GetInfo<Department>(departments);
PrintMenu();
}
else if (input == 7)
{
break;
}
else
{
Console.WriteLine("Z?y numer!");
PrintMenu();
}
}
}
}
} |
namespace HospitalDatabase
{
using System;
using System.Data.Entity;
using Models;
public class HospitalDatabaseContext : DbContext
{
public HospitalDatabaseContext()
: base("name=HospitalDatabaseContext")
{
}
public DbSet<Comment> Comments { get; set; }
public DbSet<Diagnose> Diagnoses { get; set; }
public DbSet<Medicament> Medicaments { get; set; }
public DbSet<Patient> Patients { get; set; }
public DbSet<Visitation> Visitations { get; set; }
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SolrDotNet.Models
{
public class ResponseHeader
{
[JsonProperty("status")]
public int Status { get; set; }
public int QTime { get; set; }
[JsonProperty("params")]
public Dictionary<string, string> Params { get; set; }
}
}
|
using LoowooTech.Stock.ArcGISTool;
using LoowooTech.Stock.Common;
using LoowooTech.Stock.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Rules
{
public class GHYTJSYDGZQRule:ArcGISBaseTool,Models.IRule
{
public override string RuleName { get { return "规划用途与建设用地管制区逻辑一致性检查"; } }
public override string ID { get { return "3003"; } }
public override CheckProject2 CheckProject { get { return CheckProject2.规划用途与建设用地管制区对比检查; } }
public bool Space { get { return true; } }
public void Check()
{
if (ExtractGHYT() == false)
{
return;
}
if (ArcExtensions2.ImportFeatureClass(string.Format("{0}\\{1}", ParameterManager2.MDBFilePath, "JSYDGZQ"), MdbFilePath, "JSYDGZQ", null) == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("导入建设用地管制区图层数据失败!")
});
return;
}
if (ArcExtensions2.Select(string.Format("{0}\\{1}", MdbFilePath, "GHYT"), string.Format("{0}\\{1}", MdbFilePath, "GHYT_G21"), "GHYTDM LIKE 'G21*'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("规划用途层中提取新增城乡建设用地数据失败!")
});
}
else
{
if (ArcExtensions2.Select(string.Format("{0}\\{1}", MdbFilePath, "JSYDGZQ"), string.Format("{0}\\{1}", MdbFilePath, "JSYDGZQ_010"), "GZQLXDM = '010'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取建设用地管制区中允许建设区图层失败")
});
}
else
{
if (ArcExtensions2.Erase(string.Format("{0}\\{1}", MdbFilePath, "GHYT_G21"), string.Format("{0}\\{1}", MdbFilePath, "JSYDGZQ_010"), string.Format("{0}\\{1}", MdbFilePath, "GHYT_G21_Erase"), ParameterManager2.Tolerance) == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("新增城乡建设用地Erase允许建设区失败!")
});
}
else
{
var sql = "SELECT COUNT(*) FROM GHYT_G21_Erase";
var obj = SearchRecord(MdbFilePath, sql);
if (obj != null)
{
var count = 0;
if(int.TryParse(obj.ToString(),out count))
{
if (count > 0)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("存在新增城乡建设用地不在允许建设区内")
});
}
}
else
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("查询新增城乡建设用地是否与允许建设区内失败")
});
}
}
}
}
}
if(ArcExtensions2.Select(string.Format("{0}\\{1}",MdbFilePath,"GHYT"),string.Format("{0}\\{1}",MdbFilePath,"GHYT_E"),"CJJX = 'E1' OR CJJX = 'E2'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取规划用图层中拟新增E2、虚拟新增E1数据失败")
});
}
else
{
if(ArcExtensions2.Select(string.Format("{0}\\{1}",MdbFilePath,"GHYT"),string.Format("{0}\\{1}",MdbFilePath,"JSYDGZQ_021"),"GZQLXDM = '021' OR GZQLXDM = '020'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取建设用地管制区中有条件建设区失败")
});
}
else
{
if (ArcExtensions2.Erase(string.Format("{0}\\{1}", MdbFilePath, "GHYT_E"), string.Format("{0}\\{1}", MdbFilePath, "JSYDGZQ_021"),string.Format("{0}\\{1}",MdbFilePath,"GHYT_E_Erase"), ParameterManager2.Tolerance) == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("拟新增、虚拟新增Erase有条件建设区失败")
});
}
else
{
var sql = "SELECT COUNT(*) FROM GHYT_E_Erase";
var obj = SearchRecord(MdbFilePath, sql);
if (obj != null)
{
var count = 0;
if(int.TryParse(obj.ToString(),out count))
{
if (count > 0)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("存在拟新增E2、虚拟新增E1不在有条件建设区")
});
}
}
}
}
}
}
if(ArcExtensions2.Select(string.Format("{0}\\{1}",MdbFilePath,"GHYT"),string.Format("{0}\\{1}",MdbFilePath,"GHYT_G111"),"GHYTDM = 'G111'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取规划用途层中示范区基本农田数据失败")
});
}
else
{
if(ArcExtensions2.Select(string.Format("{0}\\{1}",MdbFilePath,"JSYDGZQ"),string.Format("{0}\\{1}",MdbFilePath,"JSYDGZQ_040"),"GZQLXDM = '040'") == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("提取禁止建设区数据失败")
});
}
else
{
if (ArcExtensions2.Erase(string.Format("{0}\\{1}", MdbFilePath, "GHYT_G111"), string.Format("{0}\\{1}", MdbFilePath, "JSYDGZQ_040"), string.Format("{0}\\{1}", MdbFilePath, "GHYT_G111_Erase"), ParameterManager2.Tolerance) == false)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("示范区基本农田Erase禁止建设区失败")
});
}
else
{
var sql = "SELECT COUNT(*) FROM GHYT_G111_Erase";
var obj = SearchRecord(MdbFilePath, sql);
if (obj != null)
{
var count = 0;
if(int.TryParse(obj.ToString(),out count))
{
if (count > 0)
{
QuestionManager2.Add(new Question2
{
Code = ID,
Name = RuleName,
CheckProject = CheckProject,
Description = string.Format("存在示范区基本农田部不在禁止建设区")
});
}
}
}
}
}
}
}
}
}
|
/** 版本信息模板在安装目录下,可自行修改。
* tb_node.cs
*
* 功 能: N/A
* 类 名: tb_node
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2017-04-05 10:52:24 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace ND.FluentTaskScheduling.Model
{
/// <summary>
/// tb_node:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
public partial class tb_node
{
public tb_node()
{}
#region Model
private int _id;
private string _nodename;
private DateTime _nodelastmodifytime= Convert.ToDateTime("2099-12-30");
private string _nodeip;
private DateTime _nodelastupdatetime= Convert.ToDateTime("2099-12-30");
private DateTime _lastrefreshcommandqueuetime = Convert.ToDateTime("2099-12-30");
private bool _ifcheckstate= false;
private string _nodecommanddllversion="";
private int _alarmtype = 0;
private string _alarmuserid = "";
private int _isenablealarm = 0;
private int _refreshcommandqueuestatus = 0;
private int _createby = 0;
private int _nodestatus = 0;
private int _isdel = 0;
private int _maxrefreshcommandqueuecount = 0;
private DateTime _createtime = DateTime.Now;
private string _nodediscription = "";
private string _machinename = "";
private string _performancecollectjson = "";
private int _lastmaxid = 0;
private int _ifmonitor = 1;
/// <summary>
/// 是否监控
/// </summary>
public int ifmonitor
{
set { _ifmonitor = value; }
get { return _ifmonitor; }
}
/// <summary>
/// 节点性能收集json
/// </summary>
public string performancecollectjson
{
set { _performancecollectjson = value; }
get { return _performancecollectjson; }
}
/// <summary>
/// 节点机器名称
/// </summary>
public string machinename
{
set { _machinename = value; }
get { return _machinename; }
}
/// <summary>
/// 保存上次取得最大id值
/// </summary>
public int lastmaxid
{
set { _lastmaxid = value; }
get { return _lastmaxid; }
}
/// <summary>
/// 节点描述
/// </summary>
public string nodediscription
{
set { _nodediscription = value; }
get { return _nodediscription; }
}
/// <summary>
/// 最大刷取命令个数
/// </summary>
public int maxrefreshcommandqueuecount
{
set { _maxrefreshcommandqueuecount = value; }
get { return _maxrefreshcommandqueuecount; }
}
/// <summary>
/// 创建时间
/// </summary>
public DateTime createtime
{
set { _createtime = value; }
get { return _createtime; }
}
/// <summary>
/// 上次刷新队列时间
/// </summary>
public DateTime lastrefreshcommandqueuetime
{
set { _lastrefreshcommandqueuetime = value; }
get { return _lastrefreshcommandqueuetime; }
}
/// <summary>
/// 创建人
/// </summary>
public int createby
{
set { _createby = value; }
get { return _createby; }
}
/// <summary>
/// 节点状态
/// </summary>
public int nodestatus
{
set { _nodestatus = value; }
get { return _nodestatus; }
}
/// <summary>
/// 是否删除
/// </summary>
public int isdel
{
set { _isdel = value; }
get { return _isdel; }
}
/// <summary>
/// 刷新命令队列状态
/// </summary>
public int refreshcommandqueuestatus
{
set { _refreshcommandqueuestatus = value; }
get { return _refreshcommandqueuestatus; }
}
/// <summary>
///
/// </summary>
public int isenablealarm
{
set { _isenablealarm = value; }
get { return _isenablealarm; }
}
/// <summary>
///
/// </summary>
public string alarmuserid
{
set { _alarmuserid = value; }
get { return _alarmuserid; }
}
/// <summary>
///
/// </summary>
public int alarmtype
{
set { _alarmtype = value; }
get { return _alarmtype; }
}
/// <summary>
///
/// </summary>
public int id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
public string nodename
{
set{ _nodename=value;}
get{return _nodename;}
}
/// <summary>
///
/// </summary>
public DateTime nodelastmodifytime
{
set { _nodelastmodifytime = value; }
get { return _nodelastmodifytime; }
}
/// <summary>
///
/// </summary>
public string nodeip
{
set{ _nodeip=value;}
get{return _nodeip;}
}
/// <summary>
///
/// </summary>
public DateTime nodelastupdatetime
{
set{ _nodelastupdatetime=value;}
get{return _nodelastupdatetime;}
}
/// <summary>
///
/// </summary>
public bool ifcheckstate
{
set{ _ifcheckstate=value;}
get{return _ifcheckstate;}
}
/// <summary>
/// 节点对应命令dll版本
/// </summary>
public string nodecommanddllversion
{
set{ _nodecommanddllversion=value;}
get{return _nodecommanddllversion;}
}
#endregion Model
}
}
|
using System.Collections.Generic;
namespace CLDatabaseCore.Mock
{
//internal class MockGenresTable
//{
// // data
// List<Genre> Genres { get; set; }
// // constructor
// public MockGenresTable()
// {
// this.Genres = new List<Genre> {
// new Genre {GenreID = 0, isFiction = true, Description = "Space Book", Name = "Space Oddesy" },
// new Genre {GenreID = 0, isFiction = true, Description = "How to fly", Name = "TakingOff" },
// new Genre {GenreID = 0, isFiction = false, Description = "C# for Bootcampers", Name = "Your first Program" },
// new Genre {GenreID = 0, isFiction = false, Description = "Bio", Name = "Some Famous person" }
// };
// }
//}
}
|
using Modulus2D.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modulus2D.Graphics
{
public class SpriteBatch {
private uint maxSprites = 2048;
public uint MaxSprites { get => maxSprites; set => maxSprites = value; }
// 32 pixels per meter
public static float PixelsToMeters = 0.03125f;
// Index of current sprite
private int index = 0;
private ITarget target;
private OrthoCamera camera;
public OrthoCamera Camera { get => camera; set => camera = value; }
private float[] vertices;
private uint[] indices;
private VertexArray vertexArray;
private Shader shader;
private Uniform viewProj;
private Texture texture;
public SpriteBatch(ITarget target, OrthoCamera camera)
{
this.target = target;
this.camera = camera;
vertices = new float[MaxSprites * 16];
indices = new uint[MaxSprites * 6];
CreateDefaultShader();
vertexArray = new VertexArray()
{
Attribs = new VertexAttrib[] {
new VertexAttrib // position
{
Size = 2,
Normalized = false,
},
new VertexAttrib // UV
{
Size = 2,
Normalized = false,
}
}
};
}
private void CreateDefaultShader()
{
shader = new Shader();
shader.AddVertex(@"
#version 150 core
in vec2 vertexPosition;
in vec2 vertexUV;
out vec2 UV;
uniform mat4 viewProj;
void main()
{
gl_Position = viewProj * vec4(vertexPosition, 0.0, 1.0);
UV = vertexUV;
}
");
shader.AddFragment(
@"
#version 150 core
in vec2 UV;
out vec4 color;
uniform sampler2D tex;
void main()
{
color = texture(tex, UV);
}
");
shader.Link();
viewProj = shader.GetUniform("viewProj");
}
/// <summary>
/// Full draw function with all parameters
/// </summary>
/// <param name="texture">Texture</param>
/// <param name="position">Position</param>
/// <param name="scale">Scale</param>
/// <param name="uv1">Lower left UV</param>
/// <param name="uv2">Top right UV</param>
/// <param name="rotation">Rotation</param>
public void Draw(Texture texture, Vector2 position, Vector2 scale, Vector2 uv1, Vector2 uv2, float rotation)
{
if (index >= MaxSprites)
{
// Render if MaxSprites is exceeded
Flush();
}
if (this.texture == null)
{
this.texture = texture;
}
else if (this.texture != texture)
{
Flush();
this.texture = texture;
}
// UVs determine the size of the sprite relative to the size of the texture
float halfWidth = texture.Width * (uv2.X - uv1.X) * scale.X * PixelsToMeters * 0.5f;
float halfHeight = texture.Height * (uv2.Y - uv1.Y) * scale.Y * PixelsToMeters * 0.5f;
// 4 values per vertex, 4 * 4 = 16
int firstValue = index * 16;
// 6 indices per sprite
int firstIndex = index * 6;
if (rotation == 0f)
{
// Lower left
vertices[firstValue + 0] = position.X - halfWidth; // Position X
vertices[firstValue + 1] = position.Y - halfHeight; // Position Y
vertices[firstValue + 2] = uv1.X; // UV X
vertices[firstValue + 3] = uv2.Y; // UV Y
// Lower right
vertices[firstValue + 4] = position.X + halfWidth; // Position X
vertices[firstValue + 5] = position.Y - halfHeight; // Position Y
vertices[firstValue + 6] = uv2.X; // UV X
vertices[firstValue + 7] = uv2.Y; // UV Y
// Upper right
vertices[firstValue + 8] = position.X + halfWidth; // Position X
vertices[firstValue + 9] = position.Y + halfHeight; // Position Y
vertices[firstValue + 10] = uv2.X; // UV X
vertices[firstValue + 11] = uv1.Y; // UV Y
// Upper left
vertices[firstValue + 12] = position.X - halfWidth; // Position X
vertices[firstValue + 13] = position.Y + halfHeight; // Position Y
vertices[firstValue + 14] = uv1.X; // UV X
vertices[firstValue + 15] = uv1.Y; // UV Y
}
else
{
// Rotate if necessary
float cos = (float)System.Math.Cos(rotation);
float sin = (float)System.Math.Sin(rotation);
// Lower left
vertices[firstValue + 0] = position.X - halfWidth * sin - halfHeight * cos; // Position X
vertices[firstValue + 1] = position.Y - halfWidth * cos + halfHeight * sin; // Position Y
vertices[firstValue + 2] = uv1.X; // UV X
vertices[firstValue + 3] = uv2.Y; // UV Y
// Lower right
vertices[firstValue + 4] = position.X - halfWidth * sin + halfHeight * cos; // Position X
vertices[firstValue + 5] = position.Y - halfWidth * cos - halfHeight * sin; // Position Y
vertices[firstValue + 6] = uv2.X; // UV X
vertices[firstValue + 7] = uv2.Y; // UV Y
// Upper right
vertices[firstValue + 8] = position.X + halfWidth * sin + halfHeight * cos; // Position X
vertices[firstValue + 9] = position.Y + halfWidth * cos - halfHeight * sin; // Position Y
vertices[firstValue + 10] = uv2.X; // UV X
vertices[firstValue + 11] = uv1.Y; // UV Y
// Upper left
vertices[firstValue + 12] = position.X + halfWidth * sin - halfHeight * cos; // Position X
vertices[firstValue + 13] = position.Y + halfWidth * cos + halfHeight * sin; // Position Y
vertices[firstValue + 14] = uv1.X; // UV X
vertices[firstValue + 15] = uv1.Y; // UV Y
}
// 4 vertices per sprite
uint firstVertex = (uint)index * 4;
// Create two triangles from coordinates
indices[firstIndex + 0] = firstVertex + 3; // Upper left
indices[firstIndex + 1] = firstVertex + 0; // Lower left
indices[firstIndex + 2] = firstVertex + 1; // Lower right
indices[firstIndex + 3] = firstVertex + 3; // Upper left
indices[firstIndex + 4] = firstVertex + 2; // Upper right
indices[firstIndex + 5] = firstVertex + 1; // Lower right
// Advance to next sprite
index++;
}
/// <summary>
/// Renders the current sprites and resets
/// </summary>
public void Flush()
{
// Update camera
shader.Set(viewProj, camera.Update());
// Update vertices
// 4 components per vertex, 4 vertices per sprite
vertexArray.Upload(vertices, index * 16);
// Bind texture
target.SetTexture(texture);
// Bind shader
target.SetShader(shader);
// Draw vertices
// 6 indices per sprite
target.Draw(vertexArray, indices, index * 6);
// Reset
index = 0;
}
public void Draw(Texture texture, Vector2 position)
{
Draw(texture, position, Vector2.One, Vector2.Zero, Vector2.One, 0f);
}
public void Draw(Texture texture, Vector2 position, float rotation)
{
Draw(texture, position, Vector2.One, Vector2.Zero, Vector2.One, rotation);
}
public void Draw(Texture texture, Vector2 position, Vector2 scale)
{
Draw(texture, position, scale, Vector2.Zero, Vector2.One, 0f);
}
public void Draw(Texture texture, Vector2 position, Vector2 scale, float rotation)
{
Draw(texture, position, scale, Vector2.Zero, Vector2.One, rotation);
}
}
} |
using SQLServerBackupTool.Lib.Annotations;
using SQLServerBackupTool.Web;
using SQLServerBackupTool.Web.Lib;
using SQLServerBackupTool.Web.Models;
using System.ComponentModel;
using System.Data.Entity;
using System.Web.Security;
[assembly: WebActivator.PostApplicationStartMethod(typeof(AutoInstall), "PostStart")]
namespace SQLServerBackupTool.Web
{
[Localizable(false)]
public static class AutoInstall
{
[UsedImplicitly]
public static void PostStart()
{
BasicMembershipAuthHttpModule.Realm = "SSBT.web";
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SSBTDbContext>());
using (var ddb = new SSBTDbContext())
{
ddb.Database.Initialize(false);
}
MembershipUser defaultUser = null;
if (Membership.GetAllUsers().Count == 0)
{
defaultUser = Membership.CreateUser("admin", "password");
}
if (!Roles.RoleExists("Admin"))
{
Roles.CreateRole("Admin");
if (defaultUser != null)
{
Roles.AddUserToRole(defaultUser.UserName, "Admin");
}
}
if (!Roles.RoleExists("Operator"))
{
Roles.CreateRole("Operator");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Common.Logging;
using Microsoft.Practices.Unity;
using Quartz;
using Quartz.Spi;
using Quartz.Util;
using Ach.Fulfillment.Common;
namespace Ach.Fulfillment.Scheduler
{
public class UnityJobFactory : IJobFactory
{
private static readonly ILog Log = LogManager.GetLogger(typeof(UnityJobFactory));
public UnityJobFactory(IUnityContainer container)
{
Container = container;
}
[Dependency]
public IUnityContainer Container { get; set; }
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
var job = Container.Resolve(bundle.JobDetail.JobType) as IJob;
return job;
}
catch (Exception exception)
{
throw new SchedulerException("Error on creation of new job", exception);
}
}
}
}
|
namespace RosPurcell.Web.ViewModels.NestedContent
{
using RosPurcell.Web.ViewModels.Media;
using RosPurcell.Web.ViewModels.NestedContent.Base;
public class SidebarItem : BaseNestedContent
{
public TeaserImage Image { get; set; }
public string Quote { get; set; }
public bool ShowQuote => !string.IsNullOrEmpty(Quote);
public string Author { get; set; }
public bool ShowAuthor => !string.IsNullOrEmpty(Author);
}
}
|
using System;
class PrimeNumberCheck
{
static void Main()
{
Console.WriteLine("Infinite loop. If you want to stop, pres CTRL+C !!!");
while (true)
{
int liNumber, liCounter;
bool lbIsPrime = false;
Console.Write("Enter integer number between 1 and 100 : ");
liNumber = int.Parse(Console.ReadLine());
if (liNumber > 1)
{
liCounter = (int)Math.Sqrt(liNumber);
lbIsPrime = true;
for (int i = 2; i <= liCounter; i++)
{
if ((liNumber % i) == 0)
{
lbIsPrime = false;
break;
}
}
}
Console.WriteLine("is a number a prime : {0}", lbIsPrime);
}
}
} |
using System;
namespace Algorithms.GoogleCodeJam
{
class CountingSheep
{
static short digitsLength = 10;
static bool AllMarked(byte[] marked)
{
for (int i = 0; i < digitsLength; i++)
{
if (marked[i] == 0) return false;
}
return true;
}
static byte[] MarkNumber(byte[] marked, int current)
{
while (current >= 1)
{
marked[current % 10] = 1;
current /= 10;
}
return marked;
}
static void Main(string[] args)
{
int numTests = Convert.ToInt32(Console.ReadLine());
int j, current = 0;
int[,] results = new int[numTests, 2];
byte[] marked;
for (int i = 0; i < numTests; i++)
{
j = 1;
current = Convert.ToInt32(Console.ReadLine());
if (current * j > 0)
{
marked = new byte[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
while (!AllMarked(MarkNumber(marked, current * j))) j++;
}
results[i, 0] = current;
results[i, 1] = current * j;
}
for (int i = 0; i < numTests; i++)
{
Console.WriteLine("Case #{0}:\t==>\tInput:\t{1}\tOutput:\t{2}", i, results[i, 0], results[i, 1]);
}
Console.Read();
}
}
} |
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class SilentRunningEvent : Event
{
public const string NAME = "Silent running";
public const string DESCRIPTION = "Triggered when you activate or deactivate silent running";
public const string SAMPLE = null;
[PublicAPI("A boolean value. True if silent running is active.")]
public bool silentrunning { get; private set; }
public SilentRunningEvent(DateTime timestamp, bool silentRunning) : base(timestamp, NAME)
{
this.silentrunning = silentRunning;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Newtonsoft.Json;
using Our.Umbraco.Tuple.Models;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Web.PropertyEditors;
namespace Our.Umbraco.Tuple.PropertyEditors
{
internal class TuplePropertyValueEditor : PropertyValueEditorWrapper
{
public TuplePropertyValueEditor(PropertyValueEditor wrapped)
: base(wrapped)
{
Validators.Add(new TupleValidator());
}
public override void ConfigureForDisplay(PreValueCollection preValues)
{
base.ConfigureForDisplay(preValues);
if (preValues.PreValuesAsDictionary.ContainsKey("hideLabel"))
{
var boolAttempt = preValues.PreValuesAsDictionary["hideLabel"].Value.TryConvertTo<bool>();
if (boolAttempt.Success)
{
this.HideLabel = boolAttempt.Result;
}
}
}
public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
var propertyValue = property?.Value?.ToString();
if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
return base.ConvertDbToEditor(property, propertyType, dataTypeService);
var items = JsonConvert.DeserializeObject<TupleValueItems>(propertyValue);
if (items == null || items.Count == 0)
return base.ConvertDbToEditor(property, propertyType, dataTypeService);
foreach (var item in items)
{
// Get the associated datatype definition
var dtd = dataTypeService.GetDataTypeDefinitionById(item.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
if (dtd == null)
continue;
// Lookup the property editor and convert the db to editor value
var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // TODO: Caching? [LK:2018-06-25]
if (propEditor == null)
continue;
var propType = new PropertyType(dtd, propertyType.Alias);
var prop = new Property(propType, item.Value);
item.Value = propEditor.ValueEditor.ConvertDbToEditor(prop, propType, dataTypeService);
}
// Return the strongly-typed object, Umbraco will handle the JSON serializing/parsing, then Angular can handle it directly
return items;
}
public override string ConvertDbToString(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
var propertyValue = property?.Value?.ToString();
if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
return base.ConvertDbToString(property, propertyType, dataTypeService);
var items = JsonConvert.DeserializeObject<TupleValueItems>(propertyValue);
if (items == null || items.Count == 0)
return base.ConvertDbToString(property, propertyType, dataTypeService);
foreach (var item in items)
{
var dtd = dataTypeService.GetDataTypeDefinitionById(item.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
if (dtd == null)
continue;
var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // TODO: Caching? [LK:2018-06-25]
if (propEditor == null)
continue;
var propType = new PropertyType(dtd, propertyType.Alias);
var prop = new Property(propType, item.Value);
item.Value = propEditor.ValueEditor.ConvertDbToString(prop, propType, dataTypeService);
}
return JsonConvert.SerializeObject(items);
}
public override XNode ConvertDbToXml(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
{
var propertyValue = property?.Value?.ToString();
if (propertyValue == null || string.IsNullOrWhiteSpace(propertyValue))
return base.ConvertDbToXml(property, propertyType, dataTypeService);
var items = JsonConvert.DeserializeObject<TupleValueItems>(propertyValue);
if (items == null || items.Count == 0)
return base.ConvertDbToXml(property, propertyType, dataTypeService);
foreach (var item in items)
{
var dtd = dataTypeService.GetDataTypeDefinitionById(item.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
if (dtd == null)
continue;
var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias); // TODO: Caching? [LK:2018-06-25]
if (propEditor == null)
continue;
var propType = new PropertyType(dtd, propertyType.Alias);
var prop = new Property(propType, item.Value);
item.DataTypeUdi = dtd.GetUdi();
item.Value = propEditor.ValueEditor.ConvertDbToXml(prop, propType, dataTypeService);
}
return new XElement("values", items.Select(x => new XElement("value", new XAttribute("udi", x.DataTypeUdi), x.Value)));
}
public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
{
var value = editorValue?.Value?.ToString();
if (value == null || string.IsNullOrWhiteSpace(value))
return base.ConvertEditorToDb(editorValue, currentValue);
var model = JsonConvert.DeserializeObject<TupleValueItems>(value);
if (model == null || model.Count == 0)
return base.ConvertEditorToDb(editorValue, currentValue);
var dataTypeService = ApplicationContext.Current.Services.DataTypeService;
for (var i = 0; i < model.Count; i++)
{
var obj = model[i];
var dtd = dataTypeService.GetDataTypeDefinitionById(obj.DataTypeGuid); // TODO: Caching? [LK:2018-06-25]
if (dtd == null)
continue;
var preValues = dataTypeService.GetPreValuesCollectionByDataTypeId(dtd.Id); // TODO: Caching? [LK:2018-06-25]
if (preValues == null)
continue;
var propEditor = PropertyEditorResolver.Current.GetByAlias(dtd.PropertyEditorAlias);
if (propEditor == null)
continue;
var propData = new ContentPropertyData(obj.Value, preValues, new Dictionary<string, object>());
model[i].Value = propEditor.ValueEditor.ConvertEditorToDb(propData, obj.Value);
}
return JsonConvert.SerializeObject(model);
}
}
} |
using PhotonInMaze.Common.Flow;
using UnityEngine;
using UnityEngine.UI;
namespace PhotonInMaze.CanvasGame.TimeToEnd {
internal class TimeToEndController : FlowBehaviourSingleton<TimeToEndController> {
public float TimeToEnd { get; private set; }
string minutes, seconds;
public override void OnInit() {
TimeToEnd = 120f;
}
public override IInvoke OnLoop() {
return GameFlowManager.Instance.Flow
.When(State.GameRunning)
.Then(CountDownTimeToEnd)
.Build();
}
private void CountDownTimeToEnd() {
TimeToEnd -= Time.deltaTime;
if(TimeToEnd <= 0f) {
GameFlowManager.Instance.Flow.NextState();
} else {
seconds = (TimeToEnd % 60).ToString("00");
minutes = Mathf.Floor(TimeToEnd / 60).ToString("00");
if(seconds.Equals("60")) {
seconds = "00"; minutes = (int.Parse(minutes) + 1).ToString("00");
}
gameObject.GetComponent<Text>().text = string.Format("Time to end: {0} : {1}", minutes, seconds);
}
}
public override int GetInitOrder() {
return (int)InitOrder.Default;
}
}
} |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ConcurrentCollectionExamples
{
public class Example1 : IExample
{
public void Run()
{
Console.WriteLine("Example 1");
var orders = new Queue<string>();
Task task1 = Task.Run(() => PlaceOrders(orders, "Mark"));
Task task2 = Task.Run(() => PlaceOrders(orders, "Ramdevi"));
Task task3 = Task.Run(() => PlaceOrders(orders, "John"));
Task.WaitAll(task1, task2, task3);
foreach (var order in orders)
{
Console.WriteLine(order);
}
}
private static object _lockObj = new object();
private static void PlaceOrders(Queue<string> orders, string name)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1);
string orderName = string.Format("{0} wants t-shirt {1}", name, i);
lock (_lockObj)
{
orders.Enqueue(orderName);
}
}
}
}
} |
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using OpenQA.Selenium.Remote;
namespace AkCore.E2ETests
{
public static class Helpers
{
public static IWebElement FindVisible(this ReadOnlyCollection<IWebElement> elements)
{
foreach (var element in elements)
{
if (element.Displayed)
{
return element;
}
}
return null;
}
public static IWebElement WaitAndGetElement(this IWebDriver driver, Func<string, By> by, string elementName)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementIsVisible(by(elementName)));
return driver.FindElement(by(elementName));
}
public static bool WaitForValue(this IWebDriver driver, Func<string, By> by, string elementName, string value)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
return wait.Until<bool>(d => d.FindElement(by(elementName)).GetAttribute("value") == value);
}
public static bool WaitForValue(this IWebElement element, IWebDriver driver, string value)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
return wait.Until<bool>(d => element.GetAttribute("value") == value);
}
public static bool WaitForValueNotNull(this IWebElement element, IWebDriver driver)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
return wait.Until(d => element.GetAttribute("value") != "");
}
public static IWebElement WaitFindId(this IWebDriver driver, string id, int timeOutInMinutes = 3)
{
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(timeOutInMinutes));
return wait.Until(d => d.FindElements(By.Id(id)).FirstOrDefault());
}
public static IWebElement WaitFindSelector(this IWebDriver driver, string selector, int index = 0,
int timeOutInMinutes = 3)
{
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(timeOutInMinutes));
return wait.Until(d => d.FindElements(By.CssSelector(selector)).ElementAtOrDefault(index));
}
public static bool IsAlertPresent(IWebDriver driver)
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
public static RemoteWebDriver SetBrowser(string browser)
{
var path = Directory.GetCurrentDirectory();
switch (browser)
{
case "Chrome":
return new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver") ?? path);
case "Firefox":
return new FirefoxDriver(Environment.GetEnvironmentVariable("GeckoWebDriver") ?? path);
case "IE":
return new InternetExplorerDriver(Environment.GetEnvironmentVariable("IEWebDriver") ?? path);
default:
return new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver") ?? path);
}
}
}
} |
using StardewValley;
using StardewValley.Network;
namespace FunnySnek.AntiCheat.Server.Framework.Patches
{
/// <summary>Harmony patch for making sure no messages are received from client.</summary>
internal class Multiplayer_ProcessIncomingMessage_Patcher : Patch
{
/*********
** Properties
*********/
protected override PatchDescriptor GetPatchDescriptor() => new PatchDescriptor(typeof(Multiplayer), "processIncomingMessage");
/*********
** Public methods
*********/
public static bool Prefix(IncomingMessage msg)
{
if (Game1.IsServer && (msg == null || !Game1.otherFarmers.ContainsKey(msg.FarmerID)))
{
//They have been kicked off the server
return false;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CenterSlider : MonoBehaviour
{
public float minValue = 0;
public float maxValue = 100;
private float curValue;
public Image background;
public Image fill;
protected void Start()
{
fill.transform.localScale = Vector3.zero;
}
public void UpdatePercentage(float percent)
{
fill.transform.localScale = background.transform.localScale * (percent / maxValue);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LocusNew.Core.Models
{
public class SellerLead
{
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public int SquareMeters { get; set; }
public int PropertyTypeId { get; set; }
public PropertyType PropertyType { get; set; }
public int Floor { get; set; }
public string Address { get; set; }
public DateTime Date { get; set; }
public bool Elevator { get; set; }
public bool Balcony { get; set; }
public decimal FeeWanted { get; set; }
public bool IsSelling { get; set; }
public bool IsRepurchasing { get; set; }
}
} |
using Microsoft.AspNetCore.Mvc;
using WpfBu.Models;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authorization;
namespace netbu.Controllers
{
[Authorize]
public class DataController : Controller
{
public JsonResult getdata(string id, string mode, string page, string Fc, string TextParams, string SQLParams)
{
var F = new Finder();
F.Account = User.Identity.Name;
if (string.IsNullOrEmpty(F.Account))
F.Account = "malkin";
F.nrows = 30;
if (!string.IsNullOrEmpty(mode))
F.Mode = mode;
else
F.Mode = "new";
if (!string.IsNullOrEmpty(page))
F.page = int.Parse(page);
if (!string.IsNullOrEmpty(Fc))
{
F.Fcols = JsonConvert.DeserializeObject<List<FinderField>>(Fc);
}
if (!string.IsNullOrEmpty(TextParams))
{
F.TextParams = JsonConvert.DeserializeObject<Dictionary<string, string>>(TextParams);
}
if (!string.IsNullOrEmpty(SQLParams))
{
F.SQLParams = JsonConvert.DeserializeObject<Dictionary<string, object>>(SQLParams);
Dictionary<string, object> parseParam = new Dictionary<string, object>();
foreach (string k in F.SQLParams.Keys)
{
DateTime dval;
string val = F.SQLParams[k].ToString();
if (DateTime.TryParse(val, out dval))
{
parseParam.Add(k, dval);
}
else
{
parseParam.Add(k, F.SQLParams[k]);
}
}
F.SQLParams = parseParam;
}
try
{
F.not_page = "y";
F.start(id);
return Json(F.MainTab);
}
catch (Exception e)
{
return Json(new { Error = e.Message });
}
}
}
} |
using APIXULib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace APIXUWebSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetWeather(string[] city)
{
List<WeatherModel> listOfCities = new List<WeatherModel>();
if (city == null) {
return Json(listOfCities, JsonRequestBehavior.AllowGet);
}
else
{
foreach (var City in city)
{
string key = "eb2a0633229b456ba6093557151106";
IRepository repo = new Repository();
if (City == "")
{
//DO NOTHING
}
else
{
var GetCityForecastWeatherResult = repo.GetWeatherData(key, GetBy.CityName, City, Days.Three);
if (GetCityForecastWeatherResult.current == null && GetCityForecastWeatherResult.location == null)
{
//DO NOTHING - IF CANT FIND CITY/COUNTRY
}
else
{
listOfCities.Add(GetCityForecastWeatherResult);
}
}
}
return Json(listOfCities, JsonRequestBehavior.AllowGet);
}
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} |
using FIMMonitoring.Domain.Enum;
using System;
using System.ComponentModel.DataAnnotations;
namespace FIMMonitoring.Domain
{
public class ServiceImportError : EntityBase
{
#region Properties
public ErrorSource ErrorSource { get; set; }
public ErrorLevel ErrorLevel { get; set; }
public ErrorType? ErrorType { get; set; }
public DateTime? ErrorDate { get; set; }
public DateTime CreatedAt { get; set; }
public bool IsValidated { get; set; }
public bool IsParsed { get; set; }
public bool IsDownloaded { get; set; }
public bool IsSent { get; set; }
public bool IsBusinessValidated { get; set; }
[MaxLength]
public string Description { get; set; }
[MaxLength(200)]
public string CustomerName { get; set; }
[MaxLength(200)]
public string CarrierName { get; set; }
[MaxLength(200)]
public string SourceName { get; set; }
public Guid Guid { get; set; }
#endregion Properties
#region ForeignKeys
public int? ImportId { get; set; }
public int? SourceId { get; set; }
public int? CustomerId { get; set; }
public int? CarrierId { get; set; }
public int? FileCheckId { get; set; }
#endregion ForeignKeys
#region Virtuals
public virtual FileCheck FileCheck { get; set; }
#endregion Virtuals
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.