问:
many to many insert from one form/controller method to all three tables - author, book & author_book in laravel
Succesfully inserted to author and book table but unable to insert in pivot table. I need to insert from the same form in all the 3 tables. I have attached screenshot of all of my code. Pls help.

Book Model

```<code>class Book extends Model
{
  protected $guarded = [];

  public function authors(){
    return $this->belongsToMany('App\Models\Author');
  }
}
</code>```

Author Model

```<code>class Author extends Model
{
  public $guarded = [];

  public function books(){
    return $this->belongsToMany('App\Models\Book');
  }
 }
</code>```

Book Controller

```<code>public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;
    // $author_id=Author::latest()->first()->id;

    // $book = new Book();
    // $book->authors()->attach($author_id);

    $author = new Author();
    $author->books()->attach($book_id);
    return back()->with('status', 'Insert Successful!');
}

public function validateBookInputs(){
    return request()->validate([
        'book_name' => 'required'
    ]);
}
public function validateAuthorInputs(){
    return request()->validate([
        'author_name' => 'required'
    ]);
}
</code>```

Book Create - View

```<code><form action="/books" method="POST">
<div class="form-group">
    <label>Enter Book Name</label>
    <input type="text" name="book_name" placeholder="Book Name" value="{{old('book_name')}}" class="form-control">
</div>
<div class="form-group">
    <label>Enter Author Name</label>
    <input type="text" name="author_name" placeholder="Author Name" value="{{old('author_name')}}"
        class="form-control">
</div>

<button type="submit" class="button-green">Submit</button>
@csrf
</code>```

create authors table

```<code>public function up()
{
    Schema::create('authors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('author_name', '30');
        $table->timestamps();
    });
}
</code>```

create books table

```<code>public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name', '30');
        $table->timestamps();
    });
}
</code>```

create author_book table

```<code>public function up()
{
    Schema::create('author_book', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('author_id');
        $table->unsignedBigInteger('book_id');
        $table->timestamps();
    });
}
</code>```

The Error

```<code>Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'author_id' cannot be null (SQL: insert into `author_book` (`author_id`, `book_id`) values (?, 25))
</code>```

答:
Here's the error in your controller store method:

```<code>public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;

    $author = new Author(); // <----
//  ^^^^^^^^^^^^^^^^^^^^^^^
    $author->books()->attach($book_id);

    return back()->with('status', 'Insert Successful!');
}
</code>```

Here, you are creating a new instance of Author, not using the newly created author object. That's why is throwing an error: the new instance doesn't have an id yet (because it just exist in memory, it isn't persisted yet).

Update the code like so:

```<code>public function store(Request $request)
{
    $book = Book::create($this->validateBookInputs());
//  ^^^^^^^
    $author = Author::create($this->validateAuthorInputs());
//  ^^^^^^^

    $author->books()->attach($book->id); // <---
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    return back()->with('status', 'Insert Successful!');
}
</code>```

Body:
Succesfully inserted to author and book table but unable to insert in pivot table. I need to insert from the same form in all the 3 tables. I have attached screenshot of all of my code. Pls help.

Book Model

class Book extends Model
{
  protected $guarded = [];

  public function authors(){
    return $this->belongsToMany('App\Models\Author');
  }
}

Author Model

class Author extends Model
{
  public $guarded = [];

  public function books(){
    return $this->belongsToMany('App\Models\Book');
  }
 }

Book Controller

public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;
    // $author_id=Author::latest()->first()->id;

    // $book = new Book();
    // $book->authors()->attach($author_id);

    $author = new Author();
    $author->books()->attach($book_id);
    return back()->with('status', 'Insert Successful!');
}

public function validateBookInputs(){
    return request()->validate([
        'book_name' => 'required'
    ]);
}
public function validateAuthorInputs(){
    return request()->validate([
        'author_name' => 'required'
    ]);
}

Book Create - View

<form action="/books" method="POST">

    Enter Book Name
    <input type="text" name="book_name" placeholder="Book Name" value="{{old('book_name')}}" class="form-control">

    Enter Author Name
    <input type="text" name="author_name" placeholder="Author Name" value="{{old('author_name')}}"
        class="form-control">

<button type="submit" class="button-green">Submit</button>
@csrf

create authors table

public function up()
{
    Schema::create('authors', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('author_name', '30');
        $table->timestamps();
    });
}

create books table

public function up()
{
    Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name', '30');
        $table->timestamps();
    });
}

create author_book table

public function up()
{
    Schema::create('author_book', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('author_id');
        $table->unsignedBigInteger('book_id');
        $table->timestamps();
    });
}

The Error

Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'author_id' cannot be null (SQL: insert into `author_book` (`author_id`, `book_id`) values (?, 25))

Body:
Here's the error in your controller store method:

public function store(Request $request)
{
    Book::create($this->validateBookInputs());
    Author::create($this->validateAuthorInputs());

    $book_id=Book::latest()->first()->id;

    $author = new Author(); // <----
//  ^^^^^^^^^^^^^^^^^^^^^^^
    $author->books()->attach($book_id);

    return back()->with('status', 'Insert Successful!');
}

Here, you are creating a new instance of Author, not using the newly created author object. That's why is throwing an error: the new instance doesn't have an id yet (because it just exist in memory, it isn't persisted yet).

Update the code like so:

public function store(Request $request)
{
    $book = Book::create($this->validateBookInputs());
//  ^^^^^^^
    $author = Author::create($this->validateAuthorInputs());
//  ^^^^^^^

    $author->books()->attach($book->id); // <---
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    return back()->with('status', 'Insert Successful!');
}


来源: stackexchange

问:
Possible to work with Isolated Storage from Javascript?
I'm needing to delete a value in Isolated storage from javascript code.

If this is possible how is it done? I found some code from a post written in 2007 and Silverlight has changed a lot since then.

答:
The best way would be to call a Silverlight method from JavaScript.  This link provides examples on how to handle this:

http://weblogs.asp.net/mschwarz/archive/2007/06/01/call-scribtable-methods-from-javascript-with-silverlight.aspx

ContentLicense: CC BY-SA 3.0


问:
Kotlin: what does annotation (acc: S, T) -> S mean?
I'm very new to Kotlin. I looked at Kotlin's source code and I saw this prototype:

```<code>public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S
</code>```

I understand that operation is a method, 'acc' is one its arguments, 'acc' is of type S and the return value of operation is of type S. However, what does the T inside list of arguments mean?
Where is its arguments?

答:
(acc: S, T) -> S is a type.

In Kotlin, functions are first-class types.  Some types have a simple name, such as String or Int.  Others need parameters, such as List<URL> or Map<Int, String>.  Function types have even more complicated names, of the form:

        (params) -> returnType

So a function which takes a single Int parameter and returns a String would have the type (Int) -> String.

You can also give names to the parameters if you want, e.g. (count: Int) -> String, though the name is ignored.

So in your example, the reduce() method takes a single parameter, called operation.  That parameter is a function which itself takes two parameters (the first called acc of type S, and the second of type T with no name), and returns a value of type S.

What's particular confusing in your case is that S and T are type parameters: they refer to types that aren't known yet.  When the reduce() method is called, the caller will specify them (or the compiler will infer them).  That's what the <S, T : S> after the fun means: the method needs two type parameters: S, and T (which must be S or a subtype).

ContentLicense: CC BY-SA 4.0

Body:
I'm very new to Kotlin. I looked at Kotlin's source code and I saw this prototype:

public inline fun <S, T : S> Iterable<T>.reduce(operation: (acc: S, T) -> S): S

I understand that operation is a method, 'acc' is one its arguments, 'acc' is of type S and the return value of operation is of type S. However, what does the T inside list of arguments mean?
Where is its arguments?


答:
problem is in BookController method store because use a new instance of Author model that not exists in database and just it is a instance of Author model, so change store method like following:</p>

```<code>$book = Book::create($this->validateBookInputs());
$author = Author::create($this->validateAuthorInputs());

$author->books()->attach($book->id);
return back()->with('status', 'Insert Successful!');
</code>```

Title: many to many insert from one form/controller method to all three tables - author, book & author_book in laravel

Body:
problem is in BookController method store because use a new instance of Author model that not exists in database and just it is a instance of Author model, so change store method like following:

$book = Book::create($this->validateBookInputs());
$author = Author::create($this->validateAuthorInputs());

$author->books()->attach($book->id);
return back()->with('status', 'Insert Successful!');


问:
replace several matches of a substring with their indexes
assuming that you have a string with multiple occurrences of the same substring what would be the best one-liner to replace the matches with their another substring which contains the index of the math as well? As an example, let's say you have the following string: This is a test. and we want to replace all the occurrences of is with X and their index to have something like: ThX-0 X-1 a test.

Any ideas on this?

答:
Simple solution in awk will be:

```<code>awk '{while(sub(/[iI][Ss]/,"X-"count++)){a=""};count=""} 1' Input_file
</code>```

OR as per anubhava sir's comment adding above code's shorter version:

```<code>awk '{while(sub(/[iI][Ss]/,"X-"count++));count=""} 1'  Input_file
</code>```

Simple explanation will be, run a loop till a substitution is found and do literally nothing inside it :) print the line at last.

Body:
Simple solution in awk will be:

awk '{while(sub(/[iI][Ss]/,"X-"count++)){a=""};count=""} 1' Input_file

OR as per anubhava sir's comment adding above code's shorter version:

awk '{while(sub(/[iI][Ss]/,"X-"count++));count=""} 1'  Input_file

Simple explanation will be, run a loop till a substitution is found and do literally nothing inside it :) print the line at last.


问:
Getting Enum Description in react component
I am totally new to react and javascript, So it may sound silly So Iam trying to show descriptive info about a enum value in react component. Below is code that I have written and not working

