Code Compiles and Runs on Linux, Crashes with Heap Corruption on Windows

Question: I was testing out the Microsoft 'cl' compiler using PowerShell, and I figured I'd try compiling and running an old homework assignment for a custom MyString class.  The assignment in question has been previously compiled and run with g++ on Linux without any issues (and I assumed it should be correct since I got 100% for the assignment).  However, when I try to compile this code on Windows with cl, or even with MinGW, it compiles without error but crashes in run-time.
I've tried compiling all my other old assignments and they run just fine on Windows (with MinGW or cl).  I tried using the /Zi option for cl and ran the Visual Studio debugger, which told me that I am causing heap corruption errors.  I've tried re-writing parts of the code I thought could be the problem, but I simply cannot figure it out.
I suspect the issue might be in how I'm doing my operator overloading; if that isn't the issue I'll post the rest of the code.
MyString& MyString::operator+=(const char rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += 1;    //set new length (addition is single char)
    string = new char[length];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    string[length - 1] = rhs;   //concatenate return string with added char
    return *this;   //return this object as reference
}

MyString& MyString::operator+=(const char* rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += strlen(rhs);  //set new length (addition is c-string)
    string = new char[length];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    strcat(string, rhs);    //concatenate return string with added c-string
    return *this;   //return this object as reference
}

MyString& MyString::operator+=(const MyString& rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += rhs.length;   //set new length (addition is MyString)
    string = new char[length];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    strcat(string, rhs.string); //concatenate return string with added MyString
    return *this;   //return this object as reference
}

The other spot that Visual Studio kept stopping at was in part of my Professor's header file:
//casting operator: an operator to cast MyString to string type.
//This is going to be used in main() function, in order to grade your assignment.
    inline operator std::string() const
    {
        std::stringstream os;
        for(int i=0; i<length; i++)
            os << string[i];
        std::string str = os.str();
        return str;
    }

Runs fine on Linux, does not on Windows (even when successfully compiling via g++ on both).
EDIT2:
I appologize for not including all my source.  I was under the impression that I wasn't supposed to, based on a bit of text during the submission process that said something to that effect.
I've followed jww's advice and redone my code to account for the null-terminator on c-strings.  I'm still stuck with the same issue.
To compile for MinGW or g++ use the instructions in the comment header.
For compiling with cl use:
cl /TP /utf-8 /EHa /Fetestmystring mystring.cxx testmystring.cxx

or for VS debugging:
cl /TP /utf-8 /EHa /Zi /Fetestmystring mystring.cxx testmystring.cxx

Here is my 'mystring.cxx'
// Description: This is the function definition file for a custom
//  string class.
//
// To compile, use the following:
//
//   g++ -ansi -pedantic -Wall mystring.cxx testmystring.cxx -o testmystring
//
// To run, use the following:
//
//   ./testmystring
//
// Acknowledgements:
// 1. I used Dr. ####'s startup files.
// 2. I referred to https://en.cppreference.com/w/ to find some of the functions
//  that I ended up using.
//=====================================================================
#include <iostream>
#include <assert.h>
#include <string.h>
#include "mystring.h"

MyString::MyString()
{
    length = 0; //default constructor, initiate to '0' and 'NULL'
    string = NULL;
}

MyString::MyString(const char src)
{
    length = 1; //set length (char)
    string = new char[length + 1];  //allocate memory for string
    string[0] = src;    //set string
    string[1] = '\0';
}

MyString::MyString(const char* src)
{
    length = strlen(src);   //set length (c-string)
    string = new char[length + 1];  //allocate memory for string
    strcpy(string, src);    //set string via copy
    string[length] = '\0';
}

MyString::MyString(const MyString& src)
{
    length = src.length;    //copy constructor; copy length
    string = new char[length + 1];  //allocate memory of correct length
    strcpy(string, src.string); //deep copy the string
    string[length] = '\0';
}

MyString::~MyString()
{
    delete [] string;   //destructor, safely delete allocated memory
    string = NULL;
}

int MyString::GetLength() const
{
    return length;  //simple getter, nothing complicated
}

char MyString::GetCharAt(int index) const
{
    return string[index];   //simple getter, could add out-of-bounds error checking
}

void MyString::SetCharAt(int index, char ch) const
{
    string[index] = ch; //simple setter, could add out-of-bounds error checking
}

MyString& MyString::operator= (const char rhs)
{
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length = 1; //set length (input is single char)
    string = new char[length + 1];  //allocate memory for string
    string[0] = rhs;    //initiate string
    string[1] = '\0';
    return *this;   //return this object as reference
}

MyString& MyString::operator= (const char* rhs)
{
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length = strlen(rhs);   //set length (input is c-string)
    string = new char[length + 1];  //allocate memory for string
    strcpy(string, rhs);    //initiate string
    string[length] = '\0';
    return *this;   //return this object as reference
}

MyString& MyString::operator= (const MyString& rhs)
{
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length = rhs.length;    //copy length
    string = new char[length + 1];  //allocate new string of correct length
    strcpy(string, rhs.string); //deep copy implementation
    string[length] = '\0';
    return *this;   //return this object as reference
}

MyString MyString::operator+ (const char rhs) const
{
    MyString ret;   //create string object for returning
    ret.length = length + 1;    //initiate return string length (current + 1)
    ret.string = new char[ret.length + 1];  //allocate return string memory
    strcpy(ret.string, string); //set initial return string value
    ret.string[ret.length - 1] = rhs;   //concatenate return string with added char
    ret.string[ret.length] = '\0';
    return ret; //return addition result
}

MyString MyString::operator+ (const char* rhs) const
{
    MyString ret;   //create string object for returning
    ret.length = length + strlen(rhs);  //initiate return string length (current + new)
    ret.string = new char[ret.length + 1];  //allocate return string memory
    strcpy(ret.string, string); //set initial return string value
    strcat(ret.string, rhs);    //concatenate return string with added c-string
    ret.string[ret.length] = '\0';
    return ret; //return addition result
}

MyString MyString::operator+ (const MyString& rhs) const
{
    MyString ret;   //create string object for returning
    ret.length = length + rhs.length;   //initiate return string length (current + new)
    ret.string = new char[ret.length + 1];  //allocate return string memory
    strcpy(ret.string, string); //set initial return string value
    strcat(ret.string, rhs.string); //concatenate return string with added MyString
    ret.string[ret.length] = '\0';
    return ret; //return addition result
}

MyString& MyString::operator+=(const char rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += 1;    //set new length (addition is single char)
    string = new char[length + 1];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    string[length - 1] = rhs;   //concatenate return string with added char
    string[length] = '\0';
    return *this;   //return this object as reference
}

MyString& MyString::operator+=(const char* rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += strlen(rhs);  //set new length (addition is c-string)
    string = new char[length + 1];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    strcat(string, rhs);    //concatenate return string with added c-string
    string[length] = '\0';
    return *this;   //return this object as reference
}

MyString& MyString::operator+=(const MyString& rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    delete [] string;   //clear string memory if it exists
    string = NULL;
    length += rhs.length;   //set new length (addition is MyString)
    string = new char[length + 1];  //allocate new memory for string
    strcpy(string, temp.string);    //set initial return string value
    strcat(string, rhs.string); //concatenate return string with added MyString
    string[length] = '\0';
    return *this;   //return this object as reference
}

bool MyString::operator==(const MyString& rhs) const
{
    if(rhs.length != length)
        return false;   //if string length's are != then return false and break
    for(int i = 0; i < length; i++) //loop through string
        if(rhs.string[i] != string[i])  //compare each char
            return false;   //if chars != then return false and break
    return true;    //if you got to here, strings are ==, so return true
}

bool MyString::operator==(const char* rhs) const
{
    if(static_cast<int>(strlen(rhs)) != length) //static cast to get rid of signed/unsigned warning
        return false;   //if string length's are != then return false and break
    for(int i = 0; i < length; i++) //loop through string
        if(rhs[i] != string[i]) //compare each char
            return false;   //if chars != then return false and break
    return true;    //if you got to here, strings are ==, so return true
}

bool MyString::operator!=(const MyString& rhs) const
{
    if(rhs.length != length)
        return true;    //if string length's are != then return true and break
    for(int i = 0; i < length; i++) //loop through string
        if(rhs.string[i] != string[i])  //compare each char
            return true;    //if chars != then return true and break
    return false;   //if you got to here, strings are ==, so return false
}

bool MyString::operator!=(const char* rhs) const
{
    if(static_cast<int>(strlen(rhs)) != length) //static cast to get rid of signed/unsigned warning
        return true;    //if string length's are != then return true and break
    for(int i = 0; i < length; i++) //loop through string
        if(rhs[i] != string[i]) //compare each char
            return true;    //if chars != then return true and break
    return false;   //if you got to here, strings are ==, so return false
}

std::ostream& operator<< (std::ostream& os, const MyString& str)
{
    return os << str.string;    //pass string through ostream and return as reference (for loop as alternative?)
}

std::istream& operator>> (std::istream& is, MyString& str)
{
    char temp[4096];    //temporary, arbitrarily sized array (would prefer a better method)
    delete [] str.string;   //clear string memory if it exists
    str.string = NULL;
    is.read(temp, sizeof temp); //read input into local temp array
    str.length = is.gcount();   //set string length to size of input
    str.string = new char[str.length + 1];  //create new string of correct length
    strcpy(str.string, temp);    //move input from temp to string
    str.string[str.length] = '\0';
    return is;  //return istream as reference
}

My Professor's provided 'mystring.h'
*  Description:                                                         *
*                                                                       *
*  This is a header file for MyString class.                            *
*  Do not modify this file. Implement methods in MyString.cxx.          *
*                                                                       *
*  Please report any bug to ####(professor's email, hidden for privacy) *
*************************************************************************/

#ifndef __mystring_h__
#define __mystring_h__

#include <iostream>
#include <string>
#include <sstream>
#include <assert.h>

using namespace std;

class MyString
{
private:
    int   length;   // length of a string
    char* string;   // string pointer. Its size must be length.
public:
    // casting operator: an operator to cast MyString to string type.
    //                   This is going to be used in main() function, in order to grade your assignment.
    inline operator std::string() const
    {
        std::stringstream os;
        for(int i=0; i<length; i++)
            os << string[i];
        std::string str = os.str();
        return str;
    }
    // index operator []: an operator that allows array like operation. ( ex: a[3] )
    //                    This is going to be used for test 08 in main() function, in order to grade your assignment.
    char operator[] (int index)
    {
        if(index < 0      ) throw "out of index in operator[]";
        if(index >= length) throw "out of index in operator[]";
        return string[index];
    }
public:
    MyString();
    MyString(const char src);               // create a string from a char
    MyString(const char* src);              // create a string from C-string
    MyString(const MyString& src);          // copy constructor
    ~MyString();                            // destructor

