问:
Property length does not exist on type Observable <[]> in angular
I have this service in angular which returns transcript

```<code>public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }
</code>```

.ts file

```<code>service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}
</code>```

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

```<code> const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;
</code>```

Any solution to resolve this issue Thanks

答:
You have observable element. You cant check length there. You need to subscribe your element and inside it you should do your process</p>
```<code> this.service.getTranscriptValue().subscribe(el=>{
    for (var i = 0; i < el.length; i++) {
    }
  }) ;
</code>```

Body:
I have this service in angular which returns transcript

public transcript_arr =new ReplaySubject<[]>(1);
public confidence_arr=new ReplaySubject<[]>(1);
getTranscriptValue()
  {
    return this.transcript_arr.pipe(data => {return data;})
  }

getConfidenceValue()
  {
    return this.confidence_arr;
  }

.ts file

service_transcript$: Observable<[]>;

this.service_transcript$=this.service.getTranscriptValue();

 for (var i = 0; i < this.service_transcript$.length; i++) {

 }

 this.http.post(this.baseUrl+'api/auth/post-data', formData).subscribe(response  => {

}

In .ts file i'm using service data for computational purpose then sending it to server but getting
this error :

Property length does not exist on type Observable <[]> in angular
Updated Code:

 const transcript_arr = [];
 const confidence_arr = [];

      this.service.getTranscriptValue().subscribe(el=>{
        for (var i = 0; i < el.length; i++) {
            if(this.hasWhiteSpace(el[i]))
            {
              const arr_transcript = el[i].trim().split(" ");
              for (var j = 0; j < arr_transcript.length; j++) {
                transcript_arr.push(arr_transcript[j].toLowerCase());
                confidence_arr.push(service_confidence[i]);
              }
            }
            else
            {
              transcript_arr.push(el[i].toLowerCase());
              confidence_arr.push(service_confidence[i]);
            }
        }
      }) ;

Any solution to resolve this issue Thanks

Body:
You have observable element. You cant check length there. You need to subscribe your element and inside it you should do your process

 this.service.getTranscriptValue().subscribe(el=>{
    for (var i = 0; i < el.length; i++) {
    }
  }) ;


来源: stackexchange

问:
mutable borrows in a loop

My code:

struct Foo<'a> {
    bytes: &'a mut [u8],
}

impl<'a> Foo<'a> {
    fn bar<'b>(&'b mut self) {
        self.bytes = &mut self.bytes[1..];
    }
}

fn baz<'a, 'b>(foo: &'b mut Foo<'a>) {
    println!("baz!");

    for _ in 0..3 {
        foo.bar();
    }
}
```
<p>Also here in a Rust Playground.</p>
<p>This results in the following error traceback:</p>
```   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'b` as defined here...
  --> src/main.rs:11:12
   |
11 |     fn bar<'b>(&'b mut self) {
   |            ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:10:6
   |
10 | impl<'a> Foo<'a> {
   |      ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:22
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                      ^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error
```

Goal

I'm looking to change the function signatures of bar / baz to get this to compile. My understanding was that I needed to specify lifetime bounds on 'a & 'b and it would work, but I get different errors for both 'b: 'a and 'a: 'b in either/both functions.

I've also looked through ~10 other "mutable borrow in loop" questions, but I don't understand the answers well enough to apply them to my problem, so even if this is a duplicate I'd appreciate an answer relevant to this toy example specifically.

Any help is appreciated!

答:
@vikram2784's solution works, but can be expressed a bit more concisely by only replacing bytes, not the entire Foo:

```<code>impl<'a> Foo<'a> {
    fn bar(&mut self) {
        let tmp = &mut [][..];
        let bytes = std::mem::replace(&mut self.bytes, tmp);
        self.bytes = &mut bytes[1..];
    }
}
</code>```

This pattern is also easier to use if Foo contains some additional fields that don't have obvious default values.

One thing to note about this kind of solution: If the bytes[1..] panics, the empty temporary will be left in place. Here, the only reason for a panic I can think of is bytes being empty, so it won't matter, but depending on the situation, you may get bitten by it.

ContentLicense: CC BY-SA 4.0

Title: mutable borrows in a loop

Body:
My code:

struct Foo<'a> {
    bytes: &'a mut [u8],
}

impl<'a> Foo<'a> {
    fn bar<'b>(&'b mut self) {
        self.bytes = &mut self.bytes[1..];
    }
}

fn baz<'a, 'b>(foo: &'b mut Foo<'a>) {
    println!("baz!");

    for _ in 0..3 {
        foo.bar();
    }
}

Also <a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&code=%23!%5Ballow(unused)%5D%0Afn%20main()%20%7B%0Ause%20std%3A%3Aany%3A%3AAny%3B%0Ause%20std%3A%3Aio%3A%3ARead%3B%0A%0Astruct%20Foo%3C%27a%3E%20%7B%0A%20%20%20%20bytes%3A%20%26%27a%20mut%20%5Bu8%5D%2C%0A%7D%0A%0Aimpl%3C%27a%3E%20Foo%3C%27a%3E%20%7B%0A%20%20%20%20fn%20bar%3C%27b%3E(%26%27b%20mut%20self)%20%7B%0A%20%20%20%20%20%20%20%20self.bytes%20%3D%20%26mut%20self.bytes%5B1..%5D%3B%0A%20%20%20%20%7D%0A%7D%0A%0Afn%20baz%3C%27a%2C%20%27b%3E(foo%3A%20%26%27b%20mut%20Foo%3C%27a%3E)%20%7B%0A%20%20%20%20println!(%22baz!%22)%3B%0A%20%20%20%20%0A%20%20%20%20for%20_%20in%200..3%20%7B%0A%20%20%20%20%20%20%20%20foo.bar()%3B%0A%20%20%20%20%7D%0A%7D%0A%0A%7D" rel="nofollow noreferrer">here in a Rust Playground.

This results in the following error traceback:

   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'b` as defined here...
  --> src/main.rs:11:12
   |
11 |     fn bar<'b>(&'b mut self) {
   |            ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:27
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                           ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
  --> src/main.rs:10:6
   |
10 | impl<'a> Foo<'a> {
   |      ^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:12:22
   |
12 |         self.bytes = &mut self.bytes[1..];
   |                      ^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error

Goal

I'm looking to change the function signatures of bar / baz to get this to compile. My understanding was that I needed to specify lifetime bounds on 'a & 'b and it would work, but I get different errors for both 'b: 'a and 'a: 'b in either/both functions.

I've also looked through ~10 other "mutable borrow in loop" questions, but I don't understand the answers well enough to apply them to my problem, so even if this is a duplicate I'd appreciate an answer relevant to this toy example specifically.

Any help is appreciated!

Body:
@vikram2784's solution works, but can be expressed a bit more concisely by only replacing bytes, not the entire Foo:

impl<'a> Foo<'a> {
    fn bar(&mut self) {
        let tmp = &mut [][..];
        let bytes = std::mem::replace(&mut self.bytes, tmp);
        self.bytes = &mut bytes[1..];
    }
}

This pattern is also easier to use if Foo contains some additional fields that don't have obvious default values.

One thing to note about this kind of solution: If the bytes[1..] panics, the empty temporary will be left in place. Here, the only reason for a panic I can think of is bytes being empty, so it won't matter, but depending on the situation, you may get bitten by it.


问:
Replace values from a string if they are present in an array of variables
Having the following array of objects:

```<code>const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];
</code>```

And the input string:

```<code>const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;
</code>```

The function should take as arguments variables and inputString and return the following sting:

```<code>'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'
</code>```

Here is the function so far:

```<code>function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}
</code>```

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?

答:
You could do a recursive call until there are no variables left in the string

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' },
];

const inputString = `Hi, my name is %NAME%', I like %HOBBY%, you can contact me at %EMAIL%`;

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
    output = output.replace(variables[i].name, variables[i].value);
  }
  for (let i = 0; i < variables.length; i++) {
    if (output.includes(variables[i].name)) {
      output = doMagic(variables, output);
    }
  }
  return output;
}

