Here are the examples of the csharp api System.Collections.Generic.IEnumerable.LastOrDefault() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
836 Examples
19
Source : Program.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
static void ReadPaged()
{
WriteLine("Paging Sample", ConsoleColor.Green);
using (SqlConnection con = new SqlConnection(Common.ConnectionString))
{
Repository<City> cityRepo = new Repository<City>(con);
List<City> cities = cityRepo.ReadAllPaged("name", 1, 5).ToList();
WriteLine($"Found {cities.Count} Records in Page 1", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},Type={city.CityType},IsActive={city.IsActive}");
}
cities = cityRepo.ReadAllPaged("name", 2, 5).ToList();
WriteLine($"Found {cities.Count} Records in Page 2", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},Type={city.CityType},IsActive={city.IsActive}");
}
cities = cityRepo.ReadAllPaged("name", 1, 5, null, new { State = "GU" }).ToList();
WriteLine($"Found {cities.Count} Records where State=GU in Page 1", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},State={city.State},IsActive={city.IsActive}");
}
}
WriteLine("Paging Sample No Offset", ConsoleColor.Green);
using (SqlConnection con = new SqlConnection(Common.ConnectionString))
{
Repository<City> cityRepo = new Repository<City>(con);
List<City> cities = cityRepo.ReadAllPaged("name", 5, PageNavigationEnum.First).ToList();
WriteLine($"Found {cities.Count} Records in First Page", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},Type={city.CityType},IsActive={city.IsActive}");
}
cities = cityRepo.ReadAllPaged("name", 5, PageNavigationEnum.Next, null, null, new object[] { cities.LastOrDefault().Name }, cities.LastOrDefault().Id).ToList();
WriteLine($"Found {cities.Count} Records in Next Page", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},Type={city.CityType},IsActive={city.IsActive}");
}
cities = cityRepo.ReadAllPaged("name", 5, PageNavigationEnum.First, null, null, null, new { State = "GU" }).ToList();
WriteLine($"Found {cities.Count} Records where State=GU in First Page", ConsoleColor.Green);
foreach (City city in cities)
{
WriteLine($"City Id={city.Id},Name={city.Name},State={city.State},IsActive={city.IsActive}");
}
}
WriteLine("Press any key to continue...");
Console.ReadKey();
}
19
Source : WebRequestExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static IEnumerable<Cookie> ToCookies(this string cookie, string domain)
{
return from item in cookie.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
let kv = item.Split('=')
let name = kv.FirstOrDefault().Trim()
let value = kv.Length > 1 ? kv.LastOrDefault() : string.Empty
select new Cookie(name, value) { Domain = domain };
}
19
Source : SpellSet.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void Unpack(BinaryReader reader)
{
SpellSetTiers.UnpackPackedHashTable(reader);
HighestTier = SpellSetTiers.Keys.LastOrDefault();
SpellSetTiers lastSpellSetTier = null;
for (uint i = 0; i <= HighestTier; i++)
{
if (SpellSetTiers.TryGetValue(i, out var spellSetTiers))
lastSpellSetTier = spellSetTiers;
if (lastSpellSetTier != null)
SpellSetTiersNoGaps.Add(i, lastSpellSetTier);
}
}
19
Source : ConcurrentList.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public T Pop(Func<T, bool> predicate = null)
{
lock (_storage)
{
var result = predicate == null ? _storage.LastOrDefault() : _storage.LastOrDefault(predicate);
_storage.Remove(result);
return result;
}
}
19
Source : AttackDamage.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool LastHitCritical(List<AttackDamage> attacks)
{
var lastHit = attacks.LastOrDefault();
if (lastHit != null)
return lastHit.IsCritical;
else
return false;
}
19
Source : CommandInterpreter.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void ApplyListHeadMovement(List<CommandListElement> list)
{
var head = list.LastOrDefault();
if (head == null)
return;
// if head is mouse
//MovePlayer(head.Command, true, head.Speed, true, head.HoldRun);
// else
MovePlayer(head.Command, true, head.Speed, false, false); // always false?
}
19
Source : EnumerableExtraExtensions.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
public static T? LastOrNullable<T>(this IEnumerable<T> source)
where T : struct
{
source.ThrowOnNull(nameof(source));
return source.Cast<T?>().LastOrDefault();
}
19
Source : Arbitrary.cs
with MIT License
from adamant
with MIT License
from adamant
private static List<PsuedoToken> AppendPsuedoToken(
int size,
List<PsuedoToken> tokens)
{
var lastToken = tokens.LastOrDefault();
// TODO this is a huge hack calling Sample() FIX IT!
var token = GenPsuedoToken().Where(t =>
{
if (lastToken == null)
return true;
return !SeparateTokens(lastToken, t);
}).Sample(size, 1).Single();
tokens.Add(token);
return tokens;
}
19
Source : SqliteSyncConfigurationBuilder.cs
with MIT License
from adospace
with MIT License
from adospace
public SqliteSyncConfigurationBuilder SelectIncrementalQuery(string selectIncrementalQuery)
{
if (string.IsNullOrWhiteSpace(selectIncrementalQuery))
{
throw new ArgumentException($"'{nameof(selectIncrementalQuery)}' cannot be null or whitespace", nameof(selectIncrementalQuery));
}
var lastTable = _tables.LastOrDefault();
if (lastTable == null)
{
throw new InvalidOperationException("SelectIncrementalQuery requires a table");
}
lastTable.SelectIncrementalQuery = selectIncrementalQuery;
return this;
}
19
Source : SqliteSyncConfigurationBuilder.cs
with MIT License
from adospace
with MIT License
from adospace
public SqliteSyncConfigurationBuilder CustomSnapshotQuery(string customSnapshotQuery)
{
if (string.IsNullOrWhiteSpace(customSnapshotQuery))
{
throw new ArgumentException($"'{nameof(customSnapshotQuery)}' cannot be null or whitespace", nameof(customSnapshotQuery));
}
var lastTable = _tables.LastOrDefault();
if (lastTable == null)
{
throw new InvalidOperationException("CustomSnapshotQuery requires a table");
}
lastTable.CustomSnapshotQuery = customSnapshotQuery;
return this;
}
19
Source : SqlSyncConfigurationBuilder.cs
with MIT License
from adospace
with MIT License
from adospace
public SqlSyncConfigurationBuilder CustomSnapshotQuery(string customSnapshotQuery)
{
if (string.IsNullOrWhiteSpace(customSnapshotQuery))
{
throw new ArgumentException($"'{nameof(customSnapshotQuery)}' cannot be null or whitespace", nameof(customSnapshotQuery));
}
var lastTable = _tables.LastOrDefault();
if (lastTable == null)
{
throw new InvalidOperationException("CustomSnapshotQuery requires a table");
}
lastTable.CustomSnapshotQuery = customSnapshotQuery;
return this;
}
19
Source : SqlSyncConfigurationBuilder.cs
with MIT License
from adospace
with MIT License
from adospace
public SqlSyncConfigurationBuilder SkipColumns(params string[] columnNames)
{
if (columnNames == null)
throw new ArgumentNullException();
var lastTable = _tables.LastOrDefault();
if (lastTable == null)
{
throw new InvalidOperationException("SkipColumns requires a table");
}
//remove duplicates
lastTable.SkipColumns = columnNames;
return this;
}
19
Source : SqlSyncConfigurationBuilder.cs
with MIT License
from adospace
with MIT License
from adospace
public SqlSyncConfigurationBuilder SelectIncrementalQuery(string selectIncrementalQuery)
{
if (string.IsNullOrWhiteSpace(selectIncrementalQuery))
{
throw new ArgumentException($"'{nameof(selectIncrementalQuery)}' cannot be null or whitespace", nameof(selectIncrementalQuery));
}
var lastTable = _tables.LastOrDefault();
if (lastTable == null)
{
throw new InvalidOperationException("SelectIncrementalQuery requires a table");
}
lastTable.SelectIncrementalQuery = selectIncrementalQuery;
return this;
}
19
Source : UnwrapNotFoundExceptionAttribute.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static HttpException FindOriginalHttpException(Exception ex)
{
return GetAllHttpExceptions(ex).LastOrDefault();
}
19
Source : UIManager.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static bool Disable(GUIBase gui)
{
if (!gui.IsActive)
{
return false;
}
if (Instance == null)
{
onAwakeRms += delegate ()
{
Disable(gui);
};
return false;
}
lock (activeGUIs)
{
bool wasLast = activeGUIs
.OrderBy(g => g.Layer)
.LastOrDefault() == gui;
int oldCount = activeGUIs.Length;
activeGUIs = activeGUIs
.Where(x => x != gui)
.ToArray();
bool wasRemoved = oldCount != activeGUIs.Length;
if (wasRemoved)
{
gui.Disable();
}
if (activeGUIs.Length == 0)
{
activeGUIs = new GUIBase[0];
return wasRemoved;
}
if (!wasLast)
{
UpdateDepths();
}
return wasRemoved;
}
}
19
Source : PlanManage.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public IApiResult Station(string station)
{
if (string.IsNullOrEmpty(station))
{
return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
}
station = station.Split('-').LastOrDefault();
return new ApiArrayResult<ZeroPlan>
{
ResultData = Plans.Values.Where(p => p.station.Equals(station, StringComparison.OrdinalIgnoreCase)).ToList()
};
}
19
Source : RrCompatibleHttpClient.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
private async Task<ExecuteResult> MsgToExecuteResult(
RetryActionResult<string, HttpResponseMessage> res,
List<ExecuteResult> prevResults)
{
var response = GetResponse(res);
var body = response != null
? await response.Content.ReadreplacedtringAsync()
: "";
var isScala = GetIsScala(response);
var exceptions = (prevResults.LastOrDefault()?.Exceptions ?? new RouteException[0])
.Concat(GetExceptionList(res))
.ToList();
return new ExecuteResult(
body,
(int)res.Elapsed.TotalMilliseconds,
Encoding.UTF8.GetByteCount(body),
_isGzip,
res.Attempt - 1,
GetUrl(res),
GetStatusCode(response),
isScala,
!res.IsError,
// Duplicate current list
prevResults,
exceptions);
}
19
Source : JsonSchemaBuilder.cs
with MIT License
from akaskela
with MIT License
from akaskela
private JsonSchema Pop()
{
JsonSchema poppedSchema = _currentSchema;
_stack.RemoveAt(_stack.Count - 1);
_currentSchema = _stack.LastOrDefault();
return poppedSchema;
}
19
Source : JsonSchemaGenerator.cs
with MIT License
from akaskela
with MIT License
from akaskela
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
19
Source : FilePlayback.cs
with GNU Affero General Public License v3.0
from akira0245
with GNU Affero General Public License v3.0
from akira0245
private static TrackInfo GetTrackInfos(Note[] notes, TrackChunk i, int index)
{
var eventsCollection = i.Events;
var TrackNameEventsText = eventsCollection.OfType<SequenceTrackNameEvent>().Select(j => j.Text.Replace("\0", string.Empty).Trim()).Distinct().ToArray();
var TrackName = TrackNameEventsText.FirstOrDefault() ?? "Unreplacedled";
var IsProgramControlled = Regex.IsMatch(TrackName, @"^Program:.+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var timedNoteOffEvent = notes.LastOrDefault()?.GetTimedNoteOffEvent();
return new TrackInfo
{
//TextEventsText = eventsCollection.OfType<TextEvent>().Select(j => j.Text.Replace("\0", string.Empty).Trim()).Distinct().ToArray(),
ProgramChangeEventsText = eventsCollection.OfType<ProgramChangeEvent>().Select(j => $"channel {j.Channel}, {j.GetGMProgramName()}").Distinct().ToArray(),
TrackNameEventsText = TrackNameEventsText,
HighestNote = notes.MaxElement(j => (int)j.NoteNumber),
LowestNote = notes.MinElement(j => (int)j.NoteNumber),
NoteCount = notes.Length,
DurationMetric = timedNoteOffEvent?.TimeAs<MetricTimeSpan>(CurrentTMap) ?? new MetricTimeSpan(),
DurationMidi = timedNoteOffEvent?.Time ?? 0,
TrackName = TrackName,
IsProgramControlled = IsProgramControlled,
Index = index
};
}
19
Source : JsonStringLocalizer.cs
with MIT License
from AlexTeixeira
with MIT License
from AlexTeixeira
private string GetPluralLocalization(string name, string format, object[] arguments)
{
object last = arguments.LastOrDefault();
string value;
if (last != null && last is bool boolean)
{
bool isPlural = boolean;
value = GetString(name);
if (!string.IsNullOrEmpty(value) && value.Contains(_localizationOptions.Value.PluralSeparator))
{
int index = isPlural ? 1 : 0;
value = value.Split(_localizationOptions.Value.PluralSeparator)[index];
}
else
{
value = string.Format(format ?? name, arguments);
}
}
else
{
value = string.Format(format ?? name, arguments);
}
return value;
}
19
Source : GridifyExtensionsShould.cs
with MIT License
from alirezanet
with MIT License
from alirezanet
[Theory]
[InlineData(0, 5, true)]
[InlineData(1, 5, false)]
[InlineData(0, 10, true)]
[InlineData(3, 3, false)]
[InlineData(4, 3, true)]
[InlineData(0, 15, false)]
[InlineData(19, 10, true)]
public void ApplyOrderingAndPaging_UsingCustomValues(int page, int pageSize, bool isSortAsc)
{
var orderByExp = "name " + (isSortAsc ? "asc" : "desc");
var gq = new GridifyQuery { Page = page, PageSize = pageSize, OrderBy = orderByExp };
// actual
var actual = _fakeRepository.AsQueryable()
.ApplyOrderingAndPaging(gq)
.ToList();
// expected
var skip = (page - 1) * pageSize;
var expectedQuery = _fakeRepository.AsQueryable();
if (isSortAsc)
expectedQuery = expectedQuery.OrderBy(q => q.Name);
else
expectedQuery = expectedQuery.OrderByDescending(q => q.Name);
var expected = expectedQuery.Skip(skip).Take(pageSize).ToList();
replacedert.Equal(expected.Count, actual.Count);
replacedert.Equal(expected.FirstOrDefault()?.Id, actual.FirstOrDefault()?.Id);
replacedert.Equal(expected.LastOrDefault()?.Id, actual.LastOrDefault()?.Id);
}
19
Source : DumpCreator.cs
with GNU Lesser General Public License v3.0
from Alois-xx
with GNU Lesser General Public License v3.0
from Alois-xx
internal static int FindPidInProcDumpArgs(string[] procdumpArgs, out string exeName)
{
exeName = null;
bool bUseNext = false;
foreach(string arg in procdumpArgs.Reverse().Take(2))
{
if( int.TryParse(arg, out int pid))
{
return pid;
}
else if( arg.IndexOf(".exe", StringComparison.OrdinalIgnoreCase) != -1)
{
exeName = arg;
}
else if( arg.IndexOf(".dmp", StringComparison.OrdinalIgnoreCase) != -1)
{
bUseNext = true;
}
else if( bUseNext )
{
exeName = arg;
break;
}
}
if( exeName == null )
{
exeName = procdumpArgs.LastOrDefault();
}
return 0;
}
19
Source : KeyController.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
public void KeyPlayBack(
Queue<KeyPlayList> keyQueue,
double speed,
CancellationToken token,
int startOffset)
{
this.isRunningFlag = true;
initFlag = true;
this.UpdateKeyMap();
double? timeMs = keyQueue.LastOrDefault<KeyPlayList>()?.TimeMs;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (keyQueue.Any<KeyPlayList>())
{
KeyPlayList keyPlayList = keyQueue.Dequeue();
double num1 = (double)startOffset + keyPlayList.TimeMs * speed;
while (true)
{
if (!this.isPlayingFlag || num1 + (double)ParameterController.GetInstance().Offset + (double)this.pauseOffset > (double)stopwatch.ElapsedMilliseconds)
Thread.Sleep(1);
else
break;
}
if (keyPlayList.Ev == KeyPlayList.NoteEvent.NoteOn)
this.KeyboardPress(keyPlayList.Pitch + ParameterController.GetInstance().Pitch);
else
this.KeyboardRelease(keyPlayList.Pitch + ParameterController.GetInstance().Pitch);
double num2 = keyPlayList.TimeMs * 100.0;
double? nullable = timeMs;
Daigreplacedou.Utils.Log.overlayProcess(((int)(nullable.HasValue ? new double?(num2 / nullable.GetValueOrDefault()) : new double?()).Value).ToString());
}
Daigreplacedou.Utils.Log.overlayLog("演奏:演奏结束");
if(stopHandler!=null)
{
stopHandler.BeginInvoke(null, null);
}
this.ResetKey();
}
19
Source : SideMenuView.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private bool TryResolveFlingGesture(ref SideMenuViewState state)
{
if (state != CurrentGestureState)
{
state = CurrentGestureState;
return false;
}
if (_timeDiffItems.Count < 2)
{
return false;
}
var lasreplacedem = _timeDiffItems.LastOrDefault();
var firsreplacedem = _timeDiffItems.FirstOrDefault();
var distDiff = lasreplacedem.Diff - firsreplacedem.Diff;
if (Sign(distDiff) != Sign(lasreplacedem.Diff))
{
return false;
}
var absDistDiff = Abs(distDiff);
var timeDiff = lasreplacedem.Time - firsreplacedem.Time;
var acceptValue = SwipeThresholdDistance * timeDiff.TotalMilliseconds / SwipeThresholdTime.TotalMilliseconds;
if (absDistDiff < acceptValue)
{
return false;
}
state = ResolveSwipeState(distDiff > 0);
return true;
}
19
Source : SideMenuView.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private void CleanDiffItems()
{
var time = _timeDiffItems.LastOrDefault().Time;
for (var i = _timeDiffItems.Count - 1; i >= 0; --i)
{
if (time - _timeDiffItems[i].Time > SwipeThresholdTime)
{
_timeDiffItems.RemoveAt(i);
}
}
}
19
Source : IconController.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public IconFile GetIconFile(
string name)
{
if (string.IsNullOrEmpty(name))
{
return null;
}
if (name.Contains("\\"))
{
name = name.Split('\\').LastOrDefault();
}
return this.EnumerateIcon().FirstOrDefault(x =>
string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase) ||
string.Equals(Path.GetFileNameWithoutExtension(x.Name), name, StringComparison.OrdinalIgnoreCase));
}
19
Source : TimelineTesterView.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void TestTimer_Tick(object sender, EventArgs e)
{
lock (this)
{
var now = DateTime.Now;
if (this.isPause)
{
this.prevTestTimestamp = now;
return;
}
this.TestTime += now - this.prevTestTimestamp;
this.prevTestTimestamp = now;
var logs = (
from x in this.Logs
where
x.Time <= this.TestTime &&
!x.IsDone
orderby
x.Seq
select
x).ToArray();
foreach (var log in logs)
{
var xivlog = XIVLog.CreateToSimulation(
DateTime.Now,
log.Log);
TimelineController.XIVLogQueue.Enqueue(xivlog);
log.IsDone = true;
Thread.Yield();
}
var last = logs.LastOrDefault();
if (last != null)
{
this.TimelineTestListView.ScrollIntoView(last);
}
}
}
19
Source : TriggerTesterView.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private void TestTimer_Tick(object sender, EventArgs e)
{
lock (this)
{
var now = DateTime.Now;
if (this.isPause)
{
this.prevTestTimestamp = now;
return;
}
this.TestTime += now - this.prevTestTimestamp;
this.prevTestTimestamp = now;
var logs = (
from x in this.Logs
where
x.Time <= this.TestTime &&
!x.IsDone
orderby
x.Seq
select
x).ToArray();
foreach (var log in logs)
{
var xivlog = XIVLog.CreateToSimulation(
DateTime.Now,
log.Log);
PluginMainWorker.Instance.LogBuffer.XIVLogQueue.Enqueue(xivlog);
log.IsDone = true;
Thread.Yield();
}
var last = logs.LastOrDefault();
if (last != null)
{
this.TimelineTestListView.ScrollIntoView(last);
}
}
}
19
Source : TriggerTesterView.xaml.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private Task AddLogLineAsync() => Task.Run(async () =>
{
if (string.IsNullOrEmpty(this.LogLine))
{
return;
}
var xivlog = XIVLog.CreateToSimulation(
DateTime.Now,
this.LogLine);
PluginMainWorker.Instance.LogBuffer.XIVLogQueue.Enqueue(xivlog);
await WPFHelper.InvokeAsync(() =>
{
this.Logs.Add(new TestLog(xivlog.LogLine)
{
Seq = this.Logs.Count() + 1,
IsDone = true,
Time = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second),
});
var last = this.Logs.LastOrDefault();
if (last != null)
{
this.TimelineTestListView.ScrollIntoView(last);
}
this.LogLine = string.Empty;
});
});
19
Source : EnmityInfoWorker.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private bool RefreshEPS()
{
if (this.DiffSampleTimer.Elapsed.TotalSeconds < 3.0)
{
return false;
}
this.DiffSampleTimer.Restart();
var me = this.CurrentEnmityModelList.FirstOrDefault(x => x.IsMe);
var sample = (
from x in this.CurrentEnmityModelList
where
x.JobID == JobIDs.PLD ||
x.JobID == JobIDs.WAR ||
x.JobID == JobIDs.DRK
orderby
Math.Abs(x.Enmity - (me?.Enmity ?? 0)) ascending
select
x).FirstOrDefault();
if (sample == null)
{
this.currentTankEPS = 0;
this.currentNearThreshold = 0;
return true;
}
var last = this.DiffEnmityList.LastOrDefault();
var diff = Math.Abs(sample.Enmity - (last?.Value ?? 0));
var now = DateTime.Now;
this.DiffEnmityList.Add(new DiffEnmity()
{
Timestamp = now,
SampleName = sample.Name,
Value = sample.Enmity,
Diff = diff,
});
var olds = this.DiffEnmityList
.Where(x => x.Timestamp < now.AddSeconds(-30))
.ToArray();
foreach (var item in olds)
{
this.DiffEnmityList.Remove(item);
}
var parameters = this.DiffEnmityList
.Where(x =>
this.currentTankEPS <= 0 ||
x.Diff <= (this.currentTankEPS * 10.0));
// EPSと危険域閾値を算出する
this.currentTankEPS = parameters.Any() ?
parameters.Average(x => x.Diff) :
0;
this.currentNearThreshold = this.currentTankEPS * Settings.Instance.Enmity.NearThresholdRate;
return true;
}
19
Source : FuzzyLogicCore.cs
with MIT License
from antonio-leonardo
with MIT License
from antonio-leonardo
private bool ProcessFilter(string filter, TEnreplacedy invalidData, string propertyName)
{
if (typeof(TEnreplacedy).GetProperty(propertyName).PropertyType == typeof(Double) && filter.Contains(","))
{
filter = filter.Replace(",", ".");
}
bool ratingResult = false;
const char FIRST_BRACKET = '(',
LAST_BRACKET = ')';
string newFilter = filter;
ConcurrentBag<int> charsIdWithStartParentesesParallel = new ConcurrentBag<int>();
ConcurrentBag<int> charsIdWithEndParentesesParallel = new ConcurrentBag<int>();
char[] filterChars = filter.ToCharArray();
Parallel.For(0, filterChars.Length, i =>
{
if (filterChars[i] == FIRST_BRACKET)
{
charsIdWithStartParentesesParallel.Add(i);
}
else if (filterChars[i] == LAST_BRACKET)
{
charsIdWithEndParentesesParallel.Add(i);
}
});
List<int> charsIdWithStartParenteses = charsIdWithStartParentesesParallel.ToList();
List<int> charsIdWithEndParenteses = charsIdWithEndParentesesParallel.ToList();
bool isMatch = false;
while (!isMatch)
{
try
{
this.SubsreplaceduteChars(ref newFilter);
ratingResult = DynamicLinq.DynamicExpression.ParseLambda<TEnreplacedy, bool>(newFilter).Compile().Invoke(invalidData);
isMatch = true;
}
catch
{
if (charsIdWithStartParenteses.Count > charsIdWithEndParenteses.Count)
{
filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
newFilter = filter;
charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
}
else if (charsIdWithStartParenteses.Count < charsIdWithEndParenteses.Count)
{
filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
newFilter = filter;
charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
}
else
{
if (charsIdWithStartParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithStartParenteses.Count)))
{
filter = filter.Remove(filter.LastIndexOf(LAST_BRACKET) - 1, 1);
newFilter = filter;
charsIdWithEndParenteses.Remove(charsIdWithEndParenteses.LastOrDefault());
}
else if (charsIdWithEndParenteses.SequenceEqual(Enumerable.Range(1, charsIdWithEndParenteses.Count)))
{
filter = filter.Remove(filter.IndexOf(FIRST_BRACKET), 1);
newFilter = filter;
charsIdWithStartParenteses.Remove(charsIdWithStartParenteses.FirstOrDefault());
}
}
}
}
return ratingResult;
}
19
Source : BibleTextImage.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private DrawingVisual DrawBody(
int imageNumber,
int totalImageCount,
IReadOnlyCollection<string> lines,
int linesPerImage,
double lineHeight,
double spaceForreplacedle)
{
DrawingVisual visual = new DrawingVisual();
if (BodyDropShadow)
{
visual.Effect = new DropShadowEffect
{
Color = BodyDropShadowColor,
Opacity = BodyDropShadowOpacity,
BlurRadius = BodyDropShadowBlurRadius,
ShadowDepth = BodyDropShadowDepth
};
}
using (var c = visual.RenderOpen())
{
var linesForBmp = GetBatchOfLines(lines, imageNumber, linesPerImage).ToArray();
var linesForPreviousBmp = GetBatchOfLines(lines, imageNumber - 1, linesPerImage);
int lineCount = linesForBmp.Length;
double adjustmentForShortLineCount = 0;
if (BodyVerticalAlignment == OnlyVBodyVerticalAlignment.Middle && lineCount < linesPerImage)
{
adjustmentForShortLineCount = (lineHeight * (linesPerImage - lineCount)) / 2;
}
var moreImagesAfterThis = imageNumber < totalImageCount - 1;
var adjustmentForreplacedleAtTop = Showreplacedle && replacedlePosition == OnlyVreplacedlePosition.Top
? spaceForreplacedle
: 0;
for (var lineNum = 0; lineNum < lineCount; ++lineNum)
{
var lineStr = linesForBmp[lineNum];
if (UseContinuationEllipses &&
lineNum == 0 &&
lineStr.Length > 0 &&
!IsEndOfSentenceOrPhrase(linesForPreviousBmp?.LastOrDefault()))
{
// ellipsis at start of this line...
lineStr = string.Concat(Ellipsis, lineStr);
}
if (UseContinuationEllipses &&
lineNum == linesForBmp.Length - 1 &&
moreImagesAfterThis &&
!IsEndOfSentenceOrPhrase(lineStr))
{
// ellipsis at the end of the last line (if appropriate)...
lineStr = string.Concat(lineStr, Ellipsis);
}
var y = TopMargin + adjustmentForreplacedleAtTop + adjustmentForShortLineCount + (lineNum * lineHeight);
DrawTextLine(c, lineStr, y);
}
}
return visual;
}
19
Source : BibleTextImage.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private static bool IsEndOfSentenceOrPhrase(string lastOrDefault)
{
if (lastOrDefault != null)
{
char ch = lastOrDefault.Trim().LastOrDefault();
if (ch == '.' || ch == ',' || ch == ';' || ch == ':' || ch == '-' || ch == '—')
{
return true;
}
return false;
}
return true;
}
19
Source : CommonAndroidViewPresenter.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
protected override bool TryPerformCloseFragmentTransaction(FragmentManager fragmentManager, MvxFragmentPresentationAttribute fragmentAttribute)
{
var fragmentName = fragmentAttribute.ViewType.FragmentJavaName();
var fragmentTransaction = fragmentManager.BeginTransaction();
fragmentTransaction.DisallowAddToBackStack();
PopFragment(fragmentManager, fragmentTransaction, fragmentAttribute, fragmentName, true);
var newLastCachedFragment = FragmentsBackStack?.LastOrDefault();
if (newLastCachedFragment != null)
PushFragment(fragmentManager, fragmentTransaction, null, null, newLastCachedFragment.ViewModel, newLastCachedFragment.Key);
fragmentTransaction.CommitNow();
return true;
}
19
Source : CommonAndroidViewPresenter.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public virtual void MoveBack()
{
if (CanPop())
{
var cachedFragment = FragmentsBackStack?.LastOrDefault();
if (cachedFragment != null)
{
var fragmentManager = CurrentFragmentManager;
var fragmentTransaction = fragmentManager.BeginTransaction();
fragmentTransaction.DisallowAddToBackStack();
PopFragment(fragmentManager, fragmentTransaction, DeqeueFragmentAttributeIfExist(cachedFragment.Key), cachedFragment.Key, true);
var newLastCachedFragment = FragmentsBackStack?.LastOrDefault();
if (newLastCachedFragment != null)
PushFragment(fragmentManager, fragmentTransaction, null, null, newLastCachedFragment.ViewModel, newLastCachedFragment.Key);
fragmentTransaction.CommitNow();
}
}
else
{
if ((new Java.Util.Date().Time - LastBackClick.Time) / 1000 < 3)
{
CurrentActivity.FinishAffinity();
Process.KillProcess(Process.MyPid());
}
else
{
LastBackClick = new Java.Util.Date();
(CurrentActivity as ICommonActivity)?.ShowToast(Mvx.IoCProvider.Resolve<ILocalizationService>().GetLocalizableString("Base", "Hint_CloseApp"));
}
}
}
19
Source : LocalizationManagerTests.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
[Parallelizable(ParallelScope.None)]
[TestCase(LogLevel.Info)]
[TestCase(LogLevel.Debug)]
[TestCase(LogLevel.Error)]
[TestCase(LogLevel.Fatal)]
[TestCase(LogLevel.Warn)]
public void Should_BeAble_LogLocalizedMessage(LogLevel logLevel)
{
switch (logLevel)
{
case LogLevel.Info:
LocalizedLogger.Info(NavigationKey, TestUrl);
break;
case LogLevel.Debug:
LocalizedLogger.Debug(NavigationKey, null, TestUrl);
break;
case LogLevel.Error:
LocalizedLogger.Error(NavigationKey, TestUrl);
break;
case LogLevel.Fatal:
LocalizedLogger.Fatal(NavigationKey, null, TestUrl);
break;
case LogLevel.Warn:
LocalizedLogger.Warn(NavigationKey, TestUrl);
break;
default:
throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, "Cannot process log level");
}
var logMessage = File.ReadAllLines(LogPath).LastOrDefault();
replacedert.IsFalse(string.IsNullOrEmpty(logMessage), "Message should appear in log file");
replacedert.IsTrue(logMessage.Contains(LocalizedNavigationMessage),
$"Message should be localized. Expected: {LocalizedNavigationMessage}, actual: {logMessage}");
}
19
Source : AssTransformTagHandler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private static T FetchColorAnimation<T>(
replacedTagContext context,
DateTime startTime,
DateTime endTime,
Func<T, bool> predicate,
Func<replacedSection, Color> getSectionColor,
Func<DateTime, DateTime, Color, T> createAnim
)
where T : ColorAnimation
{
context.Section.Animations.RemoveAll(a => a is T && a.StartTime > startTime);
replacedSection section = context.Section;
IEnumerable<T> existingAnims = section.Animations.OfType<T>().Where(a => a.StartTime == startTime && a.EndTime == endTime);
if (predicate != null)
existingAnims = existingAnims.Where(predicate);
T anim = existingAnims.FirstOrDefault();
if (anim == null)
{
IEnumerable<T> prevAnims = section.Animations.OfType<T>();
if (predicate != null)
prevAnims = prevAnims.Where(predicate);
T prevAnim = prevAnims.LastOrDefault();
anim = createAnim(startTime, endTime, prevAnim?.EndColor ?? getSectionColor(section));
section.Animations.Add(anim);
}
return anim;
}
19
Source : RunningCommand.cs
with MIT License
from ardacetinkaya
with MIT License
from ardacetinkaya
public void FireChanged()
{
Changed?.Invoke(Tasks.LastOrDefault());
}
19
Source : StructureLog.cs
with MIT License
from ark-mod
with MIT License
from ark-mod
[System.Diagnostics.Conditional("STRUCTURELOG")]
public void Save()
{
if (!Directory.Exists(_binaryTemplateOutputDirPath)) Directory.CreateDirectory(_binaryTemplateOutputDirPath);
string path;
var num = 0;
while (true)
{
num++;
path = Path.Combine(_binaryTemplateOutputDirPath, $"toolkit_{num:0000}.bt");
if (!File.Exists(path)) break;
else if (num > 1000) return;
}
using var sw = new StreamWriter(path);
var flat = new List<StackLogTreeNode>();
StackLogTreeNode root = null;
StackLogTreeNode currentNode = null;
StackLogTreeNode toIdNullMaxLevelNode = null;
foreach (var sl in _stackLog)
{
var node = StackLogTreeNode.FromStackLog(sl);
flat.Add(node);
if (root == null) root = currentNode = node;
else
{
if (node.Level < currentNode.Level)
{
for (var i = currentNode.Level; i >= node.Level; i--) currentNode = currentNode.Parent;
}
else if (node.Level == currentNode.Level)
{
currentNode = currentNode.Parent;
}
node.Parent = currentNode;
currentNode.Children.Add(node);
currentNode = node;
}
}
// we are looking for the current stack entry here
// get the last struct without set toId, if the end has multiple we want the last one with a previous set
toIdNullMaxLevelNode = flat.LastOrDefault();
var prev = flat.TakeWhile(x => x != toIdNullMaxLevelNode).ToList();
prev.Add(toIdNullMaxLevelNode);
prev.Reverse();
var tmp = _offsets.Select(x => new OffsetLog(x.start, x.len, x.type, x.name, x.id)).ToList();
foreach (var c in prev)
{
OffsetLog[] ofs = null;
if (c == toIdNullMaxLevelNode) ofs = tmp.Where(x => x.Id >= c.FromId).ToArray();
else if (!c.ToId.HasValue) continue;
else ofs = tmp.Where(x => x.Id >= c.FromId && x.Id <= c.ToId.Value).ToArray();
foreach (var o in ofs) tmp.Remove(o);
c.Offsets.AddRange(ofs);
}
string RecursiveGetNextName(Dictionary<string, (string name, int? num)> propNames, string name, int? num = null)
{
var nextName = name + (num != null ? $"_{num}" : "");
if (!propNames.TryGetValue(nextName, out var prevVarName)) prevVarName = (name, num);
else return RecursiveGetNextName(propNames, name, (num ?? 0) + 1);
propNames.Add(nextName, prevVarName);
return nextName;
}
void RecursiveWriteTreeNode(StackLogTreeNode node, string structName)
{
WriteStructStart(sw, node);
var propNames = new Dictionary<string, (string name, int? num)>();
foreach (var o in node.Ordered)
{
if (o is OffsetLog)
{
var log = o as OffsetLog;
var name = RecursiveGetNextName(propNames, log.Name);
WriteVariable(sw, log, name, node.Level + 1);
}
else if (o is StackLogTreeNode)
{
var sn = o as StackLogTreeNode;
var name = sn.Stack.VarName != null ? RecursiveGetNextName(propNames, sn.Stack.VarName) : sn.Stack.TypeName;
RecursiveWriteTreeNode(sn, name);
}
}
WriteStructEnd(sw, node, structName);
}
RecursiveWriteTreeNode(root, "ARK");
sw.Flush();
var tmp2 = _offsets.Select(x => new OffsetLog(x.start, x.len, x.type, x.name, x.id)).ToList();
var tmp3 = prev.Select(x => StackLogTreeNode.FromStackLog(x)).ToList();
var json = Newtonsoft.Json.JsonConvert.SerializeObject(root, Newtonsoft.Json.Formatting.Indented);
var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(_stackLog, Newtonsoft.Json.Formatting.Indented);
var json3 = Newtonsoft.Json.JsonConvert.SerializeObject(tmp2, Newtonsoft.Json.Formatting.Indented);
var json4 = Newtonsoft.Json.JsonConvert.SerializeObject(tmp3, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(Path.Combine(_binaryTemplateOutputDirPath, $"toolkit_tree.json"), json);
File.WriteAllText(Path.Combine(_binaryTemplateOutputDirPath, $"toolkit_stackLog.json"), json2);
File.WriteAllText(Path.Combine(_binaryTemplateOutputDirPath, $"toolkit_offsets.json"), json3);
File.WriteAllText(Path.Combine(_binaryTemplateOutputDirPath, $"toolkit_prev_order.json"), json4);
}
19
Source : FopExpressionBuilder.cs
with MIT License
from arslanaybars
with MIT License
from arslanaybars
private static IEnumerable<IFilterList> FilterExpressionBuilder(string filter)
{
//filter = filter.ToLower();
var genericType = typeof(T);
var genericTypeName = genericType.Name;
var multipleLogicParts = filter.Split('$');
var filterList = new IFilterList[multipleLogicParts.Length];
for (var i = 0; i < multipleLogicParts.Length; i++)
{
var multipleLogicPart = multipleLogicParts[i];
var filterLogicParts = multipleLogicPart.Split(';');
var logicOperator = filterLogicParts[filterLogicParts.Length - 1];
var (filterLogicPartLength, logicOperatorEnum) = FilterLogicPartLength(logicOperator, filterLogicParts);
filterList[i] = new FilterList
{
Filters = new Filter.Filter[filterLogicPartLength],
Logic = logicOperatorEnum
};
for (var j = 0; j < filterLogicPartLength; j++)
{
var filterLogicPart = filterLogicParts[j];
var (key, value) = Operator.Dictionary.FirstOrDefault(x => filterLogicPart.Contains(x.Key));
if (key == null)
{
throw new FilterOperatorNotFoundException(
$"{filterLogicPart} is not found in our Operator.Dictionary");
}
var filterObject = filterLogicPart.Split(key);
// var property = genericProperties.FirstOrDefault(x => x.Name.ToLower() == filterObject[0]);
var propertyInfos = new List<PropertyInfo>();
var property = GetPropertyValue(genericType, filterObject[0], propertyInfos);
var lastProperty = property.LastOrDefault();
((Filter.Filter[])filterList[i].Filters)[j] = new Filter.Filter
{
Operator = value,
DataType = GetFilterDataTypes(lastProperty),
Key = genericTypeName + "." + property.Select(x => x.Name).Aggregate((a, b) => a + "." + b),
Value = filterObject[1],
replacedembly = lastProperty?.Module.Name.Replace(".dll", string.Empty),
Fullname = lastProperty?.PropertyType.FullName
};
}
}
return filterList;
}
19
Source : EmailProviderService.cs
with Apache License 2.0
from aruss
with Apache License 2.0
from aruss
public async Task<EmailProviderInfo> GetProviderInfo(string email)
{
if (string.IsNullOrWhiteSpace(email))
{
throw new ArgumentNullException(nameof(email));
}
string host = email
.Trim()
.Split('@')
.LastOrDefault()
.ToLowerInvariant();
if (!this._providerInfos.ContainsKey(host))
{
return null;
}
EmailProviderInfo result = this._providerInfos[host];
return result;
}
19
Source : ReCaptchaDialog.cs
with MIT License
from Ashesh3
with MIT License
from Ashesh3
private void geckoWebBrowser1_Navigating(object sender, Gecko.Events.GeckoNavigatingEventArgs e)
{
if (Regex.IsMatch(e.Uri?.Segments?.LastOrDefault() ?? "",
@"join\/?", RegexOptions.IgnoreCase)
|| (e.Uri?.Host ?? "").ToLower() != (Defaults.Web.STEAM_JOIN_URI?.Host?.ToLower() ?? "NULL"))
{
Logger.Trace("Navigated to /join/.");
return;
}
try
{
Logger.Info("Stopping navigation to new location...");
e.Cancel = true;
}
catch(Exception ex)
{
Logger.Error("Failed to stop navigation...", ex);
try
{
geckoWebBrowser1.Navigate(Defaults.Web.STEAM_JOIN_ADDRESS);
}
catch(Exception exNav)
{
Logger.Error("Navigation error", exNav);
}
}
}
19
Source : RaidProtectionModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public void SlideWindow(TimeSpan windowSize)
{
var last = _data.LastOrDefault();
if (last != null)
_data.RemoveAll(x => x.Timestamp < last.Timestamp - windowSize);
}
19
Source : SqliteProvider.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public async Task<long> GetEventsAsync(string actorName, long indexStart, long indexEnd, Action<object> callback)
{
using var connection = new SqliteConnection(ConnectionString);
await connection.OpenAsync();
using var selectCommand = CreateCommand(
connection,
"SELECT EventIndex, EventData FROM Events WHERE ActorName = $ActorName AND EventIndex >= $IndexStart AND EventIndex <= $IndexEnd ORDER BY EventIndex ASC",
("$ActorName", actorName),
("$IndexStart", indexStart),
("$IndexEnd", indexEnd)
);
var indexes = new List<long>();
using var reader = await selectCommand.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
indexes.Add(Convert.ToInt64(reader["EventIndex"]));
callback(JsonConvert.DeserializeObject<object>(reader["EventData"].ToString(), AutoTypeSettings));
}
return indexes.Any() ? indexes.LastOrDefault() : -1;
}
19
Source : InMemoryProvider.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public Task<(object Snapshot, long Index)> GetSnapshotAsync(string actorName)
{
if (!_snapshots.TryGetValue(actorName, out var snapshots))
return Task.FromResult<(object, long)>((null, 0));
var snapshot = snapshots.OrderBy(ss => ss.Key).LastOrDefault();
return Task.FromResult((snapshot.Value, snapshot.Key));
}
19
Source : Book.Part.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
public void RemovePaddingChapters () {
if (Chapters.FirstOrDefault()?.IsPaddingChapter ?? false)
Chapters.RemoveAt (0);
if (Chapters.LastOrDefault()?.IsPaddingChapter ?? false)
Chapters.RemoveAt (Chapters.Count - 1);
}
19
Source : Chapter.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
private void handleChapterMark (Chapter nextChapter) {
TimeInterval lastSilence = Silences.Last ();
// last silence extends into next chapter?
if (this.endsWithSilence (lastSilence)) {
bool nextChapterStartsWithSilence = nextChapter?.startsWithSilence () ?? false;
// is this a long silence?
if (lastSilence.Duration > TS_MAX_LAST_SILENCE) {
// but next chapter already starts with silence?
if (nextChapterStartsWithSilence)
return;
} else {
// If we end with a silence but the next chapter starts without one, then let's split our silence in half
if (!nextChapterStartsWithSilence)
setAdjustment (nextChapter, lastSilence);
return;
}
}
// the next chapter may start with silence but it might not be the right one.
if (nextChapter?.startsWithSilence () ?? false) {
var sil = Silences.Where (s => s.End > this.Time.Duration - TS_PART_replacedLE_LENGTH && s.Duration > TS_LONGER_SILENCE).LastOrDefault ();
if (sil.IsNull())
return;
}
// this chapter does not end and next does not begin with silence
// so we look closer
// only treat it, if close to the end
if (lastSilence.End < Time.Duration - TS_CATCH_RANGE) {
Log (3, this, () => $"{this}; out of range: {lastSilence}");
return;
}
if (!nextChapter.IsNull ()) {
// alternatively merge nearest longer silences from next and this into tmp
var silences = new List<TimeInterval> ();
silences.AddRange (Silences.Where (s => s.End > this.Time.Duration - TS_PART_replacedLE_LENGTH && s.Duration > TS_LONGER_SILENCE).Select (s => new TimeInterval (s)));
silences.AddRange (nextChapter.Silences.Where (s => s.Begin < TS_PART_replacedLE_LENGTH && s.Duration > TS_LONGER_SILENCE).Select (s => new TimeInterval (s, this.Time.Duration)));
// pick the one closest to the chapter mark
var silence = closestToChapterMark (silences, true);
if (!silence.IsNull ()) {
lastSilence = silence;
Log (3, this, () => $"{this}; replacedumed end #{silences.IndexOf (silence) + 1}/{silences.Count}: {silence}, [abs -> {(Time.Begin + silence.End).ToStringHMSm()}]");
}
}
setAdjustment (nextChapter, lastSilence);
}
19
Source : Chapter.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
public void CreateCueSheet (Book.Part part, int trackDurMins, bool splitTimeMode) {
Log (3, this, () => this.ToString ());
// chapter duration in sec
double chLenSec = this.Time.Duration.TotalSeconds;
// rounded number of tracks in chapter, observing desired track duration
int numTracks = Math.Max ((int)(chLenSec / (trackDurMins * 60) + 0.5), 1);
// average track length in sec
double aveTrackLen = chLenSec / numTracks;
// average track length as TimeSpan
var tsAveTrackLen = TimeSpan.FromSeconds (aveTrackLen);
// search range for silence at desired end of track is +/- 1/3 ave track length
var tsSearchRange = TimeSpan.FromSeconds (aveTrackLen / 3);
// start 1st track at zero
// unless in time split mode where we start at the actual beginning of the chapter
var tsStart = TimeSpan.Zero;
if (splitTimeMode)
tsStart = this.Time.Begin;
// desired end of 1st track
var tsEnd = tsStart + tsAveTrackLen;
// max end is chapter duration unless in time split mode
var tsChEnd = this.Time.Duration - TS_EPS_SILENCE;
if (splitTimeMode)
tsChEnd = this.Time.End;
// filter silences
var silences = this.Silences.Where (s => s.Duration >= TS_SHORT_SILENCE).ToList ();
// while chapter length has not been reached, will be checked in loop
while (true) {
if (tsEnd < tsChEnd) {
// upper search limit for silence
var tsUpper = tsEnd + tsSearchRange;
// lower search limit for silence
var tsLower = tsEnd - tsSearchRange;
// take the easy road using LINQ, find nearest silence or none, above and below
var silUp = silences.Where (t => t.Begin >= tsEnd && t.Begin < tsUpper).FirstOrDefault ();
var silDn = silences.Where (t => t.End > tsLower && t.End <= tsEnd).LastOrDefault ();
// which silence shall it be
TimeInterval sil = null;
if (!(silUp is null || silDn is null)) {
// up and down found, use nearest
var deltaUp = silUp.Begin - tsEnd;
var deltaDn = tsEnd - silDn.End;
if (deltaUp < deltaDn)
sil = silUp;
else
sil = silDn;
} else {
// not both found, use any present
if (!(silUp is null))
sil = silUp;
else if (!(silDn is null))
sil = silDn;
}
// silence has been found
if (!(sil is null)) {
// actual track end
// add half of the silence interval, put other half of the silence into the next track.
// However, cut in stream will not be precise.
var tsActualEnd = sil.Begin + TimeSpan.FromTicks (sil.Duration.Ticks / 2);
// check for overshooting
if (tsActualEnd > tsChEnd)
tsActualEnd = tsChEnd;
// actual difference
var tsDelta = tsActualEnd - tsEnd;
// create new track item
var track = new Track (tsStart, tsActualEnd) {
Chapter = this
};
part.Tracks.Add (track);
// set for next track
tsStart = tsActualEnd;
tsEnd = tsStart + tsAveTrackLen - tsDelta;
if (tsEnd + tsSearchRange > tsChEnd)
tsEnd = tsChEnd;
} else {
// silence not found, extend track
tsEnd += tsAveTrackLen;
}
}
// at the end of the chapter
if (tsEnd >= tsChEnd) {
// last track without silence search
var track = new Track (tsStart, tsChEnd) {
Chapter = this
};
part.Tracks.Add (track);
// done
break;
}
}
}
19
Source : FFmpeg.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
private void ffMpegAsyncHandlerActivation (object sendingProcess, DataReceivedEventArgs outLine) {
onCancel ();
if (outLine.Data is null)
return;
#if TRACE && EXTRA
Trace.WriteLine (outLine.Data);
#endif
Log (4, this, () => ID + outLine.Data.SubsreplacedUser ());
Match match = null;
if (!Chapters.IsNull () && !_listComplete) {
match = _rgxChapter.Match (outLine.Data);
if (match.Success) {
var chapter = new Chapter ();
Chapters.Add (chapter);
chapter.Time.Begin = tryParseSeconds (match);
chapter.Time.End = tryParseSeconds (match, 2);
return;
} else {
match = _rgxAnyStream.Match (outLine.Data);
if (match.Success)
_listComplete = true;
else {
var chapter = Chapters.LastOrDefault ();
if (!chapter.IsNull ()) {
match = _rgxChapterMeta.Match (outLine.Data);
if (match.Success) {
chapter.Name = string.Empty;
return;
} else {
if (chapter.Name == string.Empty) {
match = _rgxChapterreplacedle.Match (outLine.Data);
if (match.Success) {
chapter.Name = match.Groups[1].Value;
}
return;
}
}
}
}
}
}
match = _rgxErrorHeader.Match (outLine.Data);
if (match.Success)
_success = false;
else {
match = _rgxErrorActivationOption.Match (outLine.Data);
if (match.Success) {
_success = false;
} else {
match = _rgxInvalid.Match (outLine.Data);
if (match.Success) {
_success = false;
} else {
match = _rgxNoActivatonOpt.Match (outLine.Data);
if (match.Success) {
HasNoActivation = true;
} else {
match = _rgxAudioStream.Match (outLine.Data);
if (match.Success) {
string format = match.Groups[1].Value;
IsMp3Stream = format.ToLowerInvariant () == "mp3";
} else {
match = _rgxAaFile.Match (outLine.Data);
if (match.Success) {
IsAaFile = true;
} else {
match = _rgxAaxFile.Match (outLine.Data);
if (match.Success)
IsAaxFile = true;
}
}
}
}
}
}
}
See More Examples