问:
jQuery DataTable Not a Function
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            $('#myTable').DataTable();
        });
    </script>
</head>
<body style="margin:20px auto">
    <table id="myTable" class="table table-striped" >
        <thead>
          <tr>
            <th>ENO</th>
            <th>EMPName</th>
            <th>Country</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>001</td>
            <td>Anusha</td>
            <td>India</td>
            <td>10000</td>
          </tr>
          <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
       <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

       <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
  </div>
</body>

</html>
</code>```

答:
You have a
 at the end of your table that shouldn't be there, but otherwise your code works fine...

$(document).ready(function(){
  $('#myTable').DataTable();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body style="margin:20px auto">
    <table id="myTable" class="table table-striped" >
        <thead>
          <tr>
            <th>ENO</th>
            <th>EMPName</th>
            <th>Country</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>001</td>
            <td>Anusha</td>
            <td>India</td>
            <td>10000</td>
          </tr>
          <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
       <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

       <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
</body>
</html></code>```

Perhaps there is something else on your page that is interfering with it?

Title: jQuery DataTable Not a Function

Body:
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>

            ENO
            EMPName
            Country
            Salary

            001
            Anusha
            India
            10000

        002
        Charles
        United Kingdom
        28000

        003
        Sravani
        Australia
        7000

        004
        Amar
        India
        18000

        005
        Lakshmi
        India
        12000

        006
        James
        Canada
        50000

        007
        Ronald
        US
        75000

        008
        Mike
        Belgium
        100000

Body:
You have a </div> at the end of your table that shouldn't be there, but otherwise your code works fine...

$(document).ready(function(){
  $('#myTable').DataTable();
});

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body style="margin:20px auto">
    <table id="myTable" class="table table-striped" >
        <thead>
          <tr>
            <th>ENO</th>
            <th>EMPName</th>
            <th>Country</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>001</td>
            <td>Anusha</td>
            <td>India</td>
            <td>10000</td>
          </tr>
          <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
       <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

       <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

Perhaps there is something else on your page that is interfering with it?


来源: stackexchange

问:
c++ create object with an array as member
i'm new to c++ (coming from java) and i'm actually struggeling with the
following:
Let foo be a class

```<code>int bar[10] = {};

Foo::Foo()
{
    bar[1] = 42;

}
</code>```

and doSmth() a method in the main class:

```<code>Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}
</code>```

the main will be something like:

```<code>int main(int argc, char *argv[])
{
Foo f = doSmth();

cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}
</code>```

Is this the right way to return the foo-object in doSmth()?
I want to create the object on stack, but I'm worried about the array (bar) from the foo object, when will it be deleted from stack?

答:
Is this the right way to return the foo object in doSmth()?

Yes, objects created locally must be returned by value. Typically the compiler will create the object in place and the copy will be optimized out. You can read more about returning local objects here: https://isocpp.org/wiki/faq/ctors#return-local-var-by-value-optimization

I want to create the object on stack, but I'm worried about bar from the foo object, when will it be deleted from stack?

As mentioned above, because of return value optimization the compiler will typically not even create this object within doSmith's stack frame. Furthermore, even if it was created in doSmith's stack frame, the behavior of the default copy constructor and the default assignment operator is such that:

If the subobject is an array, each element is assigned, in the manner appropriate to the element type

See 15.8.1[class.copy.ctor]14.1 and 15.8.2[class.copy.assign]12.2

ContentLicense: CC BY-SA 3.0

Body:
i'm new to c++ (coming from java) and i'm actually struggeling with the
following:
Let foo be a class

int bar[10] = {};

Foo::Foo()
{
    bar[1] = 42;

}

and doSmth() a method in the main class:

Foo doSmth(){
Foo f;
f.bar[0] = 10;
return f;
}

the main will be something like:

int main(int argc, char *argv[])
{
Foo f = doSmth();

cout << f.bar[1] << endl;
cout << f.bar[0] << endl;
return 0;
}

Is this the right way to return the foo-object in doSmth()?
I want to create the object on stack, but I'm worried about the array (bar) from the foo object, when will it be deleted from stack?


问:
Preferred way to check object property is `null` or `undefined`
If I have some object that has a property that may or may not exist, is there a preferred way to check for its' existence?

```<code>// Good?
(someObj.property !== undefined && someObj.property !== null)

// Better?
(typeof someObj.property !== 'undefined')

// Best?
(someObj.property != null)
</code>```

*The last != operator is on purpose:

Strict equality checks (===) must be used in favor of abstract equality checks (==). The only exception is when checking for undefined and null by way of null. The use of == null is also acceptable in cases where only one of null or undefined may be logically encountered, such as uninitialized variables.

答:
I reckon you'd use obj.hasOwnProperty(prop)

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Body:
If I have some object that has a property that may or may not exist, is there a preferred way to check for its' existence?

// Good?
(someObj.property !== undefined && someObj.property !== null)

// Better?
(typeof someObj.property !== 'undefined')

// Best?
(someObj.property != null)

*The last != operator is on purpose:

Strict equality checks (===) must be used in favor of abstract equality checks (==). The only exception is when checking for undefined and null by way of null. The use of == null is also acceptable in cases where only one of null or undefined may be logically encountered, such as uninitialized variables.


问:
Detect if the mouse is clicked outside GroupBox
I am looking for an event if the mouse is clicked outside of the groupBox in Qt. I tried FocusOutEvent but was not able to get the event:

```<code>ui.groupBox->installEventFilter(this);

void myClass::focusOutEvent(QFocusEvent *event) { ui.groupBox->hide(); }
</code>```

Any kind of help would be greatly appreciated!

答:
You have the following options:

Subclass QGroupBox and override mousePressEvent()

Install an event filter on that group box and catch QMouseEvents

If you want to catch only right mouse clicks (context menu), implement a custom context menu handler.

Body:
I am looking for an event if the mouse is clicked outside of the groupBox in Qt. I tried FocusOutEvent but was not able to get the event:

ui.groupBox->installEventFilter(this);

void myClass::focusOutEvent(QFocusEvent *event) { ui.groupBox->hide(); }

Any kind of help would be greatly appreciated!


问:
Populating Array of Pointers in Function
I have a class with an array of pointers that gets dynamically allocated in the constructor.  This class also has a function to populate the array.

```<code>HolderClass::HolderClass(int number)
{
  arrayOfPointers = new ItemClass*[number];
}

HolderClass::addItem(int number, ItemClass item)
{
  arrayofPointers[number] = &item;
}
</code>```

Even though this would compile is my understanding correct in that I would actually be populating the array with dangling pointers since the lifetime of the item variable is only for the duration of the addItem function?

What would be the correct way of populating the arrayOfPointers with pointers to the passed in items?  The one complexity here is that there will be child classes of ItemClass that will get passed to the addItem function so I don't believe default copy constructors could be used.

EDIT: This code is for an Arduino so I'm fairly limited in what can and can't be done.  This also means that I would like to keep things simply for users of this class (since there are lots of Arduino newbies) and not require them to pass in a pointer to the addItem function (which would require them to manage the life of the passed in ItemClass object).

答:
What would be the correct way of populating the arrayOfPointers with pointers to the passed in items?

Firstly, don't use raw new and delete. Use containers and smart pointers.

```<code>struct HolderClass
{
    std::unique_ptr<std::unique_ptr<ItemClass>[]> arrayOfPointers;
    // ...
};

HolderClass::HolderClass(int number)
{
     arrayOfPointers = std::make_unique<std::unique_ptr<ItemClass>[]>(number);
}
</code>```

Then, pass a pointer to addItem instead of a value to avoid object slicing and lifetime issues:

```<code>HolderClass::addItem(int number, std::unique_ptr<ItemClass> item)
{
    arrayofPointers[number] = std::move(item);
}
</code>```

Body:
I have a class with an array of pointers that gets dynamically allocated in the constructor.  This class also has a function to populate the array.

HolderClass::HolderClass(int number)
{
  arrayOfPointers = new ItemClass*[number];
}

HolderClass::addItem(int number, ItemClass item)
{
  arrayofPointers[number] = &item;
}

Even though this would compile is my understanding correct in that I would actually be populating the array with dangling pointers since the lifetime of the item variable is only for the duration of the addItem function?

