Exemple #1
0
        private void TestSigmaBounding(double[] srcData, int[] expecteds, double[] loBounds, double[] hiBounds)
        {
            List <Thingy> thingies = new List <Thingy>();

            foreach (double d in srcData)
            {
                thingies.Add(new Thingy(d));
            }

            Console.WriteLine("Created a list of Thingies, {0}.", StringOperations.ToCommasAndAndedList(thingies.ConvertAll <string>(n => n.ToString())));

            double average = thingies.Average <Thingy>(n => n.DoubleValue);
            double stDev   = thingies.StandardDeviation <Thingy>(n => n.DoubleValue);

            Console.WriteLine("Mean = {0}\r\nStDev = {1}", average, stDev);

            for (int i = 0; i < expecteds.Length; i++)
            {
                object state = null;
                IEnumerable <Thingy> boundedThingies = thingies.BoundBySigmas <Thingy>(n => n.DoubleValue, loBounds[i], hiBounds[i], ref state);
                IEnumerable <Thingy> enumerable      = boundedThingies as Thingy[] ?? boundedThingies.ToArray();
                int numBoundedThingies = enumerable.Count();
                Assert.AreEqual(expecteds[i], numBoundedThingies, string.Format("ERROR: Thingy list bounded -{0} to +{1} should have yielded {2} elements, and yielded {3} instead.", loBounds[i], hiBounds[i], expecteds[i], numBoundedThingies));
            }
        }
Exemple #2
0
 public override string ToString()
 {
     return(StringOperations.Values(Form) + "|" +
            StringOperations.Values(Block) + "|" +
            StringOperations.Values(Order) + "|" +
            StringOperations.Values(Enable));
 }
Exemple #3
0
        static void Main(string[] args)
        {
            //Task1
            int[] intArray1 = { 1, 2, 3, 4, 3, 2, 1 };
            int[] intArray2 = { 1, 100, 50, -51, 1, 1 };
            int[] intArray3 = { 1, 2, 3, 4, 5, 6 };
            int[] intArray4 = { 0, 0, 0, 0, 0 };

            Console.WriteLine(ArrayOperations.FindTheCentral(intArray1));
            Console.WriteLine(ArrayOperations.FindTheCentral(intArray2));
            Console.WriteLine(ArrayOperations.FindTheCentral(intArray3));
            Console.WriteLine(ArrayOperations.FindTheCentral(intArray4));
            Console.WriteLine();

            //Task2
            string firstString  = "xyaabBdcccdefww";
            string secondString = "xxxxyyyyabklmopq";
            string thirdString  = "abcdefghijklmnopqrstuvwxyz";

            string firstPlusSecond = StringOperations.Longest(firstString, secondString);

            thirdString = StringOperations.Longest(thirdString, thirdString);

            Console.WriteLine(firstPlusSecond);
            Console.WriteLine(thirdString);
            Console.WriteLine();

            //Task3
            int result = BitOperations.Insertion(8, 15, 0, 0);

            Console.WriteLine(result);
            result = BitOperations.Insertion(0, 15, 30, 30);
            Console.WriteLine(result);
            result = BitOperations.Insertion(0, 15, 0, 30);
            Console.WriteLine(result);
            result = BitOperations.Insertion(15, -15, 0, 4);
            Console.WriteLine(result);
            result = BitOperations.Insertion(15, int.MaxValue, 3, 5);
            Console.WriteLine(result);

            /*[TestCase(int.MaxValue, int.MaxValue, 3, 5, ExpectedResult = int.MaxValue)]
             * [TestCase(15, int.MaxValue, 3, 5, ExpectedResult = 63)]
             * [TestCase(15, 15, 1, 3, ExpectedResult = 15)]
             * [TestCase(15, 15, 1, 4, ExpectedResult = 31)]
             * [TestCase(15, -15, 0, 4, ExpectedResult = 31)]
             * [TestCase(15, -15, 1, 4, ExpectedResult = 15)]
             * [TestCase(-8, -15, 1, 4, ExpectedResult = -6)]*/


            Console.WriteLine(BitOperations.Insertion(int.MaxValue, int.MaxValue, 3, 5));
            Console.WriteLine(BitOperations.Insertion(15, int.MaxValue, 3, 5));
            Console.WriteLine(BitOperations.Insertion(15, 15, 1, 3));
            Console.WriteLine(BitOperations.Insertion(15, 15, 1, 4));
            Console.WriteLine(BitOperations.Insertion(15, -15, 0, 4));
            Console.WriteLine(BitOperations.Insertion(15, -15, 1, 4));
            Console.WriteLine(BitOperations.Insertion(-8, -15, 1, 4));


            Console.ReadLine();
        }
