text:
Q: Enum addition vs subtraction and casting Why does addition require a cast but subtraction works without a cast?  See the code below to understand what I am asking
public enum Stuff
{
    A = 1,
    B = 2,
    C = 3
}

var resultSub = Stuff.A - Stuff.B; // Compiles
var resultAdd = Stuff.A + Stuff.B; // Does not compile
var resultAdd2 = (int)Stuff.A + Stuff.B; // Compiles

note: For both addition and subtraction it does not matter whether result is out of range (of the enum) or not in all three examples above.

A: Good question - I was surprised that the first and third lines worked.
However, they are supported in the C# language specification - in section 7.8.4, it talks about enumeration addition:

Every enumeration type implicitly provides the following pre-defined operators, where E is the enum type and U is the underlying type of E:
E operator +(E x, U y)
E operator +(U x, E y)

At runtime, these operators are ealuated exactly as (E)((U)x + (U)y)

And in section 7.8.5:

Every enumeration type implicitly provides the following predefined operator, where E is the enum type and U is the underlying type of E:
U operator -(E x, E y)

This operator is evaluated exactly as (U)((U)x - (U)y)). In other words, the operator computes the difference between the ordinal values of x and y, and the type of the result is the underlying type of the enumeration.
E operator -(E x, U y);

This operator is evaluated exactly as (E)((U)x - y). In other words, the operator subtracts a value from the underlying type of the enumeration, yielding a value of the enumeration.

So that's why the compiler behaves like that - because it's what the C# spec says to do :)
I wasn't aware that any of these operators exist, and I've never knowingly seen them used. I suspect the reasons for their existence are buried somewhere in the language design meeting notes that Eric Lippert occasionally dives into - but I also wouldn't be surprised if they were regretted as adding features for little benefit. Then again, maybe they're really useful in some situations :)

A: The default values for enums are 0,1,2... so in this case the difference between two enums will create another enum (compare them first to make sure you are subtracting the smaller from the larger).
Half the time addition will create a value too high to be a valid enum.

A: The problem is that "+" in this context is not like a plus between the values of enumeration.
It is important to understand that + is operator and there are no rules defined how to apply it to operands ( Stuff.A and Stuff.B)


text:
Q: Suppose $\lim\limits_{n \rightarrow \infty } n^2 a_n =1$, then $ \sum\limits _{n=1} ^{\infty} a_n$ is convergent? Or is it divergent?
Suppose $\lim_{n \rightarrow \infty } n^2 a_n =1$ then $ \sum _{n=1} ^{\infty} a_n$ is convergent or divergent?

We use the definition of the limit, then for $\varepsilon =1$ there must exist an $n_0\geq n$  such that $$ |n^2 a_n -1|<1$$ so we can say that:
$$ 0 < n^2 a_n < 2 $$
We divide by:
$$ 0 < a_n < \frac{2}{n^2} $$
We now  know  if we take the infinite sum we get:
$$ 0 <  \sum _{n=1} ^{\infty} a_n <  \sum _{n=1} ^{\infty} \frac{2}{n^2} $$
 We know that the right side converges, so the sum is bounded, but how would I prove that is converges? Or can we find a counterexample that diverges, bur stays within these bounds.

A: A series converges iff its remainder term $\sum\limits_N^\infty a_n \rightarrow 0$ as $N\rightarrow \infty$. Your argument shows that you can, for large enough $N$, bound $|\sum\limits_N^\infty a_n|$ by $\sum\limits_N^\infty \frac{1}{n^2}$. The latter term approaches zero as $N\rightarrow \infty$, since $\sum \frac{1}{n^2}$ converges.

A: The hypothesis means first that, if $n$  is large enough, $a_n>0$, and also that $a_n$ is asymptotically equivalent to $\dfrac1{n^2}$.
Now two series with (eventually positive) equivalent terms both converge or both diverge.

A: Option.
$\lim_{n \rightarrow \infty}n^2a_n=1.$
This Implies for  $n \in \mathbb{Z^+}$ :
$n^2|a_n| \lt M$, positive real number.
$|a_n| \lt M/n^2.$
By comparison test $\sum |a_n|$ is convergent,
hence $\sum a_n$ is convergent.

A: Your argument is correct, more simply we can refer directly to limit comparison test with $$\sum \frac1{n^2}$$
indeed
$$\frac{a_n}{ \frac1{n^2}}=n^2a_n\to 1$$
therefore $\sum a_n$ converges.
It is important to recognize that since, more in general, when we solve a problem we don't need everytime to prove all the results that we have already proved in a general way.
Therefore if you are not requested to use esplicitely the $\epsilon-\delta$ definition a solution by limit comparison test is fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a base class that implements a singleton for the derived class So before you shoot me down telling me this is a terrible thing to do, I just want to state that I want to know this just for the sake of curiosity and possible code reduction. I want to have a base class that implements a singleton for a derived class. However, in doing so data is lost from the derived class. How can I get the base class to implement a singleton in terms of the derived class. Eg:
class Application{
public:
/**
 * @brief instance: C++11 [If control enters the declaration concurrently while the     variable is being initialized,
 *the concurrent execution shall wait for completion of the initialization.—§6.7 [stmt.dcl] p4]
 * @return handle to application
 */
static Application& instance(){
    static Application s_Application;
    return s_Application;
}

void setName(std::string Name){
    AppName=Name;
}

std::string getName(){
    return AppName;
}
virtual ~Application(){ }

private:
Application(){}
std::string AppName;
};

Now I create a derived class that inherits from Application:
class Test:public Application{
    public:
    void printer(std::string test){
        std::cout<<"test\n";
    }
};

int main(int argc, char *argv[]) {
    Application test1=Test::instance();
    //Test test2=static_cast<Test>(test1);
    test1.setName("bla");
    test1.printer(test1.getName());
}

So as expected test1 cannot call the .printer() method since the returned object is of type 'Application'. Is there any way to pass the type of the derived class back to the main class and create an instance of the derived class?
Edit: I have used CRTP to pass the value up, however when I do the following it doesn't equal each other:
Test test1=Test::instance();
Test test2=Test::instance();
cout<<"Is test1 the same as test 2? "<<(&test1==&test2)<<endl;

The result of this is always FALSE.

A: You also need to make copy constructor and assignment private so that one cannot copy the object (since only object has to exist).
In your code
Test test1=Test::instance();
Test test2=Test::instance();

You are actually calling
Test test1(Test::instance());

which is actually calling
Test (const Test &);

which is copy constructor and hence creating the copy of your object. And you are actually creating two different objects. That is why their address is different.
So, make copy constructor and assignment operator private so that no one can copy it.
And use the following
Test & test1 = Test::instance();
Test & test2 = Test::instance();

In this case, address will be same.
Or you can return pointer in Test::instance if you want.


text:
Q: Canceling Retrofit requests or handling them when leaving the activity or fragment - android I use Retrofit library to handle JSON response from my WCF web-service.
RestService.getRestService().search("tools", new Callback<SearchResult>() {
    @Override
    public void success(SearchResult searchResult, Response response) {
        if( searchResult == null) return;
        textView.setText(searchResult.toString());
    } // end of success(

    @Override
    public void failure(RetrofitError error) {
            showToast(R.string.internet_sikintisi);

    }
});

I noticed that i get error if i leave the fragment or activity where i called this function from. Because I set text in textView where the activity or fragment is not already exists.
I modified the code to be like this:
RestService.getRestService().search("tools", new Callback<SearchResult>() {
    @Override
    public void success(SearchResult searchResult, Response response) {

        if( searchResult == null) return;
        try{
            textView.setText(searchResult.toString());
        } catch(Exception e) {}

    } // end of success(

    @Override
    public void failure(RetrofitError error) {
        try{
                showToast(R.string.internet_sikintisi);
            } catch(Exception e) {}
    }
});

Basically, the problem solved, the app is not crashing every time the user gets in and out immediately. Still there might be a better solution for this problem.
I checked and Retrofit DOES NOT have cancel request feature!

A: You need to added checks success and failure methods the same way you would when using an asynctask check if the context still exist or make a isActive field that you set on onResume/onPause of the activity or fragment.

A: It is possible to cancel Retrofit requests in Retrofit 2(beta is available now.)
 call.cancel();// as simple as that


text:
Q: Distribution upgrade Error When I go to System Settings and click on Software Sources nothing happens. When I try
sudo apt-get dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Failed
The following packages have unmet dependencies:
 gnome-shell : Depends: libcogl5 (>= 1.7.4) but it is not going to be installed
               Depends: gnome-shell-common (= 3.2.2.1-0ubuntu0.1) but 3.4.0+git20120401.c16dbd76-0ubuntu1~11.10~ricotz0 is to be installed
 gnome-shell-common : Breaks: gnome-tweak-tool (< 3.3) but 3.2.0-2ubuntu1~oneiric is to be installed
 libmutter0 : Breaks: gnome-shell (< 3.3.92~) but 3.2.2.1-0ubuntu0.1 is to be installed
 mutter-common : Breaks: gnome-shell (< 3.3.92~) but 3.2.2.1-0ubuntu0.1 is to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

A: It seems Gnome-shell stucks the upgrade. You shall try to uninstall the packet and re-install it when the upgrade is done (gnome-shell is available in the repository in oneiric).


text:
Q: Xamarin.android Microsoft.SQLite Always return no rows   string path = Path.Combine(
         System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
          "Service.db3");

            SqliteConnection cn = new SqliteConnection("Data Source=" + path + " ");

            List<String> entries = new List<string>();

            SqliteCommand sqCommand = (SqliteCommand)cn.CreateCommand();
            sqCommand.CommandText = $"SELECT ID FROM Members ";
            cn.Open();

  SqliteDataReader sqReader = sqCommand.ExecuteReader();

            if (sqReader.HasRows)
            {

            }
            else
            {

            }

that is my code I'm using but there is no row although I have 2 rows at the table
and if I used

SELECT name FROM sqlite_master
  I got the table name that I created  I don't understand??

A: I know the answer now
I have to make function create the db and table
I was creating the db with sqlite studio and save it

A: string path = Path.Combine(
     System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
      "Service.db3");

        SqliteConnection cn = new SqliteConnection("Filename=" + path);

        List<String> entries = new List<string>();

        SqliteCommand sqCommand = (SqliteCommand)cn.CreateCommand();
        sqCommand.CommandText = "SELECT ID FROM Members ";
        cn.Open();

         SqliteDataReader sqReader = sqCommand.ExecuteReader();

        if (sqReader.HasRows)
        {

        }
        else
        {

        }

Try this


text:
Q: Check checkbox by index in another list I have an unordered list with div and a hidden checkbox list, each with the same number of items.
How can I check an item in list 2 when I click a div in list 1 with the same index?

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  if ($('.product-checkbox #checkbox index').prop('checked')) {
    $('.product-checkbox #checkbox index').prop('checked', false);
  } else {
    $('.product-checkbox #checkbox index').prop('checked', true);
  }
});

Red

White

Blue

    <input type="checkbox">Red

    <input type="checkbox">White

    <input type="checkbox">Blue