What would be the correct way of populating the arrayOfPointers with pointers to the passed in items?  The one complexity here is that there will be child classes of ItemClass that will get passed to the addItem function so I don't believe default copy constructors could be used.

EDIT: This code is for an Arduino so I'm fairly limited in what can and can't be done.  This also means that I would like to keep things simply for users of this class (since there are lots of Arduino newbies) and not require them to pass in a pointer to the addItem function (which would require them to manage the life of the passed in ItemClass object).

Body:
What would be the correct way of populating the arrayOfPointers with pointers to the passed in items?

Firstly, don't use raw new and delete. Use containers and smart pointers.

struct HolderClass
{
    std::unique_ptr<std::unique_ptr<ItemClass>[]> arrayOfPointers;
    // ...
};

HolderClass::HolderClass(int number)
{
     arrayOfPointers = std::make_unique<std::unique_ptr<ItemClass>[]>(number);
}

Then, pass a pointer to addItem instead of a value to avoid object slicing and lifetime issues:

HolderClass::addItem(int number, std::unique_ptr<ItemClass> item)
{
    arrayofPointers[number] = std::move(item);
}


问:
Can't set margin left userName
i have 2 items in a relative layout that i want to put side by side,the User icon and the username, at the moment i have the user icon where i want but the username is always right at the side with no margin, i need some margin left so i can have a litle space between each other, and i tried with margin left but it didn't work.

here is the xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="142dp"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:layout_toEndOf="@+id/dateTxt"
                android:text="Avalie a fotografia" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_marginEnd="29dp"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <ImageView
                android:id="@+id/userIcon"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/plantPhoto"
                android:src="@drawable/ic_user"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="20sp" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginEnd="29dp"
                android:layout_toEndOf="@+id/userIcon"
                android:layout_toLeftOf="@+id/userIcon"
                android:layout_marginLeft="20dp"/>
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

答:
I have found too issues with your code:

You have both android:layout_toEndOf="@+id/userIcon" and android:layout_toLeftOf="@+id/userIcon" attributes set in your username view, which makes no sense. You should replace android:layout_toLeftOf with android:layout_toRightOf if you want it to be to the right of the userIcon view.

You are setting the left position of the username view with the android:layout_toEndOf="@+id/userIcon" attribute, that's why android:layout_marginLeft="20dp" has no effect. You can use android:paddingLeft="20dp" instead.

Let me know if it helps.

Title: Can't set margin left userName

Body:
i have 2 items in a relative layout that i want to put side by side,the User icon and the username, at the moment i have the user icon where i want but the username is always right at the side with no margin, i need some margin left so i can have a litle space between each other, and i tried with margin left but it didn't work.

here is the xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="142dp"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:layout_toEndOf="@+id/dateTxt"
                android:text="Avalie a fotografia" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_marginEnd="29dp"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <ImageView
                android:id="@+id/userIcon"
                android:layout_width="15dp"
                android:layout_height="15dp"
                android:layout_alignParentBottom="true"
                android:layout_below="@id/plantPhoto"
                android:src="@drawable/ic_user"
                />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="20sp" />

            <com.example.afcosta.inesctec.pt.android.Helpers.NexusBoldTextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/plantPhoto"
                android:textColor="@color/base"
                android:layout_marginEnd="29dp"
                android:layout_toEndOf="@+id/userIcon"
                android:layout_toLeftOf="@+id/userIcon"
                android:layout_marginLeft="20dp"/>
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>


问:
Divide rows with date in SQL Server 2014
I have a problem with SQL. I have the following table:

```<code>declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

```<code>declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

答:
A calendar/dates table can simplify this, but we can also use a query to generate a temporary dates table using a common table expression.

From there, we can solve this as a gaps and islands style problem. Using the dates table and using outer apply() to get the latest values for start_date and gross_sales_price we can identify the groups we want to re-aggregate by using two row_number()s. The first just ordered by date, less the other that is partitioned by the value we have as the latest start_date and ordered by date.

Then you can dump the results of the common table expression src to a temporary table and do your inserts/deletes using that or you can use merge using src.

```<code>/* -- dates --*/
declare @fromdate datetime, @thrudate datetime;
select  @fromdate = min(start_date), @thrudate = max(end_date) from #t;
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(datetime,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
    , [End_Date]=convert(datetime,dateadd(millisecond,-3,dateadd(day,row_number() over(order by (select 1)),@fromdate)))
  from n as deka cross join n as hecto cross join n as kilo
                 cross join n as tenK cross join n as hundredK
   order by [Date]
)
/* -- islands -- */
, cte as (
select
    start_date = d.date
  , end_date   = d.end_date
  , x.gross_sales_price
  , grp = row_number() over (order by d.date)
        - row_number() over (partition by x.start_date order by d.date)
from dates d
  outer apply (
    select top 1 l.start_date, l.gross_sales_price
    from #t l
    where d.date >= l.start_date
      and d.date <= l.end_date
    order by l.start_date desc
    ) x
)
/* -- aggregated islands -- */
, src as (
select
    start_date = min(start_date)
  , end_date   = max(end_date)
  , gross_sales_price
from cte
group by gross_sales_price, grp
)
/* -- merge -- */
merge #t with (holdlock) as target
using src as source
  on target.start_date = source.start_date
 and target.end_date   = source.end_date
 and target.gross_sales_price = source.gross_sales_price
when not matched by target
  then insert (start_date, end_date, gross_sales_price)
    values (start_date, end_date, gross_sales_price)
when not matched by source
  then delete
output $action, inserted.*, deleted.*;
/* -- results -- */
select
    start_date
  , end_date
  , gross_sales_price
from #t
order by start_date
</code>```

rextester demo:  http://rextester.com/MFXCQQ90933

merge output (you do not need to output this, just showing for the demo):

```<code>+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+
| $action |     START_DATE      |      END_DATE       | GROSS_SALES_PRICE |     START_DATE      |      END_DATE       | GROSS_SALES_PRICE |
+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+
| INSERT  | 2014-10-01 00:00:00 | 2014-10-06 23:59:59 | 29.99             | NULL                | NULL                | NULL              |
| INSERT  | 2014-08-06 00:00:00 | 2014-09-05 23:59:59 | 29.99             | NULL                | NULL                | NULL              |
| DELETE  | NULL                | NULL                | NULL              | 2014-08-06 00:00:00 | 2014-10-06 23:59:59 | 29.99             |
+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+
</code>```

results:

```<code>+-------------------------+-------------------------+-------------------+
|       start_date        |        end_date         | gross_sales_price |
+-------------------------+-------------------------+-------------------+
| 2014-08-06 00:00:00.000 | 2014-09-05 23:59:59.997 | 29.99             |
| 2014-09-06 00:00:00.000 | 2014-09-09 23:59:59.997 | 32.99             |
| 2014-09-10 00:00:00.000 | 2014-09-30 23:59:59.997 | 32.99             |
| 2014-10-01 00:00:00.000 | 2014-10-06 23:59:59.997 | 29.99             |
| 2014-10-07 00:00:00.000 | 2049-12-31 23:59:59.997 | 34.99             |
+-------------------------+-------------------------+-------------------+
</code>```

calendar and numbers tables reference:

Generate a set or sequence without loops 2- Aaron Bertrand

Creating a Date Table/Dimension in SQL Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in SQL Server - Aaron Bertrand

merge reference:

Use Caution with SQL Server''s MERGE Statement - Aaron Bertrand

UPSERT Race Condition With Merge - Dan Guzman

An Interesting MERGE Bug - Paul White

Can I optimize this merge statement - Aaron Bertrand

If you are using indexed views and MERGE, please read this! - Aaron Bertrand

The Case of the Blocking Merge Statement (LCK_M_RS_U locks) - Kendra Little

Writing t-sql merge statements the right way - David Stein

Body:
I have a problem with SQL. I have the following table:

declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
A calendar/dates table can simplify this, but we can also use a query to generate a temporary dates table using a common table expression.

From there, we can solve this as a gaps and islands style problem. Using the dates table and using outer apply() to get the latest values for start_date and gross_sales_price we can identify the groups we want to re-aggregate by using two row_number()s. The first just ordered by date, less the other that is partitioned by the value we have as the latest start_date and ordered by date.

