text:
Q: Qt SQLite C++ Error while trying to initialize database with information from an excel file I am working on a c++ Qt project and I have to load an SQLite database using an excel file. Below I have my database class. When I call the function to initialize the database, I get the following errors:
 "QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.

and
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'xlsx_connection', old connection removed.

I am not sure why this is happening or how to fix it. Could someone please help? Thanks! I have added my code below
Database::Database(const QString &path)
{
    myDB = QSqlDatabase::addDatabase("QSQLITE");

    myDB.setDatabaseName(path);

    if(!myDB.open())
    {
        qDebug() << "Error: can't connect to database!" << Qt::endl;

    }
    else
    {
        qDebug() << "Database: Connected" << Qt::endl;
    }

    QSqlQuery query;
    query.prepare("PRAGMA foreign_keys = ON");
    query.exec();
}

void Database::InitCollegeList(const QString &path)//path to the excel file
{
   QSqlDatabase fileDB = QSqlDatabase::addDatabase("QODBC", "xlsx_connection");
   fileDB.setDatabaseName("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + path);

   if(fileDB.open())
   {
       qDebug() << "Excel connection successful" << Qt::endl;

       QSqlQuery *query = new QSqlQuery(fileDB);
       query->exec("select * from [" + QString("Distances") + "$A1:A111]");   //Distances is the sheet name!

       QSqlQuery * querytoDb = new QSqlQuery(myDB);

       querytoDb->exec("CREATE TABLE Colleges ("
                       "collegeName TEXT);");

       QString compare = "";

       while(query->next())
       {

           if(myDB.open())
           {

               querytoDb->prepare("INSERT INTO Colleges(collegeName) values(:collegeName)");

               QString column1 = query->value(0).toString();

               if(compare != column1)
               {
                   querytoDb->bindValue(":collegeName",query->value(0).toString());
                   qDebug() << querytoDb->exec();

               }
               compare = column1;
           }
       }

       fileDB.close();
   }
}

void Database::initsouvenirList(const QString &path)
{
    QSqlDatabase fileDB = QSqlDatabase::addDatabase("QODBC", "xlsx_connection");
    fileDB.setDatabaseName("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + path);

    if(fileDB.open())
    {
        qDebug() << "Excel connection successful" << Qt::endl;

        QSqlQuery *query = new QSqlQuery(fileDB);
        query->exec("select * from [" + QString("souvenirs") + "$A1:C61]");

        QSqlQuery * querytoDb = new QSqlQuery(myDB);

        querytoDb->exec("CREATE TABLE souvenirs ("
                        "collegeName TEXT,"
                        "souvenirName TEXT,"
                        "cost DOUBLE);");

        QString tempColumn1;
        QString check;

        while(query->next())
        {
            if(myDB.open())
            {
                querytoDb->prepare("INSERT INTO souvenirs(collegeName, souvenirName, cost) VALUES(:collegeName, :souvenirName, :cost)");

                QString column1 = query->value(0).toString();
                check = column1;
                if(column1 == "" || column1 == " ")
                {
                    column1 = tempColumn1;
                }

                QString column2 = query->value(1).toString();

                double column3 = query->value(2).toDouble();

                if(check == "" && column2 != "")
                {
                    querytoDb->bindValue(":collegeName", column1);
                    querytoDb->bindValue(":souvenirName",column2);
                    querytoDb->bindValue(":cost",column3);
                    qDebug() << querytoDb->exec();

                }

                tempColumn1 = column1;
            }
        }
        fileDB.close();
    }
}

void Database::initDistanceList(const QString &path)
{
    QSqlDatabase fileDB = QSqlDatabase::addDatabase("QODBC", "xlsx_connection");
    fileDB.setDatabaseName("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + path);

    if(fileDB.open())
    {
        qDebug() << "Excel connection successful" << Qt::endl;

        QSqlQuery *query = new QSqlQuery(fileDB);
        query->exec("select * from [" + QString("Distances") + "$A1:C111]");

        QSqlQuery * querytoDb = new QSqlQuery(myDB);

        querytoDb->exec("CREATE TABLE Distances ("
                        "startCollege TEXT,"
                        "endCollege TEXT,"
                        "distance INTEGER);");

        while(query->next())
        {
            //QSqlDatabase myDB = QSqlDatabase::database("sqlite_connection");

            if(myDB.open())
            {
                querytoDb->prepare("INSERT INTO Distances(startCollege, endCollege, distance) VALUES(:startCollege, :endCollege, :distance)");

                QString column1 = query->value(0).toString();

                QString column2 = query->value(1).toString();

                int column3 = query->value(2).toInt();

                querytoDb->bindValue(":startCollege", column1);
                querytoDb->bindValue(":endCollege",column2);
                querytoDb->bindValue(":distance",column3);
                qDebug() << querytoDb->exec();
            }
        }
        fileDB.close();
    }

}

//QSqlDatabase::removeDatabase("xlsx_connection"); // need to put this out of scope of the initialised db

void Database::removeSouvenir(const QString &souvenirName, const QString &college)
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(souvenirExists(souvenirName, college))
    {
        if(myDB.open())
        {
            query->prepare("DELETE FROM souvenirs WHERE (souvenirName) = (:souvenirName)");
            query->bindValue(":souvenirName", souvenirName);

            if(query->exec())
                qDebug() << "souvenir delete success!";
            else
                qDebug() << "souvenir delete failed!";
        }
    }

}

int Database::cartQuantity(const QString college, const QString souvenir)
{
    int count = 0;
    QSqlQuery *query = new QSqlQuery(myDB);
    if(myDB.open())
    {
        query->prepare("SELECT quantity FROM Cart WHERE (college, souvenir) = (:college, :souvenir)");
        query->bindValue(":college", college);
        query->bindValue(":souvenir", souvenir);

        if(query->exec())
            qDebug() << "selected quantity";
        else
            qDebug() << "coudn't select quantity";

        while(query->next())
        {
            count = query->value(0).toInt();
            qDebug() << count;

            return count;
        }
    }

    return 0;
}

void Database::removeCart(const QString college, const QString souvenir)
{
    int count = cartQuantity(college, souvenir);
    count--;

    if(count != 0)
    {
        updateCart(college, souvenir, count);
    }
    else
    {
        QSqlQuery *query = new QSqlQuery(myDB);

        if(myDB.open())
        {
            query->prepare("DELETE FROM Cart WHERE (college, souvenir) = (:college, :souvenir)");
            query->bindValue(":college", college);
            query->bindValue(":souvenir", souvenir);

            if(query->exec())
                qDebug() << "cart delete success!";
            else
                qDebug() << "cart delete failed!";
        }
    }
}

void Database::addPurchase()
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(myDB.open())
    {
        query->prepare("INSERT INTO Purchases SELECT * FROM Cart");

        if(query->exec())
            qDebug() << "added to purchases!";
        else
            qDebug() << "coudn't add to purchases!";
    }
}

void Database::resetCart()
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(myDB.open())
    {
        query->prepare("DELETE FROM cart");

        if(query->exec())
            qDebug() << "Delete cART!";
        else
            qDebug() << "coudln't delete cart!";
    }
}

void Database::addCart(const QString trip, const QString college, const QString souvenir, const double price, const int count)
{
   QSqlQuery *query = new QSqlQuery(myDB);

   if(myDB.open())
   {
       query->prepare("INSERT INTO Cart(tripID, college, souvenir, price, quantity) VALUES(:tripID, :college, :souvenir, :price, :quantity)");
       query->bindValue(":tripID", trip);
       query->bindValue(":college", college);
       query->bindValue(":souvenir", souvenir);
       query->bindValue(":price", price);
       query->bindValue(":quantity",count);

       if(query->exec())
           qDebug() << "purchase add success!";
       else
           qDebug() << "pruchase add failed!";
   }

}

void Database::addSouvenir(const QString &college, const QString &souvenirName, const double &cost)
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(!souvenirExists(souvenirName, college))
    {
        if(myDB.open())
        {
            query->prepare("INSERT INTO souvenirs(collegeName, souvenirName, cost) VALUES(:collegeName, :souvenirName, :cost)");
            query->bindValue(":collegeName", college);
            query->bindValue(":souvenirName", souvenirName);
            query->bindValue(":cost", cost);

            if(query->exec())
                qDebug() << "souvenir add success!";
            else
                qDebug() << "souvenir add failed!";
        }
    }
    else
    {
        qDebug() << "name exists!";
    }
}

void Database::updateCart(const QString college, const QString souvenir, const int count)
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(myDB.open())
    {
        query->prepare("UPDATE Cart SET (quantity) = (:quantity) WHERE (college, souvenir) = (:college, :souvenir)");
        query->bindValue(":college", college);
        query->bindValue(":souvenir", souvenir);
        query->bindValue(":quantity", count);

        if(query->exec())
            qDebug() << "UPDATE cart";
        else
            qDebug() << "UPDATE failed: " << query->lastError() << Qt::endl;
    }

}

void Database::updateSouvenir(const QString &souvenirName, const QString &college, const double &spin, const QString &newsouvenir)
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(myDB.open())
    {
        query->prepare("UPDATE souvenirs SET (souvenirName, cost) = (:newsouvenirName, :cost) "
                       "WHERE (collegeName, souvenirName) = (:collegeName, :souvenirName)");
        query->bindValue(":newsouvenirName", newsouvenir);
        query->bindValue(":collegeName", college);
        query->bindValue(":souvenirName", souvenirName);
        query->bindValue(":cost", spin);

        if(query->exec())
        {
            qDebug() << "UPDATE WORKED" << Qt::endl;
        }
        else
        {
            qDebug() << "UPDATE failed: " << query->lastError() << Qt::endl;
        }
    }
}

void Database::addUser(const QString &user, const QString &pass)
{
    QSqlQuery *query = new QSqlQuery(myDB);
    QString userVal = "User";

   if(!userExists(user))
   {
    if(myDB.open())
    {
        query->exec("CREATE TABLE Logins ("
                    "Username TEXT,"
                    "Password TEXT,"
                    "UserValue TEXT);");

        query->prepare("INSERT INTO Logins(Username, Password, UserValue) VALUES(:Username, :Password, :UserValue)");

        query->bindValue(":Username", user);
        query->bindValue(":Password", pass);
        query->bindValue(":UserValue", userVal);
        qDebug() << query->exec();
    }
   }

}

bool Database::souvenirExists(const QString &name, const QString &college)
{
    bool exists = false;

    QSqlQuery *checkQuery = new QSqlQuery(myDB);

    checkQuery->prepare("SELECT souvenirName FROM souvenirs WHERE (collegeName, souvenirName) = (:collegeName, :souvenirName)");
    checkQuery->bindValue(":souvenirName", name);
    checkQuery->bindValue(":collegeName", college);

    if(checkQuery->exec())
    {
        if(checkQuery->next())
        {
            exists = true;
            QString souvenirName = checkQuery->value("souvenirName").toString();
            QString college = checkQuery->value("collegeName").toString();
            qDebug() << souvenirName << " " << college;
        }
    }
    else
    {
        qDebug() << "souvenir exists failed: " << checkQuery->lastError();
    }

    return exists;
}