    int GetLength() const;                      // getter
    char GetCharAt(int index) const;            // getter
    void SetCharAt(int index, char ch) const;   // setter

    // assignment operator
    MyString& operator= (const char rhs);           // operator =
    MyString& operator= (const char* rhs);          // operator =
    MyString& operator= (const MyString& rhs);      // operator =

    MyString  operator+ (const char rhs) const;     // operator +
    MyString  operator+ (const char* rhs) const;    // operator +
    MyString  operator+ (const MyString& rhs) const;// operator +

    MyString& operator+=(const char rhs);           // operator +=
    MyString& operator+=(const char* rhs);          // operator +=
    MyString& operator+=(const MyString& rhs);      // operator +=

    // equality/inequality operators
    bool operator==(const MyString& rhs) const;     // operator ==
    bool operator==(const char* rhs) const;         // operator ==
    bool operator!=(const MyString& rhs) const;     // operator !=
    bool operator!=(const char* rhs) const;         // operator !=

    // stream insertion/extraction operators as friend
    friend std::ostream& operator<< (std::ostream& os, const MyString& str);
    friend std::istream& operator>> (std::istream& is, MyString& str);
};

#endif

My Professor's provided 'testmystring.cxx'
*  Description:                                                         *
*                                                                       *
*  This is a test program for class MyString.                           *
*  Do not modify this file.                                             *
*                                                                       *
*  Please report any bug to ##### (Proff's email)                       *
*************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <limits>
#include <cmath>
#include <string>
#include <string.h>
#include "mystring.h"

using namespace std;

template<typename T>
void TestOutput(int& num_tests, int& num_success, T value, T expect, string testname)
{
    num_tests++;
    cout << endl << testname << endl;
    cout << "  result: " << value  << endl;
    cout << "  expect: " << expect << endl;

    if (value == expect)
    {
        num_success++;
        cout << "  test success" << endl;
    }
    else
    {
        cout << "  test failed !!!!!" << endl;
    }
}

