private void txtValues_TextChanged(Object eventSender, EventArgs eventArgs) { int Index = Array.IndexOf(this.txtValues, eventSender); if (!codeGeneratedChange) { editingData = true; codeGeneratedChange = true; //UPGRADE_WARNING: (2080) IsEmpty was upgraded to a comparison and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080 if (!String.IsNullOrEmpty(txtValues[0].Text)) { changedStockPrice = Double.Parse(txtValues[0].Text); } //UPGRADE_WARNING: (2080) IsEmpty was upgraded to a comparison and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080 if (!String.IsNullOrEmpty(txtValues[1].Text)) { changedStock = Double.Parse(txtValues[1].Text); } switch (Index) { case 1: if (changedStock > currentStock) { changedStock = currentStock; modMain.LogStatus("Cannot pass the original stock, to add more, add a new stock manually", this); txtValues[1].Text = changedStock.ToString(); } break; } lblNewQuantity.Text = StringsHelper.Format(changedStock * Double.Parse(currentQuantityPerUnit), "##,###.00") + currentUnit; lblCurrentQuantity.Text = StringsHelper.Format(currentStock * Double.Parse(currentQuantityPerUnit), "##,###.00") + currentUnit; codeGeneratedChange = false; } }
public WordForms_t GetWordFormsByPartOfSpeech(string word, PartOfSpeechEnum partOfSpeechFilter) { var result = new WordForms_t(word); var wordUpper = StringsHelper.ToUpperInvariant(word); if (_MorphoModel.TryGetWordForms(wordUpper, _WordForms)) { FillUniqueWordFormsDictionary(partOfSpeechFilter); #region [.fill word-forms list.] _WordForms.Clear(); foreach (var p in _UniqueWordFormsDictionary) { var form = p.Key; var partOfSpeech = p.Value; var wf = new WordForm_t(form, partOfSpeech); _WordForms.Add(wf); } result.Forms = _WordForms; #endregion } return(result); }
private static MModelRecord ToModelRecord(this KeyValuePair <IntPtr, BucketValue> pair) { return(new MModelRecord() { Ngram = StringsHelper.ToString(pair.Key), WeighByLanguages = new WeighByLanguageEnumerator(pair.Value) }); }
public AddPageViewModel() { _dialoghelper = new DialogHelper(); _stringshelper = new StringsHelper(); _fbservice = new FbService(); _modelhelper = new ModelHelper(); Page = "facebook.com/"; }
private void ReCalculateTotals(double previous, double current) { currentSubTotal = currentSubTotal - previous + current; currentTotalTax = currentSubTotal * currentTax * 0.01d; currentTotal = currentFreightCharge + currentSubTotal + currentTotalTax; txtSubTotal.Text = StringsHelper.Format(currentSubTotal, "#,##0.00"); txtTotalTax.Text = StringsHelper.Format(currentTotalTax, "#,##0.00"); txtTotal.Text = StringsHelper.Format(currentTotal, "#,##0.00"); }
unsafe public bool GetWordFormMorphologies(char *wordUpper, List <WordFormMorphology> result, WordFormMorphologyModeEnum wordFormMorphologyMode) { result.Clear(); { var fullWordLength = StringsHelper.GetLength(wordUpper); FillWordFormMorphologies(wordUpper, fullWordLength, fullWordLength, result, wordFormMorphologyMode); } return(result.Count != 0); }
private void AddToTotals(double current) { currentSubTotal += current; currentTotalTax = currentSubTotal * currentTax; currentTotal = currentFreightCharge + currentSubTotal + currentTotalTax; txtSubTotal.Text = StringsHelper.Format(currentSubTotal, "#,##0.00"); txtTotalTax.Text = StringsHelper.Format(currentTotalTax, "#,##0.00"); txtTotal.Text = StringsHelper.Format(currentTotal, "#,##0.00"); }
internal static InvalidUdtException Create(Type udtType, string resourceReason) { string reason = StringsHelper.GetString(resourceReason); string message = StringsHelper.GetString(Strings.SqlUdt_InvalidUdtMessage, udtType.FullName, reason); InvalidUdtException e = new InvalidUdtException(message); ADP.TraceExceptionAsReturnValue(e); return(e); }
public static ModelRecord ToModelRecord(IntPtr baseIntPtr) { var s = StringsHelper.ToString(baseIntPtr); return(new ModelRecord() { Ngram = s, Probability = ToProbability(baseIntPtr, s.Length + 1) }); }
private static void ToModelRecord(IntPtr baseIntPtr, out ModelRecord m) { var s = StringsHelper.ToString(baseIntPtr); m = new ModelRecord() { Ngram = s, Probability = ToProbability(baseIntPtr, s.Length + 1) }; }
private double GetWordProbability(string word) { if ((word.Length == 1) && !StringsHelper.IsLettersOrDash(word[0])) { return(1); } return(_Model.TryGetProbability(word, out var prob) ? prob : 0); }
unsafe private double GetWordProbability(ref NativeOffset no) { if ((no.Length == 1) && !StringsHelper.IsLettersOrDash(no.BasePtr[no.StartIndex])) { return(1); } return(_Model.TryGetProbability(ref no, out var prob) ? prob : 0); }
private static string GetGssApiDisplayStatus(Status majorStatus, Status minorStatus) { string majorError = GetGssApiDisplayStatus(majorStatus, isMinor: false); string minorError = GetGssApiDisplayStatus(minorStatus, isMinor: true); return((majorError != null && minorError != null) ? StringsHelper.Format(Strings.net_gssapi_operation_failed_detailed, majorError, minorError) : StringsHelper.Format(Strings.net_gssapi_operation_failed, majorStatus.ToString("x"), minorStatus.ToString("x"))); }
private async Task RestoreDefaults() { var result = await _dialogService.ShowMessageDialogAsnyc(StringsHelper.GetString("PleaseConfirm"), StringsHelper.GetString("ConfirmRestoreKeybindings"), DialogButton.OK, DialogButton.Cancel).ConfigureAwait(true); if (result == DialogButton.OK) { _settingsService.ResetKeyBindings(); Initialize(_settingsService.GetCommandKeyBindings()); } }
private static string ToString(SortedListIntPtrKey <Pair[]> .Tuple[] array) { var sb = new System.Text.StringBuilder(); foreach (var a in array) { sb.Append(StringsHelper.ToString(a.Key)).Append(Environment.NewLine); } return(sb.ToString()); }
public static IList <string> GetOutlines(this CatalogIndexedSearchCriteria criteria) { var result = criteria .GetRawOutlines() .Select(outline => StringsHelper.JoinNonEmptyStrings("/", criteria.CatalogId, outline).ToLowerInvariant()) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); return(result); }
unsafe private static void LoadFromBinFile(string modelFilename, Dictionary <IntPtr, IntPtr> dict) { const int BUFFER_SIZE = 0x2000; using (var fs = new FileStream(modelFilename, FileMode.Open, FileAccess.Read, FileShare.Read, BUFFER_SIZE, FileOptions.SequentialScan)) using (var mmf = MemoryMappedFile.CreateFromFile(fs, null, 0L, MemoryMappedFileAccess.Read, new MemoryMappedFileSecurity(), HandleInheritability.None, true)) using (var accessor = mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read)) { byte *buffer = null; accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref buffer); IntPtr textPtr; for (byte *endBuffer = buffer + fs.Length; buffer < endBuffer;) { #region [.read 'textPtr' as C#-chars (with double-byte-zero '\0').] var bufferCharPtr = (char *)buffer; for (var idx = 0; ; idx++) { if (BUFFER_SIZE < idx) { throw (new InvalidDataException("WTF?!?!: [BUFFER_SIZE < idx]")); } if (bufferCharPtr[idx] == '\0') { textPtr = StringsHelper.AllocHGlobalAndCopy(bufferCharPtr, idx); buffer = (byte *)(bufferCharPtr + idx + 1); break; } } #endregion #region [.read buckets.] var countBuckets = *buffer++; var pairsPtr = Marshal.AllocHGlobal(sizeof(byte) + countBuckets * sizeof(WeighByLanguage)); var pairsBytePtr = (byte *)pairsPtr; * pairsBytePtr++ = countBuckets; var pairsLanguageWeightPtr = (WeighByLanguage *)pairsBytePtr; for (var i = 0; i < countBuckets; i++) { var ptr = &pairsLanguageWeightPtr[i]; ptr->Language = (Language)(*buffer++); ptr->Weight = *((float *)buffer); //pairsLanguageWeightPtr[ i ] = new WeighByLanguage() // { // Language = (Language) (*buffer++), // Weight = *((float*) buffer), // }; buffer += sizeof(float); } #endregion dict.Add(textPtr, pairsPtr); } } }
static private string GetFullPathInternal(string path) { //----------------------------------------------------------------- // precondition validation // should be validated by callers of this method // NOTE: if this method moves elsewhere, this assert should become an actual runtime check // as the implicit assumptions here cannot be relied upon in an inter-class context Debug.Assert(path != null); // remove leading and trailing whitespace path = path.Trim(); if (path.Length == 0) { throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path"); } // check for the path length before we normalize it with GetFullPathName if (path.Length > MaxWin32PathLength) { // cannot use PathTooLongException here since our length limit is 32K while // PathTooLongException error message states that the path should be limited to 260 throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path"); } // GetFullPathName does not check for invalid characters so we still have to validate them before if (path.IndexOfAny(InvalidPathChars) >= 0) { throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path"); } // make sure path is a UNC path if (!path.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) { throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path"); } //----------------------------------------------------------------- // normalize the path path = UnsafeNativeMethods.SafeGetFullPathName(path); // we do not expect windows API to return invalid paths Debug.Assert(path.Length <= MaxWin32PathLength, "GetFullPathName returns path longer than max expected!"); // CONSIDER: is this a precondition validation that can be done above? Or must the path be normalized first? // after normalization, we have to ensure that the path does not attempt to refer to a root device, etc. if (path.StartsWith(@"\\.\", StringComparison.Ordinal)) { throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_PathNotValidDiskResource), "path"); } return(path); }
/// <summary> /// сохранение морфотипа /// </summary> private void AddMorphoType2Dictionary(ref MorphoTypeNative_pair_t morphoTypePair) { if (_MorphoTypesDictionary.ContainsKey(morphoTypePair.Name)) { _ModelLoadingErrorCallback("Duplicated morpho-type", StringsHelper.ToString(morphoTypePair.Name)); //throw (new DuplicatedMorphoTypeException()); } else { _MorphoTypesDictionary.Add(morphoTypePair.Name, morphoTypePair.MorphoType); } }
/// <summary> /// Генерирует случайный пароль указанной длины. /// </summary> public static string PasswordGenerate(int length, string chars = null, int?seed = null) { const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@\"#№$;%^:?&*()-_=+{}[]'\\/|<>. "; if (chars == null) { chars = _chars; } return(StringsHelper.GenerateRandomString(chars, length, seed)); }
private void RetrieveDataProduct() { if (editingData) { if (Mobilize.Web.MessageBox.Show("Do you want to cancel previous edited data?", "Data edition", Mobilize.Web.MessageBoxButtons.YesNo, Mobilize.Web.MessageBoxIcon.Question) != Mobilize.Web.DialogResult.Yes) { return; } } bool setEmpty = true; Mobilize.Web.ListViewItem withVar = null; if (!(lvStocks.FocusedItem is null)) { // UPGRADE_WARNING: (2080) IsEmpty was upgraded to a comparison and has a new behavior. More Information: https://www.mobilize.net/vbtonet/ewis/ewi2080 if (!(lvStocks.FocusedItem is null)) { currentIdStock = Convert.ToInt32(double.Parse(lvStocks.FocusedItem.Text)); withVar = lvStocks.FocusedItem; currentStock = double.Parse(Mobilize.Web.ListView.GetListViewSubItem(withVar, 1).Text); currentStockPrice = double.Parse(Mobilize.Web.ListView.GetListViewSubItem(withVar, 4).Text); codeGeneratedChange = true; txtOriginalQuantity.Text = currentStock.ToString(); txtOriginalPrice.Text = currentStockPrice.ToString(); txtStockID.Text = currentIdStock.ToString(); txtValues[0].Text = currentStockPrice.ToString(); txtValues[1].Text = currentStock.ToString(); lblNewQuantity.Text = StringsHelper.Format(currentStock * double.Parse(currentQuantityPerUnit), "##,###.00") + currentUnit; lblCurrentQuantity.Text = StringsHelper.Format(currentStock * double.Parse(currentQuantityPerUnit), "##,###.00") + currentUnit; codeGeneratedChange = false; setEmpty = false; txtValues[0].ReadOnly = false; txtValues[1].ReadOnly = false; txtValues[0].Focus(); } } if (setEmpty) { codeGeneratedChange = true; txtOriginalQuantity.Text = ""; txtOriginalPrice.Text = ""; txtStockID.Text = ""; txtValues[0].Text = ""; txtValues[1].Text = ""; lblNewQuantity.Text = ""; lblCurrentQuantity.Text = ""; codeGeneratedChange = false; } editingData = false; }
unsafe private void FillWordForms_Core(char *wordPart, int wordPartLength, int fullWordLength, List <WordForm> result) { if (_BaseMorphoForms == null) { return; } foreach (var baseMorphoForm in _BaseMorphoForms) { int baseLength = baseMorphoForm.Base.Length; if ((fullWordLength < baseLength) || (baseLength + baseMorphoForm.MorphoType.MaxEndingLength < fullWordLength) ) { continue; } var morphoForms = baseMorphoForm.MorphoType.MorphoForms; foreach (var morphoForm in morphoForms) { var endingLength = morphoForm.EndingUpper.Length; if (baseLength + endingLength != fullWordLength) { continue; } if (endingLength != wordPartLength) { continue; } if (wordPartLength == 0) { ; } else if (!StringsHelper.IsEqual(morphoForm.EndingUpper, wordPart, wordPartLength)) { continue; } var partOfSpeech = baseMorphoForm.MorphoType.PartOfSpeech; foreach (var _morphoForm in morphoForms) { /// получение словоформы var wordForm = baseMorphoForm.Base + _morphoForm.Ending; var wf = new WordForm(wordForm, partOfSpeech); result.Add(wf); } break; } } }
public static IList <string> GetPriorityFields(this CatalogIndexedSearchCriteria criteria) { var allNames = criteria .GetRawOutlines() .Select(outline => StringsHelper.JoinNonEmptyStrings("_", "priority", criteria.CatalogId, outline.Split('/').LastOrDefault()).ToLowerInvariant()) .ToList(); allNames.Add("priority"); var result = allNames.Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); return(result); }
async Task GetAllMusicFolders() { try { StorageFolder musicLibrary = KnownFolders.MusicLibrary; LogHelper.Log("Searching for music from Phone MusicLibrary ..."); await CreateDatabaseFromMusicFolder(musicLibrary); } catch (Exception e) { LogHelper.Log(StringsHelper.ExceptionToString(e)); } }
internal MorphoForm(string ending, List <MorphoAttributePair> morphoAttributePair) { Ending = string.Intern(ending); EndingUpper = string.Intern(StringsHelper.ToUpperInvariant(Ending)); if (morphoAttributePair.Count != 0) { MorphoAttributePairs = morphoAttributePair.ToArray(); } else { MorphoAttributePairs = EMPTY; } }
public IEnumerable <MModelRecord> GetAllRecords() { //return (_Dictionary.GetAllModelRecords()); foreach (var p in _Dictionary) { yield return(new MModelRecord() { Ngram = StringsHelper.ToString(p.Key), WeighByLanguages = ToArrayOfWeighByLanguage(p.Value) }); //new WeighByLanguageEnumerator( p.Value ) }); // } }
internal static string SafeGetFullPathName(string path) { Debug.Assert(path != null, "path is null?"); // make sure to test for Int16.MaxValue limit before calling this method // see the below comment re GetLastWin32Error for the reason Debug.Assert(path.Length < Int16.MaxValue); // since we expect network paths, the 'full path' is expected to be the same size // as the provided one. we still need to allocate +1 for null termination StringBuilder buffer = new StringBuilder(path.Length + 1); int cchRequiredSize = GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero); // if our buffer was smaller than required, GetFullPathName will succeed and return us the required buffer size with null if (cchRequiredSize > buffer.Capacity) { // we have to reallocate and retry buffer.Capacity = cchRequiredSize; cchRequiredSize = GetFullPathName(path, buffer.Capacity, buffer, IntPtr.Zero); } if (cchRequiredSize == 0) { // GetFullPathName call failed int lastError = Marshal.GetLastWin32Error(); if (lastError == 0) { // we found that in some cases GetFullPathName fail but does not set the last error value // for example, it happens when the path provided to it is longer than 32K: return value is 0 (failure) // but GetLastError was zero too so we raised Win32Exception saying "The operation completed successfully". // To raise proper "path too long" failure, check the length before calling this API. // For other (yet unknown cases), we will throw InvalidPath message since we do not know what exactly happened throw ADP.Argument(StringsHelper.GetString(StringsHelper.SqlFileStream_InvalidPath), "path"); } else { System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(lastError); ADP.TraceExceptionAsReturnValue(e); throw e; } } // this should not happen since we already reallocate Debug.Assert(cchRequiredSize <= buffer.Capacity, string.Format( System.Globalization.CultureInfo.InvariantCulture, "second call to GetFullPathName returned greater size: {0} > {1}", cchRequiredSize, buffer.Capacity)); return(buffer.ToString()); }
private void cmdCompute_Click(Object eventSender, EventArgs eventArgs) { int Index = 0; if (StringsHelper.ToDoubleSafe(txtYear.Text) == 0) { txtYear.Text = "-1"; } if (StringsHelper.ToDoubleSafe(txtYear.Text) < -4600) { txtYear.Text = "-4600"; } if (StringsHelper.ToDoubleSafe(txtYear.Text) > 32000) { txtYear.Text = "32000"; } int YearNum = Convert.ToInt32(Double.Parse(txtYear.Text)); modBiblcalFunctions.GregorianYear = YearNum; txtOut.Text = ""; if (modBiblcalFunctions.GregorianYear < 0) { modBiblcalFunctions.GregorianYear++; } int HYear = Convert.ToInt32(modBiblcalFunctions.GregorianYear + 3760); //Print out the Sacred year sequence txtOut.Text = txtOut.Text + modHebrewCalendarFunctions.TypeYear[modHebrewCalendarFunctions.TypeOfYear(YearNum - 1)] + " for year " + HYear.ToString() + Environment.NewLine + Environment.NewLine + "Start of months for 'Sacred' Year" + Environment.NewLine; int NumOfMonths = modHebrewCalendarFunctions.NumberOfMonths(YearNum); //Get Number of Months in this year int tempForEndVar = NumOfMonths; for (Index = 1; Index <= tempForEndVar; Index++) { txtOut.Text = txtOut.Text + modHebrewCalendarFunctions.SHMonthName[Index] + " "; if (Index > 6) { HYear = Convert.ToInt32(modBiblcalFunctions.GregorianYear + 3761); } else { HYear = Convert.ToInt32(modBiblcalFunctions.GregorianYear + 3760); } txtOut.Text = txtOut.Text + HYear.ToString() + " - "; modBiblcalFunctions.JD = modHebrewCalendarFunctions.StartOfMonth(Index, YearNum); //Get JD for start of each month PrintDayAndDate2(modBiblcalFunctions.JD); //Print the Gregorian day and date of that JD txtOut.Text = txtOut.Text + Environment.NewLine; } txtOut.Text = txtOut.Text + Environment.NewLine; HolyDays(YearNum); //Print the calculated Holy Days }
/// создание морфоформы из строки private MorphoForm CreateMorphoForm(MorphoType morphoType, string line, List <MorphoAttributePair> morphoAttributePairs) { int index = line.IndexOf(':'); if (index < 0) { throw (new MorphoFormatException()); } var ending = StringsHelper.ToLowerInvariant(line.Substring(0, index).Trim()); if (ending == EMPTY_ENDING) { ending = string.Empty; } morphoAttributePairs.Clear(); var attributes = line.Substring(index + 1).Split(MORPHO_ATTRIBUTE_SEPARATOR, StringSplitOptions.RemoveEmptyEntries); foreach (var attribute in attributes) { var attr = attribute.Trim(); if (!string.IsNullOrEmpty(attr)) { var morphoAttribute = default(MorphoAttributeEnum); if (Enum.TryParse(attr, true, out morphoAttribute)) { //---morphoAttributePairs.Add( _MorphoAttributeList.GetMorphoAttributePair( morphoType.MorphoAttributeGroup, morphoAttribute ) ); var map = _MorphoAttributeList.TryGetMorphoAttributePair(morphoType.MorphoAttributeGroup, morphoAttribute); if (map.HasValue) { morphoAttributePairs.Add(map.Value); } #if DEBUG //TOO MANY ERRORS AFTER last (2016.12.28) getting morpho-dcitionaries from 'lingvo-[ilook]' else { _ModelLoadingErrorCallback("Error in morpho-attribute: '" + attr + '\'', line); } #endif } else { _ModelLoadingErrorCallback("Unknown morpho-attribute: '" + attr + '\'', line); } } } var morphoForm = new MorphoForm(ending, morphoAttributePairs); return(morphoForm); }
public IReadOnlyList <TermProbability> Run_Debug(string text) { if (text.IsNullOrWhiteSpace()) { return(TERMPROBABILITY_EMPTY); } //---------------------------------------------------------// var text_upper = StringsHelper.ToUpperInvariant(text); //---StringsHelper.ToUpperInvariantInPlace( text ); var tuples = _VTS.Run_Debug(text_upper); return(tuples); }