bool Database::userExists(const QString &user)
{
    bool exists = false;

    QSqlQuery *checkQuery = new QSqlQuery(myDB);

    checkQuery->prepare("SELECT Username FROM Logins WHERE (Username) = (:Username)");
    checkQuery->bindValue(":Username", user);

    if(checkQuery->exec())
    {
        if(checkQuery->next())
        {
                exists = true;
                QString userName = checkQuery->value("Username").toString();
                qDebug() << userName;
        }
    }
    else
    {
        qDebug() << "person exists failed: " << checkQuery->lastError();
    }

    return exists;
}

void Database::clearDb()
{
    QSqlQuery *deleteQuery = new QSqlQuery(myDB);

    deleteQuery->prepare("DROP TABLE IF EXISTS Colleges");

    deleteQuery->exec();

    deleteQuery->prepare("DROP TABLE IF EXISTS Distances");

    deleteQuery->exec();

    deleteQuery->prepare("DROP TABLE IF EXISTS souvenirs");

    deleteQuery->exec();

}

bool Database::isOpen() const
{
    return myDB.isOpen();
}

bool Database::checkAdmin(const QString &username) const
{
    bool admin = false;

    QSqlQuery *checkQuery = new QSqlQuery(myDB);

    checkQuery->prepare("SELECT UserValue FROM logins where (Username) = (:Username)");
    checkQuery->bindValue(":Username", username);

    if(checkQuery->exec())
    {
        if(checkQuery->next())
        {
            QString userVal = checkQuery->value("UserValue").toString();

            if(userVal == "admin")
            {
                admin = true;
            }
            qDebug() << admin;
        }
    }
    else
    {
        qDebug() << "Admin exists failed:";

    }

    if(admin)
    {
        qDebug() << "Admin";
    }

    return admin;
}

QString Database::getPassword(const QString &username) const
{
    QString password = "ksaflkzfsdjfsflkzfsjlkfxzjkjfklsz";
    QSqlQuery *getQuery = new QSqlQuery(myDB);
        getQuery->prepare("SELECT Password FROM logins WHERE (Username) = (:Username)");
        getQuery->bindValue(":Username", username);

        if (getQuery->exec())
        {
            if (getQuery->next())
            {
                password = getQuery->value("Password").toString();
                qDebug() << password;
            }
            else
            {
                qDebug() << "next query fail: " << getQuery->lastError();
            }
        }
        else
        {
            qDebug() << "person 1exists failed: " << getQuery->lastError();
        }

        return password;
}

void Database::addColleges(const QString &path)
{
    QSqlDatabase fileDB = QSqlDatabase::addDatabase("QODBC", "xlsx_connection");
    fileDB.setDatabaseName("DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" + path);

    if(fileDB.open())
    {
        qDebug() << "Excel connection successful" << Qt::endl;

        QSqlQuery *query = new QSqlQuery(fileDB);
        query->exec("select * from [" + QString("New Campuses") + "$A2:C47]");

        QSqlQuery * querytoDb = new QSqlQuery(myDB);
        QSqlQuery * querytoList = new QSqlQuery(myDB);

        while(query->next())
        {
            if(myDB.open())
            {
                qDebug() << "Database loading..." << Qt::endl;
                querytoDb->prepare("INSERT INTO Distances(startCollege, endCollege, distance) VALUES(:startCollege, :endCollege, :distance)");
                querytoList->prepare("INSERT OR REPLACE INTO Colleges(collegeName) values(:collegeName)");

                QString column1 = query->value(0).toString();
                QString column2 = query->value(1).toString();

                int column3 = query->value(2).toInt();

                querytoDb->bindValue(":startCollege", column1);
                querytoDb->bindValue(":endCollege",column2);
                querytoDb->bindValue(":distance",column3);
                qDebug() << querytoDb->exec();

                {
                    querytoList->bindValue(":collegeName",query->value(0).toString());
                    qDebug() << querytoList->exec();
                }
            }
        }
        fileDB.close();
    }
}

void Database::createTripTable()
{
    QSqlQuery *query = new QSqlQuery(myDB);
    QString userVal = "User";

    if(myDB.open())
    {
        query->exec("CREATE TABLE Trips ("
                    "tripID TEXT,"
                    "college TEXT,"
                    "tripProgress INT,"
                    "distanceToNext INT);");

        query->exec("CREATE TABLE Purchases ("
                    "tripID TEXT,"
                    "college TEXT,"
                    "souvenir TEXT,"
                    "price DOUBLE,"
                    "quantity INTEGER);");
    }
}

void Database::addTrip(QString tripID, QString plannedCollege, int index, int distanceTo)
{
    QSqlQuery *query = new QSqlQuery(myDB);

    if(myDB.open())
    {
        query->prepare("INSERT INTO Trips(tripID, college, tripProgress, distanceToNext) VALUES(:tripID, :college, :int, :distanceToNext)");

        query->bindValue(":tripID", tripID);
        query->bindValue(":college", plannedCollege);
        query->bindValue(":int", (index + 1));
        query->bindValue(":distanceToNext", distanceTo);
        qDebug() << query->exec();
    }
}

bool Database::tripIdExists(QString tripID)
{
    bool exists = false;

    QSqlQuery *checkQuery = new QSqlQuery(myDB);

    checkQuery->prepare("SELECT tripID FROM Trips WHERE (tripID) = (:tripID)");
    checkQuery->bindValue(":tripID", tripID);

    if(checkQuery->exec())
    {
        if(checkQuery->next())
        {
                exists = true;
        }
    }
    else
    {
        qDebug() << "trip id does not exist";
    }

    return exists;
}

Function Call to initialize the SQLite database from the excel file:
void Admin::onInitialise()
{
        myDb.clearDb();

        myDb.InitCollegeList(PROJECT_PATH + "/College_Campus_Distances_and_Souvenirs.xlsx");

        myDb.initsouvenirList(PROJECT_PATH + "/College_Campus_Distances_and_Souvenirs.xlsx");

        myDb.initDistanceList(PROJECT_PATH + "/College_Campus_Distances_and_Souvenirs.xlsx");

    updateColleges();
    updateSouvenirs();
}


text:
Q: How do I use the ShowLegends function to produce a legend for my framed graphic? I'm new to this site and new to Mathematica as you can see from my question. I'm also new to programming, btw.
I'm trying to produce a legend for my plot which I've coded as follows:
Needs["PlotLegends`"]
ds1 = {{0, 0.53}, {10, 1.00}, {20, 2.19}, {35, 3.61}};
ds2 = {{0, 0.52}, {10, 0.91}, {20, 1.97}, {35, 3.09}};
ds3 = {{0, ds1[[1, 2]] - ds2[[1, 2]]},
       {10, ds1[[2, 2]] - ds2[[2, 2]]},
       {20, ds1[[3, 2]] - ds2[[3, 2]]},
       {35, ds1[[4, 2]] - ds2[[4, 2]]}
      };
mf1 = LinearModelFit[ds1, x, x];
mf2 = LinearModelFit[ds2, x, x];
mf3 = LinearModelFit[ds3, x, x];
m1 = mf1["BestFit"]; m2 = mf2["BestFit"]; m3 = mf3["BestFit"];

Show[
  {
    ListPlot[{ds1, ds2, ds3},
       PlotMarkers -> Automatic, PlotStyle -> {Blue, Red, Orange}
    ],
    Plot[{m1, m2, m3}, {x, 0, 35}, PlotStyle -> {Blue, Red, Orange}]
  },
  Frame -> True,
  FrameLabel -> {"Time (min)","Inorganic Phosphate Concentration (mM)"},
  ImageSize -> {400, 300}
]

So, I'd like to use the ShowLegend function to have the legend displayed outside of the frame. I know that I can use the LegendPosition function to do this.
My problem, however, is the tags. How do I get the legend to show the names of the plots (ds1, ds2, ds3, m1, m2, and m3)?

