问:
How do I set adaptive multiline UILabel text?
I have a UILabel named titleLabel in my storyboard nib set to its default height. I want it to programatically expand in height to fit it's content. Here is what I have tried so far:

```<code>// just setting content
titleLabel.text = "You don't always know what you are getting with mass-market cloud computing services. But with SimpliCompute, the picture is clear. SimpliCompute gives you powerful virtual servers you can deploy using just your web browser. That’s enterprise grade technology you can deploy and control on-the-fly."

titleLabel.numberOfLines = 0

titleLabel.preferredMaxLayoutWidth = 700

titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

titleLabel.sizeToFit()
</code>```

None of this works for me in any combination! I always only see one line of text in my UILabel. What am I doing wrong?

I absolutely need the text content to be variable.

答:
Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

```<code>label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()
</code>```

If setting frame.width dynamically using UIScreen:

```<code>extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}
</code>```

Body:
I have a UILabel named titleLabel in my storyboard nib set to its default height. I want it to programatically expand in height to fit it's content. Here is what I have tried so far:

// just setting content
titleLabel.text = "You don't always know what you are getting with mass-market cloud computing services. But with SimpliCompute, the picture is clear. SimpliCompute gives you powerful virtual servers you can deploy using just your web browser. That’s enterprise grade technology you can deploy and control on-the-fly."

titleLabel.numberOfLines = 0

titleLabel.preferredMaxLayoutWidth = 700

titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

titleLabel.sizeToFit()

None of this works for me in any combination! I always only see one line of text in my UILabel. What am I doing wrong?

I absolutely need the text content to be variable.

Body:
Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}


来源: stackexchange

问:
Python Print parameter end
How to remove the last "add -->" from the output when using end, i am not using sep here, bcoz sep will not have any effect here , as the print statement prints just 1 item at a time here and ends with incr of i

```<code>def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end=' add -> ')
</code>```

my output

```<code>0 add -> 1 add -> 1 add -> 2 add -> 3 add -> 5 add -> 8 add -> 13 add -> 21 add -> 34 add ->
</code>```

答:
Here I've simplified answer using ternary operator. May it will be helpful and better.

```<code>def fib(n):
    a, b = 0, 1
    while a < n:
        endstatement = '-' if (b < n) else ''
        print(a, end=endstatement)
        a, b = b, a+b
    print()

# Now call the function:
fib(1000)
</code>```

Result:
  0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987

ContentLicense: CC BY-SA 3.0

Title: Python Print parameter end

Body:
How to remove the last "add -->" from the output when using end, i am not using sep here, bcoz sep will not have any effect here , as the print statement prints just 1 item at a time here and ends with incr of i

def fibonaci_num(n):
    if n <= 1:
        return n
    else:
        return fibonaci_num(n-1) + fibonaci_num(n-2)

N = 10

for i in range(N):
    print(fibonaci_num(i), end=' add -> ')

my output

0 add -> 1 add -> 1 add -> 2 add -> 3 add -> 5 add -> 8 add -> 13 add -> 21 add -> 34 add ->

Body:
Here I've simplified answer using ternary operator. May it will be helpful and better.

def fib(n):
    a, b = 0, 1
    while a < n:
        endstatement = '-' if (b < n) else ''
        print(a, end=endstatement)
        a, b = b, a+b
    print()

# Now call the function:
fib(1000)

Result:
  0-1-1-2-3-5-8-13-21-34-55-89-144-233-377-610-987

ContentLicense: CC BY-SA 4.0


问:
PHP/MySQL - Multiple Selects For Query
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

```<code>$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";
</code>```

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.

答:
Have you tried:

```<code>SELECT *
FROM instruments
WHERE '$search' IN (instrument, instrument2, instrument3, instrument4, instrument5)
</code>```

? I assume this is what you want.

But a real solution would be to create a separate table with the instruments and not keep multiple columns for the same information.

You should have a table with musicians and one with instruments to hold general instruments and their info. And a 3rd one (used to resolve the many to many relationship between instruments and musicians) that only holds musician id and instrument id.

Here's a few useful links:

http://en.wikipedia.org/wiki/Database_normalization

http://dev.mysql.com/doc/refman/5.0/en/join.html

Resolve many to many relationship

Title: PHP/MySQL - Multiple Selects For Query

Body:
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.

Body:
Have you tried:

SELECT *
FROM instruments
WHERE '$search' IN (instrument, instrument2, instrument3, instrument4, instrument5)

? I assume this is what you want.

But a real solution would be to create a separate table with the instruments and not keep multiple columns for the same information.

You should have a table with musicians and one with instruments to hold general instruments and their info. And a 3rd one (used to resolve the many to many relationship between instruments and musicians) that only holds musician id and instrument id.

Here's a few useful links:

http://en.wikipedia.org/wiki/Database_normalization

http://dev.mysql.com/doc/refman/5.0/en/join.html

Resolve many to many relationship


问:
Formrecognizer preview: Train model error Payload too large
I'm trying to train a model in the formrecognizer preview using the test console (western europe) provided by azure. But i get an error code 413 Payload Too Large. The error message is: Unable to process dataset. Size of dataset exceeds size limit (4.00MB).

I've provided a SAS-Storage-Url pointing to a blob container. This blob container contains 5 png-files. Each with a size between 2.7 and 3.1 MB and with a content-type of application/png.

From the documentation i know that the file size must be smaller than 4 Mb.
Is the size of the complete dataset (sum of all trainig files) restricted to four Megabytes?

答: Form Recognizer v1 supports a training set which must be less than 4 megabytes (MB) total. The Form Recognizer v1 APIs are sync APIs and have a time limit on the processing time, hence the limits. Form Recognizer v2.0 (preview) is an async API and enabling training on large data sets. Please use the v2.0 (preview) API. </p>


问:
YACC when expression && expression error! can't read the first expression first
I'm writing a parser, and I do some error message to check.

But when I go to a loop like

while ( index<=n && index > 0 ) do ...

my syntax is fine.

but the process to run this line's code, according to my trace,

it trace the expression:index>0 first, then trace expression && expression,
the last one will be the first expression (index<=n). but why?

Isn't it correct to check index <=n first, then index >0, the last one will be expression && expression?

In only one condition, it'll be fine.

for example like: while (index<=n) do

But if it's combined conditions, things go wrong.

this are my partial code

```<code>    expr: expr LE expr
          {<br/>
           Trace("expression <= expression");
           if ($1->type != $3->type) yyerror("type not match");
           if ($1->type != intType && $1->type != realType) yyerror("operator error");
           idInfo *info = new idInfo();
           info->attribute = 2; //variable type
           info->type = boolType;
           $$ = info;
          }<br/>
         |expr AND expr
         {
          Trace("expression && expression");
          if ($1->type != $3->type) yyerror("type not match");
          if ($1->type != boolType) yyerror("operator error");
          idInfo *info = new idInfo();
          info->attribute = 2; //variable type
          info->type = boolType;
          $$ = info;
         }
        |expr GG expr
        {<br/>
         Trace("expression > expression");
         if ($1->type != $3->type) yyerror("type not match");
         if ($1->type != intType && $1->type != realType) yyerror("operator error");
         idInfo *info = new idInfo();
         info->attribute = 2; //variable type
         info->type = boolType;
         $$ = info;
        }
</code>```

These are the result according to my trace....

    while

    '('

    ID:index

    <=

    ID:n

    &&

    ID:index

    '>'

    INTEGER:0

    ')'

Line: 16 expression > expression

Line: 16 expression && expression

Line: 16 type not match

Line: 16 operator error

Line: 16 expression <= expression

Line: 16 type not match

答:
Your precedence declarations are incorrect or missing.

Without actually seeing them, it is hard to provide more information, but it looks like all of your operators have the same precedence and right associativity.

If you received a warning about parsing conflicts, it would have been useful had you mentioned that fact (and even better had you solved the issue).

It is almost always better to use Bison's built-in trace facility than to try to do it yourself. Bison's feature is more comprehensive, more accurate, and a lot less work. See the Debugging your Parser section in the Bison manual.

Body:
I'm writing a parser, and I do some error message to check.

But when I go to a loop like

while ( index<=n && index > 0 ) do ...

my syntax is fine.

but the process to run this line's code, according to my trace,

it trace the expression:index>0 first, then trace expression && expression,
the last one will be the first expression (index<=n). but why?

Isn't it correct to check index <=n first, then index >0, the last one will be expression && expression?

In only one condition, it'll be fine.

for example like: while (index<=n) do

But if it's combined conditions, things go wrong.

this are my partial code

    expr: expr LE expr
          {

           Trace("expression <= expression");
           if ($1->type != $3->type) yyerror("type not match");
           if ($1->type != intType && $1->type != realType) yyerror("operator error");
           idInfo *info = new idInfo();
           info->attribute = 2; //variable type
           info->type = boolType;
           $$ = info;
          }

         |expr AND expr
         {
          Trace("expression && expression");
          if ($1->type != $3->type) yyerror("type not match");
          if ($1->type != boolType) yyerror("operator error");
          idInfo *info = new idInfo();
          info->attribute = 2; //variable type
          info->type = boolType;
          $$ = info;
         }
        |expr GG expr
        {

         Trace("expression > expression");
         if ($1->type != $3->type) yyerror("type not match");
         if ($1->type != intType && $1->type != realType) yyerror("operator error");
         idInfo *info = new idInfo();
         info->attribute = 2; //variable type
         info->type = boolType;
         $$ = info;
        }