int main()
{
    int num_tests = 0;      // total number of tests
    int num_success = 0;    // number of tests succeeded

    try
    {
        // test constructors
        MyString t01;                    TestOutput<string>(num_tests, num_success, (string)t01, ""         , "test 01 - default constructor");
        MyString t02('c');               TestOutput<string>(num_tests, num_success, (string)t02, "c"        , "test 02 - constructor: MyString(const char)");
        MyString t03("abc");             TestOutput<string>(num_tests, num_success, (string)t03, "abc"      , "test 03 - constructor: MyString(const char*)");
        MyString t04(t03);               TestOutput<string>(num_tests, num_success, (string)t04, "abc"      , "test 04 - copy constructor");

        // test getters and setters
                                        TestOutput<int   >(num_tests, num_success,         t04.GetLength()  , 3     , "test 05 - GetLength()");
                                        TestOutput<char  >(num_tests, num_success,         t04.GetCharAt(0) , 'a'   , "test 06 - GetCharAt()");
                                        TestOutput<char  >(num_tests, num_success,         t04.GetCharAt(1) , 'b'   , "test 07 - GetCharAt()");
                                        TestOutput<char  >(num_tests, num_success,         t04[2]           , 'c'   , "test 08 - operator[] (int)");
        t04.SetCharAt(2, 'x');          TestOutput<string>(num_tests, num_success, (string)t04              , "abx" , "test 09 - SetCharAt()");

        // operators
        MyString t05, t06;
        t05 = 's';                      TestOutput<string>(num_tests, num_success, (string)t05, "s"     , "test 10 - operator=(const char)");
        t05 = "qwert";                  TestOutput<string>(num_tests, num_success, (string)t05, "qwert" , "test 11 - operator=(const char*)");
        t06 = t05 = " zxc";             TestOutput<string>(num_tests, num_success, (string)t05, " zxc"  , "test 12 - operator=(const char*)");
                                        TestOutput<string>(num_tests, num_success, (string)t06, " zxc"  , "test 13 - operator=(const MyString&)");

        MyString t07;
        t07 = t03 + '_';                TestOutput<string>(num_tests, num_success, (string)t07, "abc_"      , "test 14 - operator+(const char) const");
        t07 = t03 + "_1234";            TestOutput<string>(num_tests, num_success, (string)t07, "abc_1234"  , "test 15 - operator+(const char*) const");
        t07 = t03 + t05;                TestOutput<string>(num_tests, num_success, (string)t07, "abc zxc"   , "test 16 - operator+(const MyString&) const");

        t07 += '#';                     TestOutput<string>(num_tests, num_success, (string)t07, "abc zxc#"                  , "test 17 - operator+=(const char)");
        t07 += "hjkl";                  TestOutput<string>(num_tests, num_success, (string)t07, "abc zxc#hjkl"              , "test 18 - operator+=(const char*)");
        t07 += t07;                     TestOutput<string>(num_tests, num_success, (string)t07, "abc zxc#hjklabc zxc#hjkl"  , "test 19 - operator+=(const MyString&)");

        MyString t08="siejfin";
        MyString t09="siejfin";
        MyString t10="siejfi_";
        MyString t11="siejfin ";
                                        TestOutput<bool  >(num_tests, num_success, t08 == t09  , true , "test 20 - operator==(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t08 == t10  , false, "test 21 - operator==(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t08 == t11  , false, "test 22 - operator==(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t03 == "abc", true , "test 23 - operator==(const char*) const");
                                        TestOutput<bool  >(num_tests, num_success, t03 == "ab" , false, "test 24 - operator==(const char*) const");

                                        TestOutput<bool  >(num_tests, num_success, t08 != t09  , false, "test 25 - operator!=(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t08 != t10  , true , "test 26 - operator!=(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t08 != t11  , true , "test 27 - operator!=(const MyString&) const");
                                        TestOutput<bool  >(num_tests, num_success, t03 != "abc", false, "test 28 - operator!=(const char*) const");

        MyString t12("test-stream");
        {
            // save data of t12 to a file
            ofstream infile;
            infile.open("./testMyString.data");
            infile << t12;
            infile.close();
            // read MyString from the file
            ifstream outfile;
            outfile.open("./testMyString.data");
            MyString tmp;
            outfile >> tmp;
            outfile.close();
            // compare read file with solution
            TestOutput<string>(num_tests, num_success, (string)tmp, "test-stream"   , "test 29 - operator <<, operator >>");
        }
        MyString t13("HelloWorld!");
        {
            // save data of t12 to a file
            ofstream infile;
            infile.open("./testMyString.data");
            infile << t13;
            infile.close();
            // read MyString from the file
            ifstream outfile;
            outfile.open("./testMyString.data");
            MyString tmp;
            outfile >> tmp;
            outfile.close();
            // compare read file with solution
            TestOutput<string>(num_tests, num_success, (string)tmp, "HelloWorld!", "test 30 - operator <<, operator >>");
        }
    }
    catch(const char* message)
    {
        cout << "Exception: " << message << endl << endl;
    }
    catch(...)
    {
        cout << "Exception" << endl;
    }

    // print test results
    int total_tests = 30;
    if(num_success == total_tests)
    {
        cout << endl;
        cout << "Congratulation!" << endl;
        cout << "Your program passed all " << num_success << " test cases." << endl;
    }
    else
    {
        cout << endl;
        cout << "Your program failed " << (total_tests - num_success) << " cases out of " << total_tests << " cases." << endl;
    }
    cout << endl;

    return 0;
}

Comment: It's impossible to authoritatively state what the problem is. Your question fails to meet the requirements of a [mcve], as explained in stackoverflow.com's [help]'s instructions for [ask] questions. Having said that, it seems fairly likely that the bug is a lack of null-terminated strings, and using C library functions that expect C-style null-terminated strings; and this results in undefined behavior and memory corruption. The first overloaded operator obviously fails to properly null-terminate the string, by overwriting the null character.
Comment: This is why the very first thing I said is that your question fails to meet the requirements of a [mcve], and because of that the most you can expect are guesses as to what the problem might be. For example,  your `length` could be off; you're one off short allocating the memory for the string, because you fail to account for the same null terminating byte. There could be a bug in your copy constructor. The problem can be anything, which is why until you [edit] your question using the instructions for creating a [mcve] (did you read this link already, and if not why not?), nobody can help you.
Comment: Based on what you said about null-terminated strings, I've added "string[length] = '\0';" to all the functions wherever necessary but that doesn't seem to change anything, I'm still getting a crash in Windows and normal execution in Linux.
Comment: Sorry, I've added all the source files.
Answer: MyString::MyString(const char* src)
{
    length = strlen(src);   //set length (c-string)
    string = new char[length];  //allocate memory for string
    strcpy(string, src);    //set string via copy
}

You are missing space for the terminating NULL on the constructor.
That is the start of the spiral when the copy ctor is invoked:
MyString& MyString::operator+=(const char* rhs)
{
    MyString temp(*this);   //create temporary MyString object from 'this'
    ...
}

So maybe something like this in the copy ctor:
string = new char[length+1];

But in operator+= you need to make room for the old string and new string. So you really want to allocate:
string = new char[length+strlen(rhs)+1];

Then use strcpy and strcat to concatenate the two strings. Maybe something like:
MyString& MyString::operator+=(const char* rhs)
{
    size_t new_length = length+strlen(rhs)+1;
    char* new_string = new char[new_length];
    strcpy(new_string, string);
    strcat(new_string, rhs);

    std::swap(new_string, string);
    std::swap(new_length, length);

    delete[] new_string;

    return *this;
}

You may have more issues, but that one jumped out.

The assignment in question has been previously compiled and run with g++ on Linux without any issues (and I assumed it should be correct since I got 100% for the assignment).

I believe Linux has issues too. You just did not crash.
Try using Valgrind or Address Sanitizer on Linux. They should produce findings for the code.
Comment: I installed Valgrind and immediately found the issue; the way I implemented the += overload is causing the problem when I try to += the same MyString to itself.  Thank you!


What does beating the fingers with the bow at the end of a concert mean?

Question: I was to a violin concert and at the end of the concert, when the audience applauded, I saw some of the violinists beating their pointer fingers or palms softly with the bow.
What is this? Is this a kind of collegial applause?
Answer: Yes that is one way members of the string section applaud. Another way that all members of the orchestra can do that is to shuffle their feet. It's a sound that is easily heard by other orchestra members but hard for the audience to see or hear. I've read of it being done even during performances after an especially good solo or cadenza.


what will be the cause of redirection loop while accessing view settings page

Question: I have drupal 7.14 setup installed with views module.
Whenever i am trying to access "admin/structure/views" the
site goes into redirection loop and not opening the views setting page also same behavior is showing for Linkit Profiles settings page.
I can add views by directly calling this url "/admin/structure/views/add" but not able to edit as they are not listing but i need to know why the views settings page not showing.
Solutions which i already tried:

Uninstalled views module and again installed.
run update.php
cleared views cache from database

But it doesn't give me any result any guesses why this is happening.
Answer: Five things I would check:

.htaccess rewrite rule?
Faulty alias? Check the table url_alias for any entry that contains admin/structure/views.
Redirect? If you have any redirect modules installed (globalredirect, redirect), check if there is a redirect set for the path in question.
Otherwise check the table menu_router, look for the path in the path column and see which function is set in the page_callback column. In D7 with Views 3 this should be ctools_export_ui_switcher_page.
Check your servers access and error logs to see if there's anything suspicious.
Answer: Do you have jQuery Update module installed? I recently had some issues when editing views due to using a version of jQuery (1.9 I think) set by the jQuery Update module. What fixed it for me was installing the dev version of the module, which gives you the option of specifying a different version of jQuery - 1.5 in my case - to be used solely within the admin theme while at the same time using the more recent version for the rest of the site.


Using Azure Active Directory with Azure Key Vault

Question: I am still getting up to speed with Azure Key Vault.
Here is the setup:  I have a Windows Service on-premise that needs access to a password.  For security reasons, the password will be stored in AKV.
The Azure Portal was then used to create the AKV resource, and a "Secret" which will store the password (TheSecret).
Permissions were then added so that my AD login would have access to TheSecret.
So as far as I know, the Azure side of this is set up correctly.
Now I try to access TheSecret from a Console app.
This is the code based on the sample code in the docs:
var keyVaultUrl = @"https://css-key-vault.vault.azure.net/secrets/TheSecret/<TheGuid>";

var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential();

KeyVaultSecret theSecret = client.GetSecret("TheSecret");
Console.WriteLine($"Secret is returned with name {theSecret.Name} and value {theSecret.Value}");

When I run this, I just get a 404 error.
If I take the URL and put it in a brower, it return this message:
{"error":{"code":"Unauthorized","message":"AKV10000: Request is missing a Bearer or PoP token."}}

How do I get this to work?
I am expecting that when the Windows Service is running, the Service will use the Windows Account which it is running and somehow pass this credential information to Azure in order to Authenticate and Authorize getting the secret.  But it is not clear to me what needs to be done to pass this information to Azure.  If there is some other way to do this, I am open to that as well.
Answer: The problem is related to this line:
var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential();

when using DefaultAzureCredential, it assumes there's a managed identity associated which will be used to retrieve the access token in order to authenticate/authorize the request.
For console apps, you need to retrieve a token from Azure AD, and use it:
https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-netcore-daemon
PS: you'll need to create an application / secret in your AD for this.
Comment: DefaultAzureCredential does not only attempt Managed Identity though, it attempts various authentication methods. For example, it also checks if it can get a token using Azure PowerShell. But agreed, using a client secret/certificate is probably the better choice here. Though since the password was put to Key Vault for security, you will then be giving a secret that has access to the Key Vault anyway, so I'm not sure how this is better to just having the secret in the app itself. Other than being able to switch it centrally.
Comment: Great, thank you.  I will try this.
Comment: you're correct about it. I usually follow the approach I've added (link) for console apps


Atualizar imagem sempre que uma nova for escolhida?

Question: Estou usando o seguinte código:
private void foto_Completed(object sender, PhotoResult e)
{
    if (e.TaskResult == TaskResult.OK)
    { // se teve sucesso na escolha de uma imagem da galeria
        BitmapImage imagem = new BitmapImage(); // cria uma imagem
        imagem.SetSource(e.ChosenPhoto); // coloca o caminh da imagem escolhida nesse objeto de imagem
        using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
        { // cria um gerenciamento de arquivos
            if (iso.FileExists("bloq.jpg"))
                iso.DeleteFile("bloq.jpg"); // se houver arquivo igual ele apaga
            IsolatedStorageFileStream fs = iso.CreateFile("bloq.jpg"); // cria um novo arquivo
            var bmp1 = new WriteableBitmap(imagem); // escreve a imagem escolhida em uma nova umagem editavel

            Extensions.SaveJpeg(bmp1, fs, 480, 800, 0, 90); // salva imagem
            imagem2.UriSource = new Uri(fs.Name, UriKind.RelativeOrAbsolute); // armazena o caminho da imagem salva em outro objeto de imagem
            fs.Close(); // fecha arquivo
        }
        fot.Source = imagem2; // pega o objeto com a  imagem recem salva e atribui a imagem presente na minha tela
        descricao.Text = "Agora pressione Salvar."; // muda um texto na tela
    }
}

O código só funciona na primeira vez, exemplo, o usuário abre o app, vai na tela e aperta para escolher um imagem, daí ele escolhe, aí sim ele atualiza a imagem na tela, mas se o usuário tentar escolher outra imagem, ele até substitui a imagem no armazenamento interno do app, mas não atualiza a imagem na tela, só quando o app é reiniciado que isso é atualizado.
Quero saber se há erro na lógica ou no código, como faço para sempre atualizar a imagem na tela? Independentemente de quantas vezes o usuário trocar a imagem
Answer: Em vez de usares o path da Imagem usa o bitmap que recebes para fazer o set da imagem.
private void foto_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            // se teve sucesso na escolha de uma imagem da galeria
            var bmp = new BitmapImage();

            bmp.SetSource(e.ChosenPhoto);

            Img.Source = bmp;
        }
    }

Comment: Pode adicionar um exemplo na resposta? Assim ela fica mais completa e servirá de referencia não só para o criador da pergunta.


JavaScript/PHP libraries for calculating common

Question: I am looking for a JavaScript or a PHP library to calculate common business/statistical metrics (e.g. Total, Avg, YTD, YoY, MoM, CAGR growth, standard deviation, regression line coordinates) from simple arrays/objects with a structure such as:

The idea is that I would just provide the arrays with some basic parameters (e.g. time period I'm interested in) and would get all the numbers crunched automatically in return.
Can anybody point me to a library they've used and trust from experience?
Answer: I think You can use http://d3js.org/
or http://simplystatistics.org/tag/d3-js/
Or you can find another javascript library with stats methods


How to drop varnishncsa log if req.url matches

Question: I've got a few load balancers that all perform health checks on a number of varnish instances. The health check on the varnish side consists of matching the request method and URL to return a 200 response.
<code>if (req.method == "GET" && req.url == "/ping") {
       return(synth(200, "OK"));
}
</code>
Using HAProxy i've got health checks configured to poll /ping on the backend servers. This is generating a lot of messages in varnishncsa. Is it possible to somehow drop log entries going into varnishncsa if they match a certain req.url?
Answer: In addition to the link provided by Kirrus, there is a reference for the VSL Query Language here:
http://www.varnish-cache.org/docs/4.0/reference/vsl-query.html
Answer: varnishncsa is actually just using a query against the varnishlog. You can override what query it uses with '-q' -- update the command line parameter in your pid0 system of choice. If initV, override DAEMON_OPTS in /etc/default/varnishncsa.
Actual documentation of it is a little sparse, but there's some examples here:
https://info.varnish-software.com/blog/logging-varnish-40
Comment: Sparse at best, thanks for this, been struggling to find any examples of how to use -q, this was just what I needed.


10 people flip a coin 12 times. What is the probability that at least one person gets 10 tails?

Question: I've already calculated the probability of getting 10 tails out of 12 flips:
$\frac{12!}{10! \times 2!} \times 0.5^{10} \times 0.5^{2}$
But I can't figure out how to calculate the probability of that at least one person  out of 10 gets 10 tails flipping a coin 12 times.
Comment: The probability of at least one person getting that is the $1-$ the probability of no one getting it.
Answer: If you select a person then the probability that this person obtains the result is $\alpha$ for a certain value of $\alpha$ that you have already obtained.
Since people's results are independent between each other, the probability that none of them get the result is $(1-\alpha)^{10}$ and so the final result is $1 - (1-\alpha)^{10}$.


Comparing two means (randomized experiment)

Question: I'm kind of new to science :) for my thesis I worked on some study on health related behavior. There was an intervention for the experimental group and none for the control. So that seems to be a nice application for a basic independent two sample t-test! (or so I thought..) So I was checking my data and going through all the basic assumptions.

Normality: I can do Shapiro or Kolmogorov. But they say its non-normal distribution. Ah ok, I found the information that my samples (each about 500) may be too big (ref: Normality in Large Samples). So I only have QQplot and my gut feeling to find out about normality? :/
Next: Checking the homogeneity of variance of the samples. Ok, I go for two different forms of test (one Levene). But hugh, maybe Brown-Forsythe test is recommended when normality may be suspect (Wikipedia).

I am confident that my work isn't that wrong. Standard textbooks say, checking assumptions is soo important. Now, all assumptions are not met. So, what should I do next? Using transformations (z?) and first force my data meeting the assumptions? (I also have slightly different sample sizes because of attrition rate.)
Maybe you can give me some advice for my data. I think it is a really basic intervention experimental design and there must be common cases how to deal with those problems.
Thank you so much
Update
Oneway t-test is an easy way to determine each samples confidence intervals. For Control 95% is 3.102183 to 3.560402 and for Experimental it's 3.110003 3.561506. SE are 0.116629 respective 0.114918.
Now those values are 'looking good' to me. But what's my precise conclusion? Because each sample mean is within their 95% confidence interval it's representative for the population, right? What can I conclude from my relatively 'small' SE?
Regards
Comment: Hi Mac, sorry for the late response. Yes, your first conclusion is correct. Something you can do now is to increase your expected confidence and see how the upper and lower bound reacts to it. If you are at 99% and the bounds for both means still don't intersect then the certainty that one mean will always be larger than the other, increases. It also increases the confidence on how far they are apart and so on. Your small SE is an indicator for a slim distribution, which also is a reason why the tests behave so well.
Answer: Well, whenever dealing with means, it is a good idea to check the standard error of both and see if their confidence intervals overlap. This gives you an intuition to start with. In fact you could build another statistical test on this that figures out your problem.
Why exactly are you shying away from the two sample t-test? Both, checking for equality, i.e., ${\mu _X} = {\mu _Y}$ or their difference, e.g. ${\mu _X} - {\mu _Y} < \omega$ where $\omega$ is your self-defined limit, should work fine. The later would be a one sample t-test. With a sample size of 500, you can assume your data is actually normally distributed given these tests. Especially for the differences of two means (${\mu _X} - {\mu _Y}$) this is easy to grasp (Central Limit Theorem).
Best
Comment: I think you figured that out. You can estimate the variance from your sample. Don't forget: these tests always assume a lot of things (normal distributed data to name one. The data won't be perfectly normal distributed. Same goes for estimating mean and SE from the sample in the t-test. The conclusion is that we have a mathematical correct test but we should not fully trust it.
Comment: Ok, I stick to the two sample t-test. But for standard error and confidence intervals, didn't I have to know the true variance of the population. There's a difference between sample means and sample variance and population, right? Or put it in other words: How do I calculate those confidence intervals? :)
Comment: Update: Now I am aware of standard errors, confidence intervals and their calculation with R (I think)


Relation between jet and singularities of a curve

Question: I am trying to understand the relationship between a jet and the singularities of a curve. Concretely I am trying to understand the following example:
Let $\gamma(t) = (\cos t , b \sin t)$ where $b > 0$ be an ellipse. Let $f$ be the distance squared function from $({1\over 2},0)$ to $\gamma (t)$ i.e.
$$ f(t) = ({1\over 2} - \cos t)^2 + b^2 \sin^2 t$$
For each $t_0$ consider the $2$-jet at $t_0$ of $f$:
$$ (\sin t_0 + (b^2 -1)\sin 2 t_0)t + (\cos t_0 + 2(b^2 -1)\cos 2 t_0) t^2$$
Writing this as $c_1 t + c_2 t^2$ the points $(c_1, c_2)$ will trace out a curve $\delta$ as $t_0$ varies. This curve will cross the $c_2-$axis at points where $f$ has a singularity $A_{\ge 1}$ at $t_0$ and will pass through the origin where $f$ has an $A_{\ge2}$ singularity at $t_0$. The geometrical interpretation of this is that $f$ has an $A_{\ge1}$ singularity at $t_0$ iff the normal to the ellipse at $\gamma (t_0)$ passes through $({1\over 2},0)$ and an $A_{\ge 2}$ singularity iff $({1\over 2},0)$ is the centre of curvature at $\gamma (t_0)$.

I have absolutely no intuition about why the coefficients of the jet
  should have the property that they trace out a curve and this curves
  contains information about the singularities of the original curve.
  Please could someone help me understand why this is true?

This example can be found here on page 57.
Answer: Let $\gamma$ be a regular plane curve, $p_{0}$ a point of the plane, and
$$
f(t) = \|\gamma(t) - p_{0}\|^{2}
  = \bigl(\gamma(t) - p_{0}\bigr) \cdot \bigl(\gamma(t) - p_{0}\bigr).
$$
Note that
$$
f'(t) = 2\bigl(\gamma(t) - p_{0}\bigr) \cdot \gamma'(t),
\tag{1}
$$
and
$$
f''(t) = 2\bigl[\bigl(\gamma(t) - p_{0}\bigr) \cdot \gamma''(t) + \gamma'(t) \cdot \gamma'(t)\bigr].
\tag{2}
$$
Let $T$ be the unit tangent field and $N$ the normal field, and write $\gamma' = vT$, $T' = \kappa N$.
By (1), $f$ has a critical point at $t_{0}$ if and only if $\gamma'(t_{0})$ is orthogonal to the displacement $\gamma(t_{0}) - p_{0}$, if and only if $\gamma(t_{0}) - p_{0}$ is a multiple of $N$; by (2), $f''(t_{0}) = 0$ in addition if and only if
$$
\bigl(\gamma(t_{0}) - p_{0}\bigr) \cdot \gamma''(t_{0}) + \gamma'(t_{0}) \cdot \gamma'(t_{0}) = 0.
$$
Since $\gamma''(t_{0}) \cdot N(t_{0}) = \kappa(t_{0}) v(t_{0})^{2}$, the preceding equation gives
$$
\left\lVert \gamma(t_{0}) - p_{0} \right\rVert \kappa(t_{0}) v(t_{0})^{2}
  = \bigl(\gamma(t_{0}) - p_{0}\bigr) \cdot \gamma''(t_{0})
  = -v(t_{0})^{2},
$$
or $\left\lVert \gamma(t_{0}) - p_{0} \right\rVert = -1/\kappa(t_{0})$. That is,
$$
\gamma(t_{0}) - p_{0}
  = \left\lVert \gamma(t_{0}) - p_{0} \right\rVert N(t_{0})
  = -\frac{1}{\kappa(t_{0})} N(t_{0}),\quad\text{or}\quad
p_{0} = \gamma(t_{0}) + \frac{1}{\kappa(t_{0})} N(t_{0}),
$$
which means $p_{0}$ is the center of curvature.
The connection with $2$-jets is immediate: the $2$-jet of $f$ at $t_{0}$ is
$$
f(t_{0}) + f'(t_{0})(t - t_{0}) + \tfrac{1}{2} f''(t_{0})(t - t_{0})^{2}
  = c_{0} + c_{1}(t - t_{0}) + c_{2} (t - t_{0})^{2}.
$$
The curve $\bigl(c_{1}(t_{0}), c_{2}(t_{0})\bigr) = \bigl(f'(t_{0}), \frac{1}{2}f''(t_{0})\bigr)$ crosses the $c_{2}$-axis if and only if $c_{1}(t_{0}) = 0$, if and only if $f$ has a critical point at $t_{0}$; the curve touches the origin if and only if both components are zero, if and only if $p_{0}$ is the center of curvature of $\gamma$ at $\gamma(t_{0})$.


Graphs with zero eigenvalues

Question: I search about known graphs have spectrum with the most zero eigenvalues respect to  their adjacency matrix. I know null, complete, bipartite and cocktel party graphs.
 Any kind of suggestion is appreciated. Thanks to everyone for the help.
Comment: In the category of "highest multiplicity of zero as an eigenvalue", it's rather hard to beat the zero matrix, coming from the null graph. Is that really the question you mean to ask?
Comment: @Jmerry,Thank you for your conment but I search in family of known graphs. I don't want to construct graphs with this property.
Comment: If you don't want people to propose graphs you haven't listed, but also don't want people to propose the graphs you have listed, then it is unclear what it is you do want. If there is some specific list of graphs you consider "known" then provide that list.
Answer: Take the bipartite graph $K_{m,n}$, then its spectrum is
$$ \{ \sqrt{mn}, 0^{m+n-2}, - \sqrt{mn}\}$$
Surely one of the most non-trivial graph with the desired property.
Otherwise yes as stated in the comments, take the null matrix.
Edit you should take a look at this article, talking about cospectrality of complete bipartite graph. You should be able to construct graph with spectrum close to the complete bipartite's one, hence with some null values
Edit 2 Looking at this, you can generalize on complete multi partite graphs, with $k$ sets and eigenvalue $0^{n-k}$. After that i don't know if you can do much better.
Comment: Sorryy, answered before the edit "no bipartite"
Comment: @ Thomas Thank you for your conment but I pointed the bipartite graphs in my question. I search in family of known graphs. I don't want to construct graphs with this property.

Graphs with zero eigenvalues


Fechar tooltip no Full Calendar

Question: Estou tentando fechar minha tooltip no calendario jQuery:
Exemplo
Clicando no evento, irá aparecer a tooltip e um " x " no canto superior, ao clicar nele a tooltip deve ser fechada, o codigo no JS na linha 16 chama a funcao para fechar.
Porém não estou tendo resultados.
JS
$.fn.popover.defaults.container = 'body';

$('#mycalendar').fullCalendar({
             header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'agendaWeek,agendaDay'
                    },
        eventRender: function (event, element) {
                    element.popover({
                        title: 'My Title
x
',
                        placement:'top',
                        html:true,
                        content: event.msg
                    });
                    $('#x-fechar').click(function(e){
                        element.popover('hide');
                    });
                  },
                 editable: false,
          events: [
                    {
                        title  : 'Click me 1',
                        msg: 'I am clipped to the left which is annoying',
                        start  : '2014-09-01 06:00:00',
                        end  : '2014-09-01 08:00:00',
                        editable: false,
                        allDay : false
                    },
                    {
                        title  : 'Click me 2',
                        msg: 'I am OK',
                        start  : '2014-09-04 14:00:00',
                        end  : '2014-09-04 15:00:00',
                        editable: false,
                        allDay : false
                    }
                ]
        });

Comment: Furlan, é importante [incluir seu código na pergunta](http://meta.pt.stackoverflow.com/questions/1913/posso-mostrar-s%C3%B3-um-link-pro-meu-site-com-problemas).
Comment: Dica2: o botão `TidyUp` lá no jsfiddle é tipo tudo de bom :)
Comment: cara...q btn lindo!! *-* kkk
Answer: Como o #x-fechar ainda não existe no DOM, tem que declarar seu click() assim:
$(document).on("click", "#x-fechar", function(e){
    element.popover('hide');
});

Mas como é mais de um elemento, deve-se usar uma classe .x-fechar. Não achei um jeito oficial de fazer isto, mas para saber qual popover pertence a qual evento, podemos adicionar o ID do evento no elemento .x-fechar:
title: 'My Title
x
',

E conferir durante o clique:
$(document).on("click", ".x-fechar", function (e) {
    if( $(this).data('eid') == event._id )
        element.popover('hide');
});

$('#mycalendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'agendaWeek,agendaDay'
    },
    defaultDate: '2014-09-01',
    eventRender: function (event, element) {
        element.popover({
            title: event.title + '
x
',
            placement: 'top',
            html: true,
            content: event.msg
        });
        $(document).on("click", ".x-fechar", function (e) {
            if( $(this).data('eid') == event._id )
                element.popover('hide');
        });
    },
    editable: false,
    events: [{
        title: 'Evento 1',
        msg: 'Lorem ipsum lorem.',
        start: '2014-09-01 06:00:00',
        end: '2014-09-01 08:00:00',
        editable: false,
        allDay: false
    }, {
        title: 'Evento 2',
        msg: 'Ut enim ad minim veniam',
        start: '2014-09-04 14:00:00',
        end: '2014-09-04 15:00:00',
        editable: false,
        allDay: false
    }]
});
#mycalendar {
    margin:30px;
    height:600px;
    max-width:500px;
}
.x-fechar {
    position: absolute;
    right: 0;
    padding: 0px 20px 0 0px;
    margin: -15px 0 0 0;
    cursor: pointer;
}

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.1.1/fullcalendar.min.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css">