console.log(doMagic(variables, inputString));```

Body:
Having the following array of objects:

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];

And the input string:

const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;

The function should take as arguments variables and inputString and return the following sting:

'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'

Here is the function so far:

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答: I don't think you're assigning the member char * name to anything in your ctors.</p>

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

OwnerDisplayName: drewh


问:
Good XSLT for Python - lxml struggles
I'm trying to transform XHTML to text using a user-defined XSLT, which is the following:

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://www.w3.org/1999/xhtml">

<xsl:output method="text"/>

<xsl:template match="/html">
Reading document entitled <xsl:value-of select="head/title"/>.

The top menu for this site has the following options:
<xsl:for-each select="body//ul[@role='menubar']/li/a">
    <xsl:value-of select="."></xsl:value-of> <xsl:text>
</xsl:text>
</xsl:for-each>

Now let's read the main part of the page.
<xsl:for-each select="body//main[@class='container']//(h1 | h2 | h3 | h4 | p | ul/li/a)">
    <xsl:value-of select="normalize-space(.)"/><xsl:text>
</xsl:text><xsl:text>
</xsl:text>
</xsl:for-each>

The footer menu for this site has the following options:
<xsl:for-each select="body//footer[@id='wb-info']//ul/li/a">
    <xsl:value-of select="."></xsl:value-of> <xsl:text>
</xsl:text>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>
</code>```

When I test in http://xsltransform.net/, applying it a typical HTML, the output is as expected.

I test the same XSLT against the same XHTML using the following Python code:

```<code>import lxml.etree as ET

html = ET.parse("../fixed_html/about.html")
xslt = ET.parse("../templates/generic.xslt")
transform = ET.XSLT(xslt)
res = transform(html)
print(res)
</code>```

I get the following error:

lxml.etree.XSLTParseError: xsl:for-each : could not compile select expression 'body//main[@class='container']//(h1 | h2 | h3 | h4 | p | ul/li/a)'

My first thought is that lxml has limitations. It can't handle valid XSLT. I'm hoping that's not the case, and I just failed to setup the code correctly.

Any issues with the Python code? Can I process the XSLT above in Python some other way?

答:
XSLT 2 or 3 for Python is supported by Saxonica's SaxonC 11.1 release, done this month, see details at https://www.saxonica.com/download/c.xml and https://www.saxonica.com/saxon-c/documentation11/index.html#!starting.

At the current stage, you need to compile/build the Python module on your own after downloading the source code and the library modules of SaxonC 11.1.

Title: Good XSLT for Python - lxml struggles

Body:
I'm trying to transform XHTML to text using a user-defined XSLT, which is the following:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://www.w3.org/1999/xhtml">

<xsl:output method="text"/>

<xsl:template match="/html">
Reading document entitled <xsl:value-of select="head/title"/>.

The top menu for this site has the following options:
<xsl:for-each select="body//ul[@role='menubar']/li/a">
    <xsl:value-of select="."></xsl:value-of> <xsl:text>
</xsl:text>
</xsl:for-each>

Now let's read the main part of the page.
<xsl:for-each select="body//main[@class='container']//(h1 | h2 | h3 | h4 | p | ul/li/a)">
    <xsl:value-of select="normalize-space(.)"/><xsl:text>
</xsl:text><xsl:text>
</xsl:text>
</xsl:for-each>

The footer menu for this site has the following options:
<xsl:for-each select="body//footer[@id='wb-info']//ul/li/a">
    <xsl:value-of select="."></xsl:value-of> <xsl:text>
</xsl:text>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

When I test in http://xsltransform.net/, applying it a typical HTML, the output is as expected.

I test the same XSLT against the same XHTML using the following Python code:

import lxml.etree as ET

html = ET.parse("../fixed_html/about.html")
xslt = ET.parse("../templates/generic.xslt")
transform = ET.XSLT(xslt)
res = transform(html)
print(res)

I get the following error:

lxml.etree.XSLTParseError: xsl:for-each : could not compile select expression 'body//main[@class='container']//(h1 | h2 | h3 | h4 | p | ul/li/a)'

My first thought is that lxml has limitations. It can't handle valid XSLT. I'm hoping that's not the case, and I just failed to setup the code correctly.

Any issues with the Python code? Can I process the XSLT above in Python some other way?


问:
Failed to run jetifier React Native
I tried to run react-native run-android and I got this error.</p>

```<code>info Running jetifier to migrate libraries to AndroidX. You can disable
    it using "--no-jetifier" flag.
    error Failed to run jetifier. Run CLI with --verbose flag for more details.
    Error: spawnSync C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\jetifier\bin\jetify ENOENT
    at Object.spawnSync (internal/child_process.js:1002:20)
    at spawnSync (child_process.js:614:24)
    at execFileSync (child_process.js:642:13)
    at Object.runAndroid [as func] (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:101:41)
    at Command.handleAction (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:160:21)
    at Command.listener (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:315:8)
    at Command.emit (events.js:198:13)
    at Command.parseArgs (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:651:12)
    at Command.parse (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:474:21)
    at setupAndRun (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:210:24)

</code>```

答: If you run npx react-native run-android in android folder. That error will happen.  You need to run-android in the root directory.

Title: Failed to run jetifier React Native