Then you can dump the results of the common table expression src to a temporary table and do your inserts/deletes using that or you can use merge using src.

/* -- dates --*/
declare @fromdate datetime, @thrudate datetime;
select  @fromdate = min(start_date), @thrudate = max(end_date) from #t;
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(datetime,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
    , [End_Date]=convert(datetime,dateadd(millisecond,-3,dateadd(day,row_number() over(order by (select 1)),@fromdate)))
  from n as deka cross join n as hecto cross join n as kilo
                 cross join n as tenK cross join n as hundredK
   order by [Date]
)
/* -- islands -- */
, cte as (
select
    start_date = d.date
  , end_date   = d.end_date
  , x.gross_sales_price
  , grp = row_number() over (order by d.date)
        - row_number() over (partition by x.start_date order by d.date)
from dates d
  outer apply (
    select top 1 l.start_date, l.gross_sales_price
    from #t l
    where d.date >= l.start_date
      and d.date <= l.end_date
    order by l.start_date desc
    ) x
)
/* -- aggregated islands -- */
, src as (
select
    start_date = min(start_date)
  , end_date   = max(end_date)
  , gross_sales_price
from cte
group by gross_sales_price, grp
)
/* -- merge -- */
merge #t with (holdlock) as target
using src as source
  on target.start_date = source.start_date
 and target.end_date   = source.end_date
 and target.gross_sales_price = source.gross_sales_price
when not matched by target
  then insert (start_date, end_date, gross_sales_price)
    values (start_date, end_date, gross_sales_price)
when not matched by source
  then delete
output $action, inserted.*, deleted.*;
/* -- results -- */
select
    start_date
  , end_date
  , gross_sales_price
from #t
order by start_date

rextester demo:  http://rextester.com/MFXCQQ90933

merge output (you do not need to output this, just showing for the demo):

+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+
| $action |     START_DATE      |      END_DATE       | GROSS_SALES_PRICE |     START_DATE      |      END_DATE       | GROSS_SALES_PRICE |
+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+
| INSERT  | 2014-10-01 00:00:00 | 2014-10-06 23:59:59 | 29.99             | NULL                | NULL                | NULL              |
| INSERT  | 2014-08-06 00:00:00 | 2014-09-05 23:59:59 | 29.99             | NULL                | NULL                | NULL              |
| DELETE  | NULL                | NULL                | NULL              | 2014-08-06 00:00:00 | 2014-10-06 23:59:59 | 29.99             |
+---------+---------------------+---------------------+-------------------+---------------------+---------------------+-------------------+

results:

+-------------------------+-------------------------+-------------------+
|       start_date        |        end_date         | gross_sales_price |
+-------------------------+-------------------------+-------------------+
| 2014-08-06 00:00:00.000 | 2014-09-05 23:59:59.997 | 29.99             |
| 2014-09-06 00:00:00.000 | 2014-09-09 23:59:59.997 | 32.99             |
| 2014-09-10 00:00:00.000 | 2014-09-30 23:59:59.997 | 32.99             |
| 2014-10-01 00:00:00.000 | 2014-10-06 23:59:59.997 | 29.99             |
| 2014-10-07 00:00:00.000 | 2049-12-31 23:59:59.997 | 34.99             |
+-------------------------+-------------------------+-------------------+

calendar and numbers tables reference:

Generate a set or sequence without loops 2- Aaron Bertrand

Creating a Date Table/Dimension in SQL Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in SQL Server - Aaron Bertrand

merge reference:

Use Caution with SQL Server''s MERGE Statement - Aaron Bertrand

UPSERT Race Condition With Merge - Dan Guzman

An Interesting MERGE Bug - Paul White

Can I optimize this merge statement - Aaron Bertrand

If you are using indexed views and MERGE, please read this! - Aaron Bertrand

The Case of the Blocking Merge Statement (LCK_M_RS_U locks) - Kendra Little

Writing t-sql merge statements the right way - David Stein


问:
output 2d boolean masked value by tensorflow
I have a [n,m] input and [n,m] boolean mask. How could I output a [n,x] filtered matrix, instead of [x] array?

For example, input

```<code>x = [[1,2,3],[4,5,6]]
</code>```

and a boolean mask

```<code>bm = [[1,0,1],[1,0,0]]
</code>```

I tried to use tf.boolean_mask() and I got [1,3,4].
How could I get a 2D result like

```<code>result =  [[1,3],[4]]
</code>```

Thanks!

答:
There's no way to do this in TF. However, you can consider using Masked Array in numpy. You can do something like</p>

```<code>>>> import numpy as np, numpy.ma as ma
>>> x = ma.array([1., -1., 3., 4., 5., 6.], mask=[0,0,0,0,1,0])
>>> y = ma.array([1., 2., 0., 4., 5., 6.], mask=[0,0,0,0,0,1])
>>> print np.sqrt(x/y)
[1.0 -- -- 1.0 -- --]
</code>```

Body:
I have a [n,m] input and [n,m] boolean mask. How could I output a [n,x] filtered matrix, instead of [x] array?

For example, input

x = [[1,2,3],[4,5,6]]

and a boolean mask

bm = [[1,0,1],[1,0,0]]

I tried to use tf.boolean_mask() and I got [1,3,4].
How could I get a 2D result like

result =  [[1,3],[4]]

Thanks!

Body:
There's no way to do this in TF. However, you can consider using Masked Array in numpy. You can do something like

>>> import numpy as np, numpy.ma as ma
>>> x = ma.array([1., -1., 3., 4., 5., 6.], mask=[0,0,0,0,1,0])
>>> y = ma.array([1., 2., 0., 4., 5., 6.], mask=[0,0,0,0,0,1])
>>> print np.sqrt(x/y)
[1.0 -- -- 1.0 -- --]


问:
How to run firefox program in linux and get its output on windows
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

```<code># firefox
Error: GDK_BACKEND does not match available displays
</code>```

Please help

答:
Use the below command to connect

```<code>$ ssh -Y whatever.com
</code>```

On the Centos server, edit the file /etc/X11/sshd_config, it will be necessary to turn on X11 forwarding with a line like

```<code>X11Forwarding yes
</code>```

In the putty Enable X11 forwarding in the configuration.

ContentLicense: CC BY-SA 4.0

Body:
I have one centos 7 (minimum setup) installed on cloud .
I m connect it using using putty on my laptop.

I have installed Firefox on centos server which has fast internet connection.

However whenever i run Firefox its not loading because it doesn't have GUI installed (and i m connecting it using putty).

I want to browse internet on it from windows machine. How can i go about it?

Error Message

# firefox
Error: GDK_BACKEND does not match available displays

Please help

Body:
Use the below command to connect

$ ssh -Y whatever.com

On the Centos server, edit the file /etc/X11/sshd_config, it will be necessary to turn on X11 forwarding with a line like

X11Forwarding yes

In the putty Enable X11 forwarding in the configuration.


问:
Updated: Setting bool default value to true
I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.

ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.

```<code>function showSaveCardControl(ischecked) {
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
</code>```

if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.

Update:

I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.

I have tried setting the default using an attribute.

```<code>[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }
</code>```

I have tried setting it using a constructor.

```<code>public className()
{
    ischecked = true;
}
</code>```

I have also tried making all the bools nullable and the value is still being set to false

none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false

答:
Assuming the property is part of a class then just set it's default value to true in the class constructor and it will be overwritten down the line if you have logic to set the value from the config.</p>

```<code>public class LukesClass
{
 public String whatever {get;set;}
 public bool isChecked {get;set;}

 public LukesClass()
 {
  isChecked = true;
 }
}
</code>```

Body:
I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.

ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.