Exemple #4
0
        public static void RemoveLibrary(Library libraryToRemove)
        {
            if (UtilityBox.IsSteamRunning())
            {
                ErrorHandler.Instance.ShowNotificationMessage("Turn Off Steam removing steam library.");
                return;
            }
            RealSizeOnDiskTask.Instance.Cancel();
            LibraryDetector.Refresh();
            Library refreshedLibraryToRemove = null;

            foreach (Library library in BindingDataContext.Instance.LibraryList)
            {
                if (libraryToRemove.LibraryDirectory.Equals(library.LibraryDirectory, StringComparison.CurrentCultureIgnoreCase))
                {
                    refreshedLibraryToRemove = library;
                }
            }
            if (refreshedLibraryToRemove == null)
            {
                ErrorHandler.Instance.ShowErrorMessage("Library you are trying to remove is already removed.");
                return;
            }
            string newLibraryDirectory = refreshedLibraryToRemove.LibraryDirectory + "_removed";

            newLibraryDirectory = StringOperations.RenamePathWhenExists(newLibraryDirectory, "_removed");
            FileSystem.RenameDirectory(refreshedLibraryToRemove.LibraryDirectory, Path.GetFileName(newLibraryDirectory));
            BindingDataContext.Instance.LibraryList.Remove(refreshedLibraryToRemove);
            RealSizeOnDiskTask.Instance.Start();
            SteamConfigFileWriter.WriteLibraryList();
            ErrorHandler.Instance.ShowNotificationMessage("Library will still exist on harddrive. It is only removed from the list.");
            Process.Start(refreshedLibraryToRemove.LibraryDirectory + "_removed");
        }