Body:
I tried to run react-native run-android and I got this error.

info Running jetifier to migrate libraries to AndroidX. You can disable
    it using "--no-jetifier" flag.
    error Failed to run jetifier. Run CLI with --verbose flag for more details.
    Error: spawnSync C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\jetifier\bin\jetify ENOENT
    at Object.spawnSync (internal/child_process.js:1002:20)
    at spawnSync (child_process.js:614:24)
    at execFileSync (child_process.js:642:13)
    at Object.runAndroid [as func] (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:101:41)
    at Command.handleAction (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:160:21)
    at Command.listener (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:315:8)
    at Command.emit (events.js:198:13)
    at Command.parseArgs (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:651:12)
    at Command.parse (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\commander\index.js:474:21)
    at setupAndRun (C:\Users\JayK\Desktop\React\AwesomeProject\node_modules\@react-native-community\cli\build\cliEntry.js:210:24)


问:
How can I have Perl take input from STDIN one character at a time?
I am somewhat a beginner at Perl (compared to people here). I know enough to be able to write programs to do many things with through the command prompt. At one point, I decided to write a command prompt game that constructed a maze and let me solve it.  Besides quality graphics, the only thing that it was missing was the ability for me to use the WASD controls without pressing enter after every move I made in the maze.

To make my game work, I want to be able to have Perl take a single character as input from STDIN, without requiring me to use something to separate my input, like the default \n. How would I accomplish this?

I have tried searching for a simple answer online and in a book that I have, but I didn't seem to find anything.  I tried setting $/="", but that seemed to bypass all input. I think that there may be a really simple answer to my question, but I am also afraid that it might be impossible.

Also, does $/="" actually bypass input, or does it take input so quickly that it assumes there isn't any input if I'm not already pressing the key?

答:
IO::Prompt is no longer maintained but IO::Prompter
has a nice example (quoted from that site):</p>
```<code>use IO::Prompter;

# This call has no automatically added options...
my $assent = prompt "Do you wish to take the test?", -yn;

{
    use IO::Prompter [-yesno, -single, -style=>'bold'];

    # These three calls all have: -yesno, -single, -style=>'bold' options
    my $ready = prompt 'Are you ready to begin?';
    my $prev  = prompt 'Have you taken this test before?';
    my $hints = prompt 'Do you want hints as we go?';
}

# This call has no automatically added options...
scalar prompt 'Type any key to start...', -single;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
IO::Prompt is no longer maintained but IO::Prompter
has a nice example (quoted from that site):

use IO::Prompter;

# This call has no automatically added options...
my $assent = prompt "Do you wish to take the test?", -yn;

{
    use IO::Prompter [-yesno, -single, -style=>'bold'];

    # These three calls all have: -yesno, -single, -style=>'bold' options
    my $ready = prompt 'Are you ready to begin?';
    my $prev  = prompt 'Have you taken this test before?';
    my $hints = prompt 'Do you want hints as we go?';
}

# This call has no automatically added options...
scalar prompt 'Type any key to start...', -single;


问:
Why doesn't dereferencing a nil pointer in unsafe.Sizeof() cause a panic?
https://go.dev/play/p/X_BH4qGgXHJ

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var i *int
    fmt.Println(unsafe.Sizeof(*i)) // dereference of null pointer i
}

```
<p>Why doesn't this code</p>
<pre class="lang-golang prettyprint-override"><code>unsafe.Sizeof(*i)
</code>```

cause a runtime panic?

答:
Spec: Package unsafe:

Calls to Alignof, Offsetof, and Sizeof are compile-time constant expressions of type uintptr.

These functions are evaluated at compile time, no actual dereferencing happens at runtime.

This is possible because the pointed value is not needed, only information about its type is needed, which does not need dereferencing.

It's also documented at unsafe.Sizeof():

The return value of Sizeof is a Go constant.

Constants in Go are compile-time constants.

Also see Spec: Constants:

A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants.

See similar examples (which without passing them to unsafe.Sizeof() would panic at runtime or block indefinitely, but they work just fine):

```<code>fmt.Println(unsafe.Sizeof(*(*int8)(nil))) // 1, no dereferencing
fmt.Println(unsafe.Sizeof([]int16{}[10])) // 2, no indexing
x := "hi"
fmt.Println(unsafe.Sizeof(x[10]))                          // 1, no indexing
fmt.Println(unsafe.Sizeof(map[interface{}]int{}[[]int{}])) // 8, no indexing
fmt.Println(unsafe.Sizeof((interface{})(nil).(int16)))     // 2, no type assertion
i := 0
fmt.Println(unsafe.Sizeof(i / i)) // 8, no division by 0
i = -1
fmt.Println(unsafe.Sizeof(1 << i))                // 8, no negative shift count
fmt.Println(unsafe.Sizeof(make([]int, i)))        // 24, no negative length
fmt.Println(unsafe.Sizeof((*[1]int)([]int{})))    // 8, no converting to bigger array
fmt.Println(unsafe.Sizeof((func() int32)(nil)())) // 4, no function call
fmt.Println(unsafe.Sizeof(<-(chan int64)(nil)))   // 8, no receiving
var a, b interface{} = []int{}, []int{}
fmt.Println(unsafe.Sizeof(a == b)) // 1, no comparison
</code>```

Try these on the Go Playground.

Body:
https://go.dev/play/p/X_BH4qGgXHJ

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var i *int
    fmt.Println(unsafe.Sizeof(*i)) // dereference of null pointer i
}

Why doesn't this code

unsafe.Sizeof(*i)

cause a runtime panic?

Body:
Spec: Package unsafe:

Calls to Alignof, Offsetof, and Sizeof are compile-time constant expressions of type uintptr.

These functions are evaluated at compile time, no actual dereferencing happens at runtime.

This is possible because the pointed value is not needed, only information about its type is needed, which does not need dereferencing.

It's also documented at unsafe.Sizeof():

The return value of Sizeof is a Go constant.

Constants in Go are compile-time constants.

Also see Spec: Constants:

A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to any value, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants.

See similar examples (which without passing them to unsafe.Sizeof() would panic at runtime or block indefinitely, but they work just fine):

fmt.Println(unsafe.Sizeof(*(*int8)(nil))) // 1, no dereferencing
fmt.Println(unsafe.Sizeof([]int16{}[10])) // 2, no indexing
x := "hi"
fmt.Println(unsafe.Sizeof(x[10]))                          // 1, no indexing
fmt.Println(unsafe.Sizeof(map[interface{}]int{}[[]int{}])) // 8, no indexing
fmt.Println(unsafe.Sizeof((interface{})(nil).(int16)))     // 2, no type assertion
i := 0
fmt.Println(unsafe.Sizeof(i / i)) // 8, no division by 0
i = -1
fmt.Println(unsafe.Sizeof(1 << i))                // 8, no negative shift count
fmt.Println(unsafe.Sizeof(make([]int, i)))        // 24, no negative length
fmt.Println(unsafe.Sizeof((*[1]int)([]int{})))    // 8, no converting to bigger array
fmt.Println(unsafe.Sizeof((func() int32)(nil)())) // 4, no function call
fmt.Println(unsafe.Sizeof(<-(chan int64)(nil)))   // 8, no receiving
var a, b interface{} = []int{}, []int{}
fmt.Println(unsafe.Sizeof(a == b)) // 1, no comparison

Try these on the Go Playground.


问:
How to run useEffect before render for authentication
I have reading component which must show only when user is loggedIn. I now redirect the user to /login page if the user is not authenticated. But during the redirect, the reading page is displayed for a few milli seconds allowing the un-authenticated user to see a flickering of the reading page during redirection.

I tried using useLayoutEffect instead of useEffect but the same flickering happens. Also tried without using useEffect or useLayoutEffect and within a function, but still the same

I get the userInfo from a global state, which gets the userInfo from the cookie. For state management I use recoil.

Reading Page: (which must be protected and if no user, redirect to login page)

```<code>function index() {
  const router = useRouter();
  const userInfo = useRecoilValue(userAtom);   ---> userInfo is recoil global state

  useLayoutEffect(() => {
    if (!userInfo) {
      router.push("/login?redirect=/reading");
    }
  }, []);

  return (//some code)
</code>```

Note:
Adding a Loader worked, but is there any better way?

答:
I would suggest a much better way. Instead of checking on individual pages.

You can write your Auth Check for user at route level i.e inside index.js where the React-Router is defined.

```<code>// PrivateRoute.jsx
function PrivateRoute ({component: Component, isAuth, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => isAuth
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {userInfo} }} />}
    />
  )
}

