问:
Outside the coordinate system in Div html
The problem is that when you leave the block. Down and right - the scroll appears. And when you go left and up - there is none.
And it is needed (the code below can be run and checked)

$(function () {
    $("#draggable3").draggable({});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.generic-container {
 height: 95vh;
  width: 100vh;
  overflow: scroll;
 background-color: #aaa;
  position: relative;

}

#draggable3{
  height: 40vh;
  width: 40vh;
  background-color: #fff;
 position: absolute;
 left: 28%;
 top: 28%;
}</code>```

 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 <link rel="stylesheet" href="/resources/demos/style.css">

```

Limit the movement of the parameter - "containment: 'parent'" It does not suit me

答:
Add scroll: false option and remove overflow: scroll; from your css.

$(function() {
  $("#draggable3").draggable({
    containment: ".generic-container",
    scroll: false
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.generic-container {
  height: 95vh;
  width: 100vh;
  background-color: #aaa;
  position: relative;
}

#draggable3 {
  height: 40vh;
  width: 40vh;
  background-color: #fff;
  position: absolute;
  left: 28%;
  top: 28%;
}</code>```

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

```

Body:
The problem is that when you leave the block. Down and right - the scroll appears. And when you go left and up - there is none.
And it is needed (the code below can be run and checked)

$(function () {
    $("#draggable3").draggable({});
});

.generic-container {
 height: 95vh;
  width: 100vh;
  overflow: scroll;
 background-color: #aaa;
  position: relative;

}

#draggable3{
  height: 40vh;
  width: 40vh;
  background-color: #fff;
 position: absolute;
 left: 28%;
 top: 28%;
}

 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
 <link rel="stylesheet" href="/resources/demos/style.css">

Limit the movement of the parameter - "containment: 'parent'" It does not suit me

Body:
Add scroll: false option and remove overflow: scroll; from your css.

$(function() {
  $("#draggable3").draggable({
    containment: ".generic-container",
    scroll: false
  });
});

.generic-container {
  height: 95vh;
  width: 100vh;
  background-color: #aaa;
  position: relative;
}

#draggable3 {
  height: 40vh;
  width: 40vh;
  background-color: #fff;
  position: absolute;
  left: 28%;
  top: 28%;
}

<html>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<body>

  <div class="generic-container">
    <div id='draggable3' class="draggable">

    </div>

  </div>

</body>

</html>


来源: stackexchange

问:
In MS SQL Server, inserting Rows into a table variable became painfully slow all the sudden
In MS SQL Server 2008, inserting Rows into a table variable became painfully slow all the sudden.
The creation of a table variable and query and insertion rows is done in a sproc and it has become terribly slow.

The query completes virtually instantly, returns a small set (10 rows of 1 column of ints), and takes upward of 50 seconds to insert into the table variable.
I switched back to temp tables and that is fine, the operation happens in a few microseconds.

答:
From table (Transact-SQL)

Queries that modify table variables do
  not generate parallel query execution
  plans. Performance can be affected
  when very large table variables, or
  table variables in complex queries,
  are modified. In these situations,
  consider using temporary tables
  instead.

ContentLicense: CC BY-SA 2.5


问:
SQL Server 2008 - Create From and To Date from Single Date Column
To start the table I'm dealing with has inconsistency as there are blank tenant values something I cannot control (vendor will take time to fix it). Also the date columns are varchar as that how it's in the actual table. Again something I cannot control and for the purpose of the report to pick the max date, the date columns need to changed from char to date. The database is running on SQL Server 2008 so cannot use LEAD function

I have a @rent table variable as below which holds the tenant rent charged values. I.e every time a tenant rent is updated\changed it gets applied in the @rent table. In certain cases the rent can be updated multiple times in a day or changed in the future if teams find incorrect rent was applied (notice the created date_sql). The Date_changed_SQL indicates when the rent is actually applied. DATE_CHANGED_SQL column will be used to create From to To columns.

In most cases there will be a duplicate DATE_CHANGED_SQL but based on the CREATED_DATE_SQL and time of the latest TOT_DEB_Val needs to be selected

Sample data:

```<code>Declare @rent TABLE
    ([R23_SQL_ID] int, [PROP_CODE] int, [TENANT_NUMB] varchar(5), [TOT_DEB_VAL] int, [DATE_CHANGED_SQL] varchar(10), [TIME_CHANGED_SQL] varchar(5), [CREATED_DATE_SQL] varchar(10), [CREATED_TIME_SQL] varchar(5))

INSERT INTO @rent
    ([R23_SQL_ID], [PROP_CODE], [TENANT_NUMB], [TOT_DEB_VAL], [DATE_CHANGED_SQL], [TIME_CHANGED_SQL], [CREATED_DATE_SQL], [CREATED_TIME_SQL])
VALUES
    (12080, 2524, '41673', 77.49, '2011-07-28', '04:42', '2013-03-19', '04:42'),
    (12081, 2524, '41673', 79.42, '2012-02-02', '04:42', '2013-03-19', '04:42'),
    (12082, 2524, '41673', 79.95, '2012-08-16', '04:42', '2013-03-19', '04:42'),
    (21819, 2524, '', 67.91, '2015-01-15', '09:39', '2015-01-15', '09:39'),
    (21820, 2524, '51500', 67.91, '2015-01-16', '', '2015-01-15', '09:45'),
    (31729, 2524, '51500', 67.91, '2016-08-08', '', '2016-08-08', ''),
    (31152, 2524, '51500', 193.48, '2016-09-05', '10:53', '2016-09-05', '10:53'),
    (34215, 2524, '', 89.86, '2017-03-14', '18:53', '2017-03-14', '18:53'),
    (34216, 2524, '53407', 89.86, '2017-03-15', '', '2017-03-14', '18:53'),
    (34260, 2524, '53407', 89.86, '2017-03-15', '12:32', '2017-03-20', '12:32'),
     (29461, 1589, '33659', 151.78, '2000-08-21', '19:00', '2016-08-16', '19:00'),
    (8356, 1589, '33659', 136.84, '2011-05-26', '04:42', '2013-03-19', '04:42'),
    (8357, 1589, '33659', 144.36, '2011-11-24', '04:42', '2013-03-19', '04:42'),
    (8358, 1589, '33659', 147.91, '2012-05-31', '04:42', '2013-03-19', '04:42'),
    (8359, 1589, '33659', 151.78, '2012-11-29', '04:42', '2013-03-19', '04:42'),
    (14502, 1589, '33659', 200.00, '2013-08-12', '08:30', '2013-08-12', '08:30'),
    (15476, 1589, '', 157.68, '2013-11-22', '09:49', '2013-11-22', '09:49'),
    (17846, 1589, '50602', 157.68, '2013-11-29', '14:00', '2014-05-21', '14:00'),
    (18548, 1589, '50980', 157.68, '2014-06-18', '', '2014-06-18', '13:21'),
    (18547, 1589, '50980', 160.69, '2014-06-18', '13:21', '2014-06-18', '13:21'),
    (20351, 1589, '51343', 160.69, '2014-11-07', '', '2014-11-05', '14:20'),
    (24096, 1589, '51343', 163.74, '2015-07-27', '07:34', '2015-07-27', '07:34'),
    (26286, 1589, '51343', 165.01, '2016-01-25', '08:59', '2016-01-25', '08:59'),
    (28168, 1589, '51343', 166.31, '2016-06-13', '11:02', '2016-06-13', '11:02'),
    (32751, 1589, '51343', 166.80, '2016-12-12', '08:52', '2016-12-12', '08:52'),
    (34058, 1589, '53386', 110.91, '2017-03-07', '', '2017-03-07', '08:22'),
    (34057, 1589, '53386', 110.91, '2017-03-07', '08:17', '2017-03-07', '08:17'),
    (34189, 1589, '53386', 110.91, '2017-03-07', '13:19', '2017-03-13', '13:19')
</code>```

Requirement: I'm trying to create a view to show the rent period (From and To), the rent value per property and tenant as below

Desired Result Screenshot

答:
The following seems to be pretty close to what you want. You may need to adjust it a little. It doesn't quite give you the results as per your data set ... but it's pretty close and should give you something to work with.</p>

```<code>/*cte assigns a row number to each entry, so we can join to the following row for that property*/
with cte as (
select
    R23_SQL_ID,
    PROP_CODE,
    TENANT_NUMB,
    DATE_CHANGED_SQL,
    TOT_DEB_VAL,
    CREATED_DATE_SQL,
    ROW_NUMBER() OVER (PARTITION BY PROP_CODE ORDER BY DATE_CHANGED_SQL, TIME_CHANGED_SQL) as Seqn
from @rent
    --I wasn't sure about this where clause, you may want to get rid of it, but the results were closer to what you asked for with it in.
    where TENANT_NUMB <> ''
   )

select
    rentStart.R23_SQL_ID,
    rentStart.PROP_CODE,
    rentStart.TENANT_NUMB,
    rentStart.DATE_CHANGED_SQL as From_Date,
    --where you've got to the last row, I've put in "today" as the end date
    convert(char(10),isnull(dateadd(dd,-1,rentEnd.DATE_CHANGED_SQL), getdate()),121) as To_Date,
    rentStart.TOT_DEB_VAL,
    rentStart.CREATED_DATE_SQL
from
    cte as rentStart
    LEFT JOIN cte as rentEnd ON
        rentStart.Prop_Code = rentEnd .Prop_Code AND
        rentStart.Seqn + 1 = rentEnd .Seqn
where
    --Filtering to just the property you were showing
    rentStart.Prop_Code = 2524
    --This is the attempt to look only for the final change in the day. It may be better handled in the CTE rather than here.
AND (rentStart.DATE_CHANGED_SQL < rentEnd.Date_CHANGED_SQL OR rentEnd.DATE_CHANGED_SQL is null)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To start the table I'm dealing with has inconsistency as there are blank tenant values something I cannot control (vendor will take time to fix it). Also the date columns are varchar as that how it's in the actual table. Again something I cannot control and for the purpose of the report to pick the max date, the date columns need to changed from char to date. The database is running on SQL Server 2008 so cannot use LEAD function

I have a @rent table variable as below which holds the tenant rent charged values. I.e every time a tenant rent is updated\changed it gets applied in the @rent table. In certain cases the rent can be updated multiple times in a day or changed in the future if teams find incorrect rent was applied (notice the created date_sql). The Date_changed_SQL indicates when the rent is actually applied. DATE_CHANGED_SQL column will be used to create From to To columns.

In most cases there will be a duplicate DATE_CHANGED_SQL but based on the CREATED_DATE_SQL and time of the latest TOT_DEB_Val needs to be selected

Sample data:

Declare @rent TABLE
    ([R23_SQL_ID] int, [PROP_CODE] int, [TENANT_NUMB] varchar(5), [TOT_DEB_VAL] int, [DATE_CHANGED_SQL] varchar(10), [TIME_CHANGED_SQL] varchar(5), [CREATED_DATE_SQL] varchar(10), [CREATED_TIME_SQL] varchar(5))

INSERT INTO @rent
    ([R23_SQL_ID], [PROP_CODE], [TENANT_NUMB], [TOT_DEB_VAL], [DATE_CHANGED_SQL], [TIME_CHANGED_SQL], [CREATED_DATE_SQL], [CREATED_TIME_SQL])
VALUES
    (12080, 2524, '41673', 77.49, '2011-07-28', '04:42', '2013-03-19', '04:42'),
    (12081, 2524, '41673', 79.42, '2012-02-02', '04:42', '2013-03-19', '04:42'),
    (12082, 2524, '41673', 79.95, '2012-08-16', '04:42', '2013-03-19', '04:42'),
    (21819, 2524, '', 67.91, '2015-01-15', '09:39', '2015-01-15', '09:39'),
    (21820, 2524, '51500', 67.91, '2015-01-16', '', '2015-01-15', '09:45'),
    (31729, 2524, '51500', 67.91, '2016-08-08', '', '2016-08-08', ''),
    (31152, 2524, '51500', 193.48, '2016-09-05', '10:53', '2016-09-05', '10:53'),
    (34215, 2524, '', 89.86, '2017-03-14', '18:53', '2017-03-14', '18:53'),
    (34216, 2524, '53407', 89.86, '2017-03-15', '', '2017-03-14', '18:53'),
    (34260, 2524, '53407', 89.86, '2017-03-15', '12:32', '2017-03-20', '12:32'),
     (29461, 1589, '33659', 151.78, '2000-08-21', '19:00', '2016-08-16', '19:00'),
    (8356, 1589, '33659', 136.84, '2011-05-26', '04:42', '2013-03-19', '04:42'),
    (8357, 1589, '33659', 144.36, '2011-11-24', '04:42', '2013-03-19', '04:42'),
    (8358, 1589, '33659', 147.91, '2012-05-31', '04:42', '2013-03-19', '04:42'),
    (8359, 1589, '33659', 151.78, '2012-11-29', '04:42', '2013-03-19', '04:42'),
    (14502, 1589, '33659', 200.00, '2013-08-12', '08:30', '2013-08-12', '08:30'),
    (15476, 1589, '', 157.68, '2013-11-22', '09:49', '2013-11-22', '09:49'),
    (17846, 1589, '50602', 157.68, '2013-11-29', '14:00', '2014-05-21', '14:00'),
    (18548, 1589, '50980', 157.68, '2014-06-18', '', '2014-06-18', '13:21'),
    (18547, 1589, '50980', 160.69, '2014-06-18', '13:21', '2014-06-18', '13:21'),
    (20351, 1589, '51343', 160.69, '2014-11-07', '', '2014-11-05', '14:20'),
    (24096, 1589, '51343', 163.74, '2015-07-27', '07:34', '2015-07-27', '07:34'),
    (26286, 1589, '51343', 165.01, '2016-01-25', '08:59', '2016-01-25', '08:59'),
    (28168, 1589, '51343', 166.31, '2016-06-13', '11:02', '2016-06-13', '11:02'),
    (32751, 1589, '51343', 166.80, '2016-12-12', '08:52', '2016-12-12', '08:52'),
    (34058, 1589, '53386', 110.91, '2017-03-07', '', '2017-03-07', '08:22'),
    (34057, 1589, '53386', 110.91, '2017-03-07', '08:17', '2017-03-07', '08:17'),
    (34189, 1589, '53386', 110.91, '2017-03-07', '13:19', '2017-03-13', '13:19')

Requirement: I'm trying to create a view to show the rent period (From and To), the rent value per property and tenant as below

Desired Result Screenshot

Body:
The following seems to be pretty close to what you want. You may need to adjust it a little. It doesn't quite give you the results as per your data set ... but it's pretty close and should give you something to work with.

/*cte assigns a row number to each entry, so we can join to the following row for that property*/
with cte as (
select
    R23_SQL_ID,
    PROP_CODE,
    TENANT_NUMB,
    DATE_CHANGED_SQL,
    TOT_DEB_VAL,
    CREATED_DATE_SQL,
    ROW_NUMBER() OVER (PARTITION BY PROP_CODE ORDER BY DATE_CHANGED_SQL, TIME_CHANGED_SQL) as Seqn
from @rent
    --I wasn't sure about this where clause, you may want to get rid of it, but the results were closer to what you asked for with it in.
    where TENANT_NUMB <> ''
   )

select
    rentStart.R23_SQL_ID,
    rentStart.PROP_CODE,
    rentStart.TENANT_NUMB,
    rentStart.DATE_CHANGED_SQL as From_Date,
    --where you've got to the last row, I've put in "today" as the end date
    convert(char(10),isnull(dateadd(dd,-1,rentEnd.DATE_CHANGED_SQL), getdate()),121) as To_Date,
    rentStart.TOT_DEB_VAL,
    rentStart.CREATED_DATE_SQL
from
    cte as rentStart
    LEFT JOIN cte as rentEnd ON
        rentStart.Prop_Code = rentEnd .Prop_Code AND
        rentStart.Seqn + 1 = rentEnd .Seqn
where
    --Filtering to just the property you were showing
    rentStart.Prop_Code = 2524
    --This is the attempt to look only for the final change in the day. It may be better handled in the CTE rather than here.
AND (rentStart.DATE_CHANGED_SQL < rentEnd.Date_CHANGED_SQL OR rentEnd.DATE_CHANGED_SQL is null)


问:
How to reuse properties from application.properties (Spring Boot) in Maven pom.xml?
I would like to define database url, username, password in one place. Currently I have

application.properties with

```<code>spring.datasource.url=....
spring.datasource.username=sa
spring.datasource.password=00
</code>```

And pom.xml with

```<code>  <plugin>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-maven-plugin</artifactId>
    <version>4.1.2</version>
    <configuration>
      <url>....</url>
      <user>sa</user>
      <password>00</password>
    </configuration>
  </plugin>
</code>```

So probably I need to reuse property values defined in application.properties.

This <password>${spring.datasource.password}</password> doesn't work.
Also I tried

```<code> <systemProperties>
    <systemProperty>
      <name>url</name>
      <value>....</value>
    </systemProperty>
    ...
 </systemProperties>
</code>```

Neither approach is working.

答:
You can do the reverse by building a properties file from your pom file. In your properties file you'd use something like:

```<code>password=${pom.password}
</code>```

And your pom file would have something like:

```<code><password>your_db_password</password>
</code>```

Then at:

```<code>mvn clean package
</code>```

Maven will build your properties file.

Here's a simple tutorial: Add Maven Build Information ...

Body:
I would like to define database url, username, password in one place. Currently I have

application.properties with

spring.datasource.url=....
spring.datasource.username=sa
spring.datasource.password=00

And pom.xml with

  <plugin>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-maven-plugin</artifactId>
    <version>4.1.2</version>
    <configuration>
      <url>....</url>
      <user>sa</user>
      <password>00</password>
    </configuration>
  </plugin>

So probably I need to reuse property values defined in application.properties.

This <password>${spring.datasource.password}</password> doesn't work.
Also I tried

 <systemProperties>
    <systemProperty>
      <name>url</name>
      <value>....</value>
    </systemProperty>
    ...
 </systemProperties>

Neither approach is working.

Body:
You can do the reverse by building a properties file from your pom file. In your properties file you'd use something like:

password=${pom.password}

And your pom file would have something like:

<password>your_db_password</password>

Then at:

mvn clean package

Maven will build your properties file.

Here's a simple tutorial: Add Maven Build Information ...


问:
Use lines in a file as filenames for grep?
I have a file which contains filenames (and the full path to them) and I want to search for a word within all of them.
some pseudo-code to explain:

```<code>grep keyword <all files specified in files.txt>
</code>```

or

```<code>cat files.txt > grep keyword
cat files txt | grep keyword
</code>```

the problem is that I can only get grep to search the filenames, not the contents of the actual files.

答:
bash, ksh & zsh version:

```<code>grep keyword $(<files.txt)
</code>```

OwnerDisplayName: Richo

Body:
I have a file which contains filenames (and the full path to them) and I want to search for a word within all of them.
some pseudo-code to explain:

grep keyword <all files specified in files.txt>

or

cat files.txt > grep keyword
cat files txt | grep keyword

the problem is that I can only get grep to search the filenames, not the contents of the actual files.

Body:
bash, ksh & zsh version:

grep keyword $(<files.txt)


问:
How can I solve removing object that is shared among others
I have this scenario:

```<code>struct B
{
   A * ptr;
}

A * a1 = new A1;

b1.ptr = a1
b2.ptr = a1
b3.ptr = a2
</code>```

Now I delete a1 at some different place, but there are no information about b objects.  How can I automatically set:

```<code>b1.ptr = null
b2.ptr = null
</code>```

Or how is this mechanism called, so I can "google" some more info.

答:
(Edit: Accidental wrong idea removed)

Your fundamental problem seems to be ownership:

Your B struct does not own the A object ( you create it at some other point), and as such it does not know about the A object deletion.

In C++ you have the option to make use of a shared pointer:

```<code>struct B{
    std::weak_ptr<A> ptr;
}
std::shared_ptr<A> object = std::make_shared<A>();
B.ptr = object;
</code>```

In this case, the weak ptr would be used like

```<code>if(B.ptr.lock()){
    //Your code here
}
</code>```

This would prevent using the object when it is deallocated with the shared pointer going out of reference.

There is no simple way to notify the struct B that the underlying data has been deleted, as a pointer is simply just a number that stores where an object is allocated. This number has no idea what happens to the object.

Finally, a last option is making some notify() method that notifies all B objects that some A object was deleted, though this would require major reworking and is honestly not the best solution.

I hope it helped :)

Body:
I have this scenario:

struct B
{
   A * ptr;
}

A * a1 = new A1;

b1.ptr = a1
b2.ptr = a1
b3.ptr = a2

Now I delete a1 at some different place, but there are no information about b objects.  How can I automatically set:

b1.ptr = null
b2.ptr = null

Or how is this mechanism called, so I can "google" some more info.

Body:
(Edit: Accidental wrong idea removed)

Your fundamental problem seems to be ownership:

Your B struct does not own the A object ( you create it at some other point), and as such it does not know about the A object deletion.

In C++ you have the option to make use of a shared pointer:

struct B{
    std::weak_ptr<A> ptr;
}
std::shared_ptr<A> object = std::make_shared<A>();
B.ptr = object;

In this case, the weak ptr would be used like

if(B.ptr.lock()){
    //Your code here
}

This would prevent using the object when it is deallocated with the shared pointer going out of reference.

There is no simple way to notify the struct B that the underlying data has been deleted, as a pointer is simply just a number that stores where an object is allocated. This number has no idea what happens to the object.

Finally, a last option is making some notify() method that notifies all B objects that some A object was deleted, though this would require major reworking and is honestly not the best solution.

I hope it helped :)


问:
How to use receivers in Go?
There are two code samples as follows.

Sample 1:

```<code>package main

import "fmt"

type Dat struct {
    Num int
}

func (d *Dat) Fn1a(i int) {
    d.Num = i
}

func (d *Dat) Fn2a() {
    d.Num++
}

func main() {
    var d Dat
    d.Fn1a(1)
    d.Fn2a()
    fmt.Println(d)
}
</code>```

Sample 2:

```<code>package main

import "fmt"

type Dat struct {
    Num int
}

func Fn1b(i int) *Dat {
    d := &Dat{i}
    return d
}

func (d *Dat) Fn2b() *Dat {
    d.Num++
    return d
}

func main() {
    d := Fn1b(1).Fn2b()
    fmt.Println(d)
}
</code>```

Both samples output the same results.

My question is about the difference between these samples. I could notice the following difference.

Although in Sample 1, type Dat struct can be changed to type dat struct, in Sample 2, when type Dat struct is changed to type dat struct, golint shows a warning: exported func Fn1b returns unexported type *main.dat, which can be annoying to use. So in Sample 1, dat can be used directly as a struct without being public.

Are there any other differences? For example, which is better?

Thank you so much for your time and advices. And I'm sorry for my immature question.

答:
There are some different topics inside your question:

1) Exported and unexported types

If you have a function, which is exported and that function returns an unexported type this will cause to an error, when you call that function outside of your package.

So let's say that it is not allowed to make your type Dat unexported.

2) Which solution is better?

That depends on, but at all it would be sample 2. You see how much cleaner your main function is. If your struct will be more complicated you can do some stuff there. For example your struct has a parameter which is a map you need to initialize that map by using make(). In sample 1 you need to do this every time you create a new Dat type.

Normally you would call that function NewDat(). If you always use that function when creating a new Dat variable that makes your code also more flexible for changes.

Title: How to use receivers in Go?

Body:
There are two code samples as follows.

Sample 1:

package main

import "fmt"

type Dat struct {
    Num int
}

func (d *Dat) Fn1a(i int) {
    d.Num = i
}

func (d *Dat) Fn2a() {
    d.Num++
}

func main() {
    var d Dat
    d.Fn1a(1)
    d.Fn2a()
    fmt.Println(d)
}

Sample 2:

package main

import "fmt"

type Dat struct {
    Num int
}

func Fn1b(i int) *Dat {
    d := &Dat{i}
    return d
}

func (d *Dat) Fn2b() *Dat {
    d.Num++
    return d
}

func main() {
    d := Fn1b(1).Fn2b()
    fmt.Println(d)
}

Both samples output the same results.

My question is about the difference between these samples. I could notice the following difference.

Although in Sample 1, type Dat struct can be changed to type dat struct, in Sample 2, when type Dat struct is changed to type dat struct, golint shows a warning: exported func Fn1b returns unexported type *main.dat, which can be annoying to use. So in Sample 1, dat can be used directly as a struct without being public.

Are there any other differences? For example, which is better?

Thank you so much for your time and advices. And I'm sorry for my immature question.


问:
Converting a twisted consumer into a Service
I'm trying to get a twisted-based pika (RabbitMQ) consumer into a service. Here's the relevant bits of what I've put in place currently:

worker.py

```<code>import pika
from pika.adapters import twisted_connection
from twisted.internet import defer, reactor, protocol, task

@defer.inlineCallbacks
def run(connection):
    channel = yield connection.channel()
    yield channel.queue_declare(
        queue='event_queue',
        durable=True, auto_delete=False, exclusive=False
    )
    queue_object, consumer_tag = yield channel.basic_consume(
        queue='event_queue', no_ack=False
    )
    l = task.LoopingCall(process, queue_object, connection)
    l.start(0.01)

@defer.inlineCallbacks
def process(queue_object, connection):
    ch, method, properties, body = yield queue_object.get()
    if body:
         print "Do stuff here"
    yield ch.basic_ack(delivery_tag=method.delivery_tag)

def start():
    parameters = pika.ConnectionParameters()
    cc = protocol.ClientCreator(
        reactor, twisted_connection.TwistedProtocolConnection, parameters
    )
    d = cc.connectTCP(MQ_SERVER, MQ_SERVER_PORT)
    d.addCallback(lambda x: x.ready)
    d.addCallback(run)
</code>```

This worker works just fine when run using the following script :

runserver.py

```<code>import worker
from twisted.internet import reactor

if __name__ == '__main__':
    worker.start()
    reactor.run()
</code>```

I can't see to figure out how to get this to work with other Services in a .tac file.

services.tac

```<code>from twisted.application import service
application = service.Application("An application")

from other import get_service
other_service = get_service()
other_service.setServiceParent(application)

import worker
worker.start()
</code>```

This tac file doesn't work when it's run. The same code without other service seems to work, but it doesn't seem to work when there are other services enabled. Instead, it returns a timed out deferred.

Is there a way I can turn this connectTCP thing which takes deffereds into a regular service?

答:
You have to run a .tac file with twistd:

```<code>$ twistd -ny services.tac
</code>```

Body:
I'm trying to get a twisted-based pika (RabbitMQ) consumer into a service. Here's the relevant bits of what I've put in place currently:

worker.py

import pika
from pika.adapters import twisted_connection
from twisted.internet import defer, reactor, protocol, task

@defer.inlineCallbacks
def run(connection):
    channel = yield connection.channel()
    yield channel.queue_declare(
        queue='event_queue',
        durable=True, auto_delete=False, exclusive=False
    )
    queue_object, consumer_tag = yield channel.basic_consume(
        queue='event_queue', no_ack=False
    )
    l = task.LoopingCall(process, queue_object, connection)
    l.start(0.01)

@defer.inlineCallbacks
def process(queue_object, connection):
    ch, method, properties, body = yield queue_object.get()
    if body:
         print "Do stuff here"
    yield ch.basic_ack(delivery_tag=method.delivery_tag)

def start():
    parameters = pika.ConnectionParameters()
    cc = protocol.ClientCreator(
        reactor, twisted_connection.TwistedProtocolConnection, parameters
    )
    d = cc.connectTCP(MQ_SERVER, MQ_SERVER_PORT)
    d.addCallback(lambda x: x.ready)
    d.addCallback(run)

This worker works just fine when run using the following script :

runserver.py

import worker
from twisted.internet import reactor

if __name__ == '__main__':
    worker.start()
    reactor.run()

I can't see to figure out how to get this to work with other Services in a .tac file.

services.tac

from twisted.application import service
application = service.Application("An application")

from other import get_service
other_service = get_service()
other_service.setServiceParent(application)

import worker
worker.start()

This tac file doesn't work when it's run. The same code without other service seems to work, but it doesn't seem to work when there are other services enabled. Instead, it returns a timed out deferred.

Is there a way I can turn this connectTCP thing which takes deffereds into a regular service?

Body:
You have to run a .tac file with twistd:

$ twistd -ny services.tac


问:
Canvas: Simply moving a rectangle from left to right
I am very new to canvas and I am just trying to build a basic function, so a rectangle can move from left to right. It seems like I just don't understand the logic.

This is what I have so far:

```<code>var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x;

function draw() {
  ctx.beginPath();
  ctx.rect(x, 20, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + 20;
}

draw();

setInterval(draw, 1);
</code>```

https://jsfiddle.net/tj7d29fw/

Why is that code wrong and how would be the correct logic of moving a rectangle?

Any help would be appreciated!

答:
The reason it doesn't work is that you've forgotten to initialize the variable x, this means that whenever you call your draw function, you're trying to draw at a undefined x value.

See this jsfiddle: https://jsfiddle.net/tj7d29fw/4/

On a second note, I would also suggest that you use requestAnimationFrame instead of setInterval to save on system resources. See https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Note: I changed the amount at which x is increased, to make the movement easier to see.

Body:
I am very new to canvas and I am just trying to build a basic function, so a rectangle can move from left to right. It seems like I just don't understand the logic.

This is what I have so far:

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x;

function draw() {
  ctx.beginPath();
  ctx.rect(x, 20, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + 20;
}

draw();

setInterval(draw, 1);

https://jsfiddle.net/tj7d29fw/

Why is that code wrong and how would be the correct logic of moving a rectangle?

Any help would be appreciated!


问:
Ansible handler using if statements
I have an apache playbook which needs to run on centos 7 and centos 6. I want the handler triggered based on distribution major version. I have a handler called restart apache on 7 and another one restart apache on 6.

My handlers/main.yml looks like this

```<code> ---
 - name: restart apache on 7
  systemd: name=httpd state=restarted

 - name: restart apache on 6
   service: name=httpd state=restarted
</code>```

I have tried doing the following in my tasks/main.ymlbut seem to be running into syntax issues pertaining to the notify script.

```<code>- name: Copy custom configs
  copy:
   dest: /etc/httpd/conf/
   src: httpd.conf
   owner: root
  notify: {%if ansible_distribution_major_version >= '7.0' %}restart apache on 7 {%else%} restart apache on 6 {%endif%}
</code>```

Any clues on how to write the notify statement to achieve my goal?

答:
For a general solution, you can use topics, but I'm not sure why you would want to use systemd module instead of service - the latter should cover CentOS 6 and 7 without any difference.

Also use an arithmetic comparison for ansible_distribution_major_version instead of the string comparison as in your example.

Handlers listening to topics:

---
- name: restart apache on 7
  systemd: name=httpd state=restarted
  when: ansible_distribution_major_version >= 7
  listen: "restart apache"

- name: restart apache on 6
  service: name=httpd state=restarted
  when: ansible_distribution_major_version < 7
  listen: "restart apache"
```
<p>and the task notifying them:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Copy custom configs
  copy:
    dest: /etc/httpd/conf/
    src: httpd.conf
    owner: root
  notify: "restart apache"
</code>```

Title: Ansible handler using if statements

Body:
I have an apache playbook which needs to run on centos 7 and centos 6. I want the handler triggered based on distribution major version. I have a handler called restart apache on 7 and another one restart apache on 6.

My handlers/main.yml looks like this

 ---
 - name: restart apache on 7
  systemd: name=httpd state=restarted

 - name: restart apache on 6
   service: name=httpd state=restarted

I have tried doing the following in my tasks/main.ymlbut seem to be running into syntax issues pertaining to the notify script.

- name: Copy custom configs
  copy:
   dest: /etc/httpd/conf/
   src: httpd.conf
   owner: root
  notify: {%if ansible_distribution_major_version >= '7.0' %}restart apache on 7 {%else%} restart apache on 6 {%endif%}

Any clues on how to write the notify statement to achieve my goal?

Body:
For a general solution, you can use topics, but I'm not sure why you would want to use systemd module instead of service - the latter should cover CentOS 6 and 7 without any difference.

Also use an arithmetic comparison for ansible_distribution_major_version instead of the string comparison as in your example.

Handlers listening to topics:

---
- name: restart apache on 7
  systemd: name=httpd state=restarted
  when: ansible_distribution_major_version >= 7
  listen: "restart apache"

- name: restart apache on 6
  service: name=httpd state=restarted
  when: ansible_distribution_major_version < 7
  listen: "restart apache"

and the task notifying them:

- name: Copy custom configs
  copy:
    dest: /etc/httpd/conf/
    src: httpd.conf
    owner: root
  notify: "restart apache"

ContentLicense: CC BY-SA 4.0


问:
Make a div as heigh as needed
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">
    left
  </div>
  <div class="right">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

    </div>
    <div class="bottom">
      bottom right
    </div>

  </div>

  <div></code>```

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

答:
You have a height specified in px on the .top div.  take this out and your div will adjust its height to fit its content

```<code>.top {
  background-color: lightblue;
  }
</code>```

.left {
  background-color: grey;
  height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
}

.bottom {
  background-color: lightgreen;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">
    left
  </div>
  <div class="right">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

    </div>
    <div class="bottom">
      bottom right
    </div>

  </div>

  <div></code>```

Title: Make a div as heigh as needed

Body:
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}

    left

      top right
 top right
 top right
 top right
 top right
 top right
top right
top right
top right

      bottom right

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

Body:
You have a height specified in px on the .top div.  take this out and your div will adjust its height to fit its content

.top {
  background-color: lightblue;
  }

.left {
  background-color: grey;
  height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
}

.bottom {
  background-color: lightgreen;
  height: 50px;
}

<div class="wrapper">
  <div class="left">
    left
  </div>
  <div class="right">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

    </div>
    <div class="bottom">
      bottom right
    </div>

  </div>

  <div>


答:
I assumed you wanted a fixed height for your content.

The snippet I show you here as an alternative asks you to set the height only in the wrapper so it's easier to mantain, the top right div takes the height it needs and the bottom right adapts takes the remaining height from the parent

```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>    html, body{
      height: 100%;
    }
    .wrapper {
      height: 200px;
    }
    .left {
      background-color: grey;
      float: left;
      height: 100%;
    }

    .right {
      height: auto;
      float: left;
      height: 100%;
    }

    .top {
      background-color: lightblue;
      height: 166px;

    }

    .bottom {
      background-color: lightgreen;
      height: calc(100% - 166px);
    }</code>```

        left

          top right
 top right
 top right
 top right
 top right
 top right
top right
top right
top right

          bottom right

```
</div>
</div>

</code>```

Title: Make a div as heigh as needed

Body:
I assumed you wanted a fixed height for your content.

The snippet I show you here as an alternative asks you to set the height only in the wrapper so it's easier to mantain, the top right div takes the height it needs and the bottom right adapts takes the remaining height from the parent

    html, body{
      height: 100%;
    }
    .wrapper {
      height: 200px;
    }
    .left {
      background-color: grey;
      float: left;
      height: 100%;
    }

    .right {
      height: auto;
      float: left;
      height: 100%;
    }

    .top {
      background-color: lightblue;
      height: 166px;

    }

    .bottom {
      background-color: lightgreen;
      height: calc(100% - 166px);
    }

    <div class="wrapper">
      <div class="left">
        left
      </div>
      <div class="right">
        <div class="top">
          top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

        </div>
        <div class="bottom">
          bottom right
        </div>

      </div>

      <div>


问:
Laravel - diffForHumans in German
I am trying to display the created_at attribute using Carbon's diffForHumans() in German in laravel 5.2.

created_at is stored in the database as: 2017-03-29 17:31:52

The model

```<code>protected $dates = ['created_at', 'updated_at'];

public static function getCreatedAtAttribute($value)
{
    Carbon::setLocale('de');
    return Carbon::parse($value, 'Europe/Berlin')->diffForHumans();
}
</code>```

dd($value); returns "2017-03-29 17:31:52".

The view

```<code>@foreach($posts as $post)
    <small>{{ $post->getCreatedAtAttribute($post->created_at) }}</small>
@endforeach
</code>```

The error

DateTime::__construct(): Failed to parse time string (vor 3 Tagen) at
  position 0 (v): The timezone could not be found in the database

I would be very thankful for any kind of help!

答:
For a German translation I used this customization in the AppServiceProvider:

```<code>class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Localization Carbon

        \Carbon\Carbon::setLocale(config('app.locale'));
    }
}
</code>```

With this setting the data is displayed: vor 3 Tagen instead of 3 days ago.

Title: Laravel - diffForHumans in German

Body:
I am trying to display the created_at attribute using Carbon's diffForHumans() in German in laravel 5.2.

created_at is stored in the database as: 2017-03-29 17:31:52

The model

protected $dates = ['created_at', 'updated_at'];

public static function getCreatedAtAttribute($value)
{
    Carbon::setLocale('de');
    return Carbon::parse($value, 'Europe/Berlin')->diffForHumans();
}

dd($value); returns "2017-03-29 17:31:52".

The view

@foreach($posts as $post)
    {{ $post->getCreatedAtAttribute($post->created_at) }}
@endforeach

The error

DateTime::__construct(): Failed to parse time string (vor 3 Tagen) at
  position 0 (v): The timezone could not be found in the database

I would be very thankful for any kind of help!

Body:
For a German translation I used this customization in the AppServiceProvider:

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Localization Carbon

        \Carbon\Carbon::setLocale(config('app.locale'));
    }
}

With this setting the data is displayed: vor 3 Tagen instead of 3 days ago.


问:
Scheme - predicate gets null
I just build a scheme code that uses predicate and iterate over a list.

this is the code:

```<code>(define (filter para lst)
       (foldr (lambda (x y)
                (if (para x)
                    (cons x y) y)) '() lst))
</code>```

for example (filter odd? '(1 2 3)) will return '(1 3)

The lamda gets in the start '() and 3 - and make (para x) which is (odd? '()) and it works.

But if I write (odd? '()) it will print an error.

What am I missing?

答: The first parameter, x, is the current element of the list. The second one, y, is the accumulator. So on the first invocation x is 3 and y is '(). So you're not doing (odd? '()) and (cons '() 3), you're doing (odd? 3) and (cons 3 '()).

Title: Scheme - predicate gets null

Body:
I just build a scheme code that uses predicate and iterate over a list.

this is the code:

(define (filter para lst)
       (foldr (lambda (x y)
                (if (para x)
                    (cons x y) y)) '() lst))

for example (filter odd? '(1 2 3)) will return '(1 3)

The lamda gets in the start '() and 3 - and make (para x) which is (odd? '()) and it works.

But if I write (odd? '()) it will print an error.

What am I missing?


问:
NLTK is not working in docker
I want to run a nltk service in docker. However I always get the error message "'nltk' is not a package". Are you able to figure out what is going wrong? During build everything works fine, the nltk version is printed. When starting the container with docker-compose up nltk I get

$ docker-compose up nltk

```<code>Recreating nltk
Attaching to nltk
nltk          | Traceback (most recent call last):
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          | ModuleNotFoundError: No module named 'nltk.corpus'; 'nltk' is not a package
</code>```

docker-compose.yml

```<code>nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/nltk.py:/var/www/nltk.py
    environment:
      HOME: /var/www
</code>```

Dockerfile

```<code>FROM python:3.6

RUN mkdir /var/www
ENV HOME /var/www
WORKDIR /var/www
RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d $HOME/nltk_data all
RUN python -c "import nltk"
RUN python -c "import nltk; print(nltk.__version__)"

EXPOSE 80

CMD [ "python", "/var/www/nltk.py" ]
</code>```

nltk.py

```<code>import nltk
from nltk.corpus import brown

brown.words()
</code>```

答: Try renaming nltk.py to something else. I'm guessing the import nltk and from nltk.corpus is trying to import from your nltk.py file instead of the package. The reason it works when building the image is because your nltk.py file didn't exist yet, since it is mounted at runtime from the compose file.

Title: NLTK is not working in docker

Body:
I want to run a nltk service in docker. However I always get the error message "'nltk' is not a package". Are you able to figure out what is going wrong? During build everything works fine, the nltk version is printed. When starting the container with docker-compose up nltk I get

$ docker-compose up nltk

Recreating nltk
Attaching to nltk
nltk          | Traceback (most recent call last):
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          |   File "/var/www/nltk.py", line 1, in <module>
nltk          |     from nltk.corpus import brown
nltk          | ModuleNotFoundError: No module named 'nltk.corpus'; 'nltk' is not a package

docker-compose.yml

nltk:
    build: docker/nltk
    container_name: nltk
    volumes:
      - ./volumes/nltk/var/www/nltk.py:/var/www/nltk.py
    environment:
      HOME: /var/www

Dockerfile

FROM python:3.6

RUN mkdir /var/www
ENV HOME /var/www
WORKDIR /var/www
RUN pip install -U nltk
RUN pip install -U numpy
RUN python -m nltk.downloader -d $HOME/nltk_data all
RUN python -c "import nltk"
RUN python -c "import nltk; print(nltk.__version__)"

EXPOSE 80

CMD [ "python", "/var/www/nltk.py" ]

nltk.py

import nltk
from nltk.corpus import brown

brown.words()


问:
How to encrypt connection string without app.config
Assume that app.config is, for whatever reason, not an option.

How is possible to store an encrypted connection string, either in the assembly itself or another app.config like XML file?

(I don't think it matters, but this is for an COM add-in for Excel 2003.)

答:
You can use the classes in the System.Security.Cryptography namespace to
encrypt/decrypt a file. However, you run into another problem, where will
you store the key? If you store it in the assembly, the assembly can be
browsed to find the key and then someone else can use it to decrypt your
data.

do check out

http://www.codeproject.com/KB/security/encryptstrings.aspx

and

http://sharpertutorials.com/simple-string-encryption-and-decryption/


问:
How to correctly syntax a chained promise function
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

```<code>    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}
</code>```

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.

答:
You should not return defer.promise, but the result of the chained then calls, so put return here :

```<code>return defer.promise
     .then(function(){
         // etc...
</code>```

...and then you need to keep using the then method also when you treat the return value of your function:

```<code>$scope.list().then(ap_list => console.log(ap_list));
</code>```

Body:
I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

    var $q = Promise;
  $scope.list = function(scan_result) {

  return $q.resolve(scan_result)
    .then(function(scan_result) {
      // Creates an object list with bssid and signal
      const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
        }
      });
      console.log("1st Then:");
      console.log(ap_list);
      return ap_list;
    })

  .then(function(ap_list) {
  //Sort the elements Highest to Lowest Signal Level
  ap_list.sort(function(a, b) {
    return b.signal - a.signal;
  });
  console.log("2nd Then:");
  console.log(ap_list);
  return ap_list;
})

  .then(function(ap_list) {
    //Removes the elements that have signal bellow -50
    for (var i = 0; i < ap_list.length; i++) {
      if (ap_list[i].signal < -50) {
        ap_list.splice(i, 1);
      }
    }
    console.log("3rd Then:");
    console.log(ap_list);
    return ap_list;
  })

  .then(function(ap_list) {
    //From the list keep the highest 3
    //console.log(ap_list);
    console.log("4th Then:");
    console.log(ap_list.slice(0, 3));
    return ap_list.slice(0, 3);
  })
}

$scope.checkin = function() {
  var scan_result = $scope.getList();
  console.log(scan_result);
  $scope.list(scan_result)
    .then(function(result) {
      //console.log(result);
    })
}

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, definitely something is wrong here. Im not a defer guru so I kindly ask for your help.

Body:
You should not return defer.promise, but the result of the chained then calls, so put return here :

return defer.promise
     .then(function(){
         // etc...

...and then you need to keep using the then method also when you treat the return value of your function:

$scope.list().then(ap_list => console.log(ap_list));


问:
Loopback: Event resetPasswordRequest not called after reset
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

```<code>{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}
</code>```

user.json

```<code>{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}
</code>```

user.js

```<code>module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click <a href="' + url + '?access_token=' + info.accessToken.id + '">here</a>';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};
</code>```

答:
Ok, so @IvanSschwarz was right. Thank you so much! My initial code was correct, but it was missing a small change on the model-config.json: I needed to hide the User model for some reason. So I also took the opportunity and changed my model name from "user" to "member", to follow the loopback good practices guide lines.

```<code>   ...
   "User": {
     "dataSource": "mysqlDs",
     "public": false
   },
   "member": {
     "dataSource": "mysqlDs",
     "public": true,
     "options": {
       "emailVerificationRequired": true
     }
   },
   ....
</code>```

I believe that the other suggestions could potentially work as well, but I wanted to extend the User model through JSON and also leverage the built-in remote method Reset Password from the Users model. So thank you guys!

Body:
I am trying to tap into the password reset process on Loopback, so I can send an e-mail with the instructions to the user. I created a custom model called 'user' that extends 'User'. Then I added "User.on('resetPasswordRequest'...", but it never gets executed. Please check the console.log on the user.js

model-config.json

{
...

  "user": {
    "dataSource": "mysqlDs",
    "public": true,
    "options": {
      "emailVerificationRequired": false
    }
  },
...
}

user.json

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {},
  "acls": [
    {
      "principalType": "ROLE",
      "principalId": "$everyone",
      "accessType": "READ",
      "permission": "ALLOW"
    }
  ],
  "methods": []
}

user.js

module.exports = function(User) {

  console.log('It prints this log here.');

  User.on('resetPasswordRequest', function(info) {

    console.log('But it does not print this log here ever.');

    var url = 'http://www.example.com/reset-password';
    var html = 'Click here';
    loopback.Email.send({
      to: info.email,
      from: 'mail@example.com',
      subject: 'My Subject',
      html: html
    }, function() {
      console.log('> sending password reset email to:', info.email);
      if (err) return console.log('> error sending password reset email');
    });
  });

};

Body:
Ok, so @IvanSschwarz was right. Thank you so much! My initial code was correct, but it was missing a small change on the model-config.json: I needed to hide the User model for some reason. So I also took the opportunity and changed my model name from "user" to "member", to follow the loopback good practices guide lines.

   ...
   "User": {
     "dataSource": "mysqlDs",
     "public": false
   },
   "member": {
     "dataSource": "mysqlDs",
     "public": true,
     "options": {
       "emailVerificationRequired": true
     }
   },
   ....

I believe that the other suggestions could potentially work as well, but I wanted to extend the User model through JSON and also leverage the built-in remote method Reset Password from the Users model. So thank you guys!


问:
Javascript - add class to element, remove from siblings
Code is very basic (you can get the idea when you look at it, no need to explain), somehow it doesn't work... can anyone please tell me what am i doing wrong?

$("ul li").click(function() {
  $(this).addClass('cell-selected')
    .parent().siblings().find('.cell-selected').removeClass('cell-selected');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cell-selected {
  color: #fff;
  background: #5b2200;
  border-color: #ce5209;
}</code>```

First

Second

Third

```

fiddle

答:
```<code>$("ul li").click(function() {

  $(this).addClass('cell-selected')
      .siblings().removeClass('cell-selected')
});
</code>```

You are looking siblings of selected li.So,no need of  parent() and  find('.cell-selected').

Body:
Code is very basic (you can get the idea when you look at it, no need to explain), somehow it doesn't work... can anyone please tell me what am i doing wrong?

$("ul li").click(function() {
  $(this).addClass('cell-selected')
    .parent().siblings().find('.cell-selected').removeClass('cell-selected');
});

.cell-selected {
  color: #fff;
  background: #5b2200;
  border-color: #ce5209;
}

First

Second

Third

fiddle

Body:
$("ul li").click(function() {

  $(this).addClass('cell-selected')
      .siblings().removeClass('cell-selected')
});

You are looking siblings of selected li.So,no need of  parent() and  find('.cell-selected').


答:
Your code has multiple issues:

clearRect() fills the canvas with transparent pixels, which has the same effect as filling with your canvas' CSS background color, which is white per default. You need to change your CSS background color so your white rectangle becomes visible.

requestAnimationFrame() is preferred over setInterval() for visual animations as it adapts to your browser's and screen's refresh rate. Use the time stamp it supplies to your callback to synchronize your drawings.

closePath() is not needed when drawing a rectangle, as it is already a closed shape.

You need to initialize x to a Number, otherwise it is undefined which evaluates to `NaN´ when incrementing.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    last = performance.now();

function draw(timestamp) {
  requestAnimationFrame(draw);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.rect(x, 20, 20, 20);
  ctx.fillStyle = "#ffffff";
  ctx.fill();

  x += (timestamp - last) / 10;
  last = timestamp;
}
requestAnimationFrame(draw);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background-color: black;
}</code>```

<canvas id='canvas'>```

Title: Canvas: Simply moving a rectangle from left to right

Body:
Your code has multiple issues:

clearRect() fills the canvas with transparent pixels, which has the same effect as filling with your canvas' CSS background color, which is white per default. You need to change your CSS background color so your white rectangle becomes visible.

requestAnimationFrame() is preferred over setInterval() for visual animations as it adapts to your browser's and screen's refresh rate. Use the time stamp it supplies to your callback to synchronize your drawings.

closePath() is not needed when drawing a rectangle, as it is already a closed shape.

You need to initialize x to a Number, otherwise it is undefined which evaluates to `NaN´ when incrementing.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    last = performance.now();

function draw(timestamp) {
  requestAnimationFrame(draw);

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.rect(x, 20, 20, 20);
  ctx.fillStyle = "#ffffff";
  ctx.fill();

  x += (timestamp - last) / 10;
  last = timestamp;
}
requestAnimationFrame(draw);

#canvas {
  background-color: black;
}

<canvas id='canvas'>


问:
How does template return type function work in C++?
In following example :

```<code>template<typename T>
T Get()
{
    T t = 10;
    return t;
}

int main()
{
    int i = Get<int>(); // will work
    float f = Get<float>(); // will work
}
</code>```

Function overloading doesn't work with just different return type.
So, what will the compiler end up generating in this case ?

答:
When you call the function via Get<int> or Get<double>, the compiler does not need to deduce the return type. The code T t = 10 will perform a casting operation to type T. This is more clear if 10 is replaced with a non-integer like 1.5:

```<code>template<typename T>
T Get()
{
    T t = 1.5;
    return t;
}

main()
{
    int i = Get<int>(); // returns 1
    double f = Get<double>(); // returns 1.5
}
</code>```

However, with some compilers this code does generate the warning

```<code>warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [-Wliteral-conversion]
</code>```

in which case T t = static_cast<T>(1.5); might be a better choice.

Body:
In following example :

template<typename T>
T Get()
{
    T t = 10;
    return t;
}

int main()
{
    int i = Get<int>(); // will work
    float f = Get<float>(); // will work
}

Function overloading doesn't work with just different return type.
So, what will the compiler end up generating in this case ?

Body:
When you call the function via Get<int> or Get<double>, the compiler does not need to deduce the return type. The code T t = 10 will perform a casting operation to type T. This is more clear if 10 is replaced with a non-integer like 1.5:

template<typename T>
T Get()
{
    T t = 1.5;
    return t;
}

main()
{
    int i = Get<int>(); // returns 1
    double f = Get<double>(); // returns 1.5
}

However, with some compilers this code does generate the warning

warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [-Wliteral-conversion]

in which case T t = static_cast<T>(1.5); might be a better choice.


答:
You can try with it:   </p>

```<code> $("ul li").click(function() {
        $(this).addClass('cell-selected').siblings().removeClass('cell-selected');
 });
</code>```

Title: Javascript - add class to element, remove from siblings

Body:
You can try with it:

 $("ul li").click(function() {
        $(this).addClass('cell-selected').siblings().removeClass('cell-selected');
 });


问:
Python - add one dictionary to another
I want to update one dictionary with another in Python, but if there are some same arguments, their values should be added.
For example:

```<code>a = {"word_1" : 1, "word_2": 2}
b = {"word_2" : 5, "word_3": 7}
</code>```

Output must be:

```<code>{"word_1" : 1, "word_2": 7, "word_3": 7}
</code>```

I have googled a lot, but in most answers values rewrites, I want to add them
Here is my solution:

```<code>    for i in a.keys():
        if i in b.keys():
            b[i] += a[i]
        else:
            b[i] = a[i]
</code>```

Is there most efficient way to do it?

答:
How about:</p>

```<code>{k: a.get(k, 0) + b.get(k, 0) for k in set(list(a.keys()) + list(b.keys()))}
</code>```

Title: Python - add one dictionary to another

Body:
I want to update one dictionary with another in Python, but if there are some same arguments, their values should be added.
For example:

a = {"word_1" : 1, "word_2": 2}
b = {"word_2" : 5, "word_3": 7}

Output must be:

{"word_1" : 1, "word_2": 7, "word_3": 7}

I have googled a lot, but in most answers values rewrites, I want to add them
Here is my solution:

    for i in a.keys():
        if i in b.keys():
            b[i] += a[i]
        else:
            b[i] = a[i]

Is there most efficient way to do it?

Body:
How about:

{k: a.get(k, 0) + b.get(k, 0) for k in set(list(a.keys()) + list(b.keys()))}


问:
onAccessibilityEvent not called at all
I am trying to implement an AccessibilityService. I have shared my code below.
When I turn on my accessibility service from settings menu then onServiceConnected() is called but onAccessibiltyEvent() is not called at all. Please guide me on this.

Service Declaration in manifest file.

```<code><service
            android:name=".MyAccessibilityService"
            android:enabled="true"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService" />
            </intent-filter>

            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/accessibility_service_config" />
</service>
</code>```

XML file

```<code><accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:accessibilityEventTypes="typeAllMask"
    android:canRequestFilterKeyEvents="true"
    android:accessibilityFlags="flagDefault"

    android:notificationTimeout="100"
    android:canRetrieveWindowContent="true"
    />
</code>```

MyAccessibiltyService.java

```<code>public class MyAccessibilityService extends AccessibilityService {

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG,"Service Connected");

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        System.out.println("Event Occurred");
        Log.d(TAG, "onAccessibilityEvent: event=" + event);
        AccessibilityNodeInfo nodeInfo = event.getSource();
        if (null == nodeInfo) return;

    }

    @Override
    public void onInterrupt() {
        Log.d(TAG,"Accessibility Interrupted" );

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"Service Destroyed");
    }
}
</code>```

Please note that I have already checked all stackoverflow answers hence do not mark this as duplicate.

答:
I needed to add a feedback type to the accessibility_service_config file to make it work.

Try to add this

```<code>android:accessibilityFeedbackType="feedbackAllMask"
</code>```

Tested on a Nexus 6P with Android 7.1.2

Title: onAccessibilityEvent not called at all

Body:
I am trying to implement an AccessibilityService. I have shared my code below.
When I turn on my accessibility service from settings menu then onServiceConnected() is called but onAccessibiltyEvent() is not called at all. Please guide me on this.

Service Declaration in manifest file.

<service
            android:name=".MyAccessibilityService"
            android:enabled="true"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService" />
            </intent-filter>

            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/accessibility_service_config" />
</service>

XML file

<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:accessibilityEventTypes="typeAllMask"
    android:canRequestFilterKeyEvents="true"
    android:accessibilityFlags="flagDefault"

    android:notificationTimeout="100"
    android:canRetrieveWindowContent="true"
    />

MyAccessibiltyService.java

public class MyAccessibilityService extends AccessibilityService {

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG,"Service Connected");

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        System.out.println("Event Occurred");
        Log.d(TAG, "onAccessibilityEvent: event=" + event);
        AccessibilityNodeInfo nodeInfo = event.getSource();
        if (null == nodeInfo) return;

    }

    @Override
    public void onInterrupt() {
        Log.d(TAG,"Accessibility Interrupted" );

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"Service Destroyed");
    }
}

Please note that I have already checked all stackoverflow answers hence do not mark this as duplicate.

Body:
I needed to add a feedback type to the accessibility_service_config file to make it work.

Try to add this

android:accessibilityFeedbackType="feedbackAllMask"

Tested on a Nexus 6P with Android 7.1.2


问:
Set dynamic validation criteria on HTML elements based on predefined configuration
I got an employee html form with several input tags.

the problem is some input tags had dynamic validation criteria based on current user logged to the system.
for example:
user 1 : consider ssn as mandatory field with 14 character
user 2 : consider ssn as mandatory field with 10 character.

I get the criteria from DB.
I succeeded to implement required like this:

```<code>   var screenConfig = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.ScreenConfig));
   $(document).ready(function () {
    _.each(screenConfig, function(value, key) {
            if (value.IsRequired == true) {
                $("#"+value.ElementId).attr("required", "required");
                $("#"+value.ElementId).addClass("required-input");
            }

    });});