So here if I click Red in the first UL, Red gets checked in the second UL.
I can get the index of the LI in the first but not apply that index to check the box.

A: There's a couple of issues in your logic. Firstly, you can use eq() to select an element within a collection by its index. Secondly, #checkbox is looking for a single element with that id attribute. You should use the :checkbox selector instead to find any element of that type within the parent. Finally, you can make the prop() logic more succinct by providing a function which accepts the current state of the property as an argument and returns the inverted boolean value. Try this:

$(document).on('click', '.product-list li', e => {
  var index = $(e.currentTarget).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', (i, checked) => !checked);
});

/* anonymous function version for legacy support:

$(document).on('click', '.product-list li', function() {
  var index = $(this).index();
  $('.product-checkbox :checkbox').eq(index).prop('checked', function(i, checked) {
    return !checked;
  });
});
*/

Red

White

Blue

<input type="checkbox">Red

<input type="checkbox">White

<input type="checkbox">Blue

It's also worth noting that what you're doing here can be achieved in HTML alone with no need for JS or jQuery:

      Red
      <input type="checkbox" value="Red" />

      White
      <input type="checkbox" value="White" />

      Blue
      <input type="checkbox" value="Blue" />

Of course, I left the checkboxes visible in both examples so you can see the effect working, but they can still be easily hidden using CSS if necessary.


text:
Q: Вложенные транзакции SQL сервер Здравствуйте.
Ситуация следующая. Есть SQL Server 2008, в программе используется драйвер QODBC3.
Соединение установлено, данные пишутся/читаются.
Проблема, видимо, в отсутствии понимания принципа работы с вложенными транзакциями. Судя по документации к восьмому серверу, каждый новый BEGIN TRANSACTION  увеличивает счётчик TRANCOUNT на единицу. Каждый COMMIT уменьшает его на 1. Транзакция завершается и фиксируются изменения, когда счётчик станет равен 0. У меня же выходит, что первый же commit завершает транзакцию вне зависимости от того, сколько было BEGIN TRANSACTION. Пусть имеется база и запрос к ней:
db = QSqlDatabase::addDatabase("QODBC3");
...
query = new QSqlQuery(db);
...

Выполняем:
db.transaction();
      query->exec("INSERT INTO TestOnly (Value) VALUES('1')");
      db.transaction();
            query->exec("INSERT INTO TestOnly (Value) VALUES('2')");
      db.commit();
      query->exec("INSERT INTO TestOnly (Value) VALUES('3')");
db.rollback();

В результате в таблице оказываются все 3 значения ('1','2','3'). И в SQL SMS видно, что после первого же коммита пропадает единственная активная транзакция. Соответвственно последующий RollBack ничего не делает.
В чём здесь проблема? Я совсем не правильно понял идею со счётчиком открытых транзакций, или просто драйвер/Qt не поддерживают такой функционал? Или я упустил что-то где-то в настройках (сервера/драйвера)?

С проверкой возвращаемых значений операций открытия/закрытия транзакций пример выглядит страшнее, но ничего не поделать:
    bool ok;

    ok = db.transaction(); qDebug() << "Start transaction" << " result = " << ok << "; errorText: " << db.lastError().text();
    PrintTranCount(); //0

    query->exec("INSERT INTO TestOnly (Value) VALUES('1')");
    PrintTranCount(); //1

    ok = db.transaction(); qDebug() << "Start transaction" << " result = " << ok << "; errorText: " << db.lastError().text();
    PrintTranCount(); //2

    query->exec("INSERT INTO TestOnly (Value) VALUES('2')");
    PrintTranCount(); //3

    ok = db.commit(); qDebug() << "Commit transaction" << " result = " << ok << "; errorText: " << db.lastError().text();
    PrintTranCount(); //4

    query->exec("INSERT INTO TestOnly (Value) VALUES('3')");
    PrintTranCount(); //5

    ok = db.rollback();  qDebug() << "Rollback transaction" << " result = " << ok << "; errorText: " << db.lastError().text();
    PrintTranCount(); //6

Результат:
Start transaction  result =  true ; errorText:  " "
Transaction Count   0: 0
Transaction Count   1: 1
Start transaction  result =  true ; errorText:  " "
Transaction Count   2: 1
Transaction Count   3: 1
Commit transaction  result =  true ; errorText:  " "
Transaction Count   4: 0
Transaction Count   5: 0
Rollback transaction  result =  true ; errorText:  " "
Transaction Count   6: 0

Иными словами, вторая db.transaction() не инкриминирует счётчик совсем и транзакция полностью завершается после первого COMMIT'а. Буду благодарен за любые подсказки по этому поводу.
Вывод значения счётчика транзакций:
void PrintTranCount()
{
    static int Num = 0;
    query->exec("SELECT @@TRANCOUNT");query->first();
    qDebug() << "Transaction Count  "<< Num << ": " <<query->value(0).toInt();
    Num++;
}

A: Краткий ответ
Вызов метода QSqlDatabase::transaction() не начинает транзакцию в базе, а лишь включает режим "ручной режим фиксации". Для того чтобы начать явную транзакцию, нужно отослать базе непосредственно команду "begin tran".
Пояснения
Проблема заключалась в том, что я принимал желаемое поведение драйвера за действительное и поленился залезть в исходники. Спасибо @teran за то, что "ткнул носом" куда надо.
Описание функции bool QSqlDatabase::transaction() гласит:

Begins a transaction on the database if the driver supports
  transactions. Returns true if the operation succeeded. Otherwise it
  returns false.

Из этого описания я сделал ложный вывод о том, что драйвер отправляет базе команду открытия транзакции, что, мягко говоря, не соотносится с действительностью.
Из исходников:
bool QSqlDatabase::transaction()
{
    if (!d->driver->hasFeature(QSqlDriver::Transactions))
        return false;
    return d->driver->beginTransaction();
}

Функция "спрашивает" драйвер о поддержке транзакций, вызывая hasFeature(QSqlDriver::Transactions). Если получает положительный ответ - вызывает метод драйвера beginTransaction().
bool QODBCDriver::beginTransaction()
{
    Q_D(QODBCDriver);
    //---------------Проверяем открыта ли база-----------------
    if (!isOpen())
    {
        qWarning("QODBCDriver::beginTransaction: Database not open");
        return false;
    }
    //------Инициализация переменной-параметра значением,-----
    //------отключающим автоматический commit операций--------
    SQLUINTEGER ac(SQL_AUTOCOMMIT_OFF);
    //-------Устанавливаем этот параметр и проверяем на ошибки-----------------
    SQLRETURN r  = SQLSetConnectAttr(d->hDbc,
                                      SQL_ATTR_AUTOCOMMIT,
                                      (SQLPOINTER)size_t(ac),
                                      sizeof(ac));
    if (r != SQL_SUCCESS) {
        setLastError(qMakeError(tr("Unable to disable autocommit"),
                     QSqlError::TransactionError, d));
        return false;
    }
    return true;
}