// index.jsx
.
const userInfo = useRecoilValue(userAtom);
.
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute isAuth={!!userInfo} userInfo={userInfo} path='/dashboard' component={Dashboard} />
.
.
</code>```

Hope this finds it helpful.

Body:
I have reading component which must show only when user is loggedIn. I now redirect the user to /login page if the user is not authenticated. But during the redirect, the reading page is displayed for a few milli seconds allowing the un-authenticated user to see a flickering of the reading page during redirection.

I tried using useLayoutEffect instead of useEffect but the same flickering happens. Also tried without using useEffect or useLayoutEffect and within a function, but still the same

I get the userInfo from a global state, which gets the userInfo from the cookie. For state management I use recoil.

Reading Page: (which must be protected and if no user, redirect to login page)

function index() {
  const router = useRouter();
  const userInfo = useRecoilValue(userAtom);   ---> userInfo is recoil global state

  useLayoutEffect(() => {
    if (!userInfo) {
      router.push("/login?redirect=/reading");
    }
  }, []);

  return (//some code)

Note:
Adding a Loader worked, but is there any better way?

Body:
I would suggest a much better way. Instead of checking on individual pages.

You can write your Auth Check for user at route level i.e inside index.js where the React-Router is defined.

// PrivateRoute.jsx
function PrivateRoute ({component: Component, isAuth, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => isAuth
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {userInfo} }} />}
    />
  )
}

// index.jsx
.
const userInfo = useRecoilValue(userAtom);
.
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute isAuth={!!userInfo} userInfo={userInfo} path='/dashboard' component={Dashboard} />
.
.

Hope this finds it helpful.


问:
Directshow, Stream Buffer Engine, IStreamBufferSink
using IStreamBufferSink in this way:

IStreamBufferSink *pBufferSing = NULL;

...

hr = pBufferSink->LockProfile(NULL);

where will the stub file be placed (it's location)?

答:
They are in the User's temp directory. In winXp:

C:\Documents and Settings\user\Local Settings\Temp\TempSBE


问:
Sequelize create my database but doesn't send files into that
I'm trying to create a backend using express and sequelize, I have configured the config, controllers, models, routes and server files, for the first test the database was created successfully with two tables (products and reviews tables) now I'm trying to test the model and controller created with sequelize, but right when I try to use the post route to send the information inside the products table:

```<code>const db = require('../models');

// create main model
const Product = db.products;
const Review = db.reviews;

// main work

// 1. create product

const addProduct = async (req, res) => {
  let info = {
    title: req.body.title,
    price: req.body.price,
    description: req.body.description,
    published: req.body.published ? req.body.published : false
  }

  const product = await Product.create(info)
  res.status(200).send(product)
  console.log(product)
}

module.exports = {
  addProduct,
}\
</code>```

, from the controllers folder, getting the information from the Database and the models folder:

```<code>module.exports = (sequelize, DataTypes) => {
  const Product = sequelize.define("product", {
    title: {
      type: DataTypes.TEXT,
      allowNull: false
    },
    price: {
      type: DataTypes.FLOAT,
      allowNull: false
    },
    description: {
      type: DataTypes.TEXT
    },
    published: {
      type: DataTypes.BOOLEAN
    },
  });

  return Product;
}
</code>```

I get an error message on the terminal that says:

```<code>nodejs\node-fullApi\controllers\productController.js:13
    title: req.body.title,
                    ^

TypeError: Cannot read properties of undefined (reading 'title')
    at addProduct (F:\JavaScript\nodejs\node-fullApi\controllers\productController.js:13:21)
    at Layer.handle [as handle_request] (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\layer.js:95:5)
    at F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:341:12)
    at next (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:174:3)
    at router (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:47:12)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

I tried to review everything I've done, I changed the Datatypes of the title from STRING to TEXT, but nothing worked and I keep getting this same error.

Does anyone have any idea of what can be so wrong there?
My full project can be found on github following this link: My Git Repository