Exemple #5
0
 private void Activity_GainedChild(ITreeNode <Activity> self, ITreeNode <Activity> subject)
 {
     if (m_ncaMode.Equals(NewChildAccomodationMode.AdjustParentToChildren))
     {
         // for each Aspect, my start occurs at-or-before subject's start,
         //              and my finish occurs at-or-after subject's finish.
         List <object> missingAspectKeys = null;
         foreach (object aspectKey in m_timePeriods.Keys)
         {
             if (subject.Payload.GetTimePeriodAspect(aspectKey) == null)
             {
                 missingAspectKeys = new List <object> {
                     aspectKey
                 };
             }
             else
             {
                 m_timePeriods[aspectKey].AddRelationship(TimePeriod.Relationship.StartsBeforeStartOf, subject.Payload.GetTimePeriodAspect(aspectKey));
                 m_timePeriods[aspectKey].AddRelationship(TimePeriod.Relationship.EndsAfterEndOf, subject.Payload.GetTimePeriodAspect(aspectKey));
             }
             if (missingAspectKeys != null)
             {
                 string msg = string.Format("Adding a child activity without time periods with matching aspects to a parent that is set to adjust " +
                                            "itself to its children is illegal. You are adding a child without a time period corresponding to the parent's {0} aspect{1}.",
                                            StringOperations.ToCommasAndAndedList(missingAspectKeys, n => n.ToString()),
                                            (missingAspectKeys.Count > 1?"s":""));
                 throw new ApplicationException(msg);
             }
         }
     }
 }
        public ActionResult Index(string urls, string words)
        {
            if (urls == "" || words == "")
            {
                return(HttpNotFound());
            }
            AnahtarKelimeSaydirModel model = new AnahtarKelimeSaydirModel();

            model.urls  = StringOperations.GetListBySplit(urls, ',');
            model.words = StringOperations.GetListBySplit(words, ',');
            foreach (var url in model.urls)
            {
                string html = SiteSource.GetHtml(url);
                html = HtmlPack.GetHtmlExludePopup(html);
                string cleanHtml = SiteSource.GetCleanHtml(html).ToLower();
                foreach (var word in model.words)
                {
                    List <string> compatibleWords = new List <string>();
                    compatibleWords = StringOperations.GetLanguageLowerCompatible(word);
                    compatibleWords = StringOperations.GetDifferentWords(compatibleWords);
                    Keyword keyword = new Keyword();
                    keyword.Word  = word;
                    keyword.Url   = url;
                    keyword.Count = 0;
                    foreach (string compatibleWord in compatibleWords)
                    {
                        keyword.Count += StringOperations.GetCountWordInSentence(cleanHtml, compatibleWord);
                    }
                    model.keywords.Add(keyword);
                }
            }
            return(View(model));
        }
 public void Test_Counter_Should_return_Zero_String_has_NO_Consonants()
 {
     //Given, When
     (int, int)count = StringOperations.VocalsAndConsonants("AeEiou");
     //Then
     Assert.Equal((6, 0), count);
 }
Exemple #8
0
        async private void AddPetAction()
        {
            var serverConnect = new ServerConnect();
            var petObject     = new Pet
            {
                PetID    = StringOperations.GenerateID(),
                UserID   = MainApp.Session.UserID,
                PetName  = Pet_Name,
                PetBreed = Pet_Breed,
                PetDesc  = Pet_Desc
            };

            IsBusy = true;
            ServerResponseObject response = await serverConnect.ConnectApi(petObject, Keys.Aws_Resource_SavePet);

            IsBusy = false;

            if (response.status == ServerReplyStatus.Success)
            {
                await MainApp.MainPage.DisplayAlert("Attention!", "Pet data saved successfully!", "Ok");
            }
            else if (response.status == ServerReplyStatus.Fail)
            {
                await MainApp.MainPage.DisplayAlert("Attention!", "Error saving pet data!", "Ok");
            }
            else if (response.status == ServerReplyStatus.Unknown)
            {
                await MainApp.MainPage.DisplayAlert("Attention!", $"Error saving pet data!:{response.error}", "Ok");
            }
        }
 public void Test_Counter_Should_correctly_count_vocals_WORD_has_Only_Vocals()
 {
     //Given, When
     (int, int)count = StringOperations.VocalsAndConsonants("aei");
     //Then
     Assert.Equal((3, 0), count);
 }
 public void Test_Counter_Should_count_vocals_WORD_has_Vocals_AND_Consonants()
 {
     //Given, When
     (int, int)count = StringOperations.VocalsAndConsonants("abe");
     //Then
     Assert.Equal((2, 1), count);
 }
 public void Test_Counter_should_correctly_count_VOCALS_word_has_ONE_char()
 {
     //Given, When
     (int, int)count = StringOperations.VocalsAndConsonants("a");
     //Then
     Assert.Equal((1, 0), count);
 }
 public void Test_Counter_Should_Correctly_Count_Vocals_for_Upper_Case()
 {
     //Given, When
     (int, int)count = StringOperations.VocalsAndConsonants("AandDrEei");
     //Then
     Assert.Equal((5, 4), count);
 }
