text:
Q: Field 'id' expected a number but got Estoy recibiendo este error en mi nuevo proyecto en Django.
Código de la vista (view.py):
from django.shortcuts import render, redirect
from django.http import HttpResponse
from basic_app.models import productos
from basic_app.forms import products_form
from django import forms

model_name = productos.__name__

def add_products (request):
    if request.method == 'POST':
        form = productos(request.POST)
        form.save()
        return redirect('productview_base_products')
    else:
        form = products_form()

    return render(request, 'add_products.html',
                  {"form":form})

Acá el error preciso:

TypeError: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['KF3qMrop5Crow0A2jJ1LnQwjNSDMcUhapFaSayslukSwyW3yiTzvrAhJ1sNPzLxM'], 'code': ['11'], 'name': ['david'], 'price': ['45'], 'note': ['amarillo']}>.

El error completo

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'QueryDict'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/__init__.py", line 1776, in get_prep_value
    ) from e
TypeError: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['KF3qMrop5Crow0A2jJ1LnQwjNSDMcUhapFaSayslukSwyW3yiTzvrAhJ1sNPzLxM'], 'code': ['11'], 'name': ['david'], 'price': ['45'], 'note': ['amarillo']}>.
[01/Apr/2020 21:24:50]

El campo 'Id' debería auto-incrementarse pero no comprendo porque no toma el numero que le corresponde (en este caso el 1), y mas bien recibe un QueryDic
Ya probé volver a ejecutar las migraciones pero es lo mismo
Dejo también el código de la definición del modelo:
class productos(models.Model):

    code = models.IntegerField()
    name = models.CharField(max_length=30)
    price = models.IntegerField()
    note = models.CharField(max_length=100)
    active = models.BooleanField()

Y el código de la ejecución de la migración:

class Migration(migrations.Migration):

    dependencies = [
        ('basic_app', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='productos',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.IntegerField()),
                ('name', models.CharField(max_length=30)),
                ('price', models.IntegerField()),
                ('note', models.CharField(max_length=100)),
                ('active', models.BooleanField()),
            ],
        ),
    ]

Quedo atento a sus comentario y gracias...

A: El error se debe a que estas creando una instancia con los parámetros HTTP POST (un QueryDic, una clase tipo diccionario personalizada para manejar parámetros HTTP):
if request.method == 'POST':
    form = productos(request.POST)

Debes enviar los parámetros HTTP POST, al form, no al modelo:
if request.method == 'POST':
    form = products_form(request.POST)

Tu vista debería quedar así (por se acaso te olvidaste de validar el formulario):
def add_products (request):
    if request.method == 'POST':
        form = productos_form(request.POST)
        if form.is_valid(): # Entra al if si el form es valido.
            form.save()
            return redirect('productview_base_products')
    else:
        form = products_form()

    return render(request, 'add_products.html',
                  {"form":form})

Espero haberte ayudado.