答:
You need to register all body parsers BEFORE registering any routers that may use a request body of a given format:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const router = require('../routes/productRouter');
app.use('/api/products', router)
```

Body:
I'm trying to create a backend using express and sequelize, I have configured the config, controllers, models, routes and server files, for the first test the database was created successfully with two tables (products and reviews tables) now I'm trying to test the model and controller created with sequelize, but right when I try to use the post route to send the information inside the products table:

const db = require('../models');

// create main model
const Product = db.products;
const Review = db.reviews;

// main work

// 1. create product

const addProduct = async (req, res) => {
  let info = {
    title: req.body.title,
    price: req.body.price,
    description: req.body.description,
    published: req.body.published ? req.body.published : false
  }

  const product = await Product.create(info)
  res.status(200).send(product)
  console.log(product)
}

module.exports = {
  addProduct,
}\

, from the controllers folder, getting the information from the Database and the models folder:

module.exports = (sequelize, DataTypes) => {
  const Product = sequelize.define("product", {
    title: {
      type: DataTypes.TEXT,
      allowNull: false
    },
    price: {
      type: DataTypes.FLOAT,
      allowNull: false
    },
    description: {
      type: DataTypes.TEXT
    },
    published: {
      type: DataTypes.BOOLEAN
    },
  });

  return Product;
}

I get an error message on the terminal that says:

nodejs\node-fullApi\controllers\productController.js:13
    title: req.body.title,
                    ^

TypeError: Cannot read properties of undefined (reading 'title')
    at addProduct (F:\JavaScript\nodejs\node-fullApi\controllers\productController.js:13:21)
    at Layer.handle [as handle_request] (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\layer.js:95:5)
    at F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:341:12)
    at next (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:174:3)
    at router (F:\JavaScript\nodejs\node-fullApi\node_modules\express\lib\router\index.js:47:12)
[nodemon] app crashed - waiting for file changes before starting...

I tried to review everything I've done, I changed the Datatypes of the title from STRING to TEXT, but nothing worked and I keep getting this same error.

Does anyone have any idea of what can be so wrong there?
My full project can be found on github following this link: My Git Repository


问:
How to sort firebase recycler view?
I want to order my recyclerview by eventDate but im already using orderByChild.
How to do it?

Sorry if i dont explain it well, but on SQL the thing i want to achieve is:

```<code>SELECT * FROM Event WHERE eventOrganizer=stringOrganizer ORDER BY eventDate ASC;
</code>```

This is the code:

```<code>    Query query = databaseReferenceEvent.orderByChild("eventOrganizer").equalTo(stringOrganizer);
    FirebaseRecyclerOptions <ModelEvent> options = new FirebaseRecyclerOptions.Builder<ModelEvent>()
        .setQuery(query, snapshot -> new ModelEvent(
            Objects.requireNonNull(snapshot.child("eventID").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventOrganizer").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventName").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventDate").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventStatus").getValue()).toString()))
        .build();

    adapter = new FirebaseRecyclerAdapter<ModelEvent, ViewHolderEvent>(options) {
        @NonNull
        @Override
        public ViewHolderEvent onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_attendance, parent, false);
            return new ViewHolderEvent(view);
        }
</code>```

答:
I don't know how is your DB structure, but I think the best is to rethink it.
I mean, ordering the nodes from the last, then you query ordering by status</p>

Title: How to sort firebase recycler view?

Body:
I want to order my recyclerview by eventDate but im already using orderByChild.
How to do it?

Sorry if i dont explain it well, but on SQL the thing i want to achieve is:

SELECT * FROM Event WHERE eventOrganizer=stringOrganizer ORDER BY eventDate ASC;

This is the code:

    Query query = databaseReferenceEvent.orderByChild("eventOrganizer").equalTo(stringOrganizer);
    FirebaseRecyclerOptions <ModelEvent> options = new FirebaseRecyclerOptions.Builder<ModelEvent>()
        .setQuery(query, snapshot -> new ModelEvent(
            Objects.requireNonNull(snapshot.child("eventID").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventOrganizer").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventName").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventDate").getValue()).toString(),
            Objects.requireNonNull(snapshot.child("eventStatus").getValue()).toString()))
        .build();

    adapter = new FirebaseRecyclerAdapter<ModelEvent, ViewHolderEvent>(options) {
        @NonNull
        @Override
        public ViewHolderEvent onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_attendance, parent, false);
            return new ViewHolderEvent(view);
        }


问:
Hibernate issue with unquoted strategy
Starting from 5.5.3.Final, Hibernate-core changes the unquotedCaseStrategy to UPPER (while the original value is MIXED).

```<code>public class IdentifierHelperBuilder {
    private IdentifierCaseStrategy unquotedCaseStrategy = IdentifierCaseStrategy.UPPER;
    private IdentifierCaseStrategy quotedCaseStrategy = IdentifierCaseStrategy.MIXED;
</code>```

Our project uses following url (with Spring boot) to access the MariaDB. After changing to hibernate-core 5.5.3.Final, our project cannot access the MariaDB correctly. During the investigation, I found that catalog name WebServiceDB will be treated as unquoted and UPPER case WEBSERVICEDB will be used as the catalog (WebServiceDB will be used before hibernate-core 5.5.3.Final) due to the unquotedCaseStrategy change.

```<code>spring:
  datasource:
    url: jdbc:mysql://1.1.1.1:3306/WebServiceDB
</code>```

I want to make the catalog to be quoted and use quotedCaseStrategy, following configurations had been tried and did not work. Could you please help me? Thanks a lot.

```<code>url: jdbc:mysql://1.1.1.1:3306/"WebServiceDB"
url: jdbc:mysql://1.1.1.1:3306/[WebServiceDB]
</code>```

答:
The workaround is to add both globally_quoted_identifiers and globally_quoted_identifiers_skip_column_definitions:

```<code>spring:
  jpa:
    properties:
      hibernate:
        globally_quoted_identifiers: true
        globally_quoted_identifiers_skip_column_definitions: true
</code>```

And following JIRA is opened for this issue.
https://hibernate.atlassian.net/browse/HHH-15075

In my case, I am using the dialect: org.hibernate.dialect.MySQL5InnoDBDialect, and it's legacy configuration.
I need to change to org.hibernate.dialect.MariaDBDialect, because our project is using MariaDB 10.4.21.
MariaDBDialect would set unquotedCaseStrategy and quotedCaseStrategy to MIXED.

```<code>@Override
    public IdentifierHelper buildIdentifierHelper(IdentifierHelperBuilder builder, DatabaseMetaData dbMetaData)
            throws SQLException {

        // some MariaDB drivers does not return case strategy info
        builder.setUnquotedCaseStrategy( IdentifierCaseStrategy.MIXED );
        builder.setQuotedCaseStrategy( IdentifierCaseStrategy.MIXED );

        return super.buildIdentifierHelper( builder, dbMetaData );
    }
</code>```

Title: Hibernate issue with unquoted strategy

Body:
Starting from 5.5.3.Final, Hibernate-core changes the unquotedCaseStrategy to UPPER (while the original value is MIXED).

public class IdentifierHelperBuilder {
    private IdentifierCaseStrategy unquotedCaseStrategy = IdentifierCaseStrategy.UPPER;
    private IdentifierCaseStrategy quotedCaseStrategy = IdentifierCaseStrategy.MIXED;

Our project uses following url (with Spring boot) to access the MariaDB. After changing to hibernate-core 5.5.3.Final, our project cannot access the MariaDB correctly. During the investigation, I found that catalog name WebServiceDB will be treated as unquoted and UPPER case WEBSERVICEDB will be used as the catalog (WebServiceDB will be used before hibernate-core 5.5.3.Final) due to the unquotedCaseStrategy change.

spring:
  datasource:
    url: jdbc:mysql://1.1.1.1:3306/WebServiceDB

I want to make the catalog to be quoted and use quotedCaseStrategy, following configurations had been tried and did not work. Could you please help me? Thanks a lot.

url: jdbc:mysql://1.1.1.1:3306/"WebServiceDB"
url: jdbc:mysql://1.1.1.1:3306/[WebServiceDB]

Body:
The workaround is to add both globally_quoted_identifiers and globally_quoted_identifiers_skip_column_definitions:

spring:
  jpa:
    properties:
      hibernate:
        globally_quoted_identifiers: true
        globally_quoted_identifiers_skip_column_definitions: true

And following JIRA is opened for this issue.
https://hibernate.atlassian.net/browse/HHH-15075

In my case, I am using the dialect: org.hibernate.dialect.MySQL5InnoDBDialect, and it's legacy configuration.
I need to change to org.hibernate.dialect.MariaDBDialect, because our project is using MariaDB 10.4.21.
MariaDBDialect would set unquotedCaseStrategy and quotedCaseStrategy to MIXED.

@Override
    public IdentifierHelper buildIdentifierHelper(IdentifierHelperBuilder builder, DatabaseMetaData dbMetaData)
            throws SQLException {

        // some MariaDB drivers does not return case strategy info
        builder.setUnquotedCaseStrategy( IdentifierCaseStrategy.MIXED );
        builder.setQuotedCaseStrategy( IdentifierCaseStrategy.MIXED );

        return super.buildIdentifierHelper( builder, dbMetaData );
    }


问:
Error: Failed to serialize user into session || This error is coming while I am trying to log in
I got a problem with the Passport.js module and Express.js.
This is my code and I just want to use a hardcoded login for the first try.
I always get the message:
I searched a lot and found some posts in stackoverflow but I didnt get the failure.

Code of my app.js

```<code>require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const mongoose = require('mongoose')
const session = require('express-session')
const passport = require('passport')
const passportLocalMongoose = require('passport-local-mongoose')

const app = express();
const port = process.env.PORT

app.use(express.static('public'))
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended:true}))