```<code>export function EmployeeFetcher()
{
   const [employeeData, setEmployeeData] = useState();
   const [employeeId, setEmplpyeeId] = useState();

   const handleSubmit = (e) => {
        e.preventDefault();
        if (!employeeId.length) {
            setEmployeeData(false);
            return;
        }
        fetch('api/employeeinfoProvider/' + employeeId)
             .then(response => response.json())
             .then(data => {
                    setEmployeeData({ employeeType: data })
             });
       }

    return (
        <Container fluid>
            <Form onSubmit={handleSubmit}>
                <InputGroup className="mb-3 m-2">
                    <FormControl onChange={(e) => setEmplpyeeId(e.target.value)} value={employeeId}
                        placeholder="Search employee"
                        aria-label="Model Info Id"
                        aria-describedby="basic-addon2"
                    />
                    <InputGroup.Append>
                        <Button type="submit" variant="outline-secondary">Search</Button>
                    </InputGroup.Append>
                </InputGroup>
            </Form>
            {<EmployeeViewer employeeInfoData={employeeData} />}
        </Container>
    );

function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}
</code>```

I am getting below error in browser, if i try run above code with valid parameters

Error: Element type is invalid: expected a string (for built-in
  components) or a class/function (for composite components) but got:
  undefined. You likely forgot to export your component from the file
  it's defined in, or you might have mixed up default and named imports.

答:
It is difficult to answer you as we would need more code to understand the context.

From the error mentionned above, I think that you are trying to use the function EmployeeViewer in another file but you are not exporting it in this file.

You can export it as default and then use it in the other file

```<code>function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}

export default EmployeeViewer;
//------
// OtherFile.js
import EmployeeViewer from './EmployeeViewer';

function App({ data }) {
  return (<div><EmployeeViewer employeeInfoData={data} /></div>);
}

export default App;
</code>```

Or only export this function

```<code>export function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}
//------
// OtherFile.js
import { EmployeeViewer } from './EmployeeViewer';

function App({ data }) {
  return (<div><EmployeeViewer employeeInfoData={data} /></div>);
}

export default App;
</code>```

Body:
I am totally new to react and javascript, So it may sound silly So Iam trying to show descriptive info about a enum value in react component. Below is code that I have written and not working

export function EmployeeFetcher()
{
   const [employeeData, setEmployeeData] = useState();
   const [employeeId, setEmplpyeeId] = useState();

   const handleSubmit = (e) => {
        e.preventDefault();
        if (!employeeId.length) {
            setEmployeeData(false);
            return;
        }
        fetch('api/employeeinfoProvider/' + employeeId)
             .then(response => response.json())
             .then(data => {
                    setEmployeeData({ employeeType: data })
             });
       }

    return (
        <Container fluid>
            <Form onSubmit={handleSubmit}>
                <InputGroup className="mb-3 m-2">
                    <FormControl onChange={(e) => setEmplpyeeId(e.target.value)} value={employeeId}
                        placeholder="Search employee"
                        aria-label="Model Info Id"
                        aria-describedby="basic-addon2"
                    />
                    <InputGroup.Append>
                        <Button type="submit" variant="outline-secondary">Search</Button>
                    </InputGroup.Append>
                </InputGroup>
            </Form>
            {<EmployeeViewer employeeInfoData={employeeData} />}
        </Container>
    );

function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}

I am getting below error in browser, if i try run above code with valid parameters

Error: Element type is invalid: expected a string (for built-in
  components) or a class/function (for composite components) but got:
  undefined. You likely forgot to export your component from the file
  it's defined in, or you might have mixed up default and named imports.

Body:
It is difficult to answer you as we would need more code to understand the context.

From the error mentionned above, I think that you are trying to use the function EmployeeViewer in another file but you are not exporting it in this file.

You can export it as default and then use it in the other file

function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}

export default EmployeeViewer;
//------
// OtherFile.js
import EmployeeViewer from './EmployeeViewer';

function App({ data }) {
  return (<div><EmployeeViewer employeeInfoData={data} /></div>);
}

export default App;

Or only export this function

export function EmployeeViewer({ employeeInfoData}) {
    return (<Container> {employeeInfoData.employeeTypes.map(x => <Border key={x}>{EmployeeTypeString(x)}</Border>)}</Container>);
}

function EmployeeTypeString(employeeType) {
    switch (employeeType) {
        case 1:
            return "Manager";
        case 3:
            return "Lead";
        case 4:
            return "Software Engineer";
    }
}
//------
// OtherFile.js
import { EmployeeViewer } from './EmployeeViewer';

function App({ data }) {
  return (<div><EmployeeViewer employeeInfoData={data} /></div>);
}

export default App;


问:
After installing gtest, gmock_main.cc replaces my main.cc
I experience that when 'gtest' is installed by 'conan', my 'gmock_main' somehow replaces my 'main'.

I am step-by-step adding more libraries to my program, using more and more lines to conanfile.txt, clear the generated files in subdirectory build, and run "cmake..; cmake --build .". After this I run the built binary.

My conanfile.txt is

```<code>[requires]
SystemC/2.3.3@minres/stable
SystemCVerification/2.0.1@minres/stable
doxygen_installer/1.8.15@bincrafters/stable
qt/5.12.0@bincrafters/stable
gtest/1.8.1@bincrafters/stable
#flex/2.6.4@bincrafters/stable

[generators]
cmake

[options]
SystemC:stdcxx=14
SystemCVerification:stdcxx=14
</code>```

Until I add the line

```<code>gtest/1.8.1@bincrafters/stable
</code>```

everything looks file, my binary starts and makes what I want. After installing gtest, the reply from MY OWN, NON-GTEST-RELATED program changes from

```<code>       SystemC 2.3.3-Accellera --- Jun 15 2019 21:14:08
        Copyright (c) 1996-2018 by all Contributors,
        ALL RIGHTS RESERVED
 Correct usage:
</code>```

to

```<code>Running main() from gmock_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (0 ms total)
[  PASSED  ] 0 tests.
</code>```

If I remove the line and remove gtest from conan database, rebuild my binary, it works fine again. I have no idea, what can cause such a strange error? Where to find the reason? Could be an accidental name clatching?

AFTER SUBMISSION:

I guessed that the problem is somehow caused by gtest. So I made the followings:
I saved the value of ${CONAN_LIBS}
without and with having the line

```<code>gtest/1.8.1@bincrafters/stable
</code>```

active in my conanfile.txt

```<code>scv;
systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;
freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z
</code>```

as well as with gtest:

```<code>scv;
gmock_maind;gmockd;gtestd;
systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;
freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z
</code>```

For better visibility, I separated the second line, really containing the names of libraries installed with the suspected line. After that, I edited the respective CMakeLists.txt (I removed the actual ${CONAN_LIBS} and replaced it with the former value, before asking conan to install gtest.)

```<code>target_link_libraries(A
#    ${CONAN_LIBS}
scv;systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z
)
</code>```

And, my app works as expected. What is going on here? How can gmock_main.cc replace my own .cc? (actually, a int sc_main(int argc,char *argv[])
but probably is makes no difference) Or better: how can I avoid it?

I understand that 'main' call in a library can replace my own 'main'.
Why is a main function in the library and how can I avoid it (I mean a way other than making this manual editing).

SECOND EDIT:
I also noticed that if I leave the

${CONAN_LIBS}
in the test branch, gmock_maind;
take over the control: already it puts my tests into its own main program,
as I am using a System C based main program (i.e. int sc_main(int argc, char* argv[]) ), it is not really good for me. Finally, I edited again the list of conan install libs and removed

gmock_maind;gmockd;

and now finally my apps make what I expect.

It is not quite the easiness I expected for the change.
As far as I know, since 1.8.0 gmock and gtest come in one package. I do not need gmock but it is OK. But what is the reason of adding gmock_maind, that kils all subprojects, except the ones which were for havin genter code here a gmock main test file, nothing else.

Is there some option to get rid off this gmock_maind, or whihc is the newest gtest that does not comprise gmock?

答:
I suppose it is caused by the standard option behavior of the gtest package.
These are the default options of gtest 1.10:

```<code>   default_options = {"shared": False, "build_gmock": True, "fPIC": True, "no_main": False,"debug_postfix": 'd', "hide_symbols": False}
</code>```

As you can see, no_main is false - this is the reason why when you link against gtest you also get the main from gtest delivered, which hides your own main.

It should be enough to set

```<code>[options]
gtest:no_main=True
</code>```

or

```<code>default_options = {"gtest:no_main":True}
</code>```

if you use a conanfile.py or call conan like

```<code>conan install . -o gtest:no_main=True
</code>```

if you prefer to not modify your conanfile at all.

I suggest to use the new conan-center https://conan.io/center/gtest/1.10.0/?user=&channel=&revision=&os=&tab=recipe since it is the newest and best maintained site for conan packages.

To learn more about setting conan options take a look here: https://docs.conan.io/en/latest/reference/conanfile/attributes.html#options

Edit:
In your specific case the reason why the linker picks gmocks main and not yours, instead of complaining about multiple defined symbols is that you use systemcs's sc_main - main, which is actually not the correct name for the entrypoint (the name needs always to be "main") but inside systemsc there is a main function that calls your sc_main as if it would be the actual entrypoint. I assume that there is also a preprocessor mechanism in systemsc that prevents linker errors when another standard main function is defined somewhere else. Read more about here: https://forums.accellera.org/topic/5932-how-exactly-sc_main-works/

Body:
I experience that when 'gtest' is installed by 'conan', my 'gmock_main' somehow replaces my 'main'.

I am step-by-step adding more libraries to my program, using more and more lines to conanfile.txt, clear the generated files in subdirectory build, and run "cmake..; cmake --build .". After this I run the built binary.

My conanfile.txt is