text:
Q: how do you prove that the MLE is sufficient for an exponential family? I read (sorry only found such theorem in french https://perso.math.univ-toulouse.fr/jydauxoi/files/2013/11/cours_stat_inf_Master.pdf ) that whenever there exists an sufficient statistics for an exponential familly, then the maximum likelihood estimator is a function of it.
I'd like to prove something lighter, how do you prove that the MLE of an exponential family is sufficient ?
thank you.

A: I think the logic is more or less along these lines, following convention of wikipedia:
For a distribution belonging to the natural exponential family, the likelihood function given the data $x$ is of the form
$$\ell(\eta)=\exp\left\{\eta\,T(x)-A(\eta)\right\}h(x)$$
Here note that $T$ is a sufficient statistic for the parameter $\eta$.
Then the equation $\frac{\partial}{\partial\eta}\ln \ell(\eta)=0$ has the unique solution $A'(\eta)=T(x)$, assuming $T(x)$ is in the range of $A'(\eta)$. Moreover, $\frac{\partial^2}{\partial\eta^2}\ln \ell(\eta)=-A''(\eta)=-\operatorname{Var}(T)$ (see wiki).
Since variance is non-negative, $-\ln \ell(\eta)$ is convex in $\eta$ and $T(x)$ is the unique MLE of the parameter $\mu(\eta)=A'(\eta)$. The function $\mu$ is one-to-one so that $\mu^{-1}$ exists. Therefore by invariance, MLE of $\eta$ is $\hat\eta=\mu^{-1}(T(x))$.
In case you have a general exponential family, the likelihood function can be written as $$\ell(\theta)=\exp\left\{\eta(\theta)T(x)-B(\theta)\right\}h(x)$$
Now the MLE of $\theta$ is $\hat\theta=\eta^{-1}(\hat\eta)$, provided $\eta^{-1}$ exists and $\eta$ is in the range of $\eta(\theta)$.
Here also $\hat\theta$ satisfies the likelihood equation $\frac{\partial}{\partial\theta}\ln\ell(\theta)=\eta'(\theta)T(x)-B'(\theta)=0$.
So the MLE in an exponential family always turns out to be a function of a sufficient statistic. If this function is one-to-one, then the MLE is itself sufficient. These results can be generalised in similar manner for the case when the parameter is vector-valued.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cloudtrail using terraform I'm creating a cloudtrail using terraform. The problem is my source bucket keeps changing after 3 months. Now I want to give the dynamic S3 bucket value for field_selector.
I'm doing something like this:
    resource "aws_cloudtrail" "test" {
        name = "test_trail"
        s3_bucket_name = bucket.id
        enable_logging = true
        include_global_service_events = true
        is_multi_region_trail = true
        enable_log_file_validation = true

        advanced_event_selector {
          name = "Log download event data"
          field_selector {
            field = "eventCategory"
            equals = ["Data"]
          }
          field_selector {
            field = "resources.type"
            equals = ["AWS::S3::Object"]
          }
          field_selector {
            field = "eventName"
            equals = ["GetObject"]
          }
          field_selector {
            field = "resources.ARN"
            **starts_with = ["aws_s3_bucket.sftp_file_upload_bucket.arn"]**
          }
        }

Here, I'm giving the arn but logs are not getting created this way but if I hard code the bucket name it's getting created.

A: When you want to log the object events for a bucket, the ARN is not enough. As the AWS CLI documentation states [1]:

For example, if resources.type equals AWS::S3::Object , the ARN must be in one of the following formats. To log all data events for all objects in a specific S3 bucket, use the StartsWith operator, and include only the bucket ARN as the matching value. The trailing slash is intentional; do not exclude it.

So in your case you would have to fix the last field selector to:
field_selector {
  field = "resources.ARN"
  starts_with = ["${aws_s3_bucket.sftp_file_upload_bucket.arn}/"]
}

[1] https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/put-event-selectors.html#id11

A: when using an attribute of a resource you should either specify it like
"${aws_s3_bucket.sftp_file_upload_bucket.arn}"
or without quotes like
aws_s3_bucket.sftp_file_upload_bucket.arn
so, the correct version would be
      field_selector {
        field = "resources.ARN"
        starts_with = [aws_s3_bucket.sftp_file_upload_bucket.arn]
      }


text:
Q: Как удалить записи событий в vSphere Client Как можно выборочно удалить записи на вкладке "События" в vSphere Client.
Система VmWare Esxi 5.5.  VCenter не развернут.

A: нет никакой возможности удалить Events, Tasks из системы. Все это храниться в базе данных, к которой нет доступа. Конечно, если вы не взломали базу данных.
но можно их все почистить так, чтобы через консоль не были видны.
если есть доступ к самой машине с клавиатурой, то Console Menu - Restart  Network Management Agents.
или выполнить удаленно через SSH
/sbin/services.sh restart

Это никак не затронет работу VM. Эвенты не удалит из самой БД для будущего аудита, но позволит очистить ВСЕ события и таски из UI


text:
Q: How to create ajax update time? I'm creating partial view.
I need to get number of seconds that have passed since 2012.04.01
public PartialViewResult SitePowered()
{
    var dateTime = new DateTime(2012, 4, 1);
    var totalSeconds = (DateTime.Now - dateTime).TotalSeconds;
    ViewBag.TotalSeconds = totalSeconds;
    return PartialView("SitePowered");
}

view:
<script type="text/javascript">
    $(function () {
        $.getJSON("/Home/SitePowered", null, setTime);
    });
</script>
@ViewBag.TotalSeconds секунд

but it does not work

A: You have to do something like this:
Action:
public ActionResult SitePowered()
{
    var dateTime = new DateTime(2012, 4, 1);
    var totalSeconds = (DateTime.Now - dateTime).TotalSeconds;
    return Json(new { seconds = totalSeconds });
}

Client-side:
<script type="text/javascript">
    $(function () {
        $.getJSON("/Home/SitePowered", function(result) {
              // Do something here with result.seconds
              alert(result.seconds);
        });
    });
</script>

Hope it helps.


text:
Q: How to lock an item in QListWidget Qt is it possible to lock on an item in QListWidget, so when I press for example: a button, the item stays selected?
I have tried to look it up but I failed

A:
I really hope you can provide me with an example, since I am just a beginner

Yes, I can. Here we go:
testQListWidgetLockSelection.cc:
#include <set>

#include <QtWidgets>

class ListWidget: public QListWidget {

  public:
    using QListWidget::QListWidget;
    virtual ~ListWidget() = default;

    void lockSelection(bool lock);

    virtual void selectionChanged(
      const QItemSelection &selected,
      const QItemSelection &deselected) override;

  private:
    bool _lockSel = false;
    std::set<int> _selLocked;
    bool _lockResel = false;

    struct LockGuard {
      bool &lock;
      LockGuard(bool &lock): lock(lock) { lock = true; }
      ~LockGuard() { lock = false; }
    };
};

void ListWidget::lockSelection(bool lock)
{
  _lockSel = lock;
  if (_lockSel) {
    // store selected indices
    for (const QModelIndex &qMI : selectedIndexes()) _selLocked.insert(qMI.row());
  } else _selLocked.clear();
}

void ListWidget::selectionChanged(
  const QItemSelection& selected, const QItemSelection& deselected)
{
  if (_lockSel && !_lockResel) {
    const LockGuard lock(_lockResel);
    QItemSelection reselect;
    for (int row : _selLocked) {
      const QModelIndex qMI = model()->index(row, 0);
      reselect.select(qMI, qMI);
    }
    selectionModel()->select(reselect, QItemSelectionModel::Select);
  }
}

void populate(QListWidget& qLstView)
{
  for (int i = 1; i <= 20; ++i) {
    qLstView.addItem(QString("Item %1").arg(i));
  }
}

int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QWidget qWinMain;
  qWinMain.resize(640, 480);
  qWinMain.setWindowTitle("Lock Selection Demo");
  QVBoxLayout qVBox;
  QCheckBox qTglLockSel("Lock Selection");
  qVBox.addWidget(&qTglLockSel, false);
  ListWidget qLstView;
  qLstView.setSelectionMode(ListWidget::ExtendedSelection);
  qVBox.addWidget(&qLstView, true);
  qWinMain.setLayout(&qVBox);
  qWinMain.show();
  // install signal handlers
  QObject::connect(&qTglLockSel, &QCheckBox::toggled,
    &qLstView, &ListWidget::lockSelection);
  // fill GUI with sample data
  populate(qLstView);
  // runtime loop
  return app.exec();
}

Demo:

Note:
This sample has a weakness: It doesn't consider that items may be inserted or removed after the selection has been locked.
To enhance this, the member functions rowsInserted() and rowsAboutToBeRemoved() had to be overridden as well to correct the indices in ListWidget::_selLocked respectively.


text:
Q: Create a StartDate and EndDate column after value change using either T-SQL, DAX or M Query I have a table as follows:
Date /  Name  / OldValue  / NewValue
I want a way to create a Start Date & End Date columns using any of the following : DAX , T-SQL or M Query.
Meaning; the StartDate is the [Date] and the End the date is the Date where the same person will change value.
Thanks in advance.

A: Using Power Query M, you can follow these steps:

*

*In my demo data the columns came in sorted correctly, but you can use this code to ensure they are:
#"Sort Table" = Table.Sort(#"Changed Type",{{"Name", Order.Ascending}, {"Date", Order.Ascending}})

*Add an Index column > Add Column > Index Column > From 0 (It HAS to be from 0)

*Add Column > Custom Column > name End Date >
if [Name] <> #"Added Index" [Name] {[Index] + 1} then null else Date.AddDays(#"Added Index" [Date] {[Index] + 1},-1)

*Right-click End Date > Replace Errors > Replace with null

*Adjust column order as needed

*Rename New Value column to "Value", rename Date column to "Start Date".  Remove unneeded columns
Source and Output:

EDIT: I should add that this works okay on a small data set, but on a larger one you may run into performance issues.  In that case you should duplicate the query, add an index starting at 0 for one query, and on the other query start an index at 1.  Then you can merge the two together to extract the necessary dates and values.


text:
Q: How to get Advanced Statistical Data from MySQL? Hi,

I have a very large MySQL database with a table having structure like this:
In the exmaple, the DATE is in unix timestamp format. So it will need to be
converted to normal US date format and this is just a few records from my DB.

ID      DATE
REG_TYPE
--------------------------------------
1     1251917888
0
2     1251917888
1
3     1251917888
1
4     1251917888
0
5     1251917888
2
6     1251917888
3
7     1251917888
2
8     1251917888
4
9     1251917888
0
10   1251917888
0

The problem is that i want to get the count of every REG_TYPE ordered by date.
The table below of what i want to get is shown:

DATE         REGTYPE(0)
REGTYPE(1)     REGTYPE(2)     REGTYPE(3)
REGTYPE(4)
--------------------------------------------------------------------------------------------------
xxxx
4
2
2
1
1
xxxx
x
x
x
x
x

I want to get this for each and every date in database just like a summary for
each date.

Can anybody suggest a possible solution to this? I have to convert this output
into an array in PHP after fetching data from MYSQL. Reason for not using loops
in PHP for this is that the database is too big and will cause timeouts.

Best Regards

A: What you want to do is a pivot operation, which is not directly supported by SQL syntax. However, it's not too complicated, and conceptually involves 2 steps:

*

*"Blow up" the data into many columns, with one row per row in the original data set. This is usually done with CASE WHEN ... ELSE ... END or occasionally with functions (like decode() in oracle). I'll use CASE WHEN in the example below, since it works equally well for most RDBMSes

*Use GROUP BY and aggregate functions (SUM, MIN, MAX, etc) to collapse the many rows into the output row set you want.

I'm using this data set for the example:
mysql> select * from foo;
+----+------------+----------+
| id | thedate    | reg_type |
+----+------------+----------+
|  1 | 1251917888 |        0 |
|  2 | 1251917888 |        1 |
|  3 | 1251917888 |        1 |
|  4 | 1251917888 |        0 |
|  5 | 1251917888 |        2 |
|  6 | 1251917888 |        3 |
|  7 | 1251917888 |        2 |
|  8 | 1251917888 |        4 |
|  9 | 1251917888 |        0 |
| 10 | 1251917888 |        0 |
| 11 | 1251831488 |        1 |
| 12 | 1251831488 |        2 |
| 13 | 1251831488 |        2 |
| 14 | 1251831488 |        1 |
| 15 | 1251831488 |        3 |
| 16 | 1251831488 |        4 |
| 17 | 1251831488 |        3 |
| 18 | 1251831488 |        5 |
| 19 | 1251831488 |        1 |
| 20 | 1251831488 |        1 |
+----+------------+----------+

Step 1 is to "blow up" the data set:
select id
     , thedate
     , case when reg_type = 0 then 1 else 0 end as reg_type_0
     , case when reg_type = 1 then 1 else 0 end as reg_type_1
     , case when reg_type = 2 then 1 else 0 end as reg_type_2
     , case when reg_type = 3 then 1 else 0 end as reg_type_3
     , case when reg_type = 4 then 1 else 0 end as reg_type_4
     , case when reg_type = 5 then 1 else 0 end as reg_type_5
  from foo;

which gives:
+----+------------+------------+------------+------------+------------+------------+------------+
| id | thedate    | reg_type_0 | reg_type_1 | reg_type_2 | reg_type_3 | reg_type_4 | reg_type_5 |
+----+------------+------------+------------+------------+------------+------------+------------+
|  1 | 1251917888 |          1 |          0 |          0 |          0 |          0 |          0 |
|  2 | 1251917888 |          0 |          1 |          0 |          0 |          0 |          0 |
|  3 | 1251917888 |          0 |          1 |          0 |          0 |          0 |          0 |
|  4 | 1251917888 |          1 |          0 |          0 |          0 |          0 |          0 |
|  5 | 1251917888 |          0 |          0 |          1 |          0 |          0 |          0 |
|  6 | 1251917888 |          0 |          0 |          0 |          1 |          0 |          0 |
|  7 | 1251917888 |          0 |          0 |          1 |          0 |          0 |          0 |
|  8 | 1251917888 |          0 |          0 |          0 |          0 |          1 |          0 |
|  9 | 1251917888 |          1 |          0 |          0 |          0 |          0 |          0 |
| 10 | 1251917888 |          1 |          0 |          0 |          0 |          0 |          0 |
| 11 | 1251831488 |          0 |          1 |          0 |          0 |          0 |          0 |
| 12 | 1251831488 |          0 |          0 |          1 |          0 |          0 |          0 |
| 13 | 1251831488 |          0 |          0 |          1 |          0 |          0 |          0 |
| 14 | 1251831488 |          0 |          1 |          0 |          0 |          0 |          0 |
| 15 | 1251831488 |          0 |          0 |          0 |          1 |          0 |          0 |
| 16 | 1251831488 |          0 |          0 |          0 |          0 |          1 |          0 |
| 17 | 1251831488 |          0 |          0 |          0 |          1 |          0 |          0 |
| 18 | 1251831488 |          0 |          0 |          0 |          0 |          0 |          1 |
| 19 | 1251831488 |          0 |          1 |          0 |          0 |          0 |          0 |
| 20 | 1251831488 |          0 |          1 |          0 |          0 |          0 |          0 |
+----+------------+------------+------------+------------+------------+------------+------------+

Next we collapse to one row in the output per date, and sum each of the reg_type_* columns, using or initial query as an inline view (aka a "subquery"):
select thedate
     , sum(i.reg_type_0) as reg_type_0
     , sum(i.reg_type_1) as reg_type_1
     , sum(i.reg_type_2) as reg_type_2
     , sum(i.reg_type_3) as reg_type_3
     , sum(i.reg_type_4) as reg_type_4
     , sum(i.reg_type_5) as reg_type_5
  from (
         select id
              , thedate
              , case when reg_type = 0 then 1 else 0 end as reg_type_0
              , case when reg_type = 1 then 1 else 0 end as reg_type_1
              , case when reg_type = 2 then 1 else 0 end as reg_type_2
              , case when reg_type = 3 then 1 else 0 end as reg_type_3
              , case when reg_type = 4 then 1 else 0 end as reg_type_4
              , case when reg_type = 5 then 1 else 0 end as reg_type_5
           from foo
       ) i
 group by thedate
 order by thedate asc;

(Note also that you can collapse these two queries into one, though I've shown them separately here for clarity; In MySQL at least, this seems to result in a simpler execution plan, which often means faster execution -- as always, test your SQL performance on realistic data sets, don't take my word for it!)
This gives us:
+------------+------------+------------+------------+------------+------------+------------+
| thedate    | reg_type_0 | reg_type_1 | reg_type_2 | reg_type_3 | reg_type_4 | reg_type_5 |
+------------+------------+------------+------------+------------+------------+------------+
| 1251831488 |          0 |          4 |          2 |          2 |          1 |          1 |
| 1251917888 |          4 |          2 |          2 |          1 |          1 |          0 |
+------------+------------+------------+------------+------------+------------+------------+

Which is the desired result. You can convert thedate to a DATE with the MySQL function FROM_UNIXTIME, and it will likely be most efficient to do this in the part #2 query (the function is evaluated fewer times, and comparisons for group by are made on the integer, not on the DATE -- not sure if that's actually any different in MySQL).

A: apart of having an output like the one you've posted(the example output you've posted is a pivot table), you have to use the COUNT BY statement
for example:
SELECT `DATE`, COUNT(*)
FROM `TABLE_NAME`

GROUP BY `REG_TYPE`

A: You can emulate a pivot table in mysql using something like the following:
SELECT
 SUM(REG_TYPE = 0) AS reg_type_0,
 SUM(REG_TYPE = 1) AS reg_type_1,
 SUM(REG_TYPE = 2) AS reg_type_2,
 SUM(REG_TYPE = 3) AS reg_type_3,
 SUM(REG_TYPE = 4) AS reg_type_4,
 TO_DAYS(FROM_UNIXTIME(date)) AS day_number
FROM my_table
GROUP BY TO_DAYS(FROM_UNIXTIME(date))

The date manipulation bits may need some tweaking.

