Here are the examples of the csharp api System.Collections.Generic.List.RemoveAll(System.Predicate) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2197 Examples
19
Source : Animation.cs
with GNU Affero General Public License v3.0
from 0ceal0t
with GNU Affero General Public License v3.0
from 0ceal0t
public static void Tick() {
var currentTime = DateTime.Now;
foreach (var item in Anims) {
if (item.Remove) continue;
var timeElapsed = (currentTime - item.Start).TotalSeconds;
if (timeElapsed > item.Duration) {
timeElapsed = item.Duration;
}
var value = item.StartValue + (item.EndValue - item.StartValue) * (timeElapsed / item.Duration);
item.F((float)value);
}
Anims.RemoveAll(x => (currentTime - x.Start).TotalSeconds >= x.Duration || x.Remove);
}
19
Source : UIIconManager.cs
with GNU Affero General Public License v3.0
from 0ceal0t
with GNU Affero General Public License v3.0
from 0ceal0t
public void Tick() {
var time = DateTime.Now;
var millis = time.Second * 1000 + time.Millisecond;
var percent = (float)(millis % MILLIS_LOOP) / MILLIS_LOOP;
var hotbarData = UIHelper.GetHotbarUI();
if (hotbarData == null) return;
HashSet<UIIcon> foundIcons = new();
HashSet<CreateIconStruct> createIcons = new();
for (var hotbarIndex = 0; hotbarIndex < AllActionBars.Length; hotbarIndex++) {
var actionBar = (AddonActionBarBase*)AtkStage.GetSingleton()->RaptureAtkUnitManager->GetAddonByName(AllActionBars[hotbarIndex]);
if (actionBar == null || actionBar->ActionBarSlotsAction == null || actionBar->AtkUnitBase.IsVisible == false) continue;
if (hotbarIndex == 10) { // cross
ProcessCrossHotbar(hotbarIndex, actionBar, hotbarData, foundIcons, createIcons, percent);
}
else if(hotbarIndex == 11) {
ProcessDoubleCrossHotbar(hotbarIndex, actionBar, UIHelper.GetLeftDoubleCrossBar(), true, hotbarData, foundIcons, createIcons, percent);
}
else if(hotbarIndex == 12) {
ProcessDoubleCrossHotbar(hotbarIndex, actionBar, UIHelper.GetRightDoubleCrossBar(), false, hotbarData, foundIcons, createIcons, percent);
}
else {
ProcessNormalHotbar(hotbarIndex, actionBar, hotbarData, foundIcons, createIcons, percent);
}
}
// remove unused
foreach (var icon in Icons.Where(x => !foundIcons.Contains(x))) {
icon.Dispose();
}
Icons.RemoveAll(x => !foundIcons.Contains(x));
// create new
foreach (var create in createIcons) {
UIIcon newIcon = create.Props.IsTimer ?
new UIIconTimer(create.Action, create.ActionId, create.HotBarIndex, create.SlotIndex, create.Component, create.Props) :
new UIIconBuff(create.Action, create.ActionId, create.HotBarIndex, create.SlotIndex, create.Component, create.Props);
Icons.Add(newIcon);
}
}
19
Source : ExifValueCollection.cs
with MIT License
from 0xC0000054
with MIT License
from 0xC0000054
public void Remove(MetadataKey key)
{
this.exifMetadata.RemoveAll(p => p.Section == key.Section && p.TagId == key.TagId);
}
19
Source : ExifValueCollection.cs
with MIT License
from 0xC0000054
with MIT License
from 0xC0000054
public MetadataEntry GetAndRemoveValue(MetadataKey key)
{
MetadataEntry value = exifMetadata.Find(p => p.Section == key.Section && p.TagId == key.TagId);
if (value != null)
{
exifMetadata.RemoveAll(p => p.Section == key.Section && p.TagId == key.TagId);
}
return value;
}
19
Source : ConsulServiceDiscovery.cs
with MIT License
from 1100100
with MIT License
from 1100100
public async Task NodeMonitor(CancellationToken cancellationToken)
{
Logger.LogTrace("Start refresh service status,waiting for locking...");
using (await AsyncLock.LockAsync(cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
return;
foreach (var service in ServiceNodes)
{
Logger.LogTrace($"Service {service.Key} refreshing...");
try
{
var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
if (cancellationToken.IsCancellationRequested)
break;
var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
.Select(p => p.ServiceId).ToArray();
if (leavedNodes.Any())
{
//RemoveNode(service.Key, leavedNodes);
if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
OnNodeLeave?.Invoke(service.Key, leavedNodes);
Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
}
var addedNodes = healthNodes.Where(p =>
service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
.ToList();
if (addedNodes.Any())
{
//AddNode(service.Key, addedNodes);
if (ServiceNodes.TryGetValue(service.Key, out var services))
services.AddRange(addedNodes);
else
ServiceNodes.TryAdd(service.Key, addedNodes);
OnNodeJoin?.Invoke(service.Key, addedNodes);
Logger.LogTrace(
$"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
}
}
catch
{
// ignored
}
}
Logger.LogTrace("Complete refresh.");
}
}
19
Source : ZooKeeperServiceDiscovery.cs
with MIT License
from 1100100
with MIT License
from 1100100
private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
{
if (ServiceNodes.TryGetValue(serviceName, out var nodes))
{
if (!currentNodes.Any())
nodes.Clear();
var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
if (leavedNodes.Any())
{
Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
OnNodeLeave?.Invoke(serviceName, leavedNodes);
nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
}
var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
if (addedNodes.Any())
{
nodes.AddRange(addedNodes);
Logger.LogTrace(
$"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
OnNodeJoin?.Invoke(serviceName, addedNodes);
}
}
else
{
if (!currentNodes.Any())
ServiceNodes.TryAdd(serviceName, currentNodes);
}
}
19
Source : Richtext.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static Richtext Parse(BinaryReader reader)
{
var result = new Richtext();
// TODO: 解析富文本
try
{
var messageType = reader.ReadByte();
var dataLength = reader.BeReadUInt16();
var pos = reader.BaseStream.Position;
while (pos + dataLength < reader.BaseStream.Length)
{
reader.ReadByte();
switch (messageType)
{
case 0x01: // 纯文本消息、@
{
var messageStr = reader.BeReadString();
if (messageStr.StartsWith("@") && pos + dataLength - reader.BaseStream.Position == 16)
{
reader.ReadBytes(10);
result.Snippets.Add(new TextSnippet(messageStr, MessageType.At,
("Target", reader.BeReadLong32())));
}
else
{
result.Snippets.Add(messageStr);
}
break;
}
case 0x02: // Emoji(系统表情)
{
reader.BeReadUInt16(); // 这里的数字貌似总是1:系统表情只有208个。
result.Snippets.Add(new TextSnippet("", MessageType.Emoji, ("Type", reader.ReadByte())));
break;
}
case 0x03: // 图片
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Picture));
break;
}
case 0x0A: // 音频
{
result.Snippets.Add(new TextSnippet(reader.BeReadString(), MessageType.Audio));
break;
}
case 0x0E: // 未知
{
break;
}
case 0x12: // 群名片
{
break;
}
case 0x14: // XML
{
reader.ReadByte();
result.Snippets.Add(new TextSnippet(
GZipByteArray.DecompressString(reader.ReadBytes((int) (reader.BaseStream.Length - 1))),
MessageType.Xml));
break;
}
case 0x18: // 群文件
{
reader.ReadBytes(5);
var fileName = reader.BeReadString(); // 文件名称... 长度总是一个byte
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 文件大小
result.Snippets.Add(new TextSnippet(fileName, MessageType.OfflineFile));
break;
}
case 0x19: // 红包秘钥段
{
if (reader.ReadByte() != 0xC2)
{
break;
}
reader.ReadBytes(19);
reader.ReadBytes(reader.ReadByte()); // 恭喜发财
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // 赶紧点击拆开吧
reader.ReadByte();
reader.ReadBytes(reader.ReadByte()); // QQ红包
reader.ReadBytes(5);
reader.ReadBytes(reader.ReadByte()); // [QQ红包]恭喜发财
reader.ReadBytes(22);
var redId = Encoding.UTF8.GetString(reader.ReadBytes(32)); //redid
reader.ReadBytes(12);
reader.ReadBytes(reader.BeReadUInt16());
reader.ReadBytes(0x10);
var key1 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key1
reader.BeReadUInt16();
var key2 = Encoding.UTF8.GetString(reader.ReadBytes(reader.ReadByte())); //Key2
result.Snippets.Add(new TextSnippet("", MessageType.RedBag, ("RedId", redId),
("Key1", key1), ("Key2", key2)));
break;
}
}
reader.ReadBytes((int) (pos + dataLength - reader.BaseStream.Position));
messageType = reader.ReadByte();
dataLength = reader.BeReadUInt16();
pos = reader.BaseStream.Position;
}
}
catch (Exception ex)
{
}
// 移除所有空白的片段
result.Snippets.RemoveAll(s => s.Type == MessageType.Normal && string.IsNullOrEmpty(s.Content));
// 若长度大于1,那么应该只含有普通文本、At、表情、图片。
// 虽然我看着别人好像视频也能通过转发什么的弄进来,但是反正我们现在不支持接收音视频,所以不管了
return result.Snippets.Count > 1 && result.Snippets.Any(s =>
s.Type != MessageType.Normal && s.Type != MessageType.At &&
s.Type != MessageType.Emoji && s.Type != MessageType.Picture)
? throw new NotSupportedException("富文本中包含多个非聊天代码")
: result;
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual bool CreateUpdateCommand(IDbCommand cmd, object enreplacedy, object oldEnreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
{
bool isUpdateNeeded = false;
TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());
if (!tableInfo.NoUpdatedBy && tableInfo.IsUpdatedByEmpty(enreplacedy))
throw new MissingFieldException("Updated By is required");
List<string> columns = new List<string>();
if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
else columns.AddRange(tableInfo.DefaultUpdateColumns);//Get columns from Enreplacedy attributes loaded in TableInfo
StringBuilder cmdText = new StringBuilder();
cmdText.Append($"UPDATE {tableInfo.FullName} SET ");
//add default columns if doesn't exists
if (!doNotAppendCommonFields)
{
if (!tableInfo.NoVersionNo && !columns.Contains(Config.VERSIONNO_COLUMN.Name))
columns.Add(Config.VERSIONNO_COLUMN.Name);
if (!tableInfo.NoUpdatedBy && !columns.Contains(Config.UPDATEDBY_COLUMN.Name))
columns.Add(Config.UPDATEDBY_COLUMN.Name);
if (!tableInfo.NoUpdatedOn && !columns.Contains(Config.UPDATEDON_COLUMN.Name))
columns.Add(Config.UPDATEDON_COLUMN.Name);
}
//remove primarykey, createdon and createdby columns if exists
columns.RemoveAll(c => tableInfo.PkColumnList.Select(p=>p.Name).Contains(c));
columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name ||
c == Config.CREATEDBY_COLUMN.Name);
for (int i = 0; i < columns.Count(); i++)
{
if (columns[i].Equals(Config.VERSIONNO_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = {columns[i]}+1");
cmdText.Append(",");
}
else if (columns[i].Equals(Config.UPDATEDBY_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetUpdatedBy(enreplacedy));
}
else if (columns[i].Equals(Config.UPDATEDON_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (updatedOn is string)
{
cmdText.Append($"{columns[i]} = {CURRENTDATETIMESQL}");
}
else
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDON_COLUMN.ColumnDbType, updatedOn);
}
cmdText.Append(",");
}
else
{
bool includeInUpdate = true;
tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute
DbType dbType = DbType.Object;
object columnValue = null;
if (columnInfo != null && columnInfo.GetMethod != null)
{
dbType = columnInfo.ColumnDbType;
columnValue = columnInfo.GetAction(enreplacedy);
includeInUpdate = oldEnreplacedy == null; //include in update when oldEnreplacedy not available
//compare with old object to check whether update is needed or not
object oldColumnValue = null;
if (oldEnreplacedy != null)
{
oldColumnValue = columnInfo.GetAction(oldEnreplacedy);
if (oldColumnValue != null && columnValue != null)
{
if (!oldColumnValue.Equals(columnValue)) //add to history only if property is modified
{
includeInUpdate = true;
}
}
else if (oldColumnValue == null && columnValue != null)
{
includeInUpdate = true;
}
else if (oldColumnValue != null)
{
includeInUpdate = true;
}
}
if (tableInfo.NeedsHistory && includeInUpdate) audit.AppendDetail(columns[i], columnValue, dbType, oldColumnValue);
}
if (includeInUpdate)
{
isUpdateNeeded = true;
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], dbType, columnValue);
}
}
}
cmdText.RemoveLastComma(); //Remove last comma if exists
cmdText.Append(" WHERE ");
if (tableInfo.PkColumnList.Count > 1)
{
int index = 0;
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
cmdText.Append($" {(index > 0 ? " AND " : "")} {pkCol.Name}=@{pkCol.Name}");
cmd.AddInParameter("@" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(enreplacedy, pkCol));
index++;
}
}
else
{
cmdText.Append($" {tableInfo.PkColumn.Name}=@{tableInfo.PkColumn.Name}");
cmd.AddInParameter("@" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, tableInfo.GetKeyId(enreplacedy));
}
if (Config.DbConcurrencyCheck && !tableInfo.NoVersionNo)
{
cmdText.Append($" AND {Config.VERSIONNO_COLUMN.Name}=@{Config.VERSIONNO_COLUMN.Name}");
cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, tableInfo.GetVersionNo(enreplacedy));
}
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText.ToString();
return isUpdateNeeded;
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual void CreateAddCommand(IDbCommand cmd, object enreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
{
TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());
if (tableInfo.NeedsHistory && tableInfo.IsCreatedByEmpty(enreplacedy))
throw new MissingFieldException("CreatedBy is required when Audit Trail is enabled");
List<string> columns = new List<string>();
if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
else columns.AddRange(tableInfo.DefaultInsertColumns);//Get columns from Enreplacedy attributes loaded in TableInfo
bool isPrimaryKeyEmpty = false;
foreach(ColumnAttribute pkCol in tableInfo.Columns.Where(p=>p.Value.IsPrimaryKey).Select(p=>p.Value))
{
if (pkCol.PrimaryKeyInfo.IsIdenreplacedy && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
{
isPrimaryKeyEmpty = true;
//if idenreplacedy remove keyfield if added in field list
columns.Remove(pkCol.Name);
}
else if (pkCol.Property.PropertyType == typeof(Guid) && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
{
isPrimaryKeyEmpty = true;
//if not idenreplacedy and key not generated, generate before save
tableInfo.SetKeyId(enreplacedy, pkCol, Guid.NewGuid());
}
}
#region append common columns
if (!doNotAppendCommonFields)
{
if (!tableInfo.NoIsActive)
{
if (!columns.Contains(Config.ISACTIVE_COLUMN.Name))
columns.Add(Config.ISACTIVE_COLUMN.Name);
bool isActive = tableInfo.GetIsActive(enreplacedy) ?? true;
//when IsActive is not set then true for insert
cmd.AddInParameter("@" + Config.ISACTIVE_COLUMN.Name, Config.ISACTIVE_COLUMN.ColumnDbType, isActive);
if (tableInfo.NeedsHistory)
audit.AppendDetail(Config.ISACTIVE_COLUMN.Name, isActive, DbType.Boolean, null);
tableInfo.SetIsActive(enreplacedy, isActive); //Set IsActive value
}
if (!tableInfo.NoVersionNo)
{
int versionNo = tableInfo.GetVersionNo(enreplacedy) ?? 1; //set defualt versionno 1 for Insert
if (versionNo == 0) versionNo = 1; //set defualt versionno 1 for Insert even if its zero or null
if (!columns.Contains(Config.VERSIONNO_COLUMN.Name))
columns.Add(Config.VERSIONNO_COLUMN.Name);
cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, versionNo);
tableInfo.SetVersionNo(enreplacedy, versionNo); //Set VersionNo value
}
if (!tableInfo.NoCreatedBy)
{
if (!columns.Contains(Config.CREATEDBY_COLUMN.Name))
columns.Add(Config.CREATEDBY_COLUMN.Name);
cmd.AddInParameter("@" + Config.CREATEDBY_COLUMN.Name, Config.CREATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
}
if (!tableInfo.NoCreatedOn & !columns.Contains(Config.CREATEDON_COLUMN.Name))
{
columns.Add(Config.CREATEDON_COLUMN.Name);
}
if (!tableInfo.NoUpdatedBy)
{
if (!columns.Contains(Config.UPDATEDBY_COLUMN.Name))
columns.Add(Config.UPDATEDBY_COLUMN.Name);
cmd.AddInParameter("@" + Config.UPDATEDBY_COLUMN.Name, Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
}
if (!tableInfo.NoUpdatedOn & !columns.Contains(Config.UPDATEDON_COLUMN.Name))
{
columns.Add(Config.UPDATEDON_COLUMN.Name);
}
}
#endregion
//append @ before each fields to add as parameter
List<string> parameters = columns.Select(c => "@" + c).ToList();
int pIndex = parameters.FindIndex(c => c == "@" + Config.CREATEDON_COLUMN.Name);
if (pIndex >= 0)
{
var createdOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (createdOn is string)
{
parameters[pIndex] = (string)createdOn;
}
else
{
cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, createdOn);
}
//parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
}
pIndex = parameters.FindIndex(c => c == "@" + Config.UPDATEDON_COLUMN.Name);
if (pIndex >= 0)
{
var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (updatedOn is string)
{
parameters[pIndex] = (string)updatedOn;
}
else
{
cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, updatedOn);
}
//parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
}
StringBuilder cmdText = new StringBuilder();
cmdText.Append($"INSERT INTO {tableInfo.FullName} ({string.Join(",", columns)}) VALUES({string.Join(",", parameters)});");
if (tableInfo.IsKeyIdenreplacedy() && isPrimaryKeyEmpty)
{
//add query to get inserted id
cmdText.Append(LASTINSERTEDROWIDSQL);
}
//remove common columns and parameters already added above
columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || c == Config.CREATEDBY_COLUMN.Name
|| c == Config.UPDATEDON_COLUMN.Name || c == Config.UPDATEDBY_COLUMN.Name
|| c == Config.VERSIONNO_COLUMN.Name || c == Config.ISACTIVE_COLUMN.Name);
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText.ToString();
for (int i = 0; i < columns.Count(); i++)
{
tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute
DbType dbType = DbType.Object;
object columnValue = null;
if (columnInfo != null && columnInfo.GetMethod != null)
{
dbType = columnInfo.ColumnDbType;
columnValue = columnInfo.GetAction(enreplacedy);
if (tableInfo.NeedsHistory) audit.AppendDetail(columns[i], columnValue, dbType, null);
}
cmd.AddInParameter("@" + columns[i], dbType, columnValue);
}
}
19
Source : Database.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
internal virtual bool CreateUpdateCommand(IDbCommand cmd, object enreplacedy, object oldEnreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
{
bool isUpdateNeeded = false;
TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());
if (!tableInfo.NoUpdatedBy && tableInfo.IsUpdatedByEmpty(enreplacedy))
throw new MissingFieldException("Updated By is required");
List<string> columns = new List<string>();
if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
else columns.AddRange(tableInfo.DefaultUpdateColumns);//Get columns from Enreplacedy attributes loaded in TableInfo
StringBuilder cmdText = new StringBuilder();
cmdText.Append($"UPDATE {tableInfo.FullName} SET ");
//add default columns if doesn't exists
if (!doNotAppendCommonFields)
{
if (!tableInfo.NoVersionNo && !columns.Contains(Config.VERSIONNO_COLUMN.Name))
columns.Add(Config.VERSIONNO_COLUMN.Name);
if (!tableInfo.NoUpdatedBy && !columns.Contains(Config.UPDATEDBY_COLUMN.Name))
columns.Add(Config.UPDATEDBY_COLUMN.Name);
if (!tableInfo.NoUpdatedOn && !columns.Contains(Config.UPDATEDON_COLUMN.Name))
columns.Add(Config.UPDATEDON_COLUMN.Name);
}
//remove primarykey, createdon and createdby columns if exists
columns.RemoveAll(c => tableInfo.PkColumnList.Select(p=>p.Name).Contains(c));
columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name ||
c == Config.CREATEDBY_COLUMN.Name);
for (int i = 0; i < columns.Count(); i++)
{
if (columns[i].Equals(Config.VERSIONNO_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = {columns[i]}+1");
cmdText.Append(",");
}
else if (columns[i].Equals(Config.UPDATEDBY_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetUpdatedBy(enreplacedy));
}
else if (columns[i].Equals(Config.UPDATEDON_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
{
var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
if (updatedOn is string)
{
cmdText.Append($"{columns[i]} = {CURRENTDATETIMESQL}");
}
else
{
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmd.AddInParameter("@" + columns[i], Config.UPDATEDON_COLUMN.ColumnDbType, updatedOn);
}
cmdText.Append(",");
}
else
{
bool includeInUpdate = true;
tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute
DbType dbType = DbType.Object;
object columnValue = null;
if (columnInfo != null && columnInfo.GetMethod != null)
{
dbType = columnInfo.ColumnDbType;
columnValue = columnInfo.GetAction(enreplacedy);
includeInUpdate = oldEnreplacedy == null; //include in update when oldEnreplacedy not available
//compare with old object to check whether update is needed or not
object oldColumnValue = null;
if (oldEnreplacedy != null)
{
oldColumnValue = columnInfo.GetAction(oldEnreplacedy);
if (oldColumnValue != null && columnValue != null)
{
if (!oldColumnValue.Equals(columnValue)) //add to history only if property is modified
{
includeInUpdate = true;
}
}
else if (oldColumnValue == null && columnValue != null)
{
includeInUpdate = true;
}
else if (oldColumnValue != null)
{
includeInUpdate = true;
}
}
if (tableInfo.NeedsHistory && includeInUpdate) audit.AppendDetail(columns[i], columnValue, dbType, oldColumnValue);
}
if (includeInUpdate)
{
isUpdateNeeded = true;
cmdText.Append($"{columns[i]} = @{columns[i]}");
cmdText.Append(",");
cmd.AddInParameter("@" + columns[i], dbType, columnValue);
}
}
}
cmdText.RemoveLastComma(); //Remove last comma if exists
cmdText.Append(" WHERE ");
if (tableInfo.PkColumnList.Count > 1)
{
int index = 0;
foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
{
cmdText.Append($" {(index > 0 ? " AND " : "")} {pkCol.Name}=@{pkCol.Name}");
cmd.AddInParameter("@" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(enreplacedy, pkCol));
index++;
}
}
else
{
cmdText.Append($" {tableInfo.PkColumn.Name}=@{tableInfo.PkColumn.Name}");
cmd.AddInParameter("@" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, tableInfo.GetKeyId(enreplacedy));
}
if (Config.DbConcurrencyCheck && !tableInfo.NoVersionNo)
{
cmdText.Append($" AND {Config.VERSIONNO_COLUMN.Name}=@{Config.VERSIONNO_COLUMN.Name}");
cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, tableInfo.GetVersionNo(enreplacedy));
}
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText.ToString();
return isUpdateNeeded;
}
19
Source : ClientData.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public bool ApplyChats(ModelUpdateChat updateDate)
{
//переводим сообщения с сервера
for (int ic = 0; ic < updateDate.Chats.Count; ic++)
{
for (int ip = 0; ip < updateDate.Chats[ic].Posts.Count; ip++)
{
updateDate.Chats[ic].Posts[ip].Message = ChatController.ServerCharTranslate(updateDate.Chats[ic].Posts[ip].Message);
}
}
int newPost = 0;
var newStr = "";
if (Chats != null)
{
lock (Chats)
{
foreach (var chat in updateDate.Chats)
{
var cur = Chats.FirstOrDefault(c => c.Id == chat.Id);
if (cur != null)
{
cur.Posts.AddRange(chat.Posts);
var newPosts = chat.Posts.Where(p => p.OwnerLogin != SessionClientController.My.Login).ToList();
newPost += newPosts.Count;
if (newStr == "" && newPosts.Count > 0) newStr = chat.Name + ": " + newPosts[0].Message;
chat.Posts = cur.Posts;
cur.Name = chat.Name;
// это только для ускорения, сервер не передает список пати логинов, если ничего не изменилось
// т.к. передать 3000+ логинов по 8 байт, это уже несколько пакетов
if (chat.PartyLogin != null && chat.PartyLogin.Count > 0)
{
cur.PartyLogin = chat.PartyLogin;
}
}
else
{
Chats.Add(chat);
}
}
var ids = updateDate.Chats.Select(x => x.Id);
Chats.RemoveAll(x => !ids.Contains(x.Id));
}
}
else
{
Chats = updateDate.Chats;
}
if (UIInteraction && newPost > 0)
{
GameMessage(newStr);
}
ChatNotReadPost += newPost;
return newPost > 0;
}
19
Source : UpdateWorldController.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void ApplyNonPlayerWorldObject(ModelPlayToClient fromServ)
{
try
{
if (fromServ.WObjectOnlineToDelete != null && fromServ.WObjectOnlineToDelete.Count > 0)
{
var objectToDelete = Find.WorldObjects.AllWorldObjects.Where(wo => wo is Settlement)
.Where(wo => wo.HasName && !wo.Faction.IsPlayer)
.Where(o => fromServ.WObjectOnlineToDelete.Any(fs => ValidateOnlineWorldObject(fs, o))).ToList();
objectToDelete.ForEach(o => {
Find.WorldObjects.SettlementAt(o.Tile).Destroy();
Find.World.WorldUpdate();
});
if (LastWorldObjectOnline != null && LastWorldObjectOnline.Count > 0)
{
LastWorldObjectOnline.RemoveAll(WOnline => objectToDelete.Any(o => ValidateOnlineWorldObject(WOnline, o)));
}
}
if (fromServ.WObjectOnlineToAdd != null && fromServ.WObjectOnlineToAdd.Count > 0)
{
for (var i = 0; i < fromServ.WObjectOnlineToAdd.Count; i++)
{
if (!Find.WorldObjects.AnySettlementAt(fromServ.WObjectOnlineToAdd[i].Tile))
{
Faction faction = Find.FactionManager.AllFactionsListForReading.FirstOrDefault(fm =>
fm.def.LabelCap == fromServ.WObjectOnlineToAdd[i].FactionGroup &&
fm.loadID == fromServ.WObjectOnlineToAdd[i].loadID);
if (faction != null)
{
var npcBase = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
npcBase.SetFaction(faction);
npcBase.Tile = fromServ.WObjectOnlineToAdd[i].Tile;
npcBase.Name = fromServ.WObjectOnlineToAdd[i].Name;
Find.WorldObjects.Add(npcBase);
//LastWorldObjectOnline.Add(fromServ.OnlineWObjectToAdd[i]);
}
else
{
Log.Warning("Faction is missing or not found : " + fromServ.WObjectOnlineToAdd[i].FactionGroup);
Loger.Log("Skipping ToAdd Settlement : " + fromServ.WObjectOnlineToAdd[i].Name);
}
}
else
{
Loger.Log("Can't Add Settlement. Tile is already occupied " + Find.WorldObjects.SettlementAt(fromServ.WObjectOnlineToAdd[i].Tile));
}
}
}
}
catch (Exception e)
{
Log.Error("Exception LoadFromServer ApplyNonPlayerWorldObject >> " + e);
}
}
19
Source : UpdateWorldController.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void ApplyFactionsToWorld(ModelPlayToClient fromServ)
{
try
{
// ! WIP Factions
if (fromServ.FactionOnlineToDelete != null && fromServ.FactionOnlineToDelete.Count > 0)
{
var factionToDelete = Find.FactionManager.AllFactionsListForReading.Where(f => !f.IsPlayer)
.Where(obj => fromServ.FactionOnlineToDelete.Any(fs => ValidateFaction(fs, obj))).ToList();
OCFactionManager.UpdateFactionIDS(fromServ.FactionOnlineList);
for (var i = 0; i < factionToDelete.Count; i++)
{
OCFactionManager.DeleteFaction(factionToDelete[i]);
}
if (LastFactionOnline != null && LastFactionOnline.Count > 0)
{
LastFactionOnline.RemoveAll(FOnline => factionToDelete.Any(obj => ValidateFaction(FOnline, obj)));
}
}
if (fromServ.FactionOnlineToAdd != null && fromServ.FactionOnlineToAdd.Count > 0)
{
for (var i = 0; i < fromServ.FactionOnlineToAdd.Count; i++)
{
try
{
var existingFaction = Find.FactionManager.AllFactionsListForReading.Where(f => ValidateFaction(fromServ.FactionOnlineToAdd[i], f)).ToList();
if (existingFaction.Count == 0)
{
OCFactionManager.UpdateFactionIDS(fromServ.FactionOnlineList);
OCFactionManager.AddNewFaction(fromServ.FactionOnlineToAdd[i]);
}
else
{
Loger.Log("Failed to add faction. Faction already exists. > " + fromServ.FactionOnlineToAdd[i].LabelCap);
}
}
catch
{
Loger.Log("Error faction to add LabelCap >> " + fromServ.FactionOnlineToAdd[i].LabelCap);
Loger.Log("Error faction to add DefName >> " + fromServ.FactionOnlineToAdd[i].DefName);
}
}
}
}
catch (Exception e)
{
Log.Error("OnlineCity: Error Apply new faction to world >> " + e);
}
}
19
Source : SimFutureQueue.cs
with MIT License
from abdullin
with MIT License
from abdullin
public bool TryGetFuture(out FutureItem item) {
while (true) {
if (_future.Count == 0) {
// no more future
item = default(FutureItem);
return false;
}
var list = _future.Values[0];
var time = _future.Keys[0];
if (list.Count == 0) {
// we are about to jump to the next time point
// check if there are any future tasks
if (!_jumps.Any(p => p.Key.FutureIsNow)) {
// no, move forward
_future.RemoveAt(0);
continue;
}
var jumps = _jumps
.Where(p => p.Key.FutureIsNow)
.ToList();
// order by ID to have some order
foreach (var (jump, (sched, pos)) in jumps.OrderBy(p => p.Key.Id)) {
// move jumps to now
list.Add((sched, jump));
// remove from the jump list
_jumps.Remove(jump);
// remove from the future unless it is present
if (pos != time && pos != -1) {
if (_future.TryGetValue(pos, out var removal)) {
removal.RemoveAll(tuple => tuple.Item2 == jump);
// future could be missing due to erasure
}
}
}
}
var (scheduler, subject) = list.First();
list.RemoveAt(0);
item = new FutureItem(time, scheduler, subject);
if (subject is IFutureJump fj) {
_jumps.Remove(fj);
}
return true;
}
}
19
Source : SimFutureQueue.cs
with MIT License
from abdullin
with MIT License
from abdullin
public void Erase(SimScheduler id) {
foreach (var list in _future.Values) {
foreach (var item in list.Where(t => t.Item1 == id)) {
if (item.Item2 is SimDelayTask f) {
_jumps.Remove(f);
}
}
list.RemoveAll(t => t.Item1 == id);
}
}
19
Source : MixedRealitySearchUtility.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static async void StartProfileSearch(UnityEngine.Object profile, SearchConfig config, Action<bool, UnityEngine.Object, IReadOnlyCollection<ProfileSearchResult>> onSearchComplete)
{
if (activeTask != null && !activeTask.IsCompleted)
{
throw new Exception("Can't start a new search until the old one has completed.");
}
List<ProfileSearchResult> searchResults = new List<ProfileSearchResult>();
// Validate search configuration
if (string.IsNullOrEmpty(config.SearchFieldString))
{ // If the config is empty, bail early
onSearchComplete?.Invoke(true, profile, searchResults);
return;
}
// Generate keywords if we haven't yet
if (config.Keywords == null)
{
config.Keywords = new HashSet<string>(config.SearchFieldString.Split(new string[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries));
config.Keywords.RemoveWhere(s => s.Length < minSearchStringLength);
}
if (config.Keywords.Count == 0)
{ // If there are no useful keywords, bail early
onSearchComplete?.Invoke(true, profile, searchResults);
return;
}
// Launch the search task
bool cancelled = false;
try
{
activeTask = SearchProfileField(profile, config, searchResults);
await activeTask;
}
catch (Exception e)
{
// Profile was probably deleted in the middle of searching.
Debug.LogException(e);
cancelled = true;
}
finally
{
searchResults.Sort(delegate (ProfileSearchResult r1, ProfileSearchResult r2)
{
if (r1.ProfileMatchStrength != r2.ProfileMatchStrength)
{
return r2.ProfileMatchStrength.CompareTo(r1.ProfileMatchStrength);
}
else
{
return r2.Profile.name.CompareTo(r1.Profile.name);
}
});
searchResults.RemoveAll(r => r.Fields.Count <= 0);
onSearchComplete?.Invoke(cancelled, profile, searchResults);
}
}
19
Source : ViaCepWebservice.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
public override ACBrEndereco[] BuscarPorLogradouro(ConsultaUF uf, string municipio, string logradouro, string tipoLogradouro = "", string bairro = "")
{
var url = $"{VIACEP_URL}/{uf}/{municipio.ToLower().ToreplacedleCase()}/{logradouro.ToLower().ToreplacedleCase()}/xml";
var ret = ConsultaCEP(url);
if (!tipoLogradouro.IsEmpty())
{
ret.RemoveAll(x => !string.Equals(x.TipoLogradouro.RemoveAccent(), tipoLogradouro.RemoveAccent(), StringComparison.CurrentCultureIgnoreCase));
}
if (!bairro.IsEmpty())
{
ret.RemoveAll(x => !string.Equals(x.Bairro.RemoveAccent(), bairro.RemoveAccent(), StringComparison.CurrentCultureIgnoreCase));
}
return ret.ToArray();
}
19
Source : ACBrIBGE.cs
with MIT License
from ACBrNet
with MIT License
from ACBrNet
public int Buscarreplacedome(string municipio, ConsultaUF? uf = null, bool exata = false, bool caseSentive = false)
{
Guard.Against<ArgumentException>(municipio.IsEmpty(), "Munic�pio deve ser informado");
var request = GetClient($"{CIBGE_URL}?nome={HttpUtility.UrlEncode(municipio.Trim(), ACBrEncoding.ISO88591)}");
var responseStream = request.GetResponse().GetResponseStream();
Guard.Against<ACBrException>(responseStream.IsNull(), "Erro ao acessar o site.");
string retorno;
using (var stHtml = new StreamReader(responseStream, ACBrEncoding.ISO88591))
retorno = stHtml.ReadToEnd();
ProcessarResposta(retorno);
if (uf.HasValue)
{
Resultados.RemoveAll(x => x.UF != uf);
}
if (exata)
{
if (caseSentive)
Resultados.RemoveAll(x => x.Nome.RemoveAccent() != municipio.RemoveAccent());
else
Resultados.RemoveAll(x => x.Nome.ToUpper().RemoveAccent() != municipio.ToUpper().RemoveAccent());
}
var result = Resultados.Count;
OnBuscaEfetuada.Raise(this, EventArgs.Empty);
return result;
}
19
Source : AcceleriderUserExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static bool RemoveNetDiskUser(this IAcceleriderUser @this, INetDiskUser value)
{
Guards.ThrowIfNull(@this);
var result = _extendedMembers.NetDiskUsers.RemoveAll(item => item.Id == value.Id) > 0;
if (result)
{
@this.SaveToLocalDisk();
RaisePropertyChanged();
}
return result;
}
19
Source : NetworkSession.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void SendBundle(NetworkBundle bundle, GameMessageGroup group)
{
packetLog.DebugFormat("[{0}] Sending Bundle", session.LoggingIdentifier);
bool writeOptionalHeaders = true;
List<MessageFragment> fragments = new List<MessageFragment>();
// Pull all messages out and create MessageFragment objects
while (bundle.HasMoreMessages)
{
var message = bundle.Dequeue();
var fragment = new MessageFragment(message, ConnectionData.FragmentSequence++);
fragments.Add(fragment);
}
packetLog.DebugFormat("[{0}] Bundle Fragment Count: {1}", session.LoggingIdentifier, fragments.Count);
// Loop through while we have fragements
while (fragments.Count > 0 || writeOptionalHeaders)
{
ServerPacket packet = new ServerPacket();
PacketHeader packetHeader = packet.Header;
if (fragments.Count > 0)
packetHeader.Flags |= PacketHeaderFlags.BlobFragments;
if (bundle.EncryptedChecksum)
packetHeader.Flags |= PacketHeaderFlags.EncryptedChecksum;
int availableSpace = ServerPacket.MaxPacketSize;
// Pull first message and see if it is a large one
var firstMessage = fragments.FirstOrDefault();
if (firstMessage != null)
{
// If a large message send only this one, filling the whole packet
if (firstMessage.DataRemaining >= availableSpace)
{
packetLog.DebugFormat("[{0}] Sending large fragment", session.LoggingIdentifier);
ServerPacketFragment spf = firstMessage.GetNextFragment();
packet.Fragments.Add(spf);
availableSpace -= spf.Length;
if (firstMessage.DataRemaining <= 0)
fragments.Remove(firstMessage);
}
// Otherwise we'll write any optional headers and process any small messages that will fit
else
{
if (writeOptionalHeaders)
{
writeOptionalHeaders = false;
WriteOptionalHeaders(bundle, packet);
if (packet.Data != null)
availableSpace -= (int)packet.Data.Length;
}
// Create a list to remove completed messages after iterator
List<MessageFragment> removeList = new List<MessageFragment>();
foreach (MessageFragment fragment in fragments)
{
bool fragmentSkipped = false;
// Is this a large fragment and does it have a tail that needs sending?
if (!fragment.TailSent && availableSpace >= fragment.TailSize)
{
packetLog.DebugFormat("[{0}] Sending tail fragment", session.LoggingIdentifier);
ServerPacketFragment spf = fragment.GetTailFragment();
packet.Fragments.Add(spf);
availableSpace -= spf.Length;
}
// Otherwise will this message fit in the remaining space?
else if (availableSpace >= fragment.NextSize)
{
packetLog.DebugFormat("[{0}] Sending small message", session.LoggingIdentifier);
ServerPacketFragment spf = fragment.GetNextFragment();
packet.Fragments.Add(spf);
availableSpace -= spf.Length;
}
else
fragmentSkipped = true;
// If message is out of data, set to remove it
if (fragment.DataRemaining <= 0)
removeList.Add(fragment);
// UIQueue messages must go out in order. Otherwise, you might see an NPC's tells in an order that doesn't match their defined emotes.
if (fragmentSkipped && group == GameMessageGroup.UIQueue)
break;
}
// Remove all completed messages
fragments.RemoveAll(x => removeList.Contains(x));
}
}
// If no messages, write optional headers
else
{
packetLog.DebugFormat("[{0}] No messages, just sending optional headers", session.LoggingIdentifier);
if (writeOptionalHeaders)
{
writeOptionalHeaders = false;
WriteOptionalHeaders(bundle, packet);
if (packet.Data != null)
availableSpace -= (int)packet.Data.Length;
}
}
EnqueueSend(packet);
}
}
19
Source : SelectionHistory.cs
with MIT License
from acoppes
with MIT License
from acoppes
public void RemoveEntries(Entry.State state)
{
var deletedCount = _history.Count(e => e.GetReferenceState() == state);
var currentSelectionDestroyed = currentSelection == null || currentSelection.GetReferenceState() == state;
_history.RemoveAll(e => e.GetReferenceState() == state);
currentSelectionIndex -= deletedCount;
if (currentSelectionIndex < 0)
currentSelectionIndex = 0;
if (currentSelectionDestroyed)
currentSelectionIndex = -1;
}
19
Source : Favorites.cs
with MIT License
from acoppes
with MIT License
from acoppes
public void ClearUnreferenced()
{
favoritesList.RemoveAll(f => f.reference == null);
}
19
Source : Favorites.cs
with MIT License
from acoppes
with MIT License
from acoppes
public void RemoveFavorite(Object reference)
{
favoritesList.RemoveAll(f => f.reference == reference);
OnFavoritesUpdated?.Invoke(this);
}
19
Source : Reference.cs
with MIT License
from adamant
with MIT License
from adamant
private void PruneBorrowers()
{
// First prune recursively
borrowers.ForEach(r => r.PruneBorrowers());
var newBorrowers = new List<Reference>();
// Remove released borrowers
borrowers.RemoveAll(r =>
{
var released = r.Phase == Phase.Released;
if (released)
// But grab their pruned list of borrowers
newBorrowers.AddRange(r.Borrowers);
return released;
});
// And add it to ours instead
borrowers.AddRange(newBorrowers);
}
19
Source : SyntaxWalkerBase.cs
with MIT License
from adrianoc
with MIT License
from adrianoc
protected static string ModifiersToCecil(IReadOnlyList<SyntaxToken> modifiers, string targetEnum, string defaultAccessibility, Func<SyntaxToken, IEnumerable<string>> mapAttribute = null)
{
var finalModifierList = new List<SyntaxToken>(modifiers);
var m = string.Empty;
IsInternalProtected(finalModifierList, ref m);
IsPrivateProtected(finalModifierList, ref m);
mapAttribute ??= MapAttributeForMembers;
var modifierStr = finalModifierList.Where(ExcludeHasNoCILRepresentation).SelectMany(mapAttribute).Aggregate("", (acc, curr) => (acc.Length > 0 ? $"{acc} | " : "") + $"{targetEnum}." + curr) + m;
if(!modifiers.Any(m => m.IsKind(SyntaxKind.PrivateKeyword) || m.IsKind(SyntaxKind.InternalKeyword) || m.IsKind(SyntaxKind.PrivateKeyword) || m.IsKind(SyntaxKind.PublicKeyword) || m.IsKind(SyntaxKind.ProtectedKeyword)))
return modifierStr.AppendModifier($"{targetEnum}.{defaultAccessibility}");
return modifierStr;
void IsInternalProtected(List<SyntaxToken> tokens, ref string s)
{
if (HandleModifiers(tokens, SyntaxFactory.Token(SyntaxKind.InternalKeyword), SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)))
s = $"{targetEnum}.FamORreplacedem";
}
void IsPrivateProtected(List<SyntaxToken> tokens, ref string s)
{
if (HandleModifiers(tokens, SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)))
s = $"{targetEnum}.FamANDreplacedem";
}
bool HandleModifiers(List<SyntaxToken> tokens, SyntaxToken first, SyntaxToken second)
{
if (tokens.Any(c => c.IsKind(first.Kind())) && tokens.Any(c => c.IsKind(second.Kind())))
{
tokens.RemoveAll(c => c.IsKind(first.Kind()) || c.IsKind(second.Kind()));
return true;
}
return false;
}
IEnumerable<string> MapAttributeForMembers(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.InternalKeyword: return new[] { "replacedembly" };
case SyntaxKind.ProtectedKeyword: return new[] { "Family" };
case SyntaxKind.PrivateKeyword: return new[] { "Private" };
case SyntaxKind.PublicKeyword: return new[] { "Public" };
case SyntaxKind.StaticKeyword: return new[] { "Static" };
case SyntaxKind.AbstractKeyword: return new[] { "Abstract" };
case SyntaxKind.ConstKeyword: return new[] { "Literal", "Static" };
//case SyntaxKind.ReadOnlyKeyword: return FieldAttributes.InitOnly;
}
throw new ArgumentException($"Unsupported attribute name: {token.Kind().ToString()}");
}
}
19
Source : TreeElementUtility.cs
with MIT License
from Adsito
with MIT License
from Adsito
public static IList<T> FindCommonAncestorsWithinList<T>(IList<T> elements) where T : TreeElement
{
if (elements.Count == 1)
return new List<T>(elements);
List<T> result = new List<T>(elements);
result.RemoveAll(g => IsChildOf(g, elements));
return result;
}
19
Source : AntisThread.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private static void Loop()
{
AntisThreadExecutable[] exec = null;
bool needRemove = false;
while (true)
{
lock (executables)
{
exec = executables.ToArray();
}
if (exec.Length > 0)
{
int iterator = 0;
while (iterator < exec.Length)
{
AntisThreadExecutable executable = exec[iterator++];
if (executable == null)
{
needRemove = true;
continue;
}
executable.Check();
}
}
if (needRemove)
{
lock (executables)
{
executables.RemoveAll(delegate (AntisThreadExecutable execute) { return execute == null; });
}
needRemove = false;
}
Thread.Sleep(sleepTime);
if (nextSleepTime > 0)
{
sleepTime = nextSleepTime;
nextSleepTime = -1;
}
}
}
19
Source : BuildingManager.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
private static bool DetermineIfEnoughMaterials()
{
List<RecipeComponent> recipe = GetConstructRecipe();
if (recipe == null) {
return false;
}
// check player inventory
foreach (Item item in Program.Player.Inventory) {
RecipeComponent itemC = item.ToComponent();
if (recipe.Contains(itemC))
recipe.Remove(itemC);
}
int currentFloor = Program.Player.CurrentFloor;
Point worldIndex = Program.Player.WorldIndex;
Block[] blocks = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Blocks : Program.WorldMap[worldIndex.X, worldIndex.Y].Blocks;
int width = Program.WorldMap.TileWidth, height = Program.WorldMap.TileHeight;
// check map
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
if (blocks[i * width + j] is Item item) {
RecipeComponent itemC = item.ToComponent();
if (recipe.Contains( itemC ))
recipe.Remove( itemC );
} else if (blocks[i * width + j] is Chest chest)
foreach (Item cItem in chest.Inventory) {
RecipeComponent itemC = cItem.ToComponent();
if (recipe.Contains( itemC ))
recipe.Remove( itemC );
}
}
// check for other methods of resource aquisition
if (recipe.Count > 0) {
if (recipe.Contains(RecipeComponent.Log)) // find a tree if the recipe calls for a log
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
if (blocks[i * width + j] is Tree)
recipe.RemoveAll(rc => rc == RecipeComponent.Log);
if (recipe.Contains(RecipeComponent.Plank)) // find a tree or a log if the recipe calls for a plank
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
if (blocks[i * width + j] is Tree || blocks[i * width + j] is Log)
recipe.RemoveAll(rc => rc == RecipeComponent.Plank);
}
if (recipe.Count == 0)
return true;
return false;
}
19
Source : SetInfectedPatch.cs
with Apache License 2.0
from Aeolic
with Apache License 2.0
from Aeolic
public static void Postfix(Il2CppReferenceArray<GameData.PlayerInfo> JPGEIBIBJPJ)
{
List<PlayerControl> crewmates = PlayerControl.AllPlayerControls.ToArray().ToList();
crewmates.RemoveAll(x => x.Data.IsImpostor);
if (CultistPlugin.UseCultist.GetValue())
{
ClearCultistLists();
DidCultistsWin = false;
CLog.Info("Cultist is on for this game.");
int cultistRandomId = new System.Random().Next(0, crewmates.Count);
InitialCultist = crewmates[cultistRandomId];
crewmates.RemoveAt(cultistRandomId);
byte CultistId = InitialCultist.PlayerId;
CLog.Info("Randomly chose cultist on host side: " + InitialCultist.name);
MessageWriter writer = AmongUsClient.Instance.StartRpcImmediately(PlayerControl.LocalPlayer.NetId,
(byte) CustomRPC.SetCultist, Hazel.SendOption.None, -1);
writer.Write(CultistId);
AmongUsClient.Instance.FinishRpcImmediately(writer);
AddCultistToLists(CultistId);
SetCultistSettings();
if (PlayerControl.LocalPlayer.PlayerId == cultistRandomId)
{
ImportantTextTask cultistLeaderTask =
new GameObject("CultistLeaderTask").AddComponent<ImportantTextTask>();
cultistLeaderTask.transform.SetParent(PlayerControl.LocalPlayer.transform, false);
cultistLeaderTask.Text =
"You are the cult leader.\nConvert crewmates to join your cult.\nConversions left: " +
ConversionsLeft + "/" + MaxCultistConversions;
PlayerControl.LocalPlayer.myTasks.Insert(0, cultistLeaderTask);
}
}
}
19
Source : Objects.cs
with MIT License
from agens-no
with MIT License
from agens-no
public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); }
19
Source : Objects.cs
with MIT License
from agens-no
with MIT License
from agens-no
public void RemoveValue(string value)
{
val.RemoveAll(v => v == value);
}
19
Source : MainWindow.xaml.cs
with MIT License
from AgileoAutomation
with MIT License
from AgileoAutomation
private void replacedysis_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "SpreadSheets (*.xlsx) | *.xlsx";
dialog.Multiselect = false;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
SpreadsheetDoreplacedent spreadsheetDoreplacedent = SpreadsheetDoreplacedent.Open(dialog.FileName, false);
workbookPart = spreadsheetDoreplacedent.WorkbookPart;
}
catch
{
System.Windows.MessageBox.Show("The specification file is open in a other process");
}
SheetData sheetData = null;
try
{
Sheet sheet = workbookPart.Workbook.Sheets.ChildElements.Cast<Sheet>().First(x => x.Name == "replacedembly Specification");
int index = workbookPart.WorksheetParts.ToList().IndexOf(workbookPart.WorksheetParts.Last()) - workbookPart.Workbook.Sheets.ToList().IndexOf(sheet);
sheetData = workbookPart.WorksheetParts.ElementAt(index).Worksheet.Elements<SheetData>().First();
}
catch
{
System.Windows.MessageBox.Show("Invalid specification file :\nCouldn't find the 'replacedembly Specification' worksheet");
}
List<Row> rows = sheetData.Elements<Row>().ToList();
List<Cell> headerRow = rows.First().Elements<Cell>().ToList();
rows.RemoveAll(x => !x.Elements<Cell>().Any(y => !string.IsNullOrEmpty(TextInCell(y))));
string replacedemblyName;
if (headerRow.Any(x => TextInCell(x) == "Signed"))
{
List<SignatureSpecification> sigspecs = new List<SignatureSpecification>();
int sigIndex = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "Signed"));
foreach (Row r in rows)
{
List<Cell> row = r.Elements<Cell>().ToList();
replacedemblyName = TextInCell(row.ElementAt(0));
sigspecs.Add(new SignatureSpecification(replacedemblyName, TextInCell(row.ElementAt(sigIndex)) == "x"));
}
Signaturereplacedyzer sigreplacedyzer = new Signaturereplacedyzer();
sigreplacedyzer.replacedyze(Model, sigspecs);
}
if (headerRow.Any(x => TextInCell(x) == "Obfuscated"))
{
List<ObfuscationSpecification> obfuscationspecs = new List<ObfuscationSpecification>();
int obIndex = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "Obfuscated"));
foreach (Row r in rows)
{
List<Cell> row = r.Elements<Cell>().ToList();
replacedemblyName = TextInCell(row.ElementAt(0));
obfuscationspecs.Add(new ObfuscationSpecification(replacedemblyName, TextInCell(row.ElementAt(obIndex)) == "x"));
}
Obfuscationreplacedyzer obfuscationreplacedyzer = new Obfuscationreplacedyzer();
obfuscationreplacedyzer.replacedyze(Model, obfuscationspecs);
}
Model.SoftwareComponents.Where(x => x.Name != "System replacedemblies").ToList().ForEach(x => ModelCommonDataOrganizer.UpdateGroups(Model, x));
UpdateTreeView();
UpdateErrorNodes(GraphViewer.Graph);
replacedysis.Visibility = Visibility.Hidden;
}
}
19
Source : CustomBatchFixAllProvider.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
public async virtual Task AddDoreplacedentFixesAsync(Doreplacedent doreplacedent, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction> addFix, FixAllContext fixAllContext)
{
Debug.replacedert(!diagnostics.IsDefault, "!diagnostics.IsDefault");
var cancellationToken = fixAllContext.CancellationToken;
var fixerTasks = new Task[diagnostics.Length];
var fixes = new List<CodeAction>[diagnostics.Length];
for (var i = 0; i < diagnostics.Length; i++)
{
var currentFixIndex = i;
cancellationToken.ThrowIfCancellationRequested();
var diagnostic = diagnostics[i];
fixerTasks[i] = Task.Run(async () =>
{
var localFixes = new List<CodeAction>();
var context = new CodeFixContext(
doreplacedent,
diagnostic,
(a, d) =>
{
// TODO: Can we share code between similar lambdas that we preplaced to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
// Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
lock (localFixes)
{
localFixes.Add(a);
}
},
cancellationToken);
// TODO: Wrap call to ComputeFixesAsync() below in IExtensionManager.PerformFunctionAsync() so that
// a buggy extension that throws can't bring down the host?
var task = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? SpecializedTasks.CompletedTask;
await task.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
localFixes.RemoveAll(action => action.EquivalenceKey != fixAllContext.CodeActionEquivalenceKey);
fixes[currentFixIndex] = localFixes;
});
}
await Task.WhenAll(fixerTasks).ConfigureAwait(false);
foreach (var fix in fixes)
{
if (fix == null)
{
continue;
}
foreach (var action in fix)
{
addFix(action);
}
}
}
19
Source : ExcelParser.cs
with MIT License
from AgileoAutomation
with MIT License
from AgileoAutomation
public List<ComponentSpecification> BuildSpecifications(string filepath)
{
List<ComponentSpecification> specs = new List<ComponentSpecification>();
try
{
SpreadsheetDoreplacedent spreadsheetDoreplacedent = SpreadsheetDoreplacedent.Open(filepath, false);
workbookPart = spreadsheetDoreplacedent.WorkbookPart;
}
catch
{
MessageBox.Show("The specification file is open in a other process");
return null;
}
SheetData sheetData = null;
try
{
Sheet sheet = workbookPart.Workbook.Sheets.ChildElements.Cast<Sheet>().First(x => x.Name == "replacedembly Info");
int index = workbookPart.WorksheetParts.ToList().IndexOf(workbookPart.WorksheetParts.Last()) - workbookPart.Workbook.Sheets.ToList().IndexOf(sheet);
sheetData = workbookPart.WorksheetParts.ElementAt(index).Worksheet.Elements<SheetData>().First();
}
catch
{
MessageBox.Show("Invalid specification file :\nCouldn't find the 'replacedembly Info' worksheet");
return null;
}
rows = new List<Row>();
rows.AddRange(sheetData.Elements<Row>());
int replacedembliesColumn = -1;
try
{
List<Cell> headerRow = rows.First().Elements<Cell>().ToList();
replacedembliesColumn = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "replacedemblies"));
}
catch
{
MessageBox.Show("Invalid specification file :\nPlease respect the spreadsheet pattern, you didn't specified the replacedembly column");
}
rows.RemoveAt(0);
rows.RemoveAll(x => !x.Elements<Cell>().Any(y => !string.IsNullOrEmpty(TextInCell(y))));
while (rows.Count > 0)
{
specs.Add(BuildSpec(0, replacedembliesColumn));
}
return specs;
}
19
Source : SignInResponseGenerator.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void AddMappedClaim(Stores.RelyingParty relyParty, List<Claim> outboundClaims, IDictionary<string, string> mapping, Claim claim)
{
var outboundClaim = new Claim(mapping[claim.Type], claim.Value, claim.ValueType);
if (outboundClaim.Type == ClaimTypes.NameIdentifier)
{
outboundClaim.Properties[ClaimProperties.SamlNameIdentifierFormat] = relyParty.SamlNameIdentifierFormat;
outboundClaims.RemoveAll(c => c.Type == ClaimTypes.NameIdentifier); //remove previesly added nameid claim
}
if (outboundClaim.Type == ClaimTypes.Name)
{
outboundClaims.RemoveAll(c => c.Type == ClaimTypes.Name); //remove previesly added name claim
}
outboundClaims.Add(outboundClaim);
}
19
Source : RoleStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async virtual Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
replacedertNotNull(role, nameof(role));
replacedertNotNull(claim, nameof(claim));
var roleClaims = await GetRoleClaimsAsync(role).ConfigureAwait(false);
roleClaims.RemoveAll(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value);
var roleId = ConvertIdToString(role.Id);
await Task.WhenAll(_db.HashSetAsync(RoleClaimsRedisKey, roleId, JsonConvert.SerializeObject(roleClaims)),
_db.HashDeleteAsync(RoleClaimsKeyPrefix + claim.Type, roleId))
.ConfigureAwait(false);
}
19
Source : UserOnlyStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async override Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
replacedertNotNull(user, nameof(user));
replacedertNotNull(claims, nameof(claims));
var userId = ConvertIdToString(user.Id);
var userClaims = await GetUserClaimsAsync(user).ConfigureAwait(false);
var taskList = new List<Task>(claims.Count() + 1);
foreach (var claim in claims)
{
userClaims.RemoveAll(uc => uc.ClaimType == claim.Type && uc.ClaimValue == claim.Value);
taskList.Add(_db.HashDeleteAsync(UserClaimsKeyPrefix + claim.Type, userId));
}
taskList.Add(_db.HashSetAsync(UserClaimsRedisKey, userId, JsonConvert.SerializeObject(userClaims)));
await Task.WhenAll(taskList).ConfigureAwait(false);
}
19
Source : GameManager.cs
with MIT License
from aillieo
with MIT License
from aillieo
public void SendDamage(Vector3 position, int damage)
{
foreach (var h in heroes)
{
if (h == null || !h.alive)
{
continue;
}
if ((h.transform.position - position).sqrMagnitude < 0.1f)
{
h.OnDamage(damage);
}
}
heroes.RemoveAll(hero => hero == null|| !hero.alive);
}
19
Source : EventSyncer.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private void DeleteConversationIfExist(int conversationId)
{
if (_contacts.Any(t => t.ConversationId == conversationId))
{
_contacts.RemoveAll(t => t.ConversationId == conversationId);
}
}
19
Source : Util.cs
with MIT License
from ajayyy
with MIT License
from ajayyy
public static List<T> FindAndRemove<T>( List<T> list, System.Predicate<T> match )
{
List<T> retVal = list.FindAll( match );
list.RemoveAll( match );
return retVal;
}
19
Source : Hand.cs
with MIT License
from ajayyy
with MIT License
from ajayyy
private void CleanUpAttachedObjectStack()
{
attachedObjects.RemoveAll( l => l.attachedObject == null );
}
19
Source : EmailAttachMultipleDocuments.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected override void Execute(CodeActivityContext context)
{
this.AttachmentCount.Set(context, 0);
int max = this.MaxAttachments.Get(context);
if (max > 20 || max < 1)
{
max = 20;
}
List<Enreplacedy> notes = base.RetrieveAnnotationEnreplacedy(context, new Microsoft.Xrm.Sdk.Query.ColumnSet("filename", "mimetype", "doreplacedentbody"), max);
var potentialAttachments = notes.Select(note => new
{
FileName = note["filename"].ToString(),
MimeType = note["mimetype"],
DoreplacedentBody = note["doreplacedentbody"]
}).ToList();
if (!String.IsNullOrWhiteSpace(this.FileNameCantHave.Get(context)))
{
List<string> portions = this.FileNameCantHave.Get(context).ToLower().Split('|').ToList();
portions.ForEach(p => potentialAttachments.RemoveAll(pa => pa.FileName.ToLower().Contains(p)));
}
if (potentialAttachments.Any())
{
IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);
foreach (var a in potentialAttachments)
{
Enreplacedy attachment = new Enreplacedy("activitymimeattachment");
attachment["objectid"] = new EnreplacedyReference("email", this.Email.Get(context).Id);
attachment["objecttypecode"] = "email";
attachment["filename"] = a.FileName.ToString();
attachment["mimetype"] = a.MimeType;
attachment["body"] = a.DoreplacedentBody;
service.Create(attachment);
}
this.AttachmentCount.Set(context, potentialAttachments.Count());
}
}
19
Source : QueryGetResults.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected virtual void BuildListResults(DataTable table, CodeActivityContext context)
{
List<string> lisreplacedems = new List<string>();
for (int rowNumber = 0; rowNumber < table.Rows.Count; rowNumber++)
{
lisreplacedems.Add(table.Rows[rowNumber][0].ToString());
}
if (!this.IncludeEmptyItem.Get(context))
{
lisreplacedems.RemoveAll(i => String.IsNullOrEmpty(i));
}
this.NumberOfResults.Set(context, lisreplacedems.Count);
this.ListResults.Set(context, String.Join(this.ListSeparator.Get(context), lisreplacedems));
}
19
Source : DateConvertToCustomText.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected override void Execute(CodeActivityContext context)
{
var workflowContext = context.GetExtension<IWorkflowContext>();
var service = this.RetrieveOrganizationService(context);
List<OptionSetValue> values = new List<OptionSetValue>() {
this.Part1.Get<OptionSetValue>(context),
this.Part2.Get<OptionSetValue>(context),
this.Part3.Get<OptionSetValue>(context),
this.Part4.Get<OptionSetValue>(context),
this.Part5.Get<OptionSetValue>(context),
this.Part6.Get<OptionSetValue>(context),
this.Part7.Get<OptionSetValue>(context),
this.Part8.Get<OptionSetValue>(context),
this.Part9.Get<OptionSetValue>(context),
this.Part10.Get<OptionSetValue>(context),
this.Part11.Get<OptionSetValue>(context),
this.Part12.Get<OptionSetValue>(context),
this.Part13.Get<OptionSetValue>(context),
this.Part14.Get<OptionSetValue>(context),
this.Part15.Get<OptionSetValue>(context),
this.Part16.Get<OptionSetValue>(context),
this.Part17.Get<OptionSetValue>(context),
this.Part18.Get<OptionSetValue>(context),
this.Part19.Get<OptionSetValue>(context),
this.Part20.Get<OptionSetValue>(context) };
values.RemoveAll(osv => osv == null || osv.Value == 222540025);
TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
DateTime dateToModify = this.DateToModify.Get(context);
if (dateToModify.Kind != DateTimeKind.Utc)
{
dateToModify = dateToModify.ToUniversalTime();
}
LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;
StringBuilder sb = new StringBuilder();
foreach (OptionSetValue osv in values)
{
try
{
switch (osv.Value)
{
case 222540000:
sb.Append(timeZoneSpecificDateTime.ToString("%h"));
break;
case 222540001:
sb.Append(timeZoneSpecificDateTime.ToString("hh"));
break;
case 222540002:
sb.Append(timeZoneSpecificDateTime.ToString("%H"));
break;
case 222540003:
sb.Append(timeZoneSpecificDateTime.ToString("HH"));
break;
case 222540004:
sb.Append(timeZoneSpecificDateTime.ToString("%m"));
break;
case 222540005:
sb.Append(timeZoneSpecificDateTime.ToString("mm"));
break;
case 222540006:
sb.Append(timeZoneSpecificDateTime.ToString("%d"));
break;
case 222540007:
sb.Append(timeZoneSpecificDateTime.ToString("dd"));
break;
case 222540008:
sb.Append(timeZoneSpecificDateTime.ToString("ddd"));
break;
case 222540009:
sb.Append(timeZoneSpecificDateTime.ToString("dddd"));
break;
case 222540010:
sb.Append(timeZoneSpecificDateTime.ToString("%M"));
break;
case 222540011:
sb.Append(timeZoneSpecificDateTime.ToString("MM"));
break;
case 222540012:
sb.Append(timeZoneSpecificDateTime.ToString("MMM"));
break;
case 222540013:
sb.Append(timeZoneSpecificDateTime.ToString("MMMM"));
break;
case 222540014:
sb.Append(timeZoneSpecificDateTime.ToString("%y"));
break;
case 222540015:
sb.Append(timeZoneSpecificDateTime.ToString("yy"));
break;
case 222540016:
sb.Append(timeZoneSpecificDateTime.ToString("yyyy"));
break;
case 222540017:
sb.Append(timeZoneSpecificDateTime.ToString("%t"));
break;
case 222540018:
sb.Append(timeZoneSpecificDateTime.ToString("tt"));
break;
case 222540019:
sb.Append(" ");
break;
case 222540020:
sb.Append(",");
break;
case 222540021:
sb.Append(".");
break;
case 222540022:
sb.Append(":");
break;
case 222540023:
sb.Append("/");
break;
case 222540024:
sb.Append(@"\");
break;
case 222540026:
sb.Append("-");
break;
case 222540027:
sb.Append(timeZone.Id);
break;
case 222540028:
sb.Append(timeZone.FullName);
break;
default:
break;
}
}
catch
{
throw new Exception(osv.Value.ToString());
}
}
FormattedDate.Set(context, sb.ToString());
}
19
Source : AssetTreeView.cs
with MIT License
from akof1314
with MIT License
from akof1314
protected virtual bool OnWatcherMovedreplacedetsEvent(string[] movedFromreplacedetPaths, string[] movedreplacedets, bool resorreplacedem)
{
m_WatcherItems.Clear();
FindItemsByreplacedetPaths(rooreplacedem, movedFromreplacedetPaths, m_WatcherItems);
List<string> importedreplacedets = movedreplacedets.ToList();
if (m_WatcherItems.Count > 0)
{
var movedFromreplacedetPathsList = movedFromreplacedetPaths.ToList();
foreach (var item in m_WatcherItems)
{
var replacedetInfo = GereplacedemreplacedetInfo(item);
if (replacedetInfo != null)
{
int idx = movedFromreplacedetPathsList.IndexOf(replacedetInfo.fileRelativePath);
if (idx != -1)
{
replacedetInfo.fileRelativePath = movedreplacedets[idx];
replacedetInfo.displayName = Path.GetFileName(replacedetInfo.fileRelativePath);
importedreplacedets.Remove(movedreplacedets[idx]);
}
}
}
// 移除掉额外显示的项,因为不需要变动
m_WatcherItems.RemoveAll(IsExtraItem);
}
if (resorreplacedem && m_WatcherItems.Count > 0)
{
// 先移除
foreach (var watcherItem in m_WatcherItems)
{
if (watcherItem.parent != null)
{
watcherItem.parent.children.Remove(watcherItem);
}
watcherItem.parent = null;
var replacedetInfo = GereplacedemreplacedetInfo(watcherItem);
if (replacedetInfo != null)
{
if (replacedetInfo.parent != null)
{
replacedetInfo.parent.children.Remove(replacedetInfo);
}
replacedetInfo.parent = null;
}
}
// 排序,以防止先处理了文件
m_WatcherItems.Sort((a, b) =>
{
var aa = GereplacedemreplacedetInfo(a);
var bb = GereplacedemreplacedetInfo(b);
if (aa != null && bb != null)
{
return EditorUtility.NaturalCompare(aa.fileRelativePath, bb.fileRelativePath);
}
return EditorUtility.NaturalCompare(a.displayName, b.displayName);
});
foreach (var watcherItem in m_WatcherItems)
{
var replacedetInfo = GereplacedemreplacedetInfo(watcherItem);
if (replacedetInfo == null)
{
continue;
}
var item = FindItemByreplacedetPath(rooreplacedem, Path.GetDirectoryName(replacedetInfo.fileRelativePath));
if (item == null)
{
continue;
}
var replacedetInfo2 = GereplacedemreplacedetInfo(item);
if (replacedetInfo2 == null)
{
continue;
}
item.AddChild(watcherItem);
replacedetInfo2.AddChild(replacedetInfo);
}
SetupDepthsFromParentsAndChildren(rooreplacedem);
SortTreeViewNaturalCompare(rooreplacedem);
}
bool ret = OnWatcherImportedreplacedetsEvent(importedreplacedets.ToArray(), resorreplacedem);
return m_WatcherItems.Count > 0 || ret;
}
19
Source : MessagingCenter.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
void InnerUnsubscribe(string message, Type senderType, Type argType, object subscriber)
{
if (subscriber == null)
throw new ArgumentNullException(nameof(subscriber));
if (message == null)
throw new ArgumentNullException(nameof(message));
var key = new Sender(message, senderType, argType);
if (!_subscriptions.ContainsKey(key))
return;
_subscriptions[key].RemoveAll(sub => sub.CanBeRemoved() || sub.Subscriber.Target == subscriber);
if (!_subscriptions[key].Any())
_subscriptions.Remove(key);
}
19
Source : TrafficPolicerHandler.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
private static void eventCreator()
{
GameFiber.StartNew(delegate
{
while (true)
{
GameFiber.Wait(100);
driversConsidered.RemoveAll(x => !x.Exists());
if (!Functions.IsCalloutRunning() && !Functions.IsPlayerPerformingPullover() && Functions.GetActivePursuit() == null && !Ambientevents.BrokenDownVehicle.BrokenDownVehicleRunning
&& NextEventStopwatch.ElapsedMilliseconds >= nextEventTimer)
{
Vehicle[] vehs = Game.LocalPlayer.Character.GetNearbyVehicles(15);
foreach (Vehicle car in vehs)
{
if (!car.Exists()) { break; }
if (Ambientevents.BrokenDownVehicle.BrokenDownVehicleRunning) { break; }
if (NextEventStopwatch.ElapsedMilliseconds < nextEventTimer) { break; }
if (car.HasDriver && car.Driver.Exists() && !car.IsPoliceVehicle && !car.Hreplacediren)
{
Ped driver = car.Driver;
if (driver == Game.LocalPlayer.Character)
{
driversConsidered.Add(driver);
}
if (!driversConsidered.Contains(driver))
{
if (eventRnd.Next(mobilePhoneChance) == 1)
{
Game.LogTrivial("Creating phone event");
new Ambientevents.MobilePhone(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (car.Speed >= 11f && eventRnd.Next(speederChance) == 1)
{
Game.LogTrivial("Creating Speeder Event");
new Ambientevents.Speeder(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if ((World.TimeOfDay.Hours <= 7 || World.TimeOfDay.Hours >= 20) && eventRnd.Next(noLightAtDarkChance) == 1)
{
Game.LogTrivial("Creating No Lights at Dark event");
new Ambientevents.NoLightsAtDark(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(noBrakeLightsChance) == 1)
{
Game.LogTrivial("Creating No Brake Lights event");
new Ambientevents.NoBrakeLights(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(BurnoutWhenStationaryChance) == 1)
{
Game.LogTrivial("Creating BurnoutWhenStationary event");
new Ambientevents.BurnoutWhenStationary(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(RevEngineWhenStationaryChance) == 1)
{
Game.LogTrivial("Creating RevEngineWhenStationary event");
new Ambientevents.RevEngineWhenStationary(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(drunkDriverChance) == 1)
{
Game.LogTrivial("Creating drunk driver event");
new Ambientevents.DrunkDriver(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(drugDriverChance) == 1)
{
Game.LogTrivial("Creating drug driver event");
new Ambientevents.DrugDriver(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(unroadworthyVehicleChance) == 1)
{
Game.LogTrivial("Creating unroadworthy vehicle event");
new Ambientevents.UnroadworthyVehicle(driver, blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(motorcyclistWithoutHelmetChance) == 1)
{
Game.LogTrivial("Creating motorcyclist event");
new Ambientevents.MotorcyclistNoHelmet(blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(BrokenDownVehicleChance) == 1)
{
Game.LogTrivial("Creating Broken Down Vehicle Event");
new Ambientevents.BrokenDownVehicle(blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(stolenVehicleChance) == 1)
{
Game.LogTrivial("Creating stolen vehicle event");
new Ambientevents.StolenVehicle(blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
else if (eventRnd.Next(streetRaceChance) == 1)
{
Game.LogTrivial("Creating Street Race Event");
new Ambientevents.StreetRace(blipStatus, showAmbientEventDescriptionMessage);
SetNextEventStopwatch();
}
driversConsidered.Add(driver);
}
}
}
}
}
});
}
19
Source : MixtureGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
Texture UpdateOutputStaticTexture(OutputTextureSettings outputSettings)
{
var dimension = outputNode.settings.GetResolvedTextureDimension(this);
var width = outputNode.settings.GetResolvedWidth(this);
var height = outputNode.settings.GetResolvedHeight(this);
var depth = outputNode.settings.GetResolvedDepth(this);
var graphicsFormat = outputNode.settings.GetGraphicsFormat(this);
var creationFlags = outputSettings.hasMipMaps ? TextureCreationFlags.MipChain : TextureCreationFlags.None;
// Check if we need to re-create the texture:
var currentTexture = FindOutputTexture(outputSettings.name, outputSettings.isMain);
if (currentTexture != null)
{
bool matchTextureSettings = currentTexture.dimension == dimension
&& currentTexture.width == width && currentTexture.height == height
&& TextureUtils.GetSliceCount(currentTexture) == depth
&& (currentTexture.mipmapCount > 1) == outputSettings.hasMipMaps
&& MatchTextureTypeWithGraphType(currentTexture);
bool MatchTextureTypeWithGraphType(Texture t)
{
bool realtimeTexture = typeof(RenderTexture).IsreplacedignableFrom(t.GetType());
if (type == MixtureGraphType.Baked)
return !realtimeTexture;
else
return realtimeTexture;
}
bool conversionOrCompression = outputSettings.IsCompressionEnabled() || outputSettings.IsConversionEnabled();
matchTextureSettings &= conversionOrCompression || (!conversionOrCompression && currentTexture.graphicsFormat == graphicsFormat);
// Note that here we don't check the graphic format of the texture, because the current texture
// can use a compressed format which will be different compared to the one in the graph.
// This can be a problem because we may end up re-creating render targets when we don't need to.
if (conversionOrCompression && matchTextureSettings)
return currentTexture;
else if (!conversionOrCompression && matchTextureSettings) // Otherwise if the format is not compressed, we want to compare the format because it directly affects the data on disk
{
if (currentTexture.graphicsFormat == graphicsFormat)
return currentTexture;
}
}
outputTextures.RemoveAll(t => t.name == outputSettings.name || (outputSettings.isMain && t.name == mainOutputTexture.name));
Texture newTexture = null;
switch (dimension)
{
case TextureDimension.Tex2D:
newTexture = new Texture2D(width, height, graphicsFormat, creationFlags);
onOutputTextureUpdated?.Invoke();
break;
case TextureDimension.Tex3D:
newTexture = new Texture3D(width, height, depth, graphicsFormat, creationFlags);
onOutputTextureUpdated?.Invoke();
break;
case TextureDimension.Cube:
newTexture = new Cubemap(width, graphicsFormat, creationFlags);
onOutputTextureUpdated?.Invoke();
break;
default:
Debug.LogError("Texture format " + dimension + " is not supported");
return null;
}
newTexture.name = (outputSettings.isMain) ? mainOutputTexture.name : outputSettings.name;
outputTextures.Add(newTexture);
return newTexture;
}
19
Source : ToolbarView.cs
with MIT License
from alelievr
with MIT License
from alelievr
protected void RemoveButton(string name, bool left)
{
((left) ? leftButtonDatas : rightButtonDatas).RemoveAll(b => b.content.text == name);
}
19
Source : BaseGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
public void Disconnect(string edgeGUID)
{
List<(BaseNode, SerializableEdge)> disconnectEvents = new List<(BaseNode, SerializableEdge)>();
edges.RemoveAll(r => {
if (r.GUID == edgeGUID)
{
disconnectEvents.Add((r.inputNode, r));
disconnectEvents.Add((r.outputNode, r));
onGraphChanges?.Invoke(new GraphChanges{ removedEdge = r });
}
return r.GUID == edgeGUID;
});
// Delay the edge disconnect event to avoid recursion
foreach (var (node, edge) in disconnectEvents)
node?.OnEdgeDisconnected(edge);
}
See More Examples