[requires]
SystemC/2.3.3@minres/stable
SystemCVerification/2.0.1@minres/stable
doxygen_installer/1.8.15@bincrafters/stable
qt/5.12.0@bincrafters/stable
gtest/1.8.1@bincrafters/stable
#flex/2.6.4@bincrafters/stable

[generators]
cmake

[options]
SystemC:stdcxx=14
SystemCVerification:stdcxx=14

Until I add the line

gtest/1.8.1@bincrafters/stable

everything looks file, my binary starts and makes what I want. After installing gtest, the reply from MY OWN, NON-GTEST-RELATED program changes from

       SystemC 2.3.3-Accellera --- Jun 15 2019 21:14:08
        Copyright (c) 1996-2018 by all Contributors,
        ALL RIGHTS RESERVED
 Correct usage:

to

Running main() from gmock_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (0 ms total)
[  PASSED  ] 0 tests.

If I remove the line and remove gtest from conan database, rebuild my binary, it works fine again. I have no idea, what can cause such a strange error? Where to find the reason? Could be an accidental name clatching?

AFTER SUBMISSION:

I guessed that the problem is somehow caused by gtest. So I made the followings:
I saved the value of ${CONAN_LIBS}
without and with having the line

gtest/1.8.1@bincrafters/stable

active in my conanfile.txt

scv;
systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;
freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z

as well as with gtest:

scv;
gmock_maind;gmockd;gtestd;
systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;
freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z

For better visibility, I separated the second line, really containing the names of libraries installed with the suspected line. After that, I edited the respective CMakeLists.txt (I removed the actual ${CONAN_LIBS} and replaced it with the former value, before asking conan to install gtest.)

target_link_libraries(A
#    ${CONAN_LIBS}
scv;systemc;ssl;crypto;pcre2-posix;pcre2-8;pcre2-16;pcre2-32;double-conversion;freetyped;harfbuzz;jpeg;sqlite3;pgcommon;pq;pthread;odbc;odbccr;odbcinst;ltdl;dl;bz2;png16d;m;z
)

And, my app works as expected. What is going on here? How can gmock_main.cc replace my own .cc? (actually, a int sc_main(int argc,char *argv[])
but probably is makes no difference) Or better: how can I avoid it?

I understand that 'main' call in a library can replace my own 'main'.
Why is a main function in the library and how can I avoid it (I mean a way other than making this manual editing).

SECOND EDIT:
I also noticed that if I leave the

${CONAN_LIBS}
in the test branch, gmock_maind;
take over the control: already it puts my tests into its own main program,
as I am using a System C based main program (i.e. int sc_main(int argc, char* argv[]) ), it is not really good for me. Finally, I edited again the list of conan install libs and removed

gmock_maind;gmockd;

and now finally my apps make what I expect.

It is not quite the easiness I expected for the change.
As far as I know, since 1.8.0 gmock and gtest come in one package. I do not need gmock but it is OK. But what is the reason of adding gmock_maind, that kils all subprojects, except the ones which were for havin genter code here a gmock main test file, nothing else.

Is there some option to get rid off this gmock_maind, or whihc is the newest gtest that does not comprise gmock?

Body:
I suppose it is caused by the standard option behavior of the gtest package.
These are the default options of gtest 1.10:

   default_options = {"shared": False, "build_gmock": True, "fPIC": True, "no_main": False,"debug_postfix": 'd', "hide_symbols": False}

As you can see, no_main is false - this is the reason why when you link against gtest you also get the main from gtest delivered, which hides your own main.

It should be enough to set

[options]
gtest:no_main=True

or

default_options = {"gtest:no_main":True}

if you use a conanfile.py or call conan like

conan install . -o gtest:no_main=True

if you prefer to not modify your conanfile at all.

I suggest to use the new conan-center https://conan.io/center/gtest/1.10.0/?user=&channel=&revision=&os=&tab=recipe since it is the newest and best maintained site for conan packages.

To learn more about setting conan options take a look here: https://docs.conan.io/en/latest/reference/conanfile/attributes.html#options

Edit:
In your specific case the reason why the linker picks gmocks main and not yours, instead of complaining about multiple defined symbols is that you use systemcs's sc_main - main, which is actually not the correct name for the entrypoint (the name needs always to be "main") but inside systemsc there is a main function that calls your sc_main as if it would be the actual entrypoint. I assume that there is also a preprocessor mechanism in systemsc that prevents linker errors when another standard main function is defined somewhere else. Read more about here: https://forums.accellera.org/topic/5932-how-exactly-sc_main-works/


问:
Why is promise.finally in my Vue project not working in Edge?
I'm having tremendous trouble getting my polyfills to work in Edge. I've tried to follow the documentation with various attempts all not working. It seems to be promise.finally specifically that isn't working. This happens in a vuex module so I tried adding vuex to transpileDependencies in vue.config but with no luck.

My babel.config.js:

```<code>module.exports = {
  presets: [['@vue/cli-plugin-babel/preset', {
    useBuiltIns: 'entry',
  }]],
};
</code>```

In my main.js I have the following two imports in the very top:

```<code>import 'core-js/stable';
import 'regenerator-runtime/runtime';
</code>```

My vue.config.js

```<code>// eslint-disable-next-line import/no-extraneous-dependencies
const webpack = require('webpack');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
  configureWebpack: {
    // Set up all the aliases we use in our app.
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 6,
      }),
    ],
  },
  css: {
    // Enable CSS source maps.
    sourceMap: !isProd,
  },
  transpileDependencies: ['vuex'],
};
</code>```

Note as mentioned above I have tried both with and without the transpileDepedencies. It says here vue/babel-preset-app that es7.promise.finally is included as a default polyfill

Versions:

Microsoft Edge: 44.18

Microsoft EdgeHTML 18.18362

@vue/cli-plugin-babel": "^4.1.2"

"core-js": "^3.6.4"

"regenerator-runtime": "^0.13.3"

Update 13/02

So I tried to type Promise.prototype on my site in edge and it does appear it is polyfilled:

So currently I'm investigating if some part of my chain (axios/vue axios) does not return a promise. Since it is working in chrome I'm suspecting that a part of the chain is not being polyfilled correctly?

This is my entire chain:

```<code>/* VUEX MODULE ACTION */
[a.ALL_CUSTOMERS](context) {
    context.commit(m.SET_CUSTOMER_LOADING, true);
    CustomerService.getAll()
      .then(({ data }) => {
        context.commit(m.SET_CUSTOMERS, data);
      })
      .finally(() => context.commit(m.SET_CUSTOMER_LOADING, false));
  },

/* CUSTOMER SERVICE */
import ApiService from '@/common/api.service';
const CustomerService = {
  getAll() {
    const resource = 'customers/';
    return ApiService.get(resource);
  },
...
}

/* API SERVICE */
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

const ApiService = {
  init() {
    Vue.use(VueAxios, axios);
    let baseUrl = process.env.VUE_APP_APIURL;
    Vue.axios.defaults.baseURL = baseUrl;
  },

  setHeader() {
    Vue.axios.defaults.headers.common.Authorization = `Bearer ${getToken()}`;
  },

  get(resource) {
    this.setHeader();
    return Vue.axios.get(`${resource}`);
  },
  ...
}
</code>```

答:
This is a known issue in core-js.

In theory, Edge provides a Promise polyfill for finally, but perhaps something is going on with the feature detection or your browserlist and you need to provide a polyfill :shrug:

I would delete both the Vue babel plugin and core-js from your project and then npm install them fresh.

npm install @vue/cli-plugin-babel --save-dev

npm install core-js --save

Also, make sure you're using core-js@3 via your config (babel.config.js) here

Lastly, there's a few Github issues talking about polyfills + Promises with regards to the other 3rd party libraries executed in your vuex store. Add all three of those libraries (axios, vue-axios, vuex) to your transpileDependencies section. If that fixes it, start removing the dependencies to see if they're needed.

Body:
I'm having tremendous trouble getting my polyfills to work in Edge. I've tried to follow the documentation with various attempts all not working. It seems to be promise.finally specifically that isn't working. This happens in a vuex module so I tried adding vuex to transpileDependencies in vue.config but with no luck.

My babel.config.js:

module.exports = {
  presets: [['@vue/cli-plugin-babel/preset', {
    useBuiltIns: 'entry',
  }]],
};

In my main.js I have the following two imports in the very top:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

My vue.config.js

// eslint-disable-next-line import/no-extraneous-dependencies
const webpack = require('webpack');

const isProd = process.env.NODE_ENV === 'production';

module.exports = {
  configureWebpack: {
    // Set up all the aliases we use in our app.
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 6,
      }),
    ],
  },
  css: {
    // Enable CSS source maps.
    sourceMap: !isProd,
  },
  transpileDependencies: ['vuex'],
};

Note as mentioned above I have tried both with and without the transpileDepedencies. It says here vue/babel-preset-app that es7.promise.finally is included as a default polyfill

Versions:

Microsoft Edge: 44.18

Microsoft EdgeHTML 18.18362

@vue/cli-plugin-babel": "^4.1.2"

"core-js": "^3.6.4"

"regenerator-runtime": "^0.13.3"

Update 13/02

So I tried to type Promise.prototype on my site in edge and it does appear it is polyfilled:

So currently I'm investigating if some part of my chain (axios/vue axios) does not return a promise. Since it is working in chrome I'm suspecting that a part of the chain is not being polyfilled correctly?

This is my entire chain:

/* VUEX MODULE ACTION */
[a.ALL_CUSTOMERS](context) {
    context.commit(m.SET_CUSTOMER_LOADING, true);
    CustomerService.getAll()
      .then(({ data }) => {
        context.commit(m.SET_CUSTOMERS, data);
      })
      .finally(() => context.commit(m.SET_CUSTOMER_LOADING, false));
  },

/* CUSTOMER SERVICE */
import ApiService from '@/common/api.service';
const CustomerService = {
  getAll() {
    const resource = 'customers/';
    return ApiService.get(resource);
  },
...
}