function showSaveCardControl(ischecked) {
    $(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}

if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.

Update:

I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.

I have tried setting the default using an attribute.

[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }

I have tried setting it using a constructor.

public className()
{
    ischecked = true;
}

I have also tried making all the bools nullable and the value is still being set to false

none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false

Body:
Assuming the property is part of a class then just set it's default value to true in the class constructor and it will be overwritten down the line if you have logic to set the value from the config.

public class LukesClass
{
 public String whatever {get;set;}
 public bool isChecked {get;set;}

 public LukesClass()
 {
  isChecked = true;
 }
}


问:
Why won't my WebView display the URL I've specified?
I'm working with a WebView. If I place this call in my -awakeFromNib:

```<code>[myWebView setMainFrameURL:@"http://www.google.com"];
</code>```

I get the behavior I want. Google's homepage displays in my WebView. But, I need to set the main frame's URL in another method from a mutable array containing NSStrings.

This method call

```<code>[myWebView setMainFrameURL:[mutableArrayContainingNSStrings objectAtIndex:0]];
</code>```

does not update the WebView. Do I need to tell the WebView to reload? I tried -setNeedsDisplay:YES and -reload to no avail.

答: Have you tried setting a breakpoint on your action method to check that both myWebView and [mutableArrayContainingNSStrings objectAtIndex:0] are pointing to the correct objects?

ContentLicense: CC BY-SA 2.5

Body:
I'm working with a WebView. If I place this call in my -awakeFromNib:

[myWebView setMainFrameURL:@"http://www.google.com"];

I get the behavior I want. Google's homepage displays in my WebView. But, I need to set the main frame's URL in another method from a mutable array containing NSStrings.

This method call

[myWebView setMainFrameURL:[mutableArrayContainingNSStrings objectAtIndex:0]];

does not update the WebView. Do I need to tell the WebView to reload? I tried -setNeedsDisplay:YES and -reload to no avail.

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Marc Charbonneau


问:
Launch modal from controller
i'm trying to show a modal window (using jquery ui dialog) to the user from my controller.

For example :

```<code>def create
  if params[:id]
    #do something
  else
    #show a modal window with a partial as content
end
</code>```

Thx for your help =)

答:
This is a fix, but probably will work for you

Controller

```<code>def create
  if params[:id]
    #true code
  else
    render :new
    @dialog = true
  end
end
</code>```

on you new.html.erb

```<code><% if @dialog %>
  <%= #dialog code %>
<% else %>
  <%= #normal code %>
<% end %>
</code>```

Hope it works.

UPDATE

If what I asked you in comment is correct then you can do this

in your new.html.erb you can do this

```<code><% form_for @product do |f| %>
  <% if @product.errors %>
    <%= #dialog code %>
  <% end %>
<% end %>
</code>```

Title: Launch modal from controller

Body:
i'm trying to show a modal window (using jquery ui dialog) to the user from my controller.

For example :

def create
  if params[:id]
    #do something
  else
    #show a modal window with a partial as content
end

Thx for your help =)

Body:
This is a fix, but probably will work for you

Controller

def create
  if params[:id]
    #true code
  else
    render :new
    @dialog = true
  end
end

on you new.html.erb

<% if @dialog %>
  <%= #dialog code %>
<% else %>
  <%= #normal code %>
<% end %>

Hope it works.

UPDATE

If what I asked you in comment is correct then you can do this

in your new.html.erb you can do this

<% form_for @product do |f| %>
  <% if @product.errors %>
    <%= #dialog code %>
  <% end %>
<% end %>


问:
How get Type of attribute from reStructuredText?
How get Type of attribute from reStructuredText?
I have something like this.

```<code>@property
def port(self):
    """Get port.

    :return: port
    :rtype: str
    """
    return self._port
</code>```

How can i get type of attribute (str)?

答:
Is the code fragment yours? If yes, you can use whatever mechanics you like, e.g. add an attribute directly to the function for later inspection: SomeClass.port.fget.return_type = int. Try it, it works. Only be careful to qualify the property via the class, not via the instance (or use .__class__ on an instance).

If not, parse the port.__doc__ and extract the relevant field.

If you are CPU-constrained, you can still use e.g. SQLAlchemy without the ORM layer. It can produce very efficient SQL from table models ahead of time, e.g. during startup. Then you just invoke them with right parameters, paying rather little CPU time. In most cases, the DB round-trip dwarfs the query creation and results decoding anyway.

Same applies to parsing the RST: you can do it ahead of time, e.g. as a build step, and store the information in an easy-to-parse file, e.g. JSON or even as pickled Python data, and quickly load it as startup.

Body:
How get Type of attribute from reStructuredText?
I have something like this.

@property
def port(self):
    """Get port.

    :return: port
    :rtype: str
    """
    return self._port

How can i get type of attribute (str)?


问:
Programmatically add Pivot Items
I want to display a list of photos in a Pivot Control, so I have this xaml

```<code><Grid x:Name="LayoutRoot" Background="Transparent">
    <controls:Pivot x:Name="DiaporamaPivot">
    </controls:Pivot>
</Grid>
</code>```

and in the code behind I do :

```<code>    public Diaporama()
    {
        InitializeComponent();

        PivotItem p = new PivotItem();
        Image     i = new Image();

        i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
        p.Margin = new Thickness(0, -10, 0, -2);

        DiaporamaPivot.Items.Add(i);
    }
</code>```

Any idea why I get an exception

答:
You are adding i (Image) to Pivot. Instead, add i to p and then, add p (PivotItem) to Pivot.

```<code>public Diaporama()
{
    InitializeComponent();

    PivotItem p = new PivotItem();
    Image     i = new Image();

    i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
    p.Margin = new Thickness(0, -10, 0, -2);

    p.Content = i;
    DiaporamaPivot.Items.Add(p);
}
</code>```

Title: Programmatically add Pivot Items

Body:
I want to display a list of photos in a Pivot Control, so I have this xaml

<Grid x:Name="LayoutRoot" Background="Transparent">
    <controls:Pivot x:Name="DiaporamaPivot">
    </controls:Pivot>
</Grid>

and in the code behind I do :

    public Diaporama()
    {
        InitializeComponent();

        PivotItem p = new PivotItem();
        Image     i = new Image();

        i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
        p.Margin = new Thickness(0, -10, 0, -2);

        DiaporamaPivot.Items.Add(i);
    }

Any idea why I get an exception

Body:
You are adding i (Image) to Pivot. Instead, add i to p and then, add p (PivotItem) to Pivot.

public Diaporama()
{
    InitializeComponent();

    PivotItem p = new PivotItem();
    Image     i = new Image();

    i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
    p.Margin = new Thickness(0, -10, 0, -2);

    p.Content = i;
    DiaporamaPivot.Items.Add(p);
}


问:
SQL: Write a query that given a varchar, find if it exists in column A or column B
Suppose I have a table with two columns, A and B

```<code>CREATE table test(
    A VARCHAR(20)
    B VARCHAR(20)
);

INSERT into A
VALUES
('cat'), ('dog'),('cow'), ('horse')

INSERT into A
VALUES
('chicken'), ('steve'),('fish'), ('eel')
</code>```

I want to write a query where given a varchar, it would return the column name where it exists (returns an empty varchar if neither). A and B does not have any identical varchars. I'm relatively new with mySql.

find('cat') returns 'A'

find('eel') returns 'B'

find('goat') returns ''

答:
Simple case should do:</p>

```<code>select
   case when A='input' then 'A'
        when B='input' then 'B'
        else 'None' end as 'ColumnName'
 from Table
</code>```

Body:
Suppose I have a table with two columns, A and B

CREATE table test(
    A VARCHAR(20)
    B VARCHAR(20)
);

INSERT into A
VALUES
('cat'), ('dog'),('cow'), ('horse')

INSERT into A
VALUES
('chicken'), ('steve'),('fish'), ('eel')

I want to write a query where given a varchar, it would return the column name where it exists (returns an empty varchar if neither). A and B does not have any identical varchars. I'm relatively new with mySql.

find('cat') returns 'A'

find('eel') returns 'B'

find('goat') returns ''

Body:
Simple case should do:

select
   case when A='input' then 'A'
        when B='input' then 'B'
        else 'None' end as 'ColumnName'
 from Table