Tem um bug quando mudamos a visualização no calendário (p.ex., trocar de mês) que faz com os popovers não sumam e não possam ser fechados pelo botão .x-fechar.
Para consertar isso acrescentei o evento viewDestroy que é disparado a cada troca de visualização:
viewDestroy: function( ev, el ) {
    $('.popover').each(function(){
        $(this).remove();
     });
}

Comment: entendi...eu ja imaginava que era isso, so nao sabia como resolver, tenho alguns projetos que faço partes com AJAX, e nao funcionava por causa disso, ele nao tava no DOM, mto obrigado @brasofilo vai ser mto util!
Comment: esta funcionado, mas por exemplo, eu tenho 2 tooltip aberta, quando eu clico em fechar, ela fecha as 2 nao a que eu escolhi
Comment: Atualizei a resposta com um jeito de detectar isso.
Comment: boaa ! valew @brasofilo.... obg mesmo
Comment: @Furlan, tava fuçando no calendar e descobri um bug, atualizei a resposta.
Comment: @brasofilo, reparou que quando aumenta ou diminui a área no jsfiddle o tooltip se sobrepõe?
Comment: @PapaCharlie, fora do fiddle vejo que ele não se movimenta, no fiddle meio que tenta acompanhar a célula de origem.
Comment: @brasofilo Imaginei que fosse dentro do fiddle mesmo. Deve conflito quando redimensiona o frame.
Comment: @PapaCharlie, é, tem alguma coisa estranha, o último código que postei não roda lá...
Comment: @brasofilo, Quando ha sobreposição o [X] não fecha o anterior, só o ultimo... Acho que é o plugin mesmo que colide com a área.