/* API SERVICE */
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';

const ApiService = {
  init() {
    Vue.use(VueAxios, axios);
    let baseUrl = process.env.VUE_APP_APIURL;
    Vue.axios.defaults.baseURL = baseUrl;
  },

  setHeader() {
    Vue.axios.defaults.headers.common.Authorization = `Bearer ${getToken()}`;
  },

  get(resource) {
    this.setHeader();
    return Vue.axios.get(`${resource}`);
  },
  ...
}


问:
How modify regex to exclude some text?
I have regex as '@(?:@msU'. I need modify this expression to exclude , ), exclude ()

How can I modify my regex?

答:
This would do it:

```<code>@<script(?!.*?no-defer).*?>.*?</script>@gm
</code>```

https://regex101.com/r/NWoKj8/1

Title: How modify regex to exclude some text?

Body:
This would do it:

@<script(?!.*?no-defer).*?>.*?</script>@gm

https://regex101.com/r/NWoKj8/1


问:
Too Many DOM Elements
I am building a one page webapp and it's starting to get pretty big. There are several components to the app, each one meticulously styled. On average the app has a DOM element count of 1200+. I have been warned by my YSlow scan that this is too many, and that I should have no more than 700 DOM elements.

I am usually quite strict and efficient with my markup and I doubt I would be able to trim much off. I tend to use a lot of DOM elements to get the styling exactly right and working cross browser.

How can I dramatically cut the number of DOM elements?
Will I have to load more of the content on demand (ajax) instead on all on page load?
Does a large amount of DOM elements have a big impact on performance?

I would love to hear people's experience with this and any solutions you may have...

答:
We've built a single page web app. Initially Yslow worried me as we had 2,000+ DOM objects in the page.

After some work we got all the other Yslow items to green. And we ended up living with it(around 1,800 right now) as the app is very fast in various browsers.

But we don't support IE6 and IE7, and it could be different for these browsers.

Title: Too Many DOM Elements


问:
How to pass parameters and the target of Input in React?
I want to pass parameters and the target of Input at the same time.

```<code>handleChange (e, a) => {
 this.setState({
  price: e.target.value
 });
 this.callback(e.target.value, a);
}
...
<input type = 'text' value = {this.state.price} onChange = {(e) => handleChange(a)} />
</code>```

It didn't work as I wanted. I hope your help.

答:
You are not passing the first parameter to the handleChange function, try: onChange = {(e) => handleChange(e, a)}

Or you can do this:

```<code>handleChange = (a) => event => {
 this.setState({
  price: event.target.value
 });
 this.callback(event.target.value, a);
}
...
<input type = 'text' value = {this.state.price} onChange = {handleChange(a)} />
</code>```

Body:
I want to pass parameters and the target of Input at the same time.

handleChange (e, a) => {
 this.setState({
  price: e.target.value
 });
 this.callback(e.target.value, a);
}
...
<input type = 'text' value = {this.state.price} onChange = {(e) => handleChange(a)} />

It didn't work as I wanted. I hope your help.

Body:
You are not passing the first parameter to the handleChange function, try: onChange = {(e) => handleChange(e, a)}

Or you can do this:

handleChange = (a) => event => {
 this.setState({
  price: event.target.value
 });
 this.callback(event.target.value, a);
}
...
<input type = 'text' value = {this.state.price} onChange = {handleChange(a)} />


问:
Return large subgraphs from a list of Ids in Cypher (Neo4j)
I have a question regarding the use of the Neo4j client for Java. I have a graph with about 120.000.000 nodes and 1.000.000.000 edges. From this graph, I want to extract subgraphs (average size about 500 nodes). For this purpose, I have created an index on the Id fields of the nodes.
The queries look like this

```<code>MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb
</code>```

At the moment I am looking for the edges with a second query that looks like this

```<code>MATCH (a::XXX:YYYY)-[r:ZZZZ]-(b::XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
AND b.uid IN [9999, 5555, 7777, 99999, ...]
</code>```

This is very very slow especially when the subgraphs get bigger.
My question now is how can I connect the two queries to get both the edges and the nodes of the subgraph at once. I know that there is a faster solution because the Neo4j browser gives me a
a visualization for

```<code>MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb
</code>```

which contains all edges.

thank you very much for your help

答:
I have divided the query into two different queries. The first one fetched the nodes

```<code>MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS node
</code>```

and the second

```<code>MATCH (n:Uid)
WHERE n.uid IN [9999, 5555, 7777, 99999, ...]
WITH collect(n) AS nds
UNWIND nds AS n1
MATCH (n1)-[r]-(n2)
WHERE n2 IN nds
RETURN r AS relation
</code>```

the edges. For some reason, it gets very slow when I try to combine the two and get the list of edges and the list of nodes. The overall solution is not very satisfying but at least I was able to archive an acceptable performance.

Body:
I have a question regarding the use of the Neo4j client for Java. I have a graph with about 120.000.000 nodes and 1.000.000.000 edges. From this graph, I want to extract subgraphs (average size about 500 nodes). For this purpose, I have created an index on the Id fields of the nodes.
The queries look like this

MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb

At the moment I am looking for the edges with a second query that looks like this