В функции beginTransaction(), в свою очередь, единственное производимое действие - отключение автоматического подтверждения изменений в базе. Никаких "begin tran".
В результате, с отключённым автокоммитом база данных при выполнении каждой инструкции начинает неявную транзакцию. Это (а не сама функция transaction(), как я думал) и приводит к установке счётчика транзакций @TRANCOUNT в единицу. Нет никакой вложенности транзакций в данном случае, она одна и завершается сразу после первого же COMMIT'а.
Функция commit() (как и rollback()) содержит в себе вызов QODBCDriver::endTrans(), который вновь отключает режим неявных транзакций. Это отключение объясняет, почему в моём примере в результирующей таблице была и третья строка (та, что перед ROLLBACK'ом). COMMIT перед отправкой команды вставки этой строки завершил неявную транзакцию и отключил ручной режим фиксации, так что INSERT был автоматически зафиксирован в базе, а rollback() отработал вхолостую.

A: По поводу того, как работают вложенные транзакции на mssql:
use tempdb
go
set nocount on;
SELECT [@@TRANCOUNT]=@@TRANCOUNT ,[XACT_STATE()]=XACT_STATE() ,[IMPLICIT_TRANSACTIONS]=CASE WHEN @@OPTIONS & 2 = 2 THEN 1 ELSE 0 END
begin tran
SELECT [@@TRANCOUNT]=@@TRANCOUNT ,[XACT_STATE()]=XACT_STATE() ,[IMPLICIT_TRANSACTIONS]=CASE WHEN @@OPTIONS & 2 = 2 THEN 1 ELSE 0 END
begin tran
SELECT [@@TRANCOUNT]=@@TRANCOUNT ,[XACT_STATE()]=XACT_STATE() ,[IMPLICIT_TRANSACTIONS]=CASE WHEN @@OPTIONS & 2 = 2 THEN 1 ELSE 0 END
commit
SELECT [@@TRANCOUNT]=@@TRANCOUNT ,[XACT_STATE()]=XACT_STATE() ,[IMPLICIT_TRANSACTIONS]=CASE WHEN @@OPTIONS & 2 = 2 THEN 1 ELSE 0 END
commit
SELECT [@@TRANCOUNT]=@@TRANCOUNT ,[XACT_STATE()]=XACT_STATE() ,[IMPLICIT_TRANSACTIONS]=CASE WHEN @@OPTIONS & 2 = 2 THEN 1 ELSE 0 END

@@TRANCOUNT XACT_STATE() IMPLICIT_TRANSACTIONS
----------- ------------ ---------------------
0           0            0
1           1            0
2           1            0
1           1            0
0           0            0


text:
Q: Only variables should be passed by reference // Other variables
$MAX_FILENAME_LENGTH = 260;
$file_name = $_FILES[$upload_name]['name'];
//echo "testing-".$file_name."<br>";
//$file_name = strtolower($file_name);
$file_extension = end(explode('.', $file_name)); //ERROR ON THIS LINE
$uploadErrors = array(
    0=>'There is no error, the file uploaded with success',
    1=>'The uploaded file exceeds the upload max filesize allowed.',
    2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
    3=>'The uploaded file was only partially uploaded',
    4=>'No file was uploaded',
    6=>'Missing a temporary folder'
);

Any ideas? After 2 days still stuck.

A: PHP complains because end() expects a reference to something that it wants to change (which can be a variable only). You however pass the result of explode() directly to end() without saving it to a variable first. At the moment when explode() returns your value, it exists only in memory and no variable points to it. You cannot create a reference to something (or to something unknown in the memory), that does not exists.
Or in other words: PHP does not know, if the value you give him is the direct value or just a pointer to the value (a pointer is also a variable (integer), which stores the offset of the memory, where the actual value resides). So PHP expects here a pointer (reference) always.
But since this is still just a notice (not even deprecated) in PHP 7, you can savely ignore notices and use the ignore-operator instead of completely deactivating error reporting for notices:
$file_extension = @end(explode('.', $file_name));

A: end(...[explode('.', $file_name)]) has worked since PHP 5.6. This is documented in the RFC although not in PHP docs themselves.

A: Assign the result of explode to a variable and pass that variable to end:
$tmp = explode('.', $file_name);
$file_extension = end($tmp);

The problem is, that end requires a reference, because it modifies the internal representation of the array (i.e. it makes the current element pointer point to the last element).
The result of explode('.', $file_name) cannot be turned into a reference. This is a restriction in the PHP language, that probably exists for simplicity reasons.

A: Everyone else has already given you the reason you're getting an error, but here's the best way to do what you want to do:
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

A: Php 7 compatible proper usage:
$fileName      = 'long.file.name.jpg';
$tmp           = explode('.', $fileName);
$fileExtension = end($tmp);

echo $fileExtension;
// jpg

A: Just as you can't index the array immediately, you can't call end on it either.  Assign it to a variable first, then call end.
$basenameAndExtension = explode('.', $file_name);
$ext = end($basenameAndExtension);

A: save the array from explode() to a variable, and then call end() on this variable:
$tmp = explode('.', $file_name);
$file_extension = end($tmp);

btw: I use this code to get the file extension:
$ext = substr( strrchr($file_name, '.'), 1);

where strrchr extracts the string after the last . and substr cuts off the .

A: The answer given elsewhere,
$tmp = explode('.', $fileName);
$file_extension = end($tmp);

is correct and valid. It accomplishes what you are trying to do.
Why?
The end() function does not do quite what you think it does. This is related to how the PHP array data structure works. You don't normally see it, but arrays in PHP contain a pointer to a current element, which is used for iteration (like with foreach).
In order to use end(), you must have an actual array, which has attached to it (normally, invisibly), the current element pointer. The end() function physically modifies that pointer.
The output of explode() is not an actual array. It is a function output. Therefore, you cannot run end(explode()) because you violate language requirements.
Simply setting the output of explode() in a variable creates the array that you're looking for. That created array has a current element pointer. Now, all is once again right in the world.
So what about the parentheses?
This is not a bug. Once again, it's a language requirement.
The extra parentheses (like end((explode()))) do more than just grouping. They create an inline instance variable, just like setting the function output to a variable. You may think of it as a lambda function that is executed immediately.
This is another correct and valid solution. It is perhaps a better solution, as it takes less space. A good reviewer or maintainer should grok what you're trying to do when they see the extra parentheses.
If you use a linter or SCA program like PHPCS, that may dislike the extra parentheses, depending on the linting profile you're using. It's your linter, tell it what you want it to do for you.
Some other answers also list things like the spread operator or array_key_last(), which are also reasonable solutions. They may be perfectly valid but they're more complicated to use and read.
I'll just use the @ prefix
This solution is valid, however incorrect. It is valid because it solves the problem. That's about the end of its merit.
Suppressing errors is always bad practice. There are many reasons why. One very large one is that you are trying to suppress one specific error condition (one that you have created), but the error suppression prefix suppresses all errors.
In this case, you will probably get away with this. However, engaging in bad programming habits is cheating and will likely lead you to cheat more and bigger in the future. You will be responsible for bad code. But I'm not the Code Police and it's your code. It's valid because it solves the problem.
Okay, so what's the best answer?
Do what @ryeguy suggests. Don't do string manipulation to solve a well-defined problem that the platform already solves for you. Use pathinfo().
This has the added benefit that it actually does what you want, which is finding the extension on a file name. There is a subtle difference.
What you are doing is getting the text following the final dot. This is different from finding the file extension. Consider the file name, .gitignore. PHP knows how to handle this. Does your code?
Once again, I'm not the Code Police. Do what suits you best.

A: Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:
$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit.
Newest version of php 7.3+ offer the method array_key_last() and array_key_first().
https://www.php.net/manual/en/function.array-key-last.php
                 uuuuuuu
             uu$$$$$$$$$$$uu
          uu$$$$$$$$$$$$$$$$$uu
         u$$$$$$$$$$$$$$$$$$$$$u
        u$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$$$$$$$$$$$$$$$$$$$$u
       u$$$$$$"   "$$$"   "$$$$$$u
       "$$$$"      u$u       $$$$"
        $$$u       u$u       u$$$
        $$$u      u$$$u      u$$$
         "$$$$uu$$$   $$$uu$$$$"
          "$$$$$$$"   "$$$$$$$"
            u$$$$$$$u$$$$$$$u
             u$"$"$"$"$"$"$u
  uuu        $$u$ $ $ $ $u$$       uuu
 u$$$$        $$$$$u$u$u$$$       u$$$$
  $$$$$uu      "$$$$$$$$$"     uu$$$$$$
u$$$$$$$$$$$uu    """""    uuuu$$$$$$$$$$
$$$$"""$$$$$$$$$$uuu   uu$$$$$$$$$"""$$$"
 """      ""$$$$$$$$$$$uu ""$"""
           uuuu ""$$$$$$$$$$uuu
  u$$$uuu$$$$$$$$$uu ""$$$$$$$$$$$uuu$$$
  $$$$$$$$$$""""           ""$$$$$$$$$$$"
   "$$$$$"                      ""$$$$""
     $$$"                         $$$$"

A: Try this:
$parts = explode('.', $file_name);
$file_extension = end($parts);

The reason is that the argument for end is passed by reference, since end modifies the array by advancing its internal pointer to the final element. If you're not passing a variable in, there's nothing for a reference to point to.
See end in the PHP manual for more info.

A: PHP offical Manual :
end()
Parameters
array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

A: First, you will have to store the value in a variable like this
$value = explode("/", $string);

Then you can use the end function to get the last index from an array like this
echo end($value);

I hope it will work for you.


text:
Q: If Dynamic columns are discouraged in cassandra 1.2/Cql3 , then how is it better than Mysql in functionality? Initially I started learning Cassandra because dynamic columns caught my attention. As I started learning more, I learnt that composite primary keys are preferred to dynamic columns and Cassandra is moving to schema based (Schema is optional and not compulsory but recommended). In cql3, it is compulsory though and I read cql3 is best approach for new applications in cassandra.
Here is where I face an interesting question. I was reading a particular slide (Mysql vs Casssandra) - http://lanyrd.com/2012/austin-mysql-meetup-january/spdrx/ (Jump to 31 slide) where it discusses about fraud detection use case.
"In FraudDetection To calculate risk, it is common to need to know all the emails,destinations,origins,devices,locations,phonenumbers,etcetera ever used for the account in question. "
It was explained how we have to maintain individual table for emails, destinations , origins etc in relational world and how easy it is to be in cassandra world with dynamic column key and values. (31- 34 slides).
Now that dynamic column keys and values and discouraged, how can we solve this problem ? Should we maintain individual column families for each emails, destinations etc ? Then how is it different from relational world ? Is it only about scalability ? Can we still go ahead with schema less approach ? Is this the golden rule "Schema is optional and recommended but not mandatory?"
Thanks

A: Sorry for the confusion here. As it turned out , I didn't understand the basic concepts properly. Here is the answer
Dynamic columns are core of Cassandra. They are still supported and is still the core :) Its just that in thrift you do directly and in CQL you do in a different manner(through schema way). But still you do it :) - Read this - http://www.datastax.com/dev/blog/thrift-to-cql3
And regarding how Cassandra is better than Mysql - read this http://lanyrd.com/2012/austin-mysql-meetup-january/spdrx/ (16-24 slides)
Thanks :)

A: You can still use a schema-less approach if you use the Thrift API instead of CQL.  As a long-time Cassandra user, I also find the push toward upfront schema definition to be questionable.  But fortunately the underlying storage mechanism is the same, and all clients that I'm aware of support using Thrift-based calls.

A: Instead dynamic columns, there are supporting collection stuffs like Sets, Lists, Maps.
Isn't it enough for dynamicity


text:
Q: Platform independent way to fire off external applications/helpers by file type? For example, one application that I'm working on stores PDF files into a database, then can pull them back out for display.  I've got a call in there using Runtime.exec to do a "cmd /c start " plus the PDF filename.  Works great for Windows.  Would prefer to find a platform independent way (trying to avoid OS detection with alternate methods for various OS) to do this though as we also run the software on Solaris and Mac.

A: Look at Desktop which has a open method and that would be platform independent.

Launches the associated application to
  open the file.

A: I'd be interested to see if there is a 'correct' answer for this. If I were to do this, I'd have a properties file mapping of OS to the command needed to run, and then resolve the OS at runtime.
Eg in a properties file:
windows=cmd /c start
mac=open #(I think)
linux=... etc


text:
Q: images not switch when click on color swatches in magento When I click on colour swatches image is not changing. I do all the settings right. Colour swatches view with product but images is not changing. view this link.
view problem
Please any one help me.

A: @Pankaj, you need to upload image on simple product, where simple product is created by configurable product.
For E.g: "PANKAJ" is a configurable product and Brown & Cherry is a simple product. So here you need to upload image to the Simple products.
Hope it resolves your issue.


text:
Q: Avada Theme - Submenu customization 2 I have got the same problem as like the guy in this topic: Avada Theme - Submenu customization, but I just can't find the side-navigation CSS styles where I've to change the code.
I already put the code into the Avada theme options CSS editor but nothing changed.

A: Please make sure that your css code is correct then put it in the WP Dashboard > Appearance > Theme Options > Custom CSS field and Save.
https://theme-fusion.com/knowledgebase/how-to-make-custom-css-changes/


text:
Q: PHP Curl - Trying to set Cookies in CURL Here is my code:
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: ChosenSite=www"));
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: SportsDirect_AnonymousUserCurrency=GBP"));
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: language=en-GB"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($curl, CURLOPT_VERBOSE, true);
 $str = curl_exec($curl);
 curl_close($curl);

I am trying to set these cookies as i am trying to parse HTML dom elements but it seems i am not able to set them correctly.
Can you please tell me where is my mistake, I am setting cookies correctly ?
Thanks in advance!


text:
Q: Store user settings in map document? I have created a custom tool for ArcMap with .NET and would like to know if there is any way to store user defined settings in a MXD.  The tool simply draws a graphic circle of a certain radius with the center snapped to the closest vertex in a polyline pointed at by the mouse.
Right now, the user has to select the layer and set the radius (with a custom dialog form) every time they open the mxd and use the tool.
This layer and radius rarely changes for a project mxd, so it would be convenient to store the name of the layer and radius setting somewhere, so that it can be automatically used by the tool.

A: You need to implement an application extension. If the extension also implements relevant persistence interfaces, the saved settings get stored with the MXD document.
See How to persist data in a document for further details.


text:
Q: Call PHP program with Ajax I have a PHP program for counting user banner clicks. My banner link is something like this:
<a href="<?=$banner_url;?>" onclick="banner_click_count('<?=$banner_id;?>')">

When user clicks on image, it runs banner_click_count() function with $banner_id as parameter.
function banner_click_count($ban_id)
{
$.ajax({
   type: "POST",
   url: 'banner_click.php',
   data: {banner_id: $ban_id}
   });

}