Exemple #13
0
            public static void Run()
            {
                IModel m = new Highpoint.Sage.SimCore.Model("Demo Model");

                Highpoint.Sage.SimCore.StateMachine sm = m.StateMachine;
                sm.TransitionCompletedSuccessfully +=
                    (model, data) =>
                    Console.WriteLine("Model transitioned successfully to the {0} state.", m.StateMachine.State);

                string[] stateNames = Enum.GetNames(sm.State.GetType());
                Console.WriteLine("State machine's default states are {0}",
                                  StringOperations.ToCommasAndAndedList(stateNames));

                DateTime startDateTime = DateTime.Parse("Fri, 15 Jul 2016 00:00:00");

                Console.WriteLine("Registering an event to run in the model at {0}",
                                  StringOperations.ToCommasAndAndedList(stateNames));
                m.Executive.RequestEvent(
                    (exec, data) =>
                    Console.WriteLine("{0} : While running, Model state is {1}.", exec.Now, m.StateMachine.State),
                    startDateTime);

                Console.WriteLine("Before starting, model state is {0}.", m.StateMachine.State);
                m.Start();
                Console.WriteLine("After completion, model state is {0}.", m.StateMachine.State);
            }
Exemple #14
0
        public void giveBackCharASciiTest()
        {
            StringOperations strOp     = new StringOperations();
            char             character = 'a';

            Assert.AreEqual(97, strOp.giveBackCharAScii(character));
        }
Exemple #15
0
        private int getDateTimeBingNews(Document document)
        {
            string timeStr  = document.Get(Configure.TimeField);
            var    dateTime = StringOperations.ParseDateTimeString(timeStr, Configure.ParseTimeFormat);

            return(366 * dateTime.Year + dateTime.DayOfYear);
        }
Exemple #16
0
 public override string ToString()
 {
     return(StringOperations.Values(Id) + "|" +
            StringOperations.Values(Name) + "|" +
            StringOperations.Values(Enable) + "|" +
            StringOperations.Values(ExtId));
 }
Exemple #17
0
        public void Test_CountVocalsConsonants_WhenStringContainsDigits()
        {
            (int, int)count = StringOperations.CountVocalsConsonants("Four Words Seventeen Consonant 0123");

            Assert.Equal(17, count.Item2);
            Assert.Equal(10, count.Item1);
        }
Exemple #18
0
 public void GetHouseNumberAndSuffix(string address1, string address2, string address3, string expectedHouseNumber, string expectedSuffix)
 {
     string[] houseNumberAndSuffix = StringOperations.GetHouseNumberAndSuffix(address1, address2, address3);
     houseNumberAndSuffix[0].ShouldBe(string.Join(' ', address1, address2, address3).Trim());
     houseNumberAndSuffix[1].ShouldBe(expectedHouseNumber);
     houseNumberAndSuffix[2].ShouldBe(expectedSuffix);
 }
        private static int RunAndReturnErrorCode(ConcatenateStringOptions options)
        {
            var result = StringOperations.Concat(options.Text1, options.Text2);

            Console.WriteLine(result);
            return(0);
        }
Exemple #20
0
        public static void Main(string[] args)
        {
            var wc = new WebClient();

            Console.WriteLine("Initialized Pebble Language Downloader. By github/ardaozkal");
            Console.WriteLine("Rest in Peace, Pebble.");
            try
            {
                var LanguagesFile = wc.DownloadString("http://lp.getpebble.com/v1/languages");
                Console.WriteLine("Successfully downloaded language file. Attempting to write that in a file called \"languages.json\".");
                File.WriteAllText("languages.json", LanguagesFile);
                Console.WriteLine("Successfully wrote down language file. Starting download of language files.");
                var LanguagesList = StringOperations.FindAllBetween(LanguagesFile, "\"file\":\"", "\"", true);
                foreach (var language in LanguagesList)
                {
                    Console.WriteLine("Downloading: " + language);
                    var FileName = StringOperations.After(language, "/", true, true);
                    wc.DownloadFile(language, FileName);
                }
                Console.WriteLine("Successfully downloaded everything.");
            }
            catch
            {
                Console.WriteLine("Couldn't download language file. Rip pebble servers.");
            }
        }
        private static int RunAndReturnErrorCode(JoinStringsOptions options)
        {
            var result = StringOperations.Join(options.Strings);

            Console.WriteLine(result);
            return(0);
        }
        public override int Run(string[] remainingArguments)
        {
            var result = StringOperations.Concat(text1, text2);

            Console.WriteLine(result);
            return(0);
        }
        private static int RunAndReturnErrorCode(ReverseStringOptions options)
        {
            var result = StringOperations.Reverse(options.Text);

            Console.WriteLine(result);
            return(0);
        }