MATCH (a::XXX:YYYY)-[r:ZZZZ]-(b::XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
AND b.uid IN [9999, 5555, 7777, 99999, ...]

This is very very slow especially when the subgraphs get bigger.
My question now is how can I connect the two queries to get both the edges and the nodes of the subgraph at once. I know that there is a faster solution because the Neo4j browser gives me a
a visualization for

MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb

which contains all edges.

thank you very much for your help

Body:
I have divided the query into two different queries. The first one fetched the nodes

MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS node

and the second

MATCH (n:Uid)
WHERE n.uid IN [9999, 5555, 7777, 99999, ...]
WITH collect(n) AS nds
UNWIND nds AS n1
MATCH (n1)-[r]-(n2)
WHERE n2 IN nds
RETURN r AS relation

the edges. For some reason, it gets very slow when I try to combine the two and get the list of edges and the list of nodes. The overall solution is not very satisfying but at least I was able to archive an acceptable performance.


问:
melt columns and add 20 minutes to each row in date column
I'm trying to take this dataframe(with 1 row in this example):

```<code>id    Date                    value_now    value+20min    value+60min    value+80min
0     2015-01-11 00:00:01        12             15            18             22
</code>```

and to transform it to this:

```<code>id    Date                    Value
0     2015-01-11 00:00:01      12
0     2015-01-11 00:20:01      15
0     2015-01-11 00:40:01      18
0     2015-01-11 01:00:01      22
</code>```

as you can see I need to change the value in respond to the columns and create rows, I understood I can do it using melt, but I'm having hard time doing it.
Please help me with that.....
Thank you!

Body:
I'm trying to take this dataframe(with 1 row in this example):

id    Date                    value_now    value+20min    value+60min    value+80min
0     2015-01-11 00:00:01        12             15            18             22

and to transform it to this:

id    Date                    Value
0     2015-01-11 00:00:01      12
0     2015-01-11 00:20:01      15
0     2015-01-11 00:40:01      18
0     2015-01-11 01:00:01      22

as you can see I need to change the value in respond to the columns and create rows, I understood I can do it using melt, but I'm having hard time doing it.
Please help me with that.....
Thank you!

Body:
Here's one approach:

out = df.melt(id_vars=['id', 'Date'])

minutes = pd.to_numeric(out.variable.str.rsplit('+',1).str[-1]
                                    .str.rstrip('min'),
                        errors='coerce')

out['Date'] = pd.to_datetime(out.Date)

out['Date'] = out.Date + pd.to_timedelta(minutes.fillna(0), unit='m')

print(out.drop('variable',1))

id                Date               value
0  2015-01-11 2020-02-14 00:00:01     12
1  2015-01-11 2020-02-14 00:20:01     15
2  2015-01-11 2020-02-14 00:40:01     18
3  2015-01-11 2020-02-14 01:20:01     22


问:
How to query date with a column name in SQL?
how do I query just the date and not the time from the stored data?
I have tried the following:

```<code>select FirstName, dob from table1 where rno='123';
</code>```

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

答:
The best way to handle this is to return the full and unformatted datetime value, and let your C# code worry about formatting it and showing only the date.

In other words, don't change the SQL in the question at all.

This will save work for the database (and therefore improve scalability), while also making it easier for your app to adapt automatically to the preferred format of your users. So a user in the UK may see dd/MM/yyyy, while a user in the US could see MM/dd/yyyy from the same code.

How exactly this works depends greatly on the context of your app, and that information is not in the question, but it boils down to making sure the CultureInfo of the current process is correct (ie: supplied by the current culture settings in Windows or inferred by ASP.Net from the browser user-agent and request headers), and then formatting using the short date string standard datetime format string.

But if you really want to do this in the database, you can use the FORMAT() function, and name the result using the AS keyword so you can reference it in later code:

SELECT FORMAT(dob, 'dd/MM/yyyy') AS dob FROM table1 WHERE rno='123';
```

<p>or</p>

<pre class="lang-sql prettyprint-override"><code>SELECT FORMAT(dob, 'yyyy-MM-dd') AS dob FROM table1 WHERE rno='123';
</code>```

At this point, the C# will receive a string instead of DateTime value. Again, it's very much a good idea to let the database return the DateTime value and have the C# code worry about getting the right string representation when you need it.

Body:
how do I query just the date and not the time from the stored data?
I have tried the following:

select FirstName, dob from table1 where rno='123';

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

Body:
The best way to handle this is to return the full and unformatted datetime value, and let your C# code worry about formatting it and showing only the date.

In other words, don't change the SQL in the question at all.

This will save work for the database (and therefore improve scalability), while also making it easier for your app to adapt automatically to the preferred format of your users. So a user in the UK may see dd/MM/yyyy, while a user in the US could see MM/dd/yyyy from the same code.

How exactly this works depends greatly on the context of your app, and that information is not in the question, but it boils down to making sure the CultureInfo of the current process is correct (ie: supplied by the current culture settings in Windows or inferred by ASP.Net from the browser user-agent and request headers), and then formatting using the short date string standard datetime format string.

But if you really want to do this in the database, you can use the FORMAT() function, and name the result using the AS keyword so you can reference it in later code:

SELECT FORMAT(dob, 'dd/MM/yyyy') AS dob FROM table1 WHERE rno='123';

or

SELECT FORMAT(dob, 'yyyy-MM-dd') AS dob FROM table1 WHERE rno='123';

At this point, the C# will receive a string instead of DateTime value. Again, it's very much a good idea to let the database return the DateTime value and have the C# code worry about getting the right string representation when you need it.


问:
React Material-UI TextField looses focus with every key
I have a material-ui CharField, but I am unable to type a full string because it looses focus after one key entered, so I have to click on it after every key stroke, which is not acceptable.

This is my component SearchControl:

```<code>render() {
    const SearchControl = () => {
      return (
        <div className="col-6">
          <TextField
            className="col-11"
            id={this.state.code}
            defaultValue={this.state.code}
            label={"Modelo o Número de Serie"}
            variant="outlined"
            onChange={this.handleChange.bind(this)}
          />
          <IconButton
            ariaLabel="Buscar"
            className="col-1"
            onClick={this.handleSearchProductClick}
          >
            <SearchIcon />
          </IconButton>
        </div>
      );
    };

    if (!this.state.messageShown) {
      return (
        <div>
          <div style={{ display: "flex" }}>
            <NavBar onUpdate={this.onUpdate} />
          </div>
        </div>
      );
    } else {
      return (
        <div>
          <div fullWidth style={{ display: "flex", paddingTop: "30px" }}>
            <SearchControl />
            <ShortcutButtons />
          </div>
          <div fullWidth>
            <ProductsTable />
          </div>
          <div fullWidth />
          <div fullWidth style={{ display: "flex", paddingTop: "10px" }}>
            <ControlButtons />
            <TotalsDisplay />
          </div>
        </div>
      );
    }
}
</code>```

答:
I found the solution. The problem was that SearchControl component was an arrow function, which implies that it was a brand new function each rendering and, hence, a brand new component each rendering.

I changed SearchControl component declaration to a regular function, so each rendering would refer to the same function and, hence, to the same component:

```<code>constructor(props) {
    super(props);

    this.SearchControl = this.SearchControl.bind(this);
}

SearchControl() {
      return (
        <div className="col-6">
          <TextField
            className="col-11"
            id={this.state.code}
            defaultValue={this.state.code}
            label={"Modelo o Número de Serie"}
            variant="outlined"
            onChange={this.handleChange.bind(this)}
          />
          <IconButton
            ariaLabel="Buscar"
            className="col-1"
            onClick={this.handleSearchProductClick}
          >
            <SearchIcon />
          </IconButton>
        </div>
      );
    }

render() {
   if (!this.state.messageShown) {
      return (
        <div>
          <div style={{ display: "flex" }}>
            <NavBar onUpdate={this.onUpdate} />
          </div>
        </div>
      );
    } else {
      return (
        <div>
          <div fullWidth style={{ display: "flex", paddingTop: "30px" }}>
            <this.SearchControl />
            <ShortcutButtons />
          </div>
          <div fullWidth>
            <ProductsTable />
          </div>
          <div fullWidth />
          <div fullWidth style={{ display: "flex", paddingTop: "10px" }}>
            <ControlButtons />
            <TotalsDisplay />
          </div>
        </div>
      );
    }
  }
</code>```

Body:
I have a material-ui CharField, but I am unable to type a full string because it looses focus after one key entered, so I have to click on it after every key stroke, which is not acceptable.

This is my component SearchControl:

render() {
    const SearchControl = () => {
      return (

          <TextField
            className="col-11"
            id={this.state.code}
            defaultValue={this.state.code}
            label={"Modelo o Número de Serie"}
            variant="outlined"
            onChange={this.handleChange.bind(this)}
          />
          <IconButton
            ariaLabel="Buscar"
            className="col-1"
            onClick={this.handleSearchProductClick}
          >
            <SearchIcon />
          </IconButton>

      );
    };

    if (!this.state.messageShown) {
      return (

            <NavBar onUpdate={this.onUpdate} />

      );
    } else {
      return (

            <SearchControl />
            <ShortcutButtons />

            <ProductsTable />

            <ControlButtons />
            <TotalsDisplay />

      );
    }
}

Body:
I found the solution. The problem was that SearchControl component was an arrow function, which implies that it was a brand new function each rendering and, hence, a brand new component each rendering.

I changed SearchControl component declaration to a regular function, so each rendering would refer to the same function and, hence, to the same component:

constructor(props) {
    super(props);

    this.SearchControl = this.SearchControl.bind(this);
}

SearchControl() {
      return (
        <div className="col-6">
          <TextField
            className="col-11"
            id={this.state.code}
            defaultValue={this.state.code}
            label={"Modelo o Número de Serie"}
            variant="outlined"
            onChange={this.handleChange.bind(this)}
          />
          <IconButton
            ariaLabel="Buscar"
            className="col-1"
            onClick={this.handleSearchProductClick}
          >
            <SearchIcon />
          </IconButton>
        </div>
      );
    }

render() {
   if (!this.state.messageShown) {
      return (
        <div>
          <div style={{ display: "flex" }}>
            <NavBar onUpdate={this.onUpdate} />
          </div>
        </div>
      );
    } else {
      return (
        <div>
          <div fullWidth style={{ display: "flex", paddingTop: "30px" }}>
            <this.SearchControl />
            <ShortcutButtons />
          </div>
          <div fullWidth>
            <ProductsTable />
          </div>
          <div fullWidth />
          <div fullWidth style={{ display: "flex", paddingTop: "10px" }}>
            <ControlButtons />
            <TotalsDisplay />
          </div>
        </div>
      );
    }
  }


答:
you can melt the dataframe then use the variable column and split on + then use the right side of the split and convert to timedelta and add them back to date:

```<code>final = df.melt(['id','Date'])
final['Date'] += pd.to_timedelta(final['variable'].str.split('+').str[1].fillna('0min'))
print(final.drop('variable',1))
</code>```

```<code>   id                Date  value
0   0 2015-01-11 00:00:01     12
1   0 2015-01-11 00:20:01     15
2   0 2015-01-11 00:40:01     18
3   0 2015-01-11 01:20:01     22
</code>```

Another way proposed by @YOBEN_S where you can find the numeric in the variable column and convert to timedelta and add with the Date with df.assign:

```<code>final1 = (df.melt(['id','Date']).assign(Date=lambda x :
        x['Date']+pd.to_timedelta(x['variable'].str.findall(r'\d+')
        .str[0].fillna(0).astype(float),unit='min')))
</code>```

Title: melt columns and add 20 minutes to each row in date column

Body:
you can melt the dataframe then use the variable column and split on + then use the right side of the split and convert to timedelta and add them back to date:

final = df.melt(['id','Date'])
final['Date'] += pd.to_timedelta(final['variable'].str.split('+').str[1].fillna('0min'))
print(final.drop('variable',1))

   id                Date  value
0   0 2015-01-11 00:00:01     12
1   0 2015-01-11 00:20:01     15
2   0 2015-01-11 00:40:01     18
3   0 2015-01-11 01:20:01     22

Another way proposed by @YOBEN_S where you can find the numeric in the variable column and convert to timedelta and add with the Date with df.assign:

final1 = (df.melt(['id','Date']).assign(Date=lambda x :
        x['Date']+pd.to_timedelta(x['variable'].str.findall(r'\d+')
        .str[0].fillna(0).astype(float),unit='min')))


问:
Extracting extension from filename in Python
Is there a function to extract the extension from a filename?</p>

答:
For funsies... just collect the extensions in a dict, and track all of them in a folder.  Then just pull the extensions you want. </p>

```<code>import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)
</code>```

OwnerDisplayName: xktybot

LastEditorDisplayName: nosklo

Body:
For funsies... just collect the extensions in a dict, and track all of them in a folder.  Then just pull the extensions you want.

import os

search = {}

for f in os.listdir(os.getcwd()):
    fn, fe = os.path.splitext(f)
    try:
        search[fe].append(f)
    except:
        search[fe]=[f,]

extensions = ('.png','.jpg')
for ex in extensions:
    found = search.get(ex,'')
    if found:
        print(found)


问:
How to control interval in rxjs? - inactivate timer in angular
I try to implement a kind of "session timer" in angular app. It will logout user when (s)he don't click any key in a specified period. Everything goes ok, until first logout. After 2nd login, reset method of timer don't work. The user is logged out after the specified time, regardless of the action performed.

I made a demo on StackBlitz

Here is code of service:

```<code>@Injectable({
  providedIn: "root"
})
export class SessionTimerService {
  private readonly sessionTimer: Observable<number> = interval(10000); // 10 sec
  private sessionTimerController: Subject<void>;

  public constructor(private readonly router: Router) {}

  public initTimer(): void {
    this.sessionTimerController = new Subject<void>();
    this.sessionTimer
      .pipe(
        take(1),
        takeUntil(this.sessionTimerController)
      )
      .subscribe(() => {
        console.log("logout");
        this.sessionTimerController.next();
        this.sessionTimerController.complete();
        this.router.navigate(["/login"]);
      });
  }

  public resetTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("reset");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();

      this.initTimer();
    }
  }

  public stopTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("stop");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();
    }
  }
}
</code>```

window.relaod() is not good answer on this problem.

答:
RXJS is powerful and you can unsubscribe an on going event so I manged to do just that in this solution

https://stackblitz.com/edit/angular-session-timer-jpkxnj

here is the service code

@Injectable({
  providedIn: "root"
})
export class SessionTimerService {

  savedSub: Subscription;

  public constructor(private readonly router: Router) {

  }

  public initTimer(): void {

    this.savedSub = of(true).pipe(delay(5000))
    .subscribe(() => {
      this.router.navigate(['login']);
      this.savedSub.unsubscribe();
    })

  }

  public resetTimer(): void {
    if(this.savedSub){
    this.savedSub.unsubscribe();
    this.savedSub = null;
    this.initTimer();
    }
  }

  onDestroy(){
    if(this.savedSub){
    this.savedSub.unsubscribe();
    this.savedSub = null;
    }
  }

}

```

<p>initTimer will wait 5 seconds.. when no thing can stop it it will logout
when the subscription reference you have is <code>unsubscriped</code> is gone and it wont fire..
on mouse click we will <code>unsubscribe</code> it and re run the timer from the start on.</p>

<p>but you need to unsubscribe or <code>null</code> the value of the subscription if the no one stopped the timer.. and that's why we made <code>onDestroy</code> to be called from the main component when <code>ngOnDestroy</code> work</p>

<pre class="lang-js prettyprint-override"><code>  ngOnDestroy(){
    this.sessionTimer.onDestroy();
  }
</code>```

hope that can solve your problem.

Body:
I try to implement a kind of "session timer" in angular app. It will logout user when (s)he don't click any key in a specified period. Everything goes ok, until first logout. After 2nd login, reset method of timer don't work. The user is logged out after the specified time, regardless of the action performed.

I made a demo on StackBlitz

Here is code of service:

@Injectable({
  providedIn: "root"
})
export class SessionTimerService {
  private readonly sessionTimer: Observable<number> = interval(10000); // 10 sec
  private sessionTimerController: Subject<void>;

  public constructor(private readonly router: Router) {}

  public initTimer(): void {
    this.sessionTimerController = new Subject<void>();
    this.sessionTimer
      .pipe(
        take(1),
        takeUntil(this.sessionTimerController)
      )
      .subscribe(() => {
        console.log("logout");
        this.sessionTimerController.next();
        this.sessionTimerController.complete();
        this.router.navigate(["/login"]);
      });
  }

  public resetTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("reset");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();

      this.initTimer();
    }
  }

  public stopTimer(): void {
    if (this.sessionTimerController && !this.sessionTimerController.closed) {
      console.log("stop");
      this.sessionTimerController.next();
      this.sessionTimerController.complete();
    }
  }
}