These are the result according to my trace....

    while

    '('

    ID:index

    <=

    ID:n

    &&

    ID:index

    '>'

    INTEGER:0

    ')'

Line: 16 expression > expression

Line: 16 expression && expression

Line: 16 type not match

Line: 16 operator error

Line: 16 expression <= expression

Line: 16 type not match


问:
C# Linq filter and sum datatable
I have a datatable (see the image)

I am trying to sum '1. rate' in the 'Event' column for each clientID.

I'm using the code below to do so:

```<code>  var group = dt.AsEnumerable().GroupBy(g => g.Field<string>("Client Id"));
  foreach (var g in group)
  {
      int sum = dt.AsEnumerable().Where(r => r.Field<string>("Client Id") == g.Key
      & r.Field<string>("Total Units") == "1. rate").Count();
      Console.WriteLine(sum);
  }
</code>```

As you might notice in the image, many of the 'UnitID's' are the same. I'm trying to apply a filter so for example. If any of the same 'UnitID' has a 'Event' of 'Refundering' I want to filter all those 'UnitID's', and not just the single row. Any ideas how I can apply this filter are welcome.

Thanks in advance

答:
Group by UnitID and remove the groups that contain "Refundering", then ungroup keeping only the "1. rate" rows, group by ClientID and count the results.

```<code>var ans = dt.AsEnumerable()
            .GroupBy(r => r.Field<string>("UnitID"))
            .Where(rg => rg.All(r => r.Field<string>("Event") != "Refundering"))
            .SelectMany(rg => rg.Where(r => r.Field<string>("Event") == "1. rate"))
            .GroupBy(r => r.Field<string>("ClientID"))
            .Select(rg => new { ClientID = rg.Key, CountRate = rg.Count() });
</code>```

Title: C# Linq filter and sum datatable

Body:
I have a datatable (see the image)

I am trying to sum '1. rate' in the 'Event' column for each clientID.

I'm using the code below to do so:

  var group = dt.AsEnumerable().GroupBy(g => g.Field<string>("Client Id"));
  foreach (var g in group)
  {
      int sum = dt.AsEnumerable().Where(r => r.Field<string>("Client Id") == g.Key
      & r.Field<string>("Total Units") == "1. rate").Count();
      Console.WriteLine(sum);
  }

As you might notice in the image, many of the 'UnitID's' are the same. I'm trying to apply a filter so for example. If any of the same 'UnitID' has a 'Event' of 'Refundering' I want to filter all those 'UnitID's', and not just the single row. Any ideas how I can apply this filter are welcome.

Thanks in advance

Body:
Group by UnitID and remove the groups that contain "Refundering", then ungroup keeping only the "1. rate" rows, group by ClientID and count the results.

var ans = dt.AsEnumerable()
            .GroupBy(r => r.Field<string>("UnitID"))
            .Where(rg => rg.All(r => r.Field<string>("Event") != "Refundering"))
            .SelectMany(rg => rg.Where(r => r.Field<string>("Event") == "1. rate"))
            .GroupBy(r => r.Field<string>("ClientID"))
            .Select(rg => new { ClientID = rg.Key, CountRate = rg.Count() });


问:
Are Amazon Athena views actually hive views, or are they a separate bolt-on?
Amazon Athena is based on Presto. Amazon Athena supports views.

Presto does not support Hive views because it doesn't want to deal with Hive Query Language.  Since a view is actually a Hive query, it would have to understand hive's entire language rather than just its schema. Presto supports views via its Hive connector. These views are "Presto views",   are Presto-specific (cannot be queried from Hive).

Does Athena support Hive views under the covers?  Or are Athena views an entirely separate layer/bolt-on that just saves named Presto/Athena queries?

答:
To the best of my knowledge they are Presto views. I've dug into how views are saved in the Glue catalog, and talked to the Athena team about why it's done the way it is. I'm no expert on what makes something a Presto view vs. a Hive view, but Athena is not doing anything on top of Presto when it comes to views.

When you create a view in Athena it creates a table in Glue that is of type VIRTUAL_VIEW, and has TableInput.ViewOriginalText with a very special structure (see below). Parameters also needs to contain presto_view: true.