A: You can query all the values of REG_TYPE (if you don't know them in advance) and then assemble something like this (sorry, my MySQL is rusty):
select date,
  SUM(IF(REGTYPE=0, 0, 1) AS REGTYPE0,
  SUM(IF(REGTYPE=1, 0, 1) AS REGTYPE1,
  SUM(IF(REGTYPE=2, 0, 1) AS REGTYPE2,
  SUM(IF(REGTYPE=3, 0, 1) AS REGTYPE3,
  SUM(IF(REGTYPE=4, 0, 1) AS REGTYPE4
  FROM table
  GROUP BY date


text:
Q: C# algorithm - listing all permutations of number This is sort of a follow up to a question I posted earlier (C# algorithm - find least number of objects necessary), but a bit different.
Given I have the following code:
var max = 80;
var list = new[]{10,20,30,40,50, 60);

I want to generate a array containing all the possible combinations I can use those numbers in the list to get to that max number.
The array would contain, {40, 40}, {50, 30}, {40,30, 10} etc...

A: You'll want to iterate over all the numbers in descending order.  Then recursively add each next descending number in the sequence.  Each time the sum matches, note that combo, pop out, and move on.  When your tentative sum takes you over the max variable, pop out of the function to the next function in the stack.  If the max still hasn't been reached, successively add the next number down in the sequence.  In this way you will cover ever possible sequence, with no duplicates (unless there are duplicates in the given set, in which case you would want that duplicate).  It will be not too much code actually.

A: The naive approach is to simply generate every combination of numbers possible, and see if they add up to the target number.
Needless to say, this has hideous time complexity. But it does the job for small lists.
EDIT: Actually, if you're allowing repeated numbers, this doesn't work. An alternative algorithm (which allows repeats, but not any negatives) is to basically keep adding up the highest number in the list, and then backtrack if you go over the target.


text:
Q: WIreless mouse stop working for few sec I'm using Ubuntu 13.04 and my Logitech M510 wireless mouse stop working for few sec after not moving it for few sec. I changed the batteries for new one but the issue is still present. I'm using it on my laptop since playing Minecraft with a touch pad is not recommended.
If I keep moving the mouse around, it will work, but it is only when I stop touching it for like 3 seconds that it freeze for 1 or 2 seconds, even more sometime.
What can I do to solve this issue?
Thanks.

A: Your mouse is most likely auto sleeping after a given delay.
Logitech says that the M510 should have a 15-30 second delay before sleeping, so I don't think it's the mouse's problem alone.
It's possible that you're experiencing general autosuspend for USB devices.
Hopefully these links help:
How to disable auto power off of usb devices like usb mouse?
USB Mouse sleeping after 5 seconds when on battery


text:
Q: Compare columns but exclude specific pairs I want to write query to compare columns between two tables but to exclude specific pairs which point to the same thing but are written differently.

ID
Name

1
NYSE

2
OTC

3
OTC

ID
Name

1
New York Stock Exchange

2
NASDAQ

3
Over the Counter

This means that I when I compare columns to see which pairs are different the only result that I will have is ID 2 OTC - NASDAQ. The rest should be excluded because NYSE = New York Stock Exchange and OTC = Over the Counter.
How can I do this?

A: If you have some kind of lookup table, you could use a NOT EXISTS to check the value isn't in the other table:
SELECT ST.[Name]
FROM dbo.SecondTable ST
WHERE NOT EXISTS (SELECT 1
                  FROM dbo.LookupTable LT
                       JOIN dbo.FirstTable FT ON LT.FirstTableID = FT.ID
                  WHERE LT.SecondTableID = ST.ID);

A: One of the solution is to create lookup table:
DECLARE @Table_1 TABLE
(ID int NOT NULL, Name VARCHAR(50) NULL)

DECLARE @Table_2 TABLE
(ID int NOT NULL, Name VARCHAR(50) NULL)

DECLARE @Table_LookUp TABLE
(ShortName VARCHAR(50), Name VARCHAR(50) NULL)

Then insert data:
INSERT INTO @Table_1 (
    ID, Name
)
VALUES
  (1, 'NYSE')
, (2, 'OTC')
, (3, 'OTC')

INSERT INTO @Table_2 (
    ID, Name
)
VALUES
  (1, 'New York Stock Exchange')
, (2, 'NASDAQ')
, (3, 'Over the Counter')

INSERT INTO @Table_LookUp
(
    ShortName,
    Name
)
VALUES
(   'NYSE', -- ShortName - varchar(50)
    'New York Stock Exchange'  -- Name - varchar(50)
    )
, ('OTC', 'Over the Counter')

and the query should just check whether it does not exist in look up table:
SELECT * FROM @Table_2 AS t2
WHERE NOT EXISTS
(
    SELECT * FROM @Table_LookUp AS lp
    INNER JOIN @Table_1 AS t1 ON t1.Name = lp.ShortName
        AND lp.Name IN (t2.Name)
)


text:
Q: Works in jsfiddle but not on my website This problem is confusing. On jsfiddle it works http://jsfiddle.net/mdanz/aXjH5/16/.
When you press #bid-up the number should rise and stop on mouseup/mouseleave.
On my website the mouseup/mouseleave doesn't work, there are no errors in firebug.  Also if i remove .live() from the #bid-up and just do $('#bid-up').mousedown(function() { the #bid-up button doesn't work.  Any ideas on what is wrong, could the problems be connected?  I can't post a link to the website seeing as i'm still developing it.
HTML:

<input type='text' style='color:#707070;font-size:26px;margin-right:5px;text-align:center;width:100px;font-family:arial;' id='bid-price' readonly value='5.1' />

up

JavaScript:
$('#bid-up').live('mousedown', function() {

    var button = $(this);

    button.data('interval', setInterval(function() {

        var number = button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val();
        var newnumber = number.split('.');
        var on = button.attr('data-on');

        button.siblings('#bid-down').attr('data-on', '1');

        if (newnumber[1] < 9) {
            var first = newnumber[0];
            var second = parseInt(newnumber[1]) + 1;
        }

        if (newnumber[1] == 9) {
            var first = parseInt(newnumber[0]) + 1;
            var second = 0;
        }

        var finalnumber = first + '.' + second;
        button.parent('div').siblings('#bid-child-container-2').find('#bid-price').val(finalnumber);

    }, 200));

}).bind('mouseup mouseleave', function() {
    clearInterval($(this).data('interval'));
});


text:
Q: Send header parameter in Angular I'm using this method for login:
  doLogin(username, password){
    return this.http.post(Config.BASE_URL + '/login',{
      username: username,
      password: password

    })
  }

And I wanna add header parameter to this scope:
  doLogin(username, password){
    return this.http.post(Config.BASE_URL + '/login',{
      username: username,
      password: password,
      headers: {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
      }

    })
  }

I checked console and it didn't send header. What's wrong? How can I solve it?

A: you need to send your Headers inside a Json Variable called headers like:
return this.http.post(Config.BASE_URL + '/login', body, { headers: this.headers });
You are sending the Headers inside your body.

A: Use Headers from the http module of Angular:
import { Http, Headers } from '@angular/http';
let header1 = 'test';
let header2 = 'test2';
let headers = new Headers();
headers.append('header1', header1);
headers.append('header2', header1);

doLogin(username, password){
    return this.http.post(Config.BASE_URL + '/login',{
      username: username,
      password: password,
      headers: headers
    })
  }

A: The issue with your code is that you are sending the Headers inside your body.Try following code snippet
doLogin(username, password){
     var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')

    return this.http.post(Config.BASE_URL + '/login',{username:username,password:password},{headers:headers})

  }

If you want to POST using x-www-form-urlencoded
you can do this using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded and encode the body properly.
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);

this.http.post(Config.BASE_URL + '/login', body).map(...);

A: if interest in send auth credentials
    let headers = new Headers();
    headers.append('Authorization' , 'Basic ' +
        btoa(username
                + ':' + password));
    headers.append('Content-Type' , 'application/x-www-form-urlencoded; charset=UTF-8');
    this._http.get(url , {headers:headers});

A: let headers = new Headers();
headers.append('Content-Type', 'application/json');

let options = new RequestOptions({ headers: headers });
return this.http.post(Config.BASE_URL + '/login',{
      username: username,
      password: password
    } , options)


text:
Q: ngRoute infinite loop when changing path on a root event I'm not sure why, but when I catch an event from JQuery, update the route and notify Angular of the change, it goes into an infinite route. It's easy to reproduce, say you have a screen like this:

The click of the button is handled by jQuery, because the jquery library doesn't seem to work in a directive so I put it in a service. Once the controller loads I initialize this. Then when the user clicks that button, I catch this jquery event, and raise a new event on the root scope so that I know to navigate to the new view. Here's the code:
(function(angular, $) {
  var app = angular.module('app', ['ngRoute']);

  app.config(['$locationProvider', '$routeProvider',
    function config($locationProvider, $routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'list.html',
            controller: 'ListController'
        });

        // The view I am trying to reach via jquery event.
        $routeProvider.when('/Edit', {
            templateUrl: 'edit.html',
            controller: 'ListController'
        });

        $locationProvider.html5Mode(true);
    }]);

    app.controller('ListController',
      function ListController($scope, $rootScope, $location, JQuerySerivce) {
        // Initialize the button click listener.
        JQuerySerivce.registerBtn();

        $rootScope.$on('clicked', function() {
          $location.path("./Edit");
          // Notify angular stuff happened.
          $scope.$apply();
        });
    });

    app.controller('EditController', function EditController() {
      console.log("Edit view loaded!");
    });

    app.factory("JQuerySerivce", function ($rootScope){
      return {
        registerBtn: function() {
          $('#jqueryBtn').on('click', function() {
            $rootScope.$broadcast('clicked');
          });
        }
      };
    });

})(angular, jQuery);

The working plunker example:
https://embed.plnkr.co/WIwRreYtofGKQWdjTeQx/
[EDIT]
To clarify my question, how can I prevent this infinite loop from happening? All of the other quesitons I've found concerning routing and infinite loops have usually been some sort of mistake that introduces a loop. In this case I'm just navigating and the framework is dying. Maybe my approach is wrong? I'm open to changing it if anyone has an alternative. I can't escape the jquery event though :/ Any help would be much appreciated.

A: $location.path("/Edit");
instead of
$location.path("./Edit");
?


text:
Q: Error building Selenium+Maven: missing pom.xml I am new to Selenium and Maven tools. Trying to set up the Selenium 2.0 Java project using Maven, via this guide.
After creating and saving pom.xml in my project directory, I run mvn clean install and get the following error:
(...)
The goal you specified requires a project to execute but there is no POM
 in this directory (C:\Users\User\Documents\TestAutomation). Please verify you invoked Maven from the
 correct directory. -> [Help 1]

My pom.xml looks like this, as in the example from the link:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>2.45.0</version>
            </dependency>
        </dependencies>
</project>

I have Maven 3.3.1 and Java 1.8.0 installed on Windows 7.
Any idea, what am I doing wrong? I have little experience with testing tools in general.

A: OK, the problem was with the file extension. It was actually saved as pom.xml.txt, not pom.xml as I expected. (found that via dir command)


text:
Q: Giraffe and AspNetCore.Identity: Error opening Binary File Although my project starts and works fine, in visual studio code it is constantly stating that I have an error with my module call.
The file looks like
module GTest.App

but I am getting an error that reads:
Error opening binary file 'C:\Users\emoore\.nuget\packages\microsoft.aspnetcore.identity.ui\2.1.11\lib\netstandard2.0\Microsoft.AspNetCore.Identity.UI.dll': A positive number is required.
Parameter name: capacity //F# Compiler(229)

Is anybody aware of what is causing this issue? It does not stop me from developing, but it is extremely annoying.

A: I had the same problem and resolved it by

*

*Updating to latest dotnet core 3.1 sdk

*Updating Giraffe to latest version

*Be sure to update fsproj file as you won't need to reference the Microsoft.AspNetCore packages anymore

Hope this helps. Unfortunately I'm dealing with a similar issue with NSwag now.


text:
Q: Read/Write File in blackberry I am writing to a file using this code.
        protected void writeFile(String text) {
            DataOutputStream os = null;
            FileConnection fconn = null;
                try {
                    fconn = (FileConnection) Connector.open("file:///store/home/user/documents/file.txt", Connector.READ_WRITE);
                    if (!fconn.exists())
                        fconn.create();
                    os = fconn.openDataOutputStream();
                    os.write(text.getBytes());
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                } finally {
                    try {
                        if (null != os)
                            os.close();
                        if (null != fconn)
                            fconn.close();
                    } catch (IOException e) {
                        System.out.println(e.getMessage());
                    }
            }}

the code is working fine.
My problem is if I write first time "Banglore" and when I read it, I get "Banglore".
But, second time when I write "India" and when I read it, I get, "Indialore".
so, basically  its content is not changing according the text , I am giving.
Please tell me how to fix this.

A: writing in a file doesn't remove the content but it just replaces the content, so writing 'india' over 'Bangalore' will replace the 'Banga' with 'India' and the rest would remain the same. If you want to completely remove old content with newer one, you need to truncate()
the file from where the newer data ends. truncate(text.getBytes().length)


text:
Q: WordPress: Hide page element if there is no database data to fill it Hopefully this is simple to solve. I have a few elements which pull in form data previously entered into the database, which are added to the post as custom fields. I extract this using a php query as such:
<a href="<?php echo get_post_meta($post->ID, 'societywebsite', true); ?>" target="_blank" >Website

Obviously, this appears in the Loop (content.php) and will get added to any appropriate post. Sometimes, however, there won't be any data because a user chose not to enter a website into the 'societywebsite' field on a form. When this happens, there's no need for a link to 'Website' to be there, because it wouldn't go anywhere useful.
What I'd like to know is how to have an If clause that checks if the data exists and then shows the link only if it does. I don't mind javascript, but the cleaner and less 'hacky' the solution, the better, as content.php will run multiple times for search results.
Thanks so much for any help or advice you can provide.

A: Another way to do this, more according to the Wordpress Codex is the following...
$societywebsite = get_post_meta($post->ID, 'societywebsite', true);

if ($societywebsite != '') {
    echo 'Website';
}

You can add an 'else' at the end of this for debugging purposes.

A: Assuming that field is a string for a url, you could do something like this.
if (strlen(get_post_meta($post->id, 'societywebsite', true)) < 1) {
    echo 'ID, 'societywebsite', true) . '" target="_blank" >Website';
}

That will very simply check if that field has a string that is more than 1 characters.  If it is more than 1 characters, it will display the link.  If not...it won't do anything.


text:
Q: Why is $\int_0^x \int_0^u f(t)(u-t)dt \,du = \int_0^x\int_0^uf(t)(x-u)dt\,du$? In this question I learned that $$\int_0^x \int_0^u f(t)(u-t)dt \,du = \int_0^x\int_0^uf(t)(x-u)dt\,du.$$
I've been trying to come up with an intuitive reason why this should be so, like a geometric argument for example. Can someone think of one?

A: Since $f$ is arbitrary, it should be eliminated from the identity; it does not contribute anything to its meaning. To this end, it helps to change the order of integration, because then $f$ can be taken out of the inner integral. The identity becomes
$$\int_0^x f(t)  \int_t^x (u-t)\,du  \,dt  = \int_0^x f(t) \int_t^x (x-u)\,du\, dt$$
(Concerning the limits: note that the integration takes place over $0\le t\le u\le x$).
Again, $f$ is arbitrary: the only way for these integrals to be equal is if the inner integrals are equal: $$\int_t^x (u-t)\,du = \int_t^x (x-u)\,du$$
Which indeed has a geometric interpretation: two triangles with the same base and height have the same area. On the plot below, $[t,x]=[2,5]$.


text:
Q: Receiving an Unknown iOS Notification -- Audio Only I occasionally receive an iOS notification (an Apple push notification) that has sound only and no text.  Because it has no text, it does not appear in the notification center and I therefore cannot determine what app is causing this.  Kind of annoying.
Is there anyway to identify which app is sending an audio-only notification?

A: Yes, you can, you just have to do some digging around to find the particular one that is causing the noise. If you go into your Settings application on your iDevice, and go into the Notifications Options Tab and look for apps that have the sounds attribute available.  As seen the in the screen shot below highlighted in red.

Selecting that one will take you further into the customizations and see if the app is sending other notifications, as shown below, this one does sound and badge and can be seen in the lock screen.  Toggling those on and off will help you find the culprit.

You will be looking for an App that is only making noise, look for one that says noise only and everything else is turned off, that one will most likely be the problem.  You can then turn on other notifications so that it will be more helpful. If you find more than one app that is noise only, enable more notification types to help you narrow down which one it is. Once you find it, you can disable it or change the setting any which way you want.
I hope that this answer helps you narrow down the noisy notifier.

A: How to find the source of a sound on an iPhone? suggests it may be GMail.  One of the answers offers a way to trace it to a specific app.


text:
Q: Trouble explaining gap between _edata_loc and __bss_start in linux linker file I have trouble understanding gap between addresses _edata_loc and __bss_start symbols. According to the linker file there should not be any gap, yet symbol __bss_start, seems to be aligned to 0x2000 byte boundary ? Am I missing something here?
I am running ARM Linux.
From system.map:
c08bcf60 D _edata
c08bcf60 D _edata_loc
c08bf000 B __bss_start
c08f98c8 B __bss_stop
c08f98c8 B _end

vmlinux.lds.S:
    _edata_loc = __data_loc + SIZEOF(.data);
   #ifdef CONFIG_HAVE_TCM
        /*I do not have TCM so neglect this part*/
   #endif
    BSS_SECTION(0, 0, 0)
    _end = .;

    STABS_DEBUG
}

BSS_SECTION is defined here:
http://lxr.free-electrons.com/source/include/asm-generic/vmlinux.lds.h#L843
After compilation the generated vmlinux.lds contains :
 _edata_loc = __data_loc + SIZEOF(.data);
 . = ALIGN(0); __bss_start = .; . = ALIGN(0); .sbss : AT(ADDR(.sbss) - 0) { *(.sbss) *(.scommon) } . = ALIGN(0); .bss : AT(ADDR(.bss) - 0) { *(.bss..page_aligned) *(.dynbss) *(.bss) *(COMMON) } . = ALIGN(0); __bss_stop = .;
 _end = .;


text:
Q: show informations section in opencart I am new in opencart.I have created new theme and copy the following code from footer file to header file. I have used following code to display information section in mytheme's header.

*">

Problem is that it shows error ": Undefined variable: informations". please help me regarding this. what causes that error.

A: Are you referring to the information section as in the information pages that Opencart has within the admin section, or you want to place information in the header?  Can you show an example of your header?

A: The problem is you need to load the information in the controller for the header catalog/controller/common/header.php from the footer catalog/controller/common/footer.php
    $this->load->model('catalog/information');

    $this->data['informations'] = array();

    foreach ($this->model_catalog_information->getInformations() as $result) {
        if ($result['bottom']) {
            $this->data['informations'][] = array(
                'title' => $result['title'],
                'href'  => $this->url->link('information/information', 'information_id=' . $result['information_id'])
            );
        }
    }

Once you do that you should be good to go


text:
Q: Bash command for output of only directories based on regex I am not too savvy with shell commands. But I was wondering if there was a way to list all ONLY the directories (no files) that contain a certain regex parttern?
For instance:
a/
   /dir1
      /d_332
         file1.txt
   /dir2
      /d_123
         file2.txt
   /dir3
      /dir4
         /dir5
            /d_444
               file3.txt

The regex I want to use is d_\d+ to find all directories that start with d_ and have a series of numbers. This it Python regex. I am not sure how different it is compared to bash regex
This command would give me an output of:
a/dir1/d_332/
a/dir2/d_123/
a/dir3/dir4/dir5/d_444/

A: Use the find utility:
find path -type d -regex '.*/d_[0-9]+'

path would in your case be a; it's the top of the directory tree find is going to search.
This uses two filters:

*

*-type d filters for directories, and

*-regex '.*/d_[0-9]+' filters for paths (full paths) that match the regex .*/d_[0-9]+. The regex is applied to the full path as find prints it, not just a part of it; that's why the .* at the beginning is required.

Those entries in the directory tree that match both filters are printed.
There's also a -regextype option that allows you to use a few different flavors of regular expressions, so you may want to take a look at the manpage.

A: try this :
 find . -type d -name 'd*[0-9]*'


text:
Q: How to keep previous plots and windows in Gnuplot? I have some problems of using gnuplot. I just begin with it.
(1)What is the command for keeping the previous plot when I plot new data? Do I have to plot the old data and the new data at the same time?
(2)What is the command for open a new window while keep the old ones? Do I have to set the window's id by using, e.g.,
    set terminal wxt 3
, before each plot?
Can anyone give me some help or some good references?

A: Usually, to plot several data set you would use
plot 'data1.dat', 'data2.dat'

You could also use replot to add one of the data sets later
plot 'data1.dat'
...
replot 'data2.dat'

To open a new window, you must use the window's id like with set terminal wxt 2. The old windows stay open, but you cannot interact with them anymore (zooming, scrolling etc.). See also the discussion to the quesiton Two interactive windows in Gnuplot with wxt terminal.

A: You already wrote the answers of your questions.
1.: You can use the replot command:
plot sin(x)
replot cos(x)

but this just expands to
plot sin(x), cos(x)

So, it replots all data and does not just add the cos(x).
2.: Yes, you can also switch between the windows to update the plots. But note that settings like ranges and labels are not stored per window / plot, but globally. If they are different for different plots, you have to change them every time.
You may also have a look at "set multiplot" to put several plots on one window / picture. But it is not so nice for interactive plotting, as you will notice.
Also, output terminals supporting multiple pages like pdfcairo will add a new page for each plot.


text:
Q: How to define a static route in traefik.io I am using traefik in a docker swarm. traefik works fine to route my frontends to the corresponding docker services.
My question is: Is it also possible to add a static route into the traefik.toml file which is just routing a request to a static web server which is outside of my docker-swarm?
For example:
incomming request for "http://www.myweb.com" should be redirected to "http://some.host.de:12345/"
some.host.de is not part of my docker network. It's an internet server and I just want traefik to reverse-proxy on port 80.
I can't find an example. But it seems that I need to define a [file] section like this in my traefik.toml file?
[file]

# rules
[backends]
  [backends.backendstatic1]
    # ...

[frontends]
  [frontends.frontendstatic1]
  # ...

How must this be completed?

A: You can try this:
[file]

[backends]

  [backends.backend1]

    [backends.backend1.servers]
      [backends.backend1.servers.server0]
        url = "http://some.host.de:12345"
        # note that you cannot add path in 'url' field

[frontends]

  [frontends.frontend1]
    entryPoints = ["http"]
    backend = "backend1"
    passHostHeader = true
    [frontends.frontend1.routes]
      [frontends.frontend1.routes.route0]
        rule = "Host:www.myweb.com"

https://docs.traefik.io/v1.5/configuration/backends/file/


text:
Q: SSRS Report Parameters Start date to be set for Friday when Current day is Monday I have a report parameters start date and end date both set for previous day. I have report subscription that runs on each day of the week. But, when it executes on Monday, I need to change the Default parameter to run from the Prior Friday's date thru Sunday. How can I achieve this? TIA

A: I just replicated your use case locally.
For your start date parameter you will need expression as below. It will check if today is Friday (Weekday starts from Sunday) then set start date as Friday from last week else previous day. This shall work.
 =IIF(WeekDay(today)=2,DateAdd("d",-3,today),DateAdd("d",-1,today))


text:
Q: create xsl file to transform attribute xml to element xml for import into access I have an application on my Ipad that export data with xml. I want to import this file into MS Access 2007, but it's not possible (I guess due to the use of attributes) I guess when I can arrange a XSL file to that convert this attributes to elements, the import will work. I tried lots of XSL files from the internet, none of them worked till now. Can anyone help me?
Piece of XML file right from the ipad:
<?xml version="1.0"?>
<form name="AppVIEW">
<field name="Date" type="date"/>
<field name="Hospital" type="text"/>
<field name="ID" type="text"/>
<field name="VisitType" type="text"/>
<field name="Specialisation" type="text"/>
<field name="ContactName" type="text"/>
<field name="ContactTel" type="text"/>
<field name="ContactMail" type="text"/>
<field name="ShortText" type="text"/>
<field name="Actions" type="text"/>
<record name="OLVG">
<field name="Date">2015-10-14</field>
<field name="Hospital">OLVG</field>
<field name="ID">1</field>
<field name="VisitType">Handover</field>
<field name="Specialisation">SYS1</field>
<field name="ContactName">Nick</field>
<field name="ContactTel">0365425653</field>
<field name="ContactMail">Nick@new.nl</field>
<field name="ShortText">Dit is een test</field>
<field name="Actions">Geen verdere acties nodig</field>
</record>
</form>

So this must be imported into access, I guess with an XSL file. Thanks a million for your help!!

A: It seems to me that the problem here is not how to transform attributes to elements, but rather how to rename the already existing  field elements to the names given by their name attribute.
Caveat: I know practically nothing about MS Access, so I could be easily wrong about this. Try the following transformation:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/form">

        <xsl:apply-templates select="record"/>

</xsl:template>

<xsl:template match="record">
    <row>
        <xsl:apply-templates select="field"/>
    </row>
</xsl:template>

<xsl:template match="field">
    <xsl:element name="{@name}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

The result of applying this to your input example will be:
<?xml version="1.0" encoding="UTF-8"?>

   <row>
      <Date>2015-10-14</Date>
      <Hospital>OLVG</Hospital>
      <ID>1</ID>
      <VisitType>Handover</VisitType>
      <Specialisation>SYS1</Specialisation>
      <ContactName>Nick</ContactName>
      <ContactTel>0365425653</ContactTel>
      <ContactMail>Nick@new.nl</ContactMail>
      <ShortText>Dit is een test</ShortText>
      <Actions>Geen verdere acties nodig</Actions>
   </row>


text:
Q: How can I untar a file in an android app? I have a ".tar" file that my app downloads and I can't figure out how to extract it. I've tried reading it with ZipInputStream, but getNextEntry() returns null even though I can confirm through terminal that the tar file exists. I've been able to untar it manually so I know it's not an issue with the file.
Does anyone have any ideas? Thanks for the help!

A: As suggested above, JTAR ended up working for me:
https://github.com/kamranzafar/jtar


text:
Q: PHP - MySQLi Replace with Regex / Regexp / Regular Expression Sorry for that "Let me google that for you"-Question, but I can't find an answer.
I want to delete specfic elements from columns in my database. So I search with the following code for them: (it works fine)
    $sql = "SELECT list_id, list_domains
            FROM list
            WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
        $result = $db->prepare( $sql );
        $result->execute();
        $result->bind_result( $list_id, $list_domains );
        $result->store_result();

Now I want to delete / replace the found elements inside these columns. So I use the following code:
 $sql = "UPDATE list
        SET list_domains = REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')
        WHERE list_domains REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#'";
        $result = $db->prepare( $sql );
        $result->execute();
        $result->store_result();

Does not work. I also tried
REPLACE(list_domains, REGEXP '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')

or
REGEXP_REPLACE(list_domains, '[\s]*[a-z-]*\.[a-z/\.\?=]*.#".$number."#', '')

but these lines only produce errors.
How does it work to delete / replace specfic regular expressions with MySQLi?
Thanks for every suggestion!

A: REPLACE() doesn't allow regular expression searching.
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
If you want to manipulate strings with regex, SELECT the rows, do the manipulation in your own code, then issue an UPDATE statement to update the value, specifying the final value.


text:
Q: .NET Maui View Change With Radio Control Situation:

*

*I already have a TabBar as menu (at the bottom).

*I want another TabView for each tabpage at the top.

Problem:

*

*I cannot use TabView from DevExpress as this is only for iOS and Android (but I would like to use the app on android and windows).

*I cannot use SfTabView from Syncfusion as currently I do not have the community licence approved.

I found a great example how I can use radio buttons to accomplish this. However I do not have any idea how I get the following accomplished:
I would like to change the datatemplate and datasource of a contentpage based on the selected radio button value.
What I have in mind would be something like this:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Demo"
             xmlns:controls="clr-namespace:Demo.Controls"
             ...>

    <ContentPage.BindingContext>
        <local:PeopleViewModel x:Key="PeopleView" />
        <local:AnimalViewModel x:Key="AnimalView" />
        <local:PlantViewModel x:Key="PlantView" />
    </ContentPage.BindingContext>

    <ContentPage.Resources>
        <DataTemplate x:Key="PeopleTemplate">
            <controls:CardView BorderColor="DarkGray"
                               CardTitle="{Binding Name}"
                               CardDescription="{Binding Description}"
                               ControlTemplate="{StaticResource PeopleCardView}" />
        </DataTemplate>
        <DataTemplate x:Key="AnimalTemplate">
            <controls:CardView BorderColor="DarkGray"
                               CardTitle="{Binding Name}"
                               CardDescription="{Binding Description}"
                               ControlTemplate="{StaticResource AnimalCardView}" />
        </DataTemplate>
        <DataTemplate x:Key="PlantTemplate">
            <controls:CardView BorderColor="DarkGray"
                               CardTitle="{Binding Name}"
                               CardDescription="{Binding Description}"
                               ControlTemplate="{StaticResource PlantCardView}" />
        </DataTemplate>
    </ContentPage.Resources>

    ...

    <StackLayout Margin="10"
                 BindableLayout.ItemsSource="{Binding People}"
                 BindableLayout.ItemTemplate="{StaticResource PeopleTemplate}" />

</ContentPage>

Now I would like to replace the StackLayout section with code so depending on what a radio button value is set to (People, Animal, Plant) the ItemSource and ItemTemplate of the StackLayout is used with the corresponding data.
For People:
...
    <StackLayout Margin="10"
                 BindableLayout.ItemsSource="{Binding People}"
                 BindableLayout.ItemTemplate="{StaticResource PeopleTemplate}" />
...

For Animal:
...
    <StackLayout Margin="10"
                 BindableLayout.ItemsSource="{Binding Animal}"
                 BindableLayout.ItemTemplate="{StaticResource AnimalTemplate}" />
...

For Plant:
...
    <StackLayout Margin="10"
                 BindableLayout.ItemsSource="{Binding Plant}"
                 BindableLayout.ItemTemplate="{StaticResource PlantTemplate}" />
...

Any help is appreciated. Also welcome suggestions for ideas on how to implement it differently than described here.
I have already tried to find helpful ideas via Google, but unfortunately my search was unsuccessful.

A: Not sure if this is the best wait to achieve this but here is an idea
Make all those objects (People, Animal, Plant) be a descendant of some BaseObject
In your ViewModel have a ObservableRangeCollection (you might need to get the code for this from somewhere) and I assume you already have some sort of selectedValue Observable string that will have the value of the selected tab.
Create a OnSelectedValueChanged method that will clear your ObservableRangeCollection and add the appropriate data (this should trigger when you change tab)
Create one DataTemplate for each of your types, then create a DataTemplateSelector that will choose the Template according to the DataType (obj.GetType())
Be advised I have never implemented this, but it seams feasible


text:
Q: Display images from facebook in separate thumbnails I am developing windows phone application. here I am taking some images from Facebook.All images coming in horizontal scrolling one after other
Problem: how to add some blank space between two images
This is my code so far:
<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel
          Orientation="Horizontal"
          ScrollViewer.HorizontalScrollBarVisibility="Visible"
          ScrollViewer.VerticalScrollBarVisibility="Visible" >
            <Image Source="{Binding Path=picture}" Width="250" Height="250" />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

A: Here is the solution set Margin Of Image control inside datatemplate of listbox.
<ListBox  Grid.Row="1" ScrollViewer.HorizontalScrollBarVisibility="Auto">
  <ListBox.ItemsPanel>
     <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal" />
       </ItemsPanelTemplate>
      </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
       <DataTemplate>
       <Image Source="{Binding FacebookImages}" Stretch = "Fill" Margin="20,0,0,0"/>
        </DataTemplate>
 </ListBox.ItemTemplate>
 </ListBox>


text:
Q: Passing values from one page to another I am passing a parameter to my navigation URL,the passed parameter value has to be return this value  in another page.
I am having URL in abc solution default.aspx.cs and i want to navigate to xyz solutions sample.aspx
string InvestigationPageUrl = NavigationService.GetNavigationUrl(Investigation.Investigationpage, new DetailsParameters(CurrentParameters.ReceiptNumber));

Message_Panel.Summary = string.Format(Investigation.Investigation_message, InvestigationPageUrl);

*

*passing without parameter I am able to navigate

*passing with parameter I am getting error as

could not establish a connection to one of the following addresses:
  [10.31.80.146:9098, 10.31.80.146:9099]; make sure the
  "remote-addresses" configuration element contains an address and port
  of a running TcpAcceptor

BaseExceptionDetail:

netcom.Online.estimate.Framework.Instrumentation.Exceptions.CoherenceCacheProviderException:
  could not establish a connection to one of the following addresses:
  [10.31.80.146:9098, 10.31.80.146:9099]; make sure the
  "remote-addresses" configuration element contains an address and port
  of a running TcpAcceptor --->
  Tangosol.Net.Messaging.ConnectionException: could not establish a
  connection to one of the following addresses: [10.31.80.146:9098,
  10.31.80.146:9099]; make sure the "remote-addresses" configuration element contains an address and port of a running TcpAcceptor
  --- End of inner exception stack trace ---


text:
Q: Problems with npm registry during Angular 8 update We are currently updating an Angular 7.2 version on Angular 8.
After running the command sudo ng update @angular/cli @angular/core, there are many error messages like the following:

404 Not Found - GET https://my-company-registry/leaflet

We use a company registry, which I renamed in my link above.
So far, everything has worked, but suddenly the error messages mentioned above occured. Even with simple npm install package-name commands.
I've already checked my .npmrc file inside my project or the global one and tried commands like npm cache clear --force or npm cache verify.
I also deleted my node-modules folder and tried to install everything again. Doesn't work..
If I try to use sudo npm update npm -g I get the following error:
npm ERR! code E404
npm ERR! 404 Not Found - GET https://my-company-registry/npm
npm ERR! 404
npm ERR! 404  'npm@^6.9.0' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/codehan/.npm/_logs/2019-09-20T12_51_34_857Z-debug.log

A: Run this command and enter your registry:- npm config edit,
Or if it is not work than try to run this command npm config set registry <registry url>


text:
Q: UA: didReceiveRemoteNotification:fetchCompletionHandler not being called when app is in background AND connected to Xcode I would like to implement (silent) remote notifications in my app,
note that I've already implemented regular push notifications.
Steps:

*

*Enable background Capabilities in my project (remote notifications)

*Add didReceiveRemoteNotification:fetchCompletionHandlerin my AppDelegate

*Send push notification with Urban Airship* (`"content-available" = 1;)
*UA 3.03.
It only works when the app is active in the foreground.
Am I doing something wrong??
Thx

A: I think I have found the problem:
"content-available" = 1 has to be inside aps
e.g.
{"aps":{"alert":"Hi", "content-available":"1"},"device_tokens":["…"]}


text:
Q: list of list multiplication with list I want to multiply a list of list with a list using python 3 suppose that the list of list is of name L as follows:
L = [[45.909221207388235, 84.41069326628269], [80.6591435966521, 47.93257841035172]]

and the second list is:
S = [0.002, 0.001]

the multiplication should be: L[0][0]* S[0] and L[0][1]* S[0] then L[1][0]* S[1] and L[1][1]* S[1].
I tried the zip method :
[a*b for x,y in zip(S,L) for a,b in zip(x,y)]

But an error appears: zip argument 1 must support iteration.
the second trial was using map(lambda):
map(lambda x,y:x*y,L,S)

but the obtained results were wrong:
[9.181844241477647e-05, 0.00016882138653256538, 0.0001613182871933042, 9.586515682070343e-05]

the correct values are:
[0.09181844241477648, 0.1688213865325654, 0.0806591435966521, 0.047932578410351714]

A: You want to use zip, but not twice:
>>> L = [[45.909221207388235, 84.41069326628269], [80.6591435966521, 47.93257841035172]]
>>> S = [0.002, 0.001]
>>> [n*x for n, sub in zip(S, L) for x in sub]
[0.09181844241477648, 0.1688213865325654, 0.0806591435966521, 0.047932578410351714]
>>>

So, you want to pair up every number with every sublist, then multiply every number in the sublist by that main number.
Note, just in case you are using numpy (I don't think you are, and I don't think it would be reasonable to use numpy just for this), and S and L are numpy.ndarray objects, i.e.:
>>> S = np.array(S)
>>> L = np.array(L)

Then you probably just want:
>>> (S*L).ravel()
array([0.09181844, 0.08441069, 0.16131829, 0.04793258])

A: If I understand corresly you want to multiply each column in L by the corresponding value of S:
L = [[45.909221207388235, 84.41069326628269],
     [80.6591435966521, 47.93257841035172]]
S = [0.002, 0.001]

R = [ [s*n for n in row] for s,row in zip(S,L) ]

output:
print(R)
[ [0.09181844241477648, 0.1688213865325654],
  [0.0806591435966521,  0.047932578410351714]]

You should have given an example with a different number of rows than columns to make this clearer


text:
Q: Simple C/C++ in-process cache similar to memcached I need a simple (LRU) cache which should run in-process. I found memcached, which looks great but there does not seem to be an easy way to host it in-process. I don't need a distributed cache, just a simple key/value store and some kind of LRU behaviour and some nice allocator to limit fragmentation, as the entry size varies a lot (few bytes -- few kilobytes.) There must be surely an existing implementation of such a thing? Should be C or C++.

A: I hate to answer this way, but it would be fairly simple to implement yourself.

*

*Allocator.  Use malloc and free.  They do work, and they work well.  This also makes it easier to interface with the rest of your program.

*Mutex -> hash table, tree, or trie.  You can use a linked list to track LRU.  Don't try to do fancy lockless stuff.
Should weigh less than a couple hundred lines, knock it out in a good solid day.

A: I've had success using commoncache but the project doesn't appear to have any activity and issues raised (with patches) by my colleague are still unaddressed...


text:
Q: Retrieving URL of Facebook profile picture I have the following code that has a correct output:
$request = new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,email,gender,birthday,picture.url' );
$response = $request->execute();

OUTPUT:
Facebook\GraphObject Object ( [backingData:protected] => Array ( [id] => 1412361249046879 [first_name] => Do [email] => xxxx@xxxx.com [gender] => male [birthday] => 06/30/1984 [picture] => stdClass Object ( [data] => stdClass Object ( [url] => https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpa1/t1.0-1/p50x50/10406555_1412406989042185_8978818317524743009_t.jpg ) ) ) )

Then I set variables to call later in my html:
  $uid = $response->getGraphObject()->getProperty('id');
  $name = $response->getGraphObject()->getProperty('first_name');
  $email = $response->getGraphObject()->getProperty('email');
  **$pic = $response->getGraphObject()->getProperty('picture.data.url');**
  $sex = $response->getGraphObject()->getProperty('gender');
  $bday = $response->getGraphObject()->getProperty('birthday');

The problem is the $pic variable doesn't work. I don't understand how to call the variable that is further down the GraphObject tree (ie. picture->data->url)

A: $request = new FacebookRequest( $session, 'GET', '/me?fields=id,first_name,email,gender,birthday,picture.url' );
$response = $request->execute();
$array = $response->getResponse();
$pic = $array->picture->data->url;

Here is what ended up solving it. I had to stop using the getGraphObject() function and just use the standard getResponse() so that I could treat it more like a regular array. Hope this helps somebody out.

A: Why you dont call it like this:
$pic = $response->getGraphObject()->getProperty('picture')->data->url;

OR use FQL with FB SDK
$config = array(
  'appId'  => APP_ID,
  'secret' => API_SECRET,
  'cookie' => true,

);
$facebook = new Facebook($config);
$params = array(
    'method' => 'fql.query',
    'query' => "SELECT uid,email, pic, first_name, last_name, birthday, sex FROM user WHERE uid = ".$uid.""
    );

$result = $result = $facebook->api($params);

Here is the full table of user and official PHP SDK.
I hope this helps.
Warning: But FQL it will be removed from new version of FB API.


text:
Q: Flow duration curve using facet_wrap of ggplot in R? I am using fdc of hydroTSM package. I have three data.frame and i would like to construct Flow duration curves (FDC) of the data.frame using facet_wrap functionality of ggplot to have the plots in three rows and one column. the following will produce FDC curves for DF1.
library(tidyverse)
library(hydroTSM)
library(gridExtra)

DF1 = data.frame(Ob = runif(1000,0,500), A = runif(1000,0,700), B = runif(1000,2,800))
DF2 = data.frame(Ob = runif(1000,0,500), A = runif(1000,0,700), B = runif(1000,2,800))
DF3 = data.frame(Ob = runif(1000,0,500), A = runif(1000,0,700), B = runif(1000,2,800))

fdc(DF1, plot = TRUE)

I tried to use gridExtra package with grid.arrange to force the three plots on a single figure. I not only failed to do it but it is not the preferred method. I would want to used the facet_wrap options of the ggplot. In fact the figure is wrongly drawn by using DF1 data. i am looking for something like below:

Update: This is based on @Jon Spring suggestions.
graphics.off()
rm(list = ls())

library(tidyverse)
library(hydroTSM)
library(gridExtra)

DF1 = data.frame(Ob = runif(800,0,500), M1= runif(800,0,700), M2 = runif(800,2,800), df = rep("Upstream", 800))
DF2 = data.frame(Ob = runif(1000,0,500), M1 = runif(1000,0,700), M2 = runif(1000,2,800), df = rep("Midstream", 1000))
DF3 = data.frame(Ob = runif(1000,0,500), M1 = runif(1000,0,700), M2 = runif(1000,2,800), df = rep("Downstream", 1000))

# combine data into one table with id column for the source
 bind_rows(DF1, DF2, DF3) %>%
   # reshape into longer format
  pivot_longer(-df, names_to = "src", values_to = "flow") %>%
  arrange(-flow) %>%
  group_by(df, src) %>%
  mutate(flow_pct = 1 - percent_rank(flow)) %>%
  ungroup() %>%

  ggplot(aes(flow_pct, flow, color = src)) +
  geom_line() +
  theme_light() +
  facet_wrap(~df, ncol = 1) +
  labs(x = "% Time flow equalled or exceeded",
       y = "Q, [m3/s]") +
  theme(strip.text = element_text(hjust = 0, color = "black"),
        strip.background = element_blank())

A: You could do something like this with facets in ggplot:
library(tidyverse)
# combine data into one table with id column for the source
bind_rows(DF1, DF2, DF3, .id = "df") %>%
  mutate(df = LETTERS[as.numeric(df)]) %>%
  # reshape into longer format
  pivot_longer(-df, names_to = "src", values_to = "flow") %>%
  arrange(-flow) %>%
  group_by(df, src) %>%
  mutate(flow_pct = 1 - percent_rank(flow)) %>%
  ungroup() %>%

  ggplot(aes(flow_pct, flow, color = src)) +
  geom_line() +
  theme_light() +
  facet_wrap(~df, ncol = 1) +
  labs(x = "% Time flow equalled or exceeded",
       y = "Q, [m3/s]") +
  theme(strip.text = element_text(hjust = 0, color = "black"),
        strip.background = element_blank())

If you want the letter annotations placed farther left, you could alternately use the patchwork package to stack and label the plots:
library(tidyverse)
library(patchwork)

flow_plot <- function(df) {
  df %>%
  pivot_longer(everything(), names_to = "src", values_to = "flow") %>%
  arrange(-flow) %>%
  group_by(src) %>%
  mutate(flow_pct = 1 - percent_rank(flow)) %>%
  ungroup() %>%

  ggplot(aes(flow_pct, flow, color = src)) +
  geom_line() +
  theme_light() +
  guides(color = guide_legend()) +
  labs(x = "% Time flow equalled or exceeded",
       y = "Q, [m3/s]") +
    theme(legend.position = c(0.85,0.6))
}

flow_plot(DF1) /
  flow_plot(DF2) /
  flow_plot(DF3) +
  plot_annotation(tag_levels = "A")

A: For sample data, we'll use the EgaEnEstellaQts daily flow data from the HydroGOF package. This as flows from 01/Jan/1961 to 31/Dec/1970. Create three years of data to plot
library(hydroGOF)
library(gridExtra)
library(tidyverse)

Q1 <- window(EgaEnEstellaQts, start=as.Date('1961-01-01'), end=as.Date('1961-12-31'))
Q2 <- window(EgaEnEstellaQts, start=as.Date('1963-01-01'), end=as.Date('1963-12-31'))
Q3 <- window(EgaEnEstellaQts, start=as.Date('1965-01-01'),  end=as.Date('1965-12-31'))

# Because these objects are all the same length, we can put them in one data frame

flow_df <- tibble(Q1 = coredata(Q1), Q2 = coredata(Q2), Q3 = coredata(Q3))

# Add percent ranks which we'll use to plot the fdc

p1 <- flow_df %>%
  gather(key = period, value = flow)  %>%
  group_by(period) %>%
  mutate(rank = 1 - percent_rank(flow)) %>%
  ggplot(aes(x = rank, y = flow, colour = period)) +
  geom_line() +
  scale_y_continuous(name = 'Discharge', trans = 'log10') +
  scale_x_continuous(name = 'Percentage of time flow is exceeded', breaks = seq(0,1,0.25), labels = c('0', '25%', '50%', '75%', '100%')) +
  labs(subtitle = 'A')

#Make the other graphs as required (just place holders here)

p2 <- p1 + labs(subtitle = 'B')
p3 <- p1 + labs(subtitle = 'C')

# Arrange with grid arrange
grid.arrange(p1, p2, p3)


text:
Q: Measure on $([0,1], \mathcal{P}([0,1]))$ I'm working on measures and I need to prove the following:
There exists no measure on $([0,1]\mathcal{P}([0,1]))$ such that

*

*$\mu([0,1]) = 1$

*$\mu(A) \in \{0,1\}$ for any $A \subseteq[0,1]$

*$\mu(F) = 0$ for any $F \subseteq[0,1]$ finite

I understand why this is so and to some extent how to prove it:
1) We suppose there is such a measure.
2) We split the interval in two disjoint intervals and use the additivity of measures on disjoint sets to show that one of the subintervals has measure 1 and the other one 0.
3) We do it recursively and we obtain a sequence of intervals of measure 1 that converges to a singleton of measure 1.
4) This is a contradiction since the measure of finite sets is 0.
I'm not sure how to mathematically write step 3) in a rigorous way. Could anyone please help me? I'm pretty sure this is a standard exercise for an undergraduate course on Lebesgue theory but I didn't manage to find a proof online. If there has already been such a post, a redirection would be appreciated. Thanks in advance.

A: We define the sets $A_n$ recursively as follows:
Let $A_0=[0,1]$. Given an interval $I=[a,b]$ let $f(I):=[a,\frac{a+b}{2}]$ and $g(I):= [\frac{a+b}{2},b]$ we clearly have that $I=f(I)\bigcup g(I)$ (also the union is disjoint up to measure zero).
Assuming we constructed $A_n$ such that $\mu(A_n)=1$, we construct $A_{n+1}$ as follows:
Look at $f(A_n),g(A_n)$, then we have that $A_n=f(A_n)\cup g(A_n)$ is of measure $1$. Therefore $\mu(f(A_n))+\mu(g(A_n))=1$ and so either $f(A_n)$ or $g(A_n)$ is of measure $1$. Let $A_{n+1}$ be this interval (the one of measure $1$).
We obtain a sequence of intervals $A_n$ such that $\mu(A_n)=1$. Moreover $A_{n+1}$ is either $f(A_n)$ or $g(A_n)$ and so it's length is half the length of $A_n$.


text:
Q: getting line numbers of offending code in debug vs release builds My understanding is that with crash dump of debug build you can get the line number of stack trace and this does not happen with release build. In order to try this, I created a very simple application that crashes.
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press any key to continue");
        Console.ReadKey();
        TestMe(null);
    }

    static void TestMe(MyClass c)
    {
        Console.WriteLine(c.Field);
    }
}

class MyClass
{
    public string Field { get; set; }
}

I created one debug build and one release build. Ran both of these and catpured crash dump via ADPlus. Below  are the stack traces for each build. As you can see I am getting the line number in both builds. Obviously difference is that in release build its not reporting call to TestMe method. Any ideas why? Do I need add symbol path to application pdb files in both cases
Debug build
0:000> !CLRStack
OS Thread Id: 0x2398 (0)
Child SP IP       Call Site
001eee74 003400db ConsoleApplication1.Program.TestMe(ConsoleApplication1.MyClass)*** WARNING: Unable to verify checksum for ConsoleApplication1.exe
 [c:\ConsoleApplication1\ConsoleApplication1\Program.cs @ 20]
001eee84 003400a5 ConsoleApplication1.Program.Main(System.String[]) [c:\ConsoleApplication1\ConsoleApplication1\Program.cs @ 14]
001ef0c8 6ccb21bb [GCFrame: 001ef0c8]

Release build
0:000> !CLRStack
OS Thread Id: 0x2e40 (0)
Child SP IP       Call Site
003bf5f8 772af8c1 [GCFrame: 003bf5f8] Unknown
003bf3b4 002b0098 ConsoleApplication1.Program.Main(System.String[])*** WARNING: Unable to verify checksum for ConsoleApplication1.exe
 [c:\ConsoleApplication1\ConsoleApplication1\Program.cs @ 14]
003bf5f8 6ccb21bb [GCFrame: 003bf5f8]

A: In the release build, the JIT compiler is no doubt inlining the method call - that's why the line number is different.


text:
Q: Matlab - Access the output a function inside another function I am trying to access the output of a function from another function. I have the following function:
function f = doSomething
f = 5+6;

In another function I'm calling doSomething as follows:
doSomething;

Is there a way to get the value of f? I want to read the output of doSomething and display it.

A: Write

output = doSomething();

to store the result to the variable "output", and

fprintf('%d\n',output);

to display it.


text:
Q: .zshrc doesn't export variable for anaconda I installed Anaconda Python on my Mac today and following line was added to .bash_profile by Anaconda. Since I am using zsh so I moved this line to .zshrc. However, it doesn't work properly even if I source .zshrc in iTerm.
export PATH="/Users/shawn/Softfolder/anaconda/anaconda/bin:$PATH"

If I move that line to .bash_profile and source it, Anaconda works as expected.
I am wondering does Anaconda work in that way or I did something wrong?
Many thanks!
More: I found following line in .zshrc below the line I added for anaconda. Is this line overridden the path for anaconda?
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/texbin"

PS: I used
bash -l

to start a login session of bash then anaconda does work.

A: anaconda USES BASH so short of you running

sudo chsh -s /usr/bin/zsh $username

FIRST it will not  look in ~/.zshrc as zsh is installed but not running


text:
Q: React  onClick handler is ignored - Google analytics I have problem with React onClick handler. Despite e.preventDefaul(), this link sometimes trigger full reload. I have this code:
<a
                href={isInactive ? undefined : item.url}
                onClick={(e) => {
                    e.preventDefault();
                    return !isInactive ? this.props.onChange(item) : undefined;
                }}
            >
                Foo
            </a>

This bug is somehow connected with GTM, because when I comment GTM script tag everything works fine. Next thing is that when I stop use datalayer extension for Chrome (https://chrome.google.com/webstore/detail/datalayer-checker/ffljdddodmkedhkcjhpmdajhjdbkogke) everything works fine too.
Do you know any possible reason why this problems occurs?

A: The problem is likely due to the return value coming from your click handler. Click events will bubble up to all the parent elements if you don't explicitly stop the propagation. If you want the click event to not propagate beyond your handler, you need to either call e.stopPropagation(), or return false in your click handler function. If you don't prevent the click event from propagating, the anchor element will then navigate to the URL specified in the href attribute, which would cause a full page reload.
Here's an article that explains pretty concisely the difference between e.preventDefault() and return false. It also links to this article that gives a more detailed explanation of how events are handled.


text:
Q: Magento2 send Order information to Google Analytics when order from admin
*

*Though Magento 2 has the inbuilt implementation to send the
transaction/order details placed on webstore or frontend to Google
Analytics, it lacks the same ability when orders are being placed
from the Magento backend, the admin, or when orders are created
programmatically.

*The problem Google Analytics won't match the reports generated from Magento.

*So I want to send order to google  save Google Analytics Tracking Id.

How can I achieve this?

A: I have checked and found that module-google-analytics is responsible for sending order analytics to Google.
It has events.xml at magento2Root/vendor/magento/module-google-analytics/etc/frontend with following content.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer name="googleanalytics_order_success" instance="Magento\GoogleAnalytics\Observer\SetGoogleAnalyticsOnOrderSuccessPageViewObserver" />
    </event>
    <event name="multishipping_checkout_controller_success_action">
        <observer name="googleanalytics_order_success" instance="Magento\GoogleAnalytics\Observer\SetGoogleAnalyticsOnOrderSuccessPageViewObserver" />
    </event>
</config>

So, it is calling observer on order success but only for front-end.
If you move this file form frontend to global, it will work for admin as well!
So new location for events.xml will be:

magento2Root/vendor/magento/module-google-analytics/etc/events.xml

Note:
If above observer not work, you can also use checkout_submit_all_after, OR sales_order_place_after.
I have not tested above code due to unavailability of key.
If worked, do proper override in custom module.


text:
Q: GCD search for non-integers (***) i really dont know how to solve this? can someone help me please?
Find the approximation of greatest common divisor for a set of data (a vector of noninteger
numbers). In general, these will not have an exact common divisor. The solution
(also a floating point number) should be approximated with certain accuracy. E.g.:
x = [3.3308 4.4449 7.7828 12.2273 14.4405 21.1161];
epsilon = 0.01;
d = find_gcd(x,epsilon)
d =
1.1111
% verifying result
x/d
ans =
2.9978 4.0005 7.0046 11.0046 12.9966 19.0047
error = x/d – round(x/d)
error =
-0.0022 0.0005 0.0046 0.0046 -0.0034 0.0047

A: Maybe using the Euclidan Algorithm as procedure would be correct?


text:
Q: IE / Edge session cookie problems using cookie_lifetime Since a couple of days (at least, that I'm aware of), I cannot login to my website using Internet Explorer or Edge. The login does work using Firefox and Chrome! I have witnessed the problem on other computers as well, indicating that it is not a local browser problem.
I am aware that IE / Edge silently drop cookies from domains with a _ in the subdomain, however in my situation there is none.
After allot of sweat and pain, I have reduced the script to the bare minimum to replicate the problem.
I have also found the the problem, but I have no true solution.
<?PHP
    ini_set( 'session.cookie_lifetime', '3600' );

    if( session_id() == '' )
        session_start( );

    $i = 1;
    if( isset( $_POST['logout'] ) ) {
        unset( $_SESSION['loggedin' . $i] );
        session_destroy();
        header( 'Location: http://jbtje.com/test' . $i . '.php' );
    }
    if( isset( $_POST['login'] ) ) {
        $_SESSION['loggedin' . $i] = 'LOGGED IN: ' . $i;
        header( 'Location: http://jbtje.com/test' . $i . '.php' );
    }
?><!DOCTYPE html>
<html>
<head>
<title>TEST <?PHP $i ?></title>
</head>
<body>
<?PHP echo 'You are currently ' . (isset($_SESSION['loggedin' . $i]) ? $_SESSION['loggedin' . $i] : 'not logged in ' . $i); ?>
<form method="POST"><input type="submit" name="login" value="login" /></form>
<form method="POST"><input type="submit" name="logout" value="logout" /></form>

</body>
</html>

Test site: http://jbtje.com/test1.php
If you press the login button, the text should change to "You are currently LOGGED IN". But, it does not.
IF however you comment the ini_set line out, (and change $i to 2):
http://jbtje.com/test2.php it does work....
Why does setting cookie_lifetime using PHP cause IE and Edge to not store the cookie? (and how to solve this...?)
Best regards,
Jeffrey


text:
Q: check if function one to one or onto for example  f(x) = x^2
I know if we get same result from different value will be not one to one in other words if the power odd will be one to one

*

*$(-2)^2=4$

*$2^2=4$
But how do I check it is onto or not. The co domain not given in the exam

A: It can be assumed in the context of the level of mathematics you seem to be at that if the codomain is not mentioned, then it is going to be the whole of $\mathbb R$
So, in order to prove a function is onto, you need to show that for all elements of $\mathbb R$, there exists an element of the domain (also $\mathbb R$ in this context) which maps to that element.
Knowing as you do that the square of a number is always non-negative, that tells you that negative numbers are never mapped to by the square function.
The answer follows directly from that.

A: Start with a function $f:\mathbb{R}\to\mathbb{R}$ .
One one :
In order to check whether $f$ is one one or not, try to show that for any two points $x$ and $y$ , $$f(x) = f(y) \quad\iff\quad x=y$$ If so, then $f$ is one one. Otherwise not.

Onto :
In order to check whether $f$ is onto or not, you'll have to check if for any $y\in\mathbb{R}$ , there exists at least one $x\in\mathbb{R}$ such that $f(x)=y$ .
If so, then $f$ is onto. Otherwise, not.


text:
Q: How to convert any type of video in mp4 I'm using meteor with blaze for development of web-app. I have used html 5 video tag for play video in browser. other types like mp4 and m4v is working fine in all browser but MOV format file is not play in any browser.
So I think to convert MOV to mp4 before upload.
Anyone have any idea about convert video before upload using js or meteor. OR any other way we can play MOV type video in any browser

A: Using ffmpeg, you can first try
ffmpeg -i in.mov -c copy -movflags +faststart out.mp4

If the codecs aren't supported in MP4 or HTML5, run
ffmpeg -i in.mov -movflags +faststart out.mp4

A: Alternatively, you can use [VLC media player][1]
[1]: http://www.videolan.org/vlc/ to convert the file.
Click on File-> Select Convert/Save option.


text:
Q: difference between sonar and sonarqube Can anybody explain me what is the difference between sonar and sonarQube as i have said to integrate the sonar with eclipse i am using eclipse Luna but when i tried to search sonar using
Help----> Eclipse Marketplace ---->search (sonar)

i am getting sonarQube not sonar
Therefore my question is  that are they same or different if same i can go ahead to install in the eclipse if not then from where to install sonar as it is my requirement.please anybody suggest

A: Same software. The name changed last year, from Sonar to SonarQube
http://www.sonarqube.org/sonar-becomes-the-sonarqube-platform/

A: From SonarQube

SonarQube (formerly Sonar) is an open source platform for continuous inspection of code quality.

From http://www.sonarqube.org/

SonarQube™ software (previously known as "Sonar") is an open source project hosted at Codehaus.

A: SonarQube (formerly just "Sonar") is a server-based system. Of course you can install it on your local machine (the hardware requirements are minimal). But it is a central server with a database.
Analyses are performed by some Sonar "client" software, which could be the sonar runner, the sonar ant task, the sonar Eclipse plugin etc. The analysis results can be automatically uploaded to the server, where they can be accessed via the sonar Web application.
In an environment with many developers, you should run a build server (e.g. Hudson or Jenkins), which performs automatic sonar analyses as part of the nightly build. Other schedules are possible, but the developers should know when they can expect updates of the server-side analysis results. The results of the automated analysis can be displayed in the individual developer's Eclipse editor by way of the sonar Eclipse plugin.


text:
Q: Recurrence formula for a series $x_n$ -- very stuck!!! The Problem:
$x_n$ is defined as $$\sum_{k=0}^\infty \frac{(n+k)!}{k!(2n+2k)!}(\frac{1}{2})^{2k} $$
and satisfies the recurrence: $x_n-2(2n+1)x_{n+1}=x_{n+2}$
But I cannot show that this is the case...
My Attempt:
$$LHS=\sum_{k=0}^\infty\frac{(n+k)!}{k!(2n+2k)!}(\frac{1}{2})^{2k}-2(2n+1)\frac{(n+1+k)!}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{(n+k)!(2n+1+2k)(2n+2+2k)}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}-2(2n+1)\frac{(n+1+k)!}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{2(n+k)!(n+1+k)(2n+1+2k)-2(2n+1)(n+1+k)!}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{2(n+1+k)!( (2n+1+2k)-(2n+1))}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{2(n+1+k)!( 2k)}{k!(2n+2+2k)!}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{2(n+2+k)!( 2k)}{k!(2n+2+2k)!(n+2+k)}(\frac{1}{2})^{2k}$$
$$=\sum_{k=0}^\infty\frac{(n+2+k)!}{(k-1)!(2n+2+2k)!(2n+4+2k)}(\frac{1}{2})^{2(k-1)-1}$$
But from this point, I have no idea how to obtain $x_{n+2}$ from this...

A: We have that $\frac{1}{(2n+2k)!}$ is the coefficient of $z^{n+k}$ in $\sum_{m\geq 0}\frac{z^m}{(2m)!}=\cosh(\sqrt{z})$.
On the other hand, by stars and bars we have that $\frac{1}{4^k}\binom{n+k}{k}$ is the coefficient of $z^k$ in
$$ \sum_{m\geq 0}\binom{n+m}{m}\frac{z^m}{4^m}=\frac{1}{(1-z/4)^{n+1}} $$
or the coefficient of $z^{-k}$ in $\left(1-\frac{1}{4z}\right)^{-1-n}$, so that
$$ \sum_{k\geq 0}\frac{(n+k)!}{4^k k!(2n+2k)!} = n!\cdot[z^n]\frac{\cosh(\sqrt{z})}{\left(1-\frac{1}{4z}\right)^{n+1}}=n!\cdot [z^{2n}]\frac{\cosh z}{\left(1-\frac{1}{4z^2}\right)^{n+1}}. $$
By using Cauchy integral formula and the residue theorem, we may check that
$x_n$ is related with the Fourier series of $e^{-\cos\theta}$ over $(-\pi,\pi)$. In particular, we have:
$$ x_n = \sum_{k\geq 0}\frac{(n+k)!}{4^k k!(2n+2k)!} = \frac{\sqrt{\pi}}{2}\cdot I_{\frac{2n-1}{2}}\left(\frac{1}{2}\right) $$
where $I_\nu$ is a modified Bessel function of the first kind. The recurrence relation for the $x_n$ sequence then follows from the integral representation of such function, the cosine addition formulas and integration by parts, as exploited here. Notably, given such recurrence relation, we also have that $x_n$ is a linear combination of $\cosh\frac{1}{2}$ and $\sinh\frac{1}{2}$ for any $n\in\mathbb{N}$.

A: $\displaystyle x_n=\sum\limits_{k=0}^\infty \frac{(n+k)!}{k!}\frac{(1/2)^{2k}}{(2n+2k)!}$
$\displaystyle =\sum\limits_{k=0}^\infty \frac{(n+k-1)!}{k!}\frac{(1/2)^{2k+1}}{(2n+2k-1)!}$
$\displaystyle = \sum\limits_{k=0}^\infty \frac{(n+k-1)!}{k!}\frac{(1/2)^{2k+1}}{(2n+2k-2)!} - \sum\limits_{k=0}^\infty \frac{(n+k)!(n+k-1)}{k!}\frac{(1/2)^{2k-1}}{(2n+2k)!} $
$\displaystyle = \sum\limits_{k=0}^\infty \frac{(n+k-1)!}{k!}\frac{(1/2)^{2k+1}}{(2n+2k-2)!} – (n-1)\sum\limits_{k=0}^\infty \frac{(n+k)!}{k!}\frac{(1/2)^{2k-1}}{(2n+2k)!} -\sum\limits_{k=0}^\infty \frac{(n+k+1)!}{k!}\frac{(1/2)^{2k+1}}{(2n+2k+2)!} $
$\displaystyle = \frac{1}{2}x_{n-1}-2(n-1)x_n- \frac{1}{2}x_{n+1}$
$n\to n+1$ => $x_{n+1}= \frac{1}{2}x_n-2n x_{n+1}- \frac{1}{2}x_{n+2}$
=>   $\enspace x_n-2(2n+1)x_{n+1}=x_{n+2}$

A: My Solution:
To verify that the recurrence is true: we simply test the LHS and the RHS $\Rightarrow$
$$LHS=x_n - 2(2n+1)x_{n+1}$$
$$=\sum_{k=0}^\infty \frac{2(n+k+1)!( (2n+2k+1)-(2n+1) )}{k!(2n+2+2k)!}\times(1/2)^{2k}$$
Note that this is equal to $0$ when $k=0$ so we may just consider the sum starting at $k=1$
$$=\sum_{k=1}^\infty\frac{(n+k+1)!}{(k-1)!( 2(n+2)+2(k-1))!}\times(1/2)^{2(k-1)}$$
$$=\sum_{k=1}^\infty\frac{((n+2)+(k-1))!}{(k-1)!( 2(n+2)+2(k-1))!}\times(1/2)^{2(k-1)}$$
$$=\sum_{k=0}^\infty\frac{((n+2)+(k))!}{(k)!( 2(n+2)+2(k))!}\times(1/2)^{2(k)}$$
$$=x_{n+2} \text{ as required}$$


text:
Q: QWC2 first install I'm trying to install QGIS Web Client 2 (QWC2) following instructions in "Quick start" documentation:
https://github.com/qgis/qwc2-demo-app/blob/master/doc/QWC2_Documentation.md#quick-start
So, I have successfully executed the qwc2-demo-app by "yarn start".
The next step tell:

The final step is to compile a deployable application bundle for production:
  $ yarn run prod.
  You can then deploy the contents of the prod folder to your web server root.

I run "yarn run prod" and a folder "prod" is created, but I didn't understand how to use it in my web server.

A: Running "yarn run prod" will create your actual application inside the prod folder. Now we simply move this folder to your htdocs/root folder so apache or some other webserver will serve it.
That's it, now your new client will be accessible across your network. You should access it on:
mycomputerIP:<PortWhereWebserverListens>/prod

If this is your first time using the client, you will need a webserver to serve your website.


text:
Q: Entering HALT mode with master interrupt enabled but no Interrupt Enable (0xFF0F = 0)? According to Gameboy Programming Manual,

HALT mode is canceled by the following events, which have the starting addresses indicated.

*

*A LOW signal to the /RESET terminal Starting address: 0x0000

*The interrupt-enable flag and its corresponding interrupt request flag are set

*

*IME = 0 (Interrupt Master Enable flag disabled)
  Starting address: address following that of the HALT instruction

*IME = 1 (Interrupt Master Enable flag enabled)
  Starting address: each interrupt starting address

Assume a program enters HALT mode with Interrupt Master Enable flag enabled IME = 1 and Interrupt Enable disabled for any interrupt 0xFF0F = 0, what would happen? What is the expected behaviour on the actual Gameboy device?

A: I am not sure if I understand your question right, but anyway:
According to the cited manual, the IE (interrupt enable) register, address FFFF, determines which one of the 5 interrupt types are enabled. Only those set to 1 will be accepted if IME (interrupt master enable) ist set to 1.
The IF (interrupt flags) register, address FF0F, provides merely information which interrupts are requested.
So, if a program is in the HALT state with IME = 1, any interrupt is accepted that is enabled in IE. Of course, somebody had to generate the interrupt(s) which would be indicated by a (or more) 1 in the IF register.
EDIT:
Maybe this answers your question now:
If the program enters HALT mode, Interrupt Master Enable is enabled (IME = 1), but all specific interrupt types are disabled (IE = 0), no interrupt will be accepted, and HALT mode is not left. This is the expected behavior on the device.


text:
Q: Java RSA Implementation: javax.crypto.BadPaddingException I know that this question has been asked before, and I wouldn't ask again if I didn't understand what I've read - I'm implement a straightforward demo of the RSA algorithm - encrypt a message, decrypt and print the output, but the console shows the BadPaddingException thrown in the code:
Here's the code and the console output:
Code
public class RSA {
public static void main (String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);   // 1024 or 2048
    KeyPair kp = kpg.generateKeyPair();
    Key publicKey = kp.getPublic();
    Key privateKey = kp.getPrivate();
    Cipher cipher = generateCipher();
    String data = "abcdefghijklmnop\0\0\0";

    System.out.println("Plaintext: " + data);
    byte[] ciphertext = rsaEncrypt(data.getBytes(), publicKey, cipher);
    System.out.println("Ciphertext: " + ciphertext);
    byte[] plaintext = rsaDecrypt(data.getBytes(), privateKey, cipher);
    System.out.println("Decrypted Plaintext: " + plaintext);
}

public static Cipher generateCipher() throws NoSuchAlgorithmException, NoSuchPaddingException {
    Cipher cipher = Cipher.getInstance("RSA");
    return cipher;
}

public static byte[] rsaEncrypt(byte[] data, Key publicKey, Cipher cipher) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      byte[] cipherData = cipher.doFinal(data);
      return cipherData;
}

public static byte[] rsaDecrypt(byte[] data, Key privateKey, Cipher cipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      byte[] cipherData = cipher.doFinal(data); // error line: at learning.RSA.rsaDecrypt(RSA.java:43)

      return cipherData;
}
}

Console
Plaintext: abcdefghijklmnop
Ciphertext: [B@346cd0f9
Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:329)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at learning.RSA.rsaDecrypt(RSA.java:43)
at learning.RSA.main(RSA.java:26)

Again, not asking for a solution, but would appreciate an explanation of the concept padding -  if you have any good resources with sample code for implementing RSA, I'd love those recommendations too.
Thanks :)

A: This
    byte[] plaintext = rsaDecrypt(data.getBytes(), privateKey, cipher);

should be
    byte[] plaintext = rsaDecrypt(ciphertext, privateKey, cipher);