Fechar tooltip no Full Calendar


Validating email addres with specific ending rails

Question: I'm trying to add a field to a model I just added. My problem is that if I make the field a string, then it limits the field to 157 characters or some ridiculous number. Is there something bigger I could use that would give me a field that could potentially contain a ton of text in it.
Comment: In questions like this you must specify the database you are using
Answer: Make it a "text" field? Unlimited in length
Comment: Can I assign text to it? So do email:text when I make the model?
Comment: It functions exactly the same as a string field, except that it has no limitation. In your migration you indeed specify it as "text"


How to understand if 2 very correlated predictors influence the output?

Question: I have a binary output $y$ and a small set of predictors $x_1, x_2,\dotsc$
Two of these predictors are very correlated. It is known that one of them has influence on the output we want to know if also the other is relevant or not.
Is there any typical way to solve this problem?
<code>EDIT
</code>
I have tried various methods to solve this problem but I would like to know if there is a better one.

run a simple logistic regression and look at the p-value
ortogonalize the input variables define $x_2^{new} = x_2 - x_1\cdot x_2x_ 1$ (like the gram schmidt algorithm)
Compute the AUC error using bootstrap and check if the model, where both the variables are present, lead to a lower AUC error. (The models are all incredibly weak and all the prediction performances are very bad)

I need to run this kind of analysis with different combinations of input and various output values. I will so not discuss the result obtained with these methods. I would like to know if there is a standard way to do that.
MY BACKGROUND:
I am a mathematician but I have a good knowledge of machine learning.  I know a little bit of statistics as well but not too much.
Comment: There are many similar questions on site, see https://stats.stackexchange.com/questions/115915/how-to-evaluate-collinearity-or-correlation-of-predictors-in-logistic-regression
Answer: So you have set the rest of the model and you only want to test $x_2$ effect each time? Also, you are interested in an inferential statistical approach (which is, using hypothesis testing)?
If so, the simplest thing to do is to fit both model with and without $x_2$ and compare them trough a likelihood ratio test. Also looking at the p-value of $x_2$ (which comes from a Wald test instead) after ortogonazing it, should work fine, but likelihood ratio is a bit more reliable, and it doesn't even need ortogonalization.
Answer: Typical approach is to use PCA and transform original features in uncorrelated components and select components that explain most of the variance. Also one of highly correlated features may be removed in preprocessing. This is called filter feature selection.
Comment: I am not sure this directly answers the question.


NavigationDuplicated Navigating to current location ("/search") is not allowed

Question: When I want to do a search multiple times it shows me the NavigationDuplicated error. My search is in the navbar and the way I have configured the search is to take the value using a model and then pass the value as a parameter to the ContentSearched component, and then receive the value of the search in that component.
I know the right way is to use an emitter, but I still don't know how to learn to use it. To access the emit is context.emit('', someValue)
NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated", message: "Navigating to current location ("/search") is not allowed", stack: "Error↵    at new NavigationDuplicated (webpack-int…node_modules/vue/dist/vue.runtime.esm.js:1853:26)"}

NavBar.vue
<template>

      <router-link to="/" class="navbar-brand">

      </router-link>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" v-on:click.prevent="toggleNavbar">

      </button>

            <router-link class="nav-link" to="/" > Series</router-link>

            <router-link class="nav-link" :to="{name: 'EpisodesSection'}" > Episodios</router-link>

            <router-link class="nav-link" :to="{name: 'MovieSection'}" > Peliculas</router-link>

          <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" v-model="query" type="search" placeholder="Buscar películas, series ..." aria-label="Search">
            <button class="btn btn-main my-2 my-sm-0" @click.prevent="goto()" type="submit"></button>
          </form>

</template>

ContentSearched.vue
<template>

     <BoxLink/>

        Resultados para "{{query}}"

              <Series :series="content"/>

              <Movies :movies="content"/>

</template>

Answer: This happened to me when I had a router-link pointing to the same route. e.g. /products/1.

The user is able to click on the products, but if a product was already clicked (and the component view was already loaded) and the user attempts to click it again, the error/warning shows in the console.

You can learn more on the github issue..
Posva, one of the main contributors of vue-router suggests:

router.push('your-path').catch(err => {})

However, if you don't want to have a catch block which does nothing, in order to solve the issue you can compare the router navigation with the current route and only navigate if they differ:
const path = `/products/${id}`
if (this.$route.path !== path) this.$router.push(path)

Note: $route is an object provided by vue-router to every component. See The Route Object for more info.
Comment: Note that this solution will also prevent you from going from `/showPhoto?photo_id=1` to `/showPhoto?photo_id=2`.  So it might be easier to just try/catch it -- see for more details https://stackoverflow.com/a/65326844
Answer: I think the best solution to this problem can be implemented at the root level if we are not going to further use Router.push as asynchronous call.
import Router from 'vue-router';

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

Vue.use(Router);

Comment: @TechNomad you can use `$router.beforeEach'` hook and in that use `next(false)` to terminate the navigation
Comment: @TechNomad, the NavigationDuplicated is generated prior to the `$router.beforeEach` is called.
Comment: Halleluja!
Though I had this error even when using router-link! On Github posva claims this workaround would be necessary only when using router.push() but not for router-link. Any Idea why I still get this error when using router-link (and get rid off when using your code)?
Answer: If you are not feeling comfortable catching all kind of errors, I think this implementation is more considerate:
this.$router.push("path").catch(error => {
  if (error.name != "NavigationDuplicated") {
    throw error;
  }
});

Answer: As of 2021, global configuration :
I only wanted to silence NavigationDuplicated error, an empty catch can be dangerous. So I did this :
const router = new VueRouter({/* ... */})

const originalPush = router.push
router.push = function push(location, onResolve, onReject)
{
    if (onResolve || onReject) {
        return originalPush.call(this, location, onResolve, onReject)
    }

    return originalPush.call(this, location).catch((err) => {
        if (VueRouter.isNavigationFailure(err)) {
            return err
        }

        return Promise.reject(err)
    })
}

Insert this once when you initialize vue-router.
Thanks to @Oleg Abrazhaev for the update.
Comment: there is a better solution here https://github.com/vuejs/vue-router/issues/2881#issuecomment-520554378
Comment: you can also specify the navigation failure type to ignore with `if (VueRouter.isNavigationFailure(err, NavigationFailureType.duplicated)) {...}` [navigation failure type reference](https://router.vuejs.org/guide/advanced/navigation-failures.html#detecting-navigation-failures)
Answer: I encountered the same problem while searching. My solution is to add timestamp to the this.$route.query parameters of the search page.
this.$router.push({
    path: "/search",
    query: {
      q: this.searchQuery,
      t: new Date().getTime(),
    }
  });

Hope it helps you.
Comment: Thanks, this is great answer. Other answers silence the `NavigationDuplicated` error, but this allows to actually navigate to the same route. That allows to navigate to the same route but with different params. In my case I needed that for unit testing.
Comment: I would say this solution is extremely smart.
Comment: Greate answer, direct and simple
Comment: Great and smart solution! This actually allows navigating to the same route again, which I wanted in my case.
Answer: if you are using router.push in your code and you don't care about the navigation failing, you should catch it by using catch:
router.push('/location').catch(err => {})

Answer: in manual:
router.push(location, onComplete?, onAbort?)

You can use more simply
router.push("/", () => {});

Comment: This one should be the preferred, cleaner way
Answer: You mixed multiple concepts here from router-links to programmatic navigation, to query params to a state store. That makes it a bit difficult to help you and tell you what the "correct" solution here is.
Nonetheless, I think the best approach for you would be to:
1) define your route as
{
  path: "/search/:searchString",
  component: MySearchComponent,
  props: true
}

2) use a responsive <router-link> instead of your router.push
<input type="text" v-model="searchString">
<router-link :to="'/search/'+searchString" tag="button">search</router-link>

3) access the searchString in your search component via props: ['searchString'] and this.searchString
props: ['searchString'],
...
computed: {
  msg() {
    return `Searching for, ${this.searchString}!`;
  }
}

Full example: https://codesandbox.io/s/vue-routing-example-9zc6g
Note, I just forked the first codesandbox with a router I could find, adjust accordingly.
Answer: For TypeScript it worked like this
const superPush = VueRouter.prototype.push

VueRouter.prototype.push = async function push(loc:RawLocation):Promise<Route> {
  try {
    return await superPush.bind(this)(loc)
  } catch (e) {
    if (e?.name === 'NavigationDuplicated') {
      console.warn(e)
      return e
    } else {
      throw e
    }
  }
}

Comment: The question is not about TypeScript.
Answer: I'm very late to the party, but I thought I'd add my solution to this issue as it isn't listed: I simply placed an intermediate searching page as a pass-through to the search results view. I am now using this page for doing some preprocessing of the search terms.
The page template simply is:
<template>

