static void ParseLaboC1(IList <string> recordParts, Labo labo, int lineNumber) { if (recordParts.Count != 2) { labo.ParserErrors.AddItem(lineNumber, $"Expected 4 parts in C1 but got {recordParts.Count} parts: '{string.Join("\\", recordParts)}'"); } if (labo.Contact == null) { labo.Contact = new Contact(); } labo.Contact.Number = recordParts.ElementAtOrDefault(0); switch (recordParts.ElementAtOrDefault(1)) { case "01": case "1": labo.Contact.Type = ContactType.Consultation; break; case "02": case "2": labo.Contact.Type = ContactType.Hospitalization; break; default: labo.Contact.Type = ContactType.Unknown; break; } labo.Contact.StartDate = recordParts.ElementAtOrDefault(2)?.ToNullableDatetime("dd/MM/yyyy"); labo.Contact.EndDate = recordParts.ElementAtOrDefault(3)?.ToNullableDatetime("dd/MM/yyyy"); }
// Here we convert constants and vars into expression containers, combine simple expresions // and create IAssign's and ILCalls if nessasary bool CombineExpressions(IList <ILNode> nodes, ILExpression expr, int pos) { if (expr.Code.isExpression() && expr.Arguments.Count == 0) { int popDelta = expr.Code.GetPopDelta(); ILExpression left; ILExpression right; if (popDelta == 1 && nodes.ElementAtOrDefault(pos - 1).Match(GMCode.Push, out left) && left.isNodeResolved()) { expr.Arguments.Add(left); nodes[pos] = new ILExpression(GMCode.Push, null, expr); // change it to a push nodes.RemoveAt(pos - 1); return(true); } else if ( popDelta == 2 && (nodes.ElementAtOrDefault(pos - 1).Match(GMCode.Push, out left) && left.isNodeResolved()) && (nodes.ElementAtOrDefault(pos - 2).Match(GMCode.Push, out right) && right.isNodeResolved())) { expr.Arguments.Add(right); expr.Arguments.Add(left); nodes[pos] = new ILExpression(GMCode.Push, null, expr); // change it to a push nodes.RemoveRange(pos - 2, 2); return(true); } } return(false); }
public int Run(IList <string> args) { string command = args.FirstOrDefault() ?? ""; _stdout.WriteLine("executing subtree " + command); if (string.IsNullOrEmpty(Prefix)) { _stdout.WriteLine("Prefix must be specified, use -p or -prefix"); return(GitTfsExitCodes.InvalidArguments); } switch (command.ToLower()) { case "add": return(DoAdd(args.ElementAtOrDefault(1) ?? "", args.ElementAtOrDefault(2) ?? "")); case "pull": return(DoPull(args.ElementAtOrDefault(1))); case "split": return(DoSplit()); default: _stdout.WriteLine("Expected one of [add, pull, split]"); return(GitTfsExitCodes.InvalidArguments); } }
/// <summary> /// Navigate through list of imagelabels for labels. /// </summary> /// <param name="imageLabels">List of imagelabels to navigate.</param> /// <param name="navigationDirection">Direction of navigation</param> /// <param name="currentIndex">Current index</param> /// <returns>Imagelabel of navigation</returns> private static ImageLabel NavigateLabels(this IList <ImageLabel> imageLabels, ENavigationDirection navigationDirection, int currentIndex) { switch (navigationDirection) { case ENavigationDirection.Direct: return(imageLabels.ElementAtOrDefault(currentIndex)); case ENavigationDirection.Blank: case ENavigationDirection.NextBlank: return(imageLabels.NextUnlabeled(currentIndex)); case ENavigationDirection.Next: return(imageLabels.ElementAtOrDefault(currentIndex + 1)); case ENavigationDirection.Previous: return(imageLabels.ElementAtOrDefault(currentIndex - 1)); case ENavigationDirection.PreviousBlank: return(imageLabels.PreviousUnlabeled(currentIndex)); case ENavigationDirection.LastBlank: int?lastLabeledIndex = imageLabels.LastLabeledIndex(); return(imageLabels.ElementAtOrDefault(lastLabeledIndex.HasValue ? lastLabeledIndex.Value + 1 : 0)); } throw new NotImplementedException(); }
public string Compute(IList <string> numbers) { if (numbers.Count != 2) { throw new Exception("Invalid number of arguments, 2 expected, found: " + numbers.Count); } StringMatrixTransformer smt = new StringMatrixTransformer(); ArithmeticUtils au = new ArithmeticUtils(); IList <IList <int> > reversed = smt.TransformStringListToReversedIntMatrix(numbers); StringBuilder sb = new StringBuilder(); int carry = 0, y = 0; int n = reversed.ElementAtOrDefault(1).ElementAtOrDefault(0); IList <int> number = reversed.ElementAtOrDefault(0); foreach (int bn in number) { int x = carry; x += bn * n; au.GetCarryBase10(ref x, ref y, ref carry); sb.Append(y); } if (carry != 0) { sb.Append(carry); } return(smt.ReverseString(sb.ToString())); }
List <TableDefinitionDataEntity> ToTableDefinitionDataEntityList(IList <IList <object> > sheetValues) { List <TableDefinitionDataEntity> result = new List <TableDefinitionDataEntity>(); for (int i = 7; i < sheetValues.Count; i++) { IList <object> row = sheetValues[i]; string logicalName = row.ElementAtOrDefault(1)?.ToString(); string physicalName = row.ElementAtOrDefault(2)?.ToString(); string dataType = row.ElementAtOrDefault(3)?.ToString(); string defaultValue = row.ElementAtOrDefault(7)?.ToString(); string relation = row.ElementAtOrDefault(8)?.ToString(); // undefined dataType is threw if (string.IsNullOrEmpty(dataType)) { continue; } TableDefinitionDataEntity entity = new TableDefinitionDataEntity(logicalName, physicalName, dataType, defaultValue, relation); result.Add(entity); } return(result); }
public int Run(IList<string> args) { string command = args.FirstOrDefault() ?? ""; _stdout.WriteLine("executing subtree " + command); if (string.IsNullOrEmpty(Prefix)) { _stdout.WriteLine("Prefix must be specified, use -p or -prefix"); return GitTfsExitCodes.InvalidArguments; } switch (command.ToLower()) { case "add": return DoAdd(args.ElementAtOrDefault(1) ?? "", args.ElementAtOrDefault(2) ?? ""); case "pull": return DoPull(args.ElementAtOrDefault(1)); case "split": return DoSplit(); default: _stdout.WriteLine("Expected one of [add, pull, split]"); return GitTfsExitCodes.InvalidArguments; } }
static void ParseLaboS4(IList <string> recordParts, Labo labo, int lineNumber) { if (recordParts.Count != 2) { labo.ParserErrors.AddItem(lineNumber, $"Expected 2 parts in S4 but got {recordParts.Count} parts: '{string.Join("\\", recordParts)}'"); } if (labo.Patient == null) { labo.Patient = new LaboPatient(); } labo.Patient.BirthDate = recordParts.ElementAtOrDefault(0)?.ToNullableDatetime("dd/MM/yyyy"); switch (recordParts.ElementAtOrDefault(1)) { case "F": case "V": labo.Patient.Sex = Sex.Female; break; case "M": labo.Patient.Sex = Sex.Male; break; default: labo.Patient.Sex = Sex.Unknown; break; } }
/// <summary> /// Navigate through list of imagelabels for segments. /// </summary> /// <param name="imageLabels">List of imagelabels to navigate.</param> /// <param name="navigationDirection">Direction of navigation</param> /// <param name="labelMode">Label mode</param> /// <param name="currentIndex">Current index</param> /// <returns>Imagelabel of navigation</returns> public static ImageLabel Navigate(this IList <ImageLabel> imageLabels, ELabelMode labelMode, ENavigationDirection navigationDirection, int currentIndex) { #region validation if (imageLabels == null) { throw new ArgumentNullException(nameof(imageLabels)); } #endregion switch (navigationDirection) { case ENavigationDirection.Direct: return(imageLabels.ElementAtOrDefault(currentIndex)); case ENavigationDirection.Blank: case ENavigationDirection.NextBlank: return(imageLabels.Next(currentIndex, HasNoElements(labelMode))); case ENavigationDirection.Next: return(imageLabels.ElementAtOrDefault(currentIndex + 1)); case ENavigationDirection.Previous: return(imageLabels.ElementAtOrDefault(currentIndex - 1)); case ENavigationDirection.PreviousBlank: return(imageLabels.Previous(currentIndex, HasNoElements(labelMode))); case ENavigationDirection.LastBlank: int?lastIndex = imageLabels.LastIndex(HasElements(labelMode)); return(imageLabels.ElementAtOrDefault(lastIndex.HasValue ? lastIndex.Value + 1 : 0)); } throw new NotImplementedException(); }
public static void ElementAt(IList <Student> studentList) { Console.WriteLine(studentList.ElementAt(1)); Console.WriteLine(studentList.ElementAt(4)); Console.WriteLine(studentList.ElementAtOrDefault(1)); Console.WriteLine(studentList.ElementAtOrDefault(7)); //Console.WriteLine(studentList.ElementAt(7)) ; }
// Returns true if the tracing records are in the correct order, else returns false. private static bool ConfirmTracingOrder( IList <ExpectedTraceRecord> expectedRecords, IList <TraceRecord> actualRecords ) { int traceBeginPos = 0; foreach (ExpectedTraceRecord expectedRecord in expectedRecords) { TraceRecord beginTrace = actualRecords.SingleOrDefault( r => String.Equals( r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase ) && object.Equals(r.Kind, expectedRecord.TraceKind) ); // Ignore record of a ReflectionTypeLoadException to allow test to succeed in Visual Studio. The record is an // artifact specific to testing in VS. (Attempting to load all types from xunit.runner.visualstudio.testadapter.dll // fails with recent xUnit.net packages. The assembly references Microsoft.VisualStudio.TestPlatform.ObjectModel.dll // which is not available with xUnit.net 2.0.x.) var actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos); if ( actualRecord != null && actualRecord.Operation == null && actualRecord.Exception is ReflectionTypeLoadException && actualRecord.Message != null && actualRecord.Message.StartsWith( "Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, ", StringComparison.Ordinal ) ) { traceBeginPos++; actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos); } if (!object.ReferenceEquals(beginTrace, actualRecord)) { return(false); } traceBeginPos++; } return(true); }
private static void DoSomeProblemWork() { DateTime dtProblemWorkStart = DateTime.Now; int intRadomClassification = Helper.GetRandomNumber(0, listProblemClassificationEnums.Count); ManagementPackEnumeration mpeRandomClassification = listProblemClassificationEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRadomClassification); string strClassificationCriteriaXml = Helper.SearchObjectByEnumerationCriteriaXml(mpeRandomClassification, mpcProblem, mppProblemClassification); IObjectProjectionReader <EnterpriseManagementObject> oprProblemView = Helper.GetBufferedObjectProjectionReader(strClassificationCriteriaXml, intNumberOfWorkItemsToGet, mptpProblemView, emg); if (oprProblemView == null) { Console.WriteLine("No objects to retrieve given the criteria"); } else { //Get a particular problem (full projection) and update it by adding an action log entry and string strProblemId = null; if (oprProblemView.Count > 0) { strProblemId = oprProblemView.ElementAtOrDefault <EnterpriseManagementObjectProjection>(Helper.GetRandomNumber(0, oprProblemView.Count - 1)).Object[mpcProblem, "Id"].Value.ToString(); } if (strProblemId != null) { string strCriteriaXml = Helper.SearchWorkItemByIDCriteriaXml(strProblemId, mpSystemWorkItemLibrary.Name, mpSystemWorkItemLibrary.Version.ToString(), mpSystemWorkItemLibrary.KeyToken, "System.WorkItem"); ObjectProjectionCriteria opcProblemFull = new ObjectProjectionCriteria(strCriteriaXml, mptpProblemFull, emg); IObjectProjectionReader <EnterpriseManagementObject> oprProblemFull = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opcProblemFull, ObjectQueryOptions.Default); EnterpriseManagementObjectProjection emopProblemFull = oprProblemFull.First <EnterpriseManagementObjectProjection>(); emopProblemFull.Object[mpcProblem, "Description"].Value = Guid.NewGuid().ToString(); int intRandomEnumID = Helper.GetRandomNumber(0, listProblemClassificationEnums.Count); ManagementPackEnumeration mpeClassification = listProblemClassificationEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomEnumID); emopProblemFull.Object[mpcProblemExtension, "Classification"].Value = mpeClassification; //EnterpriseManagementObjectCriteria emocComputer = new EnterpriseManagementObjectCriteria(); ObjectQueryOptions oqoComputer = new ObjectQueryOptions(); oqoComputer.MaxResultCount = 5; oqoComputer.DefaultPropertyRetrievalBehavior = ObjectPropertyRetrievalBehavior.All; oqoComputer.ObjectRetrievalMode = ObjectRetrievalOptions.Buffered; IObjectReader <EnterpriseManagementObject> orComputers = emg.EntityObjects.GetObjectReader <EnterpriseManagementObject>(mpcComputer, oqoComputer); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } emopProblemFull.Overwrite(); DateTime dtProblemWorkEnd = DateTime.Now; TimeSpan tsProblemWork = dtProblemWorkEnd - dtProblemWorkStart; pcProblemWork.RawValue = (long)tsProblemWork.TotalSeconds; Console.WriteLine("Problem work completed (seconds): " + tsProblemWork.TotalSeconds); } } }
public InputArgument GetArgument(int pos) { string argumentName = _argumentPositions.ElementAtOrDefault(pos); if (argumentName == null) { throw new InvalidArgumentException(String.Format("The argument at position {0} does not exist", pos)); } return(GetArgument(argumentName)); }
static void ParseLaboD1(IList <string> recordParts, Labo labo, int lineNumber) { if (recordParts.Count != 2) { labo.ParserErrors.AddItem(lineNumber, $"Expected 2 parts in D1 but got {recordParts.Count} parts: '{string.Join("\\", recordParts)}'"); } if (labo.Doctor == null) { labo.Doctor = new Doctor(); } labo.Doctor.LastName = recordParts.ElementAtOrDefault(0); labo.Doctor.FirstName = recordParts.ElementAtOrDefault(1); }
static void ParseLaboS6(IList <string> recordParts, Labo labo, int lineNumber) { if (recordParts.Count != 2) { labo.ParserErrors.AddItem(lineNumber, $"Expected 2 parts in S6 but got {recordParts.Count} parts: '{string.Join("\\", recordParts)}'"); } if (labo.Patient == null) { labo.Patient = new LaboPatient(); } labo.Patient.UniquePatientNumber = recordParts.ElementAtOrDefault(0); labo.Patient.UniqueMedicalRecordNumber = recordParts.ElementAtOrDefault(1); }
static void ParseLaboS3(IList <string> recordParts, Labo labo, int lineNumber) { if (recordParts.Count != 2) { labo.ParserErrors.AddItem(lineNumber, $"Expected 2 parts in S3 but got {recordParts.Count} parts: '{string.Join("\\", recordParts)}'"); } if (labo.Patient == null) { labo.Patient = new LaboPatient(); } labo.Patient.Street = recordParts.ElementAtOrDefault(0); labo.Patient.PostalName = recordParts.ElementAtOrDefault(1); }
private static void DoSomeServiceRequestWork() { DateTime dtServiceRequestWorkStart = DateTime.Now; int intRandomAreaEnum = Helper.GetRandomNumber(0, listSRAreaEnums.Count); ManagementPackEnumeration mpeRadomArea = listSRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomAreaEnum); string strCriteria = Helper.SearchObjectByEnumerationCriteriaXml(mpeRadomArea, mpcServiceRequest, mppServiceRequestArea); IObjectProjectionReader <EnterpriseManagementObject> oprServiceRequestsView = Helper.GetBufferedObjectProjectionReader(strCriteria, intNumberOfWorkItemsToGet, mptpServiceRequestView, emg); if (oprServiceRequestsView == null) { Console.WriteLine("No objects to retrieve given the criteria"); } else { //Get a particular service request (full projection) and update it by adding an action log entry and string strServiceRequestId = null; if (oprServiceRequestsView.Count > 0) { strServiceRequestId = oprServiceRequestsView.ElementAtOrDefault <EnterpriseManagementObjectProjection>(Helper.GetRandomNumber(0, oprServiceRequestsView.Count - 1)).Object[mpcServiceRequest, "Id"].Value.ToString(); } if (strServiceRequestId != null) { string strCriteriaXml = Helper.SearchWorkItemByIDCriteriaXml(strServiceRequestId, mpSystemWorkItemLibrary.Name, mpSystemWorkItemLibrary.Version.ToString(), mpSystemWorkItemLibrary.KeyToken, "System.WorkItem"); ObjectProjectionCriteria opServiceRequestFull = new ObjectProjectionCriteria(strCriteriaXml, mptpServiceRequestFull, emg); IObjectProjectionReader <EnterpriseManagementObject> oprServiceRequestFull = emg.EntityObjects.GetObjectProjectionReader <EnterpriseManagementObject>(opServiceRequestFull, ObjectQueryOptions.Default); EnterpriseManagementObjectProjection emopServiceRequestFull = oprServiceRequestFull.First <EnterpriseManagementObjectProjection>(); if (bSimulateHumanWaitTime) { Thread.Sleep(intDoWorkPause); } emopServiceRequestFull.Object[mpcServiceRequest, "Description"].Value = Guid.NewGuid().ToString(); int intRandomEnumId = Helper.GetRandomNumber(0, listSRAreaEnums.Count); ManagementPackEnumeration mpeArea = listSRAreaEnums.ElementAtOrDefault <ManagementPackEnumeration>(intRandomEnumId); emopServiceRequestFull.Object[mpcServiceRequestExtension, "Area"].Value = mpeArea; emopServiceRequestFull.Overwrite(); DateTime dtServiceRequestWorkEnd = DateTime.Now; TimeSpan tsServiceRequestWork = dtServiceRequestWorkEnd - dtServiceRequestWorkStart; pcServiceRequestWork.RawValue = (long)tsServiceRequestWork.TotalSeconds; Console.WriteLine("Service request work completed (seconds): " + tsServiceRequestWork.TotalSeconds); } } }
private Atom ConvertCharacter(TexFormula formula, string value, ref int position, char character) { position++; if (IsSymbol(character)) { // Character is symbol. var symbolName = symbols.ElementAtOrDefault(character); if (string.IsNullOrEmpty(symbolName)) { throw new TexParseException("Unknown character : '" + character.ToString() + "'"); } try { return(SymbolAtom.GetAtom(symbolName)); } catch (SymbolNotFoundException e) { throw new TexParseException("The character '" + character.ToString() + "' was mapped to an unknown symbol with the name '" + (string)symbolName + "'!", e); } } else { // Character is alpha-numeric. return(new CharAtom(character, formula.TextStyle)); } }
// Returns content of the row forced to be instantiated without trying to reusing existing cells. private IList <LiveCell> BuildForcedRowCellsContentWithNewData <Cell>(string spreadsheetId, string sheetTitleId, int leftColumnIndex, int rowSheetRelativeIndex, int columnCount, IList <Cell> cellsData) where Cell : class { // Get instance of existing cells placeholder list. IList <LiveCell> forcedRowCellsContent = new List <LiveCell>(); // Fill empty cells placeholder with appropriate number of empty cells // for the row of the number of columns specified with the provided column count. for (int cellIndex = 0; cellIndex < columnCount; cellIndex++) { // Determine cell sheet relative index of the cell to be created, // by adding left column index, to the cell order index. int cellSheetRelativeIndex = leftColumnIndex + cellIndex; // Get cell data of the type depending on the generic type the current method. Cell cellData = cellsData?.ElementAtOrDefault(cellIndex); // Build new cell instance. LiveCell cell = LiveCell.Construct(spreadsheetId, sheetTitleId, cellSheetRelativeIndex, rowSheetRelativeIndex, cellData); // Add created cell to row cells content list. forcedRowCellsContent.Add(cell); } // Return return(forcedRowCellsContent); }
public List <ILBasicBlock> GetAllCaseBlocks(IList <ILNode> body, ILBasicBlock head, int pos, out ILExpression condition, out ILLabel fallout) { ILExpression fswitch = new ILExpression(GMCode.Switch, null); List <ILBasicBlock> caseBlocks = new List <ILBasicBlock>(); int swtichStart = pos; ILLabel trueLabel; ILLabel falseLabel; while (MatchSwitchCase(head, out trueLabel, out falseLabel, out condition)) { caseBlocks.Add(head); head = body.ElementAtOrDefault(++swtichStart) as ILBasicBlock; } ILBasicBlock switchHead = caseBlocks.First(); if (!switchHead.ElementAtLastOrDefault(5).isNodeResolved()) { fallout = null; condition = null; return(null); } // caseBlocks.Reverse(); // reverse the order so its correct Debug.Assert(switchHead.MatchLastAt(6, GMCode.Push, out condition)); // return false; switchHead.RemoveAt(switchHead.Body.Count - 6); // ugh, might have to change the matchLastAt fallout = caseBlocks.Last().OperandLabelLastAt(0); return(caseBlocks); }
bool CombineCall(IList <ILNode> nodes, ILExpression expr, int pos) { ILCall call; if (expr.Match(GMCode.CallUnresolved, out call)) { List <ILExpression> args = GetArguments(nodes, pos - 1, expr.Extra); // must use extra as the number of args could be diffrent if (args != null) { expr.Arguments = args; expr.Code = GMCode.Call; pos -= expr.Extra; if (nodes.ElementAtOrDefault(pos + 1).Match(GMCode.Popz)) { nodes[pos] = expr; //calls itself nodes.RemoveAt(pos + 1); // remove it } else { nodes[pos] = new ILExpression(GMCode.Push, null, expr); // wrap it in a push } return(true); } } return(false); }
/// <summary> /// Get data model /// </summary> /// <param name="position"></param> /// <param name="series"></param> /// <param name="items"></param> /// <returns></returns> public virtual dynamic GetModel(int position, string series, IList <IPointModel> items) { var pointModel = items.ElementAtOrDefault(position); if (pointModel == null || pointModel.Areas == null) { return(null); } pointModel.Areas.TryGetValue(Composer.Name, out IAreaModel areaModel); if (areaModel == null || areaModel.Series == null) { return(null); } areaModel.Series.TryGetValue(series, out ISeriesModel seriesModel); if (seriesModel == null || seriesModel.Model == null) { return(null); } return(seriesModel.Model); }
// Ok, so on script returns, in some cases with popz or with statments, the return value is saved in // an instance of -7, and named $$$$temp$$$$, so to fix, it should be resolved so its a assign temp, then return // fix it so its just a return. I guess this could worl on anthing other than temps...humm. public bool FixTempReturnValues(IList <ILNode> body, ILExpression head, int pos) { IList <ILExpression> assign; ILVariable v; ILExpression retExpr; ILVariable ret_v; if (head.Match(GMCode.Assign, out assign) && assign.Count == 2 && (v = assign[0].Operand as ILVariable) != null && v.Instance == -7 && // its a temp body.ElementAtOrDefault(pos + 1).Match(GMCode.Ret, out retExpr) && retExpr.Match(GMCode.Var) && (ret_v = retExpr.Operand as ILVariable) != null && ret_v.Instance == v.Instance && ret_v.Name == v.Name ) { // ok, all we need to do is remove the assign, and give its value to the return body[pos + 1] = new ILExpression(GMCode.Ret, null, assign[1]); body.RemoveAt(pos); return(true); } return(false); // temp.$$$$temp$$$$ = get_joybtnsprite(global.opjoybtn_sel) // Code = Ret Arguments = temp.$$$$temp$$$$ }
private void processStyle(Beatmap beatmap, IList <string> styleLines) { var lyricLines = beatmap.HitObjects.OfType <LyricLine>().ToList(); for (int l = 0; l < lyricLines.Count; l++) { var lyricLine = lyricLines[l]; var line = styleLines.ElementAtOrDefault(l)?.Split('=').Last(); // TODO : maybe create default layer and style index here? if (string.IsNullOrEmpty(line)) { return; } var layoutIndexStr = line.Split(',').FirstOrDefault(); var fontIndexStr = line.Split(',').ElementAtOrDefault(1); if (int.TryParse(layoutIndexStr, out int layoutIndex)) { lyricLine.LayoutIndex = layoutIndex; } if (int.TryParse(fontIndexStr, out int fontIndex)) { lyricLine.FontIndex = fontIndex; } } }
public void testingLogin() { var rand = new Random(); driver.Navigate().GoToUrl("https://www.yandex.ru/"); try { wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.LinkText("Завести почту")), "Завести почту")); driver.FindElement(By.LinkText("Завести почту")).Click(); driver.FindElement(By.Name("firstname")).SendKeys("Test12345"); driver.FindElement(By.Name("lastname")).SendKeys("Test12345"); driver.FindElement(By.Name("login")).SendKeys("Test"); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.ClassName("form__login-suggest")), "К сожалению, логин занят")); driver.FindElement(By.ClassName("login__suggest-button")).Click(); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.ClassName("suggest__logins")), "Свободные логины")); IList <IWebElement> select = driver.FindElements(By.ClassName("registration__pseudo-link")); select.ElementAtOrDefault(rand.Next(0, select.Count)).Click(); wait.Until(ExpectedConditions.TextToBePresentInElement(driver.FindElement(By.ClassName("reg-field__popup")), "Логин свободен")); // System.Threading.Thread.Sleep(10000); } catch (NoSuchElementException ex) { Assert.Fail("[Selenium] Объект не найден!" + ex.ToString()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("[Selenium] WTF exception: " + ex.ToString()); } }
/// <summary> /// Render charts /// </summary> public void CreateCharts() { View.Composer = new ComponentComposer { Name = _name, Control = View, Group = new AreaModel(), ShowIndexAction = i => { dynamic point = _points.ElementAtOrDefault((int)i); if (point == null) { return(null); } return($"{ point.Strike }"); } }; View.Composer.Create(); View.Composer.Update(); var clock = new Timer(); clock.Interval = 1000; clock.Enabled = true; clock.Elapsed += async(object sender, ElapsedEventArgs e) => { clock.Stop(); await OnData(); }; }
private void ValidateArgumentsPromote(IList <string> commandActionSplit) { if (commandActionSplit.ElementAtOrDefault(Constants.INDEX_ARGUMENTS_PROMOTE) == null) { throw new Exception(Messages.NumberEmployeePromoteNotInformed); } }
/// <summary> /// Create shape /// </summary> /// <param name="points"></param> /// <param name="shapeModel"></param> public override void CreateShape(IList <Point> points, IShapeModel shapeModel) { CreateCanvas(); var shape = new SKPath(); var origin = points.ElementAtOrDefault(0); if (origin == default) { return; } shape.MoveTo((float)origin.X, (float)origin.Y); for (var i = 1; i < points.Count; i++) { shape.LineTo((float)points[i].X, (float)points[i].Y); } shape.Close(); var pen = new SKPaint { Style = SKPaintStyle.Fill, Color = shapeModel.Color.ToSKColor() }; _canvas.DrawPath(shape, pen); pen.Dispose(); shape.Dispose(); }
//https://docs.microsoft.com/en-us/dotnet/api/system.type.isassignablefrom?view=netcore-2.2 private bool DoArgsMatchMethod(MethodInfo methodInfo, IList <Type> arguments) { var parameters = methodInfo.GetParameters(); // can't have more arguments than a method parameters if (arguments.Count() > parameters.Count()) { return(false); } foreach (var(index, parameter) in parameters.GetIndexedEnumerable()) { var argument = arguments.ElementAtOrDefault(index); if (argument == null && parameter.IsOptional) { continue; } if (!parameter.ParameterType.IsAssignableFrom(argument)) { return(false); } } return(true); }
public IList <double> Calculate(IList <double> values) { var i = 0; foreach (var val in values) { var avg = avgAcum.ElementAtOrDefault(i); if (avg < val) { avg = val; } else if (avg > 0) { avg -= avg / 20; } if (avgAcum.Count > i) { avgAcum[i] = avg; } else { avgAcum.Add(avg); } i++; } if (avgAcum.Count > values.Count) { avgAcum = avgAcum.Take(values.Count).ToList(); } return(avgAcum); }
private Atom ConvertCharacter(TexFormula formula, ref int position, SourceSpan source) { var character = source[0]; position++; if (IsSymbol(character) && formula.TextStyle != TexUtilities.TextStyleName) { // Character is symbol. var symbolName = symbols.ElementAtOrDefault(character); if (string.IsNullOrEmpty(symbolName)) { throw new TexParseException($"Unknown character : '{character}'"); } try { return(SymbolAtom.GetAtom(symbolName, source)); } catch (SymbolNotFoundException e) { throw new TexParseException("The character '" + character.ToString() + "' was mapped to an unknown symbol with the name '" + symbolName + "'!", e); } } else // Character is alpha-numeric or should be rendered as text. { return(new CharAtom(source, character, formula.TextStyle)); } }
private static void Copy( IList source, IList target, MemberSettings settings, ReferencePairCollection referencePairs) { if ((source.IsFixedSize || target.IsFixedSize) && source.Count != target.Count) { throw State.Copy.Throw.CannotCopyFixesSizeCollections(source, target, settings); } var copyValues = State.Copy.IsCopyValue( source.GetType().GetItemType(), settings); for (var i = 0; i < source.Count; i++) { if (copyValues) { target.SetElementAt(i, source[i]); continue; } var sv = source[i]; var tv = target.ElementAtOrDefault(i); bool created; bool needsSync; var clone = State.Copy.CloneWithoutSync(sv, tv, settings, out created, out needsSync); if (created) { target.SetElementAt(i, clone); } if (needsSync) { State.Copy.Sync(sv, clone, settings, referencePairs); } } target.TrimLengthTo(source); }
public void ApplyValues(string groupName, IList<string> values) { switch (groupName) { case "ribbon_group_1_name": RibbonGroupDigitalLogoTitle = values.ElementAtOrDefault(0); break; case "top_level_subtab_names": SectionsHomeTitle = values.ElementAtOrDefault(0); SectionsListTitle = values.ElementAtOrDefault(1); SectionsProductTitle = values.ElementAtOrDefault(2); SectionsSummaryTitle = values.ElementAtOrDefault(3); SectionsProductPackageTitle = values.ElementAtOrDefault(4); SectionsStandalonePackageTitle = values.ElementAtOrDefault(5); break; case "tab_2_column_header_names": ListColumnsGroupTitle = values.ElementAtOrDefault(0); ListColumnsProductTitle = values.ElementAtOrDefault(1); ListColumnsPricingTitle = values.ElementAtOrDefault(2); ListColumnsOptionsTitle = values.ElementAtOrDefault(3); break; case "tab_2_left_panel_button_names": ListSettingsDimensionTitle = values.ElementAtOrDefault(0); ListSettingsLocationTitle = values.ElementAtOrDefault(1); ListSettingsStrategyTitle = values.ElementAtOrDefault(2); ListSettingsTargetingTitle = values.ElementAtOrDefault(3); ListSettingsRichMediaTitle = values.ElementAtOrDefault(4); break; case "tab_2_new_line_placeholder_names": ListEditorsGroupTitle = values.ElementAtOrDefault(0); ListEditorsProductTitle = values.ElementAtOrDefault(1); ListEditorsLocationTitle = values.ElementAtOrDefault(2); break; case "tab_2_new_line_options_label_names": ListEditorsTargetingTitle = values.ElementAtOrDefault(0); ListEditorsRichMediaTitle = values.ElementAtOrDefault(1); break; case "tab_2_add_product_hover_tip": RibbonButtonDigitalAddTitle = values.ElementAtOrDefault(0); RibbonButtonDigitalAddTooltip = values.ElementAtOrDefault(1); break; case "tab_2_delete_product_hover_tip": RibbonButtonDigitalDeleteTitle = values.ElementAtOrDefault(0); RibbonButtonDigitalDeleteTooltip = values.ElementAtOrDefault(1); break; case "tab_2_clone_product_hover_tip": RibbonButtonDigitalCloneTitle = values.ElementAtOrDefault(0); RibbonButtonDigitalCloneTooltip = values.ElementAtOrDefault(1); break; case "tab_2_warning_popup": ListPopupGroupText = values.ElementAtOrDefault(0); break; case "tab_3_section_titles": ProductEditorsSitesTitle = values.ElementAtOrDefault(0); ProductEditorsNameTitle = values.ElementAtOrDefault(1); ProductEditorsDescriptionTitle = values.ElementAtOrDefault(2); ProductEditorsPricingTitle = values.ElementAtOrDefault(3); ProductEditorsCommentsTitle = values.ElementAtOrDefault(4); break; case "tab_3_section_icons": var imageRootFolder = Path.Combine( Path.GetDirectoryName(typeof(DigitalControlsConfiguration).Assembly.Location), "Data", "!Main_Dashboard", "Online Source", "Icon Images"); if (!Directory.Exists(imageRootFolder)) break; ProductEditorsSitesLogo = !String.IsNullOrEmpty(values.ElementAtOrDefault(0)) ? Image.FromFile(Path.Combine(imageRootFolder, values[0])) : null; ProductEditorsNameLogo = !String.IsNullOrEmpty(values.ElementAtOrDefault(1)) ? Image.FromFile(Path.Combine(imageRootFolder, values[1])) : null; ProductEditorsDescriptionLogo = !String.IsNullOrEmpty(values.ElementAtOrDefault(2)) ? Image.FromFile(Path.Combine(imageRootFolder, values[2])) : null; ProductEditorsPricingLogo = !String.IsNullOrEmpty(values.ElementAtOrDefault(3)) ? Image.FromFile(Path.Combine(imageRootFolder, values[3])) : null; ProductEditorsCommentsLogo = !String.IsNullOrEmpty(values.ElementAtOrDefault(4)) ? Image.FromFile(Path.Combine(imageRootFolder, values[4])) : null; break; case "tab_5_column_header_names": ProductPackageColumnsCategoryTitle = values.ElementAtOrDefault(0); ProductPackageColumnsSubCategoryTitle = values.ElementAtOrDefault(1); ProductPackageColumnsProductTitle = values.ElementAtOrDefault(2); ProductPackageColumnsInfoTitle = values.ElementAtOrDefault(3); ProductPackageColumnsLocationTitle = values.ElementAtOrDefault(4); ProductPackageColumnsInvestmentTitle = values.ElementAtOrDefault(5); ProductPackageColumnsImpressionsTitle = values.ElementAtOrDefault(6); ProductPackageColumnsCPMTitle = values.ElementAtOrDefault(7); ProductPackageColumnsRateTitle = values.ElementAtOrDefault(8); break; case "tab_5_left_panel_button_names": ProductPackageSettingsCategoryTitle = values.ElementAtOrDefault(0); ProductPackageSettingsSubCategoryTitle = values.ElementAtOrDefault(1); ProductPackageSettingsProductTitle = values.ElementAtOrDefault(2); ProductPackageSettingsInfoTitle = values.ElementAtOrDefault(3); ProductPackageSettingsLocationTitle = values.ElementAtOrDefault(4); ProductPackageSettingsInvestmentTitle = values.ElementAtOrDefault(5); ProductPackageSettingsImpressionsTitle = values.ElementAtOrDefault(6); ProductPackageSettingsCPMTitle = values.ElementAtOrDefault(7); ProductPackageSettingsRateTitle = values.ElementAtOrDefault(8); ProductPackageSettingsScreenshotTitle = values.ElementAtOrDefault(9); ProductPackageSettingsFormulaTitle = values.ElementAtOrDefault(10); break; case "tab_6_column_header_names": StandalonePackageColumnsCategoryTitle = values.ElementAtOrDefault(0); StandalonePackageColumnsSubCategoryTitle = values.ElementAtOrDefault(1); StandalonePackageColumnsProductTitle = values.ElementAtOrDefault(2); StandalonePackageColumnsInfoTitle = values.ElementAtOrDefault(3); StandalonePackageColumnsLocationTitle = values.ElementAtOrDefault(4); StandalonePackageColumnsInvestmentTitle = values.ElementAtOrDefault(5); StandalonePackageColumnsImpressionsTitle = values.ElementAtOrDefault(6); StandalonePackageColumnsCPMTitle = values.ElementAtOrDefault(7); StandalonePackageColumnsRateTitle = values.ElementAtOrDefault(8); break; case "tab_6_left_panel_button_names": StandalonePackageSettingsCategoryTitle = values.ElementAtOrDefault(0); StandalonePackageSettingsSubCategoryTitle = values.ElementAtOrDefault(1); StandalonePackageSettingsProductTitle = values.ElementAtOrDefault(2); StandalonePackageSettingsInfoTitle = values.ElementAtOrDefault(3); StandalonePackageSettingsLocationTitle = values.ElementAtOrDefault(4); StandalonePackageSettingsInvestmentTitle = values.ElementAtOrDefault(5); StandalonePackageSettingsImpressionsTitle = values.ElementAtOrDefault(6); StandalonePackageSettingsCPMTitle = values.ElementAtOrDefault(7); StandalonePackageSettingsRateTitle = values.ElementAtOrDefault(8); StandalonePackageSettingsScreenshotTitle = values.ElementAtOrDefault(9); StandalonePackageSettingsFormulaTitle = values.ElementAtOrDefault(10); break; case "column_header_names": DigitalInfoColumnsCategoryTitle = values.ElementAtOrDefault(0); DigitalInfoColumnsSubCategoryTitle = values.ElementAtOrDefault(1); DigitalInfoColumnsProductTitle = values.ElementAtOrDefault(2); DigitalInfoColumnsInfoTitle = values.ElementAtOrDefault(3); break; case "left_panel_button_names": DigitalInfoSettingsCategoryTitle = values.ElementAtOrDefault(0); DigitalInfoSettingsSubCategoryTitle = values.ElementAtOrDefault(1); DigitalInfoSettingsProductTitle = values.ElementAtOrDefault(2); DigitalInfoSettingsInfoTitle = values.ElementAtOrDefault(3); DigitalInfoSettingsLogosTitle = values.ElementAtOrDefault(4); DigitalInfoSettingsMontlyInvestmentTitle = values.ElementAtOrDefault(5); DigitalInfoSettingsTotalInvestmentTitle = values.ElementAtOrDefault(6); break; case "add_product_hover_tip": RibbonButtonMediaDigitalAddTitle = values.ElementAtOrDefault(0); RibbonButtonMediaDigitalAddTooltip = values.ElementAtOrDefault(1); break; case "delete_product_hover_tip": RibbonButtonMediaDigitalDeleteTitle = values.ElementAtOrDefault(0); RibbonButtonMediaDigitalDeleteTooltip = values.ElementAtOrDefault(1); break; } }
private async static void Server(IList<string> list, AHistory c) { string pwd = null; int port = 0; if (list.ElementAtOrDefault(1) == null) throw new ErrorBIRC(MainPage.GetErrorString("InvalidServerCmd")); if (list.ElementAtOrDefault(2) != null) { if (int.TryParse(list[2], out port) == false) port = IrcClient.DefaultPort; } else port = IrcClient.DefaultPort; if (list.ElementAtOrDefault(3) != null) pwd = await Encryption.Protect(list[3]); Connection newc = new Connection() { AutoConnect = true, Name = list[1], Port = port, Password = pwd }; AHistory cur = ConnectionUtils.Add(newc); ((BIRCViewModel)MainPage.currentDataContext).ServerSelection = cur; if (!cur.Command.IsConnected()) cur.Command.Connect(); }
private MethodInfo FindMethodInfo(IList<Token> arg) { var foundClassName = Type.ControllerName().EqualsIC(arg.ElementAtOrDefault(0).Value); if (foundClassName) { var methodName = arg.ElementAtOrDefault(1).Value; var methodInfo = FindMethodAmongLexedTokens.FindMethod(Type.GetControllerActionMethods(), methodName, arg); return methodInfo; } return null; }
public byte[] AppendDocumentsToPrimaryDocument(byte[] primaryDocument, IList<byte[]> documentstoAppend) { if (documentstoAppend == null) { throw new ArgumentNullException("documentstoAppend"); } if (primaryDocument == null) { throw new ArgumentNullException("primaryDocument"); } byte[] output = null; using (var finalDocumentStream = new MemoryStream()) { finalDocumentStream.Write(primaryDocument, 0, primaryDocument.Length); using (var finalDocument = WordprocessingDocument.Open(finalDocumentStream, true)) { SectionProperties finalDocSectionProperties = null; UnprotectDocument(finalDocument); var tempSectionProperties = finalDocument.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault(); if (tempSectionProperties != null) { finalDocSectionProperties = tempSectionProperties.CloneNode(true) as SectionProperties; } this.RemoveContentControlsAndKeepContents(finalDocument.MainDocumentPart.Document); foreach (byte[] documentToAppend in documentstoAppend) { var subReportPart = finalDocument.MainDocumentPart.AddAlternativeFormatImportPart( AlternativeFormatImportPartType.WordprocessingML); SectionProperties secProperties = null; using (var docToAppendStream = new MemoryStream()) { docToAppendStream.Write(documentToAppend, 0, documentToAppend.Length); using (var docToAppend = WordprocessingDocument.Open(docToAppendStream, true)) { UnprotectDocument(docToAppend); tempSectionProperties = docToAppend.MainDocumentPart.Document.Descendants<SectionProperties>().LastOrDefault(); if (tempSectionProperties != null) { secProperties = tempSectionProperties.CloneNode(true) as SectionProperties; } this.RemoveContentControlsAndKeepContents(docToAppend.MainDocumentPart.Document); docToAppend.MainDocumentPart.Document.Save(); } docToAppendStream.Position = 0; subReportPart.FeedData(docToAppendStream); } if (documentstoAppend.ElementAtOrDefault(0).Equals(documentToAppend)) { AssignSectionProperties(finalDocument.MainDocumentPart.Document, finalDocSectionProperties); } var altChunk = new AltChunk(); altChunk.Id = finalDocument.MainDocumentPart.GetIdOfPart(subReportPart); finalDocument.MainDocumentPart.Document.AppendChild(altChunk); if (!documentstoAppend.ElementAtOrDefault(documentstoAppend.Count - 1).Equals(documentToAppend)) { AssignSectionProperties(finalDocument.MainDocumentPart.Document, secProperties); } finalDocument.MainDocumentPart.Document.Save(); } finalDocument.MainDocumentPart.Document.Save(); } finalDocumentStream.Position = 0; output = new byte[finalDocumentStream.Length]; finalDocumentStream.Read(output, 0, output.Length); } return output; }
public int? GetScore(IList<BowlingFrame> frames) { var nextFrame = frames.ElementAtOrDefault(frames.IndexOf(this) + 1); // Strike if (IsStrike) { if (nextFrame != null) { // Is next ball a strike? If so, we'll need the next frame if (nextFrame.IsStrike) { var thirdFrame = frames.ElementAtOrDefault(frames.IndexOf(nextFrame) + 1); // Get first throw of third frame, if it's a strike it's just +10 if (thirdFrame != null && thirdFrame.Ball1 != null) { return 20 + thirdFrame.Ball1.Value; } else if (thirdFrame == null && nextFrame.IsLast) { // 10th frame if (nextFrame.Ball1 != null && nextFrame.Ball2 != null) { return 10 + nextFrame.Ball1.Value + nextFrame.Ball2.Value; } } } else { if (nextFrame.Ball1 == null || nextFrame.Ball2 == null) { return null; } else { return 10 + nextFrame.Ball1.Value + nextFrame.Ball2.Value; } } } else { // Last frame and a first or second ball is strike if (Ball2 == Constants.TotalPins && Ball3 != null) { return Ball1 + Ball2 + Ball3; } else if (Ball1 == Constants.TotalPins && Ball2 != null && Ball3 != null) { return Ball1 + Ball2 + Ball3; } else if (IsSpare) { return Ball1 + Ball2 + Ball3; } } // cannot calculate just yet return null; } // Spare if (IsSpare) { // Get next ball if (nextFrame != null && nextFrame.Ball1 != null) { return 10 + nextFrame.Ball1.Value; } else if (nextFrame == null && Ball3 != null) { // last frame return 10 + Ball3.Value; } // cannot calculate just yet return null; } // Open frame if (Ball2 != null && Ball1 != null) { return Ball1.Value + Ball2.Value; } else { return null; } }
private void ValidateEntity(object o, object id, PersistenceOperationEnum persistenceOperation, IList<string> properties, IList<IType> types, IList<object> currentState, IList<object> previousState) { if (ReferenceEquals(_session, null)) return; if (!ReferenceEquals(_session.Transaction, null) && _session.Transaction.WasRolledBack) return; var factoryName = _session.GetSessionImplementation().Factory.Settings.SessionFactoryName; var epc = new EntityPersistenceContext {FactoryName = factoryName, Id = id}; if (properties != null) { for (var i = 0; i < properties.Count; i++) { if (currentState != null) epc.CurrentState.Add(properties[i], currentState.ElementAtOrDefault(i)); if (types != null) epc.Types.Add(properties[i], types.ElementAtOrDefault(i)); } } switch (persistenceOperation) { case PersistenceOperationEnum.Adding: epc.IsBeingAdded = true; break; case PersistenceOperationEnum.Updating: epc.IsBeingModified = true; if (properties == null || previousState == null) break; for (var i = 0; i < properties.Count; i++ ) { epc.PreviousState.Add(properties[i], previousState.ElementAtOrDefault(i)); } break; case PersistenceOperationEnum.Removing: epc.IsBeingRemoved = true; break; default: throw new ArgumentOutOfRangeException(persistenceOperation.ToString()); } var validationResults = EntityValidator.DoMemberValidation(o, epc).ToList(); if (validationResults.Count() == 0) { if (_validationResults.ContainsKey(o)) { //remove the validation errors from a previous flush _validationResults.Remove(o); } return; } if (!_validationResults.ContainsKey(o)) { //add the validation results for the entity _validationResults.Add(o, validationResults); } else { //replace the validation results for the entity _validationResults[o] = validationResults; } }