Here are the examples of the csharp api System.Collections.Generic.List.AsReadOnly() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
966 Examples
19
View Source File : HeifEncoderParameterFactory.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
private static unsafe HeifIntegerEncoderParameter CreateIntegerParameter(SafeHeifEncoder encoder,
heif_encoder_parameter nativeParameter,
string name,
bool hasDefaultValue)
{
int defaultValue = 0;
if (hasDefaultValue)
{
// The error value is ignored because some encoders return an error
// when getting the value of a valid command.
_ = LibHeifNative.heif_encoder_get_parameter_integer(encoder, name, out defaultValue);
}
bool haveMinimumMaximum;
int minimum = 0;
int maximum = 0;
var validValues = new List<int>();
if (LibHeifVersion.Is1Point10OrLater)
{
var error = LibHeifNative.heif_encoder_parameter_get_valid_integer_values(nativeParameter,
out bool haveMinimum,
out bool haveMaximum,
ref minimum,
ref maximum,
out int numValidValues,
out var validValuesArray);
error.ThrowIfError();
haveMinimumMaximum = haveMinimum && haveMaximum;
if (numValidValues > 0 && validValuesArray != IntPtr.Zero)
{
validValues.Capacity = numValidValues;
int* integerArray = (int*)validValuesArray;
for (int i = 0; i < numValidValues; i++)
{
validValues.Add(integerArray[i]);
}
}
}
else
{
var error = LibHeifNative.heif_encoder_parameter_get_valid_integer_range(nativeParameter,
out haveMinimumMaximum,
ref minimum,
ref maximum);
error.ThrowIfError();
}
return new HeifIntegerEncoderParameter(name,
hasDefaultValue,
defaultValue,
haveMinimumMaximum,
minimum,
maximum,
validValues.AsReadOnly());
}
19
View Source File : OutputStringArray.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public unsafe ReadOnlyCollection<string> ToReadOnlyCollection()
{
var items = new List<string>();
if (this.arrayPointer != IntPtr.Zero)
{
var stringMemoryAdddress = (IntPtr*)this.arrayPointer;
while (*stringMemoryAdddress != IntPtr.Zero)
{
items.Add(Marshal.PtrToStringAnsi(*stringMemoryAdddress));
stringMemoryAdddress++;
}
}
return items.AsReadOnly();
}
19
View Source File : HeifEncoder.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
private unsafe ReadOnlyCollection<IHeifEncoderParameter> GetEncoderParameterList()
{
var encoderParameters = new List<IHeifEncoderParameter>();
var parameterList = LibHeifNative.heif_encoder_list_parameters(this.encoder);
if (parameterList.Value != IntPtr.Zero)
{
var encoderParameter = (heif_encoder_parameter*)parameterList.Value;
while (*encoderParameter != heif_encoder_parameter.Null)
{
encoderParameters.Add(HeifEncoderParameterFactory.Create(this.encoder, *encoderParameter));
encoderParameter++;
}
}
return encoderParameters.AsReadOnly();
}
19
View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public ReadOnlyCollection<SimulatedMouseInput> GetSimulatInputX()
{
var magnitudes = new List<SimulatedMouseInput>();
foreach (var slowMovement in SlowMovements)
{
var ceil = (int)Math.Ceiling(slowMovement);
var timeFactor = ceil / slowMovement;
SimulatedMouseInput mouseInputData;
mouseInputData.x = ceil;
mouseInputData.y = 0;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = Velocity(ceil, 0, mouseInputData.time);
mouseInputData.angle = 0;
magnitudes.Add(mouseInputData);
}
for (double i = 5; i < MaxVelocity; i+=Increment)
{
SimulatedMouseInput mouseInputData;
var ceil = (int)Math.Ceiling(i);
var timeFactor = ceil / i;
mouseInputData.x = ceil;
mouseInputData.y = 0;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(ceil, 0, mouseInputData.time));
mouseInputData.angle = 0;
magnitudes.Add(mouseInputData);
}
return magnitudes.AsReadOnly();
}
19
View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public ReadOnlyCollection<SimulatedMouseInput> GetSimulatedInputY()
{
var magnitudes = new List<SimulatedMouseInput>();
foreach (var slowMovement in SlowMovements)
{
var ceil = (int)Math.Ceiling(slowMovement);
var timeFactor = ceil / slowMovement;
SimulatedMouseInput mouseInputData;
mouseInputData.x = 0;
mouseInputData.y = ceil;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(0, ceil, mouseInputData.time));
mouseInputData.angle = 0;
magnitudes.Add(mouseInputData);
}
for (double i = 5; i < MaxVelocity; i+=Increment)
{
SimulatedMouseInput mouseInputData;
var ceil = (int)Math.Ceiling(i);
var timeFactor = ceil / i;
mouseInputData.x = 0;
mouseInputData.y = ceil;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(0, ceil, mouseInputData.time));
mouseInputData.angle = Math.PI / 2;
magnitudes.Add(mouseInputData);
}
return magnitudes.AsReadOnly();
}
19
View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public IReadOnlyCollection<IReadOnlyCollection<SimulatedMouseInput>> GetSimulatedDirectionalInput()
{
var magnitudesByAngle = new List<IReadOnlyCollection<SimulatedMouseInput>>();
foreach (var angle in Angles)
{
var magnitudes = new List<SimulatedMouseInput>();
foreach (var slowMoveMagnitude in SlowMovements)
{
magnitudes.Add(SimulateAngledInput(angle, slowMoveMagnitude));
}
for (double magnitude = 5; magnitude < MaxVelocity; magnitude+=Increment)
{
magnitudes.Add(SimulateAngledInput(angle, magnitude));
}
magnitudesByAngle.Add(magnitudes.AsReadOnly());
}
return magnitudesByAngle.AsReadOnly();
}
19
View Source File : AccelCalculator.cs
License : MIT License
Project Creator : a1xd
License : MIT License
Project Creator : a1xd
public ReadOnlyCollection<SimulatedMouseInput> GetSimulatedInput()
{
var magnitudes = new List<SimulatedMouseInput>();
foreach (var slowMoveX in SlowMovements)
{
var slowMoveY = 0.0;
var ceilX = (int)Math.Round(slowMoveX*50);
var ceilY = (int)Math.Round(slowMoveY*50);
var ceilMagnitude = Magnitude(ceilX, ceilY);
var timeFactor = ceilMagnitude / Magnitude(slowMoveX, slowMoveY);
SimulatedMouseInput mouseInputData;
mouseInputData.x = ceilX;
mouseInputData.y = ceilY;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(ceilX, ceilY, mouseInputData.time));
mouseInputData.angle = Math.Atan2(ceilY, ceilX);
magnitudes.Add(mouseInputData);
}
for (double i = 5; i < MaxVelocity; i+=Increment)
{
SimulatedMouseInput mouseInputData;
var ceil = (int)Math.Ceiling(i);
var timeFactor = ceil / i;
mouseInputData.x = ceil;
mouseInputData.y = 0;
mouseInputData.time = MeasurementTime * timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(ceil, 0, mouseInputData.time));
mouseInputData.angle = Math.Atan2(ceil, 0);
magnitudes.Add(mouseInputData);
}
magnitudes.Sort((m1, m2) => m1.velocity.CompareTo(m2.velocity));
return magnitudes.AsReadOnly();
}
19
View Source File : ServerInformation.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public ModelInfo GetInfo(ModelInt packet, ServiceContext context)
{
lock (context.Player)
{
switch (packet.Value)
{
case (long)ServerInfoType.Full:
{
var result = GetModelInfo(context.Player);
return result;
}
case (long)ServerInfoType.SendSave:
{
if (context.PossiblyIntruder)
{
context.Disconnect("Possibly intruder");
return null;
}
var result = new ModelInfo();
//передача файла игры, для загрузки WorldLoad();
// файл передать можно только в том случае если файлы прошли проверку
//!Для Pvp проверка нужна всегда, в PvE нет
if (ServerManager.ServerSettings.IsModsWhitelisted)
{
if ((int)context.Player.ApproveLoadWorldReason > 0)
{
context.Player.ExitReason = DisconnectReason.FilesMods;
Loger.Log($"Login : {context.Player.Public.Login} not all files checked,{context.Player.ApproveLoadWorldReason.ToString() } Disconnect");
result.SaveFileData = null;
return result;
}
}
result.SaveFileData = Repository.GetSaveData.LoadPlayerData(context.Player.Public.Login, 1);
if (result.SaveFileData != null)
{
if (context.Player.MailsConfirmationSave.Count > 0)
{
for (int i = 0; i < context.Player.MailsConfirmationSave.Count; i++)
context.Player.MailsConfirmationSave[i].NeedSaveGame = false;
Loger.Log($"MailsConfirmationSave add {context.Player.MailsConfirmationSave.Count} (mails={context.Player.Mails.Count})");
//Ого! Игрок не сохранился после приема письма, с обязательным сохранением после получения
//Отправляем письма ещё раз
if (context.Player.Mails.Count == 0)
{
context.Player.Mails = context.Player.MailsConfirmationSave.ToList();
}
else
{
var ms = context.Player.MailsConfirmationSave
.Where(mcs => context.Player.Mails.Any(m => m.GetHashBase() != mcs.GetHashBase()))
.ToList();
context.Player.Mails.AddRange(ms);
}
Loger.Log($"MailsConfirmationSave (mails={context.Player.Mails.Count})");
}
}
Loger.Log($"Load World for {context.Player.Public.Login}. (mails={context.Player.Mails.Count}, fMails={context.Player.FunctionMails.Count})");
return result;
}
case (long)ServerInfoType.FullWithDescription:
{
var result = GetModelInfo(context.Player);
//result.Description = "";
var displayAttributes = new List<Tuple<int, string>>();
foreach (var prop in typeof(ServerSettings).GetFields())
{
var attribute = prop.GetCustomAttributes(typeof(DisplayAttribute)).FirstOrDefault();
if (attribute is null || !prop.IsPublic)
{
continue;
}
var dispAtr = (DisplayAttribute)attribute;
var strvalue = string.IsNullOrEmpty(dispAtr.GetDescription()) ? prop.Name : dispAtr.GetDescription();
strvalue = strvalue + "=" + prop.GetValue(ServerManager.ServerSettings).ToString();
var order = dispAtr.GetOrder().HasValue ? dispAtr.GetOrder().Value : 0;
displayAttributes.Add(Tuple.Create(order, strvalue));
}
var sb = new StringBuilder();
var sorte = new List<string>(displayAttributes.OrderBy(x => x.Item1).Select(y => y.Item2)).AsReadOnly();
foreach (var prop in sorte)
{
sb.AppendLine(prop);
}
//result.Description = sb.ToString();
return result;
}
case (long)ServerInfoType.Short:
default:
{
// краткая (зарезервированно, пока не используется) fullInfo = false
var result = new ModelInfo();
return result;
}
}
}
}
19
View Source File : TextSegmentCollection.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public ReadOnlyCollection<T> FindOverlappingSegments(int offset, int length)
{
ThrowUtil.CheckNotNegative(length, "length");
List<T> results = new List<T>();
if (root != null) {
FindOverlappingSegments(results, root, offset, offset + length);
}
return results.AsReadOnly();
}
19
View Source File : FoldingManager.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset)
{
List<FoldingSection> result = new List<FoldingSection>();
FoldingSection fs = foldings.FindFirstSegmentWithStartAfter(startOffset);
while (fs != null && fs.StartOffset == startOffset) {
result.Add(fs);
fs = foldings.GetNextSegment(fs);
}
return result.AsReadOnly();
}
19
View Source File : VisualLine.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
internal void ConstructVisualElements(ITextRunConstructionContext context, VisualLineElementGenerator[] generators)
{
Debug.replacedert(phase == LifetimePhase.Generating);
foreach (VisualLineElementGenerator g in generators) {
g.StartGeneration(context);
}
elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (VisualLineElementGenerator g in generators) {
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in elements) {
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = elements.AsReadOnly();
CalculateOffsets();
phase = LifetimePhase.Transforming;
}
19
View Source File : VisualLine.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
internal void SetTextLines(List<TextLine> textLines)
{
this.textLines = textLines.AsReadOnly();
Height = 0;
foreach (TextLine line in textLines)
Height += line.Height;
}
19
View Source File : BaseDataProviderAccessCoreSystem.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public virtual IReadOnlyList<IMixedRealityDataProvider> GetDataProviders()
{
return dataProviders.AsReadOnly();
}
19
View Source File : OVRSkeleton.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void Awake()
{
if (_dataProvider == null)
{
_dataProvider = GetComponent<IOVRSkeletonDataProvider>();
}
_bones = new List<OVRBone>();
Bones = _bones.AsReadOnly();
_bindPoses = new List<OVRBone>();
BindPoses = _bindPoses.AsReadOnly();
_capsules = new List<OVRBoneCapsule>();
Capsules = _capsules.AsReadOnly();
}
19
View Source File : OVRSkeleton.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
virtual protected void InitializeBones(OVRPlugin.Skeleton skeleton)
{
_bones = new List<OVRBone>(new OVRBone[skeleton.NumBones]);
Bones = _bones.AsReadOnly();
if (!_bonesGO)
{
_bonesGO = new GameObject("Bones");
_bonesGO.transform.SetParent(transform, false);
_bonesGO.transform.localPosition = Vector3.zero;
_bonesGO.transform.localRotation = Quaternion.idenreplacedy;
}
// pre-populate bones list before attempting to apply bone hierarchy
for (int i = 0; i < skeleton.NumBones; ++i)
{
BoneId id = (OVRSkeleton.BoneId)skeleton.Bones[i].Id;
short parentIdx = skeleton.Bones[i].ParentBoneIndex;
Vector3 pos = skeleton.Bones[i].Pose.Position.FromFlippedXVector3f();
Quaternion rot = skeleton.Bones[i].Pose.Orientation.FromFlippedXQuatf();
var boneGO = new GameObject(id.ToString());
boneGO.transform.localPosition = pos;
boneGO.transform.localRotation = rot;
_bones[i] = new OVRBone(id, parentIdx, boneGO.transform);
}
for (int i = 0; i < skeleton.NumBones; ++i)
{
if (((OVRPlugin.BoneId)skeleton.Bones[i].ParentBoneIndex) == OVRPlugin.BoneId.Invalid)
{
_bones[i].Transform.SetParent(_bonesGO.transform, false);
}
else
{
_bones[i].Transform.SetParent(_bones[_bones[i].ParentBoneIndex].Transform, false);
}
}
}
19
View Source File : OVRSkeleton.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void InitializeBindPose(OVRPlugin.Skeleton skeleton)
{
_bindPoses = new List<OVRBone>(new OVRBone[skeleton.NumBones]);
BindPoses = _bindPoses.AsReadOnly();
if (!_bindPosesGO)
{
_bindPosesGO = new GameObject("BindPoses");
_bindPosesGO.transform.SetParent(transform, false);
_bindPosesGO.transform.localPosition = Vector3.zero;
_bindPosesGO.transform.localRotation = Quaternion.idenreplacedy;
}
for (int i = 0; i < skeleton.NumBones; ++i)
{
BoneId id = (OVRSkeleton.BoneId)skeleton.Bones[i].Id;
short parentIdx = skeleton.Bones[i].ParentBoneIndex;
var bindPoseGO = new GameObject(id.ToString());
OVRBone bone = _bones[i];
if (bone.Transform != null)
{
bindPoseGO.transform.localPosition = bone.Transform.localPosition;
bindPoseGO.transform.localRotation = bone.Transform.localRotation;
}
_bindPoses[i] = new OVRBone(id, parentIdx, bindPoseGO.transform);
}
for (int i = 0; i < skeleton.NumBones; ++i)
{
if (((OVRPlugin.BoneId)skeleton.Bones[i].ParentBoneIndex) == OVRPlugin.BoneId.Invalid)
{
_bindPoses[i].Transform.SetParent(_bindPosesGO.transform, false);
}
else
{
_bindPoses[i].Transform.SetParent(_bindPoses[_bones[i].ParentBoneIndex].Transform, false);
}
}
}
19
View Source File : OVRSkeleton.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void InitializeCapsules(OVRPlugin.Skeleton skeleton)
{
if (_enablePhysicsCapsules)
{
_capsules = new List<OVRBoneCapsule>(new OVRBoneCapsule[skeleton.NumBoneCapsules]);
Capsules = _capsules.AsReadOnly();
if (!_capsulesGO)
{
_capsulesGO = new GameObject("Capsules");
_capsulesGO.transform.SetParent(transform, false);
_capsulesGO.transform.localPosition = Vector3.zero;
_capsulesGO.transform.localRotation = Quaternion.idenreplacedy;
}
_capsules = new List<OVRBoneCapsule>(new OVRBoneCapsule[skeleton.NumBoneCapsules]);
Capsules = _capsules.AsReadOnly();
for (int i = 0; i < skeleton.NumBoneCapsules; ++i)
{
var capsule = skeleton.BoneCapsules[i];
Transform bone = Bones[capsule.BoneIndex].Transform;
var capsuleRigidBodyGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleRigidBody");
capsuleRigidBodyGO.transform.SetParent(_capsulesGO.transform, false);
capsuleRigidBodyGO.transform.position = bone.position;
capsuleRigidBodyGO.transform.rotation = bone.rotation;
var capsuleRigidBody = capsuleRigidBodyGO.AddComponent<Rigidbody>();
capsuleRigidBody.mreplaced = 1.0f;
capsuleRigidBody.isKinematic = true;
capsuleRigidBody.useGravity = false;
capsuleRigidBody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
var capsuleColliderGO = new GameObject((_bones[capsule.BoneIndex].Id).ToString() + "_CapsuleCollider");
capsuleColliderGO.transform.SetParent(capsuleRigidBodyGO.transform, false);
var capsuleCollider = capsuleColliderGO.AddComponent<CapsuleCollider>();
var p0 = capsule.Points[0].FromFlippedXVector3f();
var p1 = capsule.Points[1].FromFlippedXVector3f();
var delta = p1 - p0;
var mag = delta.magnitude;
var rot = Quaternion.FromToRotation(Vector3.right, delta);
capsuleCollider.radius = capsule.Radius;
capsuleCollider.height = mag + capsule.Radius * 2.0f;
capsuleCollider.isTrigger = false;
capsuleCollider.direction = 0;
capsuleColliderGO.transform.localPosition = p0;
capsuleColliderGO.transform.localRotation = rot;
capsuleCollider.center = Vector3.right * mag * 0.5f;
_capsules[i] = new OVRBoneCapsule(capsule.BoneIndex, capsuleRigidBody, capsuleCollider);
}
}
}
19
View Source File : LazyTreeNode.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public virtual async Task<bool> RefreshAsync()
{
if (_isRefreshing) return false;
_isRefreshing = true;
if (ChildrenProvider == null) return AbortRefresh();
var enumerable = await ChildrenProvider(Content);
if (enumerable == null) return AbortRefresh();
var collection = enumerable.ToList();
if (!collection.Any()) return AbortRefresh();
var children = collection.Select(GenerateLazyTreeNode).ToList();
children.ForEach(item => item.Parent = this);
SetChildrenCache(children.AsReadOnly());
_isRefreshing = false;
return true;
}
19
View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task DownloadFromContainerAsync(
RunnerActionPluginExecutionContext context,
String destination,
CancellationToken cancellationToken)
{
// Find out all container items need to be processed
List<FileContainerItem> containerItems = new List<FileContainerItem>();
int retryCount = 0;
while (retryCount < 3)
{
try
{
containerItems = await _fileContainerHttpClient.QueryContainerItemsAsync(_containerId,
_projectId,
_containerPath,
cancellationToken: cancellationToken);
break;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
context.Debug($"Container query has been cancelled.");
throw;
}
catch (Exception ex) when (retryCount < 2)
{
retryCount++;
context.Warning($"Fail to query container items under #/{_containerId}/{_containerPath}, Error: {ex.Message}");
context.Debug(ex.ToString());
}
var backOff = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15));
context.Warning($"Back off {backOff.TotalSeconds} seconds before retry.");
await Task.Delay(backOff);
}
if (containerItems.Count == 0)
{
context.Output($"There is nothing under #/{_containerId}/{_containerPath}");
return;
}
// container items will include both folders, files and even file with zero size
// Create all required empty folders and emptry files, gather a list of files that we need to download from server.
int foldersCreated = 0;
int emptryFilesCreated = 0;
List<DownloadInfo> downloadFiles = new List<DownloadInfo>();
foreach (var item in containerItems.OrderBy(x => x.Path))
{
if (!item.Path.StartsWith(_containerPath, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException($"Item {item.Path} is not under #/{_containerId}/{_containerPath}");
}
var localRelativePath = item.Path.Substring(_containerPath.Length).TrimStart('/');
var localPath = Path.Combine(destination, localRelativePath);
if (item.ItemType == ContainerItemType.Folder)
{
context.Debug($"Ensure folder exists: {localPath}");
Directory.CreateDirectory(localPath);
foldersCreated++;
}
else if (item.ItemType == ContainerItemType.File)
{
if (item.FileLength == 0)
{
context.Debug($"Create empty file at: {localPath}");
var parentDirectory = Path.GetDirectoryName(localPath);
Directory.CreateDirectory(parentDirectory);
IOUtil.DeleteFile(localPath);
using (new FileStream(localPath, FileMode.Create))
{
}
emptryFilesCreated++;
}
else
{
context.Debug($"Prepare download {item.Path} to {localPath}");
downloadFiles.Add(new DownloadInfo(item.Path, localPath));
}
}
else
{
throw new NotSupportedException(item.ItemType.ToString());
}
}
if (foldersCreated > 0)
{
context.Output($"{foldersCreated} folders created.");
}
if (emptryFilesCreated > 0)
{
context.Output($"{emptryFilesCreated} empty files created.");
}
if (downloadFiles.Count == 0)
{
context.Output($"There is nothing to download");
return;
}
// Start multi-task to download all files.
using (_downloadCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
// try download all files for the first time.
DownloadResult downloadResult = await ParallelDownloadAsync(context, downloadFiles.AsReadOnly(), Math.Min(downloadFiles.Count, Environment.ProcessorCount), _downloadCancellationTokenSource.Token);
if (downloadResult.FailedFiles.Count == 0)
{
// all files have been download succeed.
context.Output($"{downloadFiles.Count} files download succeed.");
return;
}
else
{
context.Output($"{downloadResult.FailedFiles.Count} files failed to download, retry these files after a minute.");
}
// Delay 1 min then retry failed files.
for (int timer = 60; timer > 0; timer -= 5)
{
context.Output($"Retry file download after {timer} seconds.");
await Task.Delay(TimeSpan.FromSeconds(5), _uploadCancellationTokenSource.Token);
}
// Retry download all failed files.
context.Output($"Start retry {downloadResult.FailedFiles.Count} failed files upload.");
DownloadResult retryDownloadResult = await ParallelDownloadAsync(context, downloadResult.FailedFiles.AsReadOnly(), Math.Min(downloadResult.FailedFiles.Count, Environment.ProcessorCount), _downloadCancellationTokenSource.Token);
if (retryDownloadResult.FailedFiles.Count == 0)
{
// all files have been download succeed after retry.
context.Output($"{downloadResult.FailedFiles} files download succeed after retry.");
return;
}
else
{
throw new Exception($"{retryDownloadResult.FailedFiles.Count} files failed to download even after retry.");
}
}
}
19
View Source File : TemplateContext.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal IReadOnlyList<String> GetFileTable()
{
return FileNames.AsReadOnly();
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static void ConfigureServiceCertificateCookieTransform(this ServiceConfiguration config)
{
if (config.ServiceCertificate != null)
{
// Use the <serviceCertificate> to protect the cookies that are sent to the client.
var sessionTransforms = new List<CookieTransform>(new CookieTransform[]
{
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(config.ServiceCertificate),
new RsaSignatureCookieTransform(config.ServiceCertificate)
});
var sessionHandler = new Microsoft.IdenreplacedyModel.Tokens.SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
config.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
}
19
View Source File : DescriptorOnlyServiceBinder.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
internal IReadOnlyList<ServiceDescriptor> GetDescriptors()
{
return _descriptors.AsReadOnly();
}
19
View Source File : ServerServiceDefinitionExtensions.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
internal IReadOnlyList<ServiceDescriptor> GetDescriptors()
{
return descriptors.AsReadOnly();
}
19
View Source File : AssemblyPointer.cs
License : MIT License
Project Creator : AgileoAutomation
License : MIT License
Project Creator : AgileoAutomation
public ReadOnlyCollection<replacedemblyName> GetReferencedreplacedemblies()
{
return replacedembly?.GetReferencedreplacedemblies().ToList().AsReadOnly();
}
19
View Source File : DatabaseSearchService.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
public async Task<IReadOnlyList<SearchResult>> SearchAsync(string query, int skip = 0, int take = 20)
{
IQueryable<Package> search = _context.Packages;
if (!string.IsNullOrEmpty(query))
{
query = query.ToLower();
search = search.Where(p => p.Id.ToLower().Contains(query));
}
var packages = await _context.Packages
.Where(p =>
search.Select(p2 => p2.Id)
.OrderBy(id => id)
.Distinct()
.Skip(skip)
.Take(take)
.Contains(p.Id))
.GroupBy(p => p.Id)
.ToListAsync();
var result = new List<SearchResult>();
foreach (var package in packages)
{
var versions = package.OrderByDescending(p => p.Version).ToList();
var latest = versions.First();
var versionResults = versions.Select(p => new SearchResultVersion(p.Version, p.Downloads));
result.Add(new SearchResult
{
Id = latest.Id,
Version = latest.Version,
Description = latest.Description,
Authors = string.Join(", ", latest.Authors),
IconUrl = latest.IconUrlString,
LicenseUrl = latest.LicenseUrlString,
ProjectUrl = latest.ProjectUrlString,
Summary = latest.Summary,
Tags = latest.Tags,
replacedle = latest.replacedle,
TotalDownloads = versions.Sum(p => p.Downloads),
Versions = versionResults.ToList().AsReadOnly(),
});
}
return result.AsReadOnly();
}
19
View Source File : DragDropTarget.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
public IList<DragDropItem> GetAllAttachedItems()
{
return attachedItems.AsReadOnly();
}
19
View Source File : GameManager.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
public ReadOnlyCollection<Hero> GetHeroes()
{
return heroes.AsReadOnly();
}
19
View Source File : OutfitsControl.xaml.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private async Task UpdateModelList()
{
var filter = IoC.Settings.OutfitModelFilter;
if (filter == 0)
filter = OutfitModelFilter.Armor.Value | OutfitModelFilter.Characters.Value;
await Async.Run(() =>
{
var models = new List<Model>();
if (OutfitModelFilter.Armor.IsFlag(filter))
models.AddRange(LoadOutfitModelList());
if (OutfitModelFilter.Characters.IsFlag(filter))
models.AddRange(LoadCharacterModelList(false));
if (OutfitModelFilter.AllCharacters.IsFlag(filter))
models.AddRange(LoadCharacterModelList(true));
Models = models.AsReadOnly();
});
UpdateModelDisplayNames(DefaultOutfits, Models);
}
19
View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return list.AsReadOnly();
}
return original;
}
19
View Source File : IdentityServerEventCaptureStore.cs
License : MIT License
Project Creator : alsami
License : MIT License
Project Creator : alsami
public IEnumerable<Event> GetEvents()
{
return this.events.AsReadOnly();
}
19
View Source File : SolutionExplorerDataItem.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public static IList<string> DecodeProjecreplacedemData(IDataObject data, string format)
{
/*
This function reads the memory stream in the data object and parses the data.
The structure of the data is as follows:
DROPFILES structure (20 bytes)
String\0
String\0
..
String\0\0
One String for each drag-dropped Soln Explorer node.
The fWide member in the DROPFILES structure tells us if the string is encoded in Unicode or ASCII.
And each string contains the following:
{project guid} +"|"+ project file name +"|"+ drag-dropped file name
The exact format is doreplacedented as part of the doreplacedentation of IVsSolution.GereplacedemOfProjref()
which is the API to parse these strings.
*/
using (MemoryStream stream = data.GetData(format) as MemoryStream)
{
if (stream == null || stream.Length <= 22 || !stream.CanRead)
return new string[0];
Encoding encoding = (System.BitConverter.IsLittleEndian ? Encoding.Unicode : Encoding.BigEndianUnicode);
BinaryReader reader = new BinaryReader(stream, encoding);
// Read the initial DROPFILES struct (20 bytes)
Int32 files = reader.ReadInt32();
Int32 x = reader.ReadInt32();
Int32 y = reader.ReadInt32();
Int32 unused = reader.ReadInt32(); // This is not used anywhere, but is read out of the way.
Int32 unicode = reader.ReadInt32();
// If the string is not unicode, use ASCII encoding
if (unicode == 0)
{
reader = new BinaryReader(stream, Encoding.ASCII);
}
char lastChar = '\0';
List<string> items = new List<string>();
StringBuilder sb = new StringBuilder();
while (stream.Position < stream.Length)
{
char c = reader.ReadChar();
if (c == '\0' && lastChar == '\0')
{
break;
}
if (c == '\0')
{
items.Add(sb.ToString());
sb.Length = 0;
}
else
{
sb.Append(c);
}
lastChar = c;
}
return items.AsReadOnly();
}
}
19
View Source File : SccProjectMap.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public ICollection<string> GetAllFilesOfAllProjects(bool exceptExcluded)
{
List<string> files = new List<string>(UniqueFileCount + 1);
if (SolutionFilename != null && !ContainsFile(SolutionFilename))
files.Add(SolutionFilename);
foreach (string file in AllFiles)
{
if (file[file.Length - 1] == '\\') // Don't return paths
continue;
if (exceptExcluded && IsSccExcluded(file))
continue;
files.Add(file);
}
return files.AsReadOnly();
}
19
View Source File : SccProjectFileReference.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public IList<string> GetSubFiles()
{
if (_subFiles != null)
return _subFiles;
ISccProjectWalker walker = _context.GetService<ISccProjectWalker>();
List<string> files = new List<string>(walker.GetSccFiles(Project.ProjectHierarchy, ProjecreplacedemId, ProjectWalkDepth.SpecialFiles, null));
files.Remove(Filename);
_subFiles = files.AsReadOnly();
return _subFiles;
}
19
View Source File : ClassicEvolve.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
public IReadOnlyCollection<Instruction> GetInstructions() => cache.AsReadOnly();
19
View Source File : LavalinkNode.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public IReadOnlyList<TPlayer> GetPlayers<TPlayer>() where TPlayer : LavalinkPlayer
{
EnsureNotDisposed();
return Players.Select(s => s.Value).OfType<TPlayer>().ToList().AsReadOnly();
}
19
View Source File : DomainEntity.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public IReadOnlyCollection<EnreplacedyEvent> GetDomainEvents()
{
return _domainEvents?.AsReadOnly();
}
19
View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
if (original != null)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return list.AsReadOnly();
}
}
return original;
}
19
View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
protected virtual ReadOnlyCollection<Expression> VisitMemberAndExpressionList(ReadOnlyCollection<MemberInfo> members, ReadOnlyCollection<Expression> original)
{
if (original != null)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.VisitMemberAndExpression(members != null ? members[i] : null, original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return list.AsReadOnly();
}
}
return original;
}
19
View Source File : FileSelector.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public System.Collections.ObjectModel.ReadOnlyCollection<String>
SelectFiles(String directory,
bool recurseDirectories)
{
if (_Criterion == null)
throw new ArgumentException("SelectionCriteria has not been set");
var list = new List<String>();
try
{
if (Directory.Exists(directory))
{
String[] filenames = Directory.GetFiles(directory);
// add the files:
foreach (String filename in filenames)
{
if (Evaluate(filename))
list.Add(filename);
}
if (recurseDirectories)
{
// add the subdirectories:
String[] dirnames = Directory.GetDirectories(directory);
foreach (String dir in dirnames)
{
if (this.TraverseReparsePoints
#if !SILVERLIGHT
|| ((File.GetAttributes(dir) & FileAttributes.ReparsePoint) == 0)
#endif
)
{
// workitem 10191
if (Evaluate(dir)) list.Add(dir);
list.AddRange(this.SelectFiles(dir, recurseDirectories));
}
}
}
}
}
// can get System.UnauthorizedAccessException here
catch (System.UnauthorizedAccessException)
{
}
catch (System.IO.IOException)
{
}
return list.AsReadOnly();
}
19
View Source File : TransitionHistory.cs
License : MIT License
Project Creator : Aptacode
License : MIT License
Project Creator : Aptacode
public IReadOnlyList<int> GetTransitionHistory()
{
return _transitionHistory.AsReadOnly();
}
19
View Source File : MappingExtensions.cs
License : MIT License
Project Creator : AspNetCoreFromZeroToOverkill
License : MIT License
Project Creator : AspNetCoreFromZeroToOverkill
public static IReadOnlyCollection<TOut> MapAsReadOnly<TIn, TOut>(this IEnumerable<TIn> toMap, Func<TIn, TOut> map)
{
_ = toMap ?? throw new ArgumentNullException(nameof(toMap));
_ = map ?? throw new ArgumentNullException(nameof(map));
return toMap switch
{
IReadOnlyCollection<TIn> readOnly => MapWithKnownCount(readOnly, readOnly.Count, map),
ICollection<TIn> collection => MapWithKnownCount(collection, collection.Count, map),
_ => toMap.Select(map).ToList().AsReadOnly()
};
19
View Source File : FileUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
public static void DeleteFiles(IEnumerable<File> files, bool includeDiskFiles, out IReadOnlyCollection<string> deleteFailedFiles)
{
List<string> failed = new List<string>();
foreach (var file in files)
{
db.Entry(file).State = EnreplacedyState.Deleted;
if (includeDiskFiles)
{
try
{
F.Delete(file.GetAbsolutePath());
}
catch (Exception ex)
{
failed.Add(file.GetAbsolutePath());
}
}
}
deleteFailedFiles = failed.AsReadOnly();
SaveChanges();
}
19
View Source File : ProjectUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
public static IReadOnlyList<File> CheckFiles(Project project)
{
var files = db.Files.Where(p => p.Project == project);
var lostFiles = new List<File>();
foreach (var file in files)
{
if (file.IsFolder)
{
if (!System.IO.Directory.Exists(file.GetAbsolutePath()))
{
lostFiles.Add(file);
}
}
else
{
if (!System.IO.File.Exists(file.GetAbsolutePath()))
{
lostFiles.Add(file);
}
}
}
return lostFiles.AsReadOnly();
}
19
View Source File : DragDropFilesHelper.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
private IReadOnlyList<UIFile> GetSelectedFiles()
{
return list switch
{
ListBox lvw => lvw.SelectedItems.Cast<UIFile>().ToList().AsReadOnly(),
TreeView t => t.SelectedItem == null ? new List<UIFile>().AsReadOnly() : new List<UIFile>() { t.SelectedItem as UIFile }.AsReadOnly(),
_ => new List<UIFile>().AsReadOnly(),
};
19
View Source File : FileClassUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
public static IReadOnlyList<File> AddFilesToClreplaced(UpdateFilesArgs args)
{
Debug.WriteLine("db begin: " + nameof(AddFilesToClreplaced));
List<File> fs = new List<File>();
if (args.Files.Any(p => !p.StartsWith(args.Project.RootPath)))
{
throw new Exception("文件不在项目目录下");
}
int index = 0;
int count = args.Files.Count;
DateTime lastCallbackTime = DateTime.MinValue;
foreach (var path in args.Files)
{
File f = new File(new FI(path), args.Project);
File existedFile = db.Files.FirstOrDefault(p => p.Name == f.Name && p.Dir == f.Dir);
//文件不存在的话,需要首先新增文件
if (existedFile == null)
{
args.GenerateThumbnailsMethod?.Invoke(f);
//if (args.IncludeThumbnails)
//{
// FileUtility.TryGenerateThumbnail(f);
//}
//if (args.IncludeExplorerIcons)
//{
// FileUtility.TryGenerateExplorerIcon(f);
//}
db.Files.Add(f);
}
else
{
var existedFileClreplaced = db.FileClreplacedes.FirstOrDefault(p => p.Clreplaced == args.Clreplaced && p.File == existedFile);
//如果文件已存在,就搜索一下是否存在关系,存在关系就不需要继续了
if (existedFileClreplaced != null && existedFileClreplaced.Status != FileClreplacedStatus.Disabled)
{
goto next;
}
//存在但被禁用
if (existedFileClreplaced != null && existedFileClreplaced.Status == FileClreplacedStatus.Disabled)
{
fs.Add(existedFile);
existedFileClreplaced.Status = FileClreplacedStatus.Auto;
db.Entry(existedFileClreplaced).State = EnreplacedyState.Modified;
goto next;
}
f = existedFile;
}
db.FileClreplacedes.Add(new FileClreplaced(args.Clreplaced, f, true));
fs.Add(f);
next:
index++;
if (args.Callback != null && (DateTime.Now - lastCallbackTime).TotalMilliseconds > CallbackUpdateMs)
{
lastCallbackTime = DateTime.Now;
if (!args.Callback(index * 1.0 / count, f))
{
db.SaveChanges();
return null;
}
}
}
SaveChanges();
Debug.WriteLine("db end: " + nameof(AddFilesToClreplaced));
return fs.AsReadOnly();
}
19
View Source File : FileClassUtility.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
public static IReadOnlyList<File> AddFilesToClreplaced(IEnumerable<File> files, Clreplaced c)
{
Debug.WriteLine("db begin: " + nameof(AddFilesToClreplaced));
List<File> addedFiles = new List<File>();
foreach (var file in files)
{
if (!db.FileClreplacedes.Any(p => p.FileID == file.ID && p.ClreplacedID == c.ID))
{
db.FileClreplacedes.Add(new FileClreplaced(c, file, true));
addedFiles.Add(file);
}
}
SaveChanges();
Debug.WriteLine("db end: " + nameof(AddFilesToClreplaced));
return addedFiles.AsReadOnly();
}
19
View Source File : GifPlainTextExtension.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : ay2015
private void Read(Stream stream, IEnumerable<GifExtension> controlExtensions, bool metadataOnly)
{
// Note: at this point, the label (0x01) has already been read
byte[] bytes = new byte[13];
stream.ReadAll(bytes,0, bytes.Length);
BlockSize = bytes[0];
if (BlockSize != 12)
throw GifHelpers.InvalidBlockSizeException("Plain Text Extension", 12, BlockSize);
Left = BitConverter.ToUInt16(bytes, 1);
Top = BitConverter.ToUInt16(bytes, 3);
Width = BitConverter.ToUInt16(bytes, 5);
Height = BitConverter.ToUInt16(bytes, 7);
CellWidth = bytes[9];
CellHeight = bytes[10];
ForegroundColorIndex = bytes[11];
BackgroundColorIndex = bytes[12];
var dataBytes = GifHelpers.ReadDataBlocks(stream, metadataOnly);
Text = Encoding.ASCII.GetString(dataBytes);
Extensions = controlExtensions.ToList().AsReadOnly();
}
19
View Source File : GifFile.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : ay2015
private void ReadFrames(Stream stream, bool metadataOnly)
{
List<GifFrame> frames = new List<GifFrame>();
List<GifExtension> controlExtensions = new List<GifExtension>();
List<GifExtension> specialExtensions = new List<GifExtension>();
while (true)
{
var block = GifBlock.ReadBlock(stream, controlExtensions, metadataOnly);
if (block.Kind == GifBlockKind.GraphicRendering)
controlExtensions = new List<GifExtension>();
if (block is GifFrame)
{
frames.Add((GifFrame)block);
}
else if (block is GifExtension)
{
var extension = (GifExtension)block;
switch (extension.Kind)
{
case GifBlockKind.Control:
controlExtensions.Add(extension);
break;
case GifBlockKind.SpecialPurpose:
specialExtensions.Add(extension);
break;
}
}
else if (block is GifTrailer)
{
break;
}
}
this.Frames = frames.AsReadOnly();
this.Extensions = specialExtensions.AsReadOnly();
}
19
View Source File : GifFrame.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : ay2015
private void Read(Stream stream, IEnumerable<GifExtension> controlExtensions, bool metadataOnly)
{
// Note: at this point, the Image Separator (0x2C) has already been read
Descriptor = GifImageDescriptor.ReadImageDescriptor(stream);
if (Descriptor.HasLocalColorTable)
{
LocalColorTable = GifHelpers.ReadColorTable(stream, Descriptor.LocalColorTableSize);
}
ImageData = GifImageData.ReadImageData(stream, metadataOnly);
Extensions = controlExtensions.ToList().AsReadOnly();
}
19
View Source File : ConstantFolding.cs
License : MIT License
Project Creator : Azure
License : MIT License
Project Creator : Azure
public static ReadOnlyCollection<Expression> FoldExpressionList(ReadOnlyCollection<Expression> inputExpressionList)
{
List<Expression> list = null;
for (int i = 0; i < inputExpressionList.Count; i++)
{
Expression p = ConstantFolding.Fold(inputExpressionList[i]);
if (list != null)
{
list.Add(p);
}
else if (p != inputExpressionList[i])
{
list = new List<Expression>(inputExpressionList.Count);
for (int j = 0; j < i; j++)
{
list.Add(inputExpressionList[j]);
}
list.Add(p);
}
}
if (list != null)
{
return list.AsReadOnly();
}
return inputExpressionList;
}
See More Examples