window.relaod() is not good answer on this problem.

Body:
RXJS is powerful and you can unsubscribe an on going event so I manged to do just that in this solution

https://stackblitz.com/edit/angular-session-timer-jpkxnj

here is the service code

@Injectable({
  providedIn: "root"
})
export class SessionTimerService {

  savedSub: Subscription;

  public constructor(private readonly router: Router) {

  }

  public initTimer(): void {

    this.savedSub = of(true).pipe(delay(5000))
    .subscribe(() => {
      this.router.navigate(['login']);
      this.savedSub.unsubscribe();
    })

  }

  public resetTimer(): void {
    if(this.savedSub){
    this.savedSub.unsubscribe();
    this.savedSub = null;
    this.initTimer();
    }
  }

  onDestroy(){
    if(this.savedSub){
    this.savedSub.unsubscribe();
    this.savedSub = null;
    }
  }

}

initTimer will wait 5 seconds.. when no thing can stop it it will logout
when the subscription reference you have is unsubscriped is gone and it wont fire..
on mouse click we will unsubscribe it and re run the timer from the start on.

but you need to unsubscribe or null the value of the subscription if the no one stopped the timer.. and that's why we made onDestroy to be called from the main component when ngOnDestroy work

  ngOnDestroy(){
    this.sessionTimer.onDestroy();
  }

hope that can solve your problem.


问:
Warning: Invalid argument supplied for foreach() on filter
I have a column where I'm pulling in objects from Recipe and getting the names back, but some posts don't have 'required' authors yet and I'm getting a debug error back - Is it possible to set a 'No authors available' echo if there are no array/objects being returned?

Here is the code:

```<code>add_action('manage_post_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe))
            {
                foreach ($recipe->get_authors() as $profile) {
                    $arr[] = '<a href="' . $profile->get_url() . '">' . $profile->get_name() . '</a>';
                }
                echo implode($arr, ', ');
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);
</code>```

Here in the screenshot below, you can see my first post has authors, but the second post doesn't have them set yet.

var_dump(is_object($recipe)) returns true for the first post.

Could someone tell me what I might be doing wrong?

```<code>public function set_authors($authors)
{
    $profiles = [];

    foreach ($authors as $author) {
        $profiles[] = Profile::init($author);
    }

    $this->authors = $profiles;
}

public function get_authors()
{
    return $this->authors;
}
</code>```

答:
You must Check on
$recipe->get_authors()

And not on $recipe

I can understand that $recipe is an object but $recipe->get_authors() is the array that you use on foreach.

If so you have to check if $recipe->get_authors() is an array before your foreach

Body:
I have a column where I'm pulling in objects from Recipe and getting the names back, but some posts don't have 'required' authors yet and I'm getting a debug error back - Is it possible to set a 'No authors available' echo if there are no array/objects being returned?

Here is the code:

add_action('manage_post_posts_custom_column', function($column, $post_id) {
    switch ($column) {
        case 'authors':

            $recipe = Recipe::init($post_id);

            if (is_array($recipe) || is_object($recipe))
            {
                foreach ($recipe->get_authors() as $profile) {
                    $arr[] = 'get_url() . '">' . $profile->get_name() . '';
                }
                echo implode($arr, ', ');
                break;
            } else {
                echo 'No authors';
            }
    }
}, 10, 3);

Here in the screenshot below, you can see my first post has authors, but the second post doesn't have them set yet.

var_dump(is_object($recipe)) returns true for the first post.

Could someone tell me what I might be doing wrong?

public function set_authors($authors)
{
    $profiles = [];

    foreach ($authors as $author) {
        $profiles[] = Profile::init($author);
    }

    $this->authors = $profiles;
}

public function get_authors()
{
    return $this->authors;
}


问:
Azure AD Connect - Unset Domain as Federated
How can I unset the 'Federated' option for a Azure AD Connect domain?

答:
The display the in the Azure portal is a display of the current configuration.  If you need to make configuration changes to any of the synchronized domains or their federation, you will need to perform that within the AD Connect tool.

MS Docs:  Manage and customize Active Directory Federation Services by using Azure AD Connect


问:
SQL insert choice of column name dependant on select value
Hope the title is a reasonable description.

I have 2 tables in a db (sqlite).

```<code>CREATE TABLE files (
  name TEXT,
  sha256 TEXT,
  fsno INT
);

CREATE TABLE sha256 (
  sha256 TEXT,
  fs1 INT,
  fs2 INT,
  fs3 INT,
  fs4 INT
);
</code>```

files.fsno ranges from 2 to 5.

I am doing:

```<code>INSERT OR IGNORE INTO sha256sums (sha256)  select sha256 from files;
</code>```

Then:

```<code>update sha256sums set fs2 = 1 where sha256 in (select sha256 from files where fsno = 2);
update sha256sums set fs3 = 1 where sha256 in (select sha256 from files where fsno = 3);
update sha256sums set fs4 = 1 where sha256 in (select sha256 from files where fsno = 4);
update sha256sums set fs5 = 1 where sha256 in (select sha256 from files where fsno = 5);
</code>```

Is there a way to replace these 4 updates with something in the INSERT OR IGNORE? Something like:

```<code>INSERT OR IGNORE INTO sha256sums (sha256, fs2, fs3, fs4, fs5)
select
sha256, fsno==2?1:0, fsno==3?1:0, fsno==4?1:0, fsno==5?1:0
from files;
</code>```

The DB is Sqlite.

TIA, Pete

答:
You can use a case expression:

```<code>INSERT OR IGNORE INTO sha256sums (sha256, fs2, fn3, fs4, fsno5)
    select sha256,
           (case when fsno = 2 then 1 end),
           (case when fsno = 3 then 1 end),
           (case when fsno = 4 then 1 end),
           (case when fsno = 5 then 1 end)
    from files;
</code>```

This assumes that that sha256 are not duplicated in the table -- that is, that you only want the new records to change.

Body:
Hope the title is a reasonable description.

I have 2 tables in a db (sqlite).

CREATE TABLE files (
  name TEXT,
  sha256 TEXT,
  fsno INT
);

CREATE TABLE sha256 (
  sha256 TEXT,
  fs1 INT,
  fs2 INT,
  fs3 INT,
  fs4 INT
);

files.fsno ranges from 2 to 5.

I am doing:

INSERT OR IGNORE INTO sha256sums (sha256)  select sha256 from files;

Then:

update sha256sums set fs2 = 1 where sha256 in (select sha256 from files where fsno = 2);
update sha256sums set fs3 = 1 where sha256 in (select sha256 from files where fsno = 3);
update sha256sums set fs4 = 1 where sha256 in (select sha256 from files where fsno = 4);
update sha256sums set fs5 = 1 where sha256 in (select sha256 from files where fsno = 5);

Is there a way to replace these 4 updates with something in the INSERT OR IGNORE? Something like:

INSERT OR IGNORE INTO sha256sums (sha256, fs2, fs3, fs4, fs5)
select
sha256, fsno==2?1:0, fsno==3?1:0, fsno==4?1:0, fsno==5?1:0
from files;

The DB is Sqlite.

TIA, Pete

Body:
You can use a case expression:

INSERT OR IGNORE INTO sha256sums (sha256, fs2, fn3, fs4, fsno5)
    select sha256,
           (case when fsno = 2 then 1 end),
           (case when fsno = 3 then 1 end),
           (case when fsno = 4 then 1 end),
           (case when fsno = 5 then 1 end)
    from files;