searching ...

</template>

The NavigationDuplicated error is now gone and as an added benefit because I perform the fetch in this intermediate page, the responsibility for error-handling is isolated from both the search bar and the results view.
Answer: I post here the solution I found, because I was not able to find it well documented somewhere, and I went through it by trial and error.
It could be useful to someone, or someone may fix my misunderstood interpretation of vue-router guards.
It make use of vue-router V4.x and a global beforeEach guard.
The use cases are:

user asks for https://app.com/ without being already authorized;
user asks for https://app.com/ being already authorized;
user asks for any available routing, which requires auth or not.

Routes:
const routes = [
  /**
   * Routes not requiring auth
   */
  {
    path: '/',
    component: () => import('layouts/NotAuthorizedLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'LOGIN',
        component: () => import('pages/Login.vue')
      },
      {
        path: 'emailsignup',
        component: () => import('pages/EmailSignup.vue')
      },
      {
        path: 'forgottenpassword',
        component: () => import('pages/ForgottenPassword.vue')
      }
    ]
  },

  /**
   * Routes requiring auth
   */
  {
    path: '/',
    component: () => import('layouts/AuthorizedLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'authors',
        name: 'AUTHORS',
        component: () => import('pages/Authors.vue')
      },
      { path: 'profile', component: () => import('pages/userProfile/index.vue') }
    ]
  }
];

beforeEach global guard:
  const redirectToLogin = route => {
    const LOGIN = 'LOGIN';
    if (route.name != LOGIN) {
      return { name: LOGIN, replace: true, query: { redirectFrom: route.fullPath } };
    }
  };

  const redirectToHome = route => {
    const DEFAULT = 'AUTHORS';
    return { name: DEFAULT, replace: true };
  };

  Router.beforeEach((to, from) => {
    const userIsAuthenticated = store.getters['authentication/userIsAuthenticated'];
    const requiresAuth = to.matched.some((route) => route.meta && route.meta.requiresAuth);

    if (!userIsAuthenticated && to.fullPath === '/') {
      return redirectToLogin(to);
    }

    if (!userIsAuthenticated && requiresAuth) {
      return redirectToLogin(to);
    }

    if (to.fullPath === '/') {
      return redirectToHome(to);
    }

    return true;
  });

Answer: Your question is rather old.
Your error is the "@click.prevent". This statement does not work, because your button is a submit button (so your event is called twice).
Use "@submit.prevent" should work (or change the type of your button).
Comment: Instead of changing the template, you can use "prevent default" in your "goto()" method.
Answer: Best practice would be:
import { isNavigationFailure, NavigationFailureType } from 'vue-router/src/util/errors';
this.$router.push(...).catch((error) => {
      if (!isNavigationFailure(error, NavigationFailureType.duplicated))
        throw error
    );
  }

See the Vue Router docs
Answer: My solution is a mix of extending prototype with check Navigation Duplicated Error. Other errors and warning should be visible. After a week on production - no NavigationDuplicated and everything is working.
import { equals } from 'ramda'

export function register(Vue) {
  const routerPush = Router.prototype.push
  const routerReplace = Router.prototype.push

  const isNavigationDuplicated = (currentRoute, nextRoute) => {
    const { name: nextName, params: nextParams = {}, query: nextQuery = {} } = nextRoute
    const { name, params, query } = currentRoute

    return equals(nextQuery, query) && equals(nextParams, params) && equals(nextName, name)
  }

  Router.prototype.push = function push(location) {
    if (!isNavigationDuplicated(this.currentRoute, location)) {
      return routerPush.call(this, location)
    }
  }

  Router.prototype.replace = function replace(location) {
    if (!isNavigationDuplicated(this.currentRoute, location)) {
      return routerReplace.call(this, location)
    }
  }

  Vue.use(Router)
}

Answer: I noticed that error comes up when I tried to replace url query parameter with same value.
I have select filters and url query string params are in sync with their values. It works well as long as you change to a new value. If value remains the same (for example coming back from history) and thus replacing query string parameter with same value, error pops out.
Solution was to check if value is changed, and then replace query param in router:
let newValue = 'foo'; // new query value for parameter
let qcopy = { ...this.$route.query }; // clone current query
// prevent NavigationDuplicated: Avoided redundant navigation to current location
if (qcopy['your_param'] != newValue){
  qcopy['your_param'] = newValue;
  this.$router.replace({query: qcopy});
}

Answer: Stop the click propagation from hitting the router action
I have a high-level answer here that may be useful to others. It may not directly answer the OP, but this thinking applies.
My take on this is to NOT fiddle around with global configuration or attempt to catch router logic. It doesn't make sense to pollute your app with exceptions all over the place.
In the case of a results view with filters. If the filters happen to be presented as router links (for various reasons), but we don't want actual router logic to occur when they're clicked.
So, capture the click before it gets to the router action!
Then you get the best of both worlds:
Search filters (as a link) that...

Do logic within a view
Still provide the benefit of being presented as a link
(benefits to bot scans, user convenience and accessibility, etc)

Technique:
Use @click.prevent on a child inside the router-link, to capture and stop the click from hitting the router.
Example:
Before:
Router logic occurs, even though we're in the route already
<router-link class="nav-link" :to="{name: 'MovieSection'}" >
    Peliculas
</router-link>

After:
Router logic inhibited, we run other logic (applyFilter)
<router-link class="nav-link" :to="{name: 'MovieSection'}" >

        Peliculas

</router-link>

With this approach you may avoid messy high-level exceptions in your app.
Answer: This worked for me in the router/index.js init. You can catch can handle the exception types or message you want in the call() method to ignore certain conditions or throw certain ones.
See

//HANDLE ROUTE ERRORS HERE

comment
import Vue from "vue";
import VueRouter from "vue-router";

import routes from "./routes";

Vue.use(VueRouter);

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default function(/* { store, ssrContext } */) {
  const router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,

    // Leave these as they are and change in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: "history"
  });

  router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth) {
      var token = window.localStorage.getItem("token");
      if (token != null) {
        var decodedtoken = JSON.parse(atob(token.split(".")[1]));
        var role =
          decodedtoken[
            "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
          ];
        if (role != "Admin") {
          next("/accessdenied");
        } else {
          next();
        }
      } else {
        next("/login");
      }
    } else {
      next();
    }

    if (to.meta.requiresLogin) {
      var token = window.localStorage.getItem("token");
      if (token != null) {
        next();
      } else {
        next("/login");
      }
    }
  });

 //HANDLE ROUTE ERRORS HERE
  const originalPush = router.push;
  router.push = function push(location) {
    return originalPush.call(this, location).catch(err => {
      console.warn("router>index.js>push()", err);
    });
  };

  return router;
}

Based on @Abhishek Shastri's answer
Answer: Here's is a simple and efficient solution:
if(from.fullPath === to.fullPath){
    return
}

Comment: @hero592 Please read through the [code of conduct](https://stackoverflow.com/conduct)  and refrain from making such comments. We all are here to help others and not indulge in such unacceptable practices.


Time change depends on day

Question: I would like to create a script where time which you will get depends on the day.
f it's a normal week day it should echo the current date but time < 4pm if the time is >4pm that it should echo +2 day. But if today is Friday and the is >4pm and Saturday/Sunday then it should echo Monday for friday and Saturday and Tuesday for Sunday and so there should be also a countdown like : "Order within....(depends on the minutes until tomorrow 4pm or day with 4pm)"
for ex.
Today is Monday 3pm: The customer have 1 hour to buy to get teh product on Tuesday so the code should echo: "Want it Tuesday, Jan. 28? Order within 00 hrs 57 mins"
Today is Monday 6pm: The customer have now time to buy it until tomorrow 4pm to get it Wednesday so the code should echo: "Want it Wednesday, Jan. 29? Order within 22 hrs 00 mins"
.. .. ..
Today is Friday 3pm: The customer have 1 hour to buy to get teh product on Saturday so the code should echo: "Want it Saturday, $date ? Order within 00 hrs 57 mins"
Today is Friday 5pm: The customer have 1 hour to buy to get teh product on Monday so the code should echo: "Want it Monday, $date ? Order within $timer"
Today is Saturday 3pm/6pm: The customer have now time to buy it until tomorrow 4pm to get it Monday so the code should echo: "Want it Tuesday, $date? Order within $timer(coundown until Monday 4pm)"
Today is Sunday 3pm/6pm: The customer have now time to buy it until tomorrow 4pm to get it Monday so the code should echo: "Want it Tuesday, $date? Order within $timer(coundown until Monday 4pm)"
$time = new DateTime('today 4 PM');

$now = new DateTime('now');

// check if current time is past 6 PM

if ($now > $time) {
    $time = new DateTime('tomorrow 4 PM');
}
$diff = $time->diff($now);

    $dw = date( "w");
    if ($dw == 6 || $dw == 0) {
        $datetime = new DateTime('today');
        if ($dw == 6) {
            $datetime->modify('+3 day');
        } else {
            $datetime->modify('+2 day');
        }
        echo "Contact us again at: " . $datetime->format('Y-m-d');
    } else {
        //echo "Today is: " . date('l jS \of F Y')."
";

        $datetime = new DateTime('today');
        $datetime->modify('+1 day');

    }

        echo "Delivery: ". $datetime->format('l, d F') . ": Order in:  ";
        echo $diff->format("%h hours und %i Minutes.");
    }

What can I change that the script works like I want
Comment: Show us what you've tried so far. SO is not for having your code written for you.. As to your question: `date('N') >= 6`
Comment: I updated the question and include this as well!
Answer: <?php
//its the time 0-23
$hour = date(" H ");
//its the day of week 1 to 7. "1 is monday."
$weeksday = date(" N ");
$weeksdayname = date(" l ");

echo $weeksdayname.' Time: '.($hour+1);

if($weeksday < 5 || ($weeksday == 5 && ($hour+1) < 16)) {
    echo "
Friday before 4 PM. and Weekday.";
    if ($weeksday = 1) { //if its monday
        echo "Contact us on Wednesday."
    }
    else if ($weeksday = 2 && ($hour+1) > 16) { //if its tuesday
        echo "Contact us on Thursday."
    }
    else if ($weeksday = 3 && ($hour+1) >  16) { //if its wednesday
        echo "Contact us on *****."
    }
    else if ($weeksday = 4 && ($hour+1) > 16) { //thursday
        echo "Contact us on *****."
    }
    else if ($weeksday = 5 && ($hour+1) > 16) { //friday
        echo "Contact us on *****."
    }
}
else { //Friday after 4PM till monday 00:00
    echo "
Weekend.";
}