Exemple #24
0
            private ExportDictionaries GetExportDictionaries(Image image)
            {
                Dictionary <string, HarmonyExport> exportsByName    = new Dictionary <string, HarmonyExport>();
                Dictionary <ushort, HarmonyExport> exportsByOrdinal = new Dictionary <ushort, HarmonyExport>();

                IMAGE_DATA_DIRECTORY directory = Environment.Is64BitProcess
                                        ? image.OptionalHeader64->ExportTable : image.OptionalHeader32->ExportTable;

                if (directory.VirtualAddress == 0)
                {
                    return(new ExportDictionaries(exportsByName, exportsByOrdinal));
                }

                IMAGE_EXPORT_DIRECTORY *exportDirectory = (IMAGE_EXPORT_DIRECTORY *)(image.BasePtr + directory.VirtualAddress);
                UIntPtr nameRef     = (UIntPtr)(image.BasePtr + exportDirectory->AddressOfNames);
                UIntPtr ordinalRef  = (UIntPtr)(image.BasePtr + exportDirectory->AddressOfNameOrdinals);
                ushort  ordinalBase = (ushort)exportDirectory->Base;

                for (int i = 0; i < exportDirectory->NumberOfNames; i++, nameRef += sizeof(UInt32), ordinalRef += sizeof(UInt16))
                {
                    byte * namePtr = image.BasePtr + (int)*(UInt32 *)nameRef;
                    string name    = StringOperations.NulTerminatedBytesToString(namePtr, image.BasePtr, image.Size);
                    ushort ordinal = *(UInt16 *)ordinalRef;

                    IntPtr exportAddress = (IntPtr)(image.BasePtr + (int)*(UInt32 *)(image.BasePtr + exportDirectory->AddressOfFunctions + ordinal * sizeof(UInt32)));

                    ushort        displayOrdinal = (ushort)(ordinal + ordinalBase);
                    HarmonyExport export         = new HarmonyExport(name, displayOrdinal, exportAddress);
                    exportsByName[name] = export;
                    exportsByOrdinal[displayOrdinal] = export;
                }

                return(new ExportDictionaries(exportsByName, exportsByOrdinal));
            }
Exemple #25
0
        public void OperationConcat3With2()
        {
            string expected  = "Hello World";
            string generated = StringOperations.Concat3With("Hello", " ")("World");

            Assert.AreEqual(expected, generated);
        }
 private void InitializeWriters()
 {
     if (Configure.IsSplitByTime)
     {
         _dateTransferFunc = str =>
         {
             var dateTime = StringOperations.ParseDateTimeString(str, _dateFormatString);
             if (Configure.SplitDayCount == 7)
             {
                 dateTime = dateTime.Subtract(TimeSpan.FromDays((int)dateTime.DayOfWeek));
             }
             else
             {
                 var days        = dateTime.Subtract(_minDateTime).TotalDays;
                 var residueDays = days % Configure.SplitDayCount;
                 dateTime = dateTime.Subtract(TimeSpan.FromDays(residueDays));
             }
             return(dateTime.ToString("yyyy-MM-dd"));
         };
     }
     else
     {
         IndexWriter writer = LuceneOperations.GetIndexWriter(Configure.OutputPath);
         _writers.Add("", writer);
     }
 }