问:
GCE Container Registry upload slow
since a couple of days the gcloud docker -- push eu.gcr.io/** has become very slow. I have tested the following:

My connection upload is fine

Restarted docker (and Mac)

What could I do? Does someone else have the same problem?

答: Sorry to hear about your poor experience. We aren't aware of any performance issue recently. If you would like us to investigate further, please share with us your project id at gcr-contact@google.com.</p>

Title: GCE Container Registry upload slow


问:
How to view syslog in ubuntu?
Follow up from this question, LogBack Syslog not working java

I use command below to view syslog in ubuntu 16.04 but get below result. Is it the correct way to view?

user@xxx:~$ tail -f /var/log/syslog Jun  6 23:08:50 xxx systemd[1]:
Starting Hostname Service... Jun  6 23:08:50 xxx dbus[889]: [system]
Successfully activated service 'org.freedesktop.hostname1' Jun  6
23:08:50 xxx systemd[1]: Started Hostname Service. Jun  6 23:09:41 xxx
gnome-session[2645]: (nautilus:2860): Gtk-WARNING **: Attempting to
read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:41 xxx org.gtk.vfs.Daemon[2508]:
(gvfsd-recent:15282): Gtk-WARNING **: Attempting to read the recently
used resources file at '/home/xxx/.local/share/recently-used.xbel',
but the parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:41 xxx gnome-session[2645]: (zeitgeist-datahub:3069):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/seng/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(nautilus:2860): Gtk-WARNING **: Attempting to read the recently used
resources file at '/home/xxx/.local/share/recently-used.xbel', but the
parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:49 xxx org.gtk.vfs.Daemon[2508]: (gvfsd-recent:15282):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(zeitgeist-datahub:3069): Gtk-WARNING **: Attempting to read the
recently used resources file at
'/home/seng/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:17:01 xxx CRON[18877]: (root) CMD (   cd
/ && run-parts --report /etc/cron.hourly)
```

<p>Try <code>cat /var/log/syslog</code> (small part of the output)</p>

```Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$
```

<p>Try  <code>cat /var/log/syslog | tail -f</code></p>

```user@xxx:/$ cat /var/log/syslog | tail -f
Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$
```

答:
In a normal terminal window (in Ubuntu, normally Gnome Terminal), what you've done -  sudo tail /var/log/syslog should display with newlines such that date/time stamps line up on the left.

Either you're not using a normal terminal window, or some control characters have knocked your terminal into a state where newlines don't display properly.

If you're using something other than a terminal window (perhaps something in your IDE?), then use a normal one instead.

tail -f /var/log/syslog is for following along as the file grows.

You can dump the whole of the file into the terminal with cat /var/log/syslog.

You can interactively scroll through the file with less /var/log/syslog.

If you prefer to use a GUI editor, you can open /var/log/syslog in a text editor like gEdit or Atom, although you would have to run those editors as root -- the responsible thing to do would be to copy the file, make it readable by your user, and open that.

Title: How to view syslog in ubuntu?

Body:
Follow up from this question, LogBack Syslog not working java

I use command below to view syslog in ubuntu 16.04 but get below result. Is it the correct way to view?

user@xxx:~$ tail -f /var/log/syslog Jun  6 23:08:50 xxx systemd[1]:
Starting Hostname Service... Jun  6 23:08:50 xxx dbus[889]: [system]
Successfully activated service 'org.freedesktop.hostname1' Jun  6
23:08:50 xxx systemd[1]: Started Hostname Service. Jun  6 23:09:41 xxx
gnome-session[2645]: (nautilus:2860): Gtk-WARNING **: Attempting to
read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:41 xxx org.gtk.vfs.Daemon[2508]:
(gvfsd-recent:15282): Gtk-WARNING **: Attempting to read the recently
used resources file at '/home/xxx/.local/share/recently-used.xbel',
but the parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:41 xxx gnome-session[2645]: (zeitgeist-datahub:3069):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/seng/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(nautilus:2860): Gtk-WARNING **: Attempting to read the recently used
resources file at '/home/xxx/.local/share/recently-used.xbel', but the
parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:49 xxx org.gtk.vfs.Daemon[2508]: (gvfsd-recent:15282):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(zeitgeist-datahub:3069): Gtk-WARNING **: Attempting to read the
recently used resources file at
'/home/seng/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:17:01 xxx CRON[18877]: (root) CMD (   cd
/ && run-parts --report /etc/cron.hourly)

Try cat /var/log/syslog (small part of the output)

Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$

Try  cat /var/log/syslog | tail -f

user@xxx:/$ cat /var/log/syslog | tail -f
Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$


问:
Angular reading data from json into textarea
I'm trying to read some test data from a local json file and output the data with correct formatting into a textarea. Right now though it just outputs [object Object].  How would I go about getting it so it outputs:

Id: theIdGoesHere

Title: theTitleGoesHere

step.service.ts The service used to call the json data

```<code>public getJson(): Observable<any>{
    return this.http.get('/assets/jsonData/MyJson.json')
      .map(response => response.json());
  }
</code>```

MyJson.json

```<code>{
    "data":[
        {
            "id": 1,
            "title":"Test1"
        },
        {
            "id": 2,
            "title":"Test2"
        }
    ]
}
</code>```

main.componenet.ts

```<code>private testVar: any;
test(){
    this.stepService.getJson().subscribe(data => (this.testVar = data));
  }

anothermethod(){
    this.test();
    this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}

get mainStepText2() { //Rebinded this one
   const text = [];
    const { data } = this.testVar;

    for (let item of this.testVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break
  }
</code>```

答:
You can use json pipe to format your object into a json string:

```<code>[(ngModel)]="mainStepText | json"
</code>```

If you want to show a specific property of your object, you can access it in your template:

```<code>[(ngModel)]="mainStepText.data[0].title"
</code>```

This will display "Test1" in your field.

Body:
I'm trying to read some test data from a local json file and output the data with correct formatting into a textarea. Right now though it just outputs [object Object].  How would I go about getting it so it outputs:

Id: theIdGoesHere

Title: theTitleGoesHere

step.service.ts The service used to call the json data

public getJson(): Observable<any>{
    return this.http.get('/assets/jsonData/MyJson.json')
      .map(response => response.json());
  }

MyJson.json

{
    "data":[
        {
            "id": 1,
            "title":"Test1"
        },
        {
            "id": 2,
            "title":"Test2"
        }
    ]
}

main.componenet.ts

private testVar: any;
test(){
    this.stepService.getJson().subscribe(data => (this.testVar = data));
  }

anothermethod(){
    this.test();
    this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}

get mainStepText2() { //Rebinded this one
   const text = [];
    const { data } = this.testVar;

    for (let item of this.testVar.data) {
      Object.keys(item).forEach(key => {
        text.push(key + ': ' + item[key]);
      });
    }

    return text.join('\r\n'); // \r\n is the line break
  }

Body:
You can use json pipe to format your object into a json string:

[(ngModel)]="mainStepText | json"

If you want to show a specific property of your object, you can access it in your template:

[(ngModel)]="mainStepText.data[0].title"

This will display "Test1" in your field.


问:
How to run a maven-packaged clojure application from the jar
I have the following contents in src/main/clojure/za/co/pb/maven_test/test.clj file:

```<code>(ns za.co.pb.maven-test.test
  (:gen-class))

(defn -main []
  (println "Hello world!"))
</code>```

I also have a POM that has the necesary dependencies on clojure-maven-plugin with the compile execution.

If I execute a mvn package command, I get a target/maven-test-1.0-SNAPSHOT.jar file and if I look in the classes folder I have these files in the folder target/classes/za/co/pb/maven_test:

test.class

test.clj

test__init.class

test$loading__4410__auto__.class

test$_main.class

This, as far as I know, is appropriate.

However, when I run this command:

java -cp target\app-1.0-SNAPSHOT.jar za.co.pb.maven_test.test

I get this:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: clojure/lang/IFn
Caused by: java.lang.ClassNotFoundException: clojure.lang.IFn
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: za.co.pb.maven_test.test. Program will exit.
</code>```

答:
If you are using leiningen, after generating the jar with lein uberjar, do not use java -jar target/your-name.jar, but use java -jar target/your-name-standalone.jar.

Same thing for boot.

Body:
I have the following contents in src/main/clojure/za/co/pb/maven_test/test.clj file:

(ns za.co.pb.maven-test.test
  (:gen-class))

(defn -main []
  (println "Hello world!"))

I also have a POM that has the necesary dependencies on clojure-maven-plugin with the compile execution.

If I execute a mvn package command, I get a target/maven-test-1.0-SNAPSHOT.jar file and if I look in the classes folder I have these files in the folder target/classes/za/co/pb/maven_test:

test.class

test.clj

test__init.class

test$loading__4410__auto__.class

test$_main.class

This, as far as I know, is appropriate.

However, when I run this command:

java -cp target\app-1.0-SNAPSHOT.jar za.co.pb.maven_test.test

I get this:

Exception in thread "main" java.lang.NoClassDefFoundError: clojure/lang/IFn
Caused by: java.lang.ClassNotFoundException: clojure.lang.IFn
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: za.co.pb.maven_test.test. Program will exit.


问:
Combinations of Map<Object, List<Object>>
I have a HashMap<GC, List<RR>> with sample data like:

```<code>key   values

gc1 - rr1
    - rr2
    - rr3

gc2 - rr4
    - rr5

gc3 - rr6
</code>```

And I need to create all possible combinations of RR from different GC like:

```<code>Combination1: rr1, rr4, rr6
Combination2: rr1, rr5, rr6
Combination3: rr2, rr4, rr6
Combination4: rr2, rr5, rr6
Combination5: rr3, rr4, rr6
Combination6: rr3, rr5, rr6
</code>```

What I've tried so far is, as @Sanket Makani suggests, to turn my HashMap<GC, List<RR>> into a List<List<RR>>, and then iterate through all the elements like:

```<code>List<List<RR>> inputList = new ArrayList<List<RR>>();

for (Map.Entry<GC, List<RR>> rrList : Map.entrySet()) {
    inputList.add(rrList.getValue());
}

List<List<RR>> combinationsList = new ArrayList<List<RR>>();

for (List<RR> rrList : inputList) {
    List<RR> rrList1 = new ArrayList<RR>();
    for (RR rr : rrList) {
        rrList1.add(rr);
    }
    combinationsList.add(rrList1);
}
</code>```

This is not working for me, as it groups all the RR inside one GC like:

```<code>Combination1: rr1, rr2, rr3
Combination2: rr4, rr5
Combination3: rr6
</code>```

So my quesiton is, how can I adapt my code to obtain the expected result?

PS: I'm working with Java6 unfortunately, so no lambdas/streams allowed.

PS2: I've seen similar questions, but can't find and exact example of what I'm looking for.

EDIT:

This is my final implementation with @nandsito's answer:

```<code>//this method groups RRs by GC key with a given list
HashMap<GC, List<RR>> GCRRHashMap = groupRRsByGC(list);

List<Map.Entry<GC, List<RR>>> mapEntryList = new ArrayList<Map.Entry<GC, List<RR>>>(GCRRHashMap.entrySet());
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
List<RR> combinations = new ArrayList<RR>();

generateCombinations(mapEntryList, combinations, combinationsList);

private void generateCombinations(
  List<Map.Entry<GC, List<RR>>> mapEntryList,
  List<RR> combinations, List<List<RR>> combinationsList) {

  if (mapEntryList.isEmpty()) {
    combinationsList.add(new ArrayList<RoomStay>(combinations));
    return;
  }

  Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);

  List<RR> entryValue = new ArrayList<RR>(entry.getValue());

  while (!entryValue.isEmpty()) {

    RR rr = entryValue.remove(0);

    combinations.add(rr);

    generateCombinations(mapEntryList, combinations, combinationsList);

    combinations.remove(combinations.size() - 1);
  }

  mapEntryList.add(0, entry);

}
</code>```

答:
Here's a recursive solution:

public static void main(String[] args) {

    // your data map
    Map<GC, List<RR>> map;

    // the map entry set as list, which will help
    // combining the elements
    //
    // note this is a modifiable list

    List<Map.Entry<GC, List<RR>>> mapEntryList =
            new ArrayList<Map.Entry<GC, List<RR>>>(map.entrySet());

    // the combinations list, which will store
    // the desired results

    List<RR> combinations = new ArrayList<RR>();

    doRecursion(mapEntryList, combinations);
}

private static void doRecursion(
        List<Map.Entry<GC, List<RR>>> mapEntryList,
        List<RR> combinations) {

    // end of recursion

    if (mapEntryList.isEmpty()) {

        // do what you wish
        //
        // here i print each element of the combination

        for (RR rr : combinations) {

            System.out.println(rr);
        }

        System.out.println();

        return;
    }

    // remove one GC from the entry list,
    // then for each RR from the taken GC
    //     put RR in the combinations list,
    //     call recursion
    //     the remove RR from the combinations list
    // end for each
    // then put GC back into its list

    Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);

    List<RR> entryValue = new ArrayList<RR>(entry.getValue());

    while (!entryValue.isEmpty()) {

        RR rr = entryValue.remove(0);

        combinations.add(rr);

        doRecursion(mapEntryList, combinations);

        combinations.remove(combinations.size() - 1);
    }

    mapEntryList.add(0, entry);
}
```

Body:
I have a HashMap<GC, List<RR>> with sample data like:

key   values

gc1 - rr1
    - rr2
    - rr3

gc2 - rr4
    - rr5

gc3 - rr6

And I need to create all possible combinations of RR from different GC like:

Combination1: rr1, rr4, rr6
Combination2: rr1, rr5, rr6
Combination3: rr2, rr4, rr6
Combination4: rr2, rr5, rr6
Combination5: rr3, rr4, rr6
Combination6: rr3, rr5, rr6

What I've tried so far is, as @Sanket Makani suggests, to turn my HashMap<GC, List<RR>> into a List<List<RR>>, and then iterate through all the elements like:

List<List<RR>> inputList = new ArrayList<List<RR>>();

for (Map.Entry<GC, List<RR>> rrList : Map.entrySet()) {
    inputList.add(rrList.getValue());
}

List<List<RR>> combinationsList = new ArrayList<List<RR>>();

for (List<RR> rrList : inputList) {
    List<RR> rrList1 = new ArrayList<RR>();
    for (RR rr : rrList) {
        rrList1.add(rr);
    }
    combinationsList.add(rrList1);
}

This is not working for me, as it groups all the RR inside one GC like:

Combination1: rr1, rr2, rr3
Combination2: rr4, rr5
Combination3: rr6

So my quesiton is, how can I adapt my code to obtain the expected result?

PS: I'm working with Java6 unfortunately, so no lambdas/streams allowed.

PS2: I've seen similar questions, but can't find and exact example of what I'm looking for.

EDIT:

This is my final implementation with @nandsito's answer:

//this method groups RRs by GC key with a given list
HashMap<GC, List<RR>> GCRRHashMap = groupRRsByGC(list);

List<Map.Entry<GC, List<RR>>> mapEntryList = new ArrayList<Map.Entry<GC, List<RR>>>(GCRRHashMap.entrySet());
List<List<RR>> combinationsList = new ArrayList<List<RR>>();
List<RR> combinations = new ArrayList<RR>();

generateCombinations(mapEntryList, combinations, combinationsList);

private void generateCombinations(
  List<Map.Entry<GC, List<RR>>> mapEntryList,
  List<RR> combinations, List<List<RR>> combinationsList) {

  if (mapEntryList.isEmpty()) {
    combinationsList.add(new ArrayList<RoomStay>(combinations));
    return;
  }

  Map.Entry<GC, List<RR>> entry = mapEntryList.remove(0);

  List<RR> entryValue = new ArrayList<RR>(entry.getValue());

  while (!entryValue.isEmpty()) {

    RR rr = entryValue.remove(0);

    combinations.add(rr);

    generateCombinations(mapEntryList, combinations, combinationsList);

    combinations.remove(combinations.size() - 1);
  }

  mapEntryList.add(0, entry);

}


问:
Cloudant in Node.js, How to make a query with multiple results
I am using node.js and ibm bluemix to run the back-end apps. I am using cloudant module. But in github as I search, I only found how to make a query with 1 result. So I want to ask you guys how can I make a query with multiple results. I want to make it in my app.js. My sample database are

```<code>{
  "userid":"chris"
  "time":"12.20",
  "power":"200",
}

{
  "userid":"chris"
  "time":"12.30",
  "power":"250",
}
</code>```

And there will be plenty of data with same userid and different time and power. How do I want to make the query it and publish it with mqtt?

Thanks for your help.

答:
You probably want to create a view for your cloudant database and then query the view. This will use the map and possibly the reduce features in the view. So, for example, if you wanted to find all records related to a single userid, you might create a view like the following: </p>

```<code>{
  "_id": "_design/views",
  "views": {
    "byUser": {
      "map": "function (doc) { if (doc.userid) {emit(doc.userid, doc); } }"
    }
  }
}
</code>```

<p>This is a slightly lazy way to handle the mapping process as it creates a view with all of your document contents in the view. That way, when the query results are returned, the result set includes complete records, rather than just an _id and the userid fields. This reduces the transactional load on the cloudant db, but increases the size of the actual db. </p>

Body:
I am using node.js and ibm bluemix to run the back-end apps. I am using cloudant module. But in github as I search, I only found how to make a query with 1 result. So I want to ask you guys how can I make a query with multiple results. I want to make it in my app.js. My sample database are

{
  "userid":"chris"
  "time":"12.20",
  "power":"200",
}

{
  "userid":"chris"
  "time":"12.30",
  "power":"250",
}

And there will be plenty of data with same userid and different time and power. How do I want to make the query it and publish it with mqtt?

Thanks for your help.

Body:
You probably want to create a view for your cloudant database and then query the view. This will use the map and possibly the reduce features in the view. So, for example, if you wanted to find all records related to a single userid, you might create a view like the following:

{
  "_id": "_design/views",
  "views": {
    "byUser": {
      "map": "function (doc) { if (doc.userid) {emit(doc.userid, doc); } }"
    }
  }
}

This is a slightly lazy way to handle the mapping process as it creates a view with all of your document contents in the view. That way, when the query results are returned, the result set includes complete records, rather than just an _id and the userid fields. This reduces the transactional load on the cloudant db, but increases the size of the actual db.


问:
Launching Activities via package names
I have been working on testing some packages that I do not have the source code for, and one of the packages is normally launched by pressing three buttons for three seconds. When I try to launch the package using the typical method, I get a java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.addFlags(int) error. Below is my code

```<code>@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    final String launcherPackage = mDevice.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

    Context context = InstrumentationRegistry.getTargetContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(DEALER_DIAG_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(DEALER_DIAG_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
</code>```

I tried using getContext instead of getTargetContext, however someone pointed out to me that if the intents are not exported, I will not be able to launch the package this way no matter what I do. I tried to get the package names by using the command adb logcat ActivityManager:V *:F as well as adb shell pm list packages -f

```<code>--------- beginning of main
I/ActivityManager( 2296): START u0 {flg=0x10000000
cmp=com.android.systemui/.usb.UsbDebuggingActivity (has extras)} from uid
1000 on display 0
I/ActivityManager( 2296): Displayed
com.android.systemui/.usb.UsbDebuggingActivity: +184ms
I/ActivityManager( 2296): START u0 {act=android.intent.action.MAIN cat=
[android.intent.category.HOME] flg=0x10200000
cmp=com.android.launcher3/.Launcher} from uid 1000 on display 0
I/ActivityManager( 2296): START u0
{act=com.REDACTED.auto.diagnostics.dealer.MAIN flg=0x10800000
cmp=com.REDACTED.auto.diagnostics/.dealer.MainActivity} from uid 1000 on
display 0
I/ActivityManager( 2296): Start proc
20943:com.REDACTED.auto.diagnostics/1000 for activity
com.REDACTED.auto.diagnostics/.dealer.MainActivity
I/ActivityManager( 2296): Displayed
com.REDACTED.auto.diagnostics/.dealer.MainActivity: +572ms
</code>```

Does anyone have any input as to why I am getting this error? I have tried using every package name listed in the logcat dump with no success. Any input would be appreciated.

答:
If you want to launch another app just first check if this app is installed, or you'll get a NullPointerException, then launch the app by an intent with the package options:

Just like this:

```<code>Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.domain.anotherapp");
        if (launchIntent != null) {
            startActivity(launchIntent);//null pointer check in case package name was not found
        }
</code>```

This will launch the app with the default launch activity, if you want to launch a specific activity you already have to know how to handle the requirements of the other app side or will simply crash or not work (probably you might need to pass some variable or some data to represent previous information of this app), anyway, to open this specific activity you have to use ComponentName.

The ComponentName constructor taking two Strings can be used to refer to a component in another application.  But, the first argument is not the package name of the class; it is the package name of the application---the package attribute of the manifest element in that application's AndroidManifest.xml.  So your first example should be

```<code>ComponentName cn = new ComponentName("com.domain.anotherapp",
    "com.domain.anotherapp.widget.WidgetProvider");
</code>```

That constructor could certainly be used to refer to components in your own application, but since you already have hold of a Context from your own application you might as well use it and use one of the other constructors.  In my opinion, the one taking a Class should be preferred whenever usable.  You could use the one taking a String if you only know the class dynamically for some reason; in that case, it should take the fully-qualified class name as above.

The complete use to launch by an intent (without handle the null pointer exception for an incorrect passed information):

```<code>Intent launchIntent = new Intent(Intent.ACTION_MAIN);
                launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                ComponentName cn = new ComponentName("com.domain.anotherapp",
                "com.domain.anotherapp.widget.WidgetProvider");
                launchIntent.setComponent(cn);

                startActivity(launchIntent);
</code>```

Reference:
https://developer.android.com/reference/android/content/ComponentName.html

Title: Launching Activities via package names

Body:
I have been working on testing some packages that I do not have the source code for, and one of the packages is normally launched by pressing three buttons for three seconds. When I try to launch the package using the typical method, I get a java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.addFlags(int) error. Below is my code

@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    final String launcherPackage = mDevice.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

    Context context = InstrumentationRegistry.getTargetContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(DEALER_DIAG_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(DEALER_DIAG_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

I tried using getContext instead of getTargetContext, however someone pointed out to me that if the intents are not exported, I will not be able to launch the package this way no matter what I do. I tried to get the package names by using the command adb logcat ActivityManager:V *:F as well as adb shell pm list packages -f

--------- beginning of main
I/ActivityManager( 2296): START u0 {flg=0x10000000
cmp=com.android.systemui/.usb.UsbDebuggingActivity (has extras)} from uid
1000 on display 0
I/ActivityManager( 2296): Displayed
com.android.systemui/.usb.UsbDebuggingActivity: +184ms
I/ActivityManager( 2296): START u0 {act=android.intent.action.MAIN cat=
[android.intent.category.HOME] flg=0x10200000
cmp=com.android.launcher3/.Launcher} from uid 1000 on display 0
I/ActivityManager( 2296): START u0
{act=com.REDACTED.auto.diagnostics.dealer.MAIN flg=0x10800000
cmp=com.REDACTED.auto.diagnostics/.dealer.MainActivity} from uid 1000 on
display 0
I/ActivityManager( 2296): Start proc
20943:com.REDACTED.auto.diagnostics/1000 for activity
com.REDACTED.auto.diagnostics/.dealer.MainActivity
I/ActivityManager( 2296): Displayed
com.REDACTED.auto.diagnostics/.dealer.MainActivity: +572ms

Does anyone have any input as to why I am getting this error? I have tried using every package name listed in the logcat dump with no success. Any input would be appreciated.

Body:
If you want to launch another app just first check if this app is installed, or you'll get a NullPointerException, then launch the app by an intent with the package options:

Just like this:

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.domain.anotherapp");
        if (launchIntent != null) {
            startActivity(launchIntent);//null pointer check in case package name was not found
        }

This will launch the app with the default launch activity, if you want to launch a specific activity you already have to know how to handle the requirements of the other app side or will simply crash or not work (probably you might need to pass some variable or some data to represent previous information of this app), anyway, to open this specific activity you have to use ComponentName.

The ComponentName constructor taking two Strings can be used to refer to a component in another application.  But, the first argument is not the package name of the class; it is the package name of the application---the package attribute of the manifest element in that application's AndroidManifest.xml.  So your first example should be

ComponentName cn = new ComponentName("com.domain.anotherapp",
    "com.domain.anotherapp.widget.WidgetProvider");

That constructor could certainly be used to refer to components in your own application, but since you already have hold of a Context from your own application you might as well use it and use one of the other constructors.  In my opinion, the one taking a Class should be preferred whenever usable.  You could use the one taking a String if you only know the class dynamically for some reason; in that case, it should take the fully-qualified class name as above.

The complete use to launch by an intent (without handle the null pointer exception for an incorrect passed information):

Intent launchIntent = new Intent(Intent.ACTION_MAIN);
                launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                ComponentName cn = new ComponentName("com.domain.anotherapp",
                "com.domain.anotherapp.widget.WidgetProvider");
                launchIntent.setComponent(cn);

                startActivity(launchIntent);

Reference:
https://developer.android.com/reference/android/content/ComponentName.html


问:
Get absolute URL for paperclip attachment
Is it possible to get the absolute URI for a Paperclip attachment? Right now, the problem is that the production environment is deployed in a sub-URI (on Passenger: RackBaseURI), but <paperclip attachment>.url returns the Rails-app relative URI (/system/images/...). Is there a way to get the absolute URI for Paperclip attachments?

I'm using Paperclip v2.7 and Rails 3.2.8.

答:
You can add to your application.rb (or for specific enviroment in config/environments/*):

```<code>config.paperclip_defaults = {
    url: "http://my.address.com/system/:class/:attachment/:id_partition/:style.:extension",
    path: ':rails_root/public/system/:class/:attachment/:id_partition/:style.:extension',
}
</code>```

Restart and reimport your images.

PS: obviously you can replace http://my.address.com with an environment variable.

Body:
You can add to your application.rb (or for specific enviroment in config/environments/*):

config.paperclip_defaults = {
    url: "http://my.address.com/system/:class/:attachment/:id_partition/:style.:extension",
    path: ':rails_root/public/system/:class/:attachment/:id_partition/:style.:extension',
}

Restart and reimport your images.

PS: obviously you can replace http://my.address.com with an environment variable.


问:
Server A using xmlreader to read XML from xmlwriter on server B
I have two servers

Server A reads http://www.some-url.com/xmlwriter_src.php using

```<code>$reader = new XMLReader();
$reader->open('http://www.some-url.com/xmlwriter_src.php');
while ($reader->read())
{
  /* -- do something -- */
}
</code>```

Server B creates an xml stream

```<code>$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}
</code>```

the xmlreader on server A keeps complaining that server B doesnt respond, even though I can see the xml result in the browser.

It takes less than a second to generate

If i copy the xml to a static file, the xmlreader outputs the file.

答:
By default the writter will buffer your output.
Once you are done you MUST call flush().

```<code>$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}
$writer->flush();
</code>```

By the way:
 where do you close the records element?

Body:
I have two servers

Server A reads http://www.some-url.com/xmlwriter_src.php using

$reader = new XMLReader();
$reader->open('http://www.some-url.com/xmlwriter_src.php');
while ($reader->read())
{
  /* -- do something -- */
}

Server B creates an xml stream

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}

the xmlreader on server A keeps complaining that server B doesnt respond, even though I can see the xml result in the browser.

It takes less than a second to generate

If i copy the xml to a static file, the xmlreader outputs the file.

Body:
By default the writter will buffer your output.
Once you are done you MUST call flush().

$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument("1.0");

$writer->startElement("records");
while(!$recordset->EOF)
{
  $writer->startElement($fieldname)
  $writer->text($recordset->fields[$fieldname]);
  $writer->endElement();
  $recordset->movenext();
}
$writer->flush();

By the way:
 where do you close the records element?


答:
Use a WHERE to filter to the row containing your variable.  Then a CASE statement for the logic.

```<code>SELECT
   CASE
    WHEN A = [your varchar] THEN 'A'
    WHEN B = [your varchar] THEN 'B'
    END