?>

Comment: You can change the echo's however you want.
Comment: but whats with the time feature
Comment: What do you mean? Can you explain it a bit more clear?
Comment: so if the time past 4 pm (limit) it should echo a countdown to +1 day for ex. if it is Monday 5pm that it should echo a countdown Tuesday but is should echo "Want it Wednesday, Jan. 29? Order within $countdown(countdown to Tuesday 4pm(that the time where he can buy it and get it next day)"  but if it is 3pm friday than echo Want it Saturday, Feb. 1? Order within $countdown(countdown to Friday 4pm)" and if it is 5pm friday or Saturday Sunday than echo Want it Tuesday, Feb. 4? Order within $countdown(countdown to Monday 4pm)"

Time change depends on day


In R, what can a data.table column store? Simple examples please

Question: Data.table package is amazing. I know I can store a vector in a column. That vector can be strings or numbers. I know I can store lists.
What else can I store? I recall that I could store models, data.tables, xml documents in a data.table. Am I confabulating? I fear I am since I am having a hard time finding straight-forward resources telling me how to store and manipulate these objects in a data.table.
Comment: In general, anything that is easily serialized can be put into a `list` which can be set as a column. Raw blobs can be. While @Waldi's point is technically true, you can insert recorded plots; try `plot(1)` and then `data.table(a=1, r=list(recordPlot()))`. It might not be convenient in this example, but it can be done. (Can't seem to get it to work with `data.frame` yet ...
Comment: Note, though, that just because you can *store* something in a list-column doesn't mean that you can properly use it. For instance, anything with ties to C objects (e.g., pointers) *cannot* be reused in new processes; `dput(data.table())` cannot be reused in a new R instance as-is because of the `.internal.selfref=` ref. Database connection objects from `DBI` also cannot. So while one might be able to store these objects in a `data.table`, if you `saveRDS` and `readRDS` that file in a new R, it won't work.
Comment: data.table(plot = plot(1)) doesn't work
Comment: @r2evans Your point that just because one can does not mean one can actually use it. Do you have a url that gives examples of **useful** items stored in data.table columns?
Comment: Farrel, nope, not really. In the tidyverse landscape, there are plenty of packages that use columns to store regression models, summaries, predictions ... `tidymodels` comes to mind, though I don't use it (atm). I think the utility of list-columns becomes much more apparent when (for example) using `magrittr::%>%` and making code read top-to-bottom instead of inside-out. That doesn't mean they're only useful there, but I find that a useful construct for code organization.
Answer: Most types are valid through data.table() but the range of well-supported classes is narrower. Mostly, to keep anything in a data.table you can put it in a list column.
Note that not all data.table operations are supported for all types, however.
To wit, we only offer sorting for atomic types (see ?is.atomic). Sorting is the workhorse behind grouping by= and joins (on= / merge), so if your grouping column or is a list, you're out of luck. Joining using complex columns is also not supported.
Please feel free to report to our issue tracker with use cases of anything that's not supported.
Comment: I seen handling complex type inside `bmerge`, so maybe it is supported but just disabled?
Comment: https://github.com/Rdatatable/data.table/issues/3690 @jangorecki IIRC the support for complex is just about columns in the output, not the columns used to join, see `DT = data.table(a = 1:5, z = 6:10 + (5:1)*1i); DT[DT, on = 'a']; DT[DT, on = 'z']` the join on `integer` with `complex` result works, but the join on `complex` with `integer` result fails


assign role after registration (male female)

Question: I need users to check male/female option when creating an account. Then I need to automatically assign a role male/female to the users.
How can this be achieved? Is there any module which I can use?
Comment: Are you asking which code you should use, or if there is a module you could use?
Answer: You can add a field to the user entity at admin/config/people/accounts/fields. Let's use the List (text) type and call it "field_gender" with the possible values of female|Female and male|Male. Display it on the user registration form.
Then you can use Rules module to react e.g. when someone creates an account and perform various actions. The idea is that you create two different rules for assigning either the male or the female role.

Install Rules if you haven't already done so, and create a new
rule at admin/config/workflow/rules/reaction/add.  Choose a name
for it and tag it if you want. The rule should react on the following
event: After saving a new user account.
Add a condition in the next step and choose Data
comparison. Then type or select account:field-gender in the data
selector.
Choose the data value in the next step to be Female.
Now your condition is ready, add an action, select Add user role,
then choose the female role.
Repeat these steps and create a rule
for assigning the male role.
Comment: great, looks like simple solution.


SQL find next record by non-unique field

Question: I need to find the next record in a database with (say) a given Surname. So if the user is looking at A Smith, the query would return either the Next A Smith, or B Smith
the solution is probably similar to that discussed here : selecting subsequent records arbitrarily with limit but using an ODBC 2.0 compliant database rather than mysql.
At the moment I have a procedural solution, but it is very slow. Is there a more elegant approach which uses only basic SQL ?
Sample Data in "appropriate" order

recnum, surname, firstnames
1000,smith,andrew
1320,smith,andrew
1340,smith,andrew
14,smith,anton
17,smith,anton
2000,smith,brian
2030,smith,brian
1017,smith,brianally

I would have the recnum of the current record and need to find the next in the above (which is ordered on surname, forenames, recnum) In this example the case for 1320 is easy, but 1340 makes it harder!
Comment: How do you determine "next" do you have an incremental id column or a 'createdDate' column or do you want ot be able to fetch the next record according to specific sort criteria?
Comment: @Andiih: can you please **update** your original question instead of posting lots of stuff into a comment which is really not suited for long lists of stuff......
Comment: marc_s - done. Didn't know it was going to do that to the format!
Answer: Given your sample data and assuming that at any point in the process you have the "recnum" value available for the current record, it would be possible to query for the next value by using a series of up to three queries.  If you think of the three pieces of data (surname, firstname, recnum) as a composite index, then you want to find the record that comes next in index order. So assuming you have the three pieces of data from the current record, run this:
select top 1 surname, firstname, recnum from Table
    where surname = @CurrentLast and
    firstname = @CurrentFirst and
    Recnum > @CurrRec
    order by surname, firstname, recnum

If that is empty, then run this:
select top 1 surname, firstname, recnum from Table
    where surname = @CurrentLast and
    firstname > @CurrentFirst
    order by surname, firstname, recnum

And finally, if that is empty:
select top 1 surname, firstname, recnum from Table
    where surname > @CurrentLast
    order by surname, firstname, recnum

If the three fields are indexed, it should be reasonably efficient. It would also be possible to use a single query such as the following (syntax probably wrong), but it would require a composite index on all three fields in order to be efficient.
select top 1 surname, firstname, recnum from Table
    where surname+firstname+convert(recnum,char) > @CombinedValue
    order by surname, firstname, recnum

If recnum refers to a physical record number in the underlying data and if the SQL engine uses the record number as the tie breaker when other conditions match in sorting, then I believe that recnum could be left out of the order by clauses.
Comment: I think the 3-query technique will work and be more efficient than what I have now. Not sure whether the rubbish odbc driver I am stuck with will cope with the second solution : But I will try it! Thanks Mark
Comment: Mark: given the ordering (surname, firstname, recnum) do queries 2 & 3 of the first part need an order by clause to ensure they pick up the first record of the next group ?
Comment: Yes they would.  Sorry about that.  They would all need order by clauses.  I had originally run this on a table of my own and tried to quickly translate the names to match your data.  Completely left off that part.  I'll edit it.
Comment: FYI I finally got to test this and it works perfectly.  The reverse, to find the previous record, is suffering performance issues - I guess because of SQL optimization.
Comment: It's good to know it worked, but that is unfortunate about the reverse operation.  You are probably correct that the SQL optimization isn't working so well.  It is possible that descending indexes on each of the fields would help that case (ouch - lots of indexes).  If the database supports ROWID, it might be worth trying to replace "recnum" with "rowid" in each query.  I think it would be logically equivalent and might optimize differently (hard to say if differently would mean better, though).
Comment: You are spot on with the requirement for descending indexes. Dataflex ODBC driver -  no support for < without a descending index. Which is impractical due to sheer volume of indexes - too much of a performance hit on data write. Lesson. Avoid Dataflex ODBC. Sigh.
Answer: SQL is intended to work with and return set of data. In fact, one of the points Coad (or one of the gurus of relationalism anyway) uses to describe a relational database is that there is no "next record" -- the concept shouldn't even exist.
As such, from the viewpoint of SQL, what you should do is create a set that contains the data you want in the order you want:
select * from YourTable
    where LastName = @whatever
    order by FirstName

Then, if you want to work with one record at a time, you probably want a cursor into that data set. Using that, you'll just look at a record, and when you advance the cursor to the next record, it'll be the one that should be next.
Comment: Think trad ASP and ODBC. No cursors, no real state preservation between calls, no stored procedures. My current solution uses a recordset, and FindFirst then FindNext - which is more or less what you describe but I was hoping for something at the SQL level.
Also worth noting that the user should be able to click "next" and move from Smith to Smyth without reentering search conditions. We simply need to find the next record in the DB , by Surname, Forenames after the one we know the recnum of.
Answer: If by 'next' you mean alphabetical on first name,
then try:
  Select * From Table T
  Where lastName = @GivenSurname
     And firstName =
      (Select Min(FirstName)
       From Table
       Where LastName = T.LastName
          And FirstName > @GivenFirstName)

If there might be more than one record with this same first name and last Name, and if you have a surrogate Primary Key, then you can arbitrarilly pick one of them by using this:
  Select * From Table T1
  Where lastName = @GivenSurname
     And PK =
      (Select Min(PK) From Table T2
       Where LastName = T1.LastName
         And FirstName =
          (Select Min(FirstName)
           From Table
           Where LastName = T1.LastName
                And FirstName > @GivenFirstName))

Comment: Sorry but no. The db could have hundreds of "A Smith" entries - also I think your code would just give the second entry ? Or am I reading it wrong somehow ?
Comment: Sorry, I was editing to deal with dupes when you commented... Also, assume you don't care which B Smith you return ?
Comment: Each time the user clicks next they need to walk through all of them.  See the sample data I (just) added to the question. Thanks for your input so far!
Answer: Does "no state preservation" mean that you can't store any data at all, even pre-caching? In other words,  query
SELECT recnum FROM my_table ORDER BY surname, firstname

Use getrows to store that in a local array. Then iterate through that array, each time executing the prepared statement
SELECT surname, firstname FROM my_table WHERE recnum = ?