Exemple #27
0
        /// <summary>
        /// Gets the primary path forward from the provided starting point node. The primary path is
        /// the path that is comprised of all of the highest-priority links out of each node encountered.
        /// </summary>
        /// <param name="startPoint">The starting point.</param>
        /// <param name="stepsOnly">if set to <c>true</c> it returns steps only. Otherwise, it returns all nodes.</param>
        /// <returns>The primary path.</returns>
        public static List <IPfcNode> GetPrimaryPath(IPfcNode startPoint, bool stepsOnly)
        {
            List <IPfcNode> retval = new List <IPfcNode>();
            IPfcNode        cursor = startPoint;

            while (true)
            {
                if (retval.Contains(cursor))
                {
                    int       firstElementInLoop = retval.IndexOf(cursor);
                    ArrayList loopers            = new ArrayList();
                    for (int i = firstElementInLoop; i < retval.Count; i++)
                    {
                        loopers.Add(retval[i]);
                    }
                    string looperString = StringOperations.ToCommasAndAndedList(loopers);
                    throw new ApplicationException("Primary path contains a loop, which consists of " + looperString + "!");
                }

                if (!stepsOnly || (cursor.ElementType.Equals(PfcElementType.Step)))
                {
                    retval.Add(cursor);
                }

                if (cursor.Successors.Count == 0)
                {
                    break;
                }
                cursor = cursor.SuccessorNodes[0];
            }
            return(retval);
        }
Exemple #28
0
        /// <summary>
        /// Returns a new Land according to bound value
        /// </summary>
        public virtual LandBase GetLand()
        {
            var boundArray = StringOperations.GetSplittedArray <int>(BoundString);
            var bound      = new Bound(boundArray.ElementAt(0), boundArray.ElementAt(1));

            return(new Land(bound));
        }
Exemple #29
0
        /// <summary>
        /// Gets the primary path forward from the provided starting point node. The primary path is
        /// the path that is comprised on all of the highest-priority links out of each node encountered.
        /// This path consists of
        /// </summary>
        /// <param name="startPoint">The starting point.</param>
        /// <param name="stepsOnly">if set to <c>true</c> it returns steps only. Otherwise, it returns all nodes.</param>
        /// <returns>The primary path as a string.</returns>
        public static string GetPrimaryPathAsString(IPfcNode startPoint, bool stepsOnly)
        {
            List <IPfcNode> primaryPathList = GetPrimaryPath(startPoint, stepsOnly);
            string          primaryPath     = StringOperations.ToCommasAndAndedListOfNames <IPfcNode>(primaryPathList);

            return(primaryPath);
        }
        public static void AnalyzeFieldValues(string inputPath, string fieldName, Func <string, string> convertValueFunc = null)
        {
            if (convertValueFunc == null)
            {
                convertValueFunc = str => str;
            }

            string       fileName = StringOperations.EnsureFolderEnd(inputPath) + fieldName + ".txt";
            StreamWriter sw       = new StreamWriter(fileName);

            Counter <string> counter = new Counter <string>();
            var indexReader          = LuceneOperations.GetIndexReader(inputPath);

            for (int iDoc = 0; iDoc < indexReader.NumDocs(); iDoc++)
            {
                var doc   = indexReader.Document(iDoc);
                var value = doc.Get(fieldName);
                counter.Add(convertValueFunc(value));
            }
            foreach (var kvp in counter.GetCountDictionary().OrderBy(kvp => kvp.Key))
            {
                sw.WriteLine(kvp.Key + "\t\t" + kvp.Value);
                Console.WriteLine(kvp.Key + "\t\t" + kvp.Value);
            }

            sw.WriteLine("total: " + indexReader.NumDocs());
            sw.Flush();
            sw.Close();

            indexReader.Close();
            Console.ReadKey();
        }
 public StringOperationsFixture()
 {
     _sut = new StringOperations();
 }