A: Something like this?
ShowLegend[
 Show[{ListPlot[{ds1, ds2, ds3}, PlotMarkers -> Automatic,
    PlotStyle -> {Blue, Red, Orange}],
   Plot[{m1, m2, m3}, {x, 0, 35}, PlotStyle -> {Blue, Red, Orange}]},
  Frame -> True,
  FrameLabel -> {"Time (min)",
    "Inorganic Phosphate Concentration (mM)"}, ImageSize -> {500}],
 {{
   {Style["\[FilledCircle]", 12, Blue], "ds1"},
   {Style["\[FilledSquare]", 12, Red], "ds2"},
   {Style["\[FilledDiamond]", 12, Orange], "ds3"},
   {Graphics@{Blue, Line[{{0, 0}, {1, 0}}]}, "m1"},
   {Graphics@{Red, Line[{{0, 0}, {1, 0}}]}, "m2"},
   {Graphics@{Orange, Line[{{0, 0}, {1, 0}}]}, "m3"}
   }, LegendPosition -> {1, -0.4}}
 ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: searching using both "and" and "or" (sum-of-products or product-of-sums) I would like to do a search on stackoverflow for all questions tagged:
([concurrent] or [multithreading]) and ([c] or [c++])
I'd even be happy if I could do a search for
([c] or [c++]) and [multithreading].
But I can't figure out the syntax.
Edit: part of the problem (as pointed out be @Hugo) is that the box in the upper right corner that tells you what you queried doesn't parenthesize correctly.  Querying ([c] or [c++])[multithreading] is:question (which really returns the right thing) says it returns:

(which is the same picture you'll get if you query [c] or ([c++][multithreading])!
Edit 2: A second part of the problem is that the or operator seems to behave differently than the [or] operator.  Sometimes one works, sometimes not, sometimes the other.  A third part of the problem is that adding the is:question qualifier seems to dramatically change the results.  (See the comments below @Hugo's answer.)
I've tried
[multithreading]([c] or [c++]) (and ([c] or [c++]) [multithreading]) but get questions tagged [c] or ([c++] and [multithreading]).
I've tried
[multithreading]([c] [or] [c++]) bug got questions tagged ([multithreading] and [c]) or [c++].
I've tried
[c][multithreading] or [c++][multithreading] but get questions tagged
[multithreading] or ([c++] and [c] and [multithreading])???
On the other hand
[c][multithreading] [or] [c++][multithreading] seems to work but [c][multithreading] [or] [c++][multithreading] is:question returns nothing.
Even stranger querying [multithreading][c] or [multithreading][c++] gives questions tagged [c] or ([multithreading] and [multithreading] and [c++]) (yes, [multithreading] twice!)
How do I do a search that involves both "and" and "or" operators?  Is there a predictable syntax I should be using?

A: Searching [multithreading]([c] or [c++]) is:question does work. But it does need the is:question else the search results are completely non-relevant.
Here are some results (in the search) that I found that corresponds to borderline cases :

*

*c++ and multithreading

*c and multithreading

*c and c++ and multithreading
I think these covers all the possible case of what you wanted.

([concurrent] or [multithreading])([c] or [c++]) is:question seems to work as expected also. (With the is:question only, else it does not work.)

Your parenthesis are wrong I think. It's written [c] or [c++][multithreading] which seems to mean ([c] or [c++])[multithreading]. The ORs seem to have precedence over the ANDs (in the UI)
When you put this ([concurrent] or [multithreading])([c] or [c++]) it outputs [concurrent] or [multithreading][c] or [c++]. And the precedence goes to ORs, as you can see because of the search results covering all possible cases.


text:
Q: regular expressions - my expression I've got (To) [a-z]+ as regular expression and I've got sentence: To kot dziki pies.
And If I compile it I will retrieve To kot.
So what can I do to retrieve only word after (only kot) "To" instead of "To kot"?

A: ^To (\w+)$ should do the trick. \w is shorthand for any word character, eg. a-z in English; other characters in other languages. If you put parens around To as in your example, it will create a matched group, which means the match for [a-z]+ will be in the second group, and To will be in the first group.
I can really recommend using an interactive tool for testing and developing regular expression, such as Expresso.

A: use groups inside the regular expression -
"To ([a-z]+)" and then retrieve group 1's value, it will contain "kot" supplied your example string.

A: Or you could use lookbehinds:
(?<=To )[a-z]+
Then the To does not become part of the captured expression.


text:
Q: Run application as user I want to give user to run  citix workspace application only and rest everything deny permission for any changes to system.
I had installed app and running in startup and able to run application properley.
But i want to give user to run this app only not anything else he can modify in operating system .


text:
Q: Where is the operator precedence documented for the .NET Regex class? Where is the order of operator precedence documented for the .NET Regex class?
I see this, but that's for JScript.
Also, it appears this is not affected by RegexOptions.ECMAScript, but confirmation would be helpful.

A: I don't think the real answer is as simple as you'd like. The short (and incomplete) answer is simply "all expressions are evaluated left to right" ...
For the long answer go here.
http://msdn.microsoft.com/en-us/library/e347654k.aspx

The .NET Framework regular expression engine is a backtracking regular
  expression matcher that incorporates a traditional Nondeterministic
  Finite Automaton (NFA) engine ... traditional NFA engines perform
  pattern matching, their processing order is driven by the regular
  expression pattern. As it processes a particular language element,
  the engine uses greedy matching; that is, it matches as much of the
  input string as it possibly can. But it also saves its state after
  successfully matching a subexpression. If a match eventually fails,
  the engine can return to a saved state so it can try additional
  matches.

Edit: Forgot to answer the second part of your question.
With regard to RegexOptions.ECMAScript, you can reference these docs:
http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx

The behavior of ECMAScript and canonical regular expressions differs
  in three areas: character class syntax, self-referencing capturing
  groups, and octal versus backreference interpretation.

It doesn't look like "order" is affected, but there could be other issues. The docs do a good job of illustrating the differences.

A: This was asked a long time ago, but not answered.
The .Net regex operator precidence is defined at the bottom of the Regular Expression Syntax page 1.


text:
Q: show only decimal value in floating point number using sprintf I'm been trying to get only decimal point value of a floating point number here are my sceanrio
21.95 => .95

22.00 => .00

I try do it using following regex

\.\d{2}

I even had other solution
number = 21.96.round(2)

precision = number - number.to_i

Or
"." + number.to_s.split('.')[1]

But I'm just not able to find it via sprintf which is what I want

A: You can only get the decimal part using the module function. Here is a solution using sprintf
a = 1001.123123
sprintf("%.2f", a.modulo(1))
# prints 0.12

Without sprintf,
a = 1001.123123
puts a.modulo(1).round(2)
# prints 0.12

Related question to get the fraction part here and more about the modulo function here.

A: I think its best to approach this problem from a char point of view.
First convert your double to an array of chars, then check each character if the value of that character  is a ".".
Next you just put the following characters into a string and output these in sprintf.


text:
Q: Optimize search of duplicate n-uplets between two tables I want to calculate a duplicate n-uplets between two tables (without association).
Suppose that we have two tables :
Table A : (firstname, lastname, email ...)
N-uplets:
TOTO/ TOTO/ TOTO@test.com ...
TITI/ TITI/ TITI@test.com ...
Table B : (firstname, lastname, email ...)
N-uplets:
TOTI/ TOTI/ TOTO@test.com ...
TITI/ TITI/ TATI@test.com ...
My request should get TOTO and TITI from table A.
   $query = $this->createQueryBuilde('a');
   $query
       ->innerJoin(B::class, 'b',
                  'with',
                   "(a.lastName = b.lastName AND a.firstname = b.firstName)
                    OR a.email = b.email"
        )
   ;

This request works, but I have 10k n-uplets in Table A and 40k in table B. The execution is slow :/
Any idea to optimize it ?
Thanks in advance :)

A: You need some indexes. Since you have an OR condition I would create two indexes:
create index ix1 on tableb (lastname, firstname);

create index ix2 on tableb (email);

The OR condition requires two scans.


text:
Q: Power Automate Flow Error with Access Denied (Creating sharing link) I've created a flow to manage data input into various sharepoint lists as well file uploads. The trigger is an MS Form and this has been working well for a couple of months. Today for some reason it was run however it failed stating access denied when creating a sharing link.
Since the last time it was run successfully, there has been zero changes to the flow, the sharepoint Lists or Folders. The only update has been the addition of a view and another flow for a different process.
I've checked through the permissions and the flow is run from my account and I have full access to the sharepoint site. I've tried to manually create a share link but there is no issues.
Does anyone have any guidance on what to check to correct this issue?

Unsure whether the below raw output will be helpful?
{
"statusCode": 403,
"headers": {
    "Pragma": "no-cache",
    "X-SharePointHealthScore": "1",
    "X-SP-SERVERSTATE": "ReadOnly=0",
    "ODATA-VERSION": "4.0",
    "SPClientServiceRequestDuration": "114",
    "SPRequestGuid": "9042f985-3113-42da-94c5-19853be88dc3",
    "request-id": "9042f985-3113-42da-94c5-19853be88dc3",
    "MS-CV": "hflCkBMx2kKUxRmFO+iNww.0",
    "Strict-Transport-Security": "max-age=31536000",
    "X-FRAME-OPTIONS": "SAMEORIGIN",
    "Content-Security-Policy": "frame-ancestors 'self' teams.microsoft.com *.teams.microsoft.com *.skype.com *.teams.microsoft.us local.teams.office.com *.powerapps.com *.yammer.com *.officeapps.live.com *.stream.azure-test.net *.microsoftstream.com;",
    "MicrosoftSharePointTeamServices": "16.0.0.21010",
    "X-Content-Type-Options": "nosniff",
    "X-MS-InvokeApp": "1; RequireReadOnly",
    "Timing-Allow-Origin": "*",
    "x-ms-apihub-cached-response": "true",
    "Cache-Control": "no-cache",
    "Date": "Thu, 25 Feb 2021 13:54:59 GMT",
    "P3P": "CP=\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\"",
    "X-AspNet-Version": "4.0.30319",
    "X-Powered-By": "ASP.NET",
    "Content-Length": "84",
    "Content-Type": "application/json",
    "Expires": "-1"
},
"body": {
    "error": {
        "code": "accessDenied",
        "message": "Access denied"
    }
}

A: Have you tried recreating your SharePoint connector connection? I have seen some issues when security setting such as Multi Factor Authentication are applied to an account used in Power Automate, Flows.


text:
Q: My atom packages are not providing me error highlighting for Elm I have installed several packages to get error highlighting among other things these worked on my Windows computer but I can't get it to work on my new Mac from work.
I am using Elm 0.18 and have the following packages
busy-signal
elm-format
intentions
language-elm (with elm-oracle)
linter
linter-elm-make
linter-ui-default
minimap

I will be honest I am not 100% sure which one of those packages should highlight my errors I was following a guide from a video in order to know which packages to install.


text:
Q: Image lazy loader for FTScroller (AngularJS) For my project I'm using ng-FTScroller (https://github.com/ftlabs/ftscroller) and I would also like to implement an image lazy loader module.
I've tried the few I've found, but they work with the body (or window) and I'm not able to use them with the FTScroller DIV (in my case it contains the ng-view).

A: You might be able to use this library: https://github.com/GeneralElectric/winchjs
It listens on both scroll and animation events to recheck if a image is with in the view port (or close to) and trigger it to load.  You can also choose to trigger a manual recheck after a ngRouteChange event.


text:
Q: How to print Arabic and English text together using Python's fpdf library pdf.multi_cell(w=150, h=5, txt="تمانتمانتمانتمانتم English Letters")

"English Letters" is rendered as a row of rectangles in the output:

I also tried using arabic_reshaper
Example code snippet:
import arabic_reshaper
from bidi.algorithm import get_display
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
pdf.set_xy(9, 132)
pdf.multi_cell(w=150, h=5, txt=bidi_text)

...but it didn't work. Are there any other possible ways to make it work?

A: The maintainer of the FPDF library answered my question in respective discussion forum
checkout the solution and the desired outcome attached in the post: https://github.com/PyFPDF/fpdf2/discussions/583


text:
Q: Parsing string/ISO 8601 Date I am looking for a way to parse multiple string formats to dates/datetime. the  as_datetime() functions works very well for my purposes for the first 3 below, but not the fourth. Any suggestions?
library(lubridate)
as_datetime("20200603", tz = "America/New_York")
as_datetime("20200603231413", tz = "America/New_York")
as_datetime("20200603231413-0400", tz = "America/New_York")
as_datetime("20200528203000+0000", tz = "America/New_York")

>   as_datetime("20200603", tz = "America/New_York")
[1] "2020-06-03 EDT"

>   as_datetime("20200603231413", tz = "America/New_York")
[1] "2020-06-03 23:14:13 EDT"

>   as_datetime("20200603231413-0400", tz = "America/New_York")
Date in ISO8601 format; converting timezone from UTC to "America/New_York".
[1] "2020-06-03 23:14:13 EDT"

>   as_datetime("20200528203000+0000", tz = "America/New_York")
[1] NA
Warning message:
All formats failed to parse. No formats found.

>   as_datetime("20200528203116+0000", tz = "America/New_York")
[1] NA
Warning message:
All formats failed to parse. No formats found.

A: You can provide more formats with format=, and in this case add %z, which ?strptime defines as
     '%z' Signed offset in hours and minutes from UTC, so '-0800' is 8
          hours behind UTC. Values up to '+1400' are accepted.
          (Standard only for output.  For input R currently supports it
          on all platforms.)

library(lubridate)
as_datetime("20200603231413-0400", format = "%Y%m%d%H%M%S%z", tz = "America/New_York")
# [1] "2020-06-03 23:14:13 EDT"
as_datetime("20200628203000+0000", format = "%Y%m%d%H%M%S%z", tz = "America/New_York")
# [1] "2020-06-28 16:30:00 EDT"
as_datetime("20200528203116+0000", format = "%Y%m%d%H%M%S%z", tz = "America/New_York")
# [1] "2020-05-28 16:31:16 EDT"


text:
Q: XSD questions: abstracts and polymorphic documents I'm working a project (assigned to me by a "pointy-haired manager"), and I've run into two things that are stumping me.
I have read a number of articles both here and on w3schools - still confused.  I think I need a practical example.
I am including a significantly pared-down & obfuscated version of the XSD that I am desperately trying to get to "validate".
Problem #1 has to do (I think) with using 'abstract/substitutionGroup' - not very clear to me.  What I need is for the 3 variant groups to have the same node-name (in this example "zzzResult").
Problem #2 has to do with polymorphism.  I need to add special "markers" to indicate the begin/end of some external operation (using XPath & JS) plus a special node of data BASED on the main document attribute named "hash" (or rather the value of its enums).
Can someone provide a 'corrected' version that will work?

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<!-- payload containers -->

  <xsd:element name="thePayload" type="xsd:string"/>

  <xsd:element name="md5">
    <xsd:simpleType>
      <xsd:restriction base="xsd:hexBinary">
        <xsd:pattern value="[0-9A-Fa-f]{32}"/>
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:element>

  <xsd:element name="sha1">
    <xsd:simpleType>
      <xsd:restriction base="xsd:hexBinary">
        <xsd:pattern value="[0-9A-Fa-f]{40}"/>
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:element>

<!-- markers -->

  <xsd:element name="zzzBegin"><xsd:complexType/></xsd:element>
  <xsd:element name="zzzEnd"><xsd:complexType/></xsd:element>

<!-- constructs -->

  <xsd:element name="theHeading">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="thePayload" maxOccurs="8"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

  <xsd:element name="theDetails">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="thePayload" maxOccurs="64"/>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>

<!-- groups -->

  <xsd:group name="_none">
    <xsd:sequence>
      <xsd:element ref="theHeading"/>
      <xsd:element ref="theDetails"/>
    </xsd:sequence>
  </xsd:group>

  <xsd:group name="_md5">
    <xsd:sequence>
      <xsd:element ref="zzzBegin"/>
      <xsd:element ref="theHeading"/>
      <xsd:element ref="theDetails"/>
      <xsd:element ref="zzzEnd"/>
    <!-- problem #1) [abstract?] ambiguous name -->
      <xsd:element name="zzzResult">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="md5"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:group>

  <xsd:group name="_sha1">
    <xsd:sequence>
      <xsd:element ref="zzzBegin"/>
      <xsd:element ref="theHeading"/>
      <xsd:element ref="theDetails"/>
      <xsd:element ref="zzzEnd"/>
    <!-- problem #1) [abstract?] ambiguous name -->
      <xsd:element name="zzzResult">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="sha1"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:group>

  <xsd:group name="_both">
    <xsd:sequence>
      <xsd:element ref="zzzBegin"/>
      <xsd:element ref="theHeading"/>
      <xsd:element ref="theDetails"/>
      <xsd:element ref="zzzEnd"/>
    <!-- problem #1) [abstract?] ambiguous name -->
      <xsd:element name="zzzResult">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="md5"/>
            <xsd:element ref="sha1"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:sequence>
  </xsd:group>

<!-- XML DOCUMENT -->

  <xsd:element name="theDocument">
    <xsd:complexType>

 <!-- problem #2) [polymorphic?] choose based on enum-value of attrib "hash" -->
      <xsd:choice>
        <xsd:group ref="_none"/>
        <xsd:group ref="_md5"/>
        <xsd:group ref="_sha1"/>
        <xsd:group ref="_both"/>
      </xsd:choice>

      <xsd:attribute name="hash" default="none">
        <xsd:simpleType>
          <xsd:restriction base="xsd:NMTOKEN">
            <xsd:enumeration value="none"/>
            <xsd:enumeration value="md5"/>
            <xsd:enumeration value="sha1"/>
            <xsd:enumeration value="both"/>
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:attribute>

    </xsd:complexType>
  </xsd:element>

Here's what I need the variant forms to look like:

<theDocument hash="none">
  <theHeading>
    <thePayload>some data here (occurs 1:8)</thePayload>
  </theHeading>
  <theDetails>
    <thePayload>more data here (occurs 1:64)</thePayload>
  </theDetails>
</theDocument>

<theDocument hash="md5">
 <zzzBegin/>
  <theHeading>
    <thePayload>some data here (occurs 1:8)</thePayload>
  </theHeading>
  <theDetails>
    <thePayload>more data here (occurs 1:64)</thePayload>
  </theDetails>
 <zzzEnd/>
  <zzzResult>
    <md5>0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a</md5>
  </zzzResult>
</theDocument>

<theDocument hash="sha1">
 <zzzBegin/>
  <theHeading>
    <thePayload>some data here (occurs 1:8)</thePayload>
  </theHeading>
  <theDetails>
    <thePayload>more data here (occurs 1:64)</thePayload>
  </theDetails>
 <zzzEnd/>
  <zzzResult>
    <sha1>3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e</sha1>
  </zzzResult>
</theDocument>

<theDocument hash="both">
 <zzzBegin/>
  <theHeading>
    <thePayload>some data here (occurs 1:8)</thePayload>
  </theHeading>
  <theDetails>
    <thePayload>more data here (occurs 1:64)</thePayload>
  </theDetails>
 <zzzEnd/>
  <zzzResult>
    <md5>0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a</md5>
    <sha1>3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e</sha1>
  </zzzResult>
</theDocument>

A: There is no way to correct your XSD 1.0 while maintaining the given set of tags and constraints because of the Unique Particle Attribution limitation.
XSD 1.1 - the most recent version of the XSD spec - provides all the mechanisms you need to enforce your model's constraints the way you want.
If XSD 1.1 is not an option, Schematron markup on top of XSD 1.0 would allow you to relax some of the constraints in your current XSD which would allow one to reconfigure your content models to avoid the UPA issue, yet maintain the constraints. Specifically, you can start by having one  zzzResult where md5 and sha1 are both present and optional; then you'll end up with only two groups (as per your current approach), _none and something else.
In the spirit of SO, I would kindly ask you to consider the above as leads to go back and try new things considering your options; and if you're still getting into issues, come back here with new details.


text:
Q: Remove WordPress theme from a specific page There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages.
Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it?

A: There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on public_html/your_site, now you want to create an HTML page that is on your_site.com/mypage, so instead of creating a page or post called mypage on your WordPress dashboard you are going to create a mypage.html and upload it to public_html/your_site, in case you want to get rid of the .html you can simply hide it from your .htaccess doing something like:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Keep in mind any tracking code you have on your WordPress, for example, Google Analytics, if you are using things like that you will have to add those codes to your HTML page as well.

A: Just make a directory on the highest level and put your html file there. If you call it directly, you will bypass WordPress. Beware that this also means the file won't be found using WP's search function. Basically, for WP, it will be an external page.


text:
Q: grok query difference check syntax [event] 02/05 09:20:01.8 PM message description
[event] 10/26 09:42:27.0 AM message description
How to different timestamp in grok syntax?
grok syntax timestamp for two query difference time


text:
Q: Is there an application that can fake permanent delete I'm just thinking about this, is there an application that can fake permanent delete of a file. For example, you press shift+del on the keyboard. And the file is permanently deleted. Is there an application that makes it look like it has been deleted. Or is there an application that can recover these files that are permanently deleted using shift+delete

A: "fake delete": move it to some folder of your choice. the normal delete does this by choosing the "trash"-folder.
there are applications which can recover "shift-delete", as long as the bits on the disk are not yet overwritten ('recuva') for example


text:
Q: WP7 - drag/drop of objects created from a DataTemplate within Canvas At a glance:
My app displays an ItemsControl containing a Canvas as its ItemsPanel. The ItemsControl is bound to a collection of objects, each having Left/Top/Width/Height properties. A DataTemplate is used to generate rectangles that are rendered in the Canvas and positioned correctly (binding on the Left and Top properties).
How can I implement drag/drop to move these rectangles around the Canvas?

Background for my question:
My WP7 app displays a "CanvasItemsControl" defined as follows:
public class CanvasItemsControl : ItemsControl
    {
        public string XBindingPath { get; set; }
        public string YBindingPath { get; set; }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            FrameworkElement contentitem = element as FrameworkElement;
            if (XBindingPath != null && YBindingPath != null)
            {
                Binding xBinding = new Binding(XBindingPath);
                Binding yBinding = new Binding(YBindingPath);
                if (contentitem != null)
                {
                    contentitem.SetBinding(Canvas.LeftProperty, xBinding);
                    contentitem.SetBinding(Canvas.TopProperty, yBinding);
                }
            }
            base.PrepareContainerForItemOverride(element, item);
        }
    }

and used in XAML as follows:
<hh:CanvasItemsControl Grid.Row="1" x:Name="TheItemsControl"
   Style="{StaticResource CanvasItemsControlStyle}"
   ItemsSource="{Binding AllObjects}"
   XBindingPath="Left" YBindingPath="Top" />

This is the style for the CanvasItemsControl:
<Style x:Key="CanvasItemsControlStyle" TargetType="local:CanvasItemsControl">
        <Setter Property="ItemTemplate" Value="{StaticResource ObjectTemplate}"/>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
</Style>

And this is the DataTemplate I use to render my class:
    <DataTemplate x:Key="ObjectTemplate"  >
        <Border Background="{Binding Brush}"
                Width="{Binding Width}"
                Height="{Binding Height}">
            <TextBlock Text="{Binding Description}"/>
        </Border>
    </DataTemplate>

The source of the CanvasItemsControl is a collection of objects that have the properties Left, Top, Width, Height, Brush, etc.
My question
As you can see, the end result is, as you add items to the AllObjects collection, each object gets rendered and positioned correctly in the canvas. Now I need to drag/drop/move these objects around the canvas. What approach would you advise me to use to implement drag/drop? Can you please guide me through the process?
Thank you

A: Here's the solution to my question (at least the best one in my opinion):
1) Use of a regular Canvas as opposed of a custom control inherited from Canvas.
2) Use of a user control taking the data context (the instance of my business entity) via constructor
3) The binding between the Left/Top properties of my business class and the Canvas.Left/Top is declared at the UserControl level.
4) Use of a custom behavior inheriting from System.Windows.Interactivity.Behavior. This behavior is attached to the User Control.