This assumes that that sha256 are not duplicated in the table -- that is, that you only want the new records to change.


问:
How to ignore safe area for a background with a linear gradient in swiftUI?
With SwiftUI, I know how to set a background with a simple color all over screen. So only background ignore the safe area. But when I want to do this with a linear gradient, I don't know do this.

My view with a simple background :

```<code>import SwiftUI

struct Settings : View {
  var body: some View {
    ScrollView {
        VStack {
          Text("Boussole")
            .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
            .multilineTextAlignment(.leading)
            .font(.system(size: 28))
            .padding(.top, 15)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
          Toggle(isOn: .constant(false)) {
            Text("Afficher le vrai nord")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          Toggle(isOn: .constant(true)) {
            Text("Activer la vibration")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          .padding(.bottom, 20)
          Divider()
        }
      .padding(.leading, 25)
      .padding(.trailing, 25)
    }
    .background(Color.gray.edgesIgnoringSafeArea(.all))
  }
}
</code>```

So in this case, the safe area is ignored only for the background.

But how can I do this with this type of background ?

```<code>.background(LinearGradient(gradient: Gradient(colors: [Color(red: 189/255, green: 195/255, blue: 199/255, opacity: 1.0), .white]), startPoint: .topTrailing, endPoint: .bottomLeading), cornerRadius: 0)
</code>```

I don't know how to place .edgesIgnoringSafeArea(.all)

答:
Although this doesn't apply to the OP, in cases where the linear gradient's color changes are strictly vertical (i.e. startPoint is .top and endPoint is .bottom), then as an alternative to Mojtaba's solution, you can add a second (and third) .background using the Colors at the top and bottom of your gradient.

So,

```<code>.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom), cornerRadius: 0)
</code>```

Could become,

```<code>.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom), cornerRadius: 0)
.background(Color(.red).edgesIgnoringSafeArea(.top))
.background(Color(.white).edgesIgnoringSafeArea(.bottom))
</code>```

This will work in portrait mode, not sure about landscape though!

Body:
With SwiftUI, I know how to set a background with a simple color all over screen. So only background ignore the safe area. But when I want to do this with a linear gradient, I don't know do this.

My view with a simple background :

import SwiftUI

struct Settings : View {
  var body: some View {
    ScrollView {
        VStack {
          Text("Boussole")
            .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
            .multilineTextAlignment(.leading)
            .font(.system(size: 28))
            .padding(.top, 15)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
          Toggle(isOn: .constant(false)) {
            Text("Afficher le vrai nord")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          Toggle(isOn: .constant(true)) {
            Text("Activer la vibration")
              .font(.system(size: 20))
              .color(Color(red: 52/255, green: 73/255, blue: 94/255, opacity: 1.0))
          }
          .padding(.top, 10)
          .padding(.bottom, 20)
          Divider()
        }
      .padding(.leading, 25)
      .padding(.trailing, 25)
    }
    .background(Color.gray.edgesIgnoringSafeArea(.all))
  }
}

So in this case, the safe area is ignored only for the background.

But how can I do this with this type of background ?

.background(LinearGradient(gradient: Gradient(colors: [Color(red: 189/255, green: 195/255, blue: 199/255, opacity: 1.0), .white]), startPoint: .topTrailing, endPoint: .bottomLeading), cornerRadius: 0)

I don't know how to place .edgesIgnoringSafeArea(.all)

Body:
Although this doesn't apply to the OP, in cases where the linear gradient's color changes are strictly vertical (i.e. startPoint is .top and endPoint is .bottom), then as an alternative to Mojtaba's solution, you can add a second (and third) .background using the Colors at the top and bottom of your gradient.

So,

.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom), cornerRadius: 0)

Could become,

.background(LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom), cornerRadius: 0)
.background(Color(.red).edgesIgnoringSafeArea(.top))
.background(Color(.white).edgesIgnoringSafeArea(.bottom))

This will work in portrait mode, not sure about landscape though!


问:
Cloning a DOM node list and accessing members are undefined
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul></code>```

答:
querySelectorAll() returns a static (not live) NodeList (not array), but concat() allows another array as parameter value.

Try with Spread syntax:

```<code>var arr2 = [].concat(...arr);
</code>```

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(...arr);
console.log(arr2[1]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul></code>```

Body:
I have a DOM node list arr1 that is being cloned arr2 and I wonder whether it has been cloned properly as both behave differently. I cannot seem to access the members of arr2 as they return undefined.

Why does this happen, and how can it be fixed?

Note that I tried cloning the same array via arr.slice but this errors with Uncaught TypeError: arr.slice is not a function

Thanks for any help here - the code is below:

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(arr);
console.log(arr2[1]); // undefined, & logs twice

test

test

test

test

test

Body:
querySelectorAll() returns a static (not live) NodeList (not array), but concat() allows another array as parameter value.

Try with Spread syntax:

var arr2 = [].concat(...arr);

var arr = document.querySelectorAll('li');
console.log(arr[1]); // works

var arr2 = [].concat(...arr);
console.log(arr2[1]);

<ul>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
  <li>test</li>
</ul>


问:
How to check if two properties are equal to another object's properties in Joi?
Is it possible to make Joi check if source.listId === destination.listId && source.index === destination.index then return an error?

My example:

const schema = Joi.object({
  source: Joi.object().keys({
    listId: Joi.string()
      .length(24)
      .required()
      .when('...destination.index', {
        is: Joi.equal(Joi.ref('index')),
        then: Joi.disallow(Joi.ref('...destination.listId'))
      }),
    index: Joi.number()
      .integer()
      .positive()
      .required()
  }),
  destination: Joi.object().keys({
    listId: Joi.string()
      .length(24)
      .required(),
    index: Joi.number()
      .integer()
      .positive()
      .required()
  })
});
```

答:
SOLVED

I had to validate source.index property with when as well:

const schema = Joi.object({
  source: Joi.object().keys({
    listId: Joi.string()
      .length(24)
      .required()
      .when('...destination.index', {
        is: Joi.equal(Joi.ref('index')),
        then: Joi.disallow(Joi.ref('...destination.listId'))
      }),
    index: Joi.number()
      .integer()
      .positive()
      .required()
      .when('...destination.listId', {
        is: Joi.equal(Joi.ref('listId')),
        then: Joi.disallow(Joi.ref('...destination.index'))
      })
  }),
  destination: Joi.object().keys({
    listId: Joi.string()
      .length(24)
      .required(),
    index: Joi.number()
      .integer()
      .positive()
      .required()
  })
});
```


问:
Call a function from within another function in Python without using class
I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.

Here's an example:

Make a function shout(word) that accepts a string and returns that string in capital letters.

```<code>def shout(word):

    return word.upper()

shout("bob")
</code>```

Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.

```<code>def introduce():

    name = input("What's your name: ")
    print(f"Hello {name}")

introduce()
</code>```

My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:

```<code>What's your name?
Bob

HELLO BOB
</code>```

Thank you for your time and answers.

答:
Just call function shout.

```<code>def shout(word):
    return word.upper()

def introduce():

    name = input("What's your name: ")
    name = shout(name)
    print(f"Hello {name}")

introduce()

</code>```

Body:
I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.

Here's an example:

Make a function shout(word) that accepts a string and returns that string in capital letters.

def shout(word):

    return word.upper()

shout("bob")

Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.

def introduce():

    name = input("What's your name: ")
    print(f"Hello {name}")

introduce()

My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:

What's your name?
Bob

HELLO BOB

Thank you for your time and answers.

Body:
Just call function shout.

def shout(word):
    return word.upper()

def introduce():

    name = input("What's your name: ")
    name = shout(name)
    print(f"Hello {name}")

introduce()


问:
Returning header to STOMP client frame object after handshake
Currently, when successfully connecting to an endpoint, I am passing a custom token (called access-token) back to the client via a response header.  This header is being set correctly and I can verify the header by analyzing the HTTP response.

However, when trying to get the header from the frame object the header is not set (see the JavaScript below):

```<code> stompClient.connect(headers,
                function(frame) {
                    console.log('=========================================');
                    console.log(frame.headers['access-token']);
                    console.log(frame);
                    console.log('=========================================');
                    stompClient.subscribe('/topic/test', function(stuff){
                       console.debug(stuff);
                    });
                },
                function(error) {
                    //error code
                }
        );
</code>```

I am setting the response header as follows on the server:

```<code>public class HttpSessionHandshakeInterceptorImpl extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
        ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {

        response.getHeaders().set("access-token", token);

         return super.beforeHandshake(request, response, wsHandler, attributes);
</code>```

I stripped out some code and can confirm that the interceptor is being called.  I take it that this is not the correct way to pass a header value back to the client when the connect function is called?  I can't seem to find any documentation on how to accomplish this.  Thanks.

答:
I'm afraid this is not possible without a major hack. The issue is, the headers are completely rebuilt AFTER the ChannelInterceptors are called. See method StompSubProtocolHandler.convertConnectAcktoStompConnected

The method StompSubProtocolHandler.handleMessageToClient will also add a few headers depending on the type of message, for example by calling afterStompSessionConnected which sets the header "user-name" if the authentication is done.

I've tried adding headers as well but I'm about to give up... My guess is that the people who wrote the STOMP implementation in Spring wanted to strictly respect the specifications

Body:
Currently, when successfully connecting to an endpoint, I am passing a custom token (called access-token) back to the client via a response header.  This header is being set correctly and I can verify the header by analyzing the HTTP response.

However, when trying to get the header from the frame object the header is not set (see the JavaScript below):

 stompClient.connect(headers,
                function(frame) {
                    console.log('=========================================');
                    console.log(frame.headers['access-token']);
                    console.log(frame);
                    console.log('=========================================');
                    stompClient.subscribe('/topic/test', function(stuff){
                       console.debug(stuff);
                    });
                },
                function(error) {
                    //error code
                }
        );

