Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Take(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4004 Examples
19
Source : RCEPControl.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
[RCEndpoint(true, "/userinfos", "?from={first}&count={count}", "?from=0&count=100", "User Infos", "Get some basic information about ALL users.")]
public static void UserInfos(Frontend f, HttpRequestEventArgs c) {
using UserDataBatchContext ctx = f.Server.UserData.OpenBatch();
string[] uids = f.Server.UserData.GetAll();
NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
if (!int.TryParse(args["from"], out int from) || from <= 0)
from = 0;
if (!int.TryParse(args["count"], out int count) || count <= 0)
count = 100;
if (from + count > uids.Length)
count = uids.Length - from;
f.RespondJSON(c, uids.Skip(from).Take(count).Select(uid => {
BasicUserInfo info = f.Server.UserData.Load<BasicUserInfo>(uid);
BanInfo ban = f.Server.UserData.Load<BanInfo>(uid);
KickHistory kicks = f.Server.UserData.Load<KickHistory>(uid);
return new {
UID = uid,
info.Name,
info.Discrim,
info.Tags,
Key = f.Server.UserData.GetKey(uid),
Ban = ban.Reason.IsNullOrEmpty() ? null : new {
ban.Name,
ban.Reason,
From = ban.From?.ToUnixTime() ?? 0,
To = ban.To?.ToUnixTime() ?? 0
},
Kicks = kicks.Log.Select(e => new {
e.Reason,
From = e.From?.ToUnixTime() ?? 0
}).ToArray()
};
}).ToArray());
}
19
Source : FileOrganization.cs
with Apache License 2.0
from 0xFireball
with Apache License 2.0
from 0xFireball
public static DirectoryStructure BuildStructure(IEnumerable<StoredFile> files)
{
var dirStructure = new DirectoryStructure
{
Path = "/"
};
foreach (var file in files)
{
var pathSegments = GetPathSegments(file.ParentDirPath);
var targetPathSegmentCount = pathSegments.Length;
var parent = dirStructure;
for (int i = 0; i < targetPathSegmentCount; i++)
{
var currentSegment = pathSegments[i];
var currentFullPath = JoinPathSegments(pathSegments.Take(i + 1).ToArray());
DirectoryStructure nextChild;
var existingChild = parent.SubDirectories.Where(x => x.Path == currentFullPath).FirstOrDefault();
if (existingChild != null)
{
nextChild = existingChild;
}
else
{
// Create and add next directory
nextChild = new DirectoryStructure
{
Name = currentSegment,
Path = parent.Path + currentSegment + "/"
};
parent.SubDirectories.Add(nextChild);
}
parent = nextChild;
}
parent.Files.Add(file);
}
return dirStructure;
}
19
Source : Decrypter.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public override int Read( byte[] buffer, int offset, int count)
{
if (Position == inputStream.Length)
return 0;
var positionInSector = Position % sectorSize;
var resultCount = 0;
if (positionInSector > 0)
{
var len = (int)Math.Min(Math.Min(count, sectorSize - positionInSector), inputStream.Position - Position);
md5.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
sha1.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
sha256.TransformBlock(bufferedSector, (int)positionInSector, len, buffer, offset);
offset += len;
count -= len;
resultCount += len;
Position += len;
if (Position % sectorSize == 0)
SectorPosition++;
}
if (Position == inputStream.Length)
return resultCount;
int readCount;
do
{
readCount = inputStream.ReadExact(tmpSector, 0, sectorSize);
if (readCount < sectorSize)
Array.Clear(tmpSector, readCount, sectorSize - readCount);
var decryptedSector = tmpSector;
if (IsEncrypted(SectorPosition))
{
WasEncrypted = true;
if (readCount % 16 != 0)
{
Log.Debug($"Block has only {(readCount % 16) * 8} bits of data, reading raw sector...");
discStream.Seek(SectorPosition * sectorSize, SeekOrigin.Begin);
var newTmpSector = new byte[sectorSize];
discStream.ReadExact(newTmpSector, 0, sectorSize);
if (!newTmpSector.Take(readCount).SequenceEqual(tmpSector.Take(readCount)))
Log.Warn($"Filesystem data and raw data do not match for sector 0x{SectorPosition:x8}");
tmpSector = newTmpSector;
}
using var aesTransform = aes.CreateDecryptor(decryptionKey, GetSectorIV(SectorPosition));
decryptedSector = aesTransform.TransformFinalBlock(tmpSector, 0, sectorSize);
}
else
WasUnprotected = true;
if (count >= readCount)
{
md5.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
sha1.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
sha256.TransformBlock(decryptedSector, 0, readCount, buffer, offset);
offset += readCount;
count -= readCount;
resultCount += readCount;
Position += readCount;
SectorPosition++;
}
else // partial sector read
{
Buffer.BlockCopy(decryptedSector, 0, bufferedSector, 0, sectorSize);
md5.TransformBlock(decryptedSector, 0, count, buffer, offset);
sha1.TransformBlock(decryptedSector, 0, count, buffer, offset);
sha256.TransformBlock(decryptedSector, 0, count, buffer, offset);
offset += count;
count = 0;
resultCount += count;
Position += count;
}
} while (count > 0 && readCount == sectorSize);
return resultCount;
}
19
Source : ProxyGenerator.cs
with MIT License
from 1100100
with MIT License
from 1100100
private static TypeSyntax GenerateType(Type type)
{
if (!type.IsGenericType)
return GenerateQualifiedNameSyntax(type);
var list = new List<SyntaxNodeOrToken>();
foreach (var genericType in type.GetGenericArguments())
{
list.Add(genericType.IsGenericType ? GenerateType(genericType) : GenerateQualifiedNameSyntax(genericType.FullName));
list.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
}
var typeArgumentList = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList<TypeSyntax>(list.Take(list.Count - 1)));
//if (type.Namespace == typeof(Task).Namespace)
return SyntaxFactory.GenericName(type.Name.Substring(0, type.Name.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
//return SyntaxFactory.GenericName(type.FullName?.Substring(0, type.FullName.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
}
19
Source : RedisDatabase.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private IList<RedisKey> GetKeys(string prefix = null, int pageSize = 10, int pageOffset = 0)
{
var pat = prefix.IsNull() ? null : $"{GetKey(prefix)}*";
var endPoints = _redis.GetEndPoints();
if (endPoints.Length > 1)
{
var skipNum = pageOffset * pageSize;
var leftNum = skipNum + pageSize;
var keys = new List<RedisKey>();
foreach (var endPoint in endPoints)
{
if (leftNum > 0)
{
foreach (var key in _redis.GetServer(endPoint).Keys(_dbIndex, pat, pageSize: leftNum))
{
if (keys.Any(m => m == key))
{
continue;
}
keys.Add(key);
leftNum--;
}
}
}
return keys.Skip(pageSize * pageOffset).Take(pageSize).ToList();
}
else
{
return _redis.GetServer(_redis.GetEndPoints().FirstOrDefault()).Keys(_dbIndex, pat, pageSize: pageSize, pageOffset: pageOffset).ToList();
}
}
19
Source : X86Assembly.cs
with MIT License
from 20chan
with MIT License
from 20chan
public static string GetCode(params object[] code)
{
string asmcode = "";
for (int i = 0; i < code.Length; i++)
{
if (!(code[i] is ASM))
if (!(code[i] is int))
if (!(code[i] is REG))
if (!(code[i] is MEM))
if (!(code[i] is string))
if (!(code[i] is Label))
if (!(code[i] is RawreplacedemblyCode))
throw new ArrayTypeMismatchException("Not supported type");
var cnt = InstructionPattern.CheckPattern(code, i);
if (cnt < 0)
throw new FormatException("Format error");
asmcode += $"{FromInline(code.Skip(i).Take(cnt + 1).ToArray())}\n";
i += cnt;
}
return asmcode;
}
19
Source : MainWindow.xaml.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void ButtonRestoreViewport_Click(object sender, RoutedEventArgs e)
{
string[] scoords = Properties.Settings.Default.ViewPortPos.Split(';');
try
{
IEnumerable<double> coords = scoords.Select(s => double.Parse(s));
viewport.Camera.Position = new Vector3(coords.Take(3).ToArray()).ToPoint3D();
viewport.Camera.LookDirection = new Vector3(coords.Skip(3).ToArray()).ToVector3D();
viewport.Camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1);
}
catch
{
ButtonResetViewport_Click(null, null);
}
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public WorkbookStream ReplaceRecord(BiffRecord oldRecord, BiffRecord newRecord)
{
if (ContainsRecord(oldRecord) == false)
{
throw new ArgumentException("Could not find oldRecord");
}
//records [r1, OLD, r2, r3, r4, r5]
//records.count = 6
//replaceRecordOffset = 1
//records.Take(1) = [r1]
//records.TakeLast(4) = [r2, r3, r4, r5]
//output = [r1, NEW, r2, r3, r4, r5]
var replaceRecordOffset = GetRecordOffset(oldRecord);
var newRecords = _biffRecords.Take(replaceRecordOffset).Append(newRecord)
.Concat(_biffRecords.TakeLast(_biffRecords.Count - (replaceRecordOffset + 1))).ToList();
return new WorkbookStream(newRecords);
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public long GetRecordByteOffset(BiffRecord record)
{
int listOffset = GetRecordOffset(record);
//Size of BiffRecord is 4 (header) + Length
return _biffRecords.Take(listOffset).Sum(r => r.Length + 4);
}
19
Source : FormulaHelper.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static List<string> BuildBase64PayloadMacros(byte[] shellcode)
{
List<string> base64Strings = new List<string>();
//Base64 expansion is 4/3, and we have 252 bytes to spend, so we can have 189 bytes / cell
//As an added bonus, 189 is always divisible by 3, so we won't have == padding.
int maxBytesPerCell = 189;
for (int offset = 0; offset < shellcode.Length; offset += maxBytesPerCell)
{
byte[] guidShellcode;
if (shellcode.Length - offset < maxBytesPerCell)
{
guidShellcode = shellcode.Skip(offset).ToArray();
}
else
{
guidShellcode = shellcode.Skip(offset).Take(maxBytesPerCell).ToArray();
}
base64Strings.Add(Convert.ToBase64String(guidShellcode));
}
base64Strings.Add("END");
return base64Strings;
}
19
Source : MacroPatterns.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static string ConvertA1StringToR1C1String(string cellFormula)
{
//Remap A1 style references to R1C1 (but ignore anything followed by a " in case its inside an EVALUATE statement)
string a1pattern = @"([A-Z]{1,2}\d{1,5})";
Regex rg = new Regex(a1pattern);
MatchCollection matches = rg.Matches(cellFormula);
int stringLenChange = 0;
//Iterate through each match and then replace it at its offset. We iterate through
//each case manually to prevent overlapping cases from double replacing - ex: SELECT(B1:B111,B1)
foreach (var match in matches)
{
string matchString = ((Match)match).Value;
string replaceContent = ExcelHelperClreplaced.ConvertA1ToR1C1(matchString);
//As we change the string, these indexes will go out of sync, track the size delta to make sure we resync positions
int matchIndex = ((Match)match).Index + stringLenChange;
//If the match is followed by a ", then ignore it
int followingIndex = matchIndex + matchString.Length;
if (followingIndex < cellFormula.Length && cellFormula[followingIndex] == '"')
{
continue;
}
//LINQ replacement for python string slicing
cellFormula = new string(cellFormula.Take(matchIndex).
Concat(replaceContent.ToArray()).
Concat(cellFormula.TakeLast(cellFormula.Length - matchIndex - matchString.Length)).ToArray());
stringLenChange += (replaceContent.Length - matchString.Length);
}
return cellFormula;
}
19
Source : MacroPatterns.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
private static string ImportCellFormula(string cellFormula)
{
if (cellFormula.Length == 0) return cellFormula;
string newCellFormula = cellFormula;
//Unescape the "s if we are looking at a CellFormula that has been escaped
if (newCellFormula.StartsWith('"'))
{
//Strip the outer quotes
newCellFormula = new string(newCellFormula.Skip(1).Take(newCellFormula.Length - 2).ToArray());
//Escape the inside content
newCellFormula = ExcelHelperClreplaced.UnescapeFormulaString(newCellFormula);
}
//Replace any uses of SELECT and ACTIVE.CELL with variable usage to better enable the sheet being hidden
//Mainly for use with importing EXCELntDonut macros
newCellFormula = ReplaceSelectActiveCellFormula(newCellFormula);
//FORMULA requires R1C1 strings
newCellFormula = ConvertA1StringToR1C1String(newCellFormula);
int charReplacements = 0;
//Remap CHAR() to actual bytes
for (int i = 1; i <= 255; i += 1)
{
int oldLength = newCellFormula.Length;
newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})&", i), "" + (char) i);
newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})", i), "" + (char)i);
//Update our poor heuristic for when we're getting a cell that is just CHAR()&CHAR()&CHAR()&CHAR()...
if (oldLength != newCellFormula.Length)
{
double lengthDelta = oldLength - newCellFormula.Length;
charReplacements += (int)Math.Floor(lengthDelta / 6.0);
}
}
//Arbitrary metric to determine if we should convert this to a string cell vs. formula cell
if (charReplacements > 3 && newCellFormula[0] == '=')
{
newCellFormula = new string(newCellFormula.Skip(1).ToArray());
//Excel cells will also check to see if we are a variable replacedignment cell:
//if we have valid variable letters before an =, it will process the replacedignment value
bool looksLikeVariablereplacedignment = LooksLikeVariablereplacedignment(newCellFormula);
//If we have a raw string content that starts with = or @, we can wrap this with ="" and it will work
//If the string content is already 255 bytes though, this won't work (FORMULA will fail trying to write the 258 byte string)
//If we're close to the limit then populate the cell with =CHAR(w/e)&Ref to cell with remainder of the content
if (newCellFormula.StartsWith('=') || newCellFormula.StartsWith('@') || looksLikeVariablereplacedignment)
{
//Need to make sure there's room for inserting 3 more characters =""
if (newCellFormula.Length >= 255 - 3)
{
//If this is a max length cell (common with 255 byte increments of shellcode)
//then mark the macro with a marker and we'll break it into two cells when we're building the sheet
return FormulaHelper.TOOLONGMARKER + newCellFormula;
}
else
{
newCellFormula = string.Format("=\"{0}\"", newCellFormula);
}
}
}
else
{
//TODO Use a proper logging package and log this as DEBUG info
// Console.WriteLine(newCellFormula);
}
if (newCellFormula.Length > 255)
{
throw new ArgumentException(string.Format("Imported Cell Formula is too long - length must be 255 or less:\n{0}", newCellFormula));
}
return newCellFormula;
}
19
Source : StringExtensions.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static List<String> SplitStringIntoChunks(this string str, int maxChunkSize)
{
List<string> chunks = new List<string>();
for (int offset = 0; offset < str.Length; offset += maxChunkSize)
{
int bytesRemaining = str.Length - offset;
int chunkSize = maxChunkSize;
if (chunkSize > bytesRemaining)
{
chunkSize = bytesRemaining;
}
chunks.Add(new string(str.Skip(offset).Take(chunkSize).ToArray()));
}
return chunks;
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public List<BiffRecord> GetRecordsForBOFRecord(BOF sheetBeginRecord)
{
var sheetRecords = _biffRecords.SkipWhile(r => r.Equals(sheetBeginRecord) == false).ToList();
int sheetSize = sheetRecords.TakeWhile(r => r.Id != RecordType.EOF).Count() + 1;
return sheetRecords.Take(sheetSize).ToList();
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public WorkbookStream RemoveRecord(BiffRecord recordToRemove)
{
if (ContainsRecord(recordToRemove) == false)
{
throw new ArgumentException("Could not find recordToRemove");
}
var removeRecordOffset = GetRecordOffset(recordToRemove);
var newRecords = _biffRecords.Take(removeRecordOffset).Concat(
_biffRecords.TakeLast(_biffRecords.Count - removeRecordOffset - 1)).ToList();
return new WorkbookStream(newRecords);
}
19
Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public WorkbookStream InsertRecords(List<BiffRecord> recordsToInsert, BiffRecord insertAfterRecord = null)
{
if (insertAfterRecord == null)
{
List<BiffRecord> recordsWithAppendedRecord = _biffRecords.Concat(recordsToInsert).ToList();
return new WorkbookStream(recordsWithAppendedRecord);
}
if (ContainsRecord(insertAfterRecord) == false)
{
throw new ArgumentException("Could not find insertAfterRecord");
}
var insertRecordOffset = GetRecordOffset(insertAfterRecord) + 1;
//records [r1, TARGET, r2, r3, r4, r5]
//records.count = 6
//insertRecordOffset = 2
//records.Take(2) = [r1, TARGET]
//records.TakeLast(4) = [r2, r3, r4, r5]
//output = [r1, TARGET, INSERT, r2, r3, r4, r5]
var newRecords = _biffRecords.Take(insertRecordOffset).Concat(recordsToInsert)
.Concat(_biffRecords.TakeLast(_biffRecords.Count - insertRecordOffset)).ToList();
return new WorkbookStream(newRecords);
}
19
Source : FormulaHelper.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static List<BiffRecord> ConvertMaxLengthStringToFormulas(string curString, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
{
string actualString =
new string(curString.Skip(FormulaHelper.TOOLONGMARKER.Length).ToArray());
string earlyString = new string(actualString.Take(16).ToArray());
string remainingString = new string(actualString.Skip(16).ToArray());
List<BiffRecord> formulas = new List<BiffRecord>();
int curRow = rwStart;
int curCol = colStart;
Random r = new Random();
int rndCol = r.Next(0x90, 0x9F);
int rndRw = r.Next(0xF000, 0xF800);
formulas.AddRange(ConvertStringToFormulas(remainingString, curRow, curCol, rndRw, rndCol, ixfe, packingMethod));
curRow += formulas.Count;
Cell remainderCell = new Cell(rndRw, rndCol);
List<Cell> createdCells = new List<Cell>();
//Create a formula string like
//"=CHAR(123)&CHAR(234)&CHAR(345)&R[RandomRw]C[RandomCol]";
//To split the 255 bytes into multiple cells - the first few bytes are CHAR() encoded, the remaining can be wrapped in ""s
string macroString = "=";
foreach (char c in earlyString)
{
macroString += string.Format("CHAR({0})&", Convert.ToUInt16(c));
}
macroString += string.Format("R{0}C{1}",rndRw + 1, rndCol + 1);
createdCells.Add(remainderCell);
List<BiffRecord> mainFormula = ConvertStringToFormulas(macroString, curRow, curCol, dstRw, dstCol, ixfe, packingMethod);
formulas.AddRange(mainFormula);
return formulas;
}
19
Source : CompletionList.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
static bool CamelCaseMatch(string text, string query)
{
// We take the first letter of the text regardless of whether or not it's upper case so we match
// against camelCase text as well as PascalCase text ("cct" matches "camelCaseText")
var theFirstLetterOfEachWord = text.Take(1).Concat(text.Skip(1).Where(char.IsUpper));
int i = 0;
foreach (var letter in theFirstLetterOfEachWord) {
if (i > query.Length - 1)
return true; // return true here for CamelCase partial match ("CQ" matches "CodeQualityreplacedysis")
if (char.ToUpperInvariant(query[i]) != char.ToUpperInvariant(letter))
return false;
i++;
}
if (i >= query.Length)
return true;
return false;
}
19
Source : CommitLogServer.cs
with MIT License
from abdullin
with MIT License
from abdullin
async Task HandleAsync(IConn conn) {
try {
using (conn) {
var req = await conn.Read(5.Sec());
switch (req) {
case DownloadRequest dr:
await conn.Write(_stored.Skip((int)dr.From).Take(dr.Count).ToList());
return;
case CommitRequest cr:
await _env.SimulateWork(5.Ms());
foreach (var e in cr.Events) {
_buffer.Enqueue(e);
}
ScheduleStore();
await conn.Write("OK");
return;
default:
conn.Write($"Unknown request {req}");
return;
}
}
} catch (Exception ex) {
_env.Debug($"Error: {ex.Message}");
}
}
19
Source : SimulatedHandUtils.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static void CalculateJointRotations(Handedness handedness, Vector3[] jointPositions, Quaternion[] jointOrientationsOut)
{
const int numFingers = 5;
int[] jointsPerFinger = { 4, 5, 5, 5, 5 }; // thumb, index, middle, right, pinky
for (int fingerIndex = 0; fingerIndex < numFingers; fingerIndex++)
{
int jointsCurrentFinger = jointsPerFinger[fingerIndex];
int lowIndex = (int)TrackedHandJoint.ThumbMetacarpalJoint + jointsPerFinger.Take(fingerIndex).Sum();
int highIndex = lowIndex + jointsCurrentFinger - 1;
for (int jointStartidx = lowIndex; jointStartidx <= highIndex; jointStartidx++)
{
// If we are at the lowIndex (metacarpals) use the wrist as the previous joint.
int jointEndidx = jointStartidx == lowIndex ? (int)TrackedHandJoint.Wrist : jointStartidx - 1;
Vector3 boneForward = jointPositions[jointStartidx] - jointPositions[jointEndidx];
Vector3 boneUp = Vector3.Cross(boneForward, GetPalmRightVector(handedness, jointPositions));
if (boneForward.magnitude > float.Epsilon && boneUp.magnitude > float.Epsilon)
{
Quaternion jointRotation = Quaternion.LookRotation(boneForward, boneUp);
// If we are the thumb, set the up vector to be from pinky to index (right hand) or index to pinky (left hand).
if (fingerIndex == 0)
{
// Rotate the thumb by 90 degrees (-90 if left hand) about thumb forward vector.
Quaternion rotateThumb90 = Quaternion.AngleAxis(handedness == Handedness.Left ? -90 : 90, boneForward);
jointRotation = rotateThumb90 * jointRotation;
}
jointOrientationsOut[jointStartidx] = jointRotation;
}
else
{
jointOrientationsOut[jointStartidx] = Quaternion.idenreplacedy;
}
}
}
jointOrientationsOut[(int)TrackedHandJoint.Palm] = Quaternion.LookRotation(GetPalmForwardVector(jointPositions), GetPalmUpVector(handedness, jointPositions));
}
19
Source : ExampleDescriptionFormattingConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var description = (string)value;
var result = string.Empty;
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var lines = description.Split(new[] { ". " }, StringSplitOptions.None).ToArray();
var sentences = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).ForEachDo(x => sentences.Add(x));
}
if (sentences.Any())
{
result = HighlightText(sentences.Select(x => x.Trim()).ToArray(), terms);
}
else
{
foreach (string sentence in lines.Take(2).Select(x => x.Trim()))
{
result = result + (sentence + ". ");
}
}
return result;
}
19
Source : ExampleSourceCodeFormattingConverter.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (MainWindowViewModel.SearchText.IsNullOrEmpty())
{
return string.Empty;
}
var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
var codeFiles = (Dictionary<string, string>) value;
var uiCodeFiles = codeFiles.Where(x => x.Key.EndsWith(".xaml"));
var lines = new List<string>();
foreach (var file in uiCodeFiles)
{
lines.AddRange(file.Value.Split(new[] {"\r\n"}, StringSplitOptions.None));
}
var toHighlight = new HashSet<string>();
foreach (var term in terms)
{
var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
containsTerm.Take(2).Select(x => x.Trim()).ForEachDo(x => toHighlight.Add(x));
}
string result;
if (toHighlight.Any())
{
lines = toHighlight.Take(2).Select(x => x.Trim().Replace('<', ' ').Replace('>', ' ') + '.').ToList();
result = HighlightText(lines, terms);
}
else
{
var sentences = lines.Take(2).Select(x => string.Format("... {0} ...", x.Trim().Replace('<', ' ').Replace('>', ' ').ToList()));
result = string.Join("\n", sentences);
}
return result;
}
19
Source : EndlessItemsControl.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void AddMoreItems()
{
var isBusy = (bool)GetValue(IsBusyProperty);
if (!isBusy)
{
SetValue(IsBusyProperty, true);
SetValue(IsBusyProperty, false);
SetValue(IsBusyProperty, true);
var delay = (TimeSpan)GetValue(PreLoadingDelayProperty);
Task.Factory.StartNew(() =>
{
Thread.Sleep(delay);
var items = _allItems.Take(10).ToList();
items.ForEach(item =>
{
Dispatcher.BeginInvoke(new Action(() => Currenreplacedems.Add(item)));
_allItems.Remove(item);
});
}).ContinueWith(_ =>
{
Dispatcher.BeginInvoke(new Action(() => SetValue(IsBusyProperty, false)));
});
}
}
19
Source : EndlessItemsControl.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void RefhrereplacedemsSource(List<object> newItems)
{
var startCapacity = (int)GetValue(StartCapacityProperty);
_allItems = newItems;
Currenreplacedems = new ObservableCollection<object>(_allItems.Take(startCapacity));
_allItems.Take(startCapacity).ToList().ForEach(item => _allItems.Remove(item));
var binding = new Binding
{
Path = new PropertyPath("Currenreplacedems"),
Source = this,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
};
SetBinding(ItemsSourceProperty, binding);
}
19
Source : Wave.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void ReadData(Stream stream)
{
var binaryWriter = new BinaryWriter(stream);
binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));
uint filesize = (uint)(Data.Length + 36); // 36 is added for all the extra we're adding for the WAV header format
binaryWriter.Write(filesize);
binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("WAVE"));
binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("fmt"));
binaryWriter.Write((byte)0x20); // Null ending to the fmt
binaryWriter.Write((int)0x10); // 16 ... length of all the above
// AC audio headers start at Format Type,
// and are usually 18 bytes, with some exceptions
// notably objectID A000393 which is 30 bytes
// WAV headers are always 16 bytes from Format Type to end of header,
// so this extra data is truncated here.
binaryWriter.Write(Header.Take(16).ToArray());
binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("data"));
binaryWriter.Write((uint)Data.Length);
binaryWriter.Write(Data);
}
19
Source : TerrainBatch.cs
with GNU General Public License v3.0
from ACEmulator
with GNU General Public License v3.0
from ACEmulator
public void AddCell(List<LandVertex> vertices, int polyIdx)
{
Vertices.AddRange(vertices.Skip(polyIdx * 3).Take(6));
}
19
Source : SuppressionFileIOTests.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
[Fact]
public void CheckSuppressionMessageConversion_FromXml()
{
var xElement = GetXElementsToCheck().Take(1).Single();
var target = xElement.Element("target").Value;
var syntaxNode = xElement.Element("syntaxNode").Value;
var messageToCheck = SuppressMessage.MessageFromElement(xElement);
messageToCheck.Should().NotBeNull();
messageToCheck.Value.Id.Should().Be(xElement.Attribute("id").Value);
messageToCheck.Value.Target.Should().Be(target);
messageToCheck.Value.SyntaxNode.Should().Be(syntaxNode);
}
19
Source : SuppressionFileIOTests.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
[Fact]
public void CheckSuppressionMessageConversion_ToXml()
{
var expectedXElement = GetXElementsToCheck().Take(1).Single();
var message = new SuppressMessage(id: "PX1001",
target: @"PX.Objects.CS.Email.ExchangeBaseLogicSyncCommand<GraphType, TPrimary, ExchangeType>.Uploader",
syntaxNode: @"new UploadFileMaintenance()");
var xElement = message.ToXml();
xElement.Should().NotBeNull();
xElement.Should().Be(expectedXElement);
}
19
Source : Helpers.cs
with MIT License
from ad313
with MIT License
from ad313
public static List<List<T>> SplitList<T>(List<T> list, int length)
{
if (list == null || list.Count <= 0 || length <= 0)
{
return new List<List<T>>();
}
var result = new List<List<T>>();
var count = list.Count / length;
count += list.Count % length > 0 ? 1 : 0;
for (var i = 0; i < count; i++)
{
result.Add(list.Skip(i * length).Take(length).ToList());
}
return result;
}
19
Source : Repository.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log)
{
var commit = this.head;
if (commit == null)
{
var version = new Version(defaultPreReleasePhase);
log.Info($"No commits found. Using default version {version}.");
return version;
}
var tagsAndVersions = this.tags
.Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix)))
.OrderBy(tagAndVersion => tagAndVersion.Item2)
.ThenBy(tagsAndVersion => tagsAndVersion.tag.Name)
.ToList();
var commitsChecked = new HashSet<string>();
var count = 0;
var height = 0;
var candidates = new List<Candidate>();
var commitsToCheck = new Stack<(Commit, int, Commit)>();
Commit previousCommit = null;
if (log.IsTraceEnabled)
{
log.Trace($"Starting at commit {commit.ShortSha} (height {height})...");
}
while (true)
{
var parentCount = 0;
if (commitsChecked.Add(commit.Sha))
{
++count;
var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList();
var foundVersion = false;
foreach (var (tag, commitVersion) in commitTagsAndVersions)
{
var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, Index = candidates.Count };
foundVersion = foundVersion || candidate.Version != null;
if (log.IsTraceEnabled)
{
log.Trace($"Found {(candidate.Version == null ? "non-" : null)}version tag {candidate}.");
}
candidates.Add(candidate);
}
if (!foundVersion)
{
if (log.IsTraceEnabled)
{
var parentIndex = 0;
Commit firstParent = null;
foreach (var parent in commit.Parents)
{
switch (parentIndex)
{
case 0:
firstParent = parent;
break;
case 1:
log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:");
log.Trace($"- {firstParent.ShortSha} (height {height + 1})");
goto default;
default:
log.Trace($"- {parent.ShortSha} (height {height + 1})");
break;
}
++parentIndex;
parentCount = parentIndex;
}
}
foreach (var parent in ((IEnumerable<Commit>)commit.Parents).Reverse())
{
commitsToCheck.Push((parent, height + 1, commit));
}
if (commitsToCheck.Count == 0 || commitsToCheck.Peek().Item2 <= height)
{
var candidate = new Candidate { Commit = commit, Height = height, Tag = null, Version = new Version(defaultPreReleasePhase), Index = candidates.Count };
if (log.IsTraceEnabled)
{
log.Trace($"Found root commit {candidate}.");
}
candidates.Add(candidate);
}
}
}
else
{
if (log.IsTraceEnabled)
{
log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path.");
}
}
if (commitsToCheck.Count == 0)
{
break;
}
if (log.IsTraceEnabled)
{
previousCommit = commit;
}
var oldHeight = height;
Commit child;
(commit, height, child) = commitsToCheck.Pop();
if (log.IsTraceEnabled)
{
if (parentCount > 1)
{
log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})...");
}
else if (height <= oldHeight)
{
if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height)
{
log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})...");
}
else
{
log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})...");
}
}
}
}
log.Debug($"{count:N0} commits checked.");
var orderedCandidates = candidates.OrderBy(candidate => candidate.Version).ThenByDescending(candidate => candidate.Index).ToList();
var tagWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Tag?.Length ?? 2) : 0;
var versionWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Version?.ToString().Length ?? 4) : 0;
var heightWidth = log.IsDebugEnabled ? orderedCandidates.Max(candidate => candidate.Height).ToString(CultureInfo.CurrentCulture).Length : 0;
if (log.IsDebugEnabled)
{
foreach (var candidate in orderedCandidates.Take(orderedCandidates.Count - 1))
{
log.Debug($"Ignoring {candidate.ToString(tagWidth, versionWidth, heightWidth)}.");
}
}
var selectedCandidate = orderedCandidates.Last();
if (selectedCandidate.Tag == null)
{
log.Info($"No commit found with a valid SemVer 2.0 version{(tagPrefix == null ? null : $" prefixed with '{tagPrefix}'")}. Using default version {selectedCandidate.Version}.");
}
log.Info($"Using{(log.IsDebugEnabled && orderedCandidates.Count > 1 ? " " : " ")}{selectedCandidate.ToString(tagWidth, versionWidth, heightWidth)}.");
return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase);
}
19
Source : POGeneratorTest.cs
with MIT License
from adams85
with MIT License
from adams85
private void Generate_LineBreak_Core(string id, params string[] lines)
{
var generator = new POGenerator(new POGeneratorSettings
{
IgnoreEncoding = true,
SkipInfoHeaders = true,
});
var catalog = new POCatalog { Encoding = "UTF-8" };
var entry = new POSingularEntry(new POKey(id));
catalog.Add(entry);
var sb = new StringBuilder();
generator.Generate(sb, catalog);
var expected = new List<string>();
expected.Add(@"msgid """"");
expected.AddRange(lines);
expected.Add(@"msgstr """"");
IEnumerable<string> actual = sb.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None).Skip(5).Take(lines.Length + 2);
replacedert.Equal(expected, actual);
}
19
Source : FactorPairCollection.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public string ToString(int take)
{
return string.Join("\t", this.Take(take).Select(factr => factr.ToString()));
}
19
Source : GaussianRow.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public void ResizeRationalPart(int size)
{
RationalPart = RationalPart.Take(size + 1).ToList();
}
19
Source : GaussianRow.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public void ResizeAlgebraicPart(int size)
{
AlgebraicPart = AlgebraicPart.Take(size + 1).ToList();
}
19
Source : GaussianRow.cs
with GNU General Public License v3.0
from AdamWhiteHat
with GNU General Public License v3.0
from AdamWhiteHat
public void ResizeQuadraticPart(int size)
{
QuadraticPart = QuadraticPart.Take(size + 1).ToList();
}
19
Source : Deserializer.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static Guid GetGuid(byte[] data, int index)
=> new Guid(data.Skip(index).Take(16).ToArray());
19
Source : TestCollectionViewComponent.cs
with MIT License
from adospace
with MIT License
from adospace
public override VisualNode Render()
{
return new RxContentPage()
{
new RxStackLayout()
{
new RxButton("SWITCH SMALL/LARGE LIST")
.OnClick(this.OnShowHideLargeList),
new RxCollectionView<Monkey>()
{
Header = RenderHeader(),
Footer = RenderFooter()
}
.RenderCollection(
_largePersonListVisible ? _allMonkeys : _allMonkeys.Take(4),
RenderMonkey)
.VFillAndExpand()
}
.HFillAndExpand()
.VFillAndExpand()
};
}
19
Source : FetchXmlPostFilterPaginator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IEnumerable<Enreplacedy> Select(int offset, int limit)
{
if (offset % limit != 0)
{
throw new ArgumentException("limit value must be a factor of offset");
}
var items = new List<Enreplacedy>();
Select(0, (offset + limit) * _initialLimitMultiple, offset + limit, items);
return items.Skip(offset).Take(limit).ToArray();
}
19
Source : PostFilterPaginator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public IEnumerable<T> Select(int offset, int limit)
{
var items = new List<T>();
Select(0, (offset + limit) * _initialLimitMultiple, offset + limit, items);
return items.Skip(offset).Take(limit).ToArray();
}
19
Source : TopPaginator.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public Page GetPage(int pageNumber)
{
var items = new List<T>();
var totalUnfilteredItems = Gereplacedems(
((_pageSize * pageNumber) * _initialSearchLimitMultiple),
0,
(_pageSize * pageNumber),
items);
var itemOffset = (pageNumber - 1) * _pageSize;
var pageItems = items.Skip(itemOffset).Take(_pageSize).ToList();
return new Page(pageItems, totalUnfilteredItems, pageNumber, _pageSize);
}
19
Source : BufferedPageReaderWriter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void WriteBytes(byte[] source, int offset, int length)
{
var range = source.Skip(offset).Take(length).ToArray();
foreach (byte @byte in range)
{
this.WriteByte(@byte);
}
}
19
Source : CrmEntityIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual ICrmEnreplacedySearchResultPage GenerateResultPage(ICollection<ICrmEnreplacedySearchResult> results, int approximateTotalHits, int pageNumber, int pageSize, RawSearchResultSet rawSearchResultSet)
{
var resultOffset = (pageNumber - 1) * pageSize;
var pageResults = results.Skip(resultOffset).Take(pageSize).ToList();
return new CrmEnreplacedySearchResultPage(pageResults, approximateTotalHits, pageNumber, pageSize);
}
19
Source : CrmEntityIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected ICrmEnreplacedySearchResultPage GetUserSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int initialOffset, int resultLimit, ICrmEnreplacedySearchResultFactory resultFactory, int pageNumber, int pageSize, ICollection<ICrmEnreplacedySearchResult> results)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("(searchLimit={0},rawOffset={1},resultLimit={2})", searchLimit, initialOffset, resultLimit));
RawSearchResultSet rawSearchResults = GetRawSearchResults(query, searchLimit, initialOffset);
if (initialOffset >= rawSearchResults.TotalHits)
{
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
var stopwatch = new Stopwatch();
stopwatch.Start();
var groupedNotes = new List<IGrouping<EnreplacedyReference, ICrmEnreplacedySearchResult>>();
var displayNotes = IsAnnotationSearchEnabled();
if (displayNotes && !string.IsNullOrEmpty(query.QueryTerm))
{
var rawNotes = this.GetRelatedAnnotations(rawSearchResults, query);
var notes =
rawNotes.Select(doreplacedent => resultFactory.GetResult(doreplacedent, 1, results.Count + 1)).ToList();
//Grouping Notes by related Knowledge Articles
groupedNotes =
notes.Where(note => note.EnreplacedyLogicalName == "annotation")
.GroupBy(note => note.Enreplacedy.GetAttributeValue<EnreplacedyReference>("objectid"))
.ToList();
}
var offsetForNexreplacederation = initialOffset;
foreach (var scoreDoc in rawSearchResults.Results)
{
offsetForNexreplacederation++;
var result = resultFactory.GetResult(_searcher.Doc(scoreDoc.Doc), scoreDoc.Score, results.Count + 1);
// Not a valid user result, filter out
if (result == null)
{
continue;
}
if (result.EnreplacedyLogicalName == "knowledgearticle" && displayNotes)
{
var relatedNotes = groupedNotes.Where(a => a.Key.Id == result.EnreplacedyID).SelectMany(i => i).Take(3).ToList();
if (relatedNotes.Any(note => note.Fragment == result.Fragment))
{
result.Fragment = GetKnowledgeArticleDescription(result);
}
result.Enreplacedy["relatedNotes"] = relatedNotes;
}
results.Add(result);
if (results.Count >= resultLimit)
{
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
}
stopwatch.Stop();
// We asked for more hits than we got back from Lucene, and we still didn't gather enough valid
// results. That's all we're going to get, so the number of results we got is the number of hits.
if (searchLimit >= rawSearchResults.TotalHits)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, results.Count, pageNumber, pageSize, rawSearchResults);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GetUserSearchResults(query, searchLimit * ExtendedSearchLimitMultiple, offsetForNexreplacederation, resultLimit, resultFactory, pageNumber, pageSize, results);
}
19
Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override ICrmEnreplacedySearchResultPage GenerateResultPage(ICollection<ICrmEnreplacedySearchResult> results, int approximateTotalHits, int pageNumber, int pageSize, RawSearchResultSet rawSearchResultSet)
{
var resultOffset = (pageNumber - 1) * pageSize;
var pageResults = results.Skip(resultOffset).Take(pageSize).ToList();
return new CrmEnreplacedySearchResultPage(pageResults, approximateTotalHits, pageNumber, pageSize, rawSearchResultSet.FacetViews, rawSearchResultSet.SortingOptions);
}
19
Source : EnumerableFilters.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static object Paginate(object input, int index, int count)
{
var blogPostsDrop = input as BlogPostsDrop;
if (blogPostsDrop != null)
{
return BlogFunctions.Paginate(blogPostsDrop, index, count);
}
var forumThreadsDrop = input as ForumThreadsDrop;
if (forumThreadsDrop != null)
{
return ForumFunctions.Paginate(forumThreadsDrop, index, count);
}
var forumPostsDrop = input as ForumPostsDrop;
if (forumPostsDrop != null)
{
return ForumFunctions.Paginate(forumPostsDrop, index, count);
}
var enumerable = input as IEnumerable;
if (enumerable != null)
{
return enumerable.Cast<object>().Skip(index).Take(count);
}
return input;
}
19
Source : EnumerableFilters.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static object Take(object input, int count)
{
var blogPostsDrop = input as BlogPostsDrop;
if (blogPostsDrop != null)
{
return BlogFunctions.Take(blogPostsDrop, count);
}
var forumThreadsDrop = input as ForumThreadsDrop;
if (forumThreadsDrop != null)
{
return ForumFunctions.Take(forumThreadsDrop, count);
}
var forumPostsDrop = input as ForumPostsDrop;
if (forumPostsDrop != null)
{
return ForumFunctions.Take(forumPostsDrop, count);
}
var enumerable = input as IEnumerable;
if (enumerable != null)
{
return enumerable.Cast<object>().Take(count);
}
return input;
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<TResult> BatchIterator<TSource, TResult>(this IEnumerable<TSource> source, int size, Func<IEnumerable<TSource>, TResult> @select)
{
TSource[] parreplacedion = null;
var count = 0;
foreach (var item in source)
{
if (parreplacedion == null)
{
parreplacedion = new TSource[size];
}
parreplacedion[count++] = item;
if (count != size)
{
continue;
}
yield return @select(parreplacedion.Select(x => x));
parreplacedion = null;
count = 0;
}
// Return the last bucket with whatever elements are left.
if (parreplacedion != null && count > 0)
{
yield return @select(parreplacedion.Take(count));
}
}
19
Source : TagAutoCompleteHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public void ProcessRequest(HttpContext context)
{
var prefix = context.Request.QueryString[TagNameQueryStringField];
if (string.IsNullOrEmpty(prefix))
{
return;
}
int maxResults = int.TryParse(context.Request.QueryString[MaxResultsQueryStringField], out maxResults)
? maxResults
: MaxResultsDefault;
var completions = GetTagNameCompletions(prefix);
if (completions.Count() > maxResults)
{
completions = completions.Take(maxResults);
}
foreach (var completion in completions)
{
context.Response.Write(completion + Environment.NewLine);
}
}
19
Source : EmbeddedResourceAssemblyAttribute.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private string ConvertVirtualPathToResourceName(string virtualPath)
{
// converting an entire path
// for all parts: prepend an '_' if the name starts with a numeric character
// replace all '/' or '\\' with '.'
// prepend the default namespace
// besides a leading underscore, filenames remain unchanged
var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);
if (parts.Any())
{
var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName);
var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_');
var tail = partsWithUnderscores.Last();
return "{0}.{1}".FormatWith(head, tail);
}
return null;
}
19
Source : SetupController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string ToErrorMessage(Exception exception)
{
return string.Join(" ", ToExceptionPath(exception).Select(e => e.Message).Take(5).ToArray());
}
See More Examples