At banner_click.php, I get the banner_id with $banner_id = $_GET['banner_id']);, search the database based on it. Find the record, then add 1 to banner_count column field. After that, redirect to banner_url.
When I run the program, I get  Parse error: parse error, expecting T_VARIABLE' or '$'' on line $.ajax({
Addendum: the error is cleared with all your help, but when I click on the link it redirects to banner_url directly and does not run the AJAX function.
Addendum:I put the alert("hello"); at the top of ajax function and i got it. So it goes into function

A: 1.You need to put your javascript function under

// in your php use as below
echo $_POST['banner_id']

A: Make sure banner_id is in quotes and that you are including JQuery in your page.
And don't forget a success/error return.
$.ajax({
   type: "POST",
   url: 'banner_click.php',
   data: {'banner_id': $ban_id},
   success: function(s) {
     console.log('success' + s);
   },
   error: function(e) {
     console.log('error' + e);
   }
});

A: Don't we need a return false before the function ends?

A: I found the solution. Thanks to all.
function banner_click_count(ban_id)
{
  $.post(
  "banner_click.php",
  {
  banner_id: ban_id
  });
}


text:
Q: Restrict access to admin but allow admin_post hook I'm using this hook to allow only admin roles access dashboard
add_action( 'admin_init', function() {
    if ( defined('DOING_AJAX') && DOING_AJAX ) {
        return;
    }

    if ( !current_user_can('manage_options') ) {
        wp_redirect( home_url('/meu-perfil') );
        exit();
    }
});

Now I need to run a function when a form is submitted on front end, like so:
function editUser() {
    error_log('message');
}
add_action( 'admin_post_nopriv_add_foobar', 'editUser' );
add_action( 'admin_post_add_foobar', 'editUser' );

But the first hook is blocking the second one.

A: All you need to do is to modify your method of restricting users.
add_action( 'admin_init', function() {
    if ( (defined('DOING_AJAX') && DOING_AJAX) || ( strpos($_SERVER['SCRIPT_NAME'], 'admin-post.php') ) ) {
        return;
    }

    if ( !current_user_can('manage_options') ) {
        wp_redirect( home_url('/meu-perfil') );
        exit();
    }
}


text:
Q: How to execute run.py script in venv in flask for windows? I am following the miguel grinberg tutorial for flask.
When it comes to running the script from python interpreter in virtualenv, I am stuck. First I will like to know what he means by this step? How to run it?
To my understanding: I installed flask inside my microblog folder, with the virtualenv flask command that is mentioned. The following is my file structure: C:\Users\myuser\microblog\flask and I have stored the run.py file in the folder Scripts which is in flask folder.
I tried to run the flask\Scripts\python run.py command from the python.exe file in scripts, but no success.

A: Normally you do not write any of your files inside the virtual environment. Put the run.py file in C:\Users\myuser\microblog\. Then cd to this directory and run the application with:
flask\Scripts\python run.py


text:
Q: How to animate a search box in android I'm wondering if it's possible to animate a search item in action bar. Currently when I touch it, it just collapses. But I want it to collapse with a nice animation.
I googled this but I didn't find anything.
this is my search menu item :
<item android:id="@+id/search"
      android:title="@string/action_search"
      android:icon="@drawable/ic_action_search"
      app:showAsAction="collapseActionView|ifRoom"
      app:actionViewClass="android.support.v7.widget.SearchView" />

A: I am using slide from right to left animation, when tap on search icon in actionbar searchview will open from right to left animtion, you can apply any view
 in view:View to animate while calling slideFromRightToLeft(view: View)
Please check the following code, its in kotlin, you can covert it into java
private fun slideFromRightToLeft(view: View) {
    var animate = TranslateAnimation(view.width.toFloat(),0f, 0f, 0f);
    animate.duration = 100
    animate.fillAfter = true
    view.startAnimation(animate)
}


text:
Q: xslt Transformation for value list There are two value lists in source system with values mentioned below (old). In target system, same value lists exist but, with some different values. I need to put XSLT transformation so, old values of source system are transformed properly into target with new values.
Value list
01 Secondary_Fraud_Type

old values
AML
Code of Conduct Breach,
Commission,
Internal,
Misappropriation,
Theft of Funds,
Expenses.

Value list
01 Secondary_Fraud_Type

New Values:
AML/Suspicious Transactions,
Code of Conduct Violation,
Commission Scheme,
Internal Theft,
Misappropriation of Funds,
Misappropriation of Funds,
Expenses Travel.

Value list
02 Primary_Allegation_SubType

old Values:
Investigative Services - Special Inquiry:441 - Special Inquiry,
Investigative Services - General:298 - Locate.

Value list
02 Primary_Allegation_SubType

New Values:
Miscellaneous - Inactive:300 - Verification,
Not Required - Inactive:100 - Closing file,

Input:
<?xml version="1.0" encoding="UTF-16"?>
<Records count="2">
    <Record parentId="0" moduleId="75"
        levelGuid="b0c2d9a1-167c-4fee-ad91-4b4e7b098b4b" levelId="113" contentId="1010597">
        <Field type="6" guid="34c044c6-b841-4c52-b9f3-b7a56ed7dbd4" id="296">123529</Field>
        <Field type="6" guid="ab6c5129-ed5b-470d-b290-9a7d84123ad3" id="28384">1010597</Field>
        <Field type="4" guid="a0d192ea-9767-4c7e-8a56-4ff973141920" id="24284">
            <ListValues>
                <ListValue id="43156" displayName="Code of Conduct Breach">Code of Conduct Breach</ListValue>
                <ListValue id="43159" displayName="Expenses">Expenses</ListValue>
                <ListValue id="43160" displayName="Forgery">Forgery</ListValue>
                <ListValue id="46729" displayName="AML">AML</ListValue>
            </ListValues>
        </Field>
        <Field type="4" guid="52926f70-9a74-4799-8a14-8d25a1b062da" id="23396">
            <ListValues>
                <ListValue id="43085" displayName="Investigative Services - Special Inquiry:441 - Special Inquiry/Annuity">441 - Special Inquiry/Annuity</ListValue>
            </ListValues>
        </Field>
    </Record>
    <Record parentId="0" moduleId="75"
        levelGuid="b0c2d9a1-167c-4fee-ad91-4b4e7b098b4b" levelId="113" contentId="1011440">
        <Field type="6" guid="34c044c6-b841-4c52-b9f3-b7a56ed7dbd4" id="296">123564</Field>
        <Field type="6" guid="ab6c5129-ed5b-470d-b290-9a7d84123ad3" id="28384">1011440</Field>
        <Field type="4" guid="a0d192ea-9767-4c7e-8a56-4ff973141920" id="24284">
            <ListValues>
                <ListValue id="43157" displayName="Commission">Commission</ListValue>
                <ListValue id="43159" displayName="Expenses">Expenses</ListValue>
                <ListValue id="43161" displayName="Identity Theft">Identity Theft</ListValue>
                <ListValue id="43162" displayName="Internal">Internal</ListValue>
                <ListValue id="43163" displayName="Misappropriation">Misappropriation</ListValue>
                <ListValue id="43164" displayName="Misrepresentation">Misrepresentation</ListValue>
            </ListValues>
        </Field>
        <Field type="4" guid="52926f70-9a74-4799-8a14-8d25a1b062da" id="23396">
            <ListValues>
                <ListValue id="43056" displayName="Investigative Services - General:298 - Locate">298 - Locate</ListValue>
            </ListValues>
        </Field>
    </Record>
    <Metadata>
        <FieldDefinitions>
            <FieldDefinition guid="34c044c6-b841-4c52-b9f3-b7a56ed7dbd4" id="296" alias="Incident_ID" name="Incident ID" />
            <FieldDefinition guid="52926f70-9a74-4799-8a14-8d25a1b062da" id="23396" alias="Primary_Allegation_SubType" name="Primary Allegation Sub-Type" />
            <FieldDefinition guid="a0d192ea-9767-4c7e-8a56-4ff973141920" id="24284" alias="Secondary_Fraud_Type" name="Additional Fraud Types" />
            <FieldDefinition guid="ab6c5129-ed5b-470d-b290-9a7d84123ad3" id="28384" alias="Unique_Tracking_ID" name="Unique Tracking ID-I" />
        </FieldDefinitions>
    </Metadata>
    <LevelCounts>
        <LevelCount count="2" guid="b0c2d9a1-167c-4fee-ad91-4b4e7b098b4b" id="113" />
    </LevelCounts>
</Records>

Expected Output:  (Replaced with new values)
<?xml version="1.0" encoding="UTF-8"?>
<ex:Record xmlns:ex="http://archertech.com/Print/Export">
    <ex:Item>
        <ex:Incident_ID>INC-123529</ex:Incident_ID>
        <ex:Unique_Tracking_ID>1010597</ex:Unique_Tracking_ID>
        <ex:Secondary_Fraud_Type>
            <ex:Item>Code of Conduct Violation</ex:Item>
            <ex:Item>Expenses Travel</ex:Item>
            <ex:Item>Forgery</ex:Item>
            <ex:Item>AML/Suspicious Transactions</ex:Item>
        </ex:Secondary_Fraud_Type>
        <ex:Primary_Allegation_SubType>
            <ex:Item>Miscellaneous - Inactive:300 - Verification</ex:Item>
        </ex:Primary_Allegation_SubType>
    </ex:Item>
    <ex:Item>
        <ex:Incident_ID>INC-123564</ex:Incident_ID>
        <ex:Unique_Tracking_ID>1011440</ex:Unique_Tracking_ID>
        <ex:Secondary_Fraud_Type>
            <ex:Item>Commission Scheme</ex:Item>
            <ex:Item>Expenses Travel</ex:Item>
            <ex:Item>Identity Theft</ex:Item>
            <ex:Item>Internal Theft</ex:Item>
            <ex:Item>Misappropriation of Funds</ex:Item>
            <ex:Item>Misrepresentation</ex:Item>
        </ex:Secondary_Fraud_Type>
        <ex:Primary_Allegation_SubType>
            <ex:Item>Not Required - Inactive:100 - Closing file</ex:Item>
        </ex:Primary_Allegation_SubType>
    </ex:Item>
</ex:Record>

A: One of the solutions is to use a template approach for converting the old values to the new values and the old nodes to new nodes e.g. <Record> to <ex:Item> or <ListValue> to <ex:Item>
<xsl:template match="ListValue[@displayName = 'Code of Conduct Breach']" mode="updateDesc">
    <ex:Item><xsl:text>Code of Conduct Violation</xsl:text></ex:Item>
</xsl:template>

Below is the complete XSLT to get the output.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ex="http://archertech.com/Print/Export">
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <xsl:template match="Records">
        <ex:Record>
            <xsl:apply-templates />
        </ex:Record>
    </xsl:template>

    <xsl:template match="Record">
        <ex:Item>
            <xsl:apply-templates />
        </ex:Item>
    </xsl:template>

    <!-- Incident_ID -->
    <xsl:template match="Field[@id = '296']">
        <xsl:variable name="elemName" select="concat('ex:', ancestor::Records/Metadata/FieldDefinitions/FieldDefinition[@id = '296']/@alias)" />
        <xsl:element name="{$elemName}">
            <xsl:value-of select="concat('INC-',.)" />
        </xsl:element>
    </xsl:template>

    <!-- Unique_Tracking_ID -->
    <xsl:template match="Field[@id = '28384']">
        <xsl:variable name="elemName" select="concat('ex:', ancestor::Records/Metadata/FieldDefinitions/FieldDefinition[@id = '28384']/@alias)" />
        <xsl:element name="{$elemName}">
            <xsl:value-of select="." />
        </xsl:element>
    </xsl:template>

    <!-- Secondary_Fraud_Type -->
    <xsl:template match="Field[@id = '24284']">
        <xsl:variable name="elemName" select="concat('ex:', ancestor::Records/Metadata/FieldDefinitions/FieldDefinition[@id = '24284']/@alias)" />
        <xsl:element name="{$elemName}">
            <xsl:apply-templates mode="updateDesc" />
        </xsl:element>
    </xsl:template>

    <!-- Primary_Allegation_SubType -->
    <xsl:template match="Field[@id = '23396']">
        <xsl:variable name="elemName" select="concat('ex:', ancestor::Records/Metadata/FieldDefinitions/FieldDefinition[@id = '23396']/@alias)" />
        <xsl:element name="{$elemName}">
            <xsl:apply-templates mode="updateDesc" />
        </xsl:element>
    </xsl:template>

    <!-- ListValue -->
    <xsl:template match="ListValue" mode="updateDesc">
        <ex:Item><xsl:value-of select="." /></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Code of Conduct Breach']" mode="updateDesc">
        <ex:Item><xsl:text>Code of Conduct Violation</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Expenses']" mode="updateDesc">
        <ex:Item><xsl:text>Expenses Travel</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'AML']" mode="updateDesc">
        <ex:Item><xsl:text>AML/Suspicious Transactions</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Investigative Services - Special Inquiry:441 - Special Inquiry/Annuity']" mode="updateDesc">
        <ex:Item><xsl:text>Miscellaneous - Inactive:300 - Verification</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Commission']" mode="updateDesc">
        <ex:Item><xsl:text>Commission Scheme</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Internal']" mode="updateDesc">
        <ex:Item><xsl:text>Internal Theft</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Misappropriation'] | ListValue[@displayName = 'Theft of Funds']" mode="updateDesc">
        <ex:Item><xsl:text>Misappropriation of Funds</xsl:text></ex:Item>
    </xsl:template>
    <xsl:template match="ListValue[@displayName = 'Investigative Services - General:298 - Locate']" mode="updateDesc">
        <ex:Item><xsl:text>Not Required - Inactive:100 - Closing file</xsl:text></ex:Item>
    </xsl:template>
</xsl:stylesheet>


text:
Q: How to include a common file which loads many javascripts into the header of an HTML file I tried many ways, and can't figure how to do this.
I am loading number of external scripts in the header of many html files. Here is an example:
<script type="text/javascript"  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({  tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>

<script type="text/javascript" language="Javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>

<script type="text/javascript" src="http://www.wolfram.com/cdf-player/plugin/v2.1/cdfplugin.js"></script>

What is the best way to avoid having to copy and paste these again and again in each HTML file?
I could not put all of these in one common.js file and include that, since these already have <script> in them. i.e. I can't do this
<script src="common.js"></script>

Any idea how to do this? may be with jquery? (I know nothing about it). May be this is related? Jquery load() a html file which contains JavaScript
thanks

A: You can use the following commands multiple times in your common.js for each source you want to load. Just keep changing the node.src value.
    var node = document.createElement('script');
    node.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js";
    document.body.appendChild(node);

And you can choose where to add your script in body i.e. document.body.appendChild(node); or head i.e document.head.appendChild(node); of html


text:
Q: You provided 'undefined' where a stream was expected I am getting this in my Console. Since it's not pointing to my code I have no idea what it's all about:
TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:28)
at subscribeToResult (subscribeToResult.js:15)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:43)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/OuterSubscriber.js.OuterSubscriber.notifyError (OuterSubscriber.js:13)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._error (InnerSubscriber.js:18)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:59)
at Observable._subscribe (throwError.js:5)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:43)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:29)
at subscribeToResult (subscribeToResult.js:13)