I am setting the response header as follows on the server:

public class HttpSessionHandshakeInterceptorImpl extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
        ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {

        response.getHeaders().set("access-token", token);

         return super.beforeHandshake(request, response, wsHandler, attributes);

I stripped out some code and can confirm that the interceptor is being called.  I take it that this is not the correct way to pass a header value back to the client when the connect function is called?  I can't seem to find any documentation on how to accomplish this.  Thanks.


问:
How to have env specific log4j2 config for spring boot2 application
Currently spring boot seems to support only classpath based logging configuration.

It also ignores any configuration passed as vm argument as follows.

```<code>-Dlog4j.configurationFile=/opt/xyz/log4j2-prod.xml
</code>```

How can we have different log4j2 configuration based on different environment, considering classpath for all environment remains same.

答: What about set the properties: logging.config=classpath:log4j2-dev-spring.xml in each application-{profile}.properties that you have. Can use like this too: logging.config=${ENV_VAR}

Body:
Currently spring boot seems to support only classpath based logging configuration.

It also ignores any configuration passed as vm argument as follows.

-Dlog4j.configurationFile=/opt/xyz/log4j2-prod.xml

How can we have different log4j2 configuration based on different environment, considering classpath for all environment remains same.


问:
Getting correct absolute path in library used by web project
I have an asp.net mvc project that uses some search methods in a seperate library.
This library needs to know the location of my lucene index files.

```<code>    private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];

    public static ColorList SearchColors(Query query) {
        return new ColorList(
            new IndexSearcher(Path.GetFullPath(lucenePath)),
            query);
    }
</code>```

This correctly reads my configured lucenePath from the web.config's application key node.
But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.

--Conclusion--

If you want to go full-out, tvanfosson's answer is probably for you.

I, however, kept it a little more brain dead by using the following:

```<code>Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
    ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));
</code>```

This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.

答: Since you are referencing this from a separate library, you might have to jump through a bunch of hoops to get access to the HttpServerUtitity or introduce some coupling to classes that are difficult to mock.  You might want to consider having a single configuration class that loads properties from the web configuration that gets injected into your library via constructor/setter.  To make it easier to test against, you could define an interface that could be mocked in your unit tests and have it implement that.  The configuration class could use the HttpServerUtility to obtain the absolute path and store it internally to be reused.</p>

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5

Body:
I have an asp.net mvc project that uses some search methods in a seperate library.
This library needs to know the location of my lucene index files.

    private static string lucenePath = ConfigurationManager.AppSettings["lucenePath"];

    public static ColorList SearchColors(Query query) {
        return new ColorList(
            new IndexSearcher(Path.GetFullPath(lucenePath)),
            query);
    }

This correctly reads my configured lucenePath from the web.config's application key node.
But how can I get the correct full path from this relative path? Path.GetFullPath gives me a completely incorrect path.

--Conclusion--

If you want to go full-out, tvanfosson's answer is probably for you.

I, however, kept it a little more brain dead by using the following:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
    ConfigurationManager.AppSettings["luceneIndex"].TrimStart('\\'));

This will look in the caller's app.config for an appkey called "path" and combine its value to the caller's path. The TrimStart() makes sure that the config file can both contain a leading \ or not.

LastEditorDisplayName: boris callens

OwnerDisplayName: tvanfosson


问:
How to bypass security dialog when the JNLP file is run
I have created a Java Web Start application. I have signed my Jar with a self-signed certificate. Also the web-server who serves the Jar and JNLP file is trusted with its certificate.

When the JNLP file is run, it opens following dialog. I wish to know if there is any way to make not to show this dialog and open the application window directly as soon as it is run.

When I googled, I couldn't find any sources referring this issue.

Looking for your help. Thanks a lot.

答:
I beg to differ from @Andrew Thompson's anwser above, but oracle's documentation has specified how to avoid these messages.

Grant AllPermissions in the Java policy file located at
  ${user.home}/.java.policy, or point to any Java policy file which has
  AllPermissions in the $(JRE_HOME)/lib/security/java.security file.
  Permissions can be granted to all applications or restricted to a
  particular URL. See Default Policy Implementation and Policy File
  Syntax for more details on .java.policy.


答:
You call functions from inside other functions the same way you call them from outside functions. Put the function name first, put the argument(s) in parentheses.</p>

```<code>def introduce():

    name = input("What's your name: ")
    print(shout(f"Hello {name}"))
</code>```

Title: Call a function from within another function in Python without using class

Body:
You call functions from inside other functions the same way you call them from outside functions. Put the function name first, put the argument(s) in parentheses.

def introduce():

    name = input("What's your name: ")
    print(shout(f"Hello {name}"))


问:
Why is my SSIS toolbox empty in Visual Studio 2019 community?
I installed Visual Studio 2019 Community and then installed data tools. I can open an Integration Services project but when I look at the SSIS Tooolbox, it's empty.

How do I fix this?

答: I had a project from 2017 and the toolbar would not open when I opened the project. I had to create a new empty project. Then go back and open the 2017 project. Then the toolbar appeared.</p>


问:
How to unit test a call to a function called when subscribing to an ActivatedRoute data?
I want to unit test the ngOnInit() method of a component in my Angular app. The ngOnInit() method subscribes to the ActivatedRoute data and calls a function inside the subscribe method. Here's the code of the method:

component.ts

```<code>ngOnInit() {
  this.route.data.subscribe(data => this.store.patchState(data));
}
</code>```

Here's my test :

component.spec.ts

```<code>beforeEach(() => {
    fixture = TestBed.createComponent(xyzComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it('#ngOnInit should call patchState', async(() => {

    const spy = spyOn(store, 'patchState');

    // When
    component.ngOnInit();

    fixture.detectChanges();

    // Then
    expect(spy.calls.count()).toBe(1, 'patchState has been called once.');

  }));
</code>```

However when I run the test I get an error telling me that 'Expected spy patchState was never called.'

I believe my problem is coming from the asynchronous nature of the test but I can't figure out why it won't work.

What am I doing wrong here ?

Thanks !

答:
Change the subscription to :

```<code>this.route.data.subscribe(data => {
                                   console.log('in route subscription);
                                   this.store.patchState(data)
                         });
</code>```

If you don't see the console.log('in route subscription'), it seems that you may not be mocking the activatedRoute correctly.

Try this:

```<code>describe('xyzComponent', () => {
  let store: Store<...>; // for you to fill out
  let component: xyzComponent;
  let fixture: ComponentFixture<xyzComponent>;
  let data$ = new BehaviorSubject({ x: 1 }); // mock data for activatedRoute

  beforeEach(async() => {
    TestBed.configureTestingModule({
      imports: [ StoreModule.forRoot(....) ], // for you to fill out
      declarations: [ XYZComponent ],
      providers: [
        { provide: ActivatedRoute, useValue: { data: data$ } },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    store = TestBed.get(store);
    spyOn(store, 'patchState').and.callThrough(); // and.callThrough() is optional, do you want it to HAVE both a spy and call the actual implementation?
    fixture = TestBed.createComponent(xyzComponent);
    component = fixture.componentInstance;
    fixture.detectChanges(); // this fixture.detectChanges() will call `ngOnInit` for us, so we don't have to manually call it
  });

  it('ngOnInit should call patchState', () => {
    expect(store.patchState).toHaveBeenCalledWith({ x: 1 });
  });
});
</code>```

That should hopefully get you unblocked. You can also change route.data in later tests and see how it would react by doing data.next$({....}) your future value.

Body:
I want to unit test the ngOnInit() method of a component in my Angular app. The ngOnInit() method subscribes to the ActivatedRoute data and calls a function inside the subscribe method. Here's the code of the method:

component.ts

ngOnInit() {
  this.route.data.subscribe(data => this.store.patchState(data));
}

Here's my test :

component.spec.ts

beforeEach(() => {
    fixture = TestBed.createComponent(xyzComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it('#ngOnInit should call patchState', async(() => {

    const spy = spyOn(store, 'patchState');

    // When
    component.ngOnInit();

    fixture.detectChanges();

    // Then
    expect(spy.calls.count()).toBe(1, 'patchState has been called once.');

  }));

However when I run the test I get an error telling me that 'Expected spy patchState was never called.'

I believe my problem is coming from the asynchronous nature of the test but I can't figure out why it won't work.

What am I doing wrong here ?

Thanks !

Body:
Change the subscription to :

this.route.data.subscribe(data => {
                                   console.log('in route subscription);
                                   this.store.patchState(data)
                         });

If you don't see the console.log('in route subscription'), it seems that you may not be mocking the activatedRoute correctly.

Try this:

describe('xyzComponent', () => {
  let store: Store<...>; // for you to fill out
  let component: xyzComponent;
  let fixture: ComponentFixture<xyzComponent>;
  let data$ = new BehaviorSubject({ x: 1 }); // mock data for activatedRoute

  beforeEach(async() => {
    TestBed.configureTestingModule({
      imports: [ StoreModule.forRoot(....) ], // for you to fill out
      declarations: [ XYZComponent ],
      providers: [
        { provide: ActivatedRoute, useValue: { data: data$ } },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    store = TestBed.get(store);
    spyOn(store, 'patchState').and.callThrough(); // and.callThrough() is optional, do you want it to HAVE both a spy and call the actual implementation?
    fixture = TestBed.createComponent(xyzComponent);
    component = fixture.componentInstance;
    fixture.detectChanges(); // this fixture.detectChanges() will call `ngOnInit` for us, so we don't have to manually call it
  });

  it('ngOnInit should call patchState', () => {
    expect(store.patchState).toHaveBeenCalledWith({ x: 1 });
  });
});

That should hopefully get you unblocked. You can also change route.data in later tests and see how it would react by doing data.next$({....}) your future value.