The structure in TableInput.ViewOriginalText looks like this /* Presto View: <BASE64 DATA> */, where the payload is a base 64 encoded JSON structure that describes the view. Value of TableInput.ViewOriginalText is produced by Presto (see https://github.com/prestosql/presto/blob/27a1b0e304be841055b461e2c00490dae4e30a4e/presto-hive/src/main/java/io/prestosql/plugin/hive/HiveUtil.java#L597-L600).

If the question is whether or not views created in Athena can be used by other tools that connect to the Glue catalog I think the answer is no. The way they are encoded is Presto-specific.


问:
Laravel excel don't detect my data in file
I just installed the last version of Laravel/Excel
I followed the tutorial but I get a problem

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'num' cannot be null (SQL: insert into notes (num, cne, nom, prenom, note, matiere, user_id, remarque, sem, ses, an, created_at, updated_at) values (, , , , , , 1, , , , , 2019-05-28 15:36:08, 2019-05-28 15:36:08))

This is my model controller and import class

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{

    protected $fillable = [
        'num',
        'cne',
        'nom',
        'prenom',
        'note',
        'matiere',
        'user_id',
        'remarque',
        'sem',
        'ses',
        'an',
        'created_at',
        'updated_at'
    ];
}
</code>```

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Imports\NoteImport;
use Maatwebsite\Excel\Facades\Excel;

class NoteController extends Controller
{

    public function addnote(){
        return view('note.create');
    }

    public function savenote(Request $request){

        Excel::import(new NoteImport, request()->file('file'));

        return redirect()->back()->with('success', 'All good!');
    }

}
</code>```

```<code><?php

namespace App\Imports;

use App\Note;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DateTime;

use Auth;
class NoteImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $now = new DateTime();
        return new Note([

            'num'=>$row['num'],
            'cne'=> $row['cne'],
            'nom'=> $row['nom'],
            'prenom'=> $row['prenom'],
            'note'=> $row['note'],
            'matiere'=> $row['matiere'],
            'user_id' => Auth::user()->id,
            'remarque' => $row['remarque'],
            'sem' => $row['sem'],
            'ses' => $row['ses'],
            'an' => $row['an'],
            'created_at'=>$now,
            'updated_at'=>$now,

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

This is a picture of the file

答:
I just added and it's working now!
to the noteImport</p>

```<code> if (!isset($row['num'])) {
            return null;
        }
</code>```

Body:
I just installed the last version of Laravel/Excel
I followed the tutorial but I get a problem

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'num' cannot be null (SQL: insert into notes (num, cne, nom, prenom, note, matiere, user_id, remarque, sem, ses, an, created_at, updated_at) values (, , , , , , 1, , , , , 2019-05-28 15:36:08, 2019-05-28 15:36:08))

This is my model controller and import class

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Note extends Model
{

    protected $fillable = [
        'num',
        'cne',
        'nom',
        'prenom',
        'note',
        'matiere',
        'user_id',
        'remarque',
        'sem',
        'ses',
        'an',
        'created_at',
        'updated_at'
    ];
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Imports\NoteImport;
use Maatwebsite\Excel\Facades\Excel;

class NoteController extends Controller
{

    public function addnote(){
        return view('note.create');
    }

    public function savenote(Request $request){

        Excel::import(new NoteImport, request()->file('file'));

        return redirect()->back()->with('success', 'All good!');
    }

}

<?php

namespace App\Imports;

use App\Note;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use DateTime;

use Auth;
class NoteImport implements ToModel, WithHeadingRow
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $now = new DateTime();
        return new Note([

            'num'=>$row['num'],
            'cne'=> $row['cne'],
            'nom'=> $row['nom'],
            'prenom'=> $row['prenom'],
            'note'=> $row['note'],
            'matiere'=> $row['matiere'],
            'user_id' => Auth::user()->id,
            'remarque' => $row['remarque'],
            'sem' => $row['sem'],
            'ses' => $row['ses'],
            'an' => $row['an'],
            'created_at'=>$now,
            'updated_at'=>$now,

        ]);
    }
}

This is a picture of the file

Body:
I just added and it's working now!
to the noteImport

 if (!isset($row['num'])) {
            return null;
        }


问:
How can referenced parameters correctly be deduced using type traits
I am trying to count the number of arguments in the passed method signature of a template.
I want to know the number of arguments as this method is wrapped into a generic lamda and depending on the number of arguments passed, I will add a bit more information to the method passed in here.

I have isolated the issue to the snippit below. The snippit below works as expected but once I change the result method to take a reference of the METHOD, it fails compiling. Why s the reference on the paramter type influencing the type? How could I make it work with a reference?

Tested this with Microsoft Visual Studio 2017.

#include "pch.h"
#include <iostream>

template <typename Func>
struct func_traits;

template <typename R, typename... TArgs>
struct func_traits<R(*)(TArgs...)> {
    static constexpr uint32_t ARG_COUNT = sizeof...(TArgs);
};

class TestClass {
public:
    // Compile error!!!
    // error C2027: use of undefined type 'func_traits<METHOD>'
    // uint32_t Result(const METHOD& function)

    template <typename METHOD>
    uint32_t Result(const METHOD function) {
        return (func_traits< METHOD >::ARG_COUNT);
    }
};

void foo(int a, int b, int c)
{
}

int bar()
{
    return 0;
}

int baz(double)
{
    return 0;
}

int main()
{
    TestClass device;

    std::cout << device.Result(foo) << std::endl;
    std::cout << device.Result(bar) << std::endl;
    std::cout << device.Result(baz) << std::endl;
    return 0;

}
```

答:
The scenario in your example is very rare and is related to particular template rule related specifically to functions and array.

To elaborate if you have a template function which takes another function by reference then type deduced for T is actual function type (not pointer to function).
For e.g.

```<code>template<typename T>
void fun(const T& f);
{
.....
}
void print(int);
fun(print); //for this case T will be deduced as void(int) and not void(*)int i.e. T will not be a function pointer
</code>```

So to get your example working for reference case you have to create one more template specialization like :

```<code>template <typename R, typename... TArgs>
struct func_traits<R(TArgs...)> {
    static constexpr uint32_t ARG_COUNT = sizeof...(TArgs);
};  //note (*) is removed from template function
</code>```

In short if you are passing function or array by value then they are decayed to pointer but if you are passing by reference then they are treated as it is.
More details are available in Scott Meyers Effective Modern C++ (https://www.oreilly.com/library/view/effective-modern-c/9781491908419/ch01.html)

Body:
The scenario in your example is very rare and is related to particular template rule related specifically to functions and array.

To elaborate if you have a template function which takes another function by reference then type deduced for T is actual function type (not pointer to function).
For e.g.

template<typename T>
void fun(const T& f);
{
.....
}
void print(int);
fun(print); //for this case T will be deduced as void(int) and not void(*)int i.e. T will not be a function pointer

So to get your example working for reference case you have to create one more template specialization like :

template <typename R, typename... TArgs>
struct func_traits<R(TArgs...)> {
    static constexpr uint32_t ARG_COUNT = sizeof...(TArgs);
};  //note (*) is removed from template function

In short if you are passing function or array by value then they are decayed to pointer but if you are passing by reference then they are treated as it is.
More details are available in Scott Meyers Effective Modern C++ (https://www.oreilly.com/library/view/effective-modern-c/9781491908419/ch01.html)


问:
Checkbutton won't be set to variable value
I created a simple Python Tkinter gui and I can't manage to have Checkbutton initalize with the correct values, both are always unchecked,  no matter what I do, whereas the two prints in the code display :

```<code>('dryRunVar', 0)
('useGenreSubFolderVar', 1)
</code>```

Tried whatever I could with BooleanVar also, and couldn't make it work

Strangely enough if I change instanciation of CheckButton() to ttk.CheckButton(), then both buttons are in 'gray' state

Even changing call to configuration values to constants 0 and 1 doesn't change anything, Buttons stay unchecked

Also try to tweak a little around Tk instanciation and mainloop, no success

```<code>#!/usr/lib/python2.7/
# -*- coding: utf-8 -*-

from Tkinter import *
import conf,ttk

class GUI():

    def __init__(self,window, configuration) :
        self.configuration = configuration
        self.window = window
        self.draw()

    def draw(self) :
        self.root = Frame(self.window,padx=15,pady=15,width=800,height=200)
        self.root.grid(column=0,row=0)
        self.drawParametersFrame()

    def drawParametersFrame(self) :
        #Parameters frame
        self.parametersFrame = LabelFrame(self.root,text="Sorting Parameters",padx=15,pady=15)
        self.parametersFrame.grid(column=0,row=2,sticky="EW")
        dryRunVar = IntVar()
        dryRunVar.set(self.configuration['dryRun'])
        print("dryRunVar",dryRunVar.get())
        dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=dryRunVar, onvalue=1, offvalue = 0)
        dryRunCheckButton.grid(column=0,row=0,sticky="W")
        useGenreSubFolderVar = IntVar()
        useGenreSubFolderVar.set(self.configuration['genreSubFolders'])
        print("useGenreSubFolderVar",useGenreSubFolderVar.get())
        useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=useGenreSubFolderVar, onvalue=1, offvalue = 0)
        useGenreSubFolderCheckButton.grid(column=2,row=0,sticky="W")

if __name__ == "__main__":
    configuration = conf.loadConf(r"/home/thomas/code/perso/python/conf.conf")
    window = Tk()
    gui = GUI(window,configuration)
    window.mainloop()
</code>```

答:
Make your IntVar an attribute of the class instead.

```<code>def drawParametersFrame(self) :
    ...
    self.dryRunVar = IntVar()
    self.dryRunVar.set(1)
    dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=self.dryRunVar, onvalue=1, offvalue = 0)
    ...
    self.useGenreSubFolderVar = IntVar()
    self.useGenreSubFolderVar.set(1)
    useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=self.useGenreSubFolderVar, onvalue=1, offvalue = 0)
    ...
</code>```

Body:
I created a simple Python Tkinter gui and I can't manage to have Checkbutton initalize with the correct values, both are always unchecked,  no matter what I do, whereas the two prints in the code display :

('dryRunVar', 0)
('useGenreSubFolderVar', 1)

Tried whatever I could with BooleanVar also, and couldn't make it work

Strangely enough if I change instanciation of CheckButton() to ttk.CheckButton(), then both buttons are in 'gray' state

Even changing call to configuration values to constants 0 and 1 doesn't change anything, Buttons stay unchecked

Also try to tweak a little around Tk instanciation and mainloop, no success

#!/usr/lib/python2.7/
# -*- coding: utf-8 -*-

from Tkinter import *
import conf,ttk

class GUI():

    def __init__(self,window, configuration) :
        self.configuration = configuration
        self.window = window
        self.draw()

    def draw(self) :
        self.root = Frame(self.window,padx=15,pady=15,width=800,height=200)
        self.root.grid(column=0,row=0)
        self.drawParametersFrame()

    def drawParametersFrame(self) :
        #Parameters frame
        self.parametersFrame = LabelFrame(self.root,text="Sorting Parameters",padx=15,pady=15)
        self.parametersFrame.grid(column=0,row=2,sticky="EW")
        dryRunVar = IntVar()
        dryRunVar.set(self.configuration['dryRun'])
        print("dryRunVar",dryRunVar.get())
        dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=dryRunVar, onvalue=1, offvalue = 0)
        dryRunCheckButton.grid(column=0,row=0,sticky="W")
        useGenreSubFolderVar = IntVar()
        useGenreSubFolderVar.set(self.configuration['genreSubFolders'])
        print("useGenreSubFolderVar",useGenreSubFolderVar.get())
        useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=useGenreSubFolderVar, onvalue=1, offvalue = 0)
        useGenreSubFolderCheckButton.grid(column=2,row=0,sticky="W")

if __name__ == "__main__":
    configuration = conf.loadConf(r"/home/thomas/code/perso/python/conf.conf")
    window = Tk()
    gui = GUI(window,configuration)
    window.mainloop()

Body:
Make your IntVar an attribute of the class instead.

def drawParametersFrame(self) :
    ...
    self.dryRunVar = IntVar()
    self.dryRunVar.set(1)
    dryRunCheckButton = Checkbutton(self.parametersFrame,text="Dry Run", variable=self.dryRunVar, onvalue=1, offvalue = 0)
    ...
    self.useGenreSubFolderVar = IntVar()
    self.useGenreSubFolderVar.set(1)
    useGenreSubFolderCheckButton = Checkbutton(self.parametersFrame,text="Use genre subfolders", variable=self.useGenreSubFolderVar, onvalue=1, offvalue = 0)
    ...


问:
Java Timer & KeyEvents problem
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

```<code>public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}
</code>```

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

```<code>..P..
..ppp
.....
.....
</code>```

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

```<code>        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;
</code>```

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)

答:
You may want to take a look at Key Bindings and its examples at the bottom of that same page.

Taken from tips4java blog:

Add new functionality by adding a new key binding:

```<code>Action action = new AbstractAction() {...};
String keyStrokeAndKey = "control Z";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
component.getInputMap(...).put(keyStroke, keyStrokeAndKey);
component.getActionMap().put(keyStrokeAndKey, action);
</code>```

Change existing functionality by replacing the Action of an existing binding:

```<code>Action action = new AbstractAction() {...};
KeyStroke keyStroke = KeyStroke.getKeyStroke("control Z");
InputMap im = component.getInputMap(...);
component.getActionMap().put(im.get(keyStroke), action);
</code>```

Share an Action with a different KeyStroke:

```<code>KeyStroke existingKeyStroke = KeyStroke.getKeyStroke("ENTER");
KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
InputMap im = component.getInputMap(...);
im.put(addedKeyStroke, im.get(existingKeyStroke));
</code>```

Remove a key binding:

```<code>KeyStroke remove = KeyStroke.getKeyStroke(...);
InputMap im =component.getInputMap(...);
im.put(remove, "none");
</code>```

Note, the above examples are for adding bindings to individual components. To add a binding at the frame or dialog level you need to use the InputMap and ActionMap of the root pane:

```<code>frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)...
frame.getRootPane().getActionMap()...
</code>```

Title: Java Timer & KeyEvents problem

Body:
I have been making Tetris game and it's almost complete. I have a problem with KeyEvents and a Timer.

My Timer calls actionPerformed every 400ms which drops down tetris block. Problem is that if I press something from the keyboard (down, left, right etc), those commands are noted also every 400 milliseconds. How can I make the timer call actionPerformed every 400ms but so that I can press whenever and how many times I want something from the keyboard and it's instantly recognized/responded to?