Can someone please help?
Update. Here is the actual call:
this.http.get(`${environment.apiUrl}/api/home/`)
   .subscribe((data: any) => {console.log(data);
});

Update 2.
Here is my interceptor where it's most like happening:
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // add authorization header with jwt token if available
  request = this.addTokenToRequest(request);
  return next.handle(request);
  // .pipe(
  //   catchError((error: HttpErrorResponse) => {
  //     if (error instanceof HttpErrorResponse) {
  //       switch (error.status) {
  //         case 406: {
  //           return this.handle406Error(request, next);
  //         }
  //         // case 'Unauthorized': {
  //         //   // return this.handle401Error(request, next);
  //         // }
  //     }}
  //   }));
}

So, if I comment out .pipe I don't get the message. But I still want to process errors if any.
Update 3.
Here is the initial call:
ngOnInit(): void {
    this.http.get(`${environment.apiUrl}/api/web/home/`)
      .subscribe((data: any) => {
        console.log(data);
    });
}

A: In my case, this error was caused by a "circular reference". So basicly, the error didn't had anything to do with rxjs. Not directly at least, it was the json serialization that went wrong so the error was actually very misleading.
What I basicly have were 2 objects:
class Person {
    id: number;
    pets: Pet[];
}

class Pet {
    id: number;
    owner: Person;
}

When I retrieved a list of Persons, having a list of Pets, I wanted to relate all the pet.owner to their parent Person as these would not be the same by reference after retrieving from the server. So I had this code:
persons.forEach(person => person.pets.forEach(pet => pet.owner = person));

Now I have the circular reference of objects: person1 has pet1 which is linked to owner person1 which has pet1 which is linked to.... etc...
When person1 is attempt to get serialized to json, json doesn't know where to stop obviously and probably returns an undefined. And this undefined is passed to the rxjs where it expects a stream, observable etc. which is results in the error.
So, if you ever run in this error and you checked all the options that have been suggested but none of the suggestions works out, check the object you use in your rxjs operations. In my case it was the HttpClient.post where I sent along the object I wanted to post to the server.


text:
Q: error MSB6006: "svnversion.exe" exited with code 1 I am trying to get revision number from svn to put on my AssemblyInfo.cs file. I already made that on my computer and works fine. But when I use hudson to build and deploy my application automatically on server then this error appears. Anyone knows why?
Thanks!

A: This is because you are using a old version of svnversion.
Try to open the Command Line Prompt, navigate to the svnversion directory and do the same job as the MSBuild.
CMD:

cd C:\ProgramFiles\TortoiseSVN\bin
[ENTER]
svnversion C:\VisualStudio\Projects\YourDirectory
[ENTER]

SVNVERSION should answer why its not working, in my case was by E155021: This client is too old to work with thew working copy at...


text: Q: python code for lepton 2.5 thermal camera I am working the lepton2.5 thermal camera. after installing the libuvc, when i run the code uvc-radiometry.py it shows an error: could not find libuvc. Could you provide me a code that works in RPI 3.


text:
Q: remove a record from has_many without deleting from db? (rails 2.3.5) it looks like delete & destroy both remove the record from the db when dealing with a has_many. Is there anyway to not do this. In other words I would like to trim a has_mnay collection before passing it to a method but I dont want my changes to persist to the db. In trying it on the console, it seems to delete immediately when I do
second_acct = users.accounts[1]
users.accounts.delete(second_acct)

My use case would be something like I want to pass only checking accounts down to a method, so I want to remove these accounts from the user.

A: second_acct = users.accounts[1]
second_acct.update_attribute(:user_id, nil)

This should work.
Or this:
second_acct.user = nil
second_acct.save

A: How are your association set up?
collection.delete(object, …)
    Removes one or more objects from the collection by setting their foreign keys to NULL. Objects will be in addition destroyed if they're associated with :dependent => :destroy, and deleted if they're associated with :dependent => :delete_all.

So, if you don't want your records to be deleted and only the association to be cleared, remove :dependent => :destroy or :dependent => :delete_all option.


text:
Q: select2 bootstrap sizing issue I am trying to use a multiple select2 select form in my html with bootstrap. But I'm having issue with sizing, the select2 box is not working with the grid, and it also gurbles the size of next item. The html

    <select class="form-control s2" id="complaint" multiple="multiple" name=
    "complaint[]">
        <option value="bad_breath">
            Bad Breath
        </option>
        <option value="bleeding_gum">
            Bleeding Gum
        </option>
        <option value="swollen_gum">
            Swollen Gum
        </option>
        <option value="gum_pain">
            Gum Pain
        </option>
        <option value="loose_teeth">
            Loose Teeth
        </option>
        <option value="sensitive_teeth">
            Sensitive Teeth
        </option>
        <option value="darkened_teeth">
            Darkened Teeth
        </option>
        <option value="damaged_teeth">
            Damaged Teeth
        </option>
    </select>

The JS

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />

A: to fix the layout (widths not correct) you need to wrap the contents in a form-group:

    Label

       <select id="select" class="form-control s2" multiple="multiple" name="name[]" data-width="100%">
            <option value="o1">Option 1</option>
            <option value="o2">Option 2</option>
        </select>

Re the JS, I think there is an issue with codeply as copying the html and js and referencing the scripts and links directly in codepen works. See here for an example.


text:
Q: Sorting HTML Table with Javascript when clicking header Hello I am building an application in Spring - Java with Thymeleaf as a templating engine and I have a table and I would like to sort the columns with javascript when clicking on them. Here is my javascript code for sorting:

And this is the table:

        <input  type='text'  id='myInput0' onkeyup="myFunction0()"  placeholder='Cauta data creare'/>
      <input  type='text'  id='myInput1' onkeyup="myFunction1()" placeholder='Cauta CIF'/>
      <input  type='text' id='myInput2' onkeyup="myFunction2()" placeholder='Cauta ID Solicitare'/>
      <input  type='text' id='myInput3' onkeyup="myFunction3()" placeholder='Cauta detalii'/>
      <input  type='text' id='myInput4' onkeyup="myFunction4()" placeholder='Cauta tip'/>
      <input  type='text' id='myInput5' onkeyup="myFunction5()" placeholder='Cauta ID'/>

        DATA CREARE
      CIF
      ID SOLICITARE
      DETALII
      TIP
      ID
      DOWNLOAD

  <form action="/efactura/download/" method="get">
      <input type='hidden' name='id' th:value="${map.getId}" >
     <button type="submit" class="btn btn-primary"  >Download</button>
  </form>

When I press the column that for which I implemented the function I get this error:
 Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
    at sortTable (listamesaje:192:15)
    at HTMLTableCellElement.onclick (listamesaje:289:46)
sortTable @ listamesaje:192
onclick @ listamesaje:289

Line of code 192 is: if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
Can you please give me a working example or tell me what I am doing wrong. Thanks


text:
Q: How to use a pipes in a loop and pass on the values out of the loop I'm working on program which generates random numbers in a parentsprocess and transfers them with os.pipe to their childprocesses, so that they can print them and save them in an array. As for now, it only works with one number generated, instead of multiple, one after another. I tried to put the code of the generator in a while-loop but it seems that this breaks the pipes between the processes.
Code with while loop:
import os
import random
import time