I would like to acknowlege Calvin Schrotenboer and Joe Gershgorin for their immense help.
<!--____ The UserControl ____-->
   <UserControl...      Canvas.Left={Binding Left}" Canvas.Top={Binding Top}">
      <Grid.... layout of the UserControl instead of using a DataTemplate/>
      <i:Interaction.Behaviors>
         <MyExample:MyMouseDragElementBehavior/>
      </i:Interaction.Behaviors>
   </UserControl>

The custom behavior:
public class MyMouseDragElementBehavior : Behavior<FrameworkElement>
{
    public event MouseEventHandler DragBegun;
    public event MouseEventHandler DragFinished;
    public event MouseEventHandler Dragging;

    private Point relativePosition;

    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register("IsEnabled", typeof(bool), typeof(MyMouseDragElementBehavior), new PropertyMetadata(true));

    public bool IsEnabled
    {
        get
        {
            return (bool)GetValue(IsEnabledProperty);
        }
        set
        {
            SetValue(IsEnabledProperty, value);
        }
    }

    protected override void OnAttached()
    {
        AssociatedObject.AddHandler(
            UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnMouseLeftButtonDown), false);
        base.OnAttached();
    }

    protected override void OnDetaching()
    {
        AssociatedObject.RemoveHandler(
            UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnMouseLeftButtonDown));
        base.OnDetaching();
    }

    private static int zIndex = 0;

    private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (!IsEnabled)
        {
            return;
        }
        zIndex++;
        Canvas.SetZIndex(AssociatedObject, zIndex);

        StartDrag(e.GetPosition(AssociatedObject));
        if (DragBegun != null)
        {
            DragBegun(this, e);
        }
    }

    private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        AssociatedObject.ReleaseMouseCapture();
    }

    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        HandleDrag(e.GetPosition(AssociatedObject));
        if (Dragging != null)
        {
            Dragging(this, e);
        }
    }

    internal void HandleDrag(Point newPositionInElementCoordinates)
    {
        double x = newPositionInElementCoordinates.X - relativePosition.X;
        double y = newPositionInElementCoordinates.Y - relativePosition.Y;

        if (AssociatedObject != null)
        {
            var currentLeft = Canvas.GetLeft(AssociatedObject);
            var currentTop = Canvas.GetTop(AssociatedObject);
            Canvas.SetLeft(AssociatedObject, currentLeft + x);
            Canvas.SetTop(AssociatedObject, currentTop + y);
        }
    }

    internal void StartDrag(Point positionInElementCoordinates)
    {
        relativePosition = positionInElementCoordinates;
        AssociatedObject.CaptureMouse();
        AssociatedObject.MouseMove += OnMouseMove;
        AssociatedObject.LostMouseCapture += OnLostMouseCapture;
        AssociatedObject.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(OnMouseLeftButtonUp), false);
    }

    internal void EndDrag()
    {
        AssociatedObject.MouseMove -= OnMouseMove;
        AssociatedObject.LostMouseCapture -= OnLostMouseCapture;
        AssociatedObject.RemoveHandler(
            UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(OnMouseLeftButtonUp));
    }

    private void OnLostMouseCapture(object sender, MouseEventArgs e)
    {
        EndDrag();
        if (DragFinished != null)
        {
            DragFinished(this, e);
        }
    }
}