EDIT: Here's some of code like people asked

public class Game extends JPanel implements ActionListener {

public static final HashMap<Character, Color> colors = new HashMap<Character,Color>();
Timer timer;
Block kpl;
Grid gameBoard;
char[][] grid;
boolean paused = false;

public Game() {

    colors.put('P', Color.blue); colors.put('S', Color.green);
    colors.put('D', Color.pink); colors.put('L', Color.red);
    colors.put('Z', Color.orange); colors.put('A', Color.cyan);
    colors.put('T', Color.magenta);
    kpl = new Block();
    gameBoard = new Grid(21,10); // 21x10 sized gameboard
    grid = gameBoard.getGrid();
    addKeyListener(new KeyListening());
    setDoubleBuffered(true);
    setFocusable(true);
    timer = new Timer(100, this);
    timer.start();

}

@Override
public void paint(Graphics g) { // draws the current game situation
    super.paint(g);

        int height = getHeight()/grid.length;
        int width = getWidth()/grid[0].length/2;

        for (int row = 0; row < grid.length; ++row) {
            for (int column = 0; column < grid[row].length; ++column) {

                if (grid[row][column] == '.') { // if empty, paint white
                    g.setColor(Color.white);
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.LIGHT_GRAY);
                    g.drawRect(column*width, row*height , width, height);
                }
                else if (grid[row][column] != '.') { // if not empty, paint with the color of the block
                    g.setColor(colors.get(grid[row][column]));
                    g.fillRect(column*width, row*height , width, height);
                    g.setColor(Color.BLACK);
                    g.drawRect(column*width, row*height , width, height);
                }
            }
        }

    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

public void actionPerformed(ActionEvent e) {
    if (!gameBoard.isFallingBlock())
        gameBoard.drop(kpl); // if not any falling blocks, drops a new block

    gameBoard.updateView(); // moves the block down
    repaint();
}

    private class KeyListening extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v"); // moves block left
                break;
            case KeyEvent.VK_RIGHT:
                gameBoard.move("o"); // moves block right
                break;
            case KeyEvent.VK_DOWN:
                gameBoard.updateView(); // moves block down
                break;
            case KeyEvent.VK_SPACE:
                gameBoard.move("p"); // drops the block to the bottom
                break;
            case KeyEvent.VK_UP: // rotates block
                gameBoard.move("k");
                break;
            case KeyEvent.VK_P: // makes the game pause
                if (paused) {
                    timer.start();
                    paused = false;
                    return;
                }

                timer.stop();
                paused = true;
                break;

        }

    }

}

}

Had to translate the variables a little since I have been naming them with my own language. GUI is also pretty simple since I made first a text version of my Tetris so it basically runs the text version of it in the background and just paints the situation of the game.

Text version itself is char typed matrix where I move the blocks, for example:

..P..
..ppp
.....
.....

SOLVED:

Problem solved! In public void keyPressed() after every command coming from keyboard I just called repaint()-method again like

        public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();
        switch (key) {
            case KeyEvent.VK_LEFT:
                gameBoard.move("v");
                repaint();
                break;

Originally my game responded to my keyboard commands instantly but drew the current state of game every 400ms in actionPerformed() where the repaint() was called. Now my blocks can be moved whenever I want without any "delay" and they're still dropping steady every 400ms :)

Body:
You may want to take a look at Key Bindings and its examples at the bottom of that same page.

Taken from tips4java blog:

Add new functionality by adding a new key binding:

Action action = new AbstractAction() {...};
String keyStrokeAndKey = "control Z";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
component.getInputMap(...).put(keyStroke, keyStrokeAndKey);
component.getActionMap().put(keyStrokeAndKey, action);

Change existing functionality by replacing the Action of an existing binding:

Action action = new AbstractAction() {...};
KeyStroke keyStroke = KeyStroke.getKeyStroke("control Z");
InputMap im = component.getInputMap(...);
component.getActionMap().put(im.get(keyStroke), action);

Share an Action with a different KeyStroke:

KeyStroke existingKeyStroke = KeyStroke.getKeyStroke("ENTER");
KeyStroke addedKeyStroke = KeyStroke.getKeyStroke("control Z");
InputMap im = component.getInputMap(...);
im.put(addedKeyStroke, im.get(existingKeyStroke));

Remove a key binding:

KeyStroke remove = KeyStroke.getKeyStroke(...);
InputMap im =component.getInputMap(...);
im.put(remove, "none");

Note, the above examples are for adding bindings to individual components. To add a binding at the frame or dialog level you need to use the InputMap and ActionMap of the root pane:

frame.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)...
frame.getRootPane().getActionMap()...


问:
Is possible to set item params programmatically drawable xml file?
I have drawable file that includes layer-list and items inside. I'm trying to set position of one item by variable (or method) from Java class.

I've tried to find it by id and use setLeft(int), but it doesn't work.

findViewById(R.id.arr).setLeft(tone.position());
```

<ul>
<li>tone.positions() gives me int values</li>
</ul>

<pre class="lang-xml prettyprint-override"><code><View
            android:id="@+id/vid"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginStart="90dp"
            android:layout_marginEnd="90dp"
            android:background="@drawable/line"/>
</code>```

This is in LinearLayout in MainActivity xml file

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#00ffffff"/>
        </shape>
    </item>
    <item android:gravity="center">
        <shape android:shape="rectangle">
            <size android:height="1dp"/>
            <solid android:color="#000000"/>
        </shape>
    </item>
    <item
        android:id="@+id/arr"
        android:left="10dp"
        android:gravity="center_horizontal"
        android:bottom="5dp"
        android:top="-5dp"
        android:drawable="@drawable/arrow" />
</layer-list>
```

There is my drawable file. I want to change "left" attribute in item with "arr" id.
Is it possible?

答:
findViewById() can be used to retrieve Views in your layout xml files. More specifically, the layout that you set using setContentView(). Your sample, will probably return null, since there is no @+id/arr in your layout. Hence, you can only use findViewById() to retrieve the view with android:id="@+id/vid"

You might be able to achieve what you want, by first getting the View. And getting the background from that view afterwards.

Something like this (untested):

```<code>val view = findViewById(R.id.vid)
val background = view.background as? LayerDrawable
background?.setLayerInsetLeft(R.id.arr, tone.positions())
</code>```

or in Java (not sure about the syntax, but you'll get the idea):

```<code>View view = findViewById(R.id.vid);
LayerDrawable background = (LayerDrawable)(view.getBackground());
background.setLayerInsetLeft(R.id.arr, tone.positions());
</code>```

For more details what you can do with a LayerDrawable, look at the official documentation

Body:
I have drawable file that includes layer-list and items inside. I'm trying to set position of one item by variable (or method) from Java class.

I've tried to find it by id and use setLeft(int), but it doesn't work.

findViewById(R.id.arr).setLeft(tone.position());

tone.positions() gives me int values

<View
            android:id="@+id/vid"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginStart="90dp"
            android:layout_marginEnd="90dp"
            android:background="@drawable/line"/>

This is in LinearLayout in MainActivity xml file

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#00ffffff"/>
        </shape>
    </item>
    <item android:gravity="center">
        <shape android:shape="rectangle">
            <size android:height="1dp"/>
            <solid android:color="#000000"/>
        </shape>
    </item>
    <item
        android:id="@+id/arr"
        android:left="10dp"
        android:gravity="center_horizontal"
        android:bottom="5dp"
        android:top="-5dp"
        android:drawable="@drawable/arrow" />
</layer-list>

There is my drawable file. I want to change "left" attribute in item with "arr" id.
Is it possible?

Body:
findViewById() can be used to retrieve Views in your layout xml files. More specifically, the layout that you set using setContentView(). Your sample, will probably return null, since there is no @+id/arr in your layout. Hence, you can only use findViewById() to retrieve the view with android:id="@+id/vid"

You might be able to achieve what you want, by first getting the View. And getting the background from that view afterwards.

Something like this (untested):

val view = findViewById(R.id.vid)
val background = view.background as? LayerDrawable
background?.setLayerInsetLeft(R.id.arr, tone.positions())

or in Java (not sure about the syntax, but you'll get the idea):

View view = findViewById(R.id.vid);
LayerDrawable background = (LayerDrawable)(view.getBackground());
background.setLayerInsetLeft(R.id.arr, tone.positions());

For more details what you can do with a LayerDrawable, look at the official documentation


问:
Is there a way to Debug why my executable JAR of a JavaFX-Project runs on my Computer but not on others ? (Using jdk 1.8._051)
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

```<code>Class-Path: .
Main-Class: proj.view.Launcher

</code>```

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

```

答:
You might get classDefNotFoundExeption: javafx.application.Application when you are running on machine having jdk above 11.

oracle has removed javaFX form JDK 11, hence need to provide dependency on javafx-controls module.

```<code>`<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>12-ea+9</version>
</dependency>`
</code>```

add this to your dependency.

https://openjfx.io/

Body:
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

Class-Path: .
Main-Class: proj.view.Launcher

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

Body:
You might get classDefNotFoundExeption: javafx.application.Application when you are running on machine having jdk above 11.

oracle has removed javaFX form JDK 11, hence need to provide dependency on javafx-controls module.

`<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>12-ea+9</version>
</dependency>`

add this to your dependency.

https://openjfx.io/