That will almost certainly be slower than querying it all at once, but it will satisfy your goal.
Comment: each time the user went to the next record, the process would have to be repeated: so this is going to be inefficient to say the least. One of the problems is that the table is several million records


Combine two text files in bash script

Question: I have a text file (FILE_A.txt) with this content:
Content1
Content2
Content3

And other text file (FILE_B.txt) with this content:
A[#]
B[#]
C[#]

I would like to combine FILE_A.txt and FILE_B.txt in other file (FILE_C.txt) in this way:
A[Content1]
B[Content2]
C[Content3]

How could I make this using bash shell in linux (sed, cut, grep, etc)?
Comment: I've tried again with diferents contents for FILE_A and FILE_B, and I don't know why it doesn't works. File_B.txt now has "something(#,@);" and File_A.txt has "__OtherTexts". When I try to combine the two files with dogbane method, it copies the content of each line at the end of the lines contained in FILE_B.txt. Any ideas?
Comment: With my new issue, the ghoti method works fine for me :)
Answer: Here we go.
# awk 'NR==FNR{a[NR]=$0;next;} sub(/#/,a[FNR])' FILE_A.txt FILE_B.txt
A[Content1]
B[Content2]
C[Content3]

How does this work?

NR==FNR - causes the following statements to be run if the record number matches the FILE record number - that is, we are currently reading only the firs tfile.
{a[NR]=$0;next;} - Store values from the first file in an array.
sub(/#/,a[FNR]) - Once we're in the second file, substitute # for the matching value stored from the first file.  Note that this isn't inside curly brackets, so it's being evaluated as a condition.  If the sub() statement succeeds, the current line is printed.
Comment: No problem, Cesar.  The advantage of this also is that because we're using `sub()` to replace a substring, this solution basically makes the lines of `FILE_A.txt` into a template for the data in `FILE_B.txt`.  If your requirements become more complex than your sample data, this may be preferable to handling the output from `paste`.
Answer: Use paste and sed as follows:
$ paste File_B.txt File_A.txt | sed 's/#]\s*\(.*$\)/\1]/g'
A[Content1]
B[Content2]
C[Content3]

Comment: Works in Linux, but the `\s` makes it non-portable.  Won't work in BSD, OSX, Solaris, etc, unless you've installed GNU sed.
Comment: @ghoti That's easily fixed. You can change the `paste` command to use a specific delimiter of your choice (using the `-d` option) and then use the same delimiter in the `sed` command instead of the `\s*`.
Answer: The following reads both files concurrently, one line at a time, and store the lines in $value and $template. We then use bash's variable substring replacement to replace # within $template with the  contents of $value.
exec 6<"FILE_B.txt"  # open file for reading and assign file descriptor 6

while read -r value; do  # loop through FILE_A.txt, storing each line as $value
  read -r template <&6   # read a line from FILE_B.txt, store as $template
  echo ${template/\#/$value}  # replace value into the template in place of `#`
done <"FILE_A.txt"

exec 6<&-  # close input file descriptor 6

Comment: Complex but very educational. Thanks for your answer.

Combine two text files in bash script


Working in complex number field

Question: I have to draw the graphic of "group of points given by the equation $$(|z^2|-3|z|+2)(z^4+4)=0$$ I solved the first part by factoring and obtaining $|z|=1$ and $|z|=2$ so in the graphic I have the points that stay on two circumferences with the respective radii. For the second part: $$z^4=-4 \to z=\sqrt2*i^{(1/4)}$$ so I'm sure I have 4 points that "form a square" but I don't know how to proceed correctly. I saw a question similar to mine but the answers were given using exponential forms that I don't know and that are not in my program. I need  a guideline that show me how to proceed when I have to solve this kind of equation or also the simpler equation form $z=v^{n/n}$, I need to have clear ideas and I'll be grateful if you can help me. Thank you in advance!
Answer: From $z^4=-4$ you get
$$z^2=\pm 2i$$
There are two main non-exponential ways to proceed from here. The first is polar form
$$z^2=r(\cos \theta + i \sin \theta)$$
Then from de Moivre's theorem you get
$$z=\pm \sqrt r \left(\cos \frac{\theta}2+\sin \frac{\theta}2\right)$$
See if you can do that for $z^2=2i$ and for $z^2=-2i$.
The other way is to let $z=a+bi$ for real $a$ and $b$, so (for example)
$$z^2=2i$$
becomes
$$(a^2-b^2)+(2ab)i=2i$$
so that
$$a^2-b^2=0$$
and
$$2ab=2$$
That is two equations with two unknowns, which is solvable, giving two solutions for $a$ and $b$. Then do the same with $z^2=-2i$.
Either method give you four solutions for $z^4=-4$ (either four $\theta$'s or four pairs $(a,b)$). Both ways the solutions are in a square in the complex plane around $0$.
Do you need more help?
Comment: Thank you for the clarification, I solved it correctly. But the way that I was going to follow: $z=\sqrt2*i^{1/4}$ can give me the same solutions?
Comment: @Dipok: No, you mean $z=\sqrt 2 \cdot (-1)^{1/4}$ or $z=\pm \sqrt {2i}$. The two ways I showed you are ways to find the four fourth roots of $-1$.
Comment: Oh yes, I realized my mistake thank you again

Working in complex number field


Get relief of Switzerland from a shp-file

Question: I would like an official source for drawing the relief over a map of Switzerland.
I downloaded https://cms.geo.admin.ch/ogd/topography/DHM25_BM_SHP.zip to use the dhm25_p.shp-File
Now using the code
aux <- st_read(dsn="dhm25_p.shp")
auxx <- as_Spatial(aux)
auxxx <- as.data.frame(auxx)

ggplot() +

  # draw the relief
  geom_raster(
    data = auxxx,
    inherit.aes = FALSE,
    aes(
      x = coords.x1,
      y = coords.x2,
      alpha = coords.x3
    )
  )

I'll get the error
Error in `geom_raster()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 1st layer.
Caused by error:
! cannot allocate vector of size 6539542.5 Gb

Comment: Stupid question: Why don't you simply use the DHM25 elevation model provided [here](https://www.swisstopo.admin.ch/en/geodata/height/dhm25200.html) instead of rasterizing ~200k points yourself?
Comment: @MPB: as dimfalk pointed out, that shape is 210k point data, not contours (as I had suspected). In that case, you could first interpolate altitudes at a coarser grid (e.g. with `interp::interp()` and then use `geom_contour()` ... but these data seem available already (see dimfalk)
Comment: Being a shapefile (.SHP) it contains some vector representation of the height model (perhaps contourlines). `geom_raster` might try to rasterize these, perhaps even at a 1x1 m² resolution, thus exceeding the maximum memory available. You could try `geom_sf(data = aux)` instead.
Comment: Thank you for that hint. Now I get a map, but unfortunately mostly black - with the exception of the lakes. Can it be that the resolution is too high, so that I can't see the details and if yes, how can I reduce it?
Answer: A shapefile of points is generally not a good source for mapping continuous phenomena such as elevation. It is better to use raster data.
Here is a simple way to make an elevation map for Switzerland
library(terra)
library(geodata)
x <- geodata::elevation_30s("Switzerland", ".")
plot(x)

Add contour lines
v <- as.contour(x, levels=c(500,1000,3000))
lines(v)

Or show shaded relief
slope <- terrain(x, "slope", unit="radians")
aspect <- terrain(x, "aspect", unit="radians")
hill <- shade(slope, aspect, 40, 270)
plot(hill, col=gray(seq(0,1,.01)), legend=F, axes=F, mar=1)

To show relief and elevation
plot(hill, col=gray(seq(0,1,.01)), legend=F, axes=F)
plot(x, col=terrain.colors(25, alpha=.5), add=T, axes=F, legend=T)

You can do the same things with the Swiss government data from the website you point to in your (now hidden) answer. But it takes some more work if you want to remove the areas outside of Switzerland.
y <- rast("DHM200.asc")
# Assign the coordinate reference system (Landesvermessung 1903)
crs(y) <- "EPSG:21781"

# get the outline of the country and project it to the crs of the raster data
swz <- geodata::gadm("Switzerland", level=1, path=".")
pswz <- project(swz, y)

# remove values for areas outside of Switzerland
y <- mask(y, pswz)

plot(y)
lines (pswz)

And with ggplot you can use geom_spatraster
library(tidyterra)
library(ggplot2)
ggplot() + geom_spatraster(data = y)

Comment: I have added that, using base plot.
Comment: You have a full post explaining how to do that also with tidyterra + ggplot2, if you are interested https://dieghernan.github.io/202210_tidyterra-hillshade/
Comment: Great - thanks! In addition: how is it possible to combine the hillshaded version with the original plot: 1) ggplot() +  geom_spatraster(data=hill) + scale_fill_hypso_c() results in a nice hillshaded version but not with the original relief values, while 2) ggplot() + geom_spatraster(data=y) + scale_fill_hypso_c() results in a nice colour version but not hillshaded. What I'm looking for is 2) with the hillshaded version of 1) - thanks again.
Answer: For posterity, leveranging also on MPB_2022 and Robert, see how you can replicate the same map using ggplot2 + tidyterra (as explained in detail in https://dieghernan.github.io/202210_tidyterra-hillshade/):
library(terra)
library(geodata)
library(tidyterra)
library(ggplot2)

x <- geodata::elevation_30s("Switzerland", ".")

slope <- terrain(x, "slope", unit = "radians")
aspect <- terrain(x, "aspect", unit = "radians")
hill <- shade(slope, aspect, 40, 270)

# Hillshading, but we need a vector of colors
pal_greys <- hcl.colors(1000, "Grays")

# Get a vector of colors based on the value of shades
# Create index
hill_col <- hill %>%
  # Rename layer
  select(shades = 1) %>%
  mutate(index_col = round(scales::rescale(shades, to = c(1, length(pal_greys))))) %>%
  pull(index_col) %>%
  pal_greys[.]

head(unique(hill_col), 10)

# Plot
ggplot() +
  # Add our hill shade and use fill with the vector color
  geom_spatraster(data = hill, fill = hill_col, maxcell = Inf, alpha = 1) +
  # And add the initial raster with some alpha
  geom_spatraster(data = x) +
  # Add an hypstometric tint
  scale_fill_hypso_tint_c(
    palette = "dem_poster",
    # Need alpha to show the hill
    alpha = 0.5 ) +
  theme_minimal() +
  labs(fill="Elevation")

Comment: Great - thanks also for this solution!