text:
Q: How could I display the selected category name of a dropdown list I have a dropdown category lists from taxonomy, how could I display the selected category name inside the dropbox when it's selected/ active?
here is dropdown category code bellow:
<select id="categ" name="categ">
   <div class="options">
      <option value="<?php echo home_url('/newsletter'); ?>" selected>一覧</option>
   <?php
      $args = array(
      'orderby' => 'slug',
      'order' => 'ASC',
      'parent' => 0,
      'hide_empty' => false
      );
    $terms = get_terms([
       'taxonomy' => 'pdf_cat',
       'hide_empty' => false,
      ]);
    foreach( $terms as $term ){
      echo '<option class="ctg" value="'. get_term_link($term->term_id) .' ">' . $term->name . '</option>';
       }
     ?>
    </div>
</select>

JS code when URL fired:
<script type="text/javascript">
  $("#categ").change(function(){
    var url = $(this).val();
    location.assign(url);
    });
</script>


text:
Q: Override default CSS classes using WTForms' render_kw() In a Flask app with the Bootstrap-Flask extension, how would one override the default style   using WTForms' render_kw class parameter when the form's HTML is automatically rendered using render_form()? [*]
I have this simple Form defined that provides a button to confirm the deletion of a database record, and I'd like that button to be red instead of the standard grey color:
class DeleteMappingForm(FlaskForm):
    submit = SubmitField(_l('Delete mapping'))

The auto-generated HTML (focusing just on the <input> element) is:
<input class="btn btn-secondary btn-md" id="submit" name="submit" type="submit" value="Delete mapping">

I'd like to use the btn-alert instead of the default btn-secondary Bootstrap class to display the button in red instead of grey.
The WTForms way of defining "keywords that will be given to the widget at render time" is to pass those as a dict in render_kw. That works fine to add new keywords, but it doesn't replace  existing, which I tried doing like this:
class DeleteMappingForm(FlaskForm):
    submit = SubmitField(_l('Delete mapping'), render_kw={'class':'btn btn-alert btn-md'})

That ends up adding the CSS classes I defined to the list of pre-defined CSS classes, ending up with this HTML:
<input class="btn btn-secondary btn-md btn btn-alert btn-md" id="submit" name="submit" type="submit" value="Delete mapping">

Is there a way to have the values passed via render_kw to override the default classes, and have just class="btn btn-alert btn-md"?
Extra information
Looking at how render_kw is handled by WTForms, it seems the values should be overriden (dict gets concatenated, which overrides the same keys, eg.:
>>> a={"class":"abc", "other":"aaa"}
>>> a
{'class': 'abc', 'other': 'aaa'}
>>> b={"class":"def", "other":"aaa"}
>>> b
{'class': 'def', 'other': 'aaa'}
>>> dict(a, **b)
{'class': 'def', 'other': 'aaa'}

I couldn't also identify a source of this in Bootstrap-Flask's handling of render_form()...
[*] I'm using the Bootstrap-Flask extension instead of the original Flask-Bootstrap because the latter unfortunately doesn't support Bootstrap 4+. render_form() is the Bootstrap-Flask equivalent of Flask-Bootstrap's quick_form().

A: Turns out the solution is to be found on the side of Bootstrap-Flask, and that it already provides a button_style parameter to the render_form macro, allowing to pass a Bootstrap class directly.
The following template gets me that red button I was looking for ;) As easy as that...
{% extends "base.html" %}
{% import 'bootstrap/form.html' as wtf %}

{% block app_content %}

{{ title }}

            {{ wtf.render_form(form, button_style="danger") }}

{% endblock %}

Well, that is kind of embarrassing - but I'm happy nonetheless to have found the solution, too bad for the time spent writing up this question, but as this might help others with the same challenge I'm adding my answer here.


text:
Q: Present SFSafariViewController from not rootController swift I have UINavigationController, firstViewController (rootController for navigationController), secondViewController and SFSafariViewController.
If I present SFSafariViewController from firstViewController, it shown correctly and load page successfully. But, if I move to secondViewController, and try to present SafariViewController, I see only white window.
I tried to present SFSafariViewController from:
override func viewDidAppear(animated: Bool)

And I tried to present SFSafariViewController by touch on button and had same result.
The code for show SFSafariViewController:
let urlString:String = "https://google.com"
let url = NSURL(string:urlString)!
let svc = SFSafariViewController.init(URL: url)
self.navigationController?.presentViewController(svc, animated: true, completion: nil)


text:
Q: Trace entropies I'm studying relationships between trace entropy functionals and combinatorics and I'm faced with the following problem. Lets $\mathcal {D}$ be the following differential operator $1 -x\cdot \cfrac{d}{dx}$ i.e. $\mathcal {D} g = g - x\cdot g'$.
For $m\ge 0$ integer, if $\Phi_m(x) := x\cdot \log(x)^m$ then $\mathcal {D} \Phi_m(x) = -m\cdot \Phi_{m-1}(x)$ and, (at least formally) for a function $g$ we can write
$g(x) = \sum\limits_{m\ge 0} g_m \cdot \Phi_m(x)$ where $$g_m = \cfrac{(-1)^m}{m!}\cdot \mathcal {D}^m g(x) |_{x=1}\;.$$
I am trying to figure out what kind of functions $g(x)$ can satisfy the following conditions on $(0;1]$
I) $g(x) \ge 0$, $g(0)=0$.  (Positivity)
II) $\mathcal {D}^2 g(x) \le 0$. (some sort of $\mathcal {D}$-concavity)
III) $\left(\mathcal {D}^2 - \mathcal {D}\right) g(x) \le 0$   (this is standard concavity expressed with the operator $\mathcal {D}$
IV) $\exists \ 0< \varepsilon \le 1$ such that $g(x) > -x^2\cdot \log(x) \quad \forall \ x \in (0;\varepsilon)$
V) $\exists \ a \in (0;\frac{1}{2}]$ such that $$g(a)+g(1-a) = -a\cdot \log(a) -(1-a)\cdot \log(1-a).$$
If we impose only conditions I),II) and III) there are a lot of functions satisfying them, but

*

*adding IV) I'm not able to find any function except of the following form  $g(x) = k\cdot x \cdot \log(x), \ k$ real constant (here $\varepsilon=1$). Note that $g$ do not satisfy V).

*adding IV) and V) I'm not able to find any other function except the Boltzman-Gibbs-Shannon entropy trace :  $-x\cdot \log(x)$
I "fear" that the Boltzman-Gibbs-Shannon entropy trace is the unique function satisfying I)-V).
Thanks in advance for any point of view.

A: For any $c\in(0,\log2]$, the function $g$ defined by the formula $g(x)=cx$ for $x\in[0,1]$ satisfies your conditions I)–V), but it is not the Boltzman–Gibbs–Shannon entropy trace.

There are many more functions $g$ satisfying your conditions I)–V) that are not the Boltzman–Gibbs–Shannon entropy trace. In particular, for any $c_1\in(0,\log2)$, any nonnegative continuous function $H$ on $[0,1]$, and any small enough real $c_2\ge0$ and $c_3\ge0$, the function $g$ defined by the formula
$$g(x)=c_1x-c_2 x\log x-c_3 x\int_0^x du\,H(u)\log\frac xu$$
for $x\in[0,1]$ satisfies your conditions I)–V), but it is not the
Boltzmann–Gibbs–Shannon entropy trace.


text:
Q: Splitting numeric column data by given number of characters I am trying to split one column into three columns so I can give a date format.
Currently the data set looks like this
YYYYMMDD         Number
20020101         0.21
20020102         0.34
20020103         1.22

I want it to look like this
Year    Month  Day  Number
2002    01     01   0.21
2002    01     02   0.34
2002    01     03   1.22

I have the following code written and it works in the sense that i can split up the column, but in doing so I create new data frames and I am unsure how to then add back in the data.frame to the original data.set

*

*dataset=data

Is there a nicer way to do it? or how to do I get new2 + new to combine with data?
res <- strsplit(data$YYYYMMDD, "(?<=.{4})" , perl = TRUE)
new<-do.call(rbind, res)
summary(new)
colnames(new)<-c("Year", "MMDD")
new<-as.data.frame(new)
new$MMDD<-as.character(new$MMDD)
res <- strsplit(new$MMDD, "(?<=.{2})" , perl = TRUE)
new2<-do.call(rbind, res)
summary(new2)
colnames(new2)<-c("Month", "Dom")
new2<-as.data.frame(new2)

A: With substring:
x <- mapply(substring, c(1, 5, 7), c(4, 6, 8),
            MoreArgs = list(text = df$YYYYMMDD), SIMPLIFY = F)
names(x) <- c('Year', 'Month', 'Day')
cbind(as.data.frame(x), df[-1])
#   Year Month Day Number
# 1 2002    01  01   0.21
# 2 2002    01  02   0.34
# 3 2002    01  03   1.22

A: We can do this easily with separate
library(tidyr)
separate(df1, YYYYMMDD, into = c('Year', 'Month', 'Day'), sep=c(4, 6))
#   Year Month Day Number
#1 2002    01  01   0.21
#2 2002    01  02   0.34
#3 2002    01  03   1.22

A: You can try this (with your variable YYYYMMDD as character):
year = substr(data$YYYYMMDD,1,4)
month = substr(data$YYYYMMDD,5,6)
day = substr(data$YYYYMMDD,7,8)

new_data = as.data.frame(cbind(year,month,day,data$Number))
colnames(new_data)[4] = "Number"

A: You can do it with lubridate like so:

library(tidyverse)
library(lubridate)

