本文整理汇总了C#中Common.List.Clear方法的典型用法代码示例。如果您正苦于以下问题:C# List.Clear方法的具体用法?C# List.Clear怎么用?C# List.Clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Common.List
的用法示例。
在下文中一共展示了List.Clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RunAsyncTasks
/// <summary>
/// Perform one or more tasks asyncronously.
/// </summary>
/// <param name="actions">The action(s) to perform</param>
public static void RunAsyncTasks(params Action[] actions)
{
var tasks = new List<Task>();
foreach (var action in actions)
{
tasks.Add(Task.Factory.StartNew(action));
}
Task.WaitAll(tasks.ToArray());
tasks.Clear();
}
示例2: btnImport_Click
private void btnImport_Click(object sender, EventArgs e)
{
//整体表格
var multilanFolder = ctlMultiLanFolder.SelectedPathOrFileName;
//整理出最大列表,防止文件之间出现单词表格不同
var uuiDs = new List<string>();
uuiDs.Clear();
if (!string.IsNullOrEmpty(multilanFolder))
{
//便利整个文件夹,获得语言字典
foreach (var filename in Directory.GetFiles(multilanFolder))
{
StringResource.InitLanguage(filename);
var singleDic = new Dictionary<string, string>();
foreach (var item in StringResource.StringDic)
{
if (!uuiDs.Contains(item.Key)) uuiDs.Add(item.Key);
singleDic.Add(item.Key, item.Value);
}
_multiLanguageDictionary.Add(StringResource.LanguageType, singleDic);
}
}
//将数据放入ListView视图
lstMultiLan.Clear();
//Header
lstMultiLan.Columns.Add("统一标示");
for (var i = 0; i < _multiLanguageDictionary.Keys.Count; i++)
{
lstMultiLan.Columns.Add(_multiLanguageDictionary.Keys.ElementAt(i));
}
//Details
for (var i = 0; i < uuiDs.Count; i++)
{
var item = new ListViewItem(uuiDs[i]);
for (var j = 0; j < _multiLanguageDictionary.Keys.Count; j++)
{
if (_multiLanguageDictionary[_multiLanguageDictionary.Keys.ElementAt(j)].ContainsKey(uuiDs[i]))
{
item.SubItems.Add(_multiLanguageDictionary[_multiLanguageDictionary.Keys.ElementAt(j)][uuiDs[i]]);
}
else
{
item.SubItems.Add("");
}
}
lstMultiLan.Items.Add(item);
}
Utility.ListViewColumnResize(lstMultiLan);
}
示例3: GetRequestPitchBoll
/// <summary>
/// 投手に要求する投球を取得
/// </summary>
/// <returns>要求する投球(コースと球種のみ設定)</returns>
public PitchingBallData GetRequestPitchBoll()
{
// 基本作戦の「常に厳しいコース」を追加
List<PitchingMission> missions = new List<PitchingMission>();
missions.Add(new PitchingMission(PitchingMissionKind.Random));
// 智力依存で投球の作戦を追加
AddMissions(missions);
// 検証用の投球作戦が指定されている場合は、他の投球作成をクリアしてそれを設定する
if (PitchingMissionsForDebug.Count > 0)
{
missions.Clear();
missions.AddRange(PitchingMissionsForDebug);
}
// 要求する投球データの初期値
// (球種はランダム、コースは厳しいコース)
PitchingBallData requestBall = new PitchingBallData()
{
IsFastBall = RandomCreater.GetBool(),
PitchingCourse = PitchingCourse.Severe
};
// 優先順位の低い順にソートした作戦を元にスイングデータを作成する
// (優先度の高い作戦により、後から上書きする)
var sortedMissions = missions.OrderBy(m => m.Priority);
foreach (PitchingMission mission in sortedMissions)
{
requestBall = mission.GetRequestBall(GameData, requestBall);
}
// ウエストの場合は球種は直球にしておく(アニメーションを直球にするため)
if (requestBall.PitchingCourse == PitchingCourse.PitchOut)
{
requestBall.IsFastBall = true;
}
return requestBall;
}
示例4: GenerateVesselPositions
private List<IPosition> GenerateVesselPositions(int vesselSize, IEnumerable<IVessel> existingVessels)
{
Orientation vesselOrientation;
IPosition startPosition;
List<IPosition> newVesselPositions = new List<IPosition>();
// Keep generating random positions until they are valid.
do
{
// Clear the list first (in case any positions have been added during previous iterations).
newVesselPositions.Clear();
// Get random orientation and start position which will determine the rest of the positions.
vesselOrientation = this.GetRandomOrientation();
startPosition = this.GetRandomStartPosition(vesselSize);
newVesselPositions.Add(startPosition);
int currentPositionRow = newVesselPositions[0].Row;
int currentPositionCol = newVesselPositions[0].Col;
// Add the remaining positions.
for (int i = 1; i < vesselSize; i++)
{
if (vesselOrientation == Orientation.Vertical)
{
currentPositionRow++;
}
else if (vesselOrientation == Orientation.Horizontal)
{
currentPositionCol++;
}
newVesselPositions.Add(new Position(currentPositionRow, currentPositionCol));
}
}
while (!this.ArePositionsEmpty(newVesselPositions, existingVessels));
return newVesselPositions;
}
示例5: ProcessRequest
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["type"] != null)
{
if (context.Request.QueryString["type"] == "bind")
{
#region 绑定用户列表
if (context.Request.QueryString["opera"] == "users")
{
Dictionary<string, string> userDic = new Dictionary<string, string>();
if (context.Request.QueryString["userID"] != null)
{
userDic["userID"] = context.Request.QueryString["userID"];
}
if (context.Request.QueryString["userName"] != null)
{
userDic["userName"] = context.Request.QueryString["userName"];
}
if (context.Request.QueryString["deptID"] != null)
{
userDic["deptID"] = context.Request.QueryString["deptID"];
}
int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
string order = string.IsNullOrEmpty(context.Request.QueryString["orderField"]) ? "UserID" : context.Request.QueryString["orderField"];
int rowCount; UserInfoBLL bll = new UserInfoBLL();
DataTable dt = bll.GetUserList(userDic, pageCurrent, order, out rowCount);
StringBuilder sb = new StringBuilder();
List<string> list = new List<string>();
list.Add("<tr><th scope='col'>序号</th><th scope='col'><input id='chkAll' type='checkbox' onclick='selectAll();' /></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserID\");'>用户ID</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserName\");'>用户姓名</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"DeptID\");'>所属部门</a></th><th scope='col'> </th></tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("<tr>");
sb.AppendFormat("<td style='width: 10%;'><span>{0}</span></td>", dt.Rows[i][0]);
sb.AppendFormat("<td style='width: 10%;'><input type='checkbox' value='{0}' /></td>", dt.Rows[i]["UserID"]);
sb.AppendFormat("<td style='width: 15%;'>{0}</td>", dt.Rows[i]["UserID"]);
sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserName"]);
sb.AppendFormat("<td style='width: 15%;'>{0}</td>", dt.Rows[i]["DeptName"]);
sb.AppendFormat("<td style='width: 10%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editUser(\"{0}\");' /></td>", dt.Rows[i]["UserID"]);
sb.Append("</tr>");
}
if (string.IsNullOrEmpty(sb.ToString()))
{
list.Clear();
list.Add("<td colspan='6' style='text-align:center;line-height:26px;'>没有数据</td>");
}
else
{
list.Add(sb.ToString());
}
list.Add("☭" + rowCount);
context.Response.Write(string.Concat(list));
}
#endregion
#region 绑定部门列表
else if (context.Request.QueryString["opera"] == "depart")
{
DepartmentModel dept = new DepartmentModel();
if (context.Request.QueryString["deptName"] != null)
{
dept.DeptName = context.Request.QueryString["deptName"];
}
if (context.Request.QueryString["manager"] != null)
{
dept.ManagerID = context.Request.QueryString["manager"];
}
int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
int rowCount; DepartmentBLL bll = new DepartmentBLL();
DataTable dt = bll.GetDepartList(dept, pageCurrent, out rowCount);
StringBuilder sb = new StringBuilder();
List<string> list = new List<string>();
list.Add("<tr><th scope='col'>序号</th><th scope='col'>部门名称</th><th scope='col'>主管</th><th scope='col'> </th></tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
string DeptID = dt.Rows[i]["DeptID"].ToString();
sb.Append("<tr>");
sb.AppendFormat("<td style='width: 10%;'><span>{0}</span></td>", dt.Rows[i][0]);
sb.AppendFormat("<td style='width: 30%;'>{0}</td>", dt.Rows[i]["DeptName"]);
sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserName"]);
// 如果部门下没有员工即可删除
if (bll.IsEmptyDepart(DeptID))
sb.AppendFormat("<td style='width: 20%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editDept(\"{0}\");' /> <input type='image' id='btnDelete' title='删除' class='imgBtn' src='/Image/common/delete.png' onclick='return deleteDept(\"{1}\");' style='border-width:0px;'></td>", DeptID, DeptID);
else
sb.AppendFormat("<td style='width: 20%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editDept(\"{0}\");' /></td>", DeptID);
sb.Append("</tr>");
}
if (string.IsNullOrEmpty(sb.ToString()))
{
list.Clear();
list.Add("<td colspan='4' style='text-align:center;line-height:26px;'>没有数据</td>");
}
else
{
list.Add(sb.ToString());
}
//.........这里部分代码省略.........
示例6: VerifyTicketPurchase
public bool VerifyTicketPurchase()
{
List<IBobAsHTML> bobsAsHTML = new List<IBobAsHTML>();
if ((this.Enabled || this.Cancelled) && (this.Invoice == null || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0))
{
string oldTicketHTML = this.AsHTML();
string ticketFromDataBaseHTML = "Unable to retrieve ticket from database.";
try
{
// Get fresh data from database and compare to MemCached Ticket
TicketSet ticketsFromDatabase = new TicketSet(new Query(new Q(Ticket.Columns.K, this.K)));
if (ticketsFromDatabase.Count == 1)
{
ticketFromDataBaseHTML = ticketsFromDatabase[0].AsHTML();
this.InvoiceItemK = ticketsFromDatabase[0].InvoiceItemK;
this.FirstName = ticketsFromDatabase[0].FirstName;
this.LastName = ticketsFromDatabase[0].LastName;
this.CardNumberEnd = ticketsFromDatabase[0].CardNumberEnd;
this.CardCV2 = ticketsFromDatabase[0].CardCV2;
this.Update();
//if (this.InvoiceItemK != ticketsFromDatabase[0].InvoiceItemK || this.Enabled != ticketsFromDatabase[0].Enabled || this.Cancelled != ticketsFromDatabase[0].Cancelled || Math.Round(this.Price, 2) != Math.Round(ticketsFromDatabase[0].Price, 2))
//{
// bobsAsHTML.Add(this);
// bobsAsHTML.Add(ticketsFromDatabase[0]);
// Utilities.AdminEmailAlert("<p>MemCache and database do not match for ticket.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>", "Error with MemCache", new DSIUserFriendlyException("Error with MemCache"), bobsAsHTML);
//}
}
if (this.InvoiceItemK == 0 || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0)
{
bobsAsHTML.Clear();
Query ticketInvoiceQuery = new Query(new And(new Q(Invoice.Columns.UsrK, this.BuyerUsrK),
//new Q(InvoiceItem.Columns.Total, this.Price),
new Q(InvoiceItem.Columns.BuyableObjectType, Convert.ToInt32(Model.Entities.ObjectType.Ticket)),
new Q(InvoiceItem.Columns.BuyableObjectK, this.K),
new Q(Invoice.Columns.Paid, 1),
new Q(Invoice.Columns.PaidDateTime, QueryOperator.GreaterThanOrEqualTo, this.BuyDateTime.AddMinutes(-8)),
new Q(Invoice.Columns.PaidDateTime, QueryOperator.LessThanOrEqualTo, this.BuyDateTime.AddMinutes(8))));
ticketInvoiceQuery.TableElement = new Join(Invoice.Columns.K, InvoiceItem.Columns.InvoiceK);
InvoiceSet ticketInvoice = new InvoiceSet(ticketInvoiceQuery);
if (ticketInvoice.Count == 1 && ticketInvoice[0].Items.Count > 0)
{
if (this.InvoiceItemK == 0)
{
foreach (InvoiceItem ii in ticketInvoice[0].Items)
{
if (ii.Type == InvoiceItem.Types.EventTickets && ii.KeyData == this.K && ii.BuyableObjectType == Model.Entities.ObjectType.Ticket && ii.BuyableObjectK == this.K && Math.Round(ii.Total, 2) == Math.Round(this.Price))
this.InvoiceItemK = ii.K;
}
}
bobsAsHTML.Add(this);
bobsAsHTML.Add(ticketInvoice[0]);
if (ticketInvoice[0].SuccessfulAppliedTransfers.Count == 1)
{
bobsAsHTML.Add(ticketInvoice[0].SuccessfulAppliedTransfers[0]);
if (this.CardNumberEnd.Length == 0)
{
this.CardNumberEnd = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardNumberEnd;
this.CardNumberDigits = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardDigits;
this.CardCV2 = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardCV2;
}
if (this.AddressPostcode.Length == 0)
{
this.AddressPostcode = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardPostcode;
}
if (this.AddressStreet.Length == 0)
{
this.AddressStreet = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardAddress1;
}
if (this.FirstName != Cambro.Misc.Utility.Snip(Utilities.GetFirstName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100))
{
this.FirstName = Cambro.Misc.Utility.Snip(Utilities.GetFirstName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100);
}
if (this.LastName != Cambro.Misc.Utility.Snip(Utilities.GetLastName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100))
{
this.LastName = Cambro.Misc.Utility.Snip(Utilities.GetLastName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100);
}
this.Update();
}
Utilities.AdminEmailAlert("<p>Ticket and invoice did not match, but have been auto fixed.</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>" + oldTicketHTML + ticketFromDataBaseHTML,
"Ticket auto fixed #" + this.K.ToString(), new DsiUserFriendlyException("Ticket auto fixed"), bobsAsHTML, new string[] { Vars.EMAIL_ADDRESS_TIMI });
}
else
{
Utilities.AdminEmailAlert("<p>Ticket and invoice did not match, and have not been fixed. Unable to find invoice from database</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>" + oldTicketHTML + ticketFromDataBaseHTML,
"Error not fixed with ticket #" + this.K.ToString(), new DsiUserFriendlyException("Ticket not fixed"), bobsAsHTML, new string[] { Vars.EMAIL_ADDRESS_TIMI });
}
}
}
catch { }
if (this.InvoiceItemK == 0 || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0)
{
Utilities.AdminEmailAlert("<p>Ticket information missing.</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>",
"Error with Ticket #" + this.K.ToString(), new DsiUserFriendlyException("Error with ticket"), new List<IBobAsHTML>(){this}, new string[] { Vars.EMAIL_ADDRESS_TIMI });
//.........这里部分代码省略.........
示例7: RecreateTargets
private void RecreateTargets()
{
List<Action<RenderTarget2D>> list = new List<Action<RenderTarget2D>>();
foreach (RenderTargetHandle renderTargetHandle in this.fullscreenRTs)
{
list.Clear();
foreach (TargetRenderingManager.RtHook rtHook in this.renderTargetsToHook)
{
if (renderTargetHandle.Target == rtHook.Target)
{
TargetRenderingManager.RtHook _ = rtHook;
list.Add((Action<RenderTarget2D>) (t => _.Target = t));
}
}
renderTargetHandle.Target.Dispose();
renderTargetHandle.Target = this.CreateFullscreenTarget();
foreach (Action<RenderTarget2D> action in list)
action(renderTargetHandle.Target);
}
}
示例8: Compute
public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, int time, bool prob)
{
try{
Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node>(600);
// Initialize our version of the matrix (can we skip this?)
Node[][] newMatrix = new Node[matrix[0].Length][];
for (int x = 0; x < matrix [0].Length; x++) {
newMatrix [x] = new Node[matrix [0] [x].Length];
for (int y = 0; y < matrix [0] [x].Length; y++) {
newMatrix [x] [y] = new Node ();
newMatrix [x] [y].parent = null;
newMatrix [x] [y].cell = matrix [0] [x] [y];
newMatrix [x] [y].x = x;
newMatrix [x] [y].y = y;
}
}
enemyPathProb(newMatrix);
// Do the work for the first cell before firing the algorithm
start = newMatrix [startX] [startY];
end = newMatrix [endX] [endY];
start.parent=null;
start.visited=true;
foreach (Node n in getAdjacent(start, newMatrix)) {
n.t=time;
n.parent = start;
float fVal = f (n);
n.Priority = fVal;
heap2.Enqueue(n,fVal);
}
while(heap2.Count != 0){
Node first = heap2.Dequeue();
if(first == end)
break;
first.visited=true;
double temprt = 1;
List<Node> adjs = getAdjacent(first,newMatrix);
foreach(Node m in adjs){
float currentG = (float)(g (first) + h (first,m, ref temprt));
if(m.visited){
if(g (m)>currentG){
m.parent=first;
m.t = first.t+time;
}
}
else{
if( !heap2.Contains(m)){
m.parent = first;
m.t= first.t +time;
m.Priority = (float)temprt*f(m);
heap2.Enqueue(m, m.Priority);
}
else
{
float gVal = g (m);
if(gVal>currentG){
m.parent= first;
m.t = first.t+time;
m.Priority= (float)temprt *f (m);
heap2.UpdatePriority(m, m.Priority);
}
}
}
}
}
// Creates the result list
Node l = end;
List<Node> points = new List<Node> ();
while (l != null) {
points.Add (l);
l = l.parent;
}
points.Reverse ();
// If we didn't find a path
if (points.Count == 1)
points.Clear ();
return points;
}catch(System.Exception e){
Debug.Log (e.Message);
Debug.Log (e.StackTrace);
Debug.Log ("ERROR 2");
return null;
}
}
示例9: OnGetFilteredArchive
public static OperationResult<List<JournalRecord>> OnGetFilteredArchive(ArchiveFilter archiveFilter, bool isReport)
{
var operationResult = new OperationResult<List<JournalRecord>>();
operationResult.Result = new List<JournalRecord>();
try
{
string dateInQuery = "DeviceTime";
if (archiveFilter.UseSystemDate)
dateInQuery = "SystemTime";
var query =
"SELECT * FROM Journal WHERE " +
"\n " + dateInQuery + " > '" + archiveFilter.StartDate.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
"\n AND " + dateInQuery + " < '" + archiveFilter.EndDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
if (archiveFilter.Descriptions.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.Descriptions.Count; i++)
{
if (i > 0)
query += "\n OR ";
var description = archiveFilter.Descriptions[i];
description = description.Replace("'", "''");
query += " Description = '" + description + "'";
}
query += ")";
}
if (archiveFilter.Subsystems.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.Subsystems.Count; i++)
{
if (i > 0)
query += "\n OR ";
var subsystem = archiveFilter.Subsystems[i];
query += " SubSystemType = '" + ((int)subsystem).ToString() + "'";
}
query += ")";
}
if (archiveFilter.PanelUIDs.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.PanelUIDs.Count; i++)
{
var deviceName = archiveFilter.PanelUIDs[i];
if (deviceName != null)
{
if (i > 0)
query += "\n OR ";
query += " PanelDatabaseId = '" + deviceName + "'";
}
}
query += ")";
}
query += "\n ORDER BY " + dateInQuery + " DESC";
using (var DataBaseContext = new SqlCeConnection(ConnectionString))
{
DataBaseContext.ConnectionString = ConnectionString;
var journalRecords = new List<JournalRecord>();
var result = new SqlCeCommand(query, DataBaseContext);
DataBaseContext.Open();
var reader = result.ExecuteReader();
while (reader.Read())
{
if (IsAbort && !isReport)
break;
try
{
var journalRecord = ReadOneJournalRecord(reader);
operationResult.Result.Add(journalRecord);
if (!isReport)
{
journalRecords.Add(journalRecord);
if (journalRecords.Count > 100)
{
if (ArchivePortionReady != null)
ArchivePortionReady(journalRecords.ToList());
journalRecords.Clear();
}
}
}
catch (Exception e)
{
Logger.Error(e, "DatabaseHelper.OnGetFilteredArchive");
}
}
if (!isReport)
{
if (ArchivePortionReady != null)
ArchivePortionReady(journalRecords.ToList());
}
DataBaseContext.Close();
}
//.........这里部分代码省略.........
示例10: Compute
public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, float playerSpeed)
{
this.speed = 1.0d / playerSpeed;
try {
Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (1000000);
List<Node> closed = new List<Node> ();
// Initialize our version of the matrix (can we skip this?)
Node[][][] newMatrix = new Node[matrix.Length][][];
for (int t=0; t<matrix.Length; t++) {
newMatrix [t] = new Node[matrix [t].Length][];
for (int x = 0; x < matrix [t].Length; x++) {
newMatrix [t] [x] = new Node[matrix [t] [x].Length];
for (int y = 0; y < matrix [t] [x].Length; y++) {
newMatrix [t] [x] [y] = new Node ();
newMatrix [t] [x] [y].parent = null;
newMatrix [t] [x] [y].cell = matrix [t] [x] [y];
newMatrix [t] [x] [y].x = x;
newMatrix [t] [x] [y].y = y;
newMatrix [t] [x] [y].t = t;
}
}
}
// Do the work for the first cell before firing the algorithm
start = newMatrix [0] [startX] [startY];
end = newMatrix [0] [endX] [endY];
start.parent = null;
start.visited = true;
start.accSpeed = speed - Math.Floor(speed);
foreach (Node n in getAdjacent(start, newMatrix)) {
n.parent = start;
float fVal = f (n);
n.Priority = fVal;
heap2.Enqueue (n, fVal);
}
while (heap2.Count != 0) {
Node first = heap2.Dequeue ();
if (first.x == end.x && first.y == end.y) {
end = newMatrix [first.t] [end.x] [end.y];
break;
}
first.visited = true;
foreach (Node m in getAdjacent(first, newMatrix)) {
float currentG = g (first) + h (m, first);
float gVal = g (m);
if (m.visited) {
if (gVal > currentG) {
m.parent = first;
acc(m);
}
} else {
if (!heap2.Contains (m)) {
m.parent = first;
m.Priority = f (m);
heap2.Enqueue (m, m.Priority);
acc(m);
} else {
if (gVal > currentG) {
m.parent = first;
m.Priority = f (m);
heap2.UpdatePriority (m, m.Priority);
acc(m);
}
}
}
}
}
// Creates the result list
Node e = end;
List<Node> points = new List<Node> ();
while (e != null) {
points.Add (e);
e = e.parent;
}
points.Reverse ();
// If we didn't find a path
if (points.Count == 1)
points.Clear ();
return points;
} catch (System.Exception e) {
Debug.Log (e.Message);
Debug.Log (e.StackTrace);
Debug.Log ("ERROR 2");
return null;
}
}
示例11: OnGetFilteredArchive
public static List<FS2JournalItem> OnGetFilteredArchive(ArchiveFilter archiveFilter, bool isReport)
{
var result = new List<FS2JournalItem>();
try
{
string dateInQuery = "DeviceTime";
if (archiveFilter.UseSystemDate)
dateInQuery = "SystemTime";
var query =
"SELECT * FROM Journal WHERE " +
"\n " + dateInQuery + " > '" + archiveFilter.StartDate.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
"\n AND " + dateInQuery + " < '" + archiveFilter.EndDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
if (archiveFilter.Descriptions.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.Descriptions.Count; i++)
{
if (i > 0)
query += "\n OR ";
var description = archiveFilter.Descriptions[i];
description = description.Replace("'", "''");
query += " Description = '" + description + "'";
}
query += ")";
}
if (archiveFilter.Subsystems.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.Subsystems.Count; i++)
{
if (i > 0)
query += "\n OR ";
var subsystem = archiveFilter.Subsystems[i];
query += " SubSystemType = '" + ((int)subsystem).ToString() + "'";
}
query += ")";
}
if (archiveFilter.PanelUIDs.Count > 0)
{
query += "\n AND (";
for (int i = 0; i < archiveFilter.PanelUIDs.Count; i++)
{
var panelUID = archiveFilter.PanelUIDs[i];
if (panelUID != null)
{
if (i > 0)
query += "\n OR ";
query += " PanelUID = '" + panelUID + "'";
}
}
query += ")";
}
query += "\n ORDER BY " + dateInQuery + " DESC";
using (var sqlCeConnection = new SqlCeConnection(ConnectionString))
{
sqlCeConnection.ConnectionString = ConnectionString;
var journalItems = new List<FS2JournalItem>();
var sqlCeCommand = new SqlCeCommand(query, sqlCeConnection);
sqlCeConnection.Open();
var reader = sqlCeCommand.ExecuteReader();
while (reader.Read())
{
if (IsAbort && !isReport)
break;
try
{
var journalItem = ReadOneJournalItem(reader);
result.Add(journalItem);
if (!isReport)
{
journalItems.Add(journalItem);
if (journalItems.Count > 100)
{
if (ArchivePortionReady != null)
ArchivePortionReady(journalItems.ToList());
journalItems.Clear();
}
}
}
catch (Exception e)
{
Logger.Error(e, "DatabaseHelper.OnGetFilteredArchive");
}
}
if (!isReport)
{
if (ArchivePortionReady != null)
ArchivePortionReady(journalItems.ToList());
}
sqlCeConnection.Close();
}
}
//.........这里部分代码省略.........
示例12: Compute
public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][] matrix, bool improve)
{
List<Node> opened = new List<Node> ();
Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (600);
List<Node> closed = new List<Node> ();
// Initialize our version of the matrix (can we skip this?)
Node[][] newMatrix = new Node[matrix.Length][];
for (int x = 0; x < matrix.Length; x++) {
newMatrix [x] = new Node[matrix [x].Length];
for (int y = 0; y < matrix[x].Length; y++) {
newMatrix [x] [y] = new Node ();
newMatrix [x] [y].parent = null;
newMatrix [x] [y].cell = matrix [x] [y];
newMatrix [x] [y].x = x;
newMatrix [x] [y].y = y;
}
}
// Do the work for the first cell before firing the algorithm
start = newMatrix [startX] [startY];
end = newMatrix [endX] [endY];
closed.Add (start);
foreach (Node c in getAdjacent(start, newMatrix)) {
c.parent = start;
if (improve)
heap2.Enqueue (c, f (c));
else
opened.Add (c);
}
while ((improve && heap2.Count > 0) || (!improve && opened.Count > 0)) {
// Pick the closest to the goal
Node minF = null;
if (improve) {
minF = heap2.Dequeue ();
} else {
for (int i = 0; i < opened.Count; i++) {
if (minF == null || f (minF) > f (opened [i]))
minF = opened [i];
}
opened.Remove (minF);
}
closed.Add (minF);
// Found it
if (minF == end)
break;
foreach (Node adj in getAdjacent(minF, newMatrix)) {
float soFar = g (minF) + h (adj, minF);
// Create the links between cells (picks the best path)
if (closed.Contains (adj)) {
if (g (adj) > soFar) {
adj.parent = minF;
}
} else {
if ((improve && heap2.Contains (adj)) || (!improve && opened.Contains (adj))) {
if (g (adj) > soFar) {
adj.parent = minF;
}
} else {
adj.parent = minF;
if (improve)
heap2.Enqueue (adj, f (adj));
else
opened.Add (adj);
}
}
}
}
// Creates the result list
Node n = end;
List<Node> points = new List<Node> ();
while (n != null) {
points.Add (n);
n = n.parent;
}
points.Reverse ();
// If we didn't find a path
if (points.Count == 1)
points.Clear ();
return points;
}
示例13: Tick
//Actual update tick
public void Tick()
{
if (this.unitCount <= 0) {
//Defeat. No more AI units on the map.
Debug.Log("AI Player is defeated.");
this.hasLostTheGame = true;
this.startAIFlag = false;
return;
}
switch (this.currentFiniteState) {
case FSMState.Wait:
if (this.selectedUnits.Count > 0) {
this.selectedUnits.Clear();
}
if (this.unitCount == 1) {
//Usually at the start of the game, or when the AI player is on the brink of defeat.
Transform child = this.unitContainer.transform.GetChild(this.unitContainer.transform.childCount - 1);
AIUnit unit = child.GetComponent<AIUnit>();
AILineOfSight lineOfSight = child.GetComponentInChildren<AILineOfSight>();
AIAttackRange attackRange = child.GetComponentInChildren<AIAttackRange>();
//TODO: Refer to an attribute manager for AI units on what attributes are required.
unit.teamFaction = this.teamFaction;
lineOfSight.teamFaction = this.teamFaction;
attackRange.teamFaction = this.teamFaction;
//Always select the unit before doing other AI state machines.
this.spawnList.Add(unit);
this.currentFiniteState = FSMState.Split;
break;
}
int scoutUnitCount = 0;
int splitUnitCount = 0;
int mergeUnitCount = 0;
foreach (Transform child in this.unitContainer.transform) {
if (splitUnitCount > 0) {
splitPercentage = splitRatio / splitUnitCount;
}
else {
splitPercentage = splitRatio / 1f;
}
if (mergeUnitCount > 0) {
mergePercentage = mergeRatio / mergeUnitCount;
}
else {
mergePercentage = mergeRatio / 1f;
}
if (scoutUnitCount > 0) {
scoutPercentage = scoutRatio / scoutUnitCount;
}
else {
scoutPercentage = scoutRatio / 1f;
}
if (this.splitPercentage > this.mergePercentage && this.splitPercentage > this.scoutPercentage) {
this.spawnList.Add(child.GetComponent<AIUnit>());
splitUnitCount++;
}
else if (this.splitPercentage > this.mergePercentage && this.splitPercentage < this.scoutPercentage) {
this.selectedUnits.Add(child.GetComponent<AIUnit>());
scoutUnitCount++;
}
else if (this.splitPercentage < this.mergePercentage && this.splitPercentage > this.scoutPercentage) {
this.mergeList.Add(child.GetComponent<AIUnit>());
mergeUnitCount++;
}
else if (this.splitPercentage < this.mergePercentage && this.splitPercentage < this.scoutPercentage) {
if (this.mergePercentage > this.scoutPercentage) {
this.mergeList.Add(child.GetComponent<AIUnit>());
mergeUnitCount++;
}
else {
this.selectedUnits.Add(child.GetComponent<AIUnit>());
scoutUnitCount++;
}
}
}
this.currentFiniteState = FSMState.Merge;
break;
case FSMState.Split:
if (this.spawnList.Count > 0) {
foreach (AIUnit unit in this.spawnList) {
if (unit != null && unit.currentState != State.Split) {
if (this.unitCount < this.maxUnitCount) {
GameObject splitObject = SplitUnit(unit);
if (splitObject != null) {
this.splitGroupList.Add(new SplitGroup(unit.gameObject, splitObject));
}
}
else {
break;
}
}
}
//.........这里部分代码省略.........
示例14: Run
public override void Run()
{
#region Create renderers
// Note: the renderers take care of creating their own
// device resources and listen for DeviceManager.OnInitialize
#region Initialize MeshRenderer instances
// Create and initialize the mesh renderer
var loadedMesh = Common.Mesh.LoadFromFile("Scene.cmo");
List<MeshRenderer> meshes = new List<MeshRenderer>();
meshes.AddRange((from mesh in loadedMesh
select ToDispose(new MeshRenderer(mesh))));
// We will support a cubemap for each mesh that contains "reflector" in its name
List<DynamicCubeMap> envMaps = new List<DynamicCubeMap>();
// We will rotate any meshes that contains "rotate" in its name
List<MeshRenderer> rotateMeshes = new List<MeshRenderer>();
// We will generate meshRows * meshColumns of any mesh that contains "replicate" in its name
int meshRows = 10;
int meshColumns = 10;
// Define an action to initialize our meshes so that we can
// dynamically change the number of reflective surfaces and
// replicated meshes
Action createMeshes = () =>
{
// Clear context states, ensures we don't have
// any of the resources we are going to release
// assigned to the pipeline.
DeviceManager.Direct3DContext.ClearState();
if (contextList != null)
{
foreach (var context in contextList)
context.ClearState();
}
// Remove meshes
foreach (var mesh in meshes)
mesh.Dispose();
meshes.Clear();
// Remove environment maps
foreach (var envMap in envMaps)
envMap.Dispose();
envMaps.Clear();
// Create non-replicated MeshRenderer instances
meshes.AddRange(from mesh in loadedMesh
where !((mesh.Name ?? "").ToLower().Contains("replicate"))
select ToDispose(new MeshRenderer(mesh)));
#region Create replicated meshes
// Add the same mesh multiple times, separate by the combined extent
var replicatedMeshes = (from mesh in loadedMesh
where (mesh.Name ?? "").ToLower().Contains("replicate")
select mesh).ToArray();
if (replicatedMeshes.Length > 0)
{
var minExtent = (from mesh in replicatedMeshes
orderby new { mesh.Extent.Min.X, mesh.Extent.Min.Z }
select mesh.Extent).First();
var maxExtent = (from mesh in replicatedMeshes
orderby new { mesh.Extent.Max.X, mesh.Extent.Max.Z } descending
select mesh.Extent).First();
var extentDiff = (maxExtent.Max - minExtent.Min);
for (int x = -(meshColumns / 2); x < (meshColumns / 2); x++)
{
for (int z = -(meshRows / 2); z < (meshRows / 2); z++)
{
var meshGroup = (from mesh in replicatedMeshes
where (mesh.Name ?? "").ToLower().Contains("replicate")
select ToDispose(new MeshRenderer(mesh))).ToList();
// Reposition based on width/depth of combined extent
foreach (var m in meshGroup)
{
m.World.TranslationVector = new Vector3(m.Mesh.Extent.Center.X + extentDiff.X * x, m.Mesh.Extent.Min.Y, m.Mesh.Extent.Center.Z + extentDiff.Z * z);
}
meshes.AddRange(meshGroup);
}
}
}
#endregion
#region Create reflective meshes
// Create reflections where necessary and add rotation meshes
int reflectorCount = 0;
meshes.ForEach(m =>
{
var name = (m.Mesh.Name ?? "").ToLower();
if (name.Contains("reflector") && reflectorCount < maxReflectors)
{
reflectorCount++;
var envMap = ToDispose(new DynamicCubeMap(512));
//.........这里部分代码省略.........
示例15: ResumeUploadInChunks
string ResumeUploadInChunks(string path, Ticket t, int chunk_size, int max_chunks, bool firstTime)
{
const int maxFailedAttempts = 5;
if (!firstTime)
{
// Check the ticket
Debug.WriteLine("ResumeUploadInChunks(" + path + ") Checking ticket...", "VimeoClient");
var ticket = vimeo_videos_upload_checkTicket(t.id);
if (ticket == null || ticket.id != t.id)
{
Debug.WriteLine("Error in checking ticket. aborting.", "VimeoClient");
return null;
}
t = ticket;
}
//Load the file, calculate the number of chunks
var file = new FileInfo(path);
int chunksCount = GetChunksCount(file.Length, chunk_size);
Debug.WriteLine("Will upload in " + chunksCount + " chunks", "VimeoClient");
//Queue chunks for upload
List<int> missingChunks = new List<int>(chunksCount);
for (int i = 0; i < chunksCount; i++) missingChunks.Add(i);
int failedAttempts = 0;
int counter = 0;
while (failedAttempts <= maxFailedAttempts)
{
if (firstTime)
{
firstTime = false;
}
else
{
//Verify and remove the successfully uploaded chunks
Debug.WriteLine("Verifying chunks...", "VimeoClient");
var verify = vimeo_videos_upload_verifyChunks(t.id);
Debug.WriteLine(verify.Items.Count.ToString() + "/" + chunksCount + " chunks uploaded successfully.", "VimeoClient");
missingChunks.Clear();
for (int i = 0; i < chunksCount; i++) missingChunks.Add(i);
foreach (var item in verify.Items)
{
if (missingChunks.Contains(item.id) && item.size == GetChunkSize(file.Length, item.id, chunk_size))
missingChunks.Remove(item.id);
}
}
//If there are no chunks left or the limit is reached stop.
if (missingChunks.Count == 0 || (max_chunks > 0 && counter >= max_chunks))
break;
//Post chunks
while (missingChunks.Count > 0)
{
//If there are no chunks left or the limit is reached stop.
if (missingChunks.Count == 0 || (max_chunks > 0 && counter >= max_chunks))
break;
if (failedAttempts > maxFailedAttempts) break;
int chunkId = missingChunks[0];
missingChunks.RemoveAt(0);
Debug.WriteLine("Posting chunk " + chunkId + ". " + missingChunks.Count + " chunks left.", "VimeoClient");
try
{
counter++;
PostVideo(t, chunkId, path, chunk_size);
}
catch (Exception e)
{
Debug.WriteLine(e, "VimeoClient");
failedAttempts++;
}
}
}
if (missingChunks.Count == 0)
{
//All chunks are uploaded
return vimeo_videos_upload_complete(file.Name, t.id);
}
if ((max_chunks > 0 && counter >= max_chunks))
{
//Max limit is reached
return string.Empty;
}
//Error
return null;
}