app.use(session({
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: false,
}))

app.use(passport.initialize())
app.use(passport.session())

mongoose.connect("mongodb://localhost:27017/userDB")

const userSchema = new mongoose.Schema({
    username: String,
    password: String,
})
userSchema.plugin(passportLocalMongoose)

const User = new mongoose.model("User",userSchema)

passport.use(User.createStrategy())

passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())

//Home Route
app.get('/',(req,res)=>{
    res.render('home')
})

//Login Route
app.route('/login')
.get((req,res)=>{
    res.render('login')
})
.post((req,res)=>{

    const user = new User({
        username: req.body.username,
        password: req.body.password
      });

      req.login(user, function(err){
        if (err) {
          console.log(err);
        } else {
          passport.authenticate("local")(req, res, function(){
            res.redirect("/secrets");
          });
        }
      });

})

//Register route

app.route('/register')
.get((req,res)=>{
    res.render('register')
})
.post((req,res)=>{

    User.register({username: req.body.username}, req.body.password,(err,user)=>{
        if(err){
            console.log(err);
            res.redirect('/register')
        }
        else{
            passport.authenticate("local")(req,res,()=>{
                res.redirect("/secrets")
            })
        }
    })

})

app.route('/secrets')
.get((req,res)=>{
    res.set('Cache-Control', 'no-store');
    if(req.isAuthenticated()){
        res.render("secrets")
    }
    else{
        res.redirect("/login")
    }
})

app.listen(port,()=>console.log("server started at port "+port))
</code>```

But its giving this error:

```<code>Error: Failed to serialize user into session
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:278:19)
    at serialized (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:283:7)
    at D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport-local-mongoose\index.js:212:7
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:291:9)
    at Authenticator.serializeUser (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:296:5)
    at SessionManager.logIn (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\sessionmanager.js:14:8)
</code>```

This problem is occuring only in case of login. register is working fine.

答: This error means passport is not able to hash (serialize) your users. Try to implement your own User.serializeUser() function using the user's _id.</p>

Body:
I got a problem with the Passport.js module and Express.js.
This is my code and I just want to use a hardcoded login for the first try.
I always get the message:
I searched a lot and found some posts in stackoverflow but I didnt get the failure.

Code of my app.js

require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const mongoose = require('mongoose')
const session = require('express-session')
const passport = require('passport')
const passportLocalMongoose = require('passport-local-mongoose')

const app = express();
const port = process.env.PORT

app.use(express.static('public'))
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended:true}))

app.use(session({
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: false,
}))

app.use(passport.initialize())
app.use(passport.session())

mongoose.connect("mongodb://localhost:27017/userDB")

const userSchema = new mongoose.Schema({
    username: String,
    password: String,
})
userSchema.plugin(passportLocalMongoose)

const User = new mongoose.model("User",userSchema)

passport.use(User.createStrategy())

passport.serializeUser(User.serializeUser())
passport.deserializeUser(User.deserializeUser())

//Home Route
app.get('/',(req,res)=>{
    res.render('home')
})

//Login Route
app.route('/login')
.get((req,res)=>{
    res.render('login')
})
.post((req,res)=>{

    const user = new User({
        username: req.body.username,
        password: req.body.password
      });

      req.login(user, function(err){
        if (err) {
          console.log(err);
        } else {
          passport.authenticate("local")(req, res, function(){
            res.redirect("/secrets");
          });
        }
      });

})

//Register route

app.route('/register')
.get((req,res)=>{
    res.render('register')
})
.post((req,res)=>{

    User.register({username: req.body.username}, req.body.password,(err,user)=>{
        if(err){
            console.log(err);
            res.redirect('/register')
        }
        else{
            passport.authenticate("local")(req,res,()=>{
                res.redirect("/secrets")
            })
        }
    })

})

app.route('/secrets')
.get((req,res)=>{
    res.set('Cache-Control', 'no-store');
    if(req.isAuthenticated()){
        res.render("secrets")
    }
    else{
        res.redirect("/login")
    }
})

app.listen(port,()=>console.log("server started at port "+port))

But its giving this error:

Error: Failed to serialize user into session
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:278:19)
    at serialized (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:283:7)
    at D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport-local-mongoose\index.js:212:7
    at pass (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:291:9)
    at Authenticator.serializeUser (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\authenticator.js:296:5)
    at SessionManager.logIn (D:\CODING\WEB\Web-Development-Series\Secrets+-+Starting+Code\Secrets - Starting Code\node_modules\passport\lib\sessionmanager.js:14:8)

This problem is occuring only in case of login. register is working fine.


问:
How to use tesseract_ocr in PHP?
I find a problem to use tesseract_ocr in php, I follow this tutorial https://github.com/thiagoalessio/tesseract-ocr-for-php.

I install tesseract_ocr use composer :

```<code>$ composer require thiagoalessio/tesseract_ocr
</code>```

this is my folder structure in localhost :

this is mycode :

```<code><!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
require __DIR__ . "/vendor/autoload.php";
use thiagoalessio\TesseractOCR\TesseractOCR;
echo (new TesseractOCR('images/8055.PNG'))
    ->whitelist(range('A', 'Z'))
    ->run();