FROM test
WHERE A = [your varchar] OR B = [your varchar]
</code>```

Note: this will return no rows if the variable is not present.  And if the variable is present multiple times, it'll return one row for every occurrence.  Finally, if it is found in both columns, this query will only return "A" since CASE statements are checked in order written.

Title: SQL: Write a query that given a varchar, find if it exists in column A or column B

Body:
Use a WHERE to filter to the row containing your variable.  Then a CASE statement for the logic.

SELECT
   CASE
    WHEN A = [your varchar] THEN 'A'
    WHEN B = [your varchar] THEN 'B'
    END
FROM test
WHERE A = [your varchar] OR B = [your varchar]

Note: this will return no rows if the variable is not present.  And if the variable is present multiple times, it'll return one row for every occurrence.  Finally, if it is found in both columns, this query will only return "A" since CASE statements are checked in order written.


答:
I would do it like this

```<code>SET @c = 'Z';
SELECT
    IfNull((SELECT 'A' FROM Test WHERE A = @c LIMIT 1), '')
    +
    IfNull((SELECT 'B' FROM Test WHERE B = @c LIMIT 1), '')
</code>```

That way you'll only get 1 row, and it'll be 'A', 'B', 'AB' (if both), '' (if none)

Body:
I would do it like this

SET @c = 'Z';
SELECT
    IfNull((SELECT 'A' FROM Test WHERE A = @c LIMIT 1), '')
    +
    IfNull((SELECT 'B' FROM Test WHERE B = @c LIMIT 1), '')

That way you'll only get 1 row, and it'll be 'A', 'B', 'AB' (if both), '' (if none)


问:
fatal error mysql.h:No such file or directory during compilation
I have the following code

```<code>#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  printf("MySQL client version: %s\n", mysql_get_client_info());

  exit(0);
}
</code>```

when i try to compile it using

```<code>gcc mysqldb.c -o mysql -I/usr/include/mysql -lmysqlclient
</code>```

i get an error saying fatal error mysql.h:No such file or directory. how can i successfully compile and run the code

答:
I come across the same error today, turn out that I forget to install package libmysqlclient-dev. After I install it with

sudo apt install libmysqlclient-dev
```