</code>```

But I got stuck with text input length, I can't think of something other than sending script from server to handle each element separately.
Can it be done other way efficiently??

答:
Based on @Avitus Suggestion:
That's what I made to make dynamic validation on HTML elements based on predefined configuration:
1. I created two tables in DB ScreenElement, ScreenSettings:

```<code>    CREATE TABLE [HR].[ScreenElement](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ElementId] [nvarchar](50) NULL,
    [ElementName] [nvarchar](50) NULL,
    [ScreenId] [int] NULL,
    [IsRequired] [bit] NULL,
    [MinLength] [int] NULL,
    [MaxLength] [int] NULL,
    CONSTRAINT [PK_ScreenElement] PRIMARY KEY CLUSTERED (
    [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [HR].[ScreenSettings](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [NameA] [nvarchar](50) NULL,
    [NameL] [varchar](50) NULL,
    [ScreenKey] [varchar](150) NULL,
 CONSTRAINT [PK_ScreenSettings] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

2.I get configuration by screen keyword that's ControllerName.ActionName and pass it in a ViewBag when the screen loads I serialize it to js object.
3.When document ready.I mark the elements with data-x attributes and some styling classes.

```<code>var screenConfig = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.ScreenConfig));

$(document).ready(function () {
    _.each(screenConfig, function(value, key) {
            if (value.IsRequired == true) {
                $("#"+value.ElementId).attr("required", "required");
                $("#"+value.ElementId).addClass("required-input");
            }
            if (value.MinLength !== 0 && value.MaxLength !== 0&&value.MaxLength>=value.MinLength) {
                $("#"+value.ElementId).attr("data-min", value.MinLength.toString());
                $("#"+value.ElementId).attr("data-max", value.MaxLength.toString());
                if (value.MinLength === value.MaxLength) {
                    $("#"+value.ElementId).attr("data-length", value.MinLength.toString());
                }

            }

    });});
</code>```

That's It.

Body:
I got an employee html form with several input tags.

the problem is some input tags had dynamic validation criteria based on current user logged to the system.
for example:
user 1 : consider ssn as mandatory field with 14 character
user 2 : consider ssn as mandatory field with 10 character.

I get the criteria from DB.
I succeeded to implement required like this:

   var screenConfig = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.ScreenConfig));
   $(document).ready(function () {
    _.each(screenConfig, function(value, key) {
            if (value.IsRequired == true) {
                $("#"+value.ElementId).attr("required", "required");
                $("#"+value.ElementId).addClass("required-input");
            }

    });});

But I got stuck with text input length, I can't think of something other than sending script from server to handle each element separately.
Can it be done other way efficiently??

Body:
Based on @Avitus Suggestion:
That's what I made to make dynamic validation on HTML elements based on predefined configuration:
1. I created two tables in DB ScreenElement, ScreenSettings:

    CREATE TABLE [HR].[ScreenElement](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ElementId] [nvarchar](50) NULL,
    [ElementName] [nvarchar](50) NULL,
    [ScreenId] [int] NULL,
    [IsRequired] [bit] NULL,
    [MinLength] [int] NULL,
    [MaxLength] [int] NULL,
    CONSTRAINT [PK_ScreenElement] PRIMARY KEY CLUSTERED (
    [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE TABLE [HR].[ScreenSettings](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [NameA] [nvarchar](50) NULL,
    [NameL] [varchar](50) NULL,
    [ScreenKey] [varchar](150) NULL,
 CONSTRAINT [PK_ScreenSettings] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

2.I get configuration by screen keyword that's ControllerName.ActionName and pass it in a ViewBag when the screen loads I serialize it to js object.
3.When document ready.I mark the elements with data-x attributes and some styling classes.

var screenConfig = @Html.Raw(new JavaScriptSerializer().Serialize(ViewBag.ScreenConfig));

$(document).ready(function () {
    _.each(screenConfig, function(value, key) {
            if (value.IsRequired == true) {
                $("#"+value.ElementId).attr("required", "required");
                $("#"+value.ElementId).addClass("required-input");
            }
            if (value.MinLength !== 0 && value.MaxLength !== 0&&value.MaxLength>=value.MinLength) {
                $("#"+value.ElementId).attr("data-min", value.MinLength.toString());
                $("#"+value.ElementId).attr("data-max", value.MaxLength.toString());
                if (value.MinLength === value.MaxLength) {
                    $("#"+value.ElementId).attr("data-length", value.MinLength.toString());
                }

            }

    });});

That's It.


问:
How to prevent that the password to decrypt the private key has to be entered every time when using Git Bash on Windows?
I've an automatic building service which download from a git private repository.
The problem is that when it tries to clone repository it need to provide the password, because it is not remembered; so because there is no human interaction, it waits forever the password.
How can I force it to remember from id_rsa.pub?</p>

答:
When I tried to push my code, I got the below error:

```<code>$ git push origin dev

remote: Too many invalid password attempts. Try logging in through the website with your password.
fatal: unable to access 'https://naushadqamar-1@bitbucket.org/xxxx/xxxx-api.git/': The requested URL returned error: 403
</code>```

After a few hours of research, I found I need to use the below command:

```<code>$ git config --global credential.helper cache
</code>```

After executing the above command, I got the prompt for entering my GitHub username and password. After providing the correct credentials, I am able to push my code.

Body:
When I tried to push my code, I got the below error:

$ git push origin dev

remote: Too many invalid password attempts. Try logging in through the website with your password.
fatal: unable to access 'https://naushadqamar-1@bitbucket.org/xxxx/xxxx-api.git/': The requested URL returned error: 403

After a few hours of research, I found I need to use the below command:

$ git config --global credential.helper cache

After executing the above command, I got the prompt for entering my GitHub username and password. After providing the correct credentials, I am able to push my code.


问:
Eigen - Balancing matrix for eigenvalue
My experience (like some others: How do I get specified Eigenvectors from the generalized Schur factorization of a matrix pair using LAPACK?) is that the eigenvalues obtained from Eigen (I don't care about the eigenvectors) are not nearly as reliable as those obtained from numpy, matlab, etc. when the matrix is ill-conditioned.

The internet (https://www.mathworks.com/help/matlab/ref/balance.html) suggests that balancing is the solution, but I can't figure out how to do this in Eigen.  Can anyone help?

At the moment I have an annoying two-layer solution that involves python and C++ and I would like to push everything into C++; the eigenvalue solver is the only part that is holding me back.

答:
As it turns out, this fantastic little paper on arxiv gives a nice clear description of balancing: https://arxiv.org/pdf/1401.5766.pdf.  When I implement this balancing, the eigenvalues agree almost perfectly with numpy.  It would be great if Eigen would balance the matrix prior to taking eigenvalues.</p>

```<code>void balance_matrix(const Eigen::MatrixXd &A, Eigen::MatrixXd &Aprime, Eigen::MatrixXd &D) {
    // https://arxiv.org/pdf/1401.5766.pdf (Algorithm #3)
    const int p = 2;
    double beta = 2; // Radix base (2?)
    Aprime = A;
    D = Eigen::MatrixXd::Identity(A.rows(), A.cols());
    bool converged = false;
    do {
        converged = true;
        for (Eigen::Index i = 0; i < A.rows(); ++i) {
            double c = Aprime.col(i).lpNorm<p>();
            double r = Aprime.row(i).lpNorm<p>();
            double s = pow(c, p) + pow(r, p);
            double f = 1;
            while (c < r / beta) {
                c *= beta;
                r /= beta;
                f *= beta;
            }
            while (c >= r*beta) {
                c /= beta;
                r *= beta;
                f /= beta;
            }
            if (pow(c, p) + pow(r, p) < 0.95*s) {
                converged = false;
                D(i, i) *= f;
                Aprime.col(i) *= f;
                Aprime.row(i) /= f;
            }
        }
    } while (!converged);
}
</code>```

Title: Eigen - Balancing matrix for eigenvalue

Body:
As it turns out, this fantastic little paper on arxiv gives a nice clear description of balancing: https://arxiv.org/pdf/1401.5766.pdf.  When I implement this balancing, the eigenvalues agree almost perfectly with numpy.  It would be great if Eigen would balance the matrix prior to taking eigenvalues.

void balance_matrix(const Eigen::MatrixXd &A, Eigen::MatrixXd &Aprime, Eigen::MatrixXd &D) {
    // https://arxiv.org/pdf/1401.5766.pdf (Algorithm #3)
    const int p = 2;
    double beta = 2; // Radix base (2?)
    Aprime = A;
    D = Eigen::MatrixXd::Identity(A.rows(), A.cols());
    bool converged = false;
    do {
        converged = true;
        for (Eigen::Index i = 0; i < A.rows(); ++i) {
            double c = Aprime.col(i).lpNorm<p>();
            double r = Aprime.row(i).lpNorm<p>();
            double s = pow(c, p) + pow(r, p);
            double f = 1;
            while (c < r / beta) {
                c *= beta;
                r /= beta;
                f *= beta;
            }
            while (c >= r*beta) {
                c /= beta;
                r *= beta;
                f /= beta;
            }
            if (pow(c, p) + pow(r, p) < 0.95*s) {
                converged = false;
                D(i, i) *= f;
                Aprime.col(i) *= f;
                Aprime.row(i) /= f;
            }
        }
    } while (!converged);
}


问:
SQL join mapping table and get back columns not rows
since 2 days I'm trying to find a solution...

I have two tables:

-- components -- colums:
id | name | description

-- components_ingredients -- colums:
component_id | ingredient_id

=> one component can have multiple ingredients

so when I join the tables with my statement:

SELECT * FROM components c
  INNER JOIN components_ingredients ci ON c.id = ci.component_id

I get back one row for every ingredient in table ci. But I want to get back only one row with the matched ingredients as additional columns like:

c.id | c.name | c.description | ci.ingredient1 | ci.ingredient2 | ci.ingredient3 ...

Is this possible and when how??

Thanks

答:
You can try using MySQL's GROUP_CONCAT() function to create a CSV list of the ingredients for each given component.

```<code>SELECT c.id, c.name, c.description, ci.ingredients
FROM components c
INNER JOIN
(
    SELECT component_id, GROUP_CONCAT(ingredient_id) AS ingredients
    FROM components_ingredients
    GROUP BY component_id
) ci
    ON c.id = ci.component_id
</code>```

Note that as @Gordon pointed out, you might be able to do without the subquery I used, but in general you might need it.  The reason Gordon's query works, even according to the ANSI standard, is a given id in the components table should uniquely determine the name and description.  Hence, it is OK to include those columns while using GROUP BY, because there is no ambiguity involved.

Body:
You can try using MySQL's GROUP_CONCAT() function to create a CSV list of the ingredients for each given component.

SELECT c.id, c.name, c.description, ci.ingredients
FROM components c
INNER JOIN
(
    SELECT component_id, GROUP_CONCAT(ingredient_id) AS ingredients
    FROM components_ingredients
    GROUP BY component_id
) ci
    ON c.id = ci.component_id

Note that as @Gordon pointed out, you might be able to do without the subquery I used, but in general you might need it.  The reason Gordon's query works, even according to the ANSI standard, is a given id in the components table should uniquely determine the name and description.  Hence, it is OK to include those columns while using GROUP BY, because there is no ambiguity involved.


答:
It is hard to put the ingredients in separate columns, because you don't now how many there are.

Much easier is to concatenate them together into a string in one column:

```<code>SELECT c.*, GROUP_CONCAT(ci.component_id) as component_ids
FROM components c INNER JOIN
     components_ingredients ci
     ON c.id = ci.component_id
GROUP BY c.id;
</code>```

Note:  It is generally bad practice to include columns in the SELECT that are not in the GROUP BY.  However, it is okay in this case, because components.id uniquely identifies each row.  This functionality is even specified as okay in the ANSI standard -- although few databases actually implement it.

Title: SQL join mapping table and get back columns not rows

Body:
since 2 days I'm trying to find a solution...

I have two tables:

-- components -- colums:
id | name | description

-- components_ingredients -- colums:
component_id | ingredient_id

=> one component can have multiple ingredients

so when I join the tables with my statement:

SELECT * FROM components c
  INNER JOIN components_ingredients ci ON c.id = ci.component_id

I get back one row for every ingredient in table ci. But I want to get back only one row with the matched ingredients as additional columns like:

c.id | c.name | c.description | ci.ingredient1 | ci.ingredient2 | ci.ingredient3 ...

Is this possible and when how??

Thanks

Body:
It is hard to put the ingredients in separate columns, because you don't now how many there are.

Much easier is to concatenate them together into a string in one column:

SELECT c.*, GROUP_CONCAT(ci.component_id) as component_ids
FROM components c INNER JOIN
     components_ingredients ci
     ON c.id = ci.component_id
GROUP BY c.id;

Note:  It is generally bad practice to include columns in the SELECT that are not in the GROUP BY.  However, it is okay in this case, because components.id uniquely identifies each row.  This functionality is even specified as okay in the ANSI standard -- although few databases actually implement it.


问:
™ character not properly translated by GetStringChars()
I noticed that the trademark character ™ doesn't seems to be translated properly by JNI's GetStringChars() function in Java 8, which is supposed to translate Unicode characters.  I have the same problem with the GetStringUTFChars() method.

This is not a big issue, as there are easy workarounds (remove Unicode characters from the string before calling the JNI function).

But as I haven't found similar problems while Googling, I came here to see if anyone has an explanation about this? (Or maybe I'm missing something in my code ?)

I'm using Java 8 and g++ 4.8 under MinGW.

Here are my code snippets :

```<code>JNIEXPORT void JNICALL Java_MyClass_JNI_myMethod (JNIEnv * env , jobject obj, jstring input_string)
{
    const jchar *inp_string = (*env).GetStringChars(input_string, NULL);
    const jchar *jch_inp_string = inp_string;
    (*env).ReleaseStringChars(input_string, inp_string);

    std::cout << jch_inp_string <<'\n';
}
</code>```

As an example, with this function, if I input this string:

```<code>Random String™
</code>```

it outputs this:

```<code>Random Stringâ„¢
</code>```

答:
I found a workaround after a deep dive in docs, it is because java support only UTF8 modified, that means it's good enough to print an XML doc, but not to print latin-1 encoded characters without errors.

To do so i called back java from c++ and made him convert his utf8 modified chars to an encoding matching my needs.
Thought i wonder if there are easiest way to do so, i find quite weird that JNI natively gives strings not fully matching a very common standard.

```<code>JNIEXPORT void JNICALL Java_MyClass_JNI_myMethod (JNIEnv * env , jobject obj, jstring input_string){

    //this calls back JNI to reformat the string form java UTF8 modified encoding to something more common
    const jclass stringClass = env->GetObjectClass(input_string);
    const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
    const jstring charsetName = env->NewStringUTF("windows-1252");
    const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(input_string, getBytes, charsetName);
    env->DeleteLocalRef(charsetName);
    const jsize length = env->GetArrayLength(stringJbytes);
    const jbyte* strBytes = env->GetByteArrayElements(stringJbytes, NULL);

    //this make sure our string is C/C++ compliant with null character
    //but it seems to work well without too
    char* my_string = malloc(length+1);
    memcpy( my_string , strBytes, length);
    my_string [length] = '\0';

    env->ReleaseByteArrayElements(stringJbytes, strBytes , JNI_ABORT);
    env->DeleteLocalRef(stringJbytes);

    std::cout << my_string << std::endl;

}
</code>```

Body:
I noticed that the trademark character ™ doesn't seems to be translated properly by JNI's GetStringChars() function in Java 8, which is supposed to translate Unicode characters.  I have the same problem with the GetStringUTFChars() method.

This is not a big issue, as there are easy workarounds (remove Unicode characters from the string before calling the JNI function).

But as I haven't found similar problems while Googling, I came here to see if anyone has an explanation about this? (Or maybe I'm missing something in my code ?)

I'm using Java 8 and g++ 4.8 under MinGW.

Here are my code snippets :

JNIEXPORT void JNICALL Java_MyClass_JNI_myMethod (JNIEnv * env , jobject obj, jstring input_string)
{
    const jchar *inp_string = (*env).GetStringChars(input_string, NULL);
    const jchar *jch_inp_string = inp_string;
    (*env).ReleaseStringChars(input_string, inp_string);

    std::cout << jch_inp_string <<'\n';
}

As an example, with this function, if I input this string:

Random String™

it outputs this:

Random Stringâ„¢

Body:
I found a workaround after a deep dive in docs, it is because java support only UTF8 modified, that means it's good enough to print an XML doc, but not to print latin-1 encoded characters without errors.

To do so i called back java from c++ and made him convert his utf8 modified chars to an encoding matching my needs.
Thought i wonder if there are easiest way to do so, i find quite weird that JNI natively gives strings not fully matching a very common standard.

JNIEXPORT void JNICALL Java_MyClass_JNI_myMethod (JNIEnv * env , jobject obj, jstring input_string){

    //this calls back JNI to reformat the string form java UTF8 modified encoding to something more common
    const jclass stringClass = env->GetObjectClass(input_string);
    const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
    const jstring charsetName = env->NewStringUTF("windows-1252");
    const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(input_string, getBytes, charsetName);
    env->DeleteLocalRef(charsetName);
    const jsize length = env->GetArrayLength(stringJbytes);
    const jbyte* strBytes = env->GetByteArrayElements(stringJbytes, NULL);

    //this make sure our string is C/C++ compliant with null character
    //but it seems to work well without too
    char* my_string = malloc(length+1);
    memcpy( my_string , strBytes, length);
    my_string [length] = '\0';

    env->ReleaseByteArrayElements(stringJbytes, strBytes , JNI_ABORT);
    env->DeleteLocalRef(stringJbytes);

    std::cout << my_string << std::endl;

}


问:
UWP[Xaml] How to access elements inside Button
How to change txtPIN.Text value in C# code behind after UserControl was initialized.

Here is XAML

```<code><Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="Change PIN" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>
</code>```

and C#

```<code>public MyUserControl()
    {
        this.InitializeComponent();
        this.btn_pin.??????????
    }
</code>```

答:
You're not doing it the right way, just fix your xaml (I changed the Text binding of your TextBlock):

```<code><Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="{TemplateBinding Content}" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>
</code>```

and every time you want to change the text, change the Content of the button like this:

```<code>    public MainPage()
    {
        this.InitializeComponent();
        btn_pin.Content = "New label";
    }
</code>```

Body:
How to change txtPIN.Text value in C# code behind after UserControl was initialized.

Here is XAML

<Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="Change PIN" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>

and C#

public MyUserControl()
    {
        this.InitializeComponent();
        this.btn_pin.??????????
    }

Body:
You're not doing it the right way, just fix your xaml (I changed the Text binding of your TextBlock):

<Button x:Name="btn_pin" Content="Change PIN" Click="button_Click" Foreground="White">
            <Button.Template>
                <ControlTemplate TargetType="Button">
                    <StackPanel  Orientation="Horizontal" VerticalAlignment="Center">
                        <Image Source="/Assets/images/settings/lock.png" Stretch="UniformToFill" Width="16" Height="16"/>
                        <TextBlock x:Name="txtPin" Text="{TemplateBinding Content}" Foreground="White" />
                    </StackPanel>
                </ControlTemplate>
            </Button.Template>
        </Button>

and every time you want to change the text, change the Content of the button like this:

    public MainPage()
    {
        this.InitializeComponent();
        btn_pin.Content = "New label";
    }


问:
Example of AudioStreamBasicDescription for 16hz, 16bit mono format as WAV file
I'm having trouble with creating a description for the above format and have tried a number of things but keep getting an invalid param when trying to record.

Does anyone have an example of how to create to this format?

```<code>var audioFileOutputDescription : AudioStreamBasicDescription = AEAudioStreamBasicDescriptionNonInterleaved16BitStereo

    audioFileOutputDescription.mFormatID = kAudioFormatLinearPCM
    audioFileOutputDescription.mSampleRate = 16000.0
    audioFileOutputDescription.mBitsPerChannel = 16
    audioFileOutputDescription.mChannelsPerFrame = 1
    audioFileOutputDescription.mFramesPerPacket = 1
    audioFileOutputDescription.mFormatFlags = kAudioFormatFlagIsSignedInteger |
        kAudioFormatFlagsNativeEndian
</code>```

Thanks.

答:
Works fine for me:</p>

```<code>fmt.mFormatID         = kAudioFormatLinearPCM; // 2
fmt.mSampleRate       = 8000.0;               // 3
fmt.mChannelsPerFrame = 1;                     // 4
fmt.mBitsPerChannel   = 16;                    // 5
fmt.mChannelsPerFrame = 1;
fmt.mFramesPerPacket  = 1;
fmt.mBytesPerFrame = 2;
fmt.mBytesPerPacket = 2;
// 7

fmt.mFormatFlags =                             // 9
kLinearPCMFormatFlagIsBigEndian
| kLinearPCMFormatFlagIsSignedInteger
| kLinearPCMFormatFlagIsPacked;
</code>```

Body:
I'm having trouble with creating a description for the above format and have tried a number of things but keep getting an invalid param when trying to record.

Does anyone have an example of how to create to this format?

var audioFileOutputDescription : AudioStreamBasicDescription = AEAudioStreamBasicDescriptionNonInterleaved16BitStereo

    audioFileOutputDescription.mFormatID = kAudioFormatLinearPCM
    audioFileOutputDescription.mSampleRate = 16000.0
    audioFileOutputDescription.mBitsPerChannel = 16
    audioFileOutputDescription.mChannelsPerFrame = 1
    audioFileOutputDescription.mFramesPerPacket = 1
    audioFileOutputDescription.mFormatFlags = kAudioFormatFlagIsSignedInteger |
        kAudioFormatFlagsNativeEndian

Thanks.

Body:
Works fine for me:

fmt.mFormatID         = kAudioFormatLinearPCM; // 2
fmt.mSampleRate       = 8000.0;               // 3
fmt.mChannelsPerFrame = 1;                     // 4
fmt.mBitsPerChannel   = 16;                    // 5
fmt.mChannelsPerFrame = 1;
fmt.mFramesPerPacket  = 1;
fmt.mBytesPerFrame = 2;
fmt.mBytesPerPacket = 2;
// 7

fmt.mFormatFlags =                             // 9
kLinearPCMFormatFlagIsBigEndian
| kLinearPCMFormatFlagIsSignedInteger
| kLinearPCMFormatFlagIsPacked;


问:
Firebase observer during all the app life
I'm trying to create a firebase observer that remains alive during all the app life. What I want is to change a property of my tabBarController when some data change in firebase. Here's my code:

```<code>self.ref.child("mySubRef").observe(.value , with: {snapshot in

        self.tabBarController?.tabBar.items?[3].badgeValue = "!"

    })
</code>```

So, I've tried creating it in the viewDidLoad of my first viewController and also in the viewDidAppear. I don't remove it since I want it to be there always. In the viewDidAppear it works only if I'm in that viewController at the moment of the change. If I want that change to happen no matter where  I am (always inside the tabBar) where do I have to put that code?

Thanks for the help!

答:
I have found the answer. The problem was that when I changed between viewControllers the reference to the observer was deallocated. So, to fix it, I have created a class like this:

```<code>class NotificationListener: NSObject {

let ref:FIRDatabaseReference = FIRDatabase.database().reference()
var user:User?

func setUpListener(tabBarController:UITabBarController){

    self.user = User()
    self.ref.child("users/" + self.user!.uid + "/notifications").observe(.value , with: {snapshot in

        tabBarController.tabBar.items?[3].badgeValue = "!"

    })

}

}
</code>```

Now I have a property of that class in every viewController and every one has a reference to the same object. When I change between VC it will not deallocate the object because it will still be referenced.

Body:
I'm trying to create a firebase observer that remains alive during all the app life. What I want is to change a property of my tabBarController when some data change in firebase. Here's my code:

self.ref.child("mySubRef").observe(.value , with: {snapshot in

        self.tabBarController?.tabBar.items?[3].badgeValue = "!"

    })

So, I've tried creating it in the viewDidLoad of my first viewController and also in the viewDidAppear. I don't remove it since I want it to be there always. In the viewDidAppear it works only if I'm in that viewController at the moment of the change. If I want that change to happen no matter where  I am (always inside the tabBar) where do I have to put that code?

Thanks for the help!

Body:
I have found the answer. The problem was that when I changed between viewControllers the reference to the observer was deallocated. So, to fix it, I have created a class like this:

class NotificationListener: NSObject {

let ref:FIRDatabaseReference = FIRDatabase.database().reference()
var user:User?

func setUpListener(tabBarController:UITabBarController){

    self.user = User()
    self.ref.child("users/" + self.user!.uid + "/notifications").observe(.value , with: {snapshot in

        tabBarController.tabBar.items?[3].badgeValue = "!"

    })

}

}

Now I have a property of that class in every viewController and every one has a reference to the same object. When I change between VC it will not deallocate the object because it will still be referenced.