r, w = os.pipe()
pid = os.fork()

r2, w2 = os.pipe()

if pid != 0:

    pid2 = os.fork()

#Loop in the parentsprocess

    if pid2 != 0:
        print("Parent")
        os.close(r)
        os.close(r2)
        #while Loop to infinitly generate numbers
        while True:
            n = random.sample(range(1, 1000), 1)
            zahlenstring = "".join(str(x) for x in n)
            pipe1 = zahlenstring.encode()
            pipe2 = zahlenstring.encode()
            os.write(w, pipe1)
            os.write(w2, pipe2)

    if pid2 == 0:
        print("Child2")
        os.close(w2)
        r2 = os.fdopen(r2)
        file = open("file.txt", "w")
        file.write(r2.read())
        file.close()

if pid == 0:
    r3, w3 = os.pipe()
    r4, w4 = os.pipe()
    os.close(w)
    pid3 = os.fork()
    if pid3 != 0:
        r = os.fdopen(r)
        verarbeiten=int(r.read())
        numbers = []
        numbers.append(verarbeiten)
        Sum = sum(numbers)
        mittelWert = (Sum / len(numbers))
        String1 = str(Sum)
        String2 = str(mittelWert)
        os.close(r3)
        os.close(r4)
        print("Child1")
        pipe3 = String1.encode()
        pipe4 = String2.encode()
        os.write(w3, pipe3)
        os.write(w4, pipe4)

    if pid3 == 0:
        os.close(r)
        print("Child from Child")
        os.close(w3)
        os.close(w4)
        r3 = os.fdopen(r3)
        print("Summe: ", r3.read())
        r4 =os.fdopen(r4)
        print("Mittelwert: ", r4.read())

Output:
Parent
Child2
Child from Child

Without the loop the generated number gets passed through the pipes into the grandchild.
Question: Where exactly is the problem with the pipes breaking when I use the loop and how do I properly build the pipes into the loop so that they keep passing the newly generated numbers to the child processes?
Thanks in advance!


text:
Q: Can't open Assembly-CSharp properties. Instantly closes I'm trying to change the root namespace on my project, which lives in the properties. Whenever I try open  Assembly-CSharp properties though, any scripts I have open will briefly flash blank and then nothing will happen. There's no error or signs it tried beyond that flash. I have no idea what to try.
Worth noting, this happen both from the project tab, and right clicking the assembly file in the solution explorer. This is also as a part of a Unity project, should that for some reason matter. I am using Visual Studio 2019 and it's fully up to date.
Thank you for any ideas.

A: If you want to change the root namespace of a Unity project, I suggest you do it via the Editor : https://docs.unity3d.com/Manual/class-EditorManager.html
If you have already done so, the rest might depend on your IDE. In any case, I suggest you check this out : How to change root namespace in unity

A: I am using Visual Studio 2019 as well and it happens there. It is a bug and it is easy to workaround it.
After getting the blank screen there are several easy workarounds you can do:

*

*Click on any other class and open it and then return back to the blank screen (it shouldn't be blank anymore).

*If the Solution Explorer is opened to you, you can change its size with the mouse, when you will change the size it will immediately show the page.

A: A friend was able to find the answer for me on this one. It turns out, Tools for Unity disablest the ability to access the properties.
To disable this go to Settings >> Tools for Unity >> General >> Miscellaneous >> Access to project properties
It turns out though, you don't need to do this anyways. I was mistaken that you need to do this in the Unity settings and the VS settings seperately, but VS will read from Unity. It's disabled because Unity will handle the project settings so they are set as expected for Unity use.


text:
Q: Custom environment contexts with behat We're using behat to run some functional tests on our system, simulating the journey of a user through our site. I've written some Contexts with definitions of things to check.
Because behat will be running on different environments (our dev PCs, then our staging server...) the @BeforeSuite function that runs needs different settings. I'd put them in behat.yml, with custom profiles, but I don't know how to read that information
So, what I'm asking is how can I get to the behat config info within my context file?

A: Parameters configured in behat.yml are injected into the main context file via a constructor (in Behat 2):
class FeatureContext extends BehatContext
{
    private $parameters;

    public function __construct(array $parameters)
    {
        $this->parameters = $parameters;
    }
}

However, since you use @BeforeSuite, context instance is not yet available (and hook method is static).
You can still fetch parameters from the event:
class FeatureContext extends BehatContext
{
    /** @BeforeSuite */
    public static function setup(SuiteEvent $event)
    {
        $parameters = $event->getContextParameters();
    }
}

Related docs: http://docs.behat.org/guides/3.hooks.html#suite-hooks


text:
Q: BeautifulSoup: How do I extract the text child element with no tag? I have the following html to parse. But I am having an issue extracting the Name only.

   #1

  Jeff Bezos

  CEO and Founder, Amazon

I am having an issue extracting the text for the name, as it is extracting the Rank alongwith it. I want to exclude the Rank showing up with the Name in the following line 2.
#1
#1 Jeff Bezos
CEO and Founder, Amazon

The code is as follows:
import requests
from bs4 import BeautifulSoup

URL = "https://www.forbes.com/profile/jeff-bezos/?list=forbes-400"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")

# Rank
rank = soup.find("span", class_="profile-heading__rank")
print(rank.text)

# Name
name = soup.find("div", class_="profile-heading--desktop").find("span").parent
print(name.text)

# Role
role = soup.find("div", class_="profile-subheading")
print(role.text)

A: You can use .find_next_sibling() method with text=True:
import requests
from bs4 import BeautifulSoup

URL = "https://www.forbes.com/profile/jeff-bezos/?list=forbes-400"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")

# Rank
rank = soup.find("span", class_="profile-heading__rank")
print(rank.text)

# Name
name = rank.find_next_sibling(text=True)    # <-- change
print(name)                                 # <-- .text is not necessary

# Role
role = soup.find("div", class_="profile-subheading")
print(role.text)

Prints:
#1
Jeff Bezos
CEO and Founder, Amazon

A: Use next_sibling from bs4 to navigate between page elements
name = soup.find("div", class_="profile-heading--desktop").find("span").next_sibling

docs: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling


text:
Q: How would I go about programmatically interacting with VST(i) Plugins to synthesize audio? Take, for example, the VSTi Triforce, by Tweakbench.  When loaded up in any VST host on the market, it allows the host to send a (presumably MIDI) signal to the VSTi.  The VSTi will then process that signal and output synthesized audio as created by a software instrument within the VSTi.
For example, sending an A4 (MIDI note, I believe) to the VSTi will cause it to synthesize the A above Middle C.  It sends the audio data back to the VST Host, which then could either play it on my speakers or save it to .wav or some other audio file format.
Let's say I have Triforce, and am trying to write a program in my language of choice that could interact with the VSTi by sending in an A4 note to be synthesized, and automatically saving it to a file on the system?
Eventually, I'd like to be able to parse an entire one-track MIDI file (using established, stable libraries already available for this purpose) and send it to the VSTi to "render"/synthesize it into an audio file.
How would I go about this, and in what language should I look to build the core framework?
Ultimately, it will be used in a Ruby-based project, so any pointers to specific Ruby resources would be nice as well.
However, I'm just trying to understand basically how the API of a VSTi works.  (I've realized that this question is very much related to the question of building a VST host in the first place, albeit one that can only save VST outputs to file and not play them back, and with considerably smaller scope)

A: Well, since you asked, the ideal language for a project like this is going to be C++.  Although there are wrappers for higher-level languages such as Java & .NET for the VST SDK, I couldn't find one for Ruby (though I did find this rather cool project which lets you program VST plugins in Ruby).  So you will be stuck doing some degree of C/C++ integration on your own.
That said, you have basically two options here:

*

*Write a VST Host in C++, and launch it as a separate process from within Ruby.

*Integrate your Ruby code directly to the VST SDK, and load the plugin DLL's/Bundles directly from your code.  This is probably the cleaner but harder way to accomplish your goal.

I wrote up a VST host programming tutorial on my blog awhile back which you may find useful in either case.  It details how you open and communicate with VST plugins on both Mac OSX and Windows.  Once you have gotten your host to load up the plugins, you need to be able to either send MIDI events directly to the plugin, either by reading them from file or some type of communication between your Ruby code and the VST host (ie, a named pipe, socket, file, etc.).  If you are unfamiliar with the MIDI protocol, check out these links:

*

*The MIDI technical fanatic's brainwashing center (silly name, serious resource)

*The Sonic Spot's MIDI file specification (in case you need to read MIDI files)

As you might have already figured out, VST is fundamentally a block-based protocol.  You request small blocks of audio data from the plugin, and you send along any MIDI events to the plugin right before it processes that respective block.  Be sure not to ignore the MIDI delta field; this will ensure that the plugin starts processing the MIDI event directly on the desired sample.  Otherwise, the plugin will sound a bit off-tempo, especially in the case of instruments.
The VST SDK is also based around floating-point blocks, so any data you get back will contain individual samples in the range { -1.0 .. 1.0 }.  Depending on your desired output format, you may need to convert these to some other format.  Fortunately, there seems to be a Ruby binding for the audiofile library, so you may be able to send your output into that in order to generate a proper AIFF/WAV file.
In all, it'll be a fair amount of work to get to your desired end goal, but it's not impossible by any means.  Good luck!


text:
Q: MouseInfo.getPointerInfo() - how to get cursor view With MouseInfo.getPointerInfo() there is a way to get mouse x,y position which are outer the Java app... And it is fine
But what about the mouse cursor view itself? I mean is there a way to know is the current cursor has a look like DEFAULT or HAND or POINTER or ...? Can it be done with pure Java?

A: You can use
Cursor.getDefaultCursor.getType()


text:
Q: can't.....since vs. haven't......since I read the first sentence on FB (I know, this is not the right place to look for perfect grammar) and would like to know if this is right:

I can't sleep well since last week

I thought a construction like this needs the present perfect 'have been':

I haven't been able to sleep well since last week

The person who wrote the first construction is a native speaker of English which is why I'm so confused. Is it slang or just another way of saying it?

A: This is a good lesson that you can't always trust what native speakers write.  Of course, sometimes it's impossible to know if the odd grammar is just slang or laziness.
You are correct, and the sentence should be:

I haven't been able to sleep well since last week.

to indicate an ongoing condition, or simply

I can't sleep well.

to indicate a present condition.

A: Well, it depends on who you ask. In general, there are two schools of thought when it comes to linguistics: prescriptivism and descriptivism.
Prescriptivists would say…

*

*language rules exist in an explicit form in a codified standard ("the norm");

*people say utterances based on these codified rules;

*the correct form is determined by what the standard is;

*ergo, if a form is correct, native speakers should use it.

Descriptivists would say…

*

*language rules exist in an implicit form in subconsciousness of its users ("the usus");

*people say utterances based on these subconscious rules;

*the correct form is determined by how people speak;

*ergo, if native speakers use a form, this form is correct.

