private void SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold(int threshold, UniquenessType uniqueBy) { dataGridView1.EndEdit(); var dubious = new HashSet <string>(StringComparer.OrdinalIgnoreCase); for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++) { var row = dataGridView1.Rows[rowIndex]; var rowTag = (Tuple <IdentityPath, PeptideDocNode>)row.Tag; int matchCount = _peptidesInBackgroundProteome.Contains(rowTag.Item1) ? 1 : 0; for (int col = 0; col < dataGridView1.ColumnCount; col++) { if (col == PeptideIncludedColumn.Index || col == PeptideColumn.Index) { continue; } if (row.Cells[col].Value is bool && ((bool)row.Cells[col].Value)) { if (uniqueBy == UniquenessType.protein) { matchCount++; } else { var peptide = rowTag.Item2; var parent = PeptideGroupDocNodes.First(p => p.Children.Contains(peptide)); string testValA; string testValB; // ATP5B and atp5b are the same thing, as are "mus musculus" and "MUS MUSCULUS" if (uniqueBy == UniquenessType.gene) { // ReSharper disable once PossibleNullReferenceException testValA = parent.ProteinMetadata.Gene; testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Gene; } else { // ReSharper disable once PossibleNullReferenceException testValA = parent.ProteinMetadata.Species; testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Species; } // Can't filter on something that isn't there - require nonempty values if (!string.IsNullOrEmpty(testValA) && !string.IsNullOrEmpty(testValB) && string.Compare(testValA, testValB, StringComparison.OrdinalIgnoreCase) != 0) { matchCount++; } if (string.IsNullOrEmpty(testValA)) { dubious.Add(parent.Name); } if (string.IsNullOrEmpty(testValB)) { dubious.Add(((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Name); } } } if (matchCount > threshold) { break; } } row.Cells[PeptideIncludedColumn.Name].Value = (matchCount <= threshold); } SetCheckBoxPeptideIncludedHeaderState(); if (dubious.Any()) { var dubiousValues = TextUtil.LineSeparate(uniqueBy == UniquenessType.gene ? Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_gene_information__this_selection_may_be_suspect_ : Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_species_information__this_selection_may_be_suspect_, Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_These_proteins_include_, TextUtil.LineSeparate(dubious)); MessageDlg.Show(this, dubiousValues); } }
private void Button2_Click(object sender, EventArgs e) { txtTag.Text = TextUtil.escapeText(txtSrc.Text); }
private void RefreshStatus() { if (File.Exists(textPath.Text)) { btnAddFastaFile.Enabled = true; ProteomeDb proteomeDb = null; int proteinCount = 0; IList <Digestion> digestions = null; try { using (var longWaitDlg = new LongWaitDlg { Text = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_Proteome_File, Message = string.Format( Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_protein_information_from__0__, textPath.Text) }) { longWaitDlg.PerformWork(this, 1000, () => { proteomeDb = ProteomeDb.OpenProteomeDb(textPath.Text); if (proteomeDb != null) { proteinCount = proteomeDb.GetProteinCount(); // This can be a lengthy operation on a large protdb, do it within the longwait digestions = proteomeDb.ListDigestions(); } }); } if (proteomeDb == null) { throw new Exception(); } tbxStatus.Text = string.Format( Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_file_contains__0__proteins, proteinCount); if (proteinCount != 0 && digestions.Count > 0) { tbxStatus.Text = TextUtil.LineSeparate(tbxStatus.Text, Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_has_already_been_digested); } } catch (Exception) { tbxStatus.Text = Resources.BuildBackgroundProteomeDlg_OkDialog_The_proteome_file_is_not_valid; btnAddFastaFile.Enabled = false; } finally { if (null != proteomeDb) { proteomeDb.Dispose(); } } } else { btnAddFastaFile.Enabled = false; tbxStatus.Text = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Open_button_to_choose_an_existing_proteome_file_or_click_the_Create_button_to_create_a_new_proteome_file; } }
public void CommonPrefixFirstStringIsSubstringOfSecondCommonPrefixIsDetected() { // Whole case. Assert.Equal(4, TextUtil.CommonPrefix("1234", "1234xyz")); }
public void CommonSuffixBothStringsEndWithSameCommonSuffixIsDetected() { // Non-null case. Assert.Equal(4, TextUtil.CommonSuffix("abcdef1234", "xyz1234")); }
public void CommonOverlapPatternInTheMiddle_NoOverlap() { Assert.Equal(0, TextUtil.CommonOverlap("123456xxx", "efgxxxabcd")); }
public void CommonOverlapEmptyStringNoOverlap() { // Detect any suffix/prefix overlap. // Null case. Assert.Equal(0, TextUtil.CommonOverlap("", "abcd")); }
public static bool DownloadAndConvert(BackgroundWorker backgroundWorker, string conversionStringTemplate, string videoFile, string targetFile, string targetTmpFile, out long resultSize) { bool flag = false; long num = 0L; string arguments = string.Format(conversionStringTemplate, videoFile, targetTmpFile); var info = new ProcessStartInfo("ffmpeg.exe", arguments) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(Application.StartupPath), RedirectStandardError = true, RedirectStandardOutput = true }; var process = new Process { StartInfo = info }; string message = null; int exitCode = -1; int userState = 0; backgroundWorker.ReportProgress(0, "Downloading && Converting"); FileGarbageCollector.Instance.Add(targetTmpFile); try { string str3; process.Start(); long ticks = DateTime.Now.Ticks; StreamReader standardError = process.StandardError; long result = 0L; int percentProgress = 0; do { long num6 = 0L; Application.DoEvents(); str3 = standardError.ReadLine(); Application.DoEvents(); if (str3.Contains("Duration: ")) { TimeSpan span; if (TimeSpan.TryParse(TextUtil.JustAfter(str3, "Duration: ", ","), out span)) { userState = (int)span.TotalSeconds; backgroundWorker.ReportProgress(0, userState); } } else if (str3.Contains("size=") && str3.Contains("time=")) { int num8; if (int.TryParse(TextUtil.JustAfter(str3, "time=", "."), out num8)) { percentProgress = num8; //percentProgress = (num8 <= progressIndicator.Maximum) ? num8 : progressIndicator.Maximum; } if (long.TryParse(TextUtil.JustAfter(str3, "size=", "kB"), out result)) { num6 = result - num; num = result; } } long num9 = DateTime.Now.Ticks - ticks; if (num9 > 0L) { try { backgroundWorker.ReportProgress(percentProgress, (num6 * 0x989680L) / num9); } catch { } } ticks = DateTime.Now.Ticks; if (backgroundWorker.CancellationPending) { process.Kill(); process.Close(); process.Dispose(); flag = true; } } while (!standardError.EndOfStream); process.WaitForExit(); if (!backgroundWorker.CancellationPending) { exitCode = process.ExitCode; message = str3; return(flag); } return(true); } catch (Exception exception) { try { process.Kill(); } catch { } try { process.Close(); } catch { } try { process.Dispose(); } catch { } message = exception.Message; } finally { if (!backgroundWorker.CancellationPending) { if ((exitCode != 0) && !string.IsNullOrEmpty(message)) { if (message.Contains("Decoder (codec id 0) not found for input stream")) { throw new VideoConversionException(message); } throw new Exception(message); } if (File.Exists(targetFile)) { try { File.Delete(targetFile); } catch { } } File.Move(targetTmpFile, targetFile); FileGarbageCollector.Instance.Remove(targetTmpFile); backgroundWorker.ReportProgress(userState, Messages.CompletedMessage); } resultSize = num; } return(flag); }
private void SetupBoosting(QuerySetup setup, QueryRequest request) { if (!setup.UseBoosting) { return; } List <Boost> boosting = GetBoosting(setup.Type, setup.BoostFields); if (boosting.Count > 0) { var searchText = request.Query.SearchText.Replace("*", String.Empty); if (!TextUtil.IsNumeric(searchText)) { boosting.RemoveAll(b => b.FieldName.Equals(DefaultFields.Id)); } request.Query.Bool.Should.AddRange( boosting.Select(b => new MatchWithBoost(b.FieldName, searchText, b.Weight, setup.Operator))); } // Boosting by type if (setup.BoostTypes.Count > 0) { request.Query.Bool.Should.AddRange( setup.BoostTypes.Select(b => new MatchWithBoost(DefaultFields.Types, b.Key.GetTypeName(), b.Value, setup.Operator))); // Direct match in Type gives higher score than match in Types, hence the +1 request.Query.Bool.Should.AddRange( setup.BoostTypes.Select(b => new MatchWithBoost(DefaultFields.Type, b.Key.GetTypeName(), b.Value + 1, setup.Operator))); } if (setup.BoostAncestors.Count > 0) { request.Query.Bool.Should.AddRange( setup.BoostAncestors.Select(b => new MatchWithBoost(DefaultFields.Path, b.Key.ToString(), b.Value, setup.Operator))); request.Query.Bool.Should.AddRange( setup.BoostAncestors.Select(b => new MatchWithBoost(DefaultFields.Id, b.Key.ToString(), b.Value, setup.Operator))); } // Best Bets if (setup.UseBestBets && !String.IsNullOrWhiteSpace(request.Query.SearchText)) { IEnumerable <string> terms = request.Query.SearchText .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(t => t.Trim().Trim('*')); var key = setup.IndexName ?? _settings.GetDefaultIndexName(Language.GetLanguageCode(setup.Language)); if (!Conventions.Indexing.BestBets.TryGetValue(key, out List <BestBet> bestBetsForLanguage)) { return; } IEnumerable <BestBet> bestBets = bestBetsForLanguage .Where(b => b.GetTerms().Any(t => terms.Contains(t))); request.Query.Bool.Should.AddRange( bestBets.Select(_ => new MatchWithBoost( DefaultFields.BestBets, request.Query.SearchText.Trim('*'), BestBetMultiplier, setup.Operator))); } }
public R <PlayResource, LocalStr> GetResourceById(AudioResource resource) { var channel = resource.ResourceId; // request api token if (!WebWrapper.DownloadString(out string jsonResponse, new Uri($"https://api.twitch.tv/api/channels/{channel}/access_token"), ("Client-ID", TwitchClientId))) { return(new LocalStr(strings.error_net_no_connection)); } var jObj = JObject.Parse(jsonResponse); // request m3u8 file var tokenResult = jObj.TryCast <string>("token"); var sigResult = jObj.TryCast <string>("sig"); if (!tokenResult.Ok || !sigResult.Ok) { return(new LocalStr(strings.error_media_internal_invalid + " (tokenResult|sigResult)")); } var token = Uri.EscapeUriString(tokenResult.Value); var sig = sigResult.Value; // guaranteed to be random, chosen by fair dice roll. const int random = 4; if (!WebWrapper.DownloadString(out string m3u8, new Uri($"http://usher.twitch.tv/api/channel/hls/{channel}.m3u8?player=twitchweb&&token={token}&sig={sig}&allow_audio_only=true&allow_source=true&type=any&p={random}"))) { return(new LocalStr(strings.error_net_no_connection)); } // parse m3u8 file var dataList = new List <StreamData>(); using (var reader = new System.IO.StringReader(m3u8)) { var header = reader.ReadLine(); if (string.IsNullOrEmpty(header) || header != "#EXTM3U") { return(new LocalStr(strings.error_media_internal_missing + " (m3uHeader)")); } while (true) { var blockInfo = reader.ReadLine(); if (string.IsNullOrEmpty(blockInfo)) { break; } var match = M3U8ExtMatch.Match(blockInfo); if (!match.Success) { continue; } switch (match.Groups[1].Value) { case "EXT-X-TWITCH-INFO": break; // Ignore twitch info line case "EXT-X-MEDIA": string streamInfo = reader.ReadLine(); Match infoMatch; if (string.IsNullOrEmpty(streamInfo) || !(infoMatch = M3U8ExtMatch.Match(streamInfo)).Success || infoMatch.Groups[1].Value != "EXT-X-STREAM-INF") { return(new LocalStr(strings.error_media_internal_missing + " (m3uStream)")); } var streamData = new StreamData(); // #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=128000,CODECS="mp4a.40.2",VIDEO="audio_only" for (int i = 0; i < infoMatch.Groups[3].Captures.Count; i++) { string key = infoMatch.Groups[4].Captures[i].Value.ToUpperInvariant(); string value = infoMatch.Groups[5].Captures[i].Value; switch (key) { case "BANDWIDTH": streamData.Bandwidth = int.Parse(value, CultureInfo.InvariantCulture); break; case "CODECS": streamData.Codec = TextUtil.StripQuotes(value); break; case "VIDEO": streamData.QualityType = Enum.TryParse(TextUtil.StripQuotes(value), out StreamQuality quality) ? quality : StreamQuality.unknown; break; } } streamData.Url = reader.ReadLine(); dataList.Add(streamData); break; } } } // Validation Process if (dataList.Count <= 0) { return(new LocalStr(strings.error_media_no_stream_extracted)); } int codec = SelectStream(dataList); if (codec < 0) { return(new LocalStr(strings.error_media_no_stream_extracted)); } return(new PlayResource(dataList[codec].Url, resource.ResourceTitle != null ? resource : resource.WithName($"Twitch channel: {channel}"))); }
public static bool InternalDownload(BackgroundWorker backgroundWorker, string conversionStringTemplate, string videoFile, string targetFile, string targetTmpFile, out long resultSize) { bool flag = false; long num = 0L; Stream stream = null; string item = ApplicationSettings.Instance.UseIndirectConversion ? targetTmpFile : targetFile; try { RemoteFileInfo remoteResource = HttpUtility.GetRemoteResource(new ResourceLocation(videoFile), out stream); backgroundWorker.ReportProgress(0, 0x7fffffff); FileGarbageCollector.Instance.Add(item); long ticks = DateTime.Now.Ticks; backgroundWorker.ReportProgress(0, "Downloading"); using (Stream stream2 = new FileStream(item, FileMode.Create)) { int count = 0; do { Application.DoEvents(); if (backgroundWorker.CancellationPending) { resultSize = num; return(true); } var buffer = new byte[0x4000]; count = stream.Read(buffer, 0, 0x4000); if (count > 0) { stream2.Write(buffer, 0, count); num += count; long num4 = (num * 0x7fffffffL) / remoteResource.FileSize; long num5 = DateTime.Now.Ticks - ticks; if (num5 > 0L) { backgroundWorker.ReportProgress((num4 <= 0x7fffffffL) ? ((int)num4) : 0x7fffffff, ((num * 0x989680L) / num5) / 0x400L); } else { backgroundWorker.ReportProgress((num4 <= 0x7fffffffL) ? ((int)num4) : 0x7fffffff, null); } } } while (count > 0); } resultSize = num; FileGarbageCollector.Instance.Remove(item); } finally { if (stream != null) { stream.Close(); stream.Dispose(); } backgroundWorker.ReportProgress(0x7fffffff, Messages.DownloadCompleted); } if ((conversionStringTemplate != null) && ApplicationSettings.Instance.UseIndirectConversion) { FileGarbageCollector.Instance.Add(item); string str2 = item + ".tmp"; FileGarbageCollector.Instance.Add(str2); string arguments = string.Format(conversionStringTemplate, item, str2); var info2 = new ProcessStartInfo("ffmpeg.exe", arguments) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(Application.StartupPath), RedirectStandardError = true, RedirectStandardOutput = true }; var process = new Process { StartInfo = info2 }; int userState = 0; FileGarbageCollector.Instance.Add(targetFile); try { backgroundWorker.ReportProgress(0, "Converting"); process.Start(); long num1 = DateTime.Now.Ticks; StreamReader standardError = process.StandardError; int percentProgress = 0; do { Application.DoEvents(); string str = standardError.ReadLine(); Application.DoEvents(); if (str.Contains("Duration: ")) { TimeSpan span; if (TimeSpan.TryParse(TextUtil.JustAfter(str, "Duration: ", ","), out span)) { userState = (int)span.TotalSeconds; backgroundWorker.ReportProgress(0, userState); } } else { int num8; if ((str.Contains("size=") && str.Contains("time=")) && int.TryParse(TextUtil.JustAfter(str, "time=", "."), out num8)) { //percentProgress = (num8 <= this.progressIndicator.Maximum) ? num8 : this.progressIndicator.Maximum; } } backgroundWorker.ReportProgress(percentProgress, userState); if (backgroundWorker.CancellationPending) { process.Kill(); process.Close(); process.Dispose(); flag = true; } } while (!standardError.EndOfStream); process.WaitForExit(); if (!backgroundWorker.CancellationPending) { int exitCode = process.ExitCode; } else { flag = true; } File.Move(str2, targetFile); FileGarbageCollector.Instance.Remove(targetFile); } catch (Exception exception) { try { process.Kill(); } catch { } try { process.Close(); } catch { } try { process.Dispose(); } catch { } string message = exception.Message; } } resultSize = num / 0x400L; return(flag); }
protected override void DoTest() { if (IsPauseForScreenShots) { RunUI(() => SkylineWindow.SetUIMode(SrmDocument.DOCUMENT_TYPE.small_molecules)); } else // old way of doing things { // Setting the UI mode, p 2 var startPage = WaitForOpenForm <StartPage>(); RunUI(() => startPage.SetUIMode(SrmDocument.DOCUMENT_TYPE.proteomic)); // PauseForScreenShot<StartPage>("Start Window proteomic", 2); RunUI(() => startPage.SetUIMode(SrmDocument.DOCUMENT_TYPE.small_molecules)); // PauseForScreenShot<StartPage>("Start Window small molecule", 3); ShowSkyline(() => startPage.DoAction(skylineWindow => true)); } // Inserting a Transition List, p. 3 { var doc = SkylineWindow.Document; var pasteDlg = ShowDialog <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg); RunUI(() => { pasteDlg.IsMolecule = true; pasteDlg.SetSmallMoleculeColumns(null); // Default columns pasteDlg.Height = 290; }); PauseForScreenShot <PasteDlg>("Paste Dialog in molecule mode", 3); var columnsOrdered = new[] { // Molecule List Name,Precursor Name,Precursor Formula,Precursor Charge,Precursor RT,Precursor CE,Product m/z,Product Charge, label type SmallMoleculeTransitionListColumnHeaders.moleculeGroup, SmallMoleculeTransitionListColumnHeaders.namePrecursor, SmallMoleculeTransitionListColumnHeaders.formulaPrecursor, SmallMoleculeTransitionListColumnHeaders.adductPrecursor, SmallMoleculeTransitionListColumnHeaders.chargePrecursor, SmallMoleculeTransitionListColumnHeaders.rtPrecursor, SmallMoleculeTransitionListColumnHeaders.cePrecursor, SmallMoleculeTransitionListColumnHeaders.mzProduct, SmallMoleculeTransitionListColumnHeaders.chargeProduct, SmallMoleculeTransitionListColumnHeaders.labelType }.ToList(); if (_inferredLabels) { columnsOrdered.Remove(SmallMoleculeTransitionListColumnHeaders.labelType); } RunUI(() => { pasteDlg.SetSmallMoleculeColumns(columnsOrdered); }); WaitForConditionUI(() => pasteDlg.GetUsableColumnCount() == columnsOrdered.Count); PauseForScreenShot <PasteDlg>("Paste Dialog with selected and ordered columns - show columns checklist", 5); SetCsvFileClipboardText(GetTestPath("SMTutorial_TransitionList.csv"), true); RunUI(pasteDlg.PasteTransitions); RunUI(pasteDlg.ValidateCells); RunUI(() => pasteDlg.Height = 428); PauseForScreenShot <PasteDlg>("Paste Dialog with validated contents", 6); OkDialog(pasteDlg, pasteDlg.OkDialog); var docTargets = WaitForDocumentChange(doc); AssertEx.IsDocumentState(docTargets, null, 6, 12, 19, 21); Assert.IsFalse(docTargets.MoleculeTransitions.Any(t => t.Transition.IsPrecursor())); RunUI(() => { SkylineWindow.ChangeTextSize(TreeViewMS.LRG_TEXT_FACTOR); SkylineWindow.Size = new Size(957, 654); }); RestoreViewOnScreen(5); PauseForScreenShot <SkylineWindow>("Skyline with small molecule targets", 5); RunUI(() => SkylineWindow.SaveDocument(GetTestPath("Amino Acid Metabolism.sky"))); using (new WaitDocumentChange(null, true)) { var importResultsDlg1 = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults); var openDataSourceDialog1 = ShowDialog <OpenDataSourceDialog>(() => importResultsDlg1.NamedPathSets = importResultsDlg1.GetDataSourcePathsFile(null)); RunUI(() => { openDataSourceDialog1.CurrentDirectory = new MsDataFilePath(GetTestPath()); openDataSourceDialog1.SelectAllFileType(ExtWatersRaw); }); PauseForScreenShot <ImportResultsDlg>("Import Results Files form", 6); OkDialog(openDataSourceDialog1, openDataSourceDialog1.Open); var importResultsNameDlg = ShowDialog <ImportResultsNameDlg>(importResultsDlg1.OkDialog); OkDialog(importResultsNameDlg, importResultsNameDlg.NoDialog); } SelectNode(SrmDocument.Level.MoleculeGroups, 0); PauseForScreenShot <SkylineWindow>("Skyline window multi-target graph", 8); var docResults = SkylineWindow.Document; var expectedTransCount = new Dictionary <string, int[]> { // transition groups, heavy transition groups, tranistions, heavy transitions { "ID15656_01_WAA263_3976_020415", new[] { 12, 7, 13, 8 } }, { "ID15658_01_WAA263_3976_020415", new[] { 12, 6, 13, 7 } }, { "ID15659_01_WAA263_3976_020415", new[] { 12, 7, 13, 8 } }, { "ID15661_01_WAA263_3976_020415", new[] { 12, 7, 13, 8 } }, { "ID15662_01_WAA263_3976_020415", new[] { 12, 7, 13, 8 } }, { "ID15663_01_WAA263_3976_020415", new[] { 11, 7, 12, 8 } }, { "ID15664_01_WAA263_3976_020415", new[] { 11, 6, 12, 7 } }, { "ID15739_01_WAA263_3976_020415", new[] { 10, 6, 10, 7 } }, { "ID15740_01_WAA263_3976_020415", new[] { 12, 6, 12, 7 } }, { "ID15740_02_WAA263_3976_020415", new[] { 11, 5, 11, 6 } }, { "ID15740_04_WAA263_3976_020415", new[] { 12, 6, 12, 7 } }, { "ID15741_01_WAA263_3976_020415", new[] { 12, 7, 13, 8 } }, { "ID15741_02_WAA263_3976_020415", new[] { 12, 6, 13, 7 } } }; var msg = ""; foreach (var chromatogramSet in docResults.Settings.MeasuredResults.Chromatograms) { int[] transitions; if (!expectedTransCount.TryGetValue(chromatogramSet.Name, out transitions)) { transitions = new[] { 12, 7, 13, 8 } } ; // Most have this value try { AssertResult.IsDocumentResultsState(docResults, chromatogramSet.Name, 12, transitions[0], transitions[1], transitions[2], transitions[3]); } catch (Exception x) { msg = TextUtil.LineSeparate(msg, x.Message); } } if (!string.IsNullOrEmpty(msg)) { Assert.IsTrue(string.IsNullOrEmpty(msg), msg); } RestoreViewOnScreen(9); PauseForScreenShot <SkylineWindow>("Skyline window multi-replicate layout", 9); if (IsCoverShotMode) { RunUI(() => { Settings.Default.ChromatogramFontSize = 14; Settings.Default.AreaFontSize = 14; SkylineWindow.ChangeTextSize(TreeViewMS.LRG_TEXT_FACTOR); SkylineWindow.AutoZoomBestPeak(); }); RestoreCoverViewOnScreen(); var pasteCoverDlg = ShowDialog <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg); SetCsvFileClipboardText(GetTestPath("SMTutorial_TransitionList.csv"), true); RunUI(() => { pasteCoverDlg.Size = new Size(810, 375); pasteCoverDlg.Left = SkylineWindow.Left + 8; pasteCoverDlg.Top = SkylineWindow.Bottom - pasteCoverDlg.Height - 8; pasteCoverDlg.PasteTransitions(); pasteCoverDlg.ValidateCells(); columnsOrdered.Remove(SmallMoleculeTransitionListColumnHeaders.labelType); pasteCoverDlg.SetSmallMoleculeColumns(columnsOrdered); }); TakeCoverShot(); OkDialog(pasteCoverDlg, pasteCoverDlg.CancelDialog); } } } }
protected ReadOnlyUrl GetCandidateUrl(Guid candidateId, ProfessionalVisibility visibility, LocationReference location, Salary desiredSalary, string desiredJobTitle) { var sb = new StringBuilder(); // Location. if (!string.IsNullOrEmpty(location.ToString())) { sb.Append(TextUtil.StripExtraWhiteSpace(TextUtil.StripToAlphaNumericAndWhiteSpace(location.ToString())).ToLower().Replace(' ', '-')); } else { if (location.IsCountry) { sb.Append(location.Country.ToString().ToLower()); } else { sb.Append("-"); } } // Salary. sb.Append("/"); if (desiredSalary == null || !visibility.IsFlagSet(ProfessionalVisibility.Salary)) { sb.Append("-"); } else { desiredSalary = desiredSalary.ToRate(SalaryRate.Year); if (desiredSalary.LowerBound != null) { if (desiredSalary.UpperBound != null) { sb.Append((int)(desiredSalary.LowerBound) / 1000).Append("k-").Append((int)(desiredSalary.UpperBound) / 1000).Append("k"); } else { sb.Append((int)(desiredSalary.LowerBound) / 1000).Append("k-and-above"); } } else { sb.Append("up-to-").Append((int)(desiredSalary.UpperBound) / 1000).Append("k"); } } // Job title. sb.Append("/"); if (string.IsNullOrEmpty(desiredJobTitle)) { sb.Append("-"); } else { sb.Append(TextUtil.StripExtraWhiteSpace(TextUtil.StripToAlphaNumericAndSpace(desiredJobTitle)).ToLower().Replace(' ', '-')); } // Id sb.Append("/"); sb.Append(candidateId.ToString()); return(new ReadOnlyApplicationUrl(_baseCandidateUrl, sb.ToString())); }
public override string SerializeToString(object obj) { var prop = obj as ICalendarProperty; if (prop?.Values == null || !prop.Values.Any()) { return(null); } // Push this object on the serialization context. SerializationContext.Push(prop); // Get a serializer factory that we can use to serialize // the property and parameter values var sf = GetService <ISerializerFactory>(); var result = new StringBuilder(1024); foreach (var v in prop.Values.Where(value => value != null)) { // Get a serializer to serialize the property's value. // If we can't serialize the property's value, the next step is worthless anyway. var valueSerializer = sf.Build(v.GetType(), SerializationContext) as IStringSerializer; // Iterate through each value to be serialized, // and give it a property (with parameters). // FIXME: this isn't always the way this is accomplished. // Multiple values can often be serialized within the // same property. How should we fix this? // NOTE: // We Serialize the property's value first, as during // serialization it may modify our parameters. // FIXME: the "parameter modification" operation should // be separated from serialization. Perhaps something // like PreSerialize(), etc. var value = valueSerializer.SerializeToString(v); // Get the list of parameters we'll be serializing var parameterList = prop.Parameters; if (v is ICalendarDataType) { parameterList = (v as ICalendarDataType).Parameters; } //This says that the TZID property of an RDATE/EXDATE collection is owned by the PeriodList that contains it. There's nothing in the spec that //prohibits having multiple EXDATE or RDATE collections, each of which specifies a different TZID. What *should* happen during serialization is //that we should work with a single collection of zoned datetime objects, and we should create distinct RDATE and EXDATE collections based on //those values. Right now, if you add CalDateTime objects, each of which specifies a different time zone, the first one "wins". This means //application developers will need to handle those cases outside the library. if (v is PeriodList) { var typed = (PeriodList)v; if (!string.IsNullOrWhiteSpace(typed.TzId) && parameterList.All(p => string.Equals("TZID", p.Value, StringComparison.OrdinalIgnoreCase))) { parameterList.Set("TZID", typed.TzId); } } var sb = new StringBuilder(256); sb.Append(prop.Name); if (parameterList.Any()) { // Get a serializer for parameters var parameterSerializer = sf.Build(typeof(CalendarParameter), SerializationContext) as IStringSerializer; if (parameterSerializer != null) { // Serialize each parameter // Separate parameters with semicolons sb.Append(";"); sb.Append(string.Join(";", parameterList.Select(param => parameterSerializer.SerializeToString(param)))); } } sb.Append(":"); sb.Append(value); result.Append(TextUtil.FoldLines(sb.ToString())); } // Pop the object off the serialization context. SerializationContext.Pop(); return(result.ToString()); }
public void CommonOverlapRecurringPatternOverlap() { Assert.Equal(4, TextUtil.CommonOverlap("xyz1212", "1212abc")); }
void DoListCustomDrawing(ref Message m) { NMLVCUSTOMDRAW lvcd = ( NMLVCUSTOMDRAW )m.GetLParam(typeof(NMLVCUSTOMDRAW)); int row = lvcd.nmcd.dwItemSpec; int col = lvcd.iSubItem; // If we don't have any items we must be doing something wrong // because the list is only going to request custom drawing of items // in the list, if we have items in the list, the Items cannot possibly // be zero Debug.Assert(Items.Count != 0); ListViewItem lvi = Items[row]; Rectangle rc = GetSubItemRect(row, col); // Draw the item // We did not need to actually paint the items that are not selected // but doing all the painting ourselves eliminates some random bugs where // the list sometimes did not update a subitem that was not selected anymore // leaving the subitem with a different background color // than the rest of the row Graphics g = Graphics.FromHdc(lvcd.nmcd.hdc); // Draw Fill Rectangle if (IsRowSelected(row)) { int subItemOffset = 2; if (GridLines) { subItemOffset = 3; } g.FillRectangle(ColorUtil.VSNetSelectionBrush, rc.Left + 1, rc.Top + 1, rc.Width - 2, rc.Height - subItemOffset); // Draw Border if (col == 0) { Color borderColor = SystemColors.Highlight; int heightOffset = 1; if (GridLines) { heightOffset = 2; } g.DrawRectangle(new Pen(borderColor), rc.Left + 1, rc.Top, rc.Width - 2, rc.Height - heightOffset); } } else { if (col == lastSortedColumn) { if (col == 0) { rc = AdjustFirstItemRect(rc); } g.FillRectangle(new SolidBrush(Color.FromArgb(247, 247, 247)), rc.Left, rc.Top, rc.Width, rc.Height); } else { if (col == 0) { rc = AdjustFirstItemRect(rc); } g.FillRectangle(SystemBrushes.Window, rc.Left, rc.Top, rc.Width, rc.Height); } } // Adjust rectangle, when getting the rectangle for column zero // the rectangle return is the one for the whole control if (col == 0) { rc = AdjustFirstItemRect(rc); } // Draw Text string text = GetSubItemText(row, col); Size textSize = TextUtil.GetTextSize(g, text, Font); int gap = 4; Point pos = new Point(rc.Left + gap, rc.Top + ((rc.Height - textSize.Height) / 2)); // I use the Windows API instead of the Graphics object to draw the string // because the Graphics object draws ellipes without living blank spaces in between // the DrawText API adds those blank spaces in between int ellipsingTringgering = 8; if (CheckBoxes && col == 0) { // draw checkbox int checkIndex = 0; if (lvi.Checked) { checkIndex = 1; } g.DrawImage(checkBoxesImageList.Images[checkIndex], rc.Left + gap, rc.Top); pos.X += IMAGE_WIDTH; rc.Width = rc.Width - IMAGE_WIDTH; } else if (col == 0 && CheckBoxes == false && lvi.ImageIndex != -1 && lvi.ImageList != null) { ImageList imageList = lvi.ImageList; Image image = imageList.Images[lvi.ImageIndex]; if (image != null) { g.DrawImage(imageList.Images[lvi.ImageIndex], rc.Left + gap, rc.Top); pos.X += IMAGE_WIDTH; rc.Width = rc.Width - IMAGE_WIDTH; } } Rectangle drawRect = new Rectangle(pos.X + 2, pos.Y, rc.Width - gap - ellipsingTringgering, rc.Height); TextUtil.DrawText(g, text, Font, drawRect); g.Dispose(); // Put structure back in the message Marshal.StructureToPtr(lvcd, m.LParam, true); m.Result = ( IntPtr )CustomDrawReturnFlags.CDRF_SKIPDEFAULT; }
public void CommonOverlapDisjunctStringsNoOverlap() { // No overlap. Assert.Equal(0, TextUtil.CommonOverlap("123456", "abcd")); }
void DoHeaderCustomDrawing(ref Message m) { NMCUSTOMDRAW nmcd = ( NMCUSTOMDRAW )m.GetLParam(typeof(NMCUSTOMDRAW)); Graphics g = Graphics.FromHdc(nmcd.hdc); Rectangle rc = GetHeaderCtrlRect(); rc = GetHeaderItemRect(nmcd.dwItemSpec); int itemRight = rc.Left + rc.Width; g.FillRectangle(SystemBrushes.ScrollBar, rc.Left, rc.Top, rc.Width, rc.Height); if (nmcd.dwItemSpec == PressedHeaderItem && !IsCursorOnDivider() && Tracking == false) { PressedHeaderItem = -1; rc.Inflate(-1, -1); g.FillRectangle(ColorUtil.VSNetPressedBrush, rc.Left, rc.Top, rc.Width, rc.Height); } else { ControlPaint.DrawBorder3D(g, rc.Left, rc.Top, rc.Width, rc.Height - 1, Border3DStyle.RaisedInner, Border3DSide.All); } string text = GetHeaderItemText(nmcd.dwItemSpec); Debug.WriteLine(text); Size textSize = TextUtil.GetTextSize(g, text, Font); int gap = 4; Point pos = new Point(rc.Left + gap, rc.Top + ((rc.Height - textSize.Height) / 2)); int headerImageIndex; if (headerIconsList != null && HasHeaderImage(nmcd.dwItemSpec, out headerImageIndex)) { if (headerImageIndex != -1) { Image image = headerImageList.Images[headerImageIndex]; if (image != null) { g.DrawImage(headerImageList.Images[headerImageIndex], rc.Left + gap, rc.Top); pos.X += IMAGE_WIDTH; rc.Width = rc.Width - IMAGE_WIDTH; } } } // Draw arrow glyph if (nmcd.dwItemSpec == lastSortedColumn) { int Left = pos.X + 2; Left += textSize.Width + TEXT_TO_ARROW_GAP; Rectangle arrowRect = new Rectangle(Left, rc.Top, ARROW_WIDTH, rc.Height); if (itemRight >= (Left + ARROW_WIDTH + 4)) { if (Sorting == SortOrder.Ascending || Sorting == SortOrder.None) { DrawUpArrow(g, arrowRect); } else { DrawDownArrow(g, arrowRect); } } } // I use the Windows API instead of the Graphics object to draw the string // because the Graphics object draws ellipes without living blank spaces in between // the DrawText API adds those blank spaces in between int ellipsingTringgering = 8; Rectangle drawRect = new Rectangle(pos.X + 2, pos.Y, rc.Width - gap - ellipsingTringgering, rc.Height); TextUtil.DrawText(g, text, Font, drawRect); g.Dispose(); m.Result = ( IntPtr )CustomDrawReturnFlags.CDRF_SKIPDEFAULT; }
public void CommonOverlapFirstEndsWithStartOfSecondOverlap() { // Overlap. Assert.Equal(3, TextUtil.CommonOverlap("123456xyz", "xyzabcd")); }
private void InstallUpdates(ICollection <ToolUpdateInfo> tools) { if (tools != null && tools.Count != 0 && !TestingDownloadOnly) { var failedUpdates = new Dictionary <string, string>(); var successfulUpdates = new Collection <string>(); int installCount = 0; foreach (var tool in tools) { labelOperation.Text = string.Format(Resources.ToolUpdatesDlg_InstallUpdates_Installing_updates_to__0_, tool._packageName); var toolList = ToolList.CopyTools(Settings.Default.ToolList); bool exceptionThrown = false; ToolInstaller.UnzipToolReturnAccumulator result = null; try { result = _updateHelper.UnpackZipTool(tool.FilePath, new ToolInstallUI.InstallZipToolHelper(this, _parent.InstallProgram)); } catch (ToolExecutionException x) { failedUpdates.Add(tool._packageName, x.Message); exceptionThrown = true; } catch (IOException x) { failedUpdates.Add(tool._packageName, TextUtil.LineSeparate(string.Format(Resources.ConfigureToolsDlg_UnpackZipTool_Failed_attempting_to_extract_the_tool_from__0_, Path.GetFileName(tool.FilePath)), x.Message)); exceptionThrown = true; } progressBar.Value = Convert.ToInt32((((((double)++installCount) / tools.Count) * 100) / 2) + 50); if (result == null) { // user cancelled if (!exceptionThrown) { failedUpdates.Add(tool._packageName, Resources.ToolUpdatesDlg_InstallUpdates_User_cancelled_installation); } // reset tool list Settings.Default.ToolList = toolList; continue; } // tool was successfully updated result.MessagesThrown.ForEach(message => MessageDlg.Show(this, message)); successfulUpdates.Add(tool._packageName); } // clean-up DirectoryEx.SafeDelete(ToolDir.FullName); progressBar.Value = 100; DisplayInstallSummary(successfulUpdates, failedUpdates); } }
public void CommonPrefixBothStringsStartWithSameCommonPrefixIsDetected2() { // Non-null case. Assert.Equal(4, TextUtil.CommonPrefix("abc1234abcdef", "efgh1234xyz", 3, 4)); }
public static bool?OverwriteOrInParallel(Control parent, string toolCollectionName, string toolCollectionVersion, List <ReportOrViewSpec> reportList, string foundVersion, string newCollectionName) { string message; string buttonText; if (toolCollectionName != null) { RelativeVersion relativeVersion = DetermineRelativeVersion(toolCollectionVersion, foundVersion); string toolMessage; switch (relativeVersion) { case RelativeVersion.upgrade: toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_, String.Empty, String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_in_parallel_, foundVersion)); buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Upgrade; break; case RelativeVersion.olderversion: toolMessage = TextUtil.LineSeparate( String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the_tool__1_, foundVersion, @"{0}"), String.Empty, String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_version__0__or_install_in_parallel_, foundVersion)); buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite; break; case RelativeVersion.reinstall: toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_, String.Empty, Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_parallel_); buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Reinstall; break; default: toolMessage = TextUtil.LineSeparate( Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_installation, String.Empty, Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_); buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite; // Or update? break; } message = String.Format(toolMessage, toolCollectionName); } else //Warn about overwritng report. { List <string> reportTitles = reportList.Select(sp => sp.GetKey()).ToList(); string reportMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_following_reports, String.Empty, @"{0}", String.Empty); string reportSingleMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report_titled__0_, String.Empty); string reportMessage = reportList.Count == 1 ? reportSingleMessage : reportMultiMessage; string question = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_; buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite; string reportMessageFormat = TextUtil.LineSeparate(reportMessage, question); message = String.Format(reportMessageFormat, TextUtil.LineSeparate(reportTitles)); } DialogResult result = MultiButtonMsgDlg.Show( parent, message, buttonText, Resources.ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel, true); switch (result) { case DialogResult.Cancel: return(null); case DialogResult.Yes: return(true); case DialogResult.No: return(false); } return(false); }
public void CommonSuffixDisjunctStringsNoCommonSuffix() { // Detect any common suffix. // Null case. Assert.Equal(0, TextUtil.CommonSuffix("abc", "xyz")); }
public static Size RenderTip(TransitionDocNode nodeTran, Graphics g, Size sizeMax, bool draw) { var table = new TableDesc(); using (RenderTools rt = new RenderTools()) { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Ion, nodeTran.Transition.FragmentIonName, rt); table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Charge, nodeTran.Transition.Charge.ToString(LocalizationHelper.CurrentCulture), rt); table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Product_m_z, string.Format("{0:F04}", nodeTran.Mz), rt); // Not L10N int?decoyMassShift = nodeTran.Transition.DecoyMassShift; if (decoyMassShift.HasValue) { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Decoy_Mass_Shift, decoyMassShift.Value.ToString(LocalizationHelper.CurrentCulture), rt); } if (nodeTran.HasLoss) { // If there is only one loss, show its full description var losses = nodeTran.Losses; if (losses.Losses.Count == 1) { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Loss, losses.ToStrings()[0], rt); } // Otherwise, just show the total mass for multiple losses // followed by individual losses else { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Loss, string.Format("{0:F04}", losses.Mass), rt); // Not L10N table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Losses, TextUtil.LineSeparate(losses.ToStrings()), rt); } } if (nodeTran.HasLibInfo) { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Library_rank, nodeTran.LibInfo.Rank.ToString(LocalizationHelper.CurrentCulture), rt); float intensity = nodeTran.LibInfo.Intensity; table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Library_intensity, MathEx.RoundAboveZero(intensity, (intensity < 10 ? 1 : 0), 4).ToString(LocalizationHelper.CurrentCulture), rt); } if (nodeTran.Transition.IsCustom() && !string.IsNullOrEmpty(nodeTran.Transition.CustomIon.Formula)) { table.AddDetailRow(Resources.TransitionTreeNode_RenderTip_Formula, nodeTran.Transition.CustomIon.Formula, rt); } SizeF size = table.CalcDimensions(g); if (draw) { table.Draw(g); } return(new Size((int)size.Width + 2, (int)size.Height + 2)); } }
private bool ProcessMSLevel(MsDataFileUri filePath, int msLevel, IEnumerable <ChromatogramInfo> transitionPointSets, ChromatogramGroupInfo chromInfo, double?apexRT, TransitionGroupDocNode nodeGroup, LibKey libKey, float tolerance) { var transitions = new List <TransitionFullScanInfo>(); var chromSource = (msLevel == 1) ? ChromSource.ms1 : ChromSource.fragment; IList <float> times = null; foreach (var tranPointSet in transitionPointSets.Where(t => t.Source == chromSource)) { transitions.Add(new TransitionFullScanInfo { //Name = tranPointSet.Header., Source = chromSource, TimeIntensities = tranPointSet.TimeIntensities, PrecursorMz = chromInfo.PrecursorMz, ProductMz = tranPointSet.ProductMz, ExtractionWidth = tranPointSet.ExtractionWidth, //Id = nodeTran.Id }); times = tranPointSet.Times; } if (!transitions.Any()) { return(true); // Nothing to do at this ms level } var chorusUrl = filePath as ChorusUrl; IScanProvider scanProvider; if (null == chorusUrl) { scanProvider = new ScanProvider(_documentFilePath, filePath, chromSource, times, transitions.ToArray(), _document.Settings.MeasuredResults, () => _document.Settings.MeasuredResults.LoadMSDataFileScanIds(filePath)); } else { scanProvider = new ChorusScanProvider(_documentFilePath, chorusUrl, chromSource, times, transitions.ToArray()); } // Across all spectra at the peak retention time, find the one with max total // intensity for the mz's of interest (ie the isotopic distribution) and note its ion mobility. var scanIndex = MsDataFileScanHelper.FindScanIndex(times, apexRT.Value); _msDataFileScanHelper.UpdateScanProvider(scanProvider, 0, scanIndex); _msDataFileScanHelper.MsDataSpectra = null; // Reset scanIndex = _msDataFileScanHelper.GetScanIndex(); _msDataFileScanHelper.ScanProvider.SetScanForBackgroundLoad(scanIndex); lock (this) { while (_msDataFileScanHelper.MsDataSpectra == null && _dataFileScanHelperException == null) { if (_progressMonitor != null && _progressMonitor.IsCanceled) { return(false); } Monitor.Wait(this, 500); // Let background loader do its thing } } if (_dataFileScanHelperException != null) { throw new IOException(TextUtil.LineSeparate(Resources.DriftTimeFinder_HandleLoadScanException_Problem_using_results_to_populate_drift_time_library__, _dataFileScanHelperException.Message), _dataFileScanHelperException); } if (_progressMonitor != null && !ReferenceEquals(nodeGroup, _currentDisplayedTransitionGroupDocNode)) { // Do this after scan load so first group after file switch doesn't seem laggy _progressStatus = _progressStatus.ChangeMessage(TextUtil.LineSeparate(filePath.GetFileName(), nodeGroup.ToString())). UpdatePercentCompleteProgress(_progressMonitor, _currentStep++, _totalSteps); _currentDisplayedTransitionGroupDocNode = nodeGroup; } EvaluateBestIonMobilityValue(msLevel, libKey, tolerance, transitions); return(true); }
void IJobFeedMapper <SyndicationItem> .ApplyPostData(SyndicationItem post, JobAd jobAd) { jobAd.Title = post.Title.Text; jobAd.CreatedTime = post.PublishDate.ToLocalTime().DateTime; jobAd.LastUpdatedTime = DateTime.Now; // Truncate to the maximum size. jobAd.Description.Summary = string.IsNullOrEmpty(post.Summary.Text) ? null : post.Summary.Text.Length > Domain.Roles.JobAds.Constants.MaxSummaryLength ? TextUtil.TruncateForDisplay(post.Summary.Text, Domain.Roles.JobAds.Constants.MaxSummaryLength) : post.Summary.Text; string suburb = null; string state = null; string postCode = null; foreach (var extension in post.ElementExtensions.Where(e => e.OuterNamespace == "http://www.pageuppeople.com")) { switch (extension.OuterName) { case "closingDate": GetValue(extension, value => jobAd.ExpiryTime = value); break; case "refNo": jobAd.Integration.ExternalReferenceId = extension.GetObject <string>(); break; case "applyLink": jobAd.Integration.ExternalApplyUrl = extension.GetObject <string>(); break; case "description": jobAd.Description.Content = extension.GetObject <string>(); break; case "workType": GetValue(extension, value => jobAd.Description.JobTypes = value); break; case "category": GetValue(extension, value => jobAd.Description.Industries = new[] { value }); break; case "siteSuburb": suburb = extension.GetObject <string>(); break; case "siteState": state = extension.GetObject <string>(); break; case "sitePostCode": postCode = extension.GetObject <string>(); break; } } jobAd.Description.Location = _locationQuery.ResolveLocation(_australia, string.Format("{0} {1} {2}", suburb, state, postCode)); }
protected override void DoTest() { // Inserting a Transition List, p. 2 { var doc = SkylineWindow.Document; var pasteDlg = ShowDialog <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg); RunUI(() => { pasteDlg.IsMolecule = false; // Default peptide view pasteDlg.Size = new Size(800, 275); }); PauseForScreenShot <PasteDlg>("Paste Dialog in peptide mode", 2); RunUI(() => { pasteDlg.IsMolecule = true; pasteDlg.SetSmallMoleculeColumns(null); // Default columns }); PauseForScreenShot <PasteDlg>("Paste Dialog in small molecule mode, default columns", 3); if (IsPauseForScreenShots) { var columnsRestricted = new[] { // Molecule List Name,Precursor Name,Precursor Formula,Product m/z,Precursor Charge,Product Charge,Precursor RT,Precursor CE PasteDlg.SmallMoleculeTransitionListColumnHeaders.moleculeGroup, PasteDlg.SmallMoleculeTransitionListColumnHeaders.namePrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.formulaPrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.mzProduct, PasteDlg.SmallMoleculeTransitionListColumnHeaders.chargePrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.chargeProduct, PasteDlg.SmallMoleculeTransitionListColumnHeaders.rtPrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.cePrecursor, }.ToList(); RunUI(() => { pasteDlg.SetSmallMoleculeColumns(columnsRestricted); pasteDlg.Height = 339; }); WaitForConditionUI(() => pasteDlg.GetUsableColumnCount() == columnsRestricted.Count); PauseForScreenShot <PasteDlg>("Paste Dialog with selected columns - show Columns checklist", 4); } var columnsOrdered = new[] { // Molecule List Name,Precursor Name,Precursor Formula,Precursor Charge,Precursor RT,Precursor CE,Product m/z,Product Charge, label type PasteDlg.SmallMoleculeTransitionListColumnHeaders.moleculeGroup, PasteDlg.SmallMoleculeTransitionListColumnHeaders.namePrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.formulaPrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.chargePrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.rtPrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.cePrecursor, PasteDlg.SmallMoleculeTransitionListColumnHeaders.mzProduct, PasteDlg.SmallMoleculeTransitionListColumnHeaders.chargeProduct, PasteDlg.SmallMoleculeTransitionListColumnHeaders.labelType }.ToList(); RunUI(() => { pasteDlg.SetSmallMoleculeColumns(columnsOrdered); }); WaitForConditionUI(() => pasteDlg.GetUsableColumnCount() == columnsOrdered.Count); PauseForScreenShot <PasteDlg>("Paste Dialog with selected and ordered columns", 4); SetCsvFileClipboardText(GetTestPath("SMTutorial_TransitionList_HeavyLight.csv"), true); RunUI(pasteDlg.PasteTransitions); RunUI(pasteDlg.ValidateCells); PauseForScreenShot <PasteDlg>("Paste Dialog with validated contents", 5); OkDialog(pasteDlg, pasteDlg.OkDialog); var docTargets = WaitForDocumentChange(doc); AssertEx.IsDocumentState(docTargets, null, 6, 12, 19, 21); Assert.IsFalse(docTargets.MoleculeTransitions.Any(t => t.Transition.IsPrecursor())); RunUI(() => { SkylineWindow.ChangeTextSize(TreeViewMS.LRG_TEXT_FACTOR); SkylineWindow.Size = new Size(957, 654); }); RestoreViewOnScreen(5); PauseForScreenShot <SkylineWindow>("Skyline with small molecule targets", 5); RunUI(() => SkylineWindow.SaveDocument(GetTestPath("Amino Acid Metabolism.sky"))); using (new WaitDocumentChange(null, true)) { var importResultsDlg1 = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults); var openDataSourceDialog1 = ShowDialog <OpenDataSourceDialog>(() => importResultsDlg1.NamedPathSets = importResultsDlg1.GetDataSourcePathsFile(null)); RunUI(() => { openDataSourceDialog1.CurrentDirectory = new MsDataFilePath(GetTestPath()); openDataSourceDialog1.SelectAllFileType(UseRawFiles ? ExtensionTestContext.ExtWatersRaw : ExtensionTestContext.ExtMzml); }); PauseForScreenShot <ImportResultsSamplesDlg>("Import Results Files form", 6); OkDialog(openDataSourceDialog1, openDataSourceDialog1.Open); var importResultsNameDlg = ShowDialog <ImportResultsNameDlg>(importResultsDlg1.OkDialog); OkDialog(importResultsNameDlg, importResultsNameDlg.NoDialog); } SelectNode(SrmDocument.Level.MoleculeGroups, 0); PauseForScreenShot <SkylineWindow>("Skyline window multi-target graph", 8); var docResults = SkylineWindow.Document; var expectedTransCount = new Dictionary <string, int[]> { // transition groups, heavy transition groups, tranistions, heavy transitions { "ID15656_01_WAA263_3976_020415", new[] { 12, 5, 13, 6 } }, { "ID15658_01_WAA263_3976_020415", new[] { 12, 6, 13, 7 } }, { "ID15659_01_WAA263_3976_020415", new[] { 11, 7, 12, 8 } }, { "ID15661_01_WAA263_3976_020415", new[] { 12, 7, 12, 8 } }, { "ID15662_01_WAA263_3976_020415", new[] { 12, 7, 12, 8 } }, { "ID15663_01_WAA263_3976_020415", new[] { 12, 7, 12, 8 } }, { "ID15664_01_WAA263_3976_020415", new[] { 11, 6, 11, 7 } }, { "ID15739_01_WAA263_3976_020415", new[] { 10, 6, 10, 7 } }, { "ID15740_01_WAA263_3976_020415", new[] { 12, 6, 12, 7 } }, { "ID15740_02_WAA263_3976_020415", new[] { 12, 5, 12, 6 } }, { "ID15740_04_WAA263_3976_020415", new[] { 12, 6, 12, 7 } }, { "ID15741_01_WAA263_3976_020415", new[] { 12, 7, 12, 8 } }, { "ID15741_02_WAA263_3976_020415", new[] { 12, 6, 12, 7 } } }; var msg = ""; foreach (var chromatogramSet in docResults.Settings.MeasuredResults.Chromatograms) { int[] transitions; if (!expectedTransCount.TryGetValue(chromatogramSet.Name, out transitions)) { transitions = new[] { 12, 7, 13, 8 } } ; // Most have this value try { AssertResult.IsDocumentResultsState(docResults, chromatogramSet.Name, 12, transitions[0], transitions[1], transitions[2], transitions[3]); } catch (Exception x) { msg = TextUtil.LineSeparate(msg, x.Message); } } if (!string.IsNullOrEmpty(msg)) { Assert.IsTrue(string.IsNullOrEmpty(msg), msg); } RestoreViewOnScreen(9); PauseForScreenShot <SkylineWindow>("Skyline window multi-replicate layout", 9); } } }
public void CommonOverlapFirstIsPrefixOfSecondFullOverlap() { // Whole case. Assert.Equal(3, TextUtil.CommonOverlap("abc", "abcd")); }
public static Lib.Data.Firma FirmaInText(string text) { if (string.IsNullOrEmpty(text)) { return(null); } string value = Devmasters.TextUtil.RemoveDiacritics(TextUtil.NormalizeToBlockText(text).ToLower()); foreach (var k in Firma.Koncovky.Select(m => m.ToLower()).OrderByDescending(m => m.Length)) { if (value.Contains(k)) { value = value.Replace(k, k.Replace(' ', (char)160)); //nahrad mezery char(160) - non breaking space, aby to tvorilo 1 slovo } else if (k.EndsWith(".") && value.EndsWith(k.Substring(0, k.Length - 1))) { value = value.Replace(k.Substring(0, k.Length - 1), k.Replace(' ', (char)160)); //nahrad mezery char(160) - non breaking space, aby to tvorilo 1 slovo } } //find company name string[] words = value.Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries); //get back space instead of #160 words = words.Select(m => m.Replace((char)160, ' ')).ToArray(); for (int firstWord = 0; firstWord < words.Length; firstWord++) { for (int skipWord = 0; skipWord < words.Length - firstWord; skipWord++) { string[] cutWords = words.Skip(firstWord) //preskoc slovo na zacatku .Reverse().Skip(skipWord).Reverse() // a ubirej od konce .ToArray(); string wordCombination = cutWords.Aggregate((f, s) => f + " " + s); string koncovka; string firmaBezKoncovky = Lib.Data.Firma.JmenoBezKoncovkyFull(wordCombination, out koncovka); string simpleName = Devmasters.TextUtil.RemoveDiacritics(firmaBezKoncovky).ToLower().Trim(); //+ "|" + koncovka; if (firmaBezKoncovky.Length > 3 && StaticData.FirmyNazvyOnlyAscii.Get().ContainsKey(simpleName) ) { //nasel jsem ico? foreach (var ico in StaticData.FirmyNazvyOnlyAscii.Get()[simpleName]) { Firma f = Firmy.Get(ico); //TODO StaticData.FirmyNazvyAscii.Get()[simpleName]); if (f.Valid) { var firmaFromText = TextUtil.ReplaceDuplicates(System.Text.RegularExpressions.Regex.Replace(wordCombination, @"[,;_""']", " ", defaultRegexOptions), ' '); var firmaFromDB = TextUtil.ReplaceDuplicates(System.Text.RegularExpressions.Regex.Replace(f.Jmeno, @"[,;_""']", " ", defaultRegexOptions), ' '); var rozdil = LevenshteinDistanceCompute( TextUtil.RemoveDiacritics(firmaFromDB).ToLower(), firmaFromText.ToLower() ); var fKoncovka = f.KoncovkaFirmy(); var nextWord = ""; if (firstWord + cutWords.Length < words.Length - 1) { nextWord = words[firstWord + cutWords.Length]; } if (string.IsNullOrEmpty(fKoncovka)) { return(f); } if (!string.IsNullOrEmpty(fKoncovka) && LevenshteinDistanceCompute(cutWords.Last(), fKoncovka) < 2) { return(f); } if (!string.IsNullOrEmpty(fKoncovka) && LevenshteinDistanceCompute(nextWord, fKoncovka) < 2) { return(f); } } } //looking for next //return null; } } } return(null); }
private void populateListViewFromDirectory(MsDataFileUri directory) { _abortPopulateList = false; listView.Cursor = Cursors.Default; _waitingForData = false; listView.Items.Clear(); var listSourceInfo = new List <SourceInfo>(); if (null == directory || directory is MsDataFilePath && string.IsNullOrEmpty(((MsDataFilePath)directory).FilePath)) { foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) { string label = string.Empty; string sublabel = driveInfo.Name; ImageIndex imageIndex = ImageIndex.Folder; _driveReadiness[sublabel] = false; try { switch (driveInfo.DriveType) { case DriveType.Fixed: imageIndex = ImageIndex.LocalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive; if (driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.CDRom: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Removable: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Network: label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Network_Share; break; } _driveReadiness[sublabel] = IsDriveReady(driveInfo); } catch (Exception) { label += string.Format(@" ({0})", Resources.OpenDataSourceDialog_populateListViewFromDirectory_access_failure); } string name = driveInfo.Name; if (label != string.Empty) { name = string.Format(@"{0} ({1})", label, name); } listSourceInfo.Add(new SourceInfo(new MsDataFilePath(driveInfo.RootDirectory.FullName)) { type = DataSourceUtil.FOLDER_TYPE, imageIndex = imageIndex, name = name, dateModified = GetDriveModifiedTime(driveInfo) }); } } else if (directory is RemoteUrl) { RemoteUrl remoteUrl = directory as RemoteUrl; if (string.IsNullOrEmpty(remoteUrl.ServerUrl)) { foreach (var remoteAccount in _remoteAccounts) { listSourceInfo.Add(new SourceInfo(remoteAccount.GetRootUrl()) { name = remoteAccount.GetKey(), type = DataSourceUtil.FOLDER_TYPE, imageIndex = ImageIndex.MyNetworkPlaces, }); } } else { RemoteAccount remoteAccount = GetRemoteAccount(remoteUrl); if (RemoteSession == null || !Equals(remoteAccount, RemoteSession.Account)) { RemoteSession = RemoteSession.CreateSession(remoteAccount); } RemoteServerException exception; bool isComplete = _remoteSession.AsyncFetchContents(remoteUrl, out exception); foreach (var item in _remoteSession.ListContents(remoteUrl)) { var imageIndex = DataSourceUtil.IsFolderType(item.Type) ? ImageIndex.Folder : ImageIndex.MassSpecFile; listSourceInfo.Add(new SourceInfo(item.MsDataFileUri) { name = item.Label, type = item.Type, imageIndex = imageIndex, dateModified = item.LastModified, size = item.FileSize }); } if (null != exception) { if (MultiButtonMsgDlg.Show(this, exception.Message, Resources.OpenDataSourceDialog_populateListViewFromDirectory_Retry) != DialogResult.Cancel) { RemoteSession.RetryFetchContents(remoteUrl); isComplete = false; } } if (!isComplete) { listView.Cursor = Cursors.WaitCursor; _waitingForData = true; } } } else if (directory is MsDataFilePath) { MsDataFilePath msDataFilePath = (MsDataFilePath)directory; DirectoryInfo dirInfo = new DirectoryInfo(msDataFilePath.FilePath); try { // subitems: Name, Type, Spectra, Size, Date Modified var arraySubDirInfo = dirInfo.GetDirectories(); Array.Sort(arraySubDirInfo, (d1, d2) => string.Compare(d1.Name, d2.Name, StringComparison.CurrentCultureIgnoreCase)); var arrayFileInfo = dirInfo.GetFiles(); Array.Sort(arrayFileInfo, (f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.CurrentCultureIgnoreCase)); // Calculate information about the files, allowing the user to cancel foreach (var info in arraySubDirInfo) { listSourceInfo.Add(getSourceInfo(info)); Application.DoEvents(); if (_abortPopulateList) { //MessageBox.Show( "abort" ); break; } } if (!_abortPopulateList) { foreach (var info in arrayFileInfo) { listSourceInfo.Add(getSourceInfo(info)); Application.DoEvents(); if (_abortPopulateList) { //MessageBox.Show( "abort" ); break; } } } } catch (Exception x) { var message = TextUtil.LineSeparate( Resources.OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_to_retrieve_the_contents_of_this_directory, x.Message); // Might throw access violation. MessageDlg.ShowWithException(this, message, x); return; } } // Populate the list var items = new List <ListViewItem>(); foreach (var sourceInfo in listSourceInfo) { if (sourceInfo != null && (sourceTypeComboBox.SelectedIndex == 0 || sourceTypeComboBox.SelectedItem.ToString() == sourceInfo.type || // Always show folders sourceInfo.isFolder)) { ListViewItem item = new ListViewItem(sourceInfo.ToArray(), (int)sourceInfo.imageIndex) { Tag = sourceInfo, }; item.SubItems[2].Tag = sourceInfo.size; item.SubItems[3].Tag = sourceInfo.dateModified; items.Add(item); } } listView.Items.AddRange(items.ToArray()); }