Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ElementAt(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2213 Examples
19
Source : SumIf.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 2);
var args = arguments.ElementAt(0).Value as ExcelDataProvider.IRangeInfo;
var criteria = arguments.ElementAt(1).ValueFirst != null ? ArgToString(arguments, 1) : null;
var retVal = 0d;
if (args == null)
{
var val = arguments.ElementAt(0).Value;
if (criteria != null && _evaluator.Evaluate(val, criteria))
{
var sumRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;
retVal = arguments.Count() > 2
? sumRange.First().ValueDouble
: ConvertUtil.GetValueDouble(val, true);
}
}
else if (arguments.Count() > 2)
{
var sumRange = arguments.ElementAt(2).Value as ExcelDataProvider.IRangeInfo;
retVal = CalculateWithSumRange(args, criteria, sumRange, context);
}
else
{
retVal = CalculateSingleRange(args, criteria, context);
}
return CreateResult(retVal, DataType.Decimal);
}
19
Source : Address.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 2);
var row = ArgToInt(arguments, 0);
var col = ArgToInt(arguments, 1);
ThrowExcelErrorValueExceptionIf(() => row < 0 && col < 0, eErrorType.Value);
var referenceType = ExcelReferenceType.AbsoluteRowAndColumn;
var worksheetSpec = string.Empty;
if (arguments.Count() > 2)
{
var arg3 = ArgToInt(arguments, 2);
ThrowExcelErrorValueExceptionIf(() => arg3 < 1 || arg3 > 4, eErrorType.Value);
referenceType = (ExcelReferenceType)ArgToInt(arguments, 2);
}
if (arguments.Count() > 3)
{
var fourthArg = arguments.ElementAt(3).Value;
if (fourthArg is bool && !(bool)fourthArg)
{
throw new InvalidOperationException("Excelformulaparser does not support the R1C1 format!");
}
}
if (arguments.Count() > 4)
{
var fifthArg = arguments.ElementAt(4).Value;
if (fifthArg is string && !string.IsNullOrEmpty(fifthArg.ToString()))
{
worksheetSpec = fifthArg + "!";
}
}
var translator = new IndexToAddressTranslator(context.ExcelDataProvider, referenceType);
return CreateResult(worksheetSpec + translator.ToAddress(col, row), DataType.ExcelAddress);
}
19
Source : Choose.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 2);
var items = new List<object>();
for (int x = 0; x < arguments.Count(); x++)
{
items.Add(arguments.ElementAt(x).ValueFirst);
}
var chooseIndeces = arguments.ElementAt(0).ValueFirst as IEnumerable<FunctionArgument>;
if (chooseIndeces != null && chooseIndeces.Count() > 1)
{
IntArgumentParser intParser = new IntArgumentParser();
object[] values = chooseIndeces.Select(chosenIndex => items[(int)intParser.Parse(chosenIndex.ValueFirst)]).ToArray();
return CreateResult(values, DataType.Enumerable);
}
else
{
var index = ArgToInt(arguments, 0);
return CreateResult(items[index].ToString(), DataType.String);
}
}
19
Source : Columns.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var r=arguments.ElementAt(0).ValueAsRangeInfo;
if (r != null)
{
return CreateResult(r.Address._toCol - r.Address._fromCol + 1, DataType.Integer);
}
else
{
var range = ArgToString(arguments, 0);
if (ExcelAddressUtil.IsValidAddress(range))
{
var factory = new RangeAddressFactory(context.ExcelDataProvider);
var address = factory.Create(range);
return CreateResult(address.ToCol - address.FromCol + 1, DataType.Integer);
}
}
throw new ArgumentException("Invalid range supplied");
}
19
Source : Index.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 2);
var arg1 = arguments.ElementAt(0);
var args = arg1.Value as IEnumerable<FunctionArgument>;
var crf = new CompileResultFactory();
if (args != null)
{
var index = ArgToInt(arguments, 1);
if (index > args.Count())
{
throw new ExcelErrorValueException(eErrorType.Ref);
}
var candidate = args.ElementAt(index - 1);
//Commented JK-Can be any data type
//if (!IsNumber(candidate.Value))
//{
// throw new ExcelErrorValueException(eErrorType.Value);
//}
//return CreateResult(ConvertUtil.GetValueDouble(candidate.Value), DataType.Decimal);
return crf.Create(candidate.Value);
}
if (arg1.IsExcelRange)
{
var row = ArgToInt(arguments, 1);
var col = arguments.Count()>2 ? ArgToInt(arguments, 2) : 1;
var ri=arg1.ValueAsRangeInfo;
if (row > ri.Address._toRow - ri.Address._fromRow + 1 ||
col > ri.Address._toCol - ri.Address._fromCol + 1)
{
ThrowExcelErrorValueException(eErrorType.Ref);
}
var candidate = ri.GetOffset(row-1, col-1);
//Commented JK-Can be any data type
//if (!IsNumber(candidate.Value))
//{
// throw new ExcelErrorValueException(eErrorType.Value);
//}
return crf.Create(candidate);
}
throw new NotImplementedException();
}
19
Source : ExcelFunction.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
protected double ArgToDecimal(IEnumerable<FunctionArgument> arguments, int index)
{
return ArgToDecimal(arguments.ElementAt(index).Value);
}
19
Source : ExcelFunction.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
protected bool ArgToBool(IEnumerable<FunctionArgument> arguments, int index)
{
var obj = arguments.ElementAt(index).Value ?? string.Empty;
return (bool)_argumentParsers.GetParser(DataType.Boolean).Parse(obj);
}
19
Source : EnumerableExpressionTests.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
[TestMethod]
public void CompileShouldReturnEnumerableOfCompiledChildExpressions()
{
var expression = new EnumerableExpression();
expression.AddChild(new IntegerExpression("2"));
expression.AddChild(new IntegerExpression("3"));
var result = expression.Compile();
replacedert.IsInstanceOfType(result.Result, typeof(IEnumerable<object>));
var resultList = (IEnumerable<object>)result.Result;
replacedert.AreEqual(2d, resultList.ElementAt(0));
replacedert.AreEqual(3d, resultList.ElementAt(1));
}
19
Source : Sample_AddFormulaFunction.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
// Sanity check, will set excel VALUE error if min length is not met
ValidateArguments(arguments, 2);
//Replace swedish year format with invariant for parameter 2.
var format = arguments.ElementAt(1).Value.ToString().Replace("åååå", "yyyy");
var newArgs = new List<FunctionArgument> { arguments.ElementAt(0) };
newArgs.Add(new FunctionArgument(format));
//Use the build-in Text function.
var func = new Text();
return func.Execute(newArgs, context);
}
19
Source : FullOrderTableSource.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public override nint RowsInSection(UITableView tableview, nint section)
{
var items = (ItemsSource as IEnumerable<IMvxViewModel>).ToList();
return section == (Sections - 1) ?
items.Where(x => x is IDeliveryTypeItemVM).Count()
:
(items.ElementAt((int)section) as IOrderFieldsGroupVM).Items.Count;
}
19
Source : MockTableImportFixed.cs
with MIT License
from Apps72
with MIT License
from Apps72
private IEnumerable<object[]> GetRowsConverted(IEnumerable<string[]> rows)
{
int fieldsCount = Fields.Count();
Type[] fieldsType = Fields.Select(i => i.DataType).ToArray();
foreach (var row in rows)
{
var rowConverted = new object[fieldsCount];
for (int i = 0; i < fieldsCount; i++)
{
try
{
// If not a string => String.Empty = NULL
if (fieldsType[i] != typeof(string) && String.IsNullOrEmpty(row[i]))
{
row[i] = "NULL";
}
if (fieldsType[i] != null && String.Compare(row[i], "NULL", ignoreCase: true) != 0)
{
// Convert
var converter = System.ComponentModel.TypeDescriptor.GetConverter(fieldsType[i]);
rowConverted[i] = Convert.ChangeType(converter.ConvertFromInvariantString(row[i]), fieldsType[i]);
// Guillemets
if (fieldsType[i] == typeof(string) && row[i].Length >= 2 && row[i][0] == '"' && row[i][row[i].Length - 1] == '"')
{
rowConverted[i] = row[i].Substring(1, row[i].Length - 2);
}
}
}
catch (Exception)
{
throw new InvalidCastException($"Invalid conversion of \"{row[i]}\" to \"{fieldsType[i].Name}\", for column \"{Fields.ElementAt(i).Name}\".");
}
}
yield return rowConverted;
}
}
19
Source : VertexArray.cs
with GNU General Public License v3.0
from Aptacode
with GNU General Public License v3.0
from Aptacode
public static VertexArray Create(IEnumerable<Vector2> vertices)
{
var Vertices = new Vector2[vertices.Count()];
for (var i = 0; i < vertices.Count(); i++)
{
Vertices[i] = vertices.ElementAt(i);
}
return new VertexArray(Vertices);
}
19
Source : BrowserTabNavigation.cs
with Apache License 2.0
from aquality-automation
with Apache License 2.0
from aquality-automation
public void SwitchToTab(int index, bool closeCurrent = false)
{
Logger.Info("loc.browser.switch.to.tab.index", index);
var names = TabHandles;
if (index < 0 || names.Count <= index)
{
throw new ArgumentOutOfRangeException(
$"Index of browser tab '{index}' you provided is out of range {0}..{names.Count}");
}
var newTab = names.ElementAt(index);
CloseAndSwitch(newTab, closeCurrent);
}
19
Source : FeaturePostProcessing.cs
with MIT License
from ar1st0crat
with MIT License
from ar1st0crat
public static float[][] Join(params IList<float[]>[] vectors)
{
var vectorCount = vectors.Length;
switch (vectorCount)
{
case 0:
throw new ArgumentException("Empty collection of feature vectors!");
case 1:
return vectors.ElementAt(0).ToArray();
}
var totalVectors = vectors[0].Count;
if (vectors.Any(v => v.Count != totalVectors))
{
throw new InvalidOperationException("All sequences of feature vectors must have the same length!");
}
var length = vectors.Sum(v => v[0].Length);
var joined = new float[totalVectors][];
for (var i = 0; i < joined.Length; i++)
{
var features = new float[length];
for (int offset = 0, j = 0; j < vectorCount; j++)
{
var size = vectors[j][i].Length;
vectors[j][i].FastCopyTo(features, size, 0, offset);
offset += size;
}
joined[i] = features;
}
return joined;
}
19
Source : ColorMap.cs
with MIT License
from ar1st0crat
with MIT License
from ar1st0crat
private void CreatePalette(IEnumerable<byte[]> colors, IEnumerable<float> positions)
{
if (colors == null || positions == null)
{
throw new ArgumentException("Collections of colors and positions should not be null!");
}
if (colors.Count() != positions.Count())
{
throw new ArgumentException("Number of colors should be the same as the number of color positions!");
}
if (colors.Count() <= 1 || colors.Count() > PaletteColors)
{
throw new ArgumentException(string.Format(
"Number of colors should be in range [2, {0}]!", PaletteColors));
}
if (positions.First().CompareTo(0) != 0 || positions.Last().CompareTo(1) != 0)
{
throw new ArgumentException("First color position should be 0.0f and last position should be 1.0f!");
}
if (colors.Any(c => c.Length != 3))
{
throw new ArgumentException("Each color should be an array of 3 bytes!");
}
_palette = new byte[PaletteColors][];
var groups = positions.Select(pos => (int)(pos * PaletteColors)).ToList();
var i = 0;
for (var group = 0; group < groups.Count - 1; group++)
{
var color1 = colors.ElementAt(group);
var color2 = colors.ElementAt(group + 1);
var groupSize = groups[group + 1] - groups[group];
for (var j = 0; j < groupSize; j++)
{
_palette[i] = new byte[3];
_palette[i][0] = (byte)(color1[0] + (double)(color2[0] - color1[0]) * j / groupSize);
_palette[i][1] = (byte)(color1[1] + (double)(color2[1] - color1[1]) * j / groupSize);
_palette[i][2] = (byte)(color1[2] + (double)(color2[2] - color1[2]) * j / groupSize);
i++;
}
}
}
19
Source : Cooking.cs
with MIT License
from ArchaicQuest
with MIT License
from ArchaicQuest
public Item.Item GenerateCookedItem(Player player, Room room, List<Tuple<Item.Item, int>> ingredients)
{
var prefixes = new List<string>()
{
"Boiled",
"Baked",
"Fried",
"Toasted",
"Smoked",
"Roast",
"Poached"
};
var suffixes = new List<string>()
{
"soup",
"stew",
"pie",
"curry",
"skewer"
};
var ingredientOrder = ingredients.OrderByDescending(item => item.Item2);
var mainIngredient = ingredientOrder.First();
var foodName = "";
if (_dice.Roll(1, 1, 2) == 1)
{
var prefix = prefixes[_dice.Roll(1, 0, 6)];
foodName = $"{prefix} {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()} {(ingredientOrder.Count() > 1 ? $"with {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}" : "")} {(ingredientOrder.Count() > 2 ? $"and {Helpers.RemoveArticle(ingredientOrder.ElementAt(2).Item1.Name).ToLower()}" : "")}";
}
else
{
var suffix = suffixes[_dice.Roll(1, 0, 5)];
foodName = $"{Helpers.RemoveArticle(mainIngredient.Item1.Name)} {(ingredientOrder.Count() > 1 ? $"with {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}" : "")} {(ingredientOrder.Count() > 2 ? $" {Helpers.RemoveArticle(ingredientOrder.ElementAt(2).Item1.Name).ToLower()} " : "")}{suffix}";
}
var food = new Item.Item()
{
Name = foodName,
ArmourRating = new ArmourRating(),
Value = 75,
Portal = new Portal(),
ItemType = Item.Item.ItemTypes.Cooked,
Container = new Container(),
Description = new Description()
{
Look =
$"A tasty looking {foodName.ToLower()} made with {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()}s{(ingredientOrder.Count() > 1 ? $" and {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}." : ".")}",
Exam =
$"A tasty looking {foodName.ToLower()} made with {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()}s{(ingredientOrder.Count() > 1 ? $" and {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}." : ".")}"
},
Modifier = new Modifier()
{
HP = CalculateModifer(ingredientOrder, "hp"),
Strength = CalculateModifer(ingredientOrder, "strength"),
Dexterity = CalculateModifer(ingredientOrder, "dexterity"),
Consreplacedution = CalculateModifer(ingredientOrder, "consreplacedution"),
Intelligence = CalculateModifer(ingredientOrder, "intelligence"),
Wisdom = CalculateModifer(ingredientOrder, "wisdom"),
Charisma = CalculateModifer(ingredientOrder, "charisma"),
Moves = CalculateModifer(ingredientOrder, "moves"),
Mana = CalculateModifer(ingredientOrder, "mana"),
DamRoll = CalculateModifer(ingredientOrder, "damroll"),
HitRoll = CalculateModifer(ingredientOrder, "hitroll"),
Saves = CalculateModifer(ingredientOrder, "saves"),
},
Level = 1,
Slot = Equipment.EqSlot.Held,
Uses = 1,
Weight = 0.3F,
};
return food;
}
19
Source : Results.cs
with GNU General Public License v3.0
from architecture-building-systems
with GNU General Public License v3.0
from architecture-building-systems
public static double GetTotalCostEmbodiedConstructionYearlyLevelized(Building.Building building, double interestRate, double buildingLifetime)
{
//double[] costsPerZonePerComponent = new double[building.Zones.Length][][];
double[] costsYearly = new double[(int)buildingLifetime];
IEnumerable<Component> surfs = building.Zones[0].SurfaceComponents;
for (int j = 0; j < surfs.Count(); j++) // single zone !!
{
Component surf = surfs.ElementAt(j);
double costEmbodied = surf.TotalCost;
//double costOperational = 0.0; // replacedume no OPEX!
for (int k = 0; k < buildingLifetime; k++)
{
if (k % surf.Lifetime == 0) costsYearly[k] += costEmbodied;
}
}
return Misc.ComputeLevelisedValues(costsYearly, interestRate, buildingLifetime);
}
19
Source : Results.cs
with GNU General Public License v3.0
from architecture-building-systems
with GNU General Public License v3.0
from architecture-building-systems
public static double GetTotalEmissionsEmbodiedConstructionYearlyLevelized(Building.Building building, double buildingLifetime)
{
double[] emissionsYearly = new double[(int)buildingLifetime];
IEnumerable<Component> surfs = building.Zones[0].SurfaceComponents;
for (int j = 0; j < surfs.Count(); j++) // single zone !!
{
Component surf = surfs.ElementAt(j);
double emissionsEmbodied = surf.TotalEmissions;
//double costOperational = 0.0; // replacedume no OPEX!
for (int k = 0; k < buildingLifetime; k++)
{
if (k % surf.Lifetime == 0) emissionsYearly[k] += emissionsEmbodied;
}
}
return Misc.ComputeLevelisedValues(emissionsYearly, 0.0, buildingLifetime);
}
19
Source : GhEnergySystem.cs
with GNU General Public License v3.0
from architecture-building-systems
with GNU General Public License v3.0
from architecture-building-systems
private void CreateViewModel(
IEnumerable<ConversionTech> conversionTechnologies, IEnumerable<Mesh> meshes, IEnumerable<Emitter> emitters)
{
if (_viewModel == null)
{
// first time we run CreateViewModel, _viewModel is not set yet...
_viewModel = new EnergySystemsInputViewModel();
_viewModel.ConversionTechnologies.Clear();
_viewModel.Surfaces.Clear();
_viewModel.Emitters.Clear();
}
// figure out which of the surfaces are from meshes... at the same time, if they came from Read(), hook them
// up to a mesh in meshes, in the same order
var meshSurfaces = _viewModel.MeshSurfaces.ToArray();
if (meshSurfaces.Length > 0 && meshSurfaces[0].Mesh == null)
// last operation was Read(), we need to hook up the meshes properly
for (var meshIndex = 0; meshIndex < meshSurfaces.Length; meshIndex++)
{
var surface = meshSurfaces[meshIndex];
surface.Mesh = meshes.ElementAt(meshIndex);
}
// remove parametrically defined conversion technologies and emitters - they'll be added below anyway
var formDefinedConversionTech =
_viewModel.ConversionTechnologies.Where(ct => !ct.IsParametricDefined).ToArray();
var formDefinedEmitters = _viewModel.Emitters.Where(e => !e.IsParametricDefined).ToArray();
_viewModel.ConversionTechnologies.Clear();
_viewModel.Emitters.Clear();
_viewModel.Surfaces.Clear();
var surfaceIndex = 0;
// was the list of meshes changed since the last SolveInstance?
foreach (var m in meshes)
if (meshSurfaces.Any(svm => svm.Mesh == m))
{
// mesh was input in last SolveInstance too, just keep it
var surface = meshSurfaces.First(svm => svm.Mesh == m);
surface.Name = $"srf{surfaceIndex++}";
_viewModel.Surfaces.Add(surface);
}
else
{
// mesh is a newly added mesh
var surface = new SurfaceViewModel
{
Area = AreaMreplacedProperties.Compute(m).Area,
Name = $"srf{surfaceIndex++}",
Mesh = m
};
_viewModel.Surfaces.Add(surface);
}
foreach (var ct in conversionTechnologies)
{
var ctvm = new ConversionTechPropertiesViewModel();
switch (ct)
{
case GasBoiler gasBoiler:
ctvm.Name = "Boiler (Gas)";
ctvm.SetProperties(gasBoiler);
break;
case Photovoltaic photovoltaic:
ctvm.Name = "Photovoltaic (PV)";
ctvm.SetProperties(photovoltaic);
var pvSurface = new SurfaceViewModel
{
Area = AreaMreplacedProperties.Compute(photovoltaic.SurfaceGeometry).Area,
Name = $"srf{surfaceIndex++}",
Mesh = photovoltaic.SurfaceGeometry
};
pvSurface.Connection = ctvm;
_viewModel.Surfaces.Add(pvSurface);
break;
case SolarThermal solarThermal:
ctvm.Name = "Solar Thermal (ST)";
ctvm.SetProperties(solarThermal);
var stSurface = new SurfaceViewModel
{
Area = AreaMreplacedProperties.Compute(solarThermal.SurfaceGeometry).Area,
Name = $"srf{surfaceIndex++}",
Mesh = solarThermal.SurfaceGeometry
};
stSurface.Connection = ctvm;
_viewModel.Surfaces.Add(stSurface);
break;
case AirSourceHeatPump ashp:
ctvm.Name = "ASHP (Electricity)";
ctvm.SetProperties(ashp);
break;
case CombinedHeatPower chp:
ctvm.Name = "CHP";
ctvm.SetProperties(chp);
break;
case Chiller chiller:
ctvm.Name = "Chiller (Electricity)";
ctvm.SetProperties(chiller);
break;
case HeatCoolingExchanger exchanger:
ctvm.Name = exchanger.IsHeating ? "Heat Exchanger" : "Cooling Exchanger";
ctvm.SetProperties(exchanger);
break;
}
_viewModel.ConversionTechnologies.Add(ctvm);
}
foreach (var ctvm in formDefinedConversionTech)
// add user (form) defined conversion technologies back to the list
_viewModel.ConversionTechnologies.Add(ctvm);
foreach (var emitter in emitters)
{
var epvm = new EmitterPropertiesViewModel();
switch (emitter)
{
case AirDiffuser airDiffuser:
epvm.Name = "Air diffuser";
epvm.SetProperties(airDiffuser);
break;
case Radiator radiator:
epvm.Name = "Radiator";
epvm.SetProperties(radiator);
break;
}
_viewModel.Emitters.Add(epvm);
}
foreach (var evm in formDefinedEmitters)
// add user (form) defined emitters back to the list
_viewModel.Emitters.Add(evm);
}
19
Source : CloudEventBatchContent.cs
with MIT License
from arcus-azure
with MIT License
from arcus-azure
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Guard.NotNull(stream, nameof(stream));
await EncodeStringToStreamAsync(stream, "[", cancellationToken: default);
for (int i = 0, l = _contents.Count(); i < l; i++)
{
CloudEventContent content = _contents.ElementAt(i);
await content.CopyToAsync(stream, context);
bool isNotLastElement = i + 1 < l;
if (isNotLastElement)
{
await EncodeStringToStreamAsync(stream, ",", cancellationToken: default);
}
}
await EncodeStringToStreamAsync(stream, "]", cancellationToken: default);
Headers.ContentType = MediaTypeHeaderValue.Parse(CloudEventBatchContentType);
}
19
Source : Client.cs
with MIT License
from arminreiter
with MIT License
from arminreiter
private static Tuple<double, double> GetMeterRate(Dictionary<double, double> meterRates, double includedQuanreplacedy, double totalUsedQuanreplacedy, double quanreplacedyToAdd)
{
Dictionary<double, double> modifiedMeterRates;
// add included quanreplacedy to meter rates with cost 0
if (includedQuanreplacedy > 0)
{
modifiedMeterRates = new Dictionary<double, double> { { 0, 0 } };
foreach (var rate in meterRates)
{
modifiedMeterRates.Add(rate.Key + includedQuanreplacedy, rate.Value);
}
}
else
modifiedMeterRates = meterRates;
double costs = 0.0;
double billableQuanreplacedy = 0.0;
for (int i = modifiedMeterRates.Count; i > 0; i--)
{
var totalNew = totalUsedQuanreplacedy + quanreplacedyToAdd;
var rate = modifiedMeterRates.ElementAt(i - 1);
var tmp = totalNew - rate.Key;
if (tmp >= 0)
{
if (tmp > quanreplacedyToAdd)
tmp = quanreplacedyToAdd;
costs += tmp * rate.Value;
if (rate.Value > 0)
billableQuanreplacedy += tmp;
quanreplacedyToAdd -= tmp;
if (quanreplacedyToAdd == 0)
break;
}
}
return new Tuple<double, double>(costs, billableQuanreplacedy);
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
public void RunCarousal()
{
m_Corousals.Add(m_SettingsSummary);
m_Corousals.Add(m_ProfitabilitySummary);
Form next = m_Corousals.ElementAt<Form>(m_CurrentCarousal);
BringToView(next);
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
void t_Tick()
{
return;//Enable this after profitability is implemented
TimeSpan elapsedTime = DateTime.Now - m_LastCarousalTurn;
if (elapsedTime.Seconds < CAROUSAL_WAIT)
return;
m_LastCarousalTurn = DateTime.Now;
Form previous = m_Corousals.ElementAt<Form>(m_CurrentCarousal);
m_CurrentCarousal++;
if (m_CurrentCarousal >= m_Corousals.Count)
m_CurrentCarousal = 0;
Form next = m_Corousals.ElementAt<Form>(m_CurrentCarousal);
RemoveFromView(previous);
BringToView(next);
}
19
Source : ImageAssetManager.cs
with Apache License 2.0
from ascora
with Apache License 2.0
from ascora
internal virtual void RecycleBitmaps()
{
lock (this)
{
for (var i = _imagereplacedets.Count - 1; i >= 0; i--)
{
var entry = _imagereplacedets.ElementAt(i);
entry.Value.Bitmap?.Dispose();
entry.Value.Bitmap = null;
_imagereplacedets.Remove(entry.Key);
}
}
}
19
Source : HttpHandler.cs
with MIT License
from Ashesh3
with MIT License
from Ashesh3
public Captcha.CaptchaSolution SolveCaptcha(Action<string> updateStatus, Models.Configuration config)
{
Logger.Debug("Getting captcha...");
updateStatus?.Invoke("Getting captcha...");
var captchaConfig = config.Captcha;
if (!GetRecaptcha(3, out string _siteKey, out _captchaGid, out bool? isRecaptcha))
return new Captcha.CaptchaSolution(true, "Get captcha info error!", captchaConfig);
if (string.IsNullOrEmpty(_captchaGid))
return new Captcha.CaptchaSolution(true, "Getting captcha GID error!", captchaConfig);
var captchaPayload = string.Empty;
if (isRecaptcha.HasValue && !isRecaptcha.Value)
{
//download and return captcha image
SetConfig($"{Defaults.Web.STEAM_RENDER_CAPTCHA_ADDRESS}?gid={_captchaGid}", Method.GET);
for (int i = 0; i < 3; i++)
{
try
{
Logger.Debug($"Downloading captcha: Try {i + 1}/3");
updateStatus($"Downloading captcha: Try {i + 1}/3");
var _captchaResp = _client.DownloadData(_request);
captchaPayload = GetBase64FromImage(_captchaResp);
break;
}
catch (Exception ex)
{
Logger.Error("Downloading captcha error.", ex);
captchaPayload = string.Empty;
}
}
}
// recognize captcha
Logger.Debug("Recognizing captcha...");
updateStatus("Recognizing captcha...");
switch (captchaConfig.Service)
{
case Enums.CaptchaService.Captchasolutions:
{
if (!captchaConfig.Enabled)
goto default;
var _params = new Dictionary<string, object>()
{
{ "key", captchaConfig.CaptchaSolutions.ApiKey },
{ "secret", captchaConfig.CaptchaSolutions.ApiSecret },
{ "out", "txt" },
};
if (isRecaptcha.HasValue && isRecaptcha.Value)
{
_params.Add("p", "nocaptcha");
_params.Add("googlekey", _siteKey);
_params.Add("pageurl", Defaults.Web.STEAM_JOIN_ADDRESS);
}
else
{
_params.Add("p", "base64");
_params.Add("captcha", $"data:image/jpg;base64,{captchaPayload}");
}
Logger.Debug("Recognizing captcha via Captchasolutions...");
var _resp = Captchasolutions("solve",
new Dictionary<string, object>()
{
{ "p", "base64" },
{ "captcha", $"data:image/jpg;base64,{captchaPayload}" },
{ "key", captchaConfig.CaptchaSolutions.ApiKey },
{ "secret", captchaConfig.CaptchaSolutions.ApiSecret },
{ "out", "txt" },
});
if (Regex.IsMatch(_resp, @"Error:\s(.+)", RegexOptions.IgnoreCase))
{
Logger.Warn($"Captchasolutions error:\n{_resp}\n====== END ======");
return new Captcha.CaptchaSolution(true, _resp, captchaConfig);
}
var solution = Regex.Replace(_resp, @"\t|\n|\r", "");
Logger.Debug($"Captchasolutions: {solution}");
return new Captcha.CaptchaSolution(solution, null, captchaConfig);
}
case Enums.CaptchaService.RuCaptcha:
{
if (!captchaConfig.Enabled)
goto default;
Logger.Debug("Recognizing captcha via TwoCaptcha/RuCaptcha");
var _params = new Dictionary<string, object>()
{
{ "key", captchaConfig.RuCaptcha.ApiKey },
{ "soft_id", "2370" },
{ "json", "0" }
};
if (isRecaptcha.HasValue && isRecaptcha.Value)
{
_params.Add("googlekey", _siteKey);
_params.Add("method", "userrecaptcha");
_params.Add("pageurl", Defaults.Web.STEAM_JOIN_ADDRESS);
}
else
{
_params.Add("body", $"data:image/jpg;base64,{captchaPayload}");
_params.Add("method", "base64");
}
var _captchaIdResponse = TwoCaptcha("in.php", _params);
var _captchaStatus = _captchaIdResponse?.FirstOrDefault()?.ToUpper() ?? "UNKNOWN";
Logger.Debug($"TwoCaptcha/RuCaptcha image upload response: {_captchaStatus}");
switch (_captchaStatus)
{
case "OK":
break;
case "ERROR_NO_SLOT_AVAILABLE":
Thread.Sleep(6000);
return new Captcha.CaptchaSolution(true, _captchaStatus, captchaConfig);
default:
return new Captcha.CaptchaSolution(false, _captchaStatus, captchaConfig);
}
var _captchaId = _captchaIdResponse.ElementAt(1);
Logger.Debug($"TwoCaptcha/RuCaptcha ID: {_captchaId}");
Thread.Sleep(TimeSpan.FromSeconds(20));
var solution = string.Empty;
var retryCount = (isRecaptcha.HasValue && isRecaptcha.Value)
? 10
: 3;
for (int i = 0; (Program.EndlessTwoCaptcha) ? true : i < retryCount; i++)
{
Logger.Debug($"TwoCaptcha/RuCaptcha requesting solution... Try {i + 1}{(Program.EndlessTwoCaptcha ? "" : $" of {retryCount}")}");
var _captchaResponse = TwoCaptcha("res.php",
new Dictionary<string, object>()
{
{ "key", captchaConfig.RuCaptcha.ApiKey },
{ "action", "get" },
{ "id", _captchaId },
{ "json", "0" },
});
var _status = _captchaResponse?.FirstOrDefault()?.ToUpper() ?? "UNKNOWN";
Logger.Debug($"TwoCaptcha/RuCaptcha solving status: {_status}");
switch (_status)
{
case "OK":
{
var _solution = new Captcha.CaptchaSolution(_captchaResponse.ElementAt(1), _captchaId, captchaConfig);
Logger.Debug($"TwoCaptcha/RuCaptcha solution: {_solution.Solution}");
return _solution;
}
case "CAPCHA_NOT_READY":
case "ERROR_NO_SLOT_AVAILABLE":
Thread.Sleep(6000);
continue;
default:
return new Captcha.CaptchaSolution(true, _status, captchaConfig);
}
}
}
Logger.Debug("TwoCaptcha/RuCaptcha somethig went wrong.");
return new Captcha.CaptchaSolution(true, "Something went wrong", captchaConfig);
case Enums.CaptchaService.Module:
{
try
{
if (isRecaptcha.HasValue && !isRecaptcha.Value)
{
var imageCaptchas = FormMain.ModuleManager.Modules.GetCaptchaSolvers();
if (imageCaptchas.Count() < 1)
goto default;
var anyRetryAvailable = false;
for (int i = 0; i < imageCaptchas.Count(); i++)
{
var ic = imageCaptchas.ElementAt(i);
var icResponse = ic.Solve(new SACModuleBase.Models.Capcha.CaptchaRequest(captchaPayload, FormMain.ProxyManager.WebProxy));
var icStatus = icResponse?.Status ?? SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve;
if (icStatus == SACModuleBase.Enums.Captcha.CaptchaStatus.Success)
return new Captcha.CaptchaSolution(icResponse.Solution, icResponse?.ToString(), captchaConfig);
switch (icStatus)
{
case SACModuleBase.Enums.Captcha.CaptchaStatus.RetryAvailable:
anyRetryAvailable = true;
continue;
case SACModuleBase.Enums.Captcha.CaptchaStatus.Failed:
case SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve:
continue;
}
}
return new Captcha.CaptchaSolution(anyRetryAvailable, "Something went wrong...", captchaConfig);
}
else
{
var reCaptchas = FormMain.ModuleManager.Modules.GetReCaptchaSolvers();
if (reCaptchas.Count() < 1)
goto default;
var anyRetryAvailable = false;
for (int i = 0; i < reCaptchas.Count(); i++)
{
var rc = reCaptchas.ElementAt(i);
var rcResponse = rc.Solve(new SACModuleBase.Models.Capcha.ReCaptchaRequest(_siteKey, Defaults.Web.STEAM_JOIN_ADDRESS));
var rcStatus = rcResponse?.Status ?? SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve;
if (rcStatus == SACModuleBase.Enums.Captcha.CaptchaStatus.Success)
return new Captcha.CaptchaSolution(rcResponse.Solution, rcResponse?.ToString(), captchaConfig);
switch (rcStatus)
{
case SACModuleBase.Enums.Captcha.CaptchaStatus.RetryAvailable:
anyRetryAvailable = true;
continue;
case SACModuleBase.Enums.Captcha.CaptchaStatus.Failed:
case SACModuleBase.Enums.Captcha.CaptchaStatus.CannotSolve:
continue;
}
}
return new Captcha.CaptchaSolution(anyRetryAvailable, "Something went wrong...", captchaConfig);
}
}
catch (Exception ex)
{
Logger.Error($"Module solving error.", ex);
}
}
return new Captcha.CaptchaSolution(true, "Something went wrong.", captchaConfig);
default:
{
try
{
var recap = isRecaptcha.HasValue && isRecaptcha.Value;
using (var dialog = (recap)
? FormMain.ExecuteInvoke(() => new ReCaptchaDialog(config, FormMain.ProxyManager.Current) as ICaptchaDialog)
: new CaptchaDialog(this, updateStatus, config))
{
var solution = default(Captcha.CaptchaSolution);
var dialogResult = DialogResult.None;
if (recap)
dialogResult = FormMain.ExecuteInvokeLock(() => dialog.ShowDialog(out solution));
else // for image captcha we don't wait other windowses
dialogResult = dialog.ShowDialog(out solution);
if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Cancel)
{
solution = solution ?? new Captcha.CaptchaSolution(true, "Something went wrong...", config.Captcha);
if (recap)
_captchaGid = (string.IsNullOrEmpty(solution?.Id)) ? _captchaGid : solution?.Id ?? "";
return solution;
}
else
return new Captcha.CaptchaSolution(false, "Captcha not recognized!", config.Captcha);
}
}
catch (Exception ex)
{
Logger.Error("Manual captcha error.", ex);
}
}
return new Captcha.CaptchaSolution(true, "Something went wrong.", captchaConfig);
}
}
19
Source : Utility.cs
with MIT License
from Ashesh3
with MIT License
from Ashesh3
public static T RandomElement<T>(this IEnumerable<T> collection)
{
if ((collection?.Count() ?? 0) < 1)
return default(T);
else if (collection.Count() == 1)
return collection.First();
return collection.ElementAt(GetRandomNumber(0, collection.Count() - 1));
}
19
Source : Communicator.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
private Task HandleReactionAdded(Cacheable<IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
{
TaskHelper.FireForget(async () =>
{
try
{
if (reaction.UserId == _client.CurrentUser.Id)
return;
// Check for page arrows
if (reaction.Emote.Name != ArrowLeft.Name && reaction.Emote.Name != ArrowRight.Name)
return;
// Lock and check if we have a page context for this message
PaginatedMessageContext context;
lock (_paginatedMessages)
{
if (!_paginatedMessages.TryGetValue(message.Id, out context))
return;
}
try
{
await context.Lock.WaitAsync();
// If requested, only allow the original invoker of the command to flip pages
var concMessage = await message.GetOrDownloadAsync();
if (context.ControlledByInvoker && reaction.UserId != context.InvokerUserId)
return;
// Message was touched -> refresh expiration date
context.ExtendLife();
// Calculate new page index and check bounds
var newPage = context.CurrentPage + (reaction.Emote.Name == ArrowLeft.Name ? -1 : 1);
if (newPage < 0 || newPage >= context.TotalPages)
{
await RemovePageReaction(concMessage, reaction.Emote, reaction.UserId);
return;
}
// Modify or resend message
var newMessage = context.Pages.ElementAt(newPage);
if (context.Resend)
{
await concMessage.DeleteAsync();
var result = await concMessage.Channel.SendMessageAsync(newMessage.Content?.Sanitise(), false, newMessage.Embed?.Build());
lock (_paginatedMessages)
{
_paginatedMessages.Add(result.Id, context);
}
await result.AddReactionAsync(ArrowLeft);
await result.AddReactionAsync(ArrowRight);
}
else
{
await concMessage.ModifyAsync(x =>
{
x.Content = newMessage.Content;
x.Embed = newMessage.Embed?.Build();
});
await RemovePageReaction(concMessage, reaction.Emote, reaction.UserId);
}
// Update context
context.CurrentPage = newPage;
}
finally
{
context.Lock.Release();
}
}
catch (Exception ex)
{
_logger.WithScope(reaction).LogError(ex, "Failed to flip a page for PaginatedMessage");
}
});
return Task.CompletedTask;
}
19
Source : StorageManagerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task ExecuteBatch_ReturnsResults_OnSuccess()
{
// Arrange
var table = InitializeTable();
ITableEnreplacedy enreplacedy1 = new DynamicTableEnreplacedy(TestParreplacedion, "data A");
var operation1 = TableOperation.Insert(enreplacedy1);
ITableEnreplacedy enreplacedy2 = new DynamicTableEnreplacedy(TestParreplacedion, "data B");
var operation2 = TableOperation.Insert(enreplacedy2);
var batch = new TableBatchOperation
{
operation1,
operation2
};
// Act
ICollection<TableResult> actual = await _manager.ExecuteBatchAsync(table, batch);
// replacedert
replacedert.Equal(2, actual.Count);
replacedert.Equal(204, actual.ElementAt(0).HttpStatusCode);
replacedert.Equal(204, actual.ElementAt(1).HttpStatusCode);
}
19
Source : SalesforceNotificationsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void Notifications_Values_AreExtracted()
{
// Act
IEnumerable<Dictionary<string, string>> actual = _notifications1.Notifications;
// Act
replacedert.Equal(3, actual.Count());
replacedert.Equal("0123456789ABCDEEAE", actual.ElementAt(0)["Id"]);
replacedert.Equal("Lead1", actual.ElementAt(0)["_NotificationType"]);
replacedert.Equal("04l37000000L0E5AAK", actual.ElementAt(0)["_NotificationId"]);
replacedert.Equal("1123456789ABCDEEAE", actual.ElementAt(1)["Id"]);
replacedert.Equal("Lead2", actual.ElementAt(1)["_NotificationType"]);
replacedert.Equal("14l37000123L0E5AAK", actual.ElementAt(1)["_NotificationId"]);
replacedert.Equal("2123456789ABCDEEAE", actual.ElementAt(2)["Id"]);
replacedert.Equal("Lead3", actual.ElementAt(2)["_NotificationType"]);
replacedert.Equal("24l37123450L0E5AAK", actual.ElementAt(2)["_NotificationId"]);
}
19
Source : Satsuma.cs
with GNU General Public License v3.0
from Athlon007
with GNU General Public License v3.0
from Athlon007
public void ToggleElements(float distance)
{
if (Toggle == IgnoreToggle)
distance = 0;
// Don't disable any elements, if the AI is driving the Satsuma.
if (drivingAI != null && drivingAI.enabled)
distance = 0;
try
{
bool onEngine = distance < 2;
bool onClose = distance <= 10 * MopSettings.ActiveDistanceMultiplicationValue;
bool onFar = distance <= 20 * MopSettings.ActiveDistanceMultiplicationValue;
if (IsKeyInserted() || IsSatsumaInInspectionArea || IsMoving())
{
onEngine = true;
onClose = true;
onFar = true;
}
for (int i = 0; i < satsumaOnActionObjects.Count; i++)
{
if (satsumaOnActionObjects[i].FSM == null && satsumaOnActionObjects[i].GameObject == null) continue;
if (satsumaOnActionObjects[i].FSM != null)
{
switch (satsumaOnActionObjects[i].EnableOn)
{
case SatsumaEnableOn.OnEngine:
satsumaOnActionObjects[i].FSM.enabled = onEngine;
break;
case SatsumaEnableOn.OnPlayerClose:
satsumaOnActionObjects[i].FSM.enabled = onClose;
break;
case SatsumaEnableOn.OnPlayerFar:
satsumaOnActionObjects[i].FSM.enabled = onFar;
break;
}
}
if (satsumaOnActionObjects[i].GameObject != null)
{
switch (satsumaOnActionObjects[i].EnableOn)
{
case SatsumaEnableOn.OnEngine:
satsumaOnActionObjects[i].GameObject.SetActive(onEngine);
break;
case SatsumaEnableOn.OnPlayerClose:
satsumaOnActionObjects[i].GameObject.SetActive(onClose);
break;
case SatsumaEnableOn.OnPlayerFar:
satsumaOnActionObjects[i].GameObject.SetActive(onFar);
break;
}
}
}
if (onEngine)
{
// This script fixes the issue with bolts staying unbolted, with parts internally being fully bolted.
if (maskedFixStages < 2)
{
switch (maskedFixStages)
{
case 0:
for (int i = 0; i < maskedElements.Count; i++)
maskedElements.ElementAt(i).Key.SetActive(true);
break;
case 1:
for (int i = 0; i < maskedElements.Count; i++)
maskedElements.ElementAt(i).Key.SetActive(maskedElements.ElementAt(i).Value);
break;
}
maskedFixStages++;
}
}
else
{
cooldownTick.SetActive(false);
}
if (onFar)
{
hasBeenMovedByFleetari = false;
UnglueAll();
}
}
catch (System.Exception ex)
{
ExceptionManager.New(ex, true, "SATSUMA_TOGGLE_ELEMENTS_ERROR");
}
}
19
Source : SiraSaberClashChecker.cs
with MIT License
from Auros
with MIT License
from Auros
public override bool AreSabersClashing(out Vector3 clashingPoint)
{
if (!_extraSabersDetected)
{
return base.AreSabersClashing(out clashingPoint);
}
if (_leftSaber.movementData.lastAddedData.time < 0.1f)
{
clashingPoint = _clashingPoint;
return false;
}
if (_prevGetFrameNum == Time.frameCount)
{
clashingPoint = _clashingPoint;
return _sabersAreClashing;
}
_prevGetFrameNum = Time.frameCount;
for (int i = 0; i < _sabers.Count; i++)
{
for (int h = 0; h < _sabers.Count; h++)
{
if (i > h)
{
Saber saberA = _sabers.ElementAt(i);
Saber saberB = _sabers.ElementAt(h);
if (saberA == saberB || saberA == null || saberB == null)
{
break;
}
Vector3 saberBladeTopPos = saberA.saberBladeTopPos;
Vector3 saberBladeTopPos2 = saberB.saberBladeTopPos;
Vector3 saberBladeBottomPos = saberA.saberBladeBottomPos;
Vector3 saberBladeBottomPos2 = saberB.saberBladeBottomPos;
if (SegmentToSegmentDist(saberBladeBottomPos, saberBladeTopPos, saberBladeBottomPos2, saberBladeTopPos2, out var clashingPoint2) < 0.08f && saberA.isActiveAndEnabled && saberB.isActiveAndEnabled)
{
if (_lastSaberA == null && _lastSaberB == null)
{
_lastSaberA = saberA;
_lastSaberB = saberB;
NewSabersClashed?.Invoke(_lastSaberA, _lastSaberB);
}
_clashingPoint = clashingPoint2;
clashingPoint = _clashingPoint;
_sabersAreClashing = true;
return _sabersAreClashing;
}
else
{
_lastSaberA = null;
_lastSaberB = null;
_sabersAreClashing = false;
}
}
}
}
clashingPoint = _clashingPoint;
return _sabersAreClashing;
}
19
Source : Ticket.cs
with MIT License
from Auros
with MIT License
from Auros
public Ticket Copy()
{
var ticket = new Ticket(Source, replacedembly);
for (int i = 0; i < _reasons.Count(); i++)
ticket.AddReason(_reasons.ElementAt(i));
return ticket;
}
19
Source : HexUtility.cs
with MIT License
from AurelWu
with MIT License
from AurelWu
public static List<Vector3Int> RemoveInvalidCoordinates(List<Vector3Int> inputCollection, Dictionary<Vector3Int, int> validCollection)
{
for (int i = 0; i < inputCollection.Count; i++)
{
Vector3Int element = inputCollection.ElementAt(i);
if (!validCollection.ContainsKey(element))
{
inputCollection.Remove(element);
i--;
}
}
return inputCollection;
}
19
Source : CustomLocaleLoader.cs
with MIT License
from Auros
with MIT License
from Auros
public async Task LoadLocales()
{
var folder = Path.Combine(UnityGame.UserDataPath, "SIRA", "Localizations");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var files = new DirectoryInfo(folder).EnumerateFiles().Where(x => x.Extension == ".csv" || x.Extension == ".tsv");
for (int i = 0; i < files.Count(); i++)
{
var file = files.ElementAt(i);
using (var reader = File.OpenText(file.FullName))
{
var fileText = await reader.ReadToEndAsync();
_localizer.AddLocalizationSheet(fileText, file.Extension.EndsWith("csv") ? GoogleDriveDownloadFormat.CSV : GoogleDriveDownloadFormat.TSV, file.FullName);
}
}
}
19
Source : Lanelet.cs
with GNU Lesser General Public License v3.0
from autocore-ai
with GNU Lesser General Public License v3.0
from autocore-ai
private Mesh LinkLeftRightPointsMesh(List<Vector3> left, List<Vector3> right)
{
Mesh ret = new Mesh
{
name = name
};
var count = left.Count + right.Count - 2;
var lastLeft = left.First();
var lastRight = right.First();
var lastLeftIndex = 1;
var lastRightIndex = 0;
var leftCount = 1;
var rightCount = 1;
List<Vector3> points = new List<Vector3> { lastRight, lastLeft };
List<int> indices = new List<int>();
for (int i = 0; i < count; i++)
{
float dl = 0, dr = 0;
bool addLeft = true, addRight = true;
if (left.Count > leftCount)
{
dl = Vector3.Distance(left.ElementAt(leftCount), lastRight);
}
else
{
addLeft = false;
}
if (right.Count > rightCount)
{
dr = Vector3.Distance(right.ElementAt(rightCount), lastLeft);
}
else
{
addRight = false;
}
if (addLeft || addRight)
{
indices.Add(lastRightIndex);
indices.Add(lastLeftIndex);
}
else
{
return ret;
}
if (addLeft && addRight)
{
if (dl > dr)
{
addLeft = false;
}
}
if (addLeft)
{
lastLeft = left.ElementAt(leftCount++);
lastLeftIndex = i + 2;
points.Add(lastLeft);
indices.Add(lastLeftIndex);
}
else
{
lastRight = right.ElementAt(rightCount++);
lastRightIndex = i + 2;
points.Add(lastRight);
indices.Add(lastRightIndex);
}
}
ret.SetVertices(points);
ret.SetIndices(indices, MeshTopology.Triangles, 0);
return ret;
}
19
Source : Utils.cs
with GNU Lesser General Public License v3.0
from autocore-ai
with GNU Lesser General Public License v3.0
from autocore-ai
public static void DestroyAll<T>(this ICollection<T> collection) where T : Object
{
for (int i = 0; i < collection.Count; i++)
{
Undo.DestroyObjectImmediate(collection.ElementAt(i));
}
}
19
Source : Way.cs
with GNU Lesser General Public License v3.0
from autocore-ai
with GNU Lesser General Public License v3.0
from autocore-ai
internal void EditPoints()
{
if (nodes.Count > 0)
{
var originPositions = nodes.Select(_ => _.transform.position);
for (int i = 0; i < originPositions.Count(); i++)
{
var oldPosition = originPositions.ElementAt(i);
var newPosition = Handles.PositionHandle(oldPosition, Quaternion.idenreplacedy);
if (!newPosition.Equals(oldPosition))
{
nodes[i].Position = newPosition;
}
}
}
}
19
Source : AsciiStlFileReader.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
public List<DMTModel> ReadFile(File file, IDMTModelFilter filter)
{
if (file.Exists == false)
{
throw new DMTFileException(DMTFileError.FileDoesNotExist);
}
var blocksIn = new List<DMTTriangleBlock>();
var blocksOut = new List<DMTTriangleBlock>();
var blockIn = new DMTTriangleBlock();
var blockOut = new DMTTriangleBlock();
var vertices = new List<Point>();
foreach (var strLine in file.ReadTextLines())
{
if (strLine.Trim().StartsWith("vertex "))
{
//Add position
var strCoords = strLine.Trim().Split(' ');
var intCounter = 0;
double x = 0;
double y = 0;
double z = 0;
foreach (var strCoord in strCoords)
{
if (Information.IsNumeric(strCoord))
{
if (intCounter == 0)
{
x = Convert.ToDouble(strCoord);
}
else if (intCounter == 1)
{
y = Convert.ToDouble(strCoord);
}
else
{
z = Convert.ToDouble(strCoord);
}
intCounter += 1;
}
}
vertices.Add(new Point(x, y, z));
}
else if (strLine.Trim().StartsWith("endloop"))
{
if (filter.CanAddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2)))
{
blockIn.AddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2));
}
else
{
blockOut.AddTriangle(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2));
}
vertices.Clear();
}
}
blocksIn.Add(blockIn);
blocksOut.Add(blockOut);
var modelWithinFilter = new DMTModel();
var modelOutsideFilter = new DMTModel();
modelWithinFilter.TriangleBlocks.AddRange(blocksIn);
modelOutsideFilter.TriangleBlocks.AddRange(blocksOut);
var result = new List<DMTModel>();
result.Add(modelWithinFilter);
result.Add(modelOutsideFilter);
return result;
}
19
Source : Application.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
private void ImportProperty(string enreplacedyClreplacedId, string propertyName, string[] values)
{
List<PropDef> propDefs = new List<PropDef>();
PropDef[] tmp = ServiceManager.PropertyService.GetPropertyDefinitionsByEnreplacedyClreplacedId(enreplacedyClreplacedId);
if (null != tmp)
{
propDefs.AddRange(tmp);
}
IEnumerable<PropDef> props = propDefs.Where(p => p.DispName == propertyName);
if (props.Count() != 0)
{
PropDef propDef = props.ElementAt(0);
EntClreplacedreplacedoc entreplacedoc = propDef.EntClreplacedreplacedocArray.SingleOrDefault(i => i.EntClreplacedId == enreplacedyClreplacedId);
if (entreplacedoc == null)
{
entreplacedoc = new EntClreplacedreplacedoc();
entreplacedoc.EntClreplacedId = enreplacedyClreplacedId;
entreplacedoc.MapDirection = AllowedMappingDirection.ReadAndWrite;
List<EntClreplacedreplacedoc> replacedocs = new List<EntClreplacedreplacedoc>();
replacedocs.AddRange(propDef.EntClreplacedreplacedocArray);
replacedocs.Add(entreplacedoc);
propDef.EntClreplacedreplacedocArray = replacedocs.ToArray();
}
EntClreplacedCtntSrcPropCfg[] contentMappings = null;
PropConstr[] constraints = null;
PropDefInfo[] propInfos = ServiceManager.PropertyService.GetPropertyDefinitionInfosByEnreplacedyClreplacedId(enreplacedyClreplacedId, new long[] { propDef.Id });
if (propInfos != null)
{
contentMappings = propInfos[0].EntClreplacedCtntSrcPropCfgArray;
constraints = propInfos[0].PropConstrArray;
}
ServiceManager.PropertyService.UpdatePropertyDefinitionInfo(propDef, contentMappings, constraints, values);
return;
}
// doesn't exist, create new one
string systemName = Guid.NewGuid().ToString("D");
ServiceManager.PropertyService.AddPropertyDefinition(systemName, propertyName, DataType.String, true, true, values[0], new string[] { enreplacedyClreplacedId }, null, null, values);
}
19
Source : Chart.cs
with MIT License
from AvaloniaCommunity
with MIT License
from AvaloniaCommunity
protected void DrawCaptionElements(SKCanvas canvas, int width, int height, List<Entry> entries, bool isLeft)
{
var margin = 2 * this.Margin;
var availableHeight = height - (2 * margin);
var x = isLeft ? this.Margin : (width - this.Margin - this.LabelTextSize);
var ySpace = (availableHeight - this.LabelTextSize) / ((entries.Count <= 1) ? 1 : entries.Count - 1);
for (int i = 0; i < entries.Count; i++)
{
var entry = entries.ElementAt(i);
var y = margin + (i * ySpace);
if (entries.Count <= 1)
{
y += (availableHeight - this.LabelTextSize) / 2;
}
var hasLabel = !string.IsNullOrEmpty(entry.Label);
var hasValueLabel = !string.IsNullOrEmpty(entry.ValueLabel);
if (hasLabel || hasValueLabel)
{
var hasOffset = hasLabel && hasValueLabel;
var captionMargin = this.LabelTextSize * 0.60f;
var space = hasOffset ? captionMargin : 0;
var captionX = isLeft ? this.Margin : width - this.Margin - this.LabelTextSize;
using (var paint = new SKPaint
{
Style = SKPaintStyle.Fill,
Color = entry.Color,
})
{
var rect = SKRect.Create(captionX, y, this.LabelTextSize, this.LabelTextSize);
canvas.DrawRect(rect, paint);
}
if (isLeft)
{
captionX += this.LabelTextSize + captionMargin;
}
else
{
captionX -= captionMargin;
}
canvas.DrawCaptionLabels(entry.Label, entry.TextColor, entry.ValueLabel, entry.Color, this.LabelTextSize, new SKPoint(captionX, y + (this.LabelTextSize / 2)), isLeft ? SKTextAlign.Left : SKTextAlign.Right);
}
}
}
19
Source : Extension.cs
with MIT License
from avarghesein
with MIT License
from avarghesein
public static void TryForEach<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
{
if (enumerable == null || handler == null)
{
return;
}
for (int index = 0; index < enumerable.Count(); ++index)
{
handler(enumerable.ElementAt(index), index);
}
}
19
Source : Extension.cs
with MIT License
from avarghesein
with MIT License
from avarghesein
public static void TryForEach<T>(this IEnumerable<T> enumerable, Action<T> handler)
{
if (enumerable == null || handler == null)
{
return;
}
for (int index = 0; index < enumerable.Count(); ++index)
{
handler(enumerable.ElementAt(index));
}
}
19
Source : AttackDragon.cs
with MIT License
from avestura
with MIT License
from avestura
public List<object[]> FillList(List<object[]> testCases, int len)
{
var result = new List<object[]>();
var maxes = testCases.Select(item => item.Length).ToArray();
var currentIndexes = new int[testCases.Count];
var halaat = testCases.Multiply(item => item.Length);
for (int i = 0; i < halaat; i++)
{
var answer = new object[len];
for (int j = 0; j < len; j++)
{
answer[j] = testCases[j].ElementAt(currentIndexes[j]);
}
result.Add(answer);
currentIndexes = IncrementSelectIndexes(currentIndexes, maxes, 0);
}
return result;
}
19
Source : DefaultRepositoryActionProvider.cs
with MIT License
from awaescher
with MIT License
from awaescher
public RepositoryAction GetSecondaryAction(Repository repository)
{
var actions = GetContextMenuActions(new[] { repository });
return actions.Count() > 1 ? actions.ElementAt(1) : null;
}
19
Source : FastRandom.cs
with GNU General Public License v3.0
from axx0
with GNU General Public License v3.0
from axx0
public T ChooseFrom<T>(ISet<T> items)
{
return items.Count == 1 ? items.First() : items.ElementAt(Next(items.Count));
}
19
Source : SqlMapperExtensions.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static long Insert<T>(this IDbConnection connection, T enreplacedyToInsert, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
{
bool flag = false;
Type type = typeof(T);
if (type.IsArray)
{
flag = true;
type = type.GetElementType();
}
else if (type.IsGenericType())
{
flag = true;
type = type.GetGenericArguments()[0];
}
string tableName = GetTableName(type);
StringBuilder stringBuilder = new StringBuilder(null);
List<PropertyInfo> first = TypePropertiesCache(type);
List<PropertyInfo> list = KeyPropertiesCache(type);
List<PropertyInfo> second = ComputedPropertiesCache(type);
List<PropertyInfo> list2 = first.Except(list.Union(second)).ToList();
ISqlAdapter formatter = GetFormatter(connection);
for (int i = 0; i < list2.Count; i++)
{
PropertyInfo propertyInfo = list2.ElementAt(i);
formatter.AppendColumnName(stringBuilder, propertyInfo.Name);
if (i < list2.Count - 1)
{
stringBuilder.Append(", ");
}
}
StringBuilder stringBuilder2 = new StringBuilder(null);
for (int j = 0; j < list2.Count; j++)
{
PropertyInfo propertyInfo2 = list2.ElementAt(j);
stringBuilder2.AppendFormat("@{0}", propertyInfo2.Name);
if (j < list2.Count - 1)
{
stringBuilder2.Append(", ");
}
}
bool num = connection.State == ConnectionState.Closed;
if (num)
{
connection.Open();
}
int num2;
if (!flag)
{
num2 = formatter.Insert(connection, transaction, commandTimeout, tableName, stringBuilder.ToString(), stringBuilder2.ToString(), list, enreplacedyToInsert);
}
else
{
string text = string.Format("insert into {0} ({1}) values ({2})", tableName, stringBuilder, stringBuilder2);
num2 = SqlMapper.Execute(connection, text, (object)enreplacedyToInsert, transaction, commandTimeout, (CommandType?)null);
}
if (num)
{
connection.Close();
}
return num2;
}
19
Source : SqlMapperExtensions.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static bool Update<T>(this IDbConnection connection, T enreplacedyToUpdate, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
{
IProxy proxy = enreplacedyToUpdate as IProxy;
if (proxy != null && !proxy.IsDirty)
{
return false;
}
Type type = typeof(T);
if (type.IsArray)
{
type = type.GetElementType();
}
else if (type.IsGenericType())
{
type = type.GetGenericArguments()[0];
}
List<PropertyInfo> list = KeyPropertiesCache(type).ToList();
List<PropertyInfo> list2 = ExplicitKeyPropertiesCache(type);
if (!list.Any() && !list2.Any())
{
throw new ArgumentException("Enreplacedy must have at least one [Key] or [ExplicitKey] property");
}
string tableName = GetTableName(type);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("update {0} set ", tableName);
List<PropertyInfo> first = TypePropertiesCache(type);
list.AddRange(list2);
List<PropertyInfo> second = ComputedPropertiesCache(type);
List<PropertyInfo> list3 = first.Except(list.Union(second)).ToList();
ISqlAdapter formatter = GetFormatter(connection);
for (int i = 0; i < list3.Count; i++)
{
PropertyInfo propertyInfo = list3.ElementAt(i);
formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo.Name);
if (i < list3.Count - 1)
{
stringBuilder.AppendFormat(", ");
}
}
stringBuilder.Append(" where ");
for (int j = 0; j < list.Count; j++)
{
PropertyInfo propertyInfo2 = list.ElementAt(j);
formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo2.Name);
if (j < list.Count - 1)
{
stringBuilder.AppendFormat(" and ");
}
}
return SqlMapper.Execute(connection, stringBuilder.ToString(), (object)enreplacedyToUpdate, transaction, commandTimeout, (CommandType?)null) > 0;
}
19
Source : SqlMapperExtensions.cs
with MIT License
from ay2015
with MIT License
from ay2015
public static bool Delete<T>(this IDbConnection connection, T enreplacedyToDelete, IDbTransaction transaction = null, int? commandTimeout = default(int?)) where T : clreplaced
{
if (enreplacedyToDelete == null)
{
throw new ArgumentException("Cannot Delete null Object", "enreplacedyToDelete");
}
Type type = typeof(T);
if (type.IsArray)
{
type = type.GetElementType();
}
else if (type.IsGenericType())
{
type = type.GetGenericArguments()[0];
}
List<PropertyInfo> list = KeyPropertiesCache(type).ToList();
List<PropertyInfo> list2 = ExplicitKeyPropertiesCache(type);
if (!list.Any() && !list2.Any())
{
throw new ArgumentException("Enreplacedy must have at least one [Key] or [ExplicitKey] property");
}
string tableName = GetTableName(type);
list.AddRange(list2);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("delete from {0} where ", tableName);
ISqlAdapter formatter = GetFormatter(connection);
for (int i = 0; i < list.Count; i++)
{
PropertyInfo propertyInfo = list.ElementAt(i);
formatter.AppendColumnNameEqualsValue(stringBuilder, propertyInfo.Name);
if (i < list.Count - 1)
{
stringBuilder.AppendFormat(" and ");
}
}
return SqlMapper.Execute(connection, stringBuilder.ToString(), (object)enreplacedyToDelete, transaction, commandTimeout, (CommandType?)null) > 0;
}
19
Source : JPathExecuteTests.cs
with MIT License
from azambrano
with MIT License
from azambrano
[Fact]
public void EvaluateArrayMultipleIndexes()
{
var a = JsonDoreplacedent.Parse(@"[1, 2, 3, 4]");
IEnumerable<JsonElement?> t = a.SelectElements("[1,2,0]").ToList();
replacedert.NotNull(t);
replacedert.Equal(3, t.Count());
replacedert.Equal(2, t.ElementAt(0).Value.GetInt32());
replacedert.Equal(3, t.ElementAt(1).Value.GetInt32());
replacedert.Equal(1, t.ElementAt(2).Value.GetInt32());
}
19
Source : PileTest64Gb.cs
with MIT License
from azist
with MIT License
from azist
[Run]
public void Parallel_PutGetDelete_Random()
{
const int PUTTER_CNT = 2, PUTTER_OP_CNT = 2 * 10000;
const int GETTER_CNT = 6, GETTER_OP_CNT = 2 * 30000;
const int DELETER_CNT = 2, DELETER_OP_CNT = 2 * 10000;
var data = new ConcurrentDictionary<PilePointer, string>();
var getAccessViolations = new ConcurrentDictionary<int, int>();
var deleteAccessViolations = new ConcurrentDictionary<int, int>();
using (var pile = new DefaultPile(NOPApplication.Instance))
{
pile.Start();
var ipile = pile as IPile;
// putter tasks
var putters = new Task[PUTTER_CNT];
for (int it = 0; it < PUTTER_CNT; it++)
{
var task = new Task(() =>
{
for (int i = 0; i < PUTTER_OP_CNT; i++)
{
var str = Azos.Text.NaturalTextGenerator.Generate();
var pp = ipile.Put(str);
data.TryAdd(pp, str);
}
});
putters[it] = task;
}
// getter tasks
var getters = new Task[GETTER_CNT];
for (int it = 0; it < GETTER_CNT; it++)
{
var task = new Task(() =>
{
for (int i = 0; i < GETTER_OP_CNT; i++)
{
if (data.Count == 0)
{
System.Threading.Thread.Yield();
continue;
}
var idx = Ambient.Random.NextScaledRandomInteger(0, data.Count - 1);
var kvp = data.ElementAt(idx);
try
{
var str = ipile.Get(kvp.Key);
Aver.AreObjectsEqual(str, kvp.Value);
}
catch (PileAccessViolationException)
{
getAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
}
}
});
getters[it] = task;
}
// deleter tasks
var deleters = new Task[DELETER_CNT];
for (int it = 0; it < DELETER_CNT; it++)
{
var task = new Task(() =>
{
for (int i = 0; i < DELETER_OP_CNT; i++)
{
if (data.Count == 0)
{
System.Threading.Thread.Yield();
continue;
}
var idx = Ambient.Random.NextScaledRandomInteger(0, data.Count - 1);
var kvp = data.ElementAt(idx);
try
{
ipile.Delete(kvp.Key);
}
catch (PileAccessViolationException)
{
deleteAccessViolations.AddOrUpdate(System.Threading.Thread.CurrentThread.ManagedThreadId, 1, (mid, val) => val + 1);
}
}
});
deleters[it] = task;
}
foreach (var task in putters) task.Start();
foreach (var task in getters) task.Start();
foreach (var task in deleters) task.Start();
Task.WaitAll(putters.Concat(getters).Concat(deleters).ToArray());
foreach (var kvp in getAccessViolations)
Console.WriteLine("Get thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
foreach (var kvp in deleteAccessViolations)
Console.WriteLine("Del thread '{0}' {1:n0} times accessed deleted pointer", kvp.Key, kvp.Value);
}
}
See More Examples