data %>%
  mutate(
    YYYYMMDD = as.Date(as.character(YYYYMMDD), format = "%Y%m%d"),
    year = year(YYYYMMDD),
    month = month(YYYYMMDD),
    day = mday(YYYYMMDD)
    )
#>     YYYYMMDD Number year month day
#> 1 2002-01-01   0.21 2002     1   1
#> 2 2002-01-02   0.34 2002     1   2
#> 3 2002-01-03   1.22 2002     1   3


text:
Q: Person Life Event I am working on life Events in FSC.I have installed Finserv managed packag.
In my sandbox org I see Personal Life Events object, while in dev I see
FinServ__LifeEvent__c.how can i Enable personal Life events.does anyone have any idea.

A: well my api versions were different in both th orgs thats why i was not able to do it.person life event is part of new release


text:
Q: Use of Index and Match function with Count/Counta/Countif to count the results on a 3rd wookbok I have great success in guidance from the experts on Stack. I need guidance once more. :)
I have workbook 1 that has a copy of names on column A and email addresses on column B. Workbook 2 that has copy of names on A and email addresses on column B and data that I need copied on Column c on workbook 2.
I have a workbook 3 in which I would like to use to build a table with matched and counted from the formula I need. Below I will show.
workbook 1 pic:

Workbook 2 pic:

Workbook 3 pic:

Ultimately, I wanted the index,matched and counted total to show up on the basic table shown on workbook 3. As you can see there are 4 email addresses that match between work book 1 and workbook 2, but there are also 4 email addresses that do not match. after the matching and unmatching is found, i want the formula to give me the count of the matched and unmatched from column c in workbook 2.
so if you just use your eyes and count, you will see that rows 2 through 4 these email addresses matched between work book 1 and work book 2. that would give me a total of 2 drinks expenses and 2 food expenses from the matching found, but also give me 2 tickets expenses and 2 parking expenses from the unmatched found.

A: For the Matched:
=SUMPRODUCT((COUNTIFS('Sheet1'!A:A,'Sheet2'!$A$2:$A$100,'Sheet1'!B:B,'Sheet2'!$B$2:$B$100)>0)*('Sheet2'!$C$2:$C$100=$B3))

For the unMatched
=SUMPRODUCT((COUNTIFS('Sheet1'!A:A,'Sheet2'!$A$2:$A$100,'Sheet1'!B:B,'Sheet2'!$B$2:$B$100)=0)*('Sheet2'!$C$2:$C$100=$B7))

These are untested as I did not want to retype that much data, but in thoery should work.


text:
Q: cin for an int inputing a char causes Loop that is supposed to check input to go wild This is a function of my game it will ask for input and cin into "iAuswahl"!
Then the while loop is checks if it is one of the Values i want 1-9 if not it activates and is supposed to ask for new input. Witch it does for int.
But if i input a char like r it will go crazy and just keep giving me back my cout and skip the cin!
My questions are why does it do it and how do i stop it?
void zug(string sSpieler, int iDran){
    int iAuswahl;
    char cXO = 'O';

    if (iDran == 1)
    {
        cXO = 'X';
    }

    cout << sSpieler << ", Sie sind am Zug. Bitte waehlen sie eins der Felder.\n" << endl;
    grafik();
    cout << "Sie sind >> " << cXO << " <<." << endl;
    cin >> iAuswahl;
    cout << endl;

    while (
        iAuswahl != 1
        && iAuswahl != 2
        && iAuswahl != 3
        && iAuswahl != 4
        && iAuswahl != 5
        && iAuswahl != 6
        && iAuswahl != 7
        && iAuswahl != 8
        && iAuswahl != 9
    )
    {
        cout << "Kein gültiges Feld bitte wählen sie noch einmal!\n" << endl;
        cin >> iAuswahl;
    }
    feldfuellen(iAuswahl, cXO);
}

A: When an error occurs when reading from a stream, an error flag gets set and no more reading is possible until you clear the error flags. That's why you get an infinite loop.
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Also, it's wrong to use the results of input operation if you don't know whether the read succeeded in the first place. You can't make assumptions about the value of iAuswahl. That's one of most often made errors by newbies using streams. Always check if the input operation was ok. This is most easily done by using operator>> in boolean context:
if (cin >> some_obj) {
    // evaluates to true if it succeeded
} else {
    // something went wrong
}

And, my oh my, this line
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)

can be just this:
while (iAuswahl < 1 || iAuswahl > 9)

A correct loop could look something like this:
while (true)
{
    if ((cin >> iAuswahl) && (iAuswahl >= 1) && (iAuswahl <= 9)) break;
    std::cout << "error, try again\n";
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

A: You need to clear error flag after reading wrong type, otherwise cin will refuse to read anything, as it will be in the invalid state. Also, you need to ignore that character that was not read by cin, because it will stuck you into a forever loop because it will always try to read from that character.
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)
{
    cout << "Kein gültiges Feld bitte wählen sie noch einmal!\n" << endl;
    cin.clear();
    // #include <limits>
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    cin >> iAuswahl;
}

Also,
while (iAuswahl != 1 && iAuswahl != 2 && iAuswahl != 3 && iAuswahl != 4 && iAuswahl != 5 && iAuswahl != 6 && iAuswahl != 7 && iAuswahl != 8 && iAuswahl != 9)

can be written as
if(iAuswahl < 1 || iAushwahl > 9)

Don't forget to initialize iAushwahl to 0, or to some other value, because if your cin >> iAushwahl fails, you will read the uninitialized variable.

A: If you are not using your iAuswahl variable to do any sort of math, which you aren't in this function, just make the variable a char variable, there is no reason in making a variable an int if it is not doing anything that would require it to be an int.


text:
Q: How to get output from paging container into a variable | Getting single virtual network from resource group Thanks in advance, I have variable at the top of my code, LOCATION, VNET_NAME, SUBNET, SUBNETRANGE. I want to fill this information from the output of function List_VNET. Using this function I'm getting virtual network from resource group on azure (I've only single virtual network per resource group). And then wanted to populate it into the variable but it is giving output as paging container. I mostly work on powershell hence i know about arrays and we can get an instance using array[0].
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute.models import DiskCreateOption
from azure.mgmt.network.v2017_03_01.models import NetworkSecurityGroup
from azure.mgmt.network.v2017_03_01.models import SecurityRule
import azure.mgmt.network.models

SUBSCRIPTION_ID = 'xxx'
GROUP_NAME = 'AQRG'
LOCATION = ''
VM_NAME = 'myVM'
VNET_NAME = ''
SUBNET_NAME = ''
SUBNETRANGE = ''

def List_VNET(network_client):
    result_create = network_client.virtual_networks.list(
            GROUP_NAME,
        )
    SUBNET_NAME = result_create

    return SUBNET_NAME

def get_credentials():
    credentials = ServicePrincipalCredentials(
        client_id = 'xxxx',
        secret = 'xxxx',
        tenant = 'xxxx'
    )

    return credentials

if __name__ == "__main__":
    credentials = get_credentials()

resource_group_client = ResourceManagementClient(
    credentials,
    SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
    credentials,
    SUBSCRIPTION_ID
)

creation_result = List_VNET(network_client)
print("------------------------------------------------------")
print(creation_result)
input('Press enter to continue...')

Getting output as below
<azure.mgmt.network.v2018_12_01.models.virtual_network_paged.VirtualNetworkPaged object at 0x0000023776C13908>

A: Update: Define the VNET_NAME as global in the function List_VNET:
   SUBSCRIPTION_ID = 'xxx'
   GROUP_NAME = 'AQRG'
   LOCATION = ''
   VM_NAME = 'myVM'
   VNET_NAME = ''
   SUBNET_NAME = ''
   SUBNETRANGE = ''

def List_VNET(network_client):
    result_create = network_client.virtual_networks.list(
            GROUP_NAME
        )
    global VNET_NAME
    for re in result_create:
        VNET_NAME=re.name

    return VNET_NAME

After the code: creation_result = List_VNET(network_client)
add the following code:
for re in creation_result:
    print(re.name)

Then you can get all the virtual networks' name.


text:
Q: UISegmentedControl not showing when used with Map View Anyone knows how I can get the UISegmentedControl to overlap with the MapView and still display properly? I'm currently trying to get a UISegmentedControl to appear in from of a MKMapView for users to switch the map type. I attached screenshots below.
This is my story board. Notice that the "Map View Controller Scene" clearly shows that the segmented control is above the Map View layer.

When I run the app with this storyboard setup, the UISegmentedControl does not appear.

Now i did manage to make it appear, only if I make sure that the uisegmentedcontrol does NOT overlap with the MapView.
This is the same story board, but this time, no overlap exists between the UISegmentedControl and the MapView

The app running, clearly showing the UISegmentedControl at the bottom

thanks!

A: "This is my story board. Notice that the "Map View Controller Scene" clearly shows that the segmented control is above the Map View layer."
I think you really want it AFTER the Map View for the z-order to be correct.
Reverse the order of the MapView and the UISegmentedControl, i.e. drag the segmented control to below/after the Map View in your Map View Controller Scene

A: I had the same problem, but for me the difficulty was not the Z ordering. It was that my struts were not set properly. I had the top strut turned on, which was pushing it below the bottom of the viewable area in landscape orientation.


text:
Q: Resharper always suggesting me to make const string instead of string which one is good:
string sQuery = "SELECT * FROM table";

or
const string sQuery = "SELECT * FROM table";

And why resharper always suggest me to do this?

A: If the string never changes and is never used outside your assembly, then const is a good idea. If it never changes but is used outside your assembly, static readonly might be a better idea -- consts are "burned in" at the site of the call, not stored in one location, so recompiling the assembly that contains the const does not update the dependent assemblies -- they have to be recompiled too. static readonly variables on the other hand do get updated in dependent assemblies.

A: The latter is better - it means that:

*

*This isn't an instance variable, so you don't end up with a redundant string reference in every instance that you create

*You won't be able to change the variable (which you presumably don't want to)

There are some other effects of "const" in terms of access from other assemblies and versioning, but it looks like this is a private field so it shouldn't be an issue. You can mostly think of it as being:
static readonly string sQuery = ...;

In general I believe it's a good idea to make fields static when you can (if it doesn't vary by instance, why should it be an instance variable?) and read-only when you can (mutable data is harder to reason about). Let me know if you want me to go into the details of the differences between static readonly and const.

A: ReSharper only suggests this if the particular string reference never changes. In that case you express your intend by using const string instead of just string.

A: It does this because if you accidentally assign a new value to sQuery in your code, if it's a const you'll get a compile error, so it will catch a bug at compile time. Same with its suggestion to make member variables which are set in the ctor only to be readonly


text:
Q: Getting elements from a list that contain any string from two other lists in python Basically searching items from a list that contains combined elements from two other lists. Also, all the items in the three lists are individual strings.
Example:
Paths = ['ab01', 'bc02', 'cd03', 'de04', 'ef05']
str1 = ['b','e']
str2 = ['3', '4']

# desired output
out = ['de04']       # only item in Paths that contains both elements from str1 and str2

A: You can use list-comprehension with any():
out = [
    p for p in Paths if any(s in p for s in str1) and any(s in p for s in str2)
]
print(out)

Prints:
['de04']