问:
How to convert a timestamp(yyyy-mm-dd-h-m-s to a date (yyyy-mm-dd)
I have a timestamp field that I need to drop the hrs,min,sec from so I can count by dates.

I've tried to_date, date_trunc, to_char

```<code>name.BIRTH_DT_TM = to_date(name.BIRTH_DT_TM,'DD mm YYYY HH24":"MI":"SS')
</code>```

I would like name.BIRTH_DT_TM to show as YYYY-DD-MM without the Hours Minutes and Seconds

答:
You should be able to use date_trunc():

```<code>select date_trunc('day', name.birth_dt_tm)
</code>```

Body:
I have a timestamp field that I need to drop the hrs,min,sec from so I can count by dates.

I've tried to_date, date_trunc, to_char

name.BIRTH_DT_TM = to_date(name.BIRTH_DT_TM,'DD mm YYYY HH24":"MI":"SS')

I would like name.BIRTH_DT_TM to show as YYYY-DD-MM without the Hours Minutes and Seconds

Body:
You should be able to use date_trunc():

select date_trunc('day', name.birth_dt_tm)


问:
How to use boost::aio::async_connect with lambda
I want to reliaze how to use boost::aio::async_connect with lambda.
Boost version 1.68

It's really strange that I could use std::bind but not lambda.
If I use std::bind, it work.
But when I use lambda, it buillt failed, and said "IteratorConnectHandler type requirements not met.

std::bind version (worked)

```<code>void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
        std::bind(
            on_connect,
            std::placeholders::_1)

    );
}
</code>```

lambda version (not worked)

```<code>void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
            [&, sp](boost::system::error_code ec) {
               if (ec) {
                   return;
               }
               ws->next_layer().async_handshake(boost::asio::ssl::stream_base::client,
                                                [&, sp](boost::system::error_code ec1) {
                                                    handShake(ec);
                                                });
        }

    );
}

</code>```

So how to use lambda here?

答:
You call async_connect with pair of iterators, so your lambda should meet iterator connect handler requirements. As second parameter you have to pass connected endpoint.

```<code>boost::asio::async_connect(ws->next_layer().next_layer(),
    results.begin(),
    results.end(),
        [&, sp](  boost::system::error_code ec,
                  boost::asio::ip::tcp::resolver::iterator it)
           {
           if (ec) {
               return;
           }
           //...
</code>```

To be consistent with reference you should also fix bind version. on_connect should also take iterator as second param.

Your current bind version compiles and works, but when asynchronous operation initiated by async_connect is completed, functor created by bind is called with only error_code, you cannot access endpoint. You can modify bind so that it takes on_connect without any arguments.

```<code>void on_connect(){}

boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(), results.end(), std::bind(on_connect)); // compiles fine
</code>```

this also compiles, but when handler is called neither error_code nor endpoint can be accessed. (Yes it is a bit strange that you are not getting compiler errors when using bind which inform that requirements of handler are not fulfilled. I don't know where this disagreement between lambda and bind comes from.)

Body:
I want to reliaze how to use boost::aio::async_connect with lambda.
Boost version 1.68

It's really strange that I could use std::bind but not lambda.
If I use std::bind, it work.
But when I use lambda, it buillt failed, and said "IteratorConnectHandler type requirements not met.

std::bind version (worked)

void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
        std::bind(
            on_connect,
            std::placeholders::_1)

    );
}

lambda version (not worked)

void SslClient::connect(boost::asio::ip::tcp::resolver::results_type results) {
    auto sp = shared_from_this();
    boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(),
        results.end(),
            [&, sp](boost::system::error_code ec) {
               if (ec) {
                   return;
               }
               ws->next_layer().async_handshake(boost::asio::ssl::stream_base::client,
                                                [&, sp](boost::system::error_code ec1) {
                                                    handShake(ec);
                                                });
        }

    );
}

So how to use lambda here?

Body:
You call async_connect with pair of iterators, so your lambda should meet iterator connect handler requirements. As second parameter you have to pass connected endpoint.

