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
Source : HeifEncoderParameterFactory.cs
with GNU Lesser General Public License v3.0
from 0xC0000054
with GNU Lesser General Public License v3.0
from 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
Source : OutputStringArray.cs
with GNU Lesser General Public License v3.0
from 0xC0000054
with GNU Lesser General Public License v3.0
from 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
Source : HeifEncoder.cs
with GNU Lesser General Public License v3.0
from 0xC0000054
with GNU Lesser General Public License v3.0
from 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
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from 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
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from 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
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from 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
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from 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
Source : ServerInformation.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from 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
Source : TextSegmentCollection.cs
with MIT License
from Abdesol
with MIT License
from 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
Source : FoldingManager.cs
with MIT License
from Abdesol
with MIT License
from 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
Source : VisualLine.cs
with MIT License
from Abdesol
with MIT License
from 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
Source : VisualLine.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
internal void SetTextLines(List<TextLine> textLines)
{
this.textLines = textLines.AsReadOnly();
Height = 0;
foreach (TextLine line in textLines)
Height += line.Height;
}
19
Source : BaseDataProviderAccessCoreSystem.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public virtual IReadOnlyList<IMixedRealityDataProvider> GetDataProviders()
{
return dataProviders.AsReadOnly();
}
19
Source : OVRSkeleton.cs
with MIT License
from absurd-joy
with MIT License
from 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
Source : OVRSkeleton.cs
with MIT License
from absurd-joy
with MIT License
from 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
Source : OVRSkeleton.cs
with MIT License
from absurd-joy
with MIT License
from 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
Source : OVRSkeleton.cs
with MIT License
from absurd-joy
with MIT License
from 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
Source : LazyTreeNode.cs
with MIT License
from Accelerider
with MIT License
from 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
Source : FileContainerServer.cs
with MIT License
from actions
with MIT License
from 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
Source : TemplateContext.cs
with MIT License
from actions
with MIT License
from actions
internal IReadOnlyList<String> GetFileTable()
{
return FileNames.AsReadOnly();
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : DescriptorOnlyServiceBinder.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
internal IReadOnlyList<ServiceDescriptor> GetDescriptors()
{
return _descriptors.AsReadOnly();
}
19
Source : ServerServiceDefinitionExtensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
internal IReadOnlyList<ServiceDescriptor> GetDescriptors()
{
return descriptors.AsReadOnly();
}
19
Source : AssemblyPointer.cs
with MIT License
from AgileoAutomation
with MIT License
from AgileoAutomation
public ReadOnlyCollection<replacedemblyName> GetReferencedreplacedemblies()
{
return replacedembly?.GetReferencedreplacedemblies().ToList().AsReadOnly();
}
19
Source : DatabaseSearchService.cs
with MIT License
from ai-traders
with MIT License
from 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
Source : DragDropTarget.cs
with MIT License
from aillieo
with MIT License
from aillieo
public IList<DragDropItem> GetAllAttachedItems()
{
return attachedItems.AsReadOnly();
}
19
Source : GameManager.cs
with MIT License
from aillieo
with MIT License
from aillieo
public ReadOnlyCollection<Hero> GetHeroes()
{
return heroes.AsReadOnly();
}
19
Source : OutfitsControl.xaml.cs
with MIT License
from AkiniKites
with MIT License
from 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
Source : ExpressionVisitor.cs
with MIT License
from albyho
with MIT License
from 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
Source : IdentityServerEventCaptureStore.cs
with MIT License
from alsami
with MIT License
from alsami
public IEnumerable<Event> GetEvents()
{
return this.events.AsReadOnly();
}
19
Source : SolutionExplorerDataItem.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from 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
Source : SccProjectMap.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from 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
Source : SccProjectFileReference.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from 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
Source : ClassicEvolve.cs
with MIT License
from ancientproject
with MIT License
from ancientproject
public IReadOnlyCollection<Instruction> GetInstructions() => cache.AsReadOnly();
19
Source : LavalinkNode.cs
with MIT License
from angelobreuer
with MIT License
from angelobreuer
public IReadOnlyList<TPlayer> GetPlayers<TPlayer>() where TPlayer : LavalinkPlayer
{
EnsureNotDisposed();
return Players.Select(s => s.Value).OfType<TPlayer>().ToList().AsReadOnly();
}
19
Source : DomainEntity.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public IReadOnlyCollection<EnreplacedyEvent> GetDomainEvents()
{
return _domainEvents?.AsReadOnly();
}
19
Source : ExpressionVisitor.cs
with MIT License
from anthonyreilly
with MIT License
from 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
Source : ExpressionVisitor.cs
with MIT License
from anthonyreilly
with MIT License
from 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
Source : FileSelector.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from 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
Source : TransitionHistory.cs
with MIT License
from Aptacode
with MIT License
from Aptacode
public IReadOnlyList<int> GetTransitionHistory()
{
return _transitionHistory.AsReadOnly();
}
19
Source : MappingExtensions.cs
with MIT License
from AspNetCoreFromZeroToOverkill
with MIT License
from 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
Source : FileUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from 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
Source : ProjectUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from 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
Source : DragDropFilesHelper.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from 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
Source : FileClassUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from 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
Source : FileClassUtility.cs
with GNU General Public License v3.0
from autodotua
with GNU General Public License v3.0
from 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
Source : GifPlainTextExtension.cs
with MIT License
from ay2015
with MIT License
from 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
Source : GifFile.cs
with MIT License
from ay2015
with MIT License
from 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
Source : GifFrame.cs
with MIT License
from ay2015
with MIT License
from 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
Source : ConstantFolding.cs
with MIT License
from Azure
with MIT License
from 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