?>

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

this is my php version :

and in the browser I get this error :

Fatal error: Uncaught thiagoalessio\TesseractOCR\TesseractNotFoundException: Error! The command "tesseract" was not found. Make sure you have Tesseract OCR installed on your system: https://github.com/tesseract-ocr/tesseract The current $PATH is C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Git\cmd;C:\Program Files\Java\jdk1.8.0_73\bin;C:\Users\frank\AppD in C:\xampp\htdocs\ocr\vendor\thiagoalessio\tesseract_ocr\src\FriendlyErrors.php on line 48

please anyone help me to solve this problem.

Thanks.

答:
Make sure the tesseract folder is in your path.

If you're unsure what I'm saying, click on the start button and type "edit the system environment variables".  Click Environment Variables, under "System variables" click on the line that has "Path" on the far left, and click edit.  Click "New" and put in the path to your executable, depending on if you're using the 64 bit or 32 bit version.  In my case it was "C:\Program Files\Tesseract-OCR".

You can test this now by opening a new command prompt (if you had an old one open, it won't have the new path variable), and type tesseract and hit enter.  You should see:

Usage:
  tesseract --help | --help-extra | --version
  tesseract --list-langs
  tesseract imagename outputbase [options...] [configfile...]

OCR options:
  -l LANG[+LANG]        Specify language(s) used for OCR.
NOTE: These options must occur before any configfile.

Single options:
  --help                Show this help message.
  --help-extra          Show extra help for advanced users.
  --version             Show version information.
  --list-langs          List available languages for tesseract engine.```

If you do, then it's installed and globally working on your machine now and should work with PHP.   If you want to get it working without composer, look up my other answer about that on here.

Title: How to use tesseract_ocr in PHP?

Body:
I find a problem to use tesseract_ocr in php, I follow this tutorial https://github.com/thiagoalessio/tesseract-ocr-for-php.

I install tesseract_ocr use composer :

$ composer require thiagoalessio/tesseract_ocr

this is my folder structure in localhost :

this is mycode :

<!DOCTYPE html>

My first PHP page

<?php
require __DIR__ . "/vendor/autoload.php";
use thiagoalessio\TesseractOCR\TesseractOCR;
echo (new TesseractOCR('images/8055.PNG'))
    ->whitelist(range('A', 'Z'))
    ->run();
?>

this is my php version :

and in the browser I get this error :

Fatal error: Uncaught thiagoalessio\TesseractOCR\TesseractNotFoundException: Error! The command "tesseract" was not found. Make sure you have Tesseract OCR installed on your system: https://github.com/tesseract-ocr/tesseract The current $PATH is C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Git\cmd;C:\Program Files\Java\jdk1.8.0_73\bin;C:\Users\frank\AppD in C:\xampp\htdocs\ocr\vendor\thiagoalessio\tesseract_ocr\src\FriendlyErrors.php on line 48

please anyone help me to solve this problem.

Thanks.

Body:
Make sure the tesseract folder is in your path.

If you're unsure what I'm saying, click on the start button and type "edit the system environment variables".  Click Environment Variables, under "System variables" click on the line that has "Path" on the far left, and click edit.  Click "New" and put in the path to your executable, depending on if you're using the 64 bit or 32 bit version.  In my case it was "C:\Program Files\Tesseract-OCR".

You can test this now by opening a new command prompt (if you had an old one open, it won't have the new path variable), and type tesseract and hit enter.  You should see:

Usage:
  tesseract --help | --help-extra | --version
  tesseract --list-langs
  tesseract imagename outputbase [options...] [configfile...]

OCR options:
  -l LANG[+LANG]        Specify language(s) used for OCR.
NOTE: These options must occur before any configfile.

Single options:
  --help                Show this help message.
  --help-extra          Show extra help for advanced users.
  --version             Show version information.
  --list-langs          List available languages for tesseract engine.

If you do, then it's installed and globally working on your machine now and should work with PHP.   If you want to get it working without composer, look up my other answer about that on here.


问:
Laravel 8 Migrate:rollback and migrate error
While I run php artisan:fresh. It rollback all the table in my database and the I run php artisan migrate it will show the error:

```<code>SQLSTATE[HY000]: General error: 1005 Can't create table `online`.`appointps` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `appointps` add constraint `appointps_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
</code>```

答:
check if the format of foreign key  like the following example

```<code>    Schema::create('appointps', function (Blueprint $table) {

    $table->id();
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->timestamps();
});
</code>```

note: check the migration of users execute before appointps

hopefully that help you

Body:
While I run php artisan:fresh. It rollback all the table in my database and the I run php artisan migrate it will show the error:

SQLSTATE[HY000]: General error: 1005 Can't create table `online`.`appointps` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `appointps` add constraint `appointps_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

Body:
check if the format of foreign key  like the following example

    Schema::create('appointps', function (Blueprint $table) {

    $table->id();
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->timestamps();
});

note: check the migration of users execute before appointps

hopefully that help you


问:
Guaranteed always on top on a webpage
I'm developing a chrome extension, without going too much into it I need to inject some code into webpages and put an overlay over the full page. Thus far I have nearly achieved this butI just cannot seem to get the overlay over certain parts of some websites. These include videos from youtube, the searchbar on top of google search results, random parts of kongregate (the stars and monthly comp info).

Below is the css I'm currently using to achieve this, I have played around and looked for solutions at various places but no solutions seems to work.

```<code>.cssX9482Overlay
{
    position: fixed;
    width: 100%;
    Height: 100%;
    vertical-align: middle;
    background: #000000;
    opacity: 0.97;
    filter: alpha(opacity=97);
    text-align: center;
    top: 0;
    left: 0;
}
</code>```

The strange css name is just so it doesn't clash with pages formatting. As you probably guessed this is being used to format a div

Remember this is a Chrome extension, therefore HTML5 and CSS3 solutions are valid.

答:
```<code><style type="text/css">
iframe, div {
    position:absolute;
    top:20px;
    left:20px;
    width:200px;
    height:25px
}

iframe { z-index:1 }

div {
    z-index:2;
    background:#000;
    border:solid 1px red;
    color:#fff;
}
</style>

<applet code="myApp.class" width="700" height="700"></applet>

<iframe></iframe>

<div>EXAMPLE TEXT</div>
</code>```

TAKEN FROM: http://www.bluestudios.co.uk/blog/?p=6
Also you had height capitalized

Title: Guaranteed always on top on a webpage

Body:
I'm developing a chrome extension, without going too much into it I need to inject some code into webpages and put an overlay over the full page. Thus far I have nearly achieved this butI just cannot seem to get the overlay over certain parts of some websites. These include videos from youtube, the searchbar on top of google search results, random parts of kongregate (the stars and monthly comp info).

Below is the css I'm currently using to achieve this, I have played around and looked for solutions at various places but no solutions seems to work.

.cssX9482Overlay
{
    position: fixed;
    width: 100%;
    Height: 100%;
    vertical-align: middle;
    background: #000000;
    opacity: 0.97;
    filter: alpha(opacity=97);
    text-align: center;
    top: 0;
    left: 0;
}

The strange css name is just so it doesn't clash with pages formatting. As you probably guessed this is being used to format a div

Remember this is a Chrome extension, therefore HTML5 and CSS3 solutions are valid.

Body:
<style type="text/css">
iframe, div {
    position:absolute;
    top:20px;
    left:20px;
    width:200px;
    height:25px
}

iframe { z-index:1 }

div {
    z-index:2;
    background:#000;
    border:solid 1px red;
    color:#fff;
}
</style>

<applet code="myApp.class" width="700" height="700"></applet>

<iframe></iframe>

<div>EXAMPLE TEXT</div>

TAKEN FROM: http://www.bluestudios.co.uk/blog/?p=6
Also you had height capitalized


问:
How do you return the last element in an array in C?
How do I return the last element in an array? I thought this function would work, as it worked for a similar function that returned the first element.</p>
```<code>int END(int arr[]) {
    int last;
    size_t s = sizeof(arr) / sizeof(arr[0]);
    if (s != 0) {
        last = arr[s - 1];
        return last;
    } else {
        return -1 ; //END(arr);
    }
}
</code>```

答:
You cannot use sizeof inside a function because sizeof(arr) will return the size of the pointer which is generally 8 bytes on a x86_64 architecture. I would not use -1 is an error value because -1 can be an element of the given array. I would prefer the C++ way of npos, returning the maximum value of the data type according to the system architecture.

I would recommend you to get the length of the array as a parameter of the function. Like this:

```<code>    #include <stdio.h>
    #include <limits.h>

    int END(int *arr, size_t length); // fix prototype error
    /*
        @brief Returns the last element of the array `arr`.
        @param arr array
        @param length array's length
        @returns If `arr` is NULL or empty returns INT_MAX, otherwise the last element.
    */
    int END(int *arr, size_t length)
    {
        if (!arr || length == 0) // if arr is NULL
            return INT_MAX;
        else
            return arr[length - 1]; // 0 based indexing system in C
    }

    int main(void)
    {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        size_t length = sizeof(arr) / sizeof(*arr);
        printf("Last element of the array: %d\n", END(arr, length));
        return 0;
    }
</code>```

Output:

```<code>Last element of the array: 10
</code>```

Body:
How do I return the last element in an array? I thought this function would work, as it worked for a similar function that returned the first element.

int END(int arr[]) {
    int last;
    size_t s = sizeof(arr) / sizeof(arr[0]);
    if (s != 0) {
        last = arr[s - 1];
        return last;
    } else {
        return -1 ; //END(arr);
    }
}

Body:
You cannot use sizeof inside a function because sizeof(arr) will return the size of the pointer which is generally 8 bytes on a x86_64 architecture. I would not use -1 is an error value because -1 can be an element of the given array. I would prefer the C++ way of npos, returning the maximum value of the data type according to the system architecture.

I would recommend you to get the length of the array as a parameter of the function. Like this:

    #include <stdio.h>
    #include <limits.h>

    int END(int *arr, size_t length); // fix prototype error
    /*
        @brief Returns the last element of the array `arr`.
        @param arr array
        @param length array's length
        @returns If `arr` is NULL or empty returns INT_MAX, otherwise the last element.
    */
    int END(int *arr, size_t length)
    {
        if (!arr || length == 0) // if arr is NULL
            return INT_MAX;
        else
            return arr[length - 1]; // 0 based indexing system in C
    }

    int main(void)
    {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        size_t length = sizeof(arr) / sizeof(*arr);
        printf("Last element of the array: %d\n", END(arr, length));
        return 0;
    }

Output:

Last element of the array: 10


答:
Issues.

You have not updated inputString after string replace.

I have made use of below logic.

Loop through variables first.

Replace the values if any of the value consist of node from variable array itself (in our case replace %NAME%@mail.com as joe@mail.com)

Use this replaced array to perform replacement of string values from inputString.

Use replaceAll instead of replace to handle multiple ovvurance of same variable.

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];
const inputString = `Hi, my name is %NAME%', I like %HOBBY%, you can contact me at %EMAIL%`;
function doMagic(variables, inputString) {
  let output = inputString;
  // First replace variables
  for (let i = 0; i < variables.length; i++) {
    const node = variables.find(item => item.value.includes(variables[i].name));
    if (node) {
      node.value = node.value.replaceAll(variables[i].name, variables[i].value);
    }
  }
  for (let i = 0; i < variables.length; i++) {
    output = output.replaceAll(variables[i].name, variables[i].value);
  }
  return output;
}
console.log(doMagic(variables, inputString))```

Title: Replace values from a string if they are present in an array of variables

Body:
Having the following array of objects:

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];

And the input string:

const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;

The function should take as arguments variables and inputString and return the following sting:

'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'

Here is the function so far:

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?


问:
difference between Flask-RESTful and Flask-RESTx
What is the difference between Flask-RESTful and Flask-RESTx? Is it more advantageous to use Flask-RESTx instead of Flask-RESTful?</p>

答: the main difference between Flask-RESTx and Flask-RESTful is that Flask-RESTx supports auto-generated Swagger documentation. i think there are no other noticeable differences.