boost::asio::async_connect(ws->next_layer().next_layer(),
    results.begin(),
    results.end(),
        [&, sp](  boost::system::error_code ec,
                  boost::asio::ip::tcp::resolver::iterator it)
           {
           if (ec) {
               return;
           }
           //...

To be consistent with reference you should also fix bind version. on_connect should also take iterator as second param.

Your current bind version compiles and works, but when asynchronous operation initiated by async_connect is completed, functor created by bind is called with only error_code, you cannot access endpoint. You can modify bind so that it takes on_connect without any arguments.

void on_connect(){}

boost::asio::async_connect(ws->next_layer().next_layer(),
        results.begin(), results.end(), std::bind(on_connect)); // compiles fine

this also compiles, but when handler is called neither error_code nor endpoint can be accessed. (Yes it is a bit strange that you are not getting compiler errors when using bind which inform that requirements of handler are not fulfilled. I don't know where this disagreement between lambda and bind comes from.)


问:
How to implement a button onto a button, to delete the parent and the child with the same click, without having the parent be clickable? (Unity)
I have a dynamically loaded List that consists of different buttons. If a button is clicked, the corresponding entry of the list will be destroyed. Now I want to have a child button on each of the dynamically created parent buttons, that will destroy the parent and the child. And the parent should "lose" this delete function.</p>

```<code>public void AddMoreButton()
{
    if (lectureInput.text.Length < 1)
    {
        return;
    }
    lectureTitle.text = lectureInput.text;
    creditsTitle.text = creditsInput.text;
    swsTitle.text = swsInput.text;
    GameObject button = (GameObject)Instantiate(prefabButton);
    Button buttonInstance = button.GetComponentInChildren<Button>();
    buttonInstance.onClick.AddListener(() => { Destroy(button); });
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);
    ClearInputs();
}
</code>```

答:
You can pretty much copy paste the button creation code, and just move Destroy(button) into its AddListener call. Make sure you don't change the parent button when creating the childButton except for in the Destroy(button) call. You can set the parent to the button, too:

```<code>public void AddMoreButton()
{
    if (lectureInput.text.Length < 1)
    {
        return;
    }
    lectureTitle.text = lectureInput.text;
    creditsTitle.text = creditsInput.text;
    swsTitle.text = swsInput.text;
    GameObject button = (GameObject)Instantiate(prefabButton);
    Button buttonInstance = button.GetComponentInChildren<Button>();
    childButtonInstance.onClick.AddListener(() => { /*whatever the parent button should do*/ });
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);

    GameObject childButton = (GameObject)Instantiate(prefabButton);
    Button childButtonInstance = childButton.GetComponentInChildren<Button>();
    buttonInstance.onClick.AddListener(() => { Destroy(button); });
    childButton.transform.SetParent(button, false);
    childButton.layer = 5;
    childButton.SetActive(true);

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

You'll probably have to adjust its position with childButton.transform.Translate(Vector3(0f,0.5f,0f)); or something so that it doesn't overlap with its parent button.

Body:
I have a dynamically loaded List that consists of different buttons. If a button is clicked, the corresponding entry of the list will be destroyed. Now I want to have a child button on each of the dynamically created parent buttons, that will destroy the parent and the child. And the parent should "lose" this delete function.

public void AddMoreButton()
{
    if (lectureInput.text.Length < 1)
    {
        return;
    }
    lectureTitle.text = lectureInput.text;
    creditsTitle.text = creditsInput.text;
    swsTitle.text = swsInput.text;
    GameObject button = (GameObject)Instantiate(prefabButton);
    Button buttonInstance = button.GetComponentInChildren<Button>();
    buttonInstance.onClick.AddListener(() => { Destroy(button); });
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);
    ClearInputs();
}

Body:
You can pretty much copy paste the button creation code, and just move Destroy(button) into its AddListener call. Make sure you don't change the parent button when creating the childButton except for in the Destroy(button) call. You can set the parent to the button, too:

public void AddMoreButton()
{
    if (lectureInput.text.Length < 1)
    {
        return;
    }
    lectureTitle.text = lectureInput.text;
    creditsTitle.text = creditsInput.text;
    swsTitle.text = swsInput.text;
    GameObject button = (GameObject)Instantiate(prefabButton);
    Button buttonInstance = button.GetComponentInChildren<Button>();
    childButtonInstance.onClick.AddListener(() => { /*whatever the parent button should do*/ });
    button.transform.SetParent(panel.transform, false);
    button.layer = 5;
    button.SetActive(true);

    GameObject childButton = (GameObject)Instantiate(prefabButton);
    Button childButtonInstance = childButton.GetComponentInChildren<Button>();
    buttonInstance.onClick.AddListener(() => { Destroy(button); });
    childButton.transform.SetParent(button, false);
    childButton.layer = 5;
    childButton.SetActive(true);

    ClearInputs();
}

You'll probably have to adjust its position with childButton.transform.Translate(Vector3(0f,0.5f,0f)); or something so that it doesn't overlap with its parent button.


问:
How is the data in TX/RX buffer of NIC is transferred to dpdk ring buffer rather than kernel ring buffer?
I wanted to know how dpdk bypasses kernel. How does userspace application access the NIC space. What tool does dpdk use to access the NIC?
I know, dpdk uses uio_pci_generic or igb_uio or vfio-pci drivers. How does this attach to NIC space. How does poll mode driver know where to poll?

I know that the RX of NIC is redirected to dpdk ring buffer instead of kernel ring buffer.

答:
dpdk uses uio_pci_generic or igb_uio or vfio-pci

That is exactly how DPDK attaches to the NIC - by binding the DPDK-compatible drivers to NIC PCI address (in most cases, for example with Mellanox, RDMA is used). Well, actually, it's you who has to bind the drivers.

DPDK then, as you said, maps the NIC buffers to userspace memory (hugepages) and interfaces with the NIC over PCI, directly "talking" to registers.

If you want to know more in-depth about the architecture, these slides do a pretty good job I think.


问:
__m256i version of _mm_test_all_zeros
I know how to test if an _m128i register is all zero with the _mm_test_all_zeros intrinsic.

What is the AVX2 / __m256i version of this intrinsic? If one isn't available, what is the fastest way to test if all 256 bits in a SIMD register are zero?

答:
The fastest is probably vptest instruction.

// Return 1 if `x` is all zeros, otherwise 0
inline int test_all_zeros( __m256i x )
{
    return _mm256_testz_si256( x, x );
}
```

Title: __m256i version of _mm_test_all_zeros


问:
Have fixed parameters in Java constructor - possible?
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

```<code>public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}
</code>```

and then call something along the lines of:

```<code>switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}
</code>```

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.

答:
If I understood your scenario right, you may want to thing about refactoring this approach.

Make MenuNode a base class, and inherit your subtypes from it (MenuNodeType1, MenuNodeType2 etc.). That way you'll get control over the single types but you can still throw them all into one collection.

Body:
I've defined an object in Java - as far as the Java is concerned, they're the same thing, but as far as the data which populates them is concerned, they can be one of three types (wildly named 1,2,3 with 0 for the "root").

What I'd really like to be able to do is have four constructors defined, as they need slightly different params for each type. I could do it with strategic nulls, but it seems like the wrong thing to do. What I'd love to have is something like:

public MenuNode(int type = 1, param1, param2, param3) {
    doStuffHere();
}
public MenuNode(int type = 2, paramX, paramY) {
    doStuffHere();
}

and then call something along the lines of:

switch (toQueue.itemType) {

    when ITEM_TYPE_STATIC {
        MenuNode mn1 = new MenuNode(ITEM_TYPE_STATIC, param1, param2, param3);
    }

    when ITEM_TYPE_DYNAMIC {
        MenuNode mn2 = new MenuNode(ITEM_TYPE_DYNAMIC, paramX, paramY);
    }

}

etc etc.

I hope this makes some sort of sense - it's a bit out there, and Googling only comes up with references to public static void etc.
If someone with a bit more experience/know-how with Java than me can take a look, eternal love and gratitude will be forthcoming.


问:
Row merging in sql
How to merge the duplicate records in single rows.

答:
You need aggregation : </p>

```<code>select id, max(lname) as lname, max(fname) as fname, max(address) as address,
       max(zip) as zip, max(city) as city, max(state) as state, max(phone)
from table t
group by id;
</code>```

Title: Row merging in sql

Body:
You need aggregation :

select id, max(lname) as lname, max(fname) as fname, max(address) as address,
       max(zip) as zip, max(city) as city, max(state) as state, max(phone)
from table t
group by id;


问:
Cannot read property of undefined and this pointing not in the right place
I have Cannot read property 'convertIntoCorrectDate' of undefined error.

I think when I call this.convertIntoCorrectDate, this refers to objectResa and not my component.
I tried to call myComp.convertIntoCorrectDate instead but it triggers error too (myComp.convertIntoCorrectDate is not a function).

Do you know how I can call my function ?

```<code>class myComp extends Component{
    constructor(props){
      //        this.convertIntoCorrectDate = this.convertIntoCorrectDate.bind(this);
    }

    fillBooking(responseJson){
        var reservations = responseJson.reservations;
        reservations.forEach(function(objectResa) {
              var aResaEvent = {
                     id: objectResa.resa.ID,
                     start: this.convertIntoCorrectDate(objectResa.resa.start),
                     end: this.convertIntoCorrectDate(objectResa.resa.end)
              };
              console.log(aResaEvent);
        });

    }

    convertIntoCorrectDate(date){
        // code to be written
        return "0";
    }
```
```

答:
If you change your fillBooking(responseJson) function to:

```<code>fillBooking = (responseJson) => {
</code>```

and the forEach to:

```<code>reservations.forEach((objectResa) => {
</code>```

(to arrow functions), the this should point to the scope you desire.

Body:
I have Cannot read property 'convertIntoCorrectDate' of undefined error.

I think when I call this.convertIntoCorrectDate, this refers to objectResa and not my component.
I tried to call myComp.convertIntoCorrectDate instead but it triggers error too (myComp.convertIntoCorrectDate is not a function).

Do you know how I can call my function ?

class myComp extends Component{
    constructor(props){
      //        this.convertIntoCorrectDate = this.convertIntoCorrectDate.bind(this);
    }

    fillBooking(responseJson){
        var reservations = responseJson.reservations;
        reservations.forEach(function(objectResa) {
              var aResaEvent = {
                     id: objectResa.resa.ID,
                     start: this.convertIntoCorrectDate(objectResa.resa.start),
                     end: this.convertIntoCorrectDate(objectResa.resa.end)
              };
              console.log(aResaEvent);
        });

    }

    convertIntoCorrectDate(date){
        // code to be written
        return "0";
    }
```

Body:
If you change your fillBooking(responseJson) function to:

fillBooking = (responseJson) => {

and the forEach to:

reservations.forEach((objectResa) => {

(to arrow functions), the this should point to the scope you desire.


问:
How to disable the calendar when it falls on a specific day in a week
I am working on a datepicker that will disable all the selection when the day falls on Friday & Saturday.

I've already created a datepicker that will only select next week's date (with the help of the other member here).

```<code>var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());

$(".datepicker").datepicker({
  minDate: dateMax,
  maxDate: daysTillWeekOver + 6
});
</code>```

I want all the dates on my datepicker will be disabled once the day in the current week falls every Friday and Saturday.

答:
Thanks for the answer above but that's not work for me. Here's what I did and solved my problem. (with the help of Grant Noe).</p>

```<code>var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());
var weekdayCheck = dateMin.getDay();

if (weekdayCheck == 5 || weekdayCheck == 6) {
var maxD = 0;
}
else{
var maxD = daysTillWeekOver + 6;
}

// activate datepicker
$(".datepicker").datepicker({

  minDate: dateMax,
  maxDate:  maxD
});
</code>```

Body:
I am working on a datepicker that will disable all the selection when the day falls on Friday & Saturday.

I've already created a datepicker that will only select next week's date (with the help of the other member here).

var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());

$(".datepicker").datepicker({
  minDate: dateMax,
  maxDate: daysTillWeekOver + 6
});

I want all the dates on my datepicker will be disabled once the day in the current week falls every Friday and Saturday.

Body:
Thanks for the answer above but that's not work for me. Here's what I did and solved my problem. (with the help of Grant Noe).

var date = new Date();
var weekday = date.getDay();
var daysTillWeekOver = 7 - weekday;

var dateMax = `+${daysTillWeekOver}d`;

var dateMin = new Date(Date.now());
dateMin.setDate(dateMin.getDate());
var weekdayCheck = dateMin.getDay();

if (weekdayCheck == 5 || weekdayCheck == 6) {
var maxD = 0;
}
else{
var maxD = daysTillWeekOver + 6;
}

// activate datepicker
$(".datepicker").datepicker({

  minDate: dateMax,
  maxDate:  maxD
});


答:
You can use aggregation:</p>

```<code>select id, max(lname) as lname, max(fname) as fname, max(address) as address,
       . . .
from t
group by id;
</code>```

Title: Row merging in sql

Body: How to merge the duplicate records in single rows.

Body:
You can use aggregation:

select id, max(lname) as lname, max(fname) as fname, max(address) as address,
       . . .
from t
group by id;


问:
Remove initial part of filename
I have multiple files that I would like to edit.

They look like

```<code>20190122-233715-886_tlog.354.2019012223043
</code>```

The prefix is mainly just date and time stamps and processing ID.

I need it to be

tlog.354.20190122230435

答:
You may use a Replace function.
For Example:

```<code> "20190122-233715-886_tlog.354.2019012223043" -replace "^.*_",""
</code>```

Will return

```<code> tlog.354.2019012223043
</code>```

So you can do something like:

```<code> $file=Get-Item -Path "D:\temp\20190122-233715-886_tlog.354.2019012223043.txt"
 Rename-Item $file -NewName $($($file.Name) -replace "^.*_","")
</code>```

And file will be renamed

Title: Remove initial part of filename

Body:
I have multiple files that I would like to edit.

They look like

20190122-233715-886_tlog.354.2019012223043

The prefix is mainly just date and time stamps and processing ID.

I need it to be

tlog.354.20190122230435

Body:
You may use a Replace function.
For Example:

 "20190122-233715-886_tlog.354.2019012223043" -replace "^.*_",""

Will return

 tlog.354.2019012223043

So you can do something like:

 $file=Get-Item -Path "D:\temp\20190122-233715-886_tlog.354.2019012223043.txt"
 Rename-Item $file -NewName $($($file.Name) -replace "^.*_","")

And file will be renamed


问:
RabbitMQ LDAP on the Management Plugin
I am new to RabbitMQ.  I have it installed on Windows 10 Enterpise for development purposes.  We have Active Directory running.  Trying to set up LDAP for the management plugin, so that any user with the right password can login as administrator.

My latest config:

```<code>[
{
    rabbit,
    [
        {
            auth_backends, [
                {rabbit_auth_backend_ldap, rabbit_auth_backend_internal},
                rabbit_auth_backend_internal
            ]
        }
    ]
},
{
  rabbitmq_auth_backend_ldap,
  [
    {
        servers, [
            "WLNC0DS23N.na.mycompany.com","WBRD0DS21N.na.mycompany.com"
        ]
    },
    {
        dn_lookup_attribute, "userPrincipalName"
    },
    {
        dn_lookup_base, "DC=na,DC=mycompany,DC=com"
    },
    {
        user_dn_pattern, "${username}@mycompany.com"
    },
    {
        use_ssl, false
    },
    {
        port, 389
    },
    {
        log, true
    },
    {
        vhost_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        resource_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        topic_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        tag_queries, [
            {
                administrator, {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
            }
        ]
    }
  ]
}
</code>```

].

Unfortunately, while LDAP seems to check me out ok, I am not able to login in and get this error in the log:

```<code>2019-05-28 16:04:14.662 [info] <0.678.0> LDAP CHECK: login for perryda
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.750 [info] <0.317.0>     LDAP bind succeeded: xxxx
2019-05-28 16:04:14.750 [info] <0.317.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.751 [info] <0.317.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP DN lookup: perryda -> CN=Perry\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP CHECK: does perryda have tag administrator?
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member",subtree}
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP filling template "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com" with
        [{username,<<"perryda">>},{user_dn,"CN=Perry\\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com"}]
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP template result: "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com"
2019-05-28 16:04:14.759 [info] <0.317.0>     LDAP DECISION: does perryda have tag administrator? true
2019-05-28 16:04:14.759 [info] <0.678.0> LDAP DECISION: login for perryda: ok
2019-05-28 16:04:14.759 [warning] <0.678.0> HTTP access denied: user 'perryda' - invalid credentials
</code>```

Does anyone have a clueon what the problem is, and how to fix?

答:
Trying to set it up so AD users that belong to a particular AD Group
  are just instantly logged in when they access the management plugin
  from IE or Edge.

The management UI doesn't support this. You will have to provide a username and password to log in using AD credentials.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

Title: RabbitMQ LDAP on the Management Plugin

Body:
I am new to RabbitMQ.  I have it installed on Windows 10 Enterpise for development purposes.  We have Active Directory running.  Trying to set up LDAP for the management plugin, so that any user with the right password can login as administrator.

My latest config:

[
{
    rabbit,
    [
        {
            auth_backends, [
                {rabbit_auth_backend_ldap, rabbit_auth_backend_internal},
                rabbit_auth_backend_internal
            ]
        }
    ]
},
{
  rabbitmq_auth_backend_ldap,
  [
    {
        servers, [
            "WLNC0DS23N.na.mycompany.com","WBRD0DS21N.na.mycompany.com"
        ]
    },
    {
        dn_lookup_attribute, "userPrincipalName"
    },
    {
        dn_lookup_base, "DC=na,DC=mycompany,DC=com"
    },
    {
        user_dn_pattern, "${username}@mycompany.com"
    },
    {
        use_ssl, false
    },
    {
        port, 389
    },
    {
        log, true
    },
    {
        vhost_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        resource_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        topic_access_query, {in_group_nested, "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
    },
    {
        tag_queries, [
            {
                administrator, {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
            }
        ]
    }
  ]
}

].

Unfortunately, while LDAP seems to check me out ok, I am not able to login in and get this error in the log:

2019-05-28 16:04:14.662 [info] <0.678.0> LDAP CHECK: login for perryda
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.663 [info] <0.678.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.750 [info] <0.317.0>     LDAP bind succeeded: xxxx
2019-05-28 16:04:14.750 [info] <0.317.0>         LDAP filling template "${username}@mycompany.com" with
        [{username,<<"perryda">>}]
2019-05-28 16:04:14.751 [info] <0.317.0>         LDAP template result: "perryda@mycompany.com"
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP DN lookup: perryda -> CN=Perry\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP CHECK: does perryda have tag administrator?
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member"}
2019-05-28 16:04:14.753 [info] <0.317.0>     LDAP evaluating query: {in_group_nested,"CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com","member",subtree}
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP filling template "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com" with
        [{username,<<"perryda">>},{user_dn,"CN=Perry\\, David,OU=Users,OU=WLNC-Wilmington,OU=OC,OU=IT-SD,DC=na,DC=mycompany,DC=com"}]
2019-05-28 16:04:14.754 [info] <0.317.0>         LDAP template result: "CN=NA_WHS,OU=GroupsAndContacts,OU=Exchange,DC=na,DC=mycompany,DC=com"
2019-05-28 16:04:14.759 [info] <0.317.0>     LDAP DECISION: does perryda have tag administrator? true
2019-05-28 16:04:14.759 [info] <0.678.0> LDAP DECISION: login for perryda: ok
2019-05-28 16:04:14.759 [warning] <0.678.0> HTTP access denied: user 'perryda' - invalid credentials

Does anyone have a clueon what the problem is, and how to fix?


问:
Using "Nested" image tags in html script with onmouseover
I am  designing a Sharepoint page with script editor. I have an image which I have used area tag on. So  with onmouseover another image pops up and it reverts back onmouseout. I further want to use another area tag on this new image onmouseover where I can add area tags.  Something like a nested image map.

```<code><img src="planets.gif" width="145" height="126" alt="Planets" name="myname"
usemap="#planetmap">

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" onmouseover=myname.src="C:\Users\Quabynar\Pictures\sun.gif" ; onmouseout=myname.src="C:\Users\Quabynar\Pictures\planets.gif">
  <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>
</code>```

I expect to put another map with area tags on the sun.gif when onmouseover where I can use href to a link about description the Sun. I don't seem to get around it.

答:
Finally I was able to get the results I wanted. I didn't need another map. I put all the area tags in one map and used functions for image switches when onmouseover and onmouseout. It was pretty straightforward. </p>

```<code><html>
<body>
<img src="planets.png" width="745" height="926" alt="Planets" name="myname"
ismap="ismap"
usemap="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126"
onmouseover=myname.src="C:\Users\Quabynar\Pictures\sun.png" ;
onmouseout=myname.src="C:\Users\Quabynar\Pictures\planets.gif">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
<area target="_blank" href=".../hackathon.htm" shape="rect" coords="73,250,234,297"
onmouseover="cycleprep()"; onmouseout="">
<area target="_blank" href="../mindmap.htm" shape="rect" coords="128,343,279,385"
onmouseover="cycleprep()"; onmouseout="" >
<area target="_blank" href=".../prep_more.htm" shape="rect" coords="206,414,375,459"
onmouseover="cycleprep()"; onmouseout="">

</map>

<script LANGUAGE="javascript">
image1=new Image
image1.src =".../sun.png"
image2=new Image
image2.src=".../planets.png"

function cycleprep() {
document.Auditcycle.src=image1.src;return true;
}

function cyclefull() {
document.Auditcycle.src=image2.src; return true;
}

</script>
</body>
</html>
</code>```

Body:
I am  designing a Sharepoint page with script editor. I have an image which I have used area tag on. So  with onmouseover another image pops up and it reverts back onmouseout. I further want to use another area tag on this new image onmouseover where I can add area tags.  Something like a nested image map.

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" onmouseover=myname.src="C:\Users\Quabynar\Pictures\sun.gif" ; onmouseout=myname.src="C:\Users\Quabynar\Pictures\planets.gif">
  <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

I expect to put another map with area tags on the sun.gif when onmouseover where I can use href to a link about description the Sun. I don't seem to get around it.

Body:
Finally I was able to get the results I wanted. I didn't need another map. I put all the area tags in one map and used functions for image switches when onmouseover and onmouseout. It was pretty straightforward.

<html>
<body>
<img src="planets.png" width="745" height="926" alt="Planets" name="myname"
ismap="ismap"
usemap="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126"
onmouseover=myname.src="C:\Users\Quabynar\Pictures\sun.png" ;
onmouseout=myname.src="C:\Users\Quabynar\Pictures\planets.gif">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
<area target="_blank" href=".../hackathon.htm" shape="rect" coords="73,250,234,297"
onmouseover="cycleprep()"; onmouseout="">
<area target="_blank" href="../mindmap.htm" shape="rect" coords="128,343,279,385"
onmouseover="cycleprep()"; onmouseout="" >
<area target="_blank" href=".../prep_more.htm" shape="rect" coords="206,414,375,459"
onmouseover="cycleprep()"; onmouseout="">

</map>

<script LANGUAGE="javascript">
image1=new Image
image1.src =".../sun.png"
image2=new Image
image2.src=".../planets.png"

function cycleprep() {
document.Auditcycle.src=image1.src;return true;
}

function cyclefull() {
document.Auditcycle.src=image2.src; return true;
}

</script>
</body>
</html>


问:
LinearNDInterpolatorExtrapolate returns error with trivial example
I'm trying to use scipy's LinearNDInterpolatorExtrapolate.

The following minimal code should be as trivial as possible, yet it returns an error

```<code>from scipy.interpolate import NearestNDInterpolator
points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator([.5,.5,.8])
</code>```

returns

```<code>TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

The error seems to come from line 81 of scipy.interpolate.ndgriddata [source]. Unfortunately I could not chase the error further, as I don't understand what tree.query is returning.

Is this a bug or I'm doing something wrong?

答:
Just pass the values without a list as a tuple of x-values

```<code>from scipy.interpolate import NearestNDInterpolator

points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator((.5,.5,.8))
# 5
</code>```

If you want to stick to passing lists, you can unpack the list contents using * as

```<code>interpolator(*[.5,.5,.8])
</code>```

For interpolating for more than one points, you can map the interpolator onto your list of points (tuples)

```<code>answer = list(map(interpolator, [(.5,.5,.8), (.05, 1.6, 2.9)]))
# [5, 5]
</code>```

Body:
I'm trying to use scipy's LinearNDInterpolatorExtrapolate.

The following minimal code should be as trivial as possible, yet it returns an error

from scipy.interpolate import NearestNDInterpolator
points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator([.5,.5,.8])

returns

TypeError: only integer scalar arrays can be converted to a scalar index

The error seems to come from line 81 of scipy.interpolate.ndgriddata [source]. Unfortunately I could not chase the error further, as I don't understand what tree.query is returning.

Is this a bug or I'm doing something wrong?

Body:
Just pass the values without a list as a tuple of x-values

from scipy.interpolate import NearestNDInterpolator

points = [[0,0,0], [1,0,0], [1,1,0],[0,1,0],[.5,.5,1]]
values = [1,2,3,4,5]
interpolator = NearestNDInterpolator(points,values)
interpolator((.5,.5,.8))
# 5

If you want to stick to passing lists, you can unpack the list contents using * as

interpolator(*[.5,.5,.8])

For interpolating for more than one points, you can map the interpolator onto your list of points (tuples)

answer = list(map(interpolator, [(.5,.5,.8), (.05, 1.6, 2.9)]))
# [5, 5]


问:
how to delete a saved project in Advanced REST client standalone app?
I'm trying to delete unused projects in ARC as they are stacking up. I couldn't find any setting related to this.

I found deleting an API call in ARC standalone app(how to delete a saved request in chrome's arc (Advanced REST Client) extension?) but not for saved project

答: I found it upon clicking kebab menu (vertical ellipsis) next to the project I want to delete and selected 'open details' and then there is 'delete project' button</p>


问:
Treat a tuple/list of Tensors as a single Tensor
I'm using Pytorch for some robotics Reinforcement Learning tasks. I'd like to use both images and information about the state as observations for this task. The implementation I'm using does not directly support this so I'm making some amendments. Expected observations are either state, as a 1 dimensional Tensor, or images as a 3 dimensional Tensor (channels, width, height). In my task I would like the observation to be a tuple of Tensors.

In many places in my codebase, the observation is of course expected to be a single Tensor, not a tuple of Tensors. Is there an easy way to treat a tuple of Tensors as a single Tensor?

For example, I would like:

```<code>observation.to(device)
</code>```

to work as normal when observation is a single Tensor, and call .to(device) on each Tensor when observation is a tuple of Tensors.

It should be simple enough to create a data type that can support this, but I'm wondering does such a data type already exist? I haven't found anything so far.

答:
If your tensors are all of the same size, you can use torch.stack to concatenate them into one tensor with one more dimension.

Example:

>>> import torch
>>> a=torch.randn(2,1)
>>> b=torch.randn(2,1)
>>> c=torch.randn(2,1)
>>> a
tensor([[ 0.7691],
        [-0.0297]])
>>> b
tensor([[ 0.4844],
        [-0.9142]])
>>> c
tensor([[ 0.0210],
        [-1.1543]])
>>> torch.stack((a,b,c))
tensor([[[ 0.7691],
         [-0.0297]],

        [[ 0.4844],
         [-0.9142]],

        [[ 0.0210],
         [-1.1543]]])
```

You can then use torch.unbind to go the other direction.

Body:
I'm using Pytorch for some robotics Reinforcement Learning tasks. I'd like to use both images and information about the state as observations for this task. The implementation I'm using does not directly support this so I'm making some amendments. Expected observations are either state, as a 1 dimensional Tensor, or images as a 3 dimensional Tensor (channels, width, height). In my task I would like the observation to be a tuple of Tensors.

In many places in my codebase, the observation is of course expected to be a single Tensor, not a tuple of Tensors. Is there an easy way to treat a tuple of Tensors as a single Tensor?

For example, I would like:

observation.to(device)

to work as normal when observation is a single Tensor, and call .to(device) on each Tensor when observation is a tuple of Tensors.

It should be simple enough to create a data type that can support this, but I'm wondering does such a data type already exist? I haven't found anything so far.

Body:
If your tensors are all of the same size, you can use torch.stack to concatenate them into one tensor with one more dimension.

Example:

>>> import torch
>>> a=torch.randn(2,1)
>>> b=torch.randn(2,1)
>>> c=torch.randn(2,1)
>>> a
tensor([[ 0.7691],
        [-0.0297]])
>>> b
tensor([[ 0.4844],
        [-0.9142]])
>>> c
tensor([[ 0.0210],
        [-1.1543]])
>>> torch.stack((a,b,c))
tensor([[[ 0.7691],
         [-0.0297]],

        [[ 0.4844],
         [-0.9142]],

        [[ 0.0210],
         [-1.1543]]])

You can then use torch.unbind to go the other direction.


问:
Model is not being created by AJAX
I want to create a View model that is created when a user finishes watching a lesson. The model should have a course id and a user id attribute. But Ajax doesn't create the view model after a lesson has been watched:

application.js:

```<code>$('#video').onended(function() {
  $.ajax({
    url:  '/views/new'
    type: 'post'
  });
});
</code>```

Views Controller:

```<code>def create
  @view = current_user.views.build
  @view.lesson = Lesson.find(params[:lesson_id])
end
</code>```

View Migration:

```<code>def change
  create_table :views do |t|
    t.integer :lesson_id
    t.integer :user_id

    t.timestamps
  end
end
</code>```

View Model:

```<code>belongs_to :user
belongs_to :lesson
</code>```

User Model:

```<code>has_many :views
</code>```

Lesson Model:

```<code>has_many :views
</code>```

Routes:

```<code>post 'views/new' => 'views#create'
</code>```

Lessons/show.html.erb:

```<code><h2><%= @lesson.name %></h2>
<video id="video" controls="true" width="auto"
height="auto">
<source src="<%= url_for(@lesson.file) %>"
type='video/mp4'>
</video>
</code>```

答:
From your AJAX you do not pass params[:lesson_id] in any way, so in controller it ends up being Lesson.find(nil), which raises ActiveRecord::RecordNotFound and controller renders error 404 (check browser's console for that).

```<code><video id="video" data-id="<%= @lesson.id %>" controls="true" width="auto" height="auto">
</code>```

$('#video').onended(function() {
  var id = $(this).data('id');
  $.ajax({
    url:  '/views/new'
    type: 'post',
    data: {
      lesson_id: id
    }
  });
});
```

<p>Also you do not save built object, use <code>create!</code> (the bang version raises error if it cannot save):</p>

```def create
  @view = current_user.views.create!(lesson: Lesson.find(params[:lesson_id]))
end
```

Title: Model is not being created by AJAX

Body:
I want to create a View model that is created when a user finishes watching a lesson. The model should have a course id and a user id attribute. But Ajax doesn't create the view model after a lesson has been watched:

application.js:

$('#video').onended(function() {
  $.ajax({
    url:  '/views/new'
    type: 'post'
  });
});

Views Controller:

def create
  @view = current_user.views.build
  @view.lesson = Lesson.find(params[:lesson_id])
end

View Migration:

def change
  create_table :views do |t|
    t.integer :lesson_id
    t.integer :user_id

    t.timestamps
  end
end

View Model:

belongs_to :user
belongs_to :lesson

User Model:

has_many :views

Lesson Model:

has_many :views

Routes:

post 'views/new' => 'views#create'

Lessons/show.html.erb:

<%= @lesson.name %>

<video id="video" controls="true" width="auto"
height="auto">
<source src="<%= url_for(@lesson.file) %>"
type='video/mp4'>
</video>

Body:
From your AJAX you do not pass params[:lesson_id] in any way, so in controller it ends up being Lesson.find(nil), which raises ActiveRecord::RecordNotFound and controller renders error 404 (check browser's console for that).

<video id="video" data-id="<%= @lesson.id %>" controls="true" width="auto" height="auto">

$('#video').onended(function() {
  var id = $(this).data('id');
  $.ajax({
    url:  '/views/new'
    type: 'post',
    data: {
      lesson_id: id
    }
  });
});

Also you do not save built object, use create! (the bang version raises error if it cannot save):

def create
  @view = current_user.views.create!(lesson: Lesson.find(params[:lesson_id]))
end


问:
how to take out the average in a single query and also checking the average greater than certain value and arranging in ascending order
Display average basic salary for each department and include only those employees who are having more than 20 years age? And display only those departments for which average basic salary is more than 5000? Then sort the output in the ascending order of average basic salary?

plz tell me a single query for this statement

Thanks,
Churchill

答:
This may help:</p>

```<code>SELECT t.Dept,t.Salary
FROM (SELECT Dept,AVG(Salary) AS Salary
FROM EMPLOYEE
WHERE Age > 20
GROUP BY Dept)t
WHERE t.Salary > 5000
ORDER BY t.Salary ASC
</code>```

Body:
This may help:

SELECT t.Dept,t.Salary
FROM (SELECT Dept,AVG(Salary) AS Salary
FROM EMPLOYEE
WHERE Age > 20
GROUP BY Dept)t
WHERE t.Salary > 5000
ORDER BY t.Salary ASC