So, in short, a prescriptivist would say that the first form doesn't follow the codified rules, thus, it is incorrect. On the other hand, a descriptivist would say that since the first one is used more often than the other one, it is a better description of the usus.
While the first line of thought (prescriptivism) might seem to you more down-to-earth and that's probably what you have been taught at school, the second one (descriptivism) is the one regarded more scientific in academic circles (and probably subscribed to by more professional linguists).

TLDR: a linguist will likely say it is correct (because a native said so), while a pedagogue will likely say it isn't. There is no common approach.

A: It's

I can't been able to sleep well since last week

because you don't have it, you can or can't do it.


text:
Q: Can logging to syslog from inside a container be visible to host's syslog? I have a C application that uses syslog API for logging. This application is further running inside a docker container (FROM ubuntu 20.04)
I am trying to collect the logs from container using the syslog driver.
Did it as documentation says, so running the container with "--log-driver syslog" option.
The documentation also says that logs captured from a container are only the ones from STDOUT and STDERR streams.
STDOUT stream reaches HOST with priority = 6 (INFO),
STDERR stream reaches HOST with priority = 3 (ERROR obviously)
I need a method to see in the hosts syslog the logs from container exactly in the same way I would see them from application running natively. (with different priorities)


text:
Q: choose same file in path list file in another path list file I have a list of path file
image_list1 = ['/content/gdrive/MyDrive/Match/bed/2.jpg','/content/gdrive/MyDrive/Match/bed/4.jpg']

and
image_list1=['/content/gdrive/MyDrive/Match/chairs/4.jpg','/content/gdrive/MyDrive/Match/chairs/3.jpg','/content/gdrive/MyDrive/Match/chairs/2.jpg','/content/gdrive/MyDrive/Match/chairs/1.jpg']

what is the code How I can create another list like this line
image_list3=['/content/gdrive/MyDrive/Match/chairs/2.jpg','/content/gdrive/MyDrive/Match/chairs/4.jpg']

I have two folders beds and chairs?

A: Try:
bed_list = [
    "/content/gdrive/MyDrive/Match/bed/2.jpg",
    "/content/gdrive/MyDrive/Match/bed/4.jpg",
]

chair_list = [
    "/content/gdrive/MyDrive/Match/chairs/4.jpg",
    "/content/gdrive/MyDrive/Match/chairs/3.jpg",
    "/content/gdrive/MyDrive/Match/chairs/2.jpg",
    "/content/gdrive/MyDrive/Match/chairs/1.jpg",
]

tmp = {i.rsplit("/", maxsplit=1)[-1] for i in bed_list}

out = [i for i in chair_list if i.rsplit("/", maxsplit=1)[-1] in tmp]
print(out)

Prints:
[
    "/content/gdrive/MyDrive/Match/chairs/4.jpg",
    "/content/gdrive/MyDrive/Match/chairs/2.jpg",
]


text:
Q: Разделить txt файл на части Есть файл listing.txt, а в нем слова такого рода:
слово 1
слово 2
....
слово 4444
слово 4445

Разбиваю его на list1.txt, list2.txt... по 400 строк:
<?php
$lines = file("listing.txt");

$fc = 1;

$lc = 400; // по сколько строк в файле

$fp = fopen("list1.txt", "a");

for ($i=0; $i<count($lines); $i++)
{
fwrite($fp, $lines[$i]);
if ($i/$lc==floor($i/$lc) and $i!=0)
  {
  fclose($fp);
  $fc += 1;
  $fp = fopen("list".$fc.".txt", "a");
  }
}
fclose($fp);
?>

В конце каждого файла остается пустая строка:
слово 1
слово 2
....
слово 399
слово 400
и тут пустая строка (401 строка)

Как ее удалить, исправив этот скрипт?
A: Держи нормальный вариант
Определяем функцию - создание порций из файла.
Параметры:
$filename- путь до исх файла;
$sizeporcii - кол-во строк в файле порции;
$mask- маска файла порции;
    function createporcii($filename,$sizeporcii,$mask)
    {
        $file=file($filename);
        $countporcii=ceil(count($file)/$sizeporcii);
        for ($i=0;$i<$countporcii;$i++)
            {
                file_put_contents($mask.($i+1).'.txt',array_merge(array_slice($file,$sizeporcii*$i,($sizeporcii-1)),array(trim($file[($i+1)*$sizeporcii-1]))));
            }
    }

вызываем
    createporcii('1111_.txt',400,'list');


text:
Q: b2Circle shape not rotating on b2Polygon shape Box2d Cocos2dx well i have a car whose wheels are not moving forward while rotating on a rectangular block.
wheels -> b2CircleShape
rectangular block -> b2PolygonShape
i have given both the densities and friction . still nothing !
Specifically i have a wheel-joint operating between car chassis and wheels.
i want the car to move forward by giving the wheel-joint motor a positive speed.
Code :
b2PolygonShape boxSahpe;
boxSahpe.SetAsBox(68/PTM_RATIO, 40/PTM_RATIO);

b2BodyDef bd;
bd.type = b2_dynamicBody;

bd.position.Set(8.85f, 10.0f);
bd.userData = this;
body = world->CreateBody(&bd);
body->CreateFixture(&boxSahpe, 1.0f);

b2BodyDef circleBD;
circleBD.type = b2_dynamicBody;

b2CircleShape circle;
circle.m_radius = 0.4f;

b2FixtureDef fd;
fd.shape = &circle;
fd.density = 1.0f;
fd.friction = 0.9f;

// left
circleBD.position.Set(7.70f, 9.0f);
m_wheel1 = world->CreateBody(&circleBD);
m_wheel1->CreateFixture(&fd);

// right
circleBD.position.Set(9.75f, 9.0f);
m_wheel2 = world->CreateBody(&circleBD);
m_wheel2->CreateFixture(&fd);

b2WheelJointDef jd;
b2Vec2 axis(0.0f, 1.10f);

jd.Initialize(body, m_wheel1, m_wheel1->GetWorldCenter(), axis);
jd.motorSpeed = 0.0f;
jd.maxMotorTorque = 20.0f;
jd.enableMotor = true;
jd.frequencyHz = m_hz;
jd.dampingRatio = m_zeta;
m_spring1 = (b2WheelJoint*)world->CreateJoint(&jd);

jd.Initialize( body,m_wheel2, m_wheel2->GetPosition(), axis);
jd.motorSpeed = 0.0f;
jd.maxMotorTorque = 10.0f;
jd.enableMotor = false;
jd.frequencyHz = m_hz;
jd.dampingRatio = m_zeta;
m_spring2 = (b2WheelJoint*)world->CreateJoint(&jd);

m_spring 1 & 2 -> b2WheelJoint
m_wheel 1 & 2 -> b2Body
body -> b2Body

A: I really recommend you use the debug draw display, otherwise it's like guessing with your eyes closed. In this case I think you would have immediately seen the problem yourself - here is what your situation is like when I try it:

With low values of frequencyHz (eg. 2) for the wheel joints, they do not have enough stiffness to hold the main body off the ground. You can make the frequencyHz higher (about 4 seems enough to get it moving), but I'm guessing you probably want to make the main body smaller as well.


text:
Q: Drap/ drop item use CDK in angular grid layout I want to build the function drag/drop using CDK show grid layout like
this demo: https://tiberiuzuld.github.io/angular-gridster2/
But can't do that. I can only do it like this demo https://angular-dragdrop-grid-dj41ya.stackblitz.io and https://angular-6dq2i1.stackblitz.io
NOTE: I don't want to use the gridster library. It just needs to use CDK in angular like what I did in the example above.
Hope everyone can help me. Thank so much


text:
Q: Program to print duplicate values of array only once in C++ int array[5]={3,3,3,3,1,1};
output:
3 1
I am unable to do this, please help me out. I tried 2 for loops with boolean check , it didn't work.
  int main()
  {
    int a[5]={3,3,3,1,1};
    int n=sizeof(a)/sizeof(a[0]);

    for (int i =0 ; i<n; i++){
       bool checked=true;
          for (int j=0 ;j<i; j++){
                 if(a[i]==a[j]){
                  bool checked=false;
        }
    }
    if(checked==true){
        cout<<a[i]<<",";
    }
}

}

A: I used a function to remove duplicate values from the array and then printed the array without the duplicates. I don't have boolean functions.
int removeDuplicate (int arr[], int size) {
    if (size == 0 || size == 1) {
        return size;
    }
    int* temp = new int[size]; /* Create a temporary
    array with size*/
    int j = 0;
    for (int i = 0; i < size - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            temp[j++] = arr[i]; //strore element if its unique
        }
    }
    temp[j++] = arr[size - 1];
    for (int i = 0; i < j; i++) {
        arr[i] = temp[i]; //modify the existing array
    }
    return j; //j is the new size for the array without duplicates
}

int main(){
    int arr[5] = {3,3,3,1,1};

    int size = removeDuplicate(arr, 5);

    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ; ";
    }
}

A: Please note bool checked=false; you are defining again checked variable.
Please see the fix.

  int main()
  {
    int a[5]={3,3,3,1,1};
    int n=sizeof(a)/sizeof(a[0]);

    for (int i =0 ; i<n; i++)
    {
       bool checked=true;
        for (int j=i+1 ;j<n; j++)
        {
            if(a[i] == a[j])
            {
                checked=false;
            }
        }
        if(checked == true)
        {
            std::cout<<a[i]<<",";
        }
    }
}

output : 3,1,
Even you can do it in a better way with std::unique algorithm.
#include <iostream>     // std::cout
#include <algorithm>    // std::unique, std::distance
#include <vector>       // std::vector