the error went away.

Body:
I have the following code

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  printf("MySQL client version: %s\n", mysql_get_client_info());

  exit(0);
}

when i try to compile it using

gcc mysqldb.c -o mysql -I/usr/include/mysql -lmysqlclient

i get an error saying fatal error mysql.h:No such file or directory. how can i successfully compile and run the code

Body:
I come across the same error today, turn out that I forget to install package libmysqlclient-dev. After I install it with

sudo apt install libmysqlclient-dev

the error went away.


问:
How do i setup a default controller or hide the controller name using asp.net MVC2
On my project I have only one controller so I want to do this:

```<code>http://www.example.com/{action}/{optional id}
</code>```

All actions will be of a defined controller.

答:
Change the path templates in the Global.asax

there will be something like

```<code>public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // route
new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // defaults
}
</code>```

to change to something like

```<code>public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
</code>```

Body:
On my project I have only one controller so I want to do this:

http://www.example.com/{action}/{optional id}

All actions will be of a defined controller.

Body:
Change the path templates in the Global.asax

there will be something like

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // route
new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // defaults
}

to change to something like

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}


问:
Which C++ versions are supported by specific Visual Studio versions?
Which Visual Studio Version support C++11, C++14 or C++17?

I assume, that some version do support not all functions, but the question is aimed at the core functions.

Are there any differences between the Community Versions concerning the supported C++ version?

Thanks.

答:
That’s a bit of a tricky question. For GCC/libstdc++ and Clang/libc++ the answer is usually pretty clear along the lines of: “Full support for all C++XX language and library features starting from version X.Y”.

But MSVC even in the very latest version does not have full support for C++11. On the other hand it already has a lot of the features from C++14 and even the upcoming C++17. So the question you’ll have to answer is: Which features do I want/need and from which version are they available? The links from the other question and its comments are a good starting point for this:

Support For C++11/14/17 Features (Modern C++)

Visual C++ Team Blog: C++17 Features In Visual Studio 2017 Version 15.3 Preview. There may be new versions of this blog post for newer VS versions as they are released. Look for posts by Stephan T. Lavavej to find the latest one. He is the maintainer of Microsoft’s standard library implementation.

As a rule of thumb I recommend you always go with the very latest version you can get your hands on. And if that’s not possible you probably don’t want to go older than VS 2015.

Microsoft constantly closes more and more of those older holes in their implementation. So probably and hopefully by C++20 or C++23 the situation will be similar to Clang or GCC.