A: this solution could help you achieve your goal, it will work with any number of paths and strings, Best of luck !
Paths = ['ab01', 'bc02', 'cd03', 'de04', 'ef05']
str1 = ['b','e']
str2 = ['3', '4']

out = ['de04']

def program(paths, *lists):
    out = []
    for path in paths:
        bools = [any([x in path for x in l]) for l in lists]
        if all(bools):
            out.append(path)
    return out

if __name__ == "__main__":
    out = program(Paths, str1, str2)
    print(out)

A: You can use list comprehension for this, but it's a bit complicated.
First you can iterate through each value in Paths, as i:
[i for i in Paths...]

But then you need to check if a value from str1 or str2 exists in i, these can be done with more list comprehension as below (not these lines will not work on their own unless you define i to test:
[j for j in str1 if j in i]
[k for k in str2 if k in i]

The above will return a list of the characters from each str that exist in i.  A useful thing in python is that an empty list will automatically evaluate to False, and a populated one will evaluate to True, so you just need to put these comprehensions into the first one, after an if statement:
out =  [i for i in Paths if [j for j in str1 if j in i] and [k for k in str2 if k in i]]
print(out)

['de04']

Although the below replaces i,j and k to be a bit more readable:
[path for path in Paths if [elem1 for elem1 in str1 if elem1 in path] and [elem2 for elem2 in str2 if elem2 in path]]

This code basically does the same as below, but in a single line. I have included the below to help with understanding:
out = []
for i in Paths:
    list1 = []
    for j in str1:
        if j in i:
            list1.append(j)

    list2 = []
    for k in str2:
        if k in i:
            list2.append(k)

    if list1 and list2:
        out.append(i)

A: Basic solution:
>>> Paths = ['ab01', 'bc02', 'cd03', 'de04', 'ef05']
>>> str1 = ['b','e']
>>> str2 = ['3', '4']
>>> out = []
>>> for i in range(len(Paths)):
...     for j in range(len(str1)):
...         if str1[j] in Paths[i]:
...              for k in range(len(str2)):
...                  if str2[k] in Paths[i]:
...                      out.append(Paths[i])
...
>>> out
['de04']


text:
Q: I am stuck in creating a simple verification. How do I take the input entered by user and verify with my data? I want to take the user input and iterate through my data to check whether it matches or not.
How do I verify if the user entered input matches with my data.

const userInput = document.querySelector(".ID");
const button = document.querySelector(".login");
const data = [
  { userName: "Jon", userId: 1, admin: true },
  { userName: "Mike", userId: 2, admin: false },
  { userName: "Martha", userId: 3, admin: false },
];

function checkUser() {
  const id = userInput.value;
  data.forEach((user) => {
    if (id === user.userId) {
      console.log("Welcome");
    } else {
      console.log("Incorrect ID");
    }
  });
}

button.addEventListener("click", (e) => {
  e.preventDefault();
  checkUser();
});
<input class="ID" />
<input type="button" class="login" value="login" />

A: Input element values are string. For your code to work, you must declare your data.userId as strings.
So it must be:
    const data = [
    { userName: "Jon", userId: "1", admin: true },
    { userName: "Mike", userId: "2", admin: false },
    { userName: "Martha", userId: "3", admin: false },
    ];

If you don't want to use strings as userId, you should change the logical operator of your conditional statement into == instead of === so it would ignore data types.


text:
Q: How to get filepath for Documents from Uri in android 10 and android 11 I am creating an app where users will upload pdf or doc files.
I have used default file chooser which returns Uri , now i need to upload those selected files to server
Its working fine upto android 9 ,i am facing issues in android 10 and 11 (i have used android:requestLegacyExternalStorage="true" for android 10 )
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            .apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "*/*"
                putExtra(Intent.EXTRA_MIME_TYPES, supportedDocumentTypes.keys.toTypedArray())
        }
        resultLauncher.launch(intent)

In Activity Result
if (data != null) {
                    var path = ""
                    val id = data.data?.lastPathSegment!!
                    val selection = "_id=?"
                    if (id.startsWith("msf:") && Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
                        path = FileHelper(requireContext()).getRealPathFromUri(data.data!!.toString()
                            .replace("msf:","").toUri())!!
                    }else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q){
                        path = FileHelper(requireContext()).getRealPathFromUri(data.data!!)!!
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        path = getDataColumn(context, MediaStore.Downloads.EXTERNAL_CONTENT_URI,
                            selection, arrayOf(getPath(data.data!!)))
                    } else {
                        data.data?.also { uri ->
                            path = FileHelper(requireContext()).getRealPathFromUri(uri)!!
                        }
                    }
                    Log.e("Doc Path ::",path)
                    AppUtils.CustomToast(requireActivity(),path)
                    uploadDocs(path)
                }

For getting Document_ID
private fun getPath(uri : Uri) : String {
        val contentResolver = requireActivity().applicationContext.contentResolver

        val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        // Check for the freshest data.
        contentResolver.takePersistableUriPermission(uri, takeFlags)

        val cursor: Cursor? = contentResolver.query(
                uri, null, null, null, null, null)
        var id = ""
            cursor?.use { cursor1 ->
                if (cursor1.moveToFirst()) {
                    val displayName: String = cursor1.getString(cursor1.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    Log.i(TAG, "Display Name: $displayName")
                    val names = cursor1.columnNames.joinToString(",") { it }
                    Log.e("names ^^^^^",names)
                    val sizeIndex: Int = cursor1.getColumnIndex(OpenableColumns.SIZE)
                    val size: String = if (!cursor1.isNull(sizeIndex)) {
                        cursor1.getString(sizeIndex)
                    } else { "Unknown" }
                    Log.i(TAG, "Size: $size")
                    id =  cursor1.getString(cursor1.getColumnIndex(cursor1.columnNames[0]))
                    Log.e("DocId",id)
                }
            }
        return id
    }

Uploading file to server using Retrofit
val builder = MultipartBody.Builder()
        builder.setType(MultipartBody.FORM)
        val file = File(docPaths)
        builder.addFormDataPart("documents", file.name,
                RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file))
        val requestBody: MultipartBody = builder.build()

I am expecting some code for getting file to upload to server
Thanks In Advance


text:
Q: No results returned (not correct) from query for number of NULLs, MinValue,MaxValue and AvgValue
I have a query below that should bring back records for the number of NULL records, the MinValue of a column, MaxValue and AvgValue. However, the query runs but does not bring back records, just the column headers, when it definitely should. Can you correct my code to show where I'm going wrong? The calculated fields should only apply to numeric, float, decimal and other selected data types, as defined in the query below.
DECLARE @schemaName AS sysname;
    DECLARE @tableName AS sysname;
    DECLARE @columnName AS sysname;
    DECLARE @schema_id AS int;
    DECLARE @object_id AS int;
    DECLARE @column_id AS int;
    DECLARE @isNullable AS bit;
    DECLARE @lastSchema_id AS int;
    DECLARE @lastTable_id AS int;
    DECLARE @recordCount AS bigint;
    DECLARE @MinValue As int;
    DECLARE @MaxValue As int;
    DECLARE @AvgValue As int;
    DECLARE @nullCnt AS bigint;
    DECLARE @SQL as nvarchar(max);
    DECLARE @paramDefinition NVARCHAR(max);

    if exists(select name from tempdb..sysobjects where name LIKE'#Columns%')
    DROP TABLE #Columns;

    CREATE TABLE #Columns (
        schema_id int,
        object_id int,
        column_id int,
        schemaName sysname,
        tableName sysname,
        columnName sysname,
        recordCnt bigint,
        MinValue int,
        MaxValue int,
        AvgValue int,
        nullCnt bigint,
        nullPct numeric(38,35) );

    -- Set to the @lastSchema_id and @lastTable_id to NULL so that the first
    --  loop through the cursor the record count is generated.
    SET @lastSchema_id = NULL;
    SET @lastTable_id = NULL;

    -- List of all the user schemas.tables.columns
    --  in the database
    DECLARE c_Cursor CURSOR FOR
    SELECT schemas.schema_id
         , all_objects.object_id
         , all_columns.column_id
         , schemas.name AS schemaName
         , all_objects.name AS tableName
         , all_columns.name AS columnName
         , all_columns.is_nullable
      FROM sys.schemas
     INNER JOIN sys.all_objects
        ON schemas.schema_id = all_objects.schema_id
       AND all_objects.type = 'U'
     INNER JOIN sys.all_columns
        ON all_objects.object_id = all_columns.object_id
         WHERE all_objects.type LIKE '%int%'
         OR all_objects.type LIKE '%float%'
         OR all_objects.type LIKE '%decimal%'
         OR all_objects.type LIKE '%numeric%'
         OR all_objects.type LIKE '%real%'
         OR all_objects.type LIKE '%money%'
     ORDER BY schemas.schema_id
         , all_objects.object_id
         , all_columns.column_id;

    OPEN c_Cursor;

    FETCH NEXT FROM c_Cursor
     INTO @schema_id
        , @object_id
        , @column_id
        , @schemaName
        , @tableName
        , @columnName
        , @isNullable;

    -- Loop through the cursor
    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- Get the record count for the table we are currently working on if this is
        --  the first time we are encountering the table.
        IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
          OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
        BEGIN

            SET @SQL = N'SELECT @recordCount = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
            SET @paramDefinition = N'@recordCount bigint OUTPUT';

            exec sp_executesql @SQL,
                               @paramDefinition,
                               @recordCount = @recordCount OUTPUT;

        END

        -- Get the min value for the table

    IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
          OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
        BEGIN

            SET @SQL = N'SELECT @MinValue = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
            SET @paramDefinition = N'@MinValue int OUTPUT';

            exec sp_executesql @SQL,
                               @paramDefinition,
                               @MinValue = @MinValue OUTPUT;

        END

        --Get the max value for the table

        IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
          OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
        BEGIN

            SET @SQL = N'SELECT @MaxValue = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
            SET @paramDefinition = N'@MaxValue int OUTPUT';

            exec sp_executesql @SQL,
                               @paramDefinition,
                               @MaxValue = @MaxValue OUTPUT;

        END

        --Get the avg value for the table
    IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
          OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
        BEGIN

            SET @SQL = N'SELECT @AvgValue = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
            SET @paramDefinition = N'@AvgValue int OUTPUT';

            exec sp_executesql @SQL,
                               @paramDefinition,
                               @AvgValue = @AvgValue OUTPUT;

        END

        -- If the column is NOT NULL, there is no reason to do a count
        --  Set the nullCnt and nullPct to 0
        IF ( @isNullable = 0 )
        BEGIN

            INSERT INTO #Columns
                 ( [schema_id]
                 , [object_id]
                 , column_id
                 , schemaName
                 , tableName
                 , columnName
                 , recordCnt
                 , nullCnt
                 , nullPct )
            VALUES
                 ( @schema_id
                 , @object_id
                 , @column_id
                 , @schemaName
                 , @tableName
                 , @columnName
                 , @recordCount
                 , 0
                 , 0.0 );
        END
        -- If the column is NULL, count the number of NULL fields in the table.
        ELSE
        BEGIN

            SET @SQL = N'SELECT @nullCnt = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) +
                       N' WHERE ' + QUOTENAME(@columnName) + N' IS NULL;';
            SET @paramDefinition = N'@nullCnt bigint OUTPUT';

            PRINT @SQL;

            exec sp_executesql @SQL,
                               @paramDefinition,
                               @nullCnt = @nullCnt OUTPUT;

            INSERT INTO #Columns
                 ( [schema_id]
                 , [object_id]
                 , column_id
                 , schemaName
                 , tableName
                 , columnName
                 , recordCnt
                 , nullCnt
                 , nullPct )
            VALUES
                 ( @schema_id
                 , @object_id
                 , @column_id
                 , @schemaName
                 , @tableName
                 , @columnName
                 , @recordCount
                 , @nullCnt
                 -- USE NULLIF in case there are no recods in the table
                 , ISNULL( @nullCnt * 1.0 / NULLIF( @recordCount, 0) * 100.0, 0 ) );

        END

        -- Set the @lastSchema_id and @lastTable_id so that on
        --  the next loop, if it's the same table there is no
        --  need to recount the columns for the table.
        SET @lastSchema_id = @schema_id;
        SET @lastTable_id = @object_id;

        FETCH NEXT FROM c_Cursor
         INTO @schema_id
            , @object_id
            , @column_id
            , @schemaName
            , @tableName
            , @columnName
            , @isNullable;

    END;

    CLOSE c_Cursor;
    DEALLOCATE c_Cursor;

    SELECT *
      FROM #Columns;