int main () {
  int a[5]={3,3,3,1,1};         // 3 3 3 1 1
  std::vector<int> myvector (a, a+5);

  // Sorting the array
  std::sort(myvector.begin(), myvector.end());

  // using default comparison:
  auto it = std::unique (myvector.begin(), myvector.end());

  myvector.resize( std::distance(myvector.begin(), it));

  // print out content:
  std::cout << "myvector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

output : myvector contains: 3 1


text:
Q: How do you determine the location of a Vagrantfile from virt-manager? OS is Debian 10, vagrant provider is libvirt.
vagrant global-status is supposed to provide information on all vms on a system, but I can see shutoff and running vms in virt-manager that are not listed by vagrant global-status. I have only used libvirt for Vagrant so I know Vagrant is the culprit.
How do I determine the associated directory/Vagrantfile for each of these vms?
I think this command would do the trick:
find / -name Vagrantfile -exec echo {} \; -exec bash -c 'cd "$(dirname {})" && vagrant status | grep -E shutoff\|running' \; 2>/dev/null
But it seems absurd that something like this would be necessary, and would take a very long time on a large filesystem.
How exactly can I determine the directory for the associated Vagrantfile for each vm? There must be an easier way besides exhaustively searching the filesystem.

A: Based on the template [1], Vagrant does not seem to keep track of the project directory associated with the VM in libvirt domain metadata.
Internally Vagrant keeps the info about the VM (including the directory) in a JSON file ~/vagrant.d/data/machine-index/index, check the example [2]
I guess it's possible to modify the template to add the directory as a metadata, similar to how Openstack Nova add some metadata to the Guest's libvirt domain, the metadata can be used to get the VM name, Flavor, etc. directly from the compute node without querying Nova.
Obviously this does not apply to the existing VMs prior the change.
[1] https://github.com/vagrant-libvirt/vagrant-libvirt/blob/master/lib/vagrant-libvirt/templates/domain.xml.erb
[2]
cat .\index | python -m json.tool
{
    "version": 1,
    "machines": {
        "4f9bf5cd740f409c867553c19c52a81c": {
            "local_data_path": "C:/Vagrant-Machines/bionic-vm/.vagrant",
            "name": "default",
            "provider": "hyperv",
            "state": "running",
            "vagrantfile_name": null,
            "vagrantfile_path": "C:/Vagrant-Machines/bionic-vm",
            "updated_at": null,
            "extra_data": {
                "box": {
                    "name": "hashicorp/bionic64",
                    "provider": "hyperv",
                    "version": "1.0.282"
                }
            }
        }
    }
}

For reference, here how the metedata looks in the case of Nova:
 virsh dumpxml instance-0033dd00 | head
<domain type='kvm' id='93'>
  <name>instance-0033dd00</name>
  <uuid>XXXXXXXXXXXXXXXXXXX</uuid>
  <metadata>
    <nova:instance xmlns:nova="http://openstack.org/xmlns/libvirt/nova/1.0">
      <nova:package version="17.0.13"/>
      <nova:name>VM-NAME</nova:name>
      <nova:creationTime>2021-05-11 10:50:49</nova:creationTime>
      <nova:flavor name="m1.small">
        <nova:memory>16384</nova:memory>


text:
Q: Java Dynamic Web Project HTTP Status 500 - Error instantiating servlet class I use Apache Tomcat Server 8.0, getting HTTP Status 500 - Error instantiating servlet class.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>THTTagTravel</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

In index.jsp:
<FORM action="TestServlet" method=get>

...

<Input Type=submit value="submit">
</FORM>

Update:
The database I used was constructed by Neo4J 2.2, I was using Neo4j2.3 in this project. I reconstructed the database, on other modification needed.

A: *

*add your servlet class in web.xml
<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.example.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/servlet/TestServlet</url-pattern>
</servlet-mapping>

*Make sure your path of servlet i.e. /yourPorjectDirectory/WEB-INF/classes


text:
Q: Save on webpage with command line like in google chrome I need to grab one webpage (single page, not all site) with all his assets(images/css) in command line.
I really like how google chrome do it - if I save webpage I get single html file and single directory with all assets. Moreover all paths to images are changed to local ones, and all links are absolute (if it was "/pricing", it becomes "http://example.com/pricing").
I know I can do it with wget, but I don't like the result - many directories (if there was images from different domains), and html file is somewhere in directory (with domain name)..
I really like the result after saving page with google chrome and I need to know if you know some command line crawlers which makes similar result.
Or you know how to configure wget to do it like I need?

A: Thank you all for your suggestions!
What I need was --no-directories parameter to wget. Then I get one directory with all files I need (html file, images, css files).
Sorry, the question wasn't well formulated.


text:
Q: What is the best way to pass data between views? I have done some research and still didn't found a solution that seems correct, in a "best practices" way.
I'm working on a App for iPhone using Xamarin. This app will be initial iPhone only, but there are plans to make versions for Android and Windows Phone in the near future.
This App crete/saves a "Moment". This moment have some pictures plus some information. Basically, this moment will be used all over the App, been incremented with more data from lots of views.
While I do save this moment to some kind of repository (SQL, filesystem, ..., I still have to implement this), I need it to be alive thru the workflow.
One way of doing it, would be:
var moment = new Moment()
// .. add infos from view to moment
nextView.Moment = moment;
PerformSegue(...);

Is this the right way of doing it? There isn't any pattern that I could use to solved it from all platforms and control better how to pass this infos between the views (samples would be appreciated)?

A: You might have seen even apple is using the singleton pattern to access the current application instance to open the URL its just an example
UIApplication.SharedApplication.OpenUrl(urlToSend)

So in your case Singleton is right choice make sure you are not putting everything here because its a performance hit.
so use singleton when you have no other ways of doing it.
Here is my sample thread safe code for making the singleton class
using System;
namespace MySingletonPattern
{
   sealed class Singleton
   {
      //To make the thread safe access we need an instance
      private static readonly object _lockObj = new object();

      //Lazy initialisation for the real instance
      private static volatile Singleton _instance;

      private Singleton()
      {
      }

      static internal Singleton Instance()
      {
         if (_instance == null)
         {
            //To make the access Thread safe
            lock(_lockObj)
            {
               if(_instance == null)
               {
    //Creating the instance of singleton class and this will be re-used
                  _instance = new Singleton();
               }
            }
         }
         return _instance;
      }
   }
}

Here is how to use it
Singleton obj1 = Singleton.Instance();

A: You could use the Singleton pattern to get access to your data in every point of your app.
Check out the Wiki page(with a sample):
http://en.wikipedia.org/wiki/Singleton_pattern

A: I generally pass the data as an argument in the constructor of the view, then inside the view keep a reference to it as a local variable.
However, if you are using the same piece of data globally throughout your app, then it might be better to use a Singleton, or just a static class.

A: If you create a singleton, you can access it anywhere in the app. Creating a singleton in ios, using a static method:
+ (Moment *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedObject = [[self alloc] init];
    });

    return sharedObject;
}

A: You are right, singleton seems the best choice.
For future references, my singleton class:
public sealed class CurrentMoment
{
    private static CurrentMoment s_instance;
    //private Moment m_moment;
    private CurrentMoment()
    {
    }

    public static CurrentMoment Instance
    {
        get
        {
            if (s_instance == null)
                s_instance = new CurrentMoment();

            return s_instance;
        }
    }

    /// <summary>
    /// Gets or sets the moment.
    /// </summary>
    /// <value>The moment.</value>
    public Moment Moment
    {
        get;
        set;
    }
}

A:
There isn't any pattern that I could use to solved it from all platforms and control better how to pass this infos between the views (samples would be appreciated)?

I'm not sure what your workflow is. Would it be conceivably atomic within one platform? That is, if user Fred has an Android tablet and an iPhone, he's not going to create a Moment on one platform and finish the workflow on the other?
If so, store it in the model (the part of the application that is independent of the platforms iOS, Windows Mobile, Android). This is basic Model-View separation, if your views change with different platforms. The singleton for CurrentMoment proposed by Giusepe makes sense to me.
If the workflow isn't "interruptable" between platforms, then don't bother with a persistent CurrentMoment.

A: You can also extend the Application class
public class HelloApplication : Application
{
    public static int GlobalVariable = 1;
}


text:
Q: Get all properties and subproperties from a class I am using reflection to get a class name, and need to get all sub properties of the class, and all the sub properties' properties.
I am running into a recursion issue where the items get added to the incorrect list.
My code is as follows:
private List<Member> GetMembers(object instance)
{
    var memberList = new List<Member>();
    var childMembers = new List<Member>();

    foreach (var propertyInfo in instance.GetType().GetProperties())
    {
        var member = new Member
        {
            Name = propertyInfo.PropertyType.IsList() ? propertyInfo.Name + "[]" : propertyInfo.Name,
            Type = SetPropertyType(propertyInfo.PropertyType),
        };

        if (propertyInfo.PropertyType.IsEnum)
        {
            member.Members = GetEnumValues(propertyInfo).ToArray();
        }

        if (propertyInfo.PropertyType.BaseType == typeof(ModelBase))
        {
            var childInstance = propertyInfo.GetValue(instance) ?? Activator.CreateInstance(propertyInfo.PropertyType);

            childMembers.AddRange(GetMembers(childInstance));

            member.Members = childMembers.ToArray();
        }

        if (propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
            propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            var itemType = propertyInfo.PropertyType.GetGenericArguments()[0];

            var childInstance = Activator.CreateInstance(itemType);

            childMembers.AddRange(GetMembers(childInstance));

            member.Members = childMembers.Distinct().ToArray();
        }

        memberList.Add(member);
    }

    return memberList;
}

A: I can't know for certain since I don't have the knowledge of your code to debug and test it; however, I believe your problem may be stemming from the fact that you're re-using  the childMembers list. Let me know if this is not the case.
private List<Member> GetMembers(object instance)
{
    var memberList = new List<Member>();

    foreach (var propertyInfo in instance.GetType().GetProperties())
    {
        var childMembers = new List<Member>(); // Moved to here, so it's not shared among all propertyInfo iterations.
        var member = new Member
        {
            Name = propertyInfo.PropertyType.IsList() ? propertyInfo.Name + "[]" : propertyInfo.Name,
            Type = SetPropertyType(propertyInfo.PropertyType),
        };

        if (propertyInfo.PropertyType.IsEnum)
        {
            member.Members = GetEnumValues(propertyInfo).ToArray();
        }

        if (propertyInfo.PropertyType.BaseType == typeof(ModelBase))
        {
            var childInstance = propertyInfo.GetValue(instance) ?? Activator.CreateInstance(propertyInfo.PropertyType);

            childMembers.AddRange(GetMembers(childInstance));

            member.Members = childMembers.ToArray();
        }

        if (propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>) ||
            propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
        {
            var itemType = propertyInfo.PropertyType.GetGenericArguments()[0];

            var childInstance = Activator.CreateInstance(itemType);

            childMembers.AddRange(GetMembers(childInstance));

            member.Members = childMembers.Distinct().ToArray();
        }

        memberList.Add(member);
    }

    return memberList;
}

A: Wouldn't the following do?
public static IEnumerable<PropertyInfo> GetProperties(this Type type, int depth = 1)
{
    IEnumerable<PropertyInfo> getProperties(Type currentType, int currentDepth)
    {
        if (currentDepth >= depth)
            yield break;

        foreach (var property in currentType.GetProperties())
        {
            yield return property;

            foreach (var subProperty in getProperties(property.PropertyType,
                                                      currentDepth + 1))
            {
                yield return subProperty;
            }
        }
    }

    if (depth < 1)
        throw new ArgumentOutOfRangeException(nameof(depth));

    return getProperties(type, 0);
}

Given the following type:
class Foo
{
    public string S { get; }
    public int I { get; }
}

The output of
Console.WriteLine(string.Join(Environment.NewLine,
                  typeof(Foo).GetProperties(2)
                             .Select(p => $"{p.DeclaringType.Name}: {p.Name}")));

would be:
Foo: S
String: Chars
String: Length
Foo: I


text:
Q: Random effect model in r I'd like to know the appropriate command to run a random-effect model under the software R.
I tried :
library(plm)
Model=plm(df$IndVar ~ df$densite + df$sexe + df$age_cat + df$production, data=df, index=c("village"), model="random")

But I got this answer :
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
  0 (non-NA) cases
In addition: Warning message:
In Ops.factor(e1, e2) : '-' not meaningful for factors

I also tried :
library(nlme)
Model=lme(df$IndVar ~ df$densite + df$sexe + df$age_cat + df$production, random=~1|village)

And I got :
Error in eval(predvars, data, env) : object 'IndVar' not found

What to do ? Need your help.