A: The problem is the first query that you use for the cursor:
   SELECT schemas.schema_id
         , all_objects.object_id
         , all_columns.column_id
         , schemas.name AS schemaName
         , all_objects.name AS tableName
         , all_columns.name AS columnName
         , all_columns.is_nullable
      FROM sys.schemas
     INNER JOIN sys.all_objects
        ON schemas.schema_id = all_objects.schema_id
       AND all_objects.type = 'U'
     INNER JOIN sys.all_columns
        ON all_objects.object_id = all_columns.object_id
         WHERE all_objects.type LIKE '%int%'
         OR all_objects.type LIKE '%float%'
         OR all_objects.type LIKE '%decimal%'
         OR all_objects.type LIKE '%numeric%'
         OR all_objects.type LIKE '%real%'
         OR all_objects.type LIKE '%money%'
     ORDER BY schemas.schema_id
         , all_objects.object_id
         , all_columns.column_id;

If you check closely, you do an INNER JOIN on all_object.type = 'U' so all types must be U but then in the WHERE you do additional filter on the same oclumn with column types which will always be false since you already filter by type U.
I think you wanted to filter by column data type, in which you will have to do an additional join and filter correctly, like the following:
SELECT
    schemas.schema_id
    , all_objects.object_id
    , all_columns.column_id
    , schemas.name AS schemaName
    , all_objects.name AS tableName
    , all_columns.name AS columnName
    , all_columns.is_nullable
FROM
    sys.schemas
    INNER JOIN sys.all_objects
    ON schemas.schema_id = all_objects.schema_id
    AND all_objects.type = 'U'
    INNER JOIN sys.all_columns
    ON all_objects.object_id = all_columns.object_id

    INNER JOIN sys.types
    ON all_columns.system_type_id = types.system_type_id
    AND all_columns.user_type_id = types.user_type_id

WHERE
    types.name LIKE '%int%'
    OR types.name LIKE '%float%'
    OR types.name LIKE '%decimal%'
    OR types.name LIKE '%numeric%'
    OR types.name LIKE '%real%'
    OR types.name LIKE '%money%'
ORDER BY
    schemas.schema_id
    , all_objects.object_id
    , all_columns.column_id;

EDIT: Here is the corrected full script. Errors mentioned below.
DECLARE @schemaName AS sysname;
DECLARE @tableName AS sysname;
DECLARE @columnName AS sysname;
DECLARE @schema_id AS int;
DECLARE @object_id AS int;
DECLARE @column_id AS int;
DECLARE @isNullable AS bit;
DECLARE @lastSchema_id AS int;
DECLARE @lastTable_id AS int;
DECLARE @recordCount AS bigint;
DECLARE @MinValue As int;
DECLARE @MaxValue As int;
DECLARE @AvgValue As int;
DECLARE @nullCnt AS bigint;
DECLARE @SQL as nvarchar(max);
DECLARE @paramDefinition NVARCHAR(max);

if exists(select name from tempdb..sysobjects where name LIKE'#Columns%')
DROP TABLE #Columns;

CREATE TABLE #Columns (
    schema_id int,
    object_id int,
    column_id int,
    schemaName sysname,
    tableName sysname,
    columnName sysname,
    recordCnt bigint,
    MinValue int,
    MaxValue int,
    AvgValue int,
    nullCnt bigint,
    nullPct numeric(38,35) );

-- Set to the @lastSchema_id and @lastTable_id to NULL so that the first
--  loop through the cursor the record count is generated.
SET @lastSchema_id = NULL;
SET @lastTable_id = NULL;

-- List of all the user schemas.tables.columns
--  in the database
DECLARE c_Cursor CURSOR FOR
SELECT
    schemas.schema_id
    , all_objects.object_id
    , all_columns.column_id
    , schemas.name AS schemaName
    , all_objects.name AS tableName
    , all_columns.name AS columnName
    , all_columns.is_nullable
FROM
    sys.schemas
    INNER JOIN sys.all_objects
    ON schemas.schema_id = all_objects.schema_id
    AND all_objects.type = 'U'
    INNER JOIN sys.all_columns
    ON all_objects.object_id = all_columns.object_id

    INNER JOIN sys.types
    ON all_columns.system_type_id = types.system_type_id
    AND all_columns.user_type_id = types.user_type_id

WHERE
    types.name LIKE '%int%'
    OR types.name LIKE '%float%'
    OR types.name LIKE '%decimal%'
    OR types.name LIKE '%numeric%'
    OR types.name LIKE '%real%'
    OR types.name LIKE '%money%'
ORDER BY
    schemas.schema_id
    , all_objects.object_id
    , all_columns.column_id;

OPEN c_Cursor;

FETCH NEXT FROM c_Cursor
 INTO @schema_id
    , @object_id
    , @column_id
    , @schemaName
    , @tableName
    , @columnName
    , @isNullable;

-- Loop through the cursor
WHILE @@FETCH_STATUS = 0
BEGIN

    -- Get the record count for the table we are currently working on if this is
    --  the first time we are encountering the table.
    IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
      OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
    BEGIN

        SET @SQL = N'SELECT @recordCount = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
        SET @paramDefinition = N'@recordCount bigint OUTPUT';

        exec sp_executesql @SQL,
                           @paramDefinition,
                           @recordCount = @recordCount OUTPUT;

    END

    -- Get the min value for the table

IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
      OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
    BEGIN

        SET @SQL = N'SELECT @MinValue = MIN(' + QUOTENAME(@columnName) + N') FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
        SET @paramDefinition = N'@MinValue int OUTPUT';

        exec sp_executesql @SQL,
                           @paramDefinition,
                           @MinValue = @MinValue OUTPUT;

    END

    --Get the max value for the table

    IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
      OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
    BEGIN

        SET @SQL = N'SELECT @MaxValue = MAX(' + QUOTENAME(@columnName) + N') FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
        SET @paramDefinition = N'@MaxValue int OUTPUT';

        exec sp_executesql @SQL,
                           @paramDefinition,
                           @MaxValue = @MaxValue OUTPUT;

    END

    --Get the avg value for the table
IF ( ( @schema_id <> @lastSchema_id ) OR ( @object_id <> @lastTable_id )
      OR ( @lastSchema_id IS NULL ) OR ( @lastTable_id IS NULL ) )
    BEGIN

        SET @SQL = N'SELECT @AvgValue = AVG(' + QUOTENAME(@columnName) + N') FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) + ';';
        SET @paramDefinition = N'@AvgValue int OUTPUT';

        exec sp_executesql @SQL,
                           @paramDefinition,
                           @AvgValue = @AvgValue OUTPUT;

    END

    -- If the column is NOT NULL, there is no reason to do a count
    --  Set the nullCnt and nullPct to 0
    IF ( @isNullable = 0 )
    BEGIN

        INSERT INTO #Columns
             ( [schema_id]
             , [object_id]
             , column_id
             , schemaName
             , tableName
             , columnName
             , recordCnt
             , nullCnt
             , nullPct
             ,MinValue
             ,MaxValue
             ,AvgValue )
        SELECT
             @schema_id
             , @object_id
             , @column_id
             , @schemaName
             , @tableName
             , @columnName
             , @recordCount
             , 0
             , 0
             , @MinValue
             , @MaxValue
             , @AvgValue
    END
    -- If the column is NULL, count the number of NULL fields in the table.
    ELSE
    BEGIN

        SET @SQL = N'SELECT @nullCnt = COUNT(1) FROM ' + QUOTENAME(@schemaName) + N'.' + QUOTENAME(@tableName) +
                   N' WHERE ' + QUOTENAME(@columnName) + N' IS NULL;';
        SET @paramDefinition = N'@nullCnt bigint OUTPUT';

        PRINT @SQL;

        exec sp_executesql @SQL,
                           @paramDefinition,
                           @nullCnt = @nullCnt OUTPUT;

        INSERT INTO #Columns
             ( [schema_id]
             , [object_id]
             , column_id
             , schemaName
             , tableName
             , columnName
             , recordCnt
             , nullCnt
             , nullPct
             ,MinValue
             ,MaxValue
             ,AvgValue )
        SELECT
              @schema_id
             , @object_id
             , @column_id
             , @schemaName
             , @tableName
             , @columnName
             , @recordCount
             , @nullCnt
             -- USE NULLIF in case there are no recods in the table
             , ISNULL( @nullCnt * 1.0 / NULLIF( @recordCount, 0) * 100.0, 0 )
             , @MinValue
             , @MaxValue
             , @AvgValue

    END

    -- Set the @lastSchema_id and @lastTable_id so that on
    --  the next loop, if it's the same table there is no
    --  need to recount the columns for the table.
    SET @lastSchema_id = @schema_id;
    SET @lastTable_id = @object_id;

    FETCH NEXT FROM c_Cursor
     INTO @schema_id
        , @object_id
        , @column_id
        , @schemaName
        , @tableName
        , @columnName
        , @isNullable;

END;

CLOSE c_Cursor;
DEALLOCATE c_Cursor;

SELECT *
  FROM #Columns;

Errors:

*

*You were calculating the avg, min and max as COUNT instead of the correct operation.

*The avg, min and max weren't applied to the correct column, it was always a hard-coded 1.

*You were calculating the avg, min and max but not inserting them in your temporary table.


text:
Q: Ideal in a $C^*$ algebra Suppose $A$ is a non-unital $C^*$ algebra, $a\in A$, $I$ is the ideal generated by $a$.
In the unital case, $a=1a1\in AaA$. But in the non-unital case, how to show that $a\in A$, can $a$ be expressed by elements in $AaA$?

A: I'll assume we are talking (as usual) about closed bilateral ideals. Any C$^*$-algebra has an approximate unit $\{e_j\}$: that is, $0\leq e_j$, $\|e_j\|\leq 1$, and $\lim_j e_ja=\lim_jae_j=a$ for all $a\in A$. Then
$$
a=\lim_j e_jae_j\in \overline{AaA},
$$
without even needing sums.