问:
Algebraic numbers in Z3
The following code sets some Z3 constraints for x,y that are satisfied (only) by:
x = sqrt(2) and y = -sqrt(2).

```<code>x, y = Reals('x y')
s = Solver()
s.add( x*x == 2 )
s.add( x>0)
s.add( y*y == 2 )
s.add( y<0)
s.check()
m = s.model()
val_x = m.get_interp(x)
val_y = m.get_interp(y)

print(f"The solutions are: x={val_x} and y={val_y}")
print(f"The defining polynomial of x has integer coefficients", val_x.poly(), " and root index ", val_x.index())
print(f"The defining polynomial of y has integer coefficients", val_y.poly(), " and root index ", val_y.index())
</code>```

The output is:

```<code>The solutions are: x=1.4142135623? and y=-1.4142135623?

the defining polynomial of x has integer coefficients [-2, 0, 1]  and root index  0

the defining polynomial of y has integer coefficients [-2, 0, 1]  and root index  0
</code>```

It thus appear that the .index() function, which is supposed to extract the index of an algebraic number, does not work: Both $sqrt(2)$ and $- sqrt(2)$ are given the same index.

I have reported this issue in the Z3 github (link) but unfortunately the devs do not have the bandwidth to solve this issue.

I had a look at the python code for the .index() function (path z3/lib.z3.py):

```<code>def index(self):
    return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast())
</code>```

which just calls:

```<code>def Z3_algebraic_get_i(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_get_i)):
  r = _elems.f(a0, a1)
  _elems.Check(a0)
  return r
</code>```

which basically (?) calls the method Z3_algebraic_get_i of the Z3 library in the C language.

I am not familiar myself with C, so I am seeking some help:

QUESTION is the Z3_algebraic_get_i function of the C Z3 library actually working, or it's just Python?

Thanks

EDIT: This is the source code of the C function from here

```<code>    unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a) {
        Z3_TRY;
        LOG_Z3_algebraic_get_i(c, a);
        RESET_ERROR_CODE();
        CHECK_IS_ALGEBRAIC(a, 0);
        algebraic_numbers::manager & _am = am(c);
        algebraic_numbers::anum const & av = get_irrational(c, a);
        return _am.get_i(av);
        Z3_CATCH_RETURN(0);
    }
</code>```

答:
This indeed seems to be a bug in z3py; and I strongly suspect in the python bindings only. However, fixing it will take intimate knowledge of the code-base, even though it might be a simple thing at the end. You did the right thing by reporting it to the developers. It's unfortunate that they don't have the bandwidth to rectify the issue.

However, I can offer a hack, which can provide a workaround till there's a proper fix, if ever. Define:

def get_root_obj_index(ar):
    return Int(ar.sexpr().split()[-1][:-1])
```
<p>Now you can change the last two lines of your program to say:</p>
<pre class="lang-py prettyprint-override"><code>print(f"The defining polynomial of x has integer coefficients", val_x.poly(), " and root index ", get_root_obj_index(val_x))
print(f"The defining polynomial of y has integer coefficients", val_y.poly(), " and root index ", get_root_obj_index(val_y))
</code>```

And this prints:

```<code>The defining polynomial of x has integer coefficients [-2, 0, 1]  and root index  2
The defining polynomial of y has integer coefficients [-2, 0, 1]  and root index  1
</code>```

This does the right thing for your particular example, and I think it'll do the right thing in general; so long as the result is a root-object. The hack is to print the object as an s-expr, which shows it as a root-object and extract the index value. Of course, you might want to be careful and do some checking on the result of sexpr() to make sure it indeed does look like a root-object first, and if not, throw an error or return some default value.

I should emphasize that this is a hack, and should be used sparingly and only with care; but it can help you if no one steps up to fix the corresponding bug in z3py.

Title: Algebraic numbers in Z3

Body:
The following code sets some Z3 constraints for x,y that are satisfied (only) by:
x = sqrt(2) and y = -sqrt(2).

x, y = Reals('x y')
s = Solver()
s.add( x*x == 2 )
s.add( x>0)
s.add( y*y == 2 )
s.add( y<0)
s.check()
m = s.model()
val_x = m.get_interp(x)
val_y = m.get_interp(y)

print(f"The solutions are: x={val_x} and y={val_y}")
print(f"The defining polynomial of x has integer coefficients", val_x.poly(), " and root index ", val_x.index())
print(f"The defining polynomial of y has integer coefficients", val_y.poly(), " and root index ", val_y.index())

The output is:

The solutions are: x=1.4142135623? and y=-1.4142135623?

the defining polynomial of x has integer coefficients [-2, 0, 1]  and root index  0

the defining polynomial of y has integer coefficients [-2, 0, 1]  and root index  0

It thus appear that the .index() function, which is supposed to extract the index of an algebraic number, does not work: Both $sqrt(2)$ and $- sqrt(2)$ are given the same index.

I have reported this issue in the Z3 github (link) but unfortunately the devs do not have the bandwidth to solve this issue.

I had a look at the python code for the .index() function (path z3/lib.z3.py):

def index(self):
    return Z3_algebraic_get_i(self.ctx_ref(), self.as_ast())

which just calls:

def Z3_algebraic_get_i(a0, a1, _elems=Elementaries(_lib.Z3_algebraic_get_i)):
  r = _elems.f(a0, a1)
  _elems.Check(a0)
  return r

which basically (?) calls the method Z3_algebraic_get_i of the Z3 library in the C language.

I am not familiar myself with C, so I am seeking some help:

QUESTION is the Z3_algebraic_get_i function of the C Z3 library actually working, or it's just Python?

Thanks

EDIT: This is the source code of the C function from here

    unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a) {
        Z3_TRY;
        LOG_Z3_algebraic_get_i(c, a);
        RESET_ERROR_CODE();
        CHECK_IS_ALGEBRAIC(a, 0);
        algebraic_numbers::manager & _am = am(c);
        algebraic_numbers::anum const & av = get_irrational(c, a);
        return _am.get_i(av);
        Z3_CATCH_RETURN(0);
    }

Body:
This indeed seems to be a bug in z3py; and I strongly suspect in the python bindings only. However, fixing it will take intimate knowledge of the code-base, even though it might be a simple thing at the end. You did the right thing by reporting it to the developers. It's unfortunate that they don't have the bandwidth to rectify the issue.

However, I can offer a hack, which can provide a workaround till there's a proper fix, if ever. Define:

def get_root_obj_index(ar):
    return Int(ar.sexpr().split()[-1][:-1])

Now you can change the last two lines of your program to say:

print(f"The defining polynomial of x has integer coefficients", val_x.poly(), " and root index ", get_root_obj_index(val_x))
print(f"The defining polynomial of y has integer coefficients", val_y.poly(), " and root index ", get_root_obj_index(val_y))

And this prints:

The defining polynomial of x has integer coefficients [-2, 0, 1]  and root index  2
The defining polynomial of y has integer coefficients [-2, 0, 1]  and root index  1

This does the right thing for your particular example, and I think it'll do the right thing in general; so long as the result is a root-object. The hack is to print the object as an s-expr, which shows it as a root-object and extract the index value. Of course, you might want to be careful and do some checking on the result of sexpr() to make sure it indeed does look like a root-object first, and if not, throw an error or return some default value.

I should emphasize that this is a hack, and should be used sparingly and only with care; but it can help you if no one steps up to fix the corresponding bug in z3py.


来源: stackexchange

问:
oneApi 2021.4 xilink: : error : Assertion failed (shared/driver/drvutils.c line 312)
Using newly installed oneAPI 2021.4 + VisualStudio 16.11.3.

Create new project - Console App -

```<code>#include <iostream>

int main() {std::cout << "Hello World!\n";}
</code>```

After rebuilding I get:

Rebuild started...

1>------ Rebuild All started: Project: xilink, Configuration: Debug
Win32 ------ 1>xilink: : error : Assertion failed
(shared/driver/drvutils.c, line 312) 1>Done building project
"xilink.vcxproj" -- FAILED.

Tried on many other projects, x32 and x64, other VS versions - the error is the same.

I have found workaround - I copied file xilink.exe  from older version 2021.2 to 2021.4 folder - and linking start working!

C:\Program Files
(x86)\Intel\oneAPI\compiler\2021.2.0\windows\bin\intel64\xilink.exe

was copied to

C:\Program Files
(x86)\Intel\oneAPI\compiler\2021.4.0\windows\bin\intel64\xilink.exe

(and intel64_ia32 was copied too..)

答:
The issue raised by you has been fixed in Intel oneAPI 2022.1 version. Please download and let us know if this resolves your issue.

As a workaround you can copy a file clang.exe (by default it is located in C:\Program Files (x86)\Intel\oneAPI\compiler\latest\windows\bin) to the folder with xilink (for x64 configuration it is in C:\Program Files (x86)\Intel\oneAPI\compiler\latest\windows\bin\intel64).

ContentLicense: CC BY-SA 4.0

Body:
Using newly installed oneAPI 2021.4 + VisualStudio 16.11.3.

Create new project - Console App -

#include <iostream>

int main() {std::cout << "Hello World!\n";}

After rebuilding I get:

Rebuild started...

1>------ Rebuild All started: Project: xilink, Configuration: Debug
Win32 ------ 1>xilink: : error : Assertion failed
(shared/driver/drvutils.c, line 312) 1>Done building project
"xilink.vcxproj" -- FAILED.

Tried on many other projects, x32 and x64, other VS versions - the error is the same.

I have found workaround - I copied file xilink.exe  from older version 2021.2 to 2021.4 folder - and linking start working!

C:\Program Files
(x86)\Intel\oneAPI\compiler\2021.2.0\windows\bin\intel64\xilink.exe

was copied to

C:\Program Files
(x86)\Intel\oneAPI\compiler\2021.4.0\windows\bin\intel64\xilink.exe

(and intel64_ia32 was copied too..)


问:
Java code exits after some seconds due to concurrency
I am writing the same code on tutorial. But in tutorial the program never exits, my in my computer it exits after 4 seconds. Why?
tutorial with exact time where this code is shown: https://youtu.be/vzBw1LPupnA?t=169</p>
```<code>public class Main {
    private static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested) {
                i++;
                System.out.println("i = " + i);
            }
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}
</code>```

答:
As the excellent Answer by Stephen C says, your code is not thread-safe.

Establishing an AtomicBoolean early on addresses the visibility problem explained in that other Answer. This class is a thread-safe wrapper around its payload boolean value.

The volatile keyword is another solution. But I find the Atomic… classes simpler and more obvious.

Also, in modern Java we rarely need to address the Thread class directly. Instead, use the Executors framework. Define your task as a Runnable or Callable, and submit to an executor service.

Something like this untested code.

public class Main {
    private static final AtomicBoolean stopRequested = new AtomicBoolean( false ) ;

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            int i = 0;
            while ( ! stopRequested.get() ) {
                i++;
                System.out.println("i = " + i);
                TimeUnit.MILLISECONDS.sleep(100); // Don’t spin too fast.
            }
        };
        ExecutorService es = Executors.newSingleThreadedExecutorService() ;
        es.submit( task ) ;
        TimeUnit.SECONDS.sleep(1);
        stopRequested.set( true ) ;
        TimeUnit.SECONDS.sleep(1);

   // Shut down here executor service. Boilerplate taken from Javadoc.
   es.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!es.awaitTermination(60, TimeUnit.SECONDS)) {
       es.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!es.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Executor service did not terminate");
     }
   } catch (InterruptedException ex) {
     // (Re-)Cancel if current thread also interrupted
     es.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
    }
}
```

Body:
I am writing the same code on tutorial. But in tutorial the program never exits, my in my computer it exits after 4 seconds. Why?
tutorial with exact time where this code is shown: https://youtu.be/vzBw1LPupnA?t=169

public class Main {
    private static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested) {
                i++;
                System.out.println("i = " + i);
            }
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}


问:
Is there a way to pass an imported component through a function?
I'm using a library called SlidingPane, and each pane has the exact same styles, just different content depending on the page. So I want to put it into a separate page, and get the content through an argument:

export default function CustomSlidingPane(content){
    <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
}
```
<p>All of the content is in separate <code>.js</code> pages that kind of look like this:</p>
<pre class="lang-js prettyprint-override"><code>export default function One() {
    return (
        <h1>Hello</h1>
    );
}
</code>```

So what I'm trying to do is pass one of the content functions through to the CustomSlidingPane like this:

import One from './One';
import CustomSlidingPane from './CustomSlidingPane';

export default function Main(){
    <Container>
        <CustomSlidingPane content={<One/>}>
    </Container>
}
```

Every thing I've tried always ends up in content being undefined. Is there any proper way to do this / is this even possible?

答:
You will need to use children prop here. I am adding an example with a simple div element.

```<code>export default function CustomSlidingPane(props) {
  return <div>{props.children}</div>;
}
</code>```

Content will be same as you defined in your example:

```<code>export default function One() {
  return <h1>Hello</h1>;
}
</code>```

This is how you can pass the content to your slidingPlane component:

```<code>export default function Main() {
  return (
    <div>
      <CustomSlidingPane>
        <One />
      </CustomSlidingPane>
    </div>
  );
}
</code>```

Body:
I'm using a library called SlidingPane, and each pane has the exact same styles, just different content depending on the page. So I want to put it into a separate page, and get the content through an argument:

export default function CustomSlidingPane(content){
    <SlidingPane
        className="slidingPanel"
        isOpen={state.isPaneOpen}
        onRequestClose={() => {
            setState({ isPaneOpen: false });
        }}
        >
        <Container>
            {content}
        </Container>
    </SlidingPane>
}

All of the content is in separate .js pages that kind of look like this:

export default function One() {
    return (

Hello

    );
}

So what I'm trying to do is pass one of the content functions through to the CustomSlidingPane like this:

import One from './One';
import CustomSlidingPane from './CustomSlidingPane';

export default function Main(){
    <Container>
        <CustomSlidingPane content={<One/>}>
    </Container>
}

Every thing I've tried always ends up in content being undefined. Is there any proper way to do this / is this even possible?

Body:
You will need to use children prop here. I am adding an example with a simple div element.

export default function CustomSlidingPane(props) {
  return <div>{props.children}</div>;
}

Content will be same as you defined in your example:

export default function One() {
  return <h1>Hello</h1>;
}

This is how you can pass the content to your slidingPlane component:

export default function Main() {
  return (
    <div>
      <CustomSlidingPane>
        <One />
      </CustomSlidingPane>
    </div>
  );
}


问:
Angular: How to Select 2 Radio Buttons between 2 Radio Groups in Material?
This is my component form:

```<code><div class="col-3 col-sm-3 col-md-3 mb-2">
    <mat-radio-group aria-label="Select an option" formControlName="gender">
        <mat-radio-button [value]="true" [checked]="false" name="male">Male</mat-radio-button>
        <mat-radio-button [value]="false" [checked]="false" name="famale">Famale</mat-radio-button>
    </mat-radio-group>
    <mat-radio-group aria-label="Select an option" formControlName="name">
        <mat-radio-button [value]="false" [checked]="false"  name="benjamin">Benjamin</mat-radio-button>
        <mat-radio-button [value]="true" [checked]="false"  name="sarah">Sarah</mat-radio-button>
    </mat-radio-group>
</div>
</code>```

I want to achieve something like this:

i.e. if I select the gender, the name referring to the currently selected gender should be automatically selected.

答:
```<code><div class="col-3 col-sm-3 col-md-3 mb-2">
    <mat-radio-group aria-label="Select an option" formControlName="gender">
        <mat-radio-button [value]="true" [checked]="false" name="male">Male</mat-radio-button>
        <mat-radio-button [value]="false" [checked]="false" name="famale">Famale</mat-radio-button>
    </mat-radio-group>
    <mat-radio-group aria-label="Select an option" formControlName="name">
        <mat-radio-button [value]="true" [checked]="form.controls['gender'].value === true" name="benjamin">Benjamin</mat-radio-button>
        <mat-radio-button [value]="false" [checked]="form.controls['gender'].value === false" name="sarah">Sarah</mat-radio-button>
    </mat-radio-group>
</div>
</code>```

Body:
This is my component form:

    <mat-radio-group aria-label="Select an option" formControlName="gender">
        <mat-radio-button [value]="true" [checked]="false" name="male">Male</mat-radio-button>
        <mat-radio-button [value]="false" [checked]="false" name="famale">Famale</mat-radio-button>
    </mat-radio-group>
    <mat-radio-group aria-label="Select an option" formControlName="name">
        <mat-radio-button [value]="false" [checked]="false"  name="benjamin">Benjamin</mat-radio-button>
        <mat-radio-button [value]="true" [checked]="false"  name="sarah">Sarah</mat-radio-button>
    </mat-radio-group>

I want to achieve something like this:

i.e. if I select the gender, the name referring to the currently selected gender should be automatically selected.


问:
Next.js with MongoDB and Mongoose throws 500 Internal Server Error when deploy it on Vercel
My application is working on localhost without problem. When I deploy it tho vercel through github it throws error. My building logs are like that

Cloning github.com/sayinmehmet47/electronic-products47 (Branch: main, Commit: 2ae970b)
Cloning completed: 738.588ms
Analyzing source code...
Installing build runtime...
Build runtime installed: 2.071s
Looking up build cache...
Build Cache not found
Installing dependencies...
yarn install v1.22.17
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning "next > styled-jsx > @babel/plugin-syntax-jsx@7.14.5" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "react-chrono > @emotion/styled > @emotion/babel-plugin@11.7.2" has unmet peer dependency "@babel/core@^7.0.0".
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
warning " > slick-carousel@1.8.1" has unmet peer dependency "jquery@>=1.8.0".
[4/4] Building fresh packages...
Done in 44.34s.
Detected Next.js version: 12.0.7
Running "yarn run build"
yarn run v1.22.17
$ next build
info  - Loaded env from /vercel/path0/.env.production
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Checking validity of types...
warn  - No ESLint configuration detected. Run next lint to begin setup
info  - Creating an optimized production build...
info  - Compiled successfully
info  - Collecting page data...
info  - Generating static pages (0/4)
info  - Generating static pages (1/4)
info  - Generating static pages (2/4)
info  - Generating static pages (3/4)
info  - Generating static pages (4/4)
info  - Finalizing page optimization...
Page                                       Size     First Load JS
┌ λ /                                      17.4 kB         116 kB
├   └ css/5674832e1468d24d.css             1.14 kB
├   /_app                                  0 B            85.6 kB
├ ○ /404                                   194 B          85.8 kB
├ λ /api/orders                            0 B            85.6 kB
├ λ /api/orders/[id]                       0 B            85.6 kB
├ λ /api/products                          0 B            85.6 kB
├ λ /api/products/[id]                     0 B            85.6 kB
├ ○ /card                                  2.48 kB         104 kB
├ λ /orders/[id]                           26.3 kB         119 kB
├ ○ /payment/Paypal                        1.05 kB        96.4 kB
└ λ /product/[id]                          3.31 kB        94.8 kB
+ First Load JS shared by all              85.6 kB
  ├ chunks/framework-91d7f78b5b4003c8.js   42 kB
  ├ chunks/main-d98b4a7f39fdfc80.js        28.2 kB
  ├ chunks/pages/_app-9a201061d3b88321.js  14.6 kB
  ├ chunks/webpack-49b6f2937c9ce9f4.js     838 B
  └ css/736f475f789b4b00.css               6.93 kB
λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
Done in 21.93s.
Traced Next.js server files in: 309.973ms
Created all serverless functions in: 1.013s
Uploading build outputs...
Deploying build outputs...
Build completed. Populating build cache...
Uploading build cache [76.45 MB]...
Build cache uploaded: 1.436s
Done with "package.json"

```
<p>When I check my functions logs I have this error.</p>
<pre class="lang-js prettyprint-override"><code>[GET] /
13:39:09:78
,
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'electronic-products47.vercel.app',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://electronic-products47.vercel.app/api/products',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Sun, 06 Feb 2022 11:39:10 GMT',
      'content-type': 'application/json',
      connection: 'close',
      'x-vercel-error': 'DEPLOYMENT_NOT_FOUND',
      'content-length': '85',
      server: 'Vercel',
      'x-vercel-id': 'iad1::gxt5k-1644147550847-622d8eef832b',
      'strict-transport-security': 'max-age=63072000; includeSubDomains; preload',
      'cache-control': 'public, max-age=0, must-revalidate',
      'x-vercel-cache': 'MISS'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'get',
      url: 'https://electronic-products47.vercel.app/api/products',
      data: undefined
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'GET /api/products HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.25.0\r\n' +
        'Host: electronic-products47.vercel.app\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/products',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'electronic-products47.vercel.app',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON],
  page: '/'
}
RequestId: 0353ce42-21d7-4ba1-80df-1a9f40898eef Error: Runtime exited with error: exit status 1
Runtime.ExitError
</code>```

I have environment variables that I also added them to vercel.

MONGODB_URI= mongodb+srv://***@cluster0.ywv3z.mongodb.net/electronicProducts?retryWrites=true&w=majority
MONGODB_DB= "electronic-products47"
PROD_URL = "https://electronic-products47.vercel.app"
DEV_URL = "http://localhost:3000"
```
<p>When I fetch some API by getServerSideProps I use this snippet</p>
<pre class="lang-js prettyprint-override"><code>export async function getServerSideProps({ params }) {
  let dev = process.env.NODE_ENV !== "production";
  let { DEV_URL, PROD_URL } = process.env;
  await dbConnect();
  const res = await fetch(
    `${dev ? DEV_URL : PROD_URL}/api/products/${params.id}`
  );
  const data = await res.json();
  return { props: { product: data } };
}

</code>```

I also followed this essay to host my app essay

Here my api/products route

import dbConnect from "../../../lib/mongodb";
import Products from "../../../models/Products";

export default async function handler(req, res) {
  const { method } = req;
  dbConnect();
  if (method === "GET") {
    try {
      const products = await Products.find();
      res.status(200).json(products);
    } catch (err) {
      res.status(500).json(err);
    }
  }

  if (method === "POST") {
    try {
      const product = await Products.create(req.body);
      res.status(201).json(product);
    } catch (err) {
      res.status(500).json(err);
    }
  }
}
```

答:
I refactored my some components. I call my MongoDB inside serverSideProps other than calling my /api/product again

import Cards from "../components/Cards";
import CarouselComponent from "../components/Carousel";
import { Navbar } from "../components/Navbar";
import dbConnect from "../lib/mongodb";
import Products from "../models/Products";
// import "tw-elements";

export default function Home({ products }) {
  console.log(products);
  return (

      <Navbar />
      <CarouselComponent />
      <Cards products={products} />

  );
}

export async function getServerSideProps() {
  // Fetch data from external API
  await dbConnect();
  const data = await Products.find().lean();

  // Pass data to the page via props
  return {
    props: {
      products: JSON.parse(JSON.stringify(data)),
    },
  };
}

```

As you see I import my model Product and fetch the data directly
This is the repo related
https://github.com/sayinmehmet47/electronic-products47

Body:
My application is working on localhost without problem. When I deploy it tho vercel through github it throws error. My building logs are like that

Cloning github.com/sayinmehmet47/electronic-products47 (Branch: main, Commit: 2ae970b)
Cloning completed: 738.588ms
Analyzing source code...
Installing build runtime...
Build runtime installed: 2.071s
Looking up build cache...
Build Cache not found
Installing dependencies...
yarn install v1.22.17
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning "next > styled-jsx > @babel/plugin-syntax-jsx@7.14.5" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "react-chrono > @emotion/styled > @emotion/babel-plugin@11.7.2" has unmet peer dependency "@babel/core@^7.0.0".
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
warning " > slick-carousel@1.8.1" has unmet peer dependency "jquery@>=1.8.0".
[4/4] Building fresh packages...
Done in 44.34s.
Detected Next.js version: 12.0.7
Running "yarn run build"
yarn run v1.22.17
$ next build
info  - Loaded env from /vercel/path0/.env.production
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Checking validity of types...
warn  - No ESLint configuration detected. Run next lint to begin setup
info  - Creating an optimized production build...
info  - Compiled successfully
info  - Collecting page data...
info  - Generating static pages (0/4)
info  - Generating static pages (1/4)
info  - Generating static pages (2/4)
info  - Generating static pages (3/4)
info  - Generating static pages (4/4)
info  - Finalizing page optimization...
Page                                       Size     First Load JS
┌ λ /                                      17.4 kB         116 kB
├   └ css/5674832e1468d24d.css             1.14 kB
├   /_app                                  0 B            85.6 kB
├ ○ /404                                   194 B          85.8 kB
├ λ /api/orders                            0 B            85.6 kB
├ λ /api/orders/[id]                       0 B            85.6 kB
├ λ /api/products                          0 B            85.6 kB
├ λ /api/products/[id]                     0 B            85.6 kB
├ ○ /card                                  2.48 kB         104 kB
├ λ /orders/[id]                           26.3 kB         119 kB
├ ○ /payment/Paypal                        1.05 kB        96.4 kB
└ λ /product/[id]                          3.31 kB        94.8 kB
+ First Load JS shared by all              85.6 kB
  ├ chunks/framework-91d7f78b5b4003c8.js   42 kB
  ├ chunks/main-d98b4a7f39fdfc80.js        28.2 kB
  ├ chunks/pages/_app-9a201061d3b88321.js  14.6 kB
  ├ chunks/webpack-49b6f2937c9ce9f4.js     838 B
  └ css/736f475f789b4b00.css               6.93 kB
λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
Done in 21.93s.
Traced Next.js server files in: 309.973ms
Created all serverless functions in: 1.013s
Uploading build outputs...
Deploying build outputs...
Build completed. Populating build cache...
Uploading build cache [76.45 MB]...
Build cache uploaded: 1.436s
Done with "package.json"

When I check my functions logs I have this error.

[GET] /
13:39:09:78
,
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'electronic-products47.vercel.app',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://electronic-products47.vercel.app/api/products',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Sun, 06 Feb 2022 11:39:10 GMT',
      'content-type': 'application/json',
      connection: 'close',
      'x-vercel-error': 'DEPLOYMENT_NOT_FOUND',
      'content-length': '85',
      server: 'Vercel',
      'x-vercel-id': 'iad1::gxt5k-1644147550847-622d8eef832b',
      'strict-transport-security': 'max-age=63072000; includeSubDomains; preload',
      'cache-control': 'public, max-age=0, must-revalidate',
      'x-vercel-cache': 'MISS'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'get',
      url: 'https://electronic-products47.vercel.app/api/products',
      data: undefined
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'GET /api/products HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.25.0\r\n' +
        'Host: electronic-products47.vercel.app\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/products',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'electronic-products47.vercel.app',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON],
  page: '/'
}
RequestId: 0353ce42-21d7-4ba1-80df-1a9f40898eef Error: Runtime exited with error: exit status 1
Runtime.ExitError

I have environment variables that I also added them to vercel.

MONGODB_URI= mongodb+srv://***@cluster0.ywv3z.mongodb.net/electronicProducts?retryWrites=true&w=majority
MONGODB_DB= "electronic-products47"
PROD_URL = "https://electronic-products47.vercel.app"
DEV_URL = "http://localhost:3000"

When I fetch some API by getServerSideProps I use this snippet

export async function getServerSideProps({ params }) {
  let dev = process.env.NODE_ENV !== "production";
  let { DEV_URL, PROD_URL } = process.env;
  await dbConnect();
  const res = await fetch(
    `${dev ? DEV_URL : PROD_URL}/api/products/${params.id}`
  );
  const data = await res.json();
  return { props: { product: data } };
}

I also followed this essay to host my app essay

Here my api/products route

import dbConnect from "../../../lib/mongodb";
import Products from "../../../models/Products";

export default async function handler(req, res) {
  const { method } = req;
  dbConnect();
  if (method === "GET") {
    try {
      const products = await Products.find();
      res.status(200).json(products);
    } catch (err) {
      res.status(500).json(err);
    }
  }

  if (method === "POST") {
    try {
      const product = await Products.create(req.body);
      res.status(201).json(product);
    } catch (err) {
      res.status(500).json(err);
    }
  }
}

Body:
I refactored my some components. I call my MongoDB inside serverSideProps other than calling my /api/product again

import Cards from "../components/Cards";
import CarouselComponent from "../components/Carousel";
import { Navbar } from "../components/Navbar";
import dbConnect from "../lib/mongodb";
import Products from "../models/Products";
// import "tw-elements";

export default function Home({ products }) {
  console.log(products);
  return (
    <div className="">
      <Navbar />
      <CarouselComponent />
      <Cards products={products} />
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch data from external API
  await dbConnect();
  const data = await Products.find().lean();

  // Pass data to the page via props
  return {
    props: {
      products: JSON.parse(JSON.stringify(data)),
    },
  };
}

As you see I import my model Product and fetch the data directly
This is the repo related
https://github.com/sayinmehmet47/electronic-products47


问:
What language could let us get the defined parameter name and passed parameter name?
For example, I defined a method:

```<code>def hello(String name) {
    println("Hello " + name)
}
</code>```

I want to the the name of argument in runtime:

```<code>def hello(String name) {
     println("The name of the parameter of this method is: " + getParamName())
     // getParamName() will be `name` here
}
</code>```

And, I expect to get the passed name of the parameter:

```<code>def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}

String user1 = "someone"
hello(user1)
</code>```

It will print:

```<code>Passed parameter name:  user1
</code>```

Notice, here is user1, the variable name!

I know this is difficult, since java/groovy/scala can't do it. But I think it's a very useful feature(especially for web-framework design). Is there a language can do it?

答:
You can't get the name of an argument in general because the argument may not be a named variable. Given this:

```<code>def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}
</code>```

What would it output here:

```<code>hello("a literal")
hello("an " + "expression")
</code>```

Given that, there are some languages that let you access the raw AST of the passed argument. Macros in Lisp, Io, and Ioke all let you define functions that will take a chunk of unevaluated code as the argument, which you can then inspect.

ContentLicense: CC BY-SA 3.0

Body:
For example, I defined a method:

def hello(String name) {
    println("Hello " + name)
}

I want to the the name of argument in runtime:

def hello(String name) {
     println("The name of the parameter of this method is: " + getParamName())
     // getParamName() will be `name` here
}

And, I expect to get the passed name of the parameter:

def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}

String user1 = "someone"
hello(user1)

It will print:

Passed parameter name:  user1

Notice, here is user1, the variable name!

I know this is difficult, since java/groovy/scala can't do it. But I think it's a very useful feature(especially for web-framework design). Is there a language can do it?

Body:
You can't get the name of an argument in general because the argument may not be a named variable. Given this:

def hello(String name) {
    println("Passed parameter name: " + getPassedName())
}

What would it output here:

hello("a literal")
hello("an " + "expression")

Given that, there are some languages that let you access the raw AST of the passed argument. Macros in Lisp, Io, and Ioke all let you define functions that will take a chunk of unevaluated code as the argument, which you can then inspect.


问:
How to pass an unknown data type through to printf in C
I'm porting some C code which contains function calls like this:

```<code>...
char string[] = "Hello";
int data = 3;
char fmt[] = "%d";
printit(string, &data, fmt);
...
/* Elsewhere */

char string[] = "Hello";
float fdata = 3.1416;
char ffmt[] = "%f";
printit(string, &fdata, ffmt);

</code>```

The function prototype for printit is:

void printit( char *s, void *data, char *format);

I don't have the code for printit (that's part of what I have to do in porting), but from context it is supposed to print the first string then pass the data and format to printf. At various points in the code, printit is called with data of various types. Since the number of arguments to printit is always the same, it doesn't seem like the whole machinery of varargs should be necessary to accomplish this but I haven't cracked a simpler way. What am I missing?

答:
Here is a skeleton of the code I think you're going to need:

```<code>void printit(char *s, void *data, char *format)
{
    char fmt[4];
    fmt[0] = format[strlen(format)-1];    /* last char of format */
    fmt[1] = '\0';

    fputs(s, stdout);

    if(strcmp(fmt, "d") == 0) {
        int i = *(int *)data;
        printf(format, i);
    } else if(strcmp(fmt, "f") == 0) {
        double d = *(double *)data;
        printf(format, d);
    } ...
}
</code>```

The key to this is that, once we know what type we're operating on, we take the "generic" data pointer and cast it to a "real" pointer type (int *, double *, etc.), and indirect on it with * to fetch the pointed-to value.

You'll have to do a trickier extraction of fmt if you want to handle types long int (%ld), long double (%Lf), or long long int (%lld).

Body:
I'm porting some C code which contains function calls like this:

...
char string[] = "Hello";
int data = 3;
char fmt[] = "%d";
printit(string, &data, fmt);
...
/* Elsewhere */

char string[] = "Hello";
float fdata = 3.1416;
char ffmt[] = "%f";
printit(string, &fdata, ffmt);

The function prototype for printit is:

void printit( char *s, void *data, char *format);

I don't have the code for printit (that's part of what I have to do in porting), but from context it is supposed to print the first string then pass the data and format to printf. At various points in the code, printit is called with data of various types. Since the number of arguments to printit is always the same, it doesn't seem like the whole machinery of varargs should be necessary to accomplish this but I haven't cracked a simpler way. What am I missing?

Body:
Here is a skeleton of the code I think you're going to need:

void printit(char *s, void *data, char *format)
{
    char fmt[4];
    fmt[0] = format[strlen(format)-1];    /* last char of format */
    fmt[1] = '\0';

    fputs(s, stdout);

    if(strcmp(fmt, "d") == 0) {
        int i = *(int *)data;
        printf(format, i);
    } else if(strcmp(fmt, "f") == 0) {
        double d = *(double *)data;
        printf(format, d);
    } ...
}

The key to this is that, once we know what type we're operating on, we take the "generic" data pointer and cast it to a "real" pointer type (int *, double *, etc.), and indirect on it with * to fetch the pointed-to value.

You'll have to do a trickier extraction of fmt if you want to handle types long int (%ld), long double (%Lf), or long long int (%lld).


问:
Python Ursina car move direction
I want to make some racing game in Python Ursina. I made my car model with rotating (changing drive directions), but I want to make it drive, where car is rotated using "w" key. But it still go only direction up, even when it's rotated and I want it to go direction which is car facing.

Code is here:

```<code>def update():

player.y += held_keys['w'] * time.dt * 0.7
player.y -= held_keys['s'] * time.dt * 0.7

if held_keys['d']:
    player.rotation_z = player.rotation_z + time.dt + 2.5

if held_keys['a']:
    player.rotation_z = player.rotation_z + time.dt - 2.5
</code>```

Thanks for your time!

答: Do player.position += player.up instead, to move it in the up direction, taking rotation into account.

Title: Python Ursina car move direction

Body:
I want to make some racing game in Python Ursina. I made my car model with rotating (changing drive directions), but I want to make it drive, where car is rotated using "w" key. But it still go only direction up, even when it's rotated and I want it to go direction which is car facing.

Code is here:

def update():

player.y += held_keys['w'] * time.dt * 0.7
player.y -= held_keys['s'] * time.dt * 0.7

if held_keys['d']:
    player.rotation_z = player.rotation_z + time.dt + 2.5

if held_keys['a']:
    player.rotation_z = player.rotation_z + time.dt - 2.5

Thanks for your time!


问:
Unable to resolve service for type Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger
I am having difficulties to scaffold an existing MySQL database using EF core.
I have added the required dependencies as mentioned in the oracle doc:

```<code><PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkcore.Tools" Version="6.0.0">
</code>```

and then, I ran this code in the package manager console:

```<code>Scaffold-Dbcontext "server=the.server.ip.address;user=user_name;database=db_name;password=db_password;port=3306" MySql.EntityFrameworkCore -o Data -v
</code>```

It shows this error:

Unable to resolve service for type
'Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[Microsoft.EntityFrameworkCore.DbLoggerCategory+Scaffolding]'
while attempting to activate
'MySql.EntityFrameworkCore.Scaffolding.Internal.MySQLDatabaseModelFactory'

Here are the relevant logs in the output window:

```<code>Finding design-time services referenced by assembly 'Test2'...
Finding design-time services referenced by assembly 'Test2'...
No referenced design-time services were found.
Finding design-time services for provider 'MySql.EntityFrameworkCore'...
Using design-time services from provider 'MySql.EntityFrameworkCore'.
Finding IDesignTimeServices implementations in assembly 'Test2'...
No design-time services were found.
</code>```

I don't know how shall I implement the design time classes and nor did I find any useful links in the web.

Note that I can access and run query on the database using MySQL Workbench.

答:
I got this error not while scaffolding but when trying to create my first migration.  I didn't want to downgrade to 5.0 because it would've had to be permanent since I was going to run a lot of migrations.

I fixed it by changing my provider from MySql.Data.EntityFrameworkCore to Pomelo.EntityFrameworkCore.MySql

Remove the old provider from both my API and DAL projects:

dotnet remove package MySql.EntityFrameworkCore

Add Pomelo provider

dotnet add package Pomelo.EntityFrameworkCore.MySql

Update your startup to use Pomelos configuartion:

https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql#2-services-configuration

Migrations are working:

dotnet ef migrations add InitialCreate

Body:
I am having difficulties to scaffold an existing MySQL database using EF core.
I have added the required dependencies as mentioned in the oracle doc:

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkcore.Tools" Version="6.0.0">

and then, I ran this code in the package manager console:

Scaffold-Dbcontext "server=the.server.ip.address;user=user_name;database=db_name;password=db_password;port=3306" MySql.EntityFrameworkCore -o Data -v

It shows this error:

Unable to resolve service for type
'Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[Microsoft.EntityFrameworkCore.DbLoggerCategory+Scaffolding]'
while attempting to activate
'MySql.EntityFrameworkCore.Scaffolding.Internal.MySQLDatabaseModelFactory'

Here are the relevant logs in the output window:

Finding design-time services referenced by assembly 'Test2'...
Finding design-time services referenced by assembly 'Test2'...
No referenced design-time services were found.
Finding design-time services for provider 'MySql.EntityFrameworkCore'...
Using design-time services from provider 'MySql.EntityFrameworkCore'.
Finding IDesignTimeServices implementations in assembly 'Test2'...
No design-time services were found.

I don't know how shall I implement the design time classes and nor did I find any useful links in the web.

Note that I can access and run query on the database using MySQL Workbench.


问:
Address of operator and r-value
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

```<code>int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}
</code>```

答:
Here you define the object a to be an array of 5 integers.

```<code>    int a[5] = {1,2,3,4,5};
</code>```

Here, you use &a, which mean, a pointer to an object which is an array of 5 integers -- sizeof(a)=5*sizeof(int).

The object &a+1 is a pointer to an array of 5 integers as well (if you do (&a+1)-a you will get sizeof(a)), which is 5*sizeof(int). So, ptr will point 5 integers beyond a (which is the same asa[0]).

```<code>    int *ptr = (int*)(&a+1);
</code>```

Next, you access *(ptr-1), but this time the pointer arithmetics will subtract only sizeof(int) from ptr, as ptr has type pointer to int -- you will access an integer at an address ptr[-1], which falls inside the first array of five elements, (&a)[0], it points on its last integer.

```<code>    printf("%d %d", *(a+1), *(ptr-1));
</code>```

*(a+1) is simple, it is just a[1], of type integer.

```<code>     &(a[1])       ptr-1 ptr
     |              |    |
     V              V    V
+----+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+----+
^                        ^                        ^
+------------------------+------------------------+
|                        |                        |
&a                       &a+1                     &a+2
</code>```

Title: Address of operator and r-value

Body:
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}

Body:
Here you define the object a to be an array of 5 integers.

    int a[5] = {1,2,3,4,5};

Here, you use &a, which mean, a pointer to an object which is an array of 5 integers -- sizeof(a)=5*sizeof(int).

The object &a+1 is a pointer to an array of 5 integers as well (if you do (&a+1)-a you will get sizeof(a)), which is 5*sizeof(int). So, ptr will point 5 integers beyond a (which is the same asa[0]).

    int *ptr = (int*)(&a+1);

Next, you access *(ptr-1), but this time the pointer arithmetics will subtract only sizeof(int) from ptr, as ptr has type pointer to int -- you will access an integer at an address ptr[-1], which falls inside the first array of five elements, (&a)[0], it points on its last integer.

    printf("%d %d", *(a+1), *(ptr-1));

*(a+1) is simple, it is just a[1], of type integer.

     &(a[1])       ptr-1 ptr
     |              |    |
     V              V    V
+----+----+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+----+----+
^                        ^                        ^
+------------------------+------------------------+
|                        |                        |
&a                       &a+1                     &a+2


问:
Java Math issue incorrect output
(51^43)Mod77 in scientific calculator gives 2 as the output however,

(int)(Math.pow(51,43)%(double)77) gives 12 which should be 2 instead.

Can you please help ?

Title: Java Math issue incorrect output

Body:
Instead of:

(int)(Math.pow(51,43)%(double)77)

do:

(int)(Math.pow(51,43))%((double)77)


问:
How do I join on two columns from multiple csv files in neo4j?
This is my first time using neo4j and I have spent past 3.5 hours in figuring out on how to join two csv files.

sample_user contains

sample_order contains

Now I simply want for each user_id what were my top 2 products by timestamp(recency of timestamp). For that I am joining sample_user to sample_order on user_id to get the other info sample_order contains. Is that the correct approach?

I have tried this till now but nothing seems to work!

```<code>LOAD CSV with headers FROM 'file:///sample_users.csv' AS row with row where row.user_phone_number is not null
merge(n:user_id {Name:row.user_id})
merge(m:user_phone_number{Name:row.user_phone_number})
merge(l:location{Name:row.location})
with *
LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.distance}]->(o)
</code>```

Different sites offering different ways by using SET and define uniqueness. Please help!

UPDATE!!! I could merge on the same table like

```<code>LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row with order_row where  order_row.product is not null
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.order_id}]->(o)
</code>```

I just want to merge this order_row.user_id with other table's user_id too in order to get their first_name, location. Basically merge both the csv files.

答:
After spending hours: i finally cracked this.
Query to merge two csv files on user ID.</p>
```<code>//load user nodes

LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row

MERGE(u:User {user_id:row.user_id, name:row.first_name, location:row.location})

RETURN count(u);

//load order nodes

LOAD CSV WITH HEADERS FROM 'file:///sample_orders.csv' AS row WITH row WHERE row.order_id IS NOT NULL

MERGE(o:Orders {order_id:row.order_id, order_ts:row.order_ts, user_id_2:row.user_id, product:row.product})

RETURN count(o);

//Create relationships

LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row

MATCH(u:User{user_id:row.user_id})

MATCH(o:Orders{user_id_2:row.user_id})

MERGE(u)-[:HAS_ORDERED]->(o)

RETURN *;
</code>```

Body:
This is my first time using neo4j and I have spent past 3.5 hours in figuring out on how to join two csv files.

sample_user contains

sample_order contains

Now I simply want for each user_id what were my top 2 products by timestamp(recency of timestamp). For that I am joining sample_user to sample_order on user_id to get the other info sample_order contains. Is that the correct approach?

I have tried this till now but nothing seems to work!

LOAD CSV with headers FROM 'file:///sample_users.csv' AS row with row where row.user_phone_number is not null
merge(n:user_id {Name:row.user_id})
merge(m:user_phone_number{Name:row.user_phone_number})
merge(l:location{Name:row.location})
with *
LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.distance}]->(o)

Different sites offering different ways by using SET and define uniqueness. Please help!

UPDATE!!! I could merge on the same table like

LOAD CSV with headers FROM 'file:///sample_orders.csv' AS order_row with order_row where  order_row.product is not null
merge(o:order_id {Name:order_row.order_id})
merge(t:order_ts{Name:order_row.order_ts})
merge(u:user_id{Name:order_row.user_id})
merge(p:product{Name:order_row.product})
merge(u) - [:TO {x:order_row.order_id}]->(o)

I just want to merge this order_row.user_id with other table's user_id too in order to get their first_name, location. Basically merge both the csv files.

Body:
After spending hours: i finally cracked this.
Query to merge two csv files on user ID.

//load user nodes

LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row

MERGE(u:User {user_id:row.user_id, name:row.first_name, location:row.location})

RETURN count(u);

//load order nodes

LOAD CSV WITH HEADERS FROM 'file:///sample_orders.csv' AS row WITH row WHERE row.order_id IS NOT NULL

MERGE(o:Orders {order_id:row.order_id, order_ts:row.order_ts, user_id_2:row.user_id, product:row.product})

RETURN count(o);

//Create relationships

LOAD CSV WITH HEADERS FROM 'file:///sample_users.csv' AS row

MATCH(u:User{user_id:row.user_id})

MATCH(o:Orders{user_id_2:row.user_id})

MERGE(u)-[:HAS_ORDERED]->(o)

RETURN *;


问:
Will destructor delete built-in types and pointer objects?
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor:

in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type."

So if I have such a class:

```<code>class Foo {
  ~Foo() { delete pi; }
  int *pi;
  int i;
};
</code>```

When an instance of Foo is going to  be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed.

In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor."

I understand that the synthesized destructor does not de-allocate the memory that has been allocated by new and is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of class Foo, does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?

答:
What the spec means is that no code is run to clean up int i. It simply ceases to exist. Its memory is part of Foo and whenever a Foo instance is released, then i goes with it.

For pointers the same is true, the pointer itself will simply disappear (it's really just another number), but the pointer might point at something that needs to also be released. The compiler doesn't know if that is the case, so you have to write a destructor.

This is why things like std::shared_ptr exist; they are clever pointers (aka 'smart') and the compiler does know if it points at something that needs to be released and will generate the correct code to do so. This is why you should always use smart pointers instead of 'naked' ones (like int *p).

Body:
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor:

in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type of the member. Members of class type are destroyed by running the member’s own destructor. The built-in types do not have destructors, so nothing is done to destroy members of built-in type."

So if I have such a class:

class Foo {
  ~Foo() { delete pi; }
  int *pi;
  int i;
};

When an instance of Foo is going to  be destroyed, according to the above text, the built in type variable int i will not be destroyed? Then how it will exist since the object to which it belongs has been destroyed.

In chapter 13.1.4: "The HasPtr class that we have used in the exercises is a good example (§ 13.1.1,p.499). That class allocates dynamic memory in its constructor. The synthesized destructor will not delete a data member that is a pointer. Therefore, this class needs to define a destructor to free the memory allocated by its constructor."

I understand that the synthesized destructor does not de-allocate the memory that has been allocated by new and is pointed to by plain pointers, but here in the text, it indicates that the pointer object itself is also not deleted by the synthesized pointer. Still the example of class Foo, does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?


问:
How do you control how many chunks are built before it is sent?
I am using GRPC to chunk data so it sends smaller chunks.  For the most part it is okay, but I tried to do a streamAll of a table rather than getting a single entry and from the client side it does not appear to be getting any of the stream chunks of messages that I am sending via onNext() on the server.

Is there something I am missing or is there a relatively large sized buffer that I am not aware of and I'm just using up all my memory?

答: My answer to your other question applies here as well. Try setting flow control using https://grpc.github.io/grpc-java/javadoc/io/grpc/netty/NettyServerBuilder.html#initialFlowControlWindow-int-</p>


问:
How to convert Day.Hours[24hr]:MM:SS into Seconds using Python, Pandas, Data frame?
I would like to convert a time series of a data frame into elapsed time.
The format is Day.Hours[24hr]:MM:SS - it's not the typical DD:HH:MM:SS and I've hit a road block. I've added a few rows of the time series I have below.  Starting at 0day 0hrs 0mins 1.1secs. Ending at 1day 17hrs 40mins 1.1secs. My desired output is a data frame column with 1.1, 10001.1, 20001.1, ...

Any ideas would be great (sometimes the sample rate is not exact so I would like to manipulate the time_data column to allow for any changes)?

Thanks everyone!

```<code>import pandas as pd

time_data = pd.DataFrame({'Time':[
'0.00:00:01.1',
'0.02:46:41.1',
'0.05:33:21.1',
'0.08:20:01.1',
'0.11:06:41.1',
'0.13:53:21.1',
'0.16:40:01.1',
'0.19:26:41.1',
'0.22:13:21.1',
'1.01:00:01.1',
'1.03:46:41.1',
'1.06:33:21.1',
'1.09:20:01.1',
'1.12:06:41.1',
'1.14:53:21.1',
'1.17:40:01.1']})
</code>```

Body:
I would like to convert a time series of a data frame into elapsed time.
The format is Day.Hours[24hr]:MM:SS - it's not the typical DD:HH:MM:SS and I've hit a road block. I've added a few rows of the time series I have below.  Starting at 0day 0hrs 0mins 1.1secs. Ending at 1day 17hrs 40mins 1.1secs. My desired output is a data frame column with 1.1, 10001.1, 20001.1, ...

Any ideas would be great (sometimes the sample rate is not exact so I would like to manipulate the time_data column to allow for any changes)?

Thanks everyone!

import pandas as pd

time_data = pd.DataFrame({'Time':[
'0.00:00:01.1',
'0.02:46:41.1',
'0.05:33:21.1',
'0.08:20:01.1',
'0.11:06:41.1',
'0.13:53:21.1',
'0.16:40:01.1',
'0.19:26:41.1',
'0.22:13:21.1',
'1.01:00:01.1',
'1.03:46:41.1',
'1.06:33:21.1',
'1.09:20:01.1',
'1.12:06:41.1',
'1.14:53:21.1',
'1.17:40:01.1']})

Body:
#Get the days part
time_data['days'] = time_data['Time'].str.split('.').str[0].astype('int')
#Get the time part
time_data['time'] = pd.to_datetime(time_data['Time'].str.split('.').str[1])
#First step in between
time_data['elapsed1'] = time_data['time'] + time_data['days']*pd.Timedelta(24,'H')
#Final step
time_data['elapsed2'] = (time_data['elapsed1'] -  time_data['elapsed1'].iloc[0]).dt.total_seconds()

This gives for the DataFrame:

            Time  days                time            elapsed1  elapsed2
0   0.00:00:01.1     0 2022-02-06 00:00:01 2022-02-06 00:00:01       0.0
1   0.02:46:41.1     0 2022-02-06 02:46:41 2022-02-06 02:46:41   10000.0
2   0.05:33:21.1     0 2022-02-06 05:33:21 2022-02-06 05:33:21   20000.0
3   0.08:20:01.1     0 2022-02-06 08:20:01 2022-02-06 08:20:01   30000.0
4   0.11:06:41.1     0 2022-02-06 11:06:41 2022-02-06 11:06:41   40000.0
5   0.13:53:21.1     0 2022-02-06 13:53:21 2022-02-06 13:53:21   50000.0
6   0.16:40:01.1     0 2022-02-06 16:40:01 2022-02-06 16:40:01   60000.0
7   0.19:26:41.1     0 2022-02-06 19:26:41 2022-02-06 19:26:41   70000.0
8   0.22:13:21.1     0 2022-02-06 22:13:21 2022-02-06 22:13:21   80000.0
9   1.01:00:01.1     1 2022-02-06 01:00:01 2022-02-07 01:00:01   90000.0
10  1.03:46:41.1     1 2022-02-06 03:46:41 2022-02-07 03:46:41  100000.0
11  1.06:33:21.1     1 2022-02-06 06:33:21 2022-02-07 06:33:21  110000.0
12  1.09:20:01.1     1 2022-02-06 09:20:01 2022-02-07 09:20:01  120000.0
13  1.12:06:41.1     1 2022-02-06 12:06:41 2022-02-07 12:06:41  130000.0
14  1.14:53:21.1     1 2022-02-06 14:53:21 2022-02-07 14:53:21  140000.0
15  1.17:40:01.1     1 2022-02-06 17:40:01 2022-02-07 17:40:01  150000.0

It's not the 1.1, etc for the elapsed as you wish, but that should be an easy fix to add an additional offset to the elapsed2 column.


问:
Dispatch is working but it is not updating the state
I am working on a application which uses redux for state management. There, at a some condition, I  want to update the state.

My initial state and reducer function looks like this:

```<code>import { createSlice } from '@reduxjs/toolkit';

const filterDataTemplate = {
  programId: '',
  year: '',
};

const initialState = {
   //some other state
  filterData: { ...filterDataTemplate },
};

const slice = createSlice({
  name: 'editFilterSlice',
  initialState: initialState,
  reducers: {
    updateFilterProgramId: (state, action) => {
      state.filterData.programId = action.payload;
    },
    updateFilterYear: (state, action) => {
      state.filterData.year = action.payload;
    },

  },
});

export const {
  updateFilterYear,
  updateFilterProgramId,
} = slice.actions;

export default slice.reducer;
</code>```

So filter details containg year and programId is obtained with the help of this code:

```<code>const filterDetails = useAppSelector(
   (state) => state.locationsFilter.filterData
 );
</code>```

Let's say I have filter data initially:

```<code>filterDetails: {year:2021, programId: "Ameria"}
</code>```

And i want to have my new filter data to be

```<code>filterDetails: {year: "", programId: "Ameria"}
</code>```

So for this what I am doing:

```<code>const handleDelete = (e) => {
    e.preventDefault();
    if (//some condition) {
      console.log("delete is called");
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}
</code>```

handleDelete function is getting called properly when I am clicking a button because I am getting value inside console.

But after running this code my filter data is not updating. I am not sure what I am doing wrong.
Please help with this.

答:
Action.payload is of object type. So You should reference action.payload.year.
I hope this example will be of any use</p>
```<code>
     setTodoDate: {
       reducer: (state, action: PayloadAction<TodoDate>) => {
         state.currentDate = action!.payload.date;
       },
       prepare: (value) => ({
         payload: { ...value },
       }),
     }
</code>```

Body:
I am working on a application which uses redux for state management. There, at a some condition, I  want to update the state.

My initial state and reducer function looks like this:

import { createSlice } from '@reduxjs/toolkit';

const filterDataTemplate = {
  programId: '',
  year: '',
};

const initialState = {
   //some other state
  filterData: { ...filterDataTemplate },
};

const slice = createSlice({
  name: 'editFilterSlice',
  initialState: initialState,
  reducers: {
    updateFilterProgramId: (state, action) => {
      state.filterData.programId = action.payload;
    },
    updateFilterYear: (state, action) => {
      state.filterData.year = action.payload;
    },

  },
});

export const {
  updateFilterYear,
  updateFilterProgramId,
} = slice.actions;

export default slice.reducer;

So filter details containg year and programId is obtained with the help of this code:

const filterDetails = useAppSelector(
   (state) => state.locationsFilter.filterData
 );

Let's say I have filter data initially:

filterDetails: {year:2021, programId: "Ameria"}

And i want to have my new filter data to be

filterDetails: {year: "", programId: "Ameria"}

So for this what I am doing:

const handleDelete = (e) => {
    e.preventDefault();
    if (//some condition) {
      console.log("delete is called");
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}

handleDelete function is getting called properly when I am clicking a button because I am getting value inside console.

But after running this code my filter data is not updating. I am not sure what I am doing wrong.
Please help with this.

Body:
Action.payload is of object type. So You should reference action.payload.year.
I hope this example will be of any use

     setTodoDate: {
       reducer: (state, action: PayloadAction<TodoDate>) => {
         state.currentDate = action!.payload.date;
       },
       prepare: (value) => ({
         payload: { ...value },
       }),
     }


问:
TypeError: object of type 'int' has no len() when converting list of tuples to pandas data frame
I have a list of tuples like this

```<code>tmp
[('chr19', 50003781, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr10', 52559169, '+', 12460988980),
...]
</code>```

and I have been following many answers from StackOverflow to convert this into a pandas data frame. Basically I need this

```<code>col1    col2      col3     col4
chr19   50003781.  +     5303232448
</code>```

When I tried to do that with for example this

```<code>df = pd.DataFrame(tmp, columns=["col1", "col2", "col3","col4])
</code>```

I got this error

```<code>TypeError: object of type 'int' has no len()
</code>```

Why?

答:
That means, tmp is not a list of tuples, there is an integer in it.

For example,

```<code>tmp = [('chr19', 50003781, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr10', 52559169, '+', 12460988980), 1]
</code>```

will give the same error. See if

```<code>any(isinstance(t, int) for t in tmp)
</code>```

is True or not. If True it means there is an integer value in tmp. In that case, you probably want to filter it out when passing tmp to the DataFrame constructor.

Body:
I have a list of tuples like this

tmp
[('chr19', 50003781, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr10', 52559169, '+', 12460988980),
...]

and I have been following many answers from StackOverflow to convert this into a pandas data frame. Basically I need this

col1    col2      col3     col4
chr19   50003781.  +     5303232448

When I tried to do that with for example this

df = pd.DataFrame(tmp, columns=["col1", "col2", "col3","col4])

I got this error

TypeError: object of type 'int' has no len()

Why?

Body:
That means, tmp is not a list of tuples, there is an integer in it.

For example,

tmp = [('chr19', 50003781, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr19', 58856544, '+', 5303232448),
 ('chr10', 52559169, '+', 12460988980), 1]

will give the same error. See if

any(isinstance(t, int) for t in tmp)

is True or not. If True it means there is an integer value in tmp. In that case, you probably want to filter it out when passing tmp to the DataFrame constructor.


问:
Make H2 treat quoted name and unquoted name as the same
H2 seems to make a difference between name with quote and name without quote. Is there a way to make it treat them the same way?

Here's the tests that I've done :

```<code>CREATE TABLE test (dummy INT);
CREATE TABLE "testquote" (dummy INT, "quotedDummy" INT);
</code>```

Here are the queries :

```<code>SELECT * FROM test; --work
SELECT * FROM "test"; -- doesn't work
SELECT * FROM "testquote"; --work
SELECT * FROM testquote; --doesn't work
SELECT dummy FROM "testquote"; --work
SELECT quotedDummy FROM "testquote"; --doesn't work
SELECT "quotedDummy" FROM "testquote"; --work
</code>```

What can I do to make those queries work with H2?

答:
I was having some weird issue with Hibernate and H2 where if I specified catalog & schema names in @Table annotation, the generated SQL would use the wrong case for the quoted table name causing it to fail.  It's probably a defect, but I found a work-around which I'm sharing here.</p>
```<code>import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;

public class H2IdentifierNamingStrategy extends PhysicalNamingStrategyStandardImpl {
    private static final long serialVersionUID = 1L;

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        if(name==null) return null;
        else return new Identifier(name.getText().toLowerCase(), name.isQuoted());
    }
}
</code>```

Body:
H2 seems to make a difference between name with quote and name without quote. Is there a way to make it treat them the same way?

Here's the tests that I've done :

CREATE TABLE test (dummy INT);
CREATE TABLE "testquote" (dummy INT, "quotedDummy" INT);

Here are the queries :

SELECT * FROM test; --work
SELECT * FROM "test"; -- doesn't work
SELECT * FROM "testquote"; --work
SELECT * FROM testquote; --doesn't work
SELECT dummy FROM "testquote"; --work
SELECT quotedDummy FROM "testquote"; --doesn't work
SELECT "quotedDummy" FROM "testquote"; --work

What can I do to make those queries work with H2?

Body:
I was having some weird issue with Hibernate and H2 where if I specified catalog & schema names in @Table annotation, the generated SQL would use the wrong case for the quoted table name causing it to fail.  It's probably a defect, but I found a work-around which I'm sharing here.

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;

public class H2IdentifierNamingStrategy extends PhysicalNamingStrategyStandardImpl {
    private static final long serialVersionUID = 1L;

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        if(name==null) return null;
        else return new Identifier(name.getText().toLowerCase(), name.isQuoted());
    }
}


答:
A destructor always destroys all members, just like a constructor always creates all members. You can't stop it from doing that.

according to the above text, the built in type variable int i will not be destroyed?

It will be destroyed. What the book says is that destroying an int doesn't perform any actions (it's said to be a "no-op"), in the sense that it translates to 0 machine instructions.

Same for pointers (not the data they point to), so the wording in (2) is sloppy, and your initial understanding was correct.

Title: Will destructor delete built-in types and pointer objects?


问:
localstorage values resetting after refresh and localstorage is not defined
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

```<code>"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

</code>```

Getting the object

```<code>export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}
</code>```

This is my function

```<code>//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

    <div className="grid grid-cols-3 rows-2 text-lg font-bold">
         {storage}

    </div>

<div className="grid grid-cols-3 grid-rows-2 gap-2 bg-black text-white border-white">
        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>

</code>```

答:
You are calling localStorage at wrong places, Even though you used type of window !== 'undefined', you are already calling const favs = JSON.parse(localStorage.getItem('name')) beforehand.

Assuming this is a React component. You can get the localstorage in a useEffect call.

```<code>const Component = () => {
     const [ fav,setFavs ] = useState([]);

     useEffect(() => {
           if (typeof window !== 'undefined') { //necessary because u are using nextjs
                const storage = localStorage.getItem('name');
                if (storage) {
                     setFavs(JSON.parse(storage));
                     //favs will be populated with your localStorage once, on component mount.
                }
           }
     },[])

     const checkId = (e.target.value) => {
          const value = e.target.value;
          if (!value) return;

          const newFavs = [...favs, value]
          localStorage.setItem('name', JSON.stringify(newFavs));
          setFavs(newFavs);
     }

     .....

     return (```{ JSON.stringify(favs, null, 4)}```)
}
</code>```

Bonus

If you want your favs to be unique (values not repeated) then instead of

```<code>const newFavs = [...favs, value]
</code>```

Change it to

```<code>const newFavs = [...new Set([...favs, value])]
</code>```

Reference on Set

Body:
My array and local storage keep resetting after every refresh. I've seen some answers like I need to parse the data and then stringify it. The issue I've faced is I keep getting an error message saying 'local storage is not defined' and an internal server error 500.

I've written the code below

//object

"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

Getting the object

export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

This is my function

//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];

//localstorage is not defined
//define it here
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists
localStorage.getItem('name') === null
 //if exists store it
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);

 }
}

         {storage}

        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count
          })
          .map((d) => (

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>

Body:
You are calling localStorage at wrong places, Even though you used type of window !== 'undefined', you are already calling const favs = JSON.parse(localStorage.getItem('name')) beforehand.

Assuming this is a React component. You can get the localstorage in a useEffect call.

const Component = () => {
     const [ fav,setFavs ] = useState([]);

     useEffect(() => {
           if (typeof window !== 'undefined') { //necessary because u are using nextjs
                const storage = localStorage.getItem('name');
                if (storage) {
                     setFavs(JSON.parse(storage));
                     //favs will be populated with your localStorage once, on component mount.
                }
           }
     },[])

     const checkId = (e.target.value) => {
          const value = e.target.value;
          if (!value) return;

          const newFavs = [...favs, value]
          localStorage.setItem('name', JSON.stringify(newFavs));
          setFavs(newFavs);
     }

     .....

     return (<pre>{ JSON.stringify(favs, null, 4)}</pre>)
}

Bonus

If you want your favs to be unique (values not repeated) then instead of

const newFavs = [...favs, value]

Change it to

const newFavs = [...new Set([...favs, value])]

Reference on Set


问:
Flask route with URI encoded component
It seems Flask doesn't support routes with a URI encoded component.  I'm curious if I'm doing something wrong, or if there is a special flag I need to include.

My route looks something like this:

```<code>@app.route('/foo/<encoded>/bar/')
def foo(encoded):
  # ...
  pass
</code>```

The URL that this should match can look like these:

```<code>http://foobar.com/foo/xxx/bar/ # matched correctly, no URI component
http://foobar.com/foo/x%2Fx%2Fx%2F/bar/ # not matched correctly, URI component
</code>```

Former URL works, latter spits out a lovely 404.

Thanks!

答:
Add path to your url rule:

@app.route('/foo/<path:encoded>/bar/')

Update per comment: The route API docs are here: http://flask.pocoo.org/docs/api/#flask.Flask.route. The underlying classes that implement the path style route converter are here: http://werkzeug.pocoo.org/docs/routing/#custom-converters (this is one of the really nice parts of pocoostan.) As far as the trailing slashes, there are special rules that amount to:

If a rule ends with a slash and is requested without a slash by the
  user, the user is automatically redirected to the same page with a
  trailing slash attached.

If a rule does not end with a trailing slash and the user request the
  page with a trailing slash, a 404 not found is raised.

Also keep in mind that if you are on Apache and are expecting a slash-trailed url, ie a bookmarklet that submits to http://ex.com/foo/<path:encoded>/bar and encoded gets something with double slashes, Apache will convert multiple slashes to a single one.

Title: Flask route with URI encoded component

Body:
It seems Flask doesn't support routes with a URI encoded component.  I'm curious if I'm doing something wrong, or if there is a special flag I need to include.

My route looks something like this:

@app.route('/foo/<encoded>/bar/')
def foo(encoded):
  # ...
  pass

The URL that this should match can look like these:

http://foobar.com/foo/xxx/bar/ # matched correctly, no URI component
http://foobar.com/foo/x%2Fx%2Fx%2F/bar/ # not matched correctly, URI component

Former URL works, latter spits out a lovely 404.

Thanks!


问:
R Studio error: `n()` must only be used inside dplyr verbs
```<code>install.packages(c("ggplot2", "ggpubr", "tidyverse", "broom", "AICcmodavg", "dplyr"))
library(ggplot2)
library(ggpubr)
library(tidyverse)
library(broom)
library(AICcmodavg)

library(dplyr)

my_data <- read.table(file = "clipboard",
                      sep = "\t", header=TRUE)

group_by(my_data, group) %>%
  suppressWarnings(as.numeric(co2))
***dplyr::summarise (count = dplyr::n(), mean = dplyr::mean("CO2", na.rm = TRUE),sd = dplyr::sd("CO2", na.rm = TRUE))***
</code>```

Working towards a one-way ANOVA test on some data I have for my dissertation but the last line (marked with *** above ***) keeps returning the following error code:

Error: n() must only be used inside dplyr verbs.

What could be going wrong?
Thanks for any help you can give!

答:
The error is admittedly a little bit opaque, but we can replicate it as simply as

summarise(count = n())
```
<p>Since you haven't piped the results of the first few lines to the final <code>summarise()</code>, your <code>summarise()</code> call is essentially being read as a standalone function, with a missing <code>data</code> argument (<code>summarise(mtcars, count = n())</code> works OK).</p>
<p>You might be looking for a pipeline like this (illustrated with built-in data set <code>mtcars</code>):</p>
<pre class="lang-r prettyprint-override"><code>library(tidyverse)
group_by(mtcars, cyl) %>%
  mutate(across(mpg, as.numeric)) %>%
  summarise(count = n(),
            mean = mean(mpg, na.rm = TRUE),
            sd = sd(mpg, na.rm = TRUE)
           )
</code>```

By the way, if you're doing an ANOVA you probably don't want to collapse the data to summary statistics first (unless someone is making you do the computations by hand); anova(lm(...)) is more natural, where you apply the lm() to non-aggregated data.

Body:
install.packages(c("ggplot2", "ggpubr", "tidyverse", "broom", "AICcmodavg", "dplyr"))
library(ggplot2)
library(ggpubr)
library(tidyverse)
library(broom)
library(AICcmodavg)

library(dplyr)

my_data <- read.table(file = "clipboard",
                      sep = "\t", header=TRUE)

group_by(my_data, group) %>%
  suppressWarnings(as.numeric(co2))
***dplyr::summarise (count = dplyr::n(), mean = dplyr::mean("CO2", na.rm = TRUE),sd = dplyr::sd("CO2", na.rm = TRUE))***

Working towards a one-way ANOVA test on some data I have for my dissertation but the last line (marked with *** above ***) keeps returning the following error code:

Error: n() must only be used inside dplyr verbs.

What could be going wrong?
Thanks for any help you can give!

Body:
The error is admittedly a little bit opaque, but we can replicate it as simply as

summarise(count = n())

Since you haven't piped the results of the first few lines to the final summarise(), your summarise() call is essentially being read as a standalone function, with a missing data argument (summarise(mtcars, count = n()) works OK).

You might be looking for a pipeline like this (illustrated with built-in data set mtcars):

library(tidyverse)
group_by(mtcars, cyl) %>%
  mutate(across(mpg, as.numeric)) %>%
  summarise(count = n(),
            mean = mean(mpg, na.rm = TRUE),
            sd = sd(mpg, na.rm = TRUE)
           )

By the way, if you're doing an ANOVA you probably don't want to collapse the data to summary statistics first (unless someone is making you do the computations by hand); anova(lm(...)) is more natural, where you apply the lm() to non-aggregated data.


问:
MySQL MIN() + 1 row
I am running a SELECT query to get data from MySQL

```<code>SELECT
    MIN(datetime) as created,
    MAX(datetime) as updated,
    COUNT(CASE WHEN type = 'update' AND contact_name <> 'System' THEN 1 END) as replies,
    COUNT(CASE WHEN type = 'update' AND (contact_name * 1 = contact_name) THEN 1 END) as customer_replies
</code>```

and it's working great, but I want to also get the next row after MIN(datetime)

Is it possible to do something like MIN()+1?

答:
Here is a solution which gives the second lowest value:

```<code>SELECT
    MIN(datetime) as created_second_minimum
FROM TableName
ORDER BY datetime
LIMIT 1,1;
</code>```

When we use LIMIT n it returns the first n lines, when LIMIT n,m it returns m lines after the first n lines (which are not returned). In our example it does not return the first line and returns only the second one. As we have ordered the query by datetime the second line is the second oldest.

Title: MySQL MIN() + 1 row

Body:
I am running a SELECT query to get data from MySQL

SELECT
    MIN(datetime) as created,
    MAX(datetime) as updated,
    COUNT(CASE WHEN type = 'update' AND contact_name <> 'System' THEN 1 END) as replies,
    COUNT(CASE WHEN type = 'update' AND (contact_name * 1 = contact_name) THEN 1 END) as customer_replies

and it's working great, but I want to also get the next row after MIN(datetime)

Is it possible to do something like MIN()+1?

Body:
Here is a solution which gives the second lowest value:

SELECT
    MIN(datetime) as created_second_minimum
FROM TableName
ORDER BY datetime
LIMIT 1,1;

When we use LIMIT n it returns the first n lines, when LIMIT n,m it returns m lines after the first n lines (which are not returned). In our example it does not return the first line and returns only the second one. As we have ordered the query by datetime the second line is the second oldest.


答:
according to the above text, the built in type variable int i will not be destroyed?

It will be destroyed, but nothing is done to destroy it. The destruction is trivial.

int *pi member variable also has a fundamental type, and same applies to it.

Then how it will exist

It won't exist.

does that mean that after an object of Foo class is destroyed, the pointer pi will not be destroyed ( so becomes an invalid pointer )?

It does not mean that. All sub objects are always destroyed both by all synthesised destructors, as well as all user defined destructors.

Deleting a pointer, and destroying a pointer are two separate things. Deletion destroys the pointed object and deallocates the dynamic memory. Destruction ends the lifetime of the pointer itself, and is trivial because pointers are fundamental types.

Destruction is what the synthesised - as well as all other - constructors do to the member. A synthesised destructor never deletes any pointer, but the user defined ~Foo in the example does delete the member.

Although it's important to learn these things, don't use owning bare pointers in practice. Use RAII classes such as smart pointers or containers instead.


Title: How to convert Day.Hours[24hr]:MM:SS into Seconds using Python, Pandas, Data frame?

Body:
Just convert your values to the Timedelta representation format:

timedelta = df['Time'].str.replace('\.', ' days ', n=1, regex=True)

df['Seconds'] = pd.to_timedelta(timedelta).dt.total_seconds()

Output:

>>> df
            Time   Seconds
0   0.00:00:01.1       1.1
1   0.02:46:41.1   10001.1
2   0.05:33:21.1   20001.1
3   0.08:20:01.1   30001.1
4   0.11:06:41.1   40001.1
5   0.13:53:21.1   50001.1
6   0.16:40:01.1   60001.1
7   0.19:26:41.1   70001.1
8   0.22:13:21.1   80001.1
9   1.01:00:01.1   90001.1
10  1.03:46:41.1  100001.1
11  1.06:33:21.1  110001.1
12  1.09:20:01.1  120001.1
13  1.12:06:41.1  130001.1
14  1.14:53:21.1  140001.1
15  1.17:40:01.1  150001.1

Focus on Timedelta:

>>> timedelta
0     0 days 00:00:01.1
1     0 days 02:46:41.1
2     0 days 05:33:21.1
3     0 days 08:20:01.1
4     0 days 11:06:41.1
5     0 days 13:53:21.1
6     0 days 16:40:01.1
7     0 days 19:26:41.1
8     0 days 22:13:21.1
9     1 days 01:00:01.1
10    1 days 03:46:41.1
11    1 days 06:33:21.1
12    1 days 09:20:01.1
13    1 days 12:06:41.1
14    1 days 14:53:21.1
15    1 days 17:40:01.1
Name: Time, dtype: object

To compute the difference between rows, use:

>>> pd.to_timedelta(timedelta).diff().dt.total_seconds()
0         NaN
1     10000.0
2     10000.0
3     10000.0
4     10000.0
5     10000.0
6     10000.0
7     10000.0
8     10000.0
9     10000.0
10    10000.0
11    10000.0
12    10000.0
13    10000.0
14    10000.0
15    10000.0
Name: Time, dtype: float64


问:
why nested foreach within javascript loop not working?
I am trying to check if the answers from a user are correct. The answers of the user are stored in variable "stad". The correct options are stored in variable "collectie". However, this variable is an array with a nested array. So i first loop through the "collectie", check if the collectie element is not an array and if not, check that the submitted value is within this collectie element.

If the collectie element is an array, i have to alter a little bit the function so the variable checks whether the answer is within the nested array.

I have the following:

```<code>function nakijken() {
var collectie = ["parijs", "8", "ijsselmeer", ["Volkswagen", "Audi", "Opel", "Porsche", "BMW", "Mercedes", "Mercedes-Benz"],
["Texel", "Vlieland", "Terschelling", "Ameland", "Schiermonnikoog"]];
var stad = [];
var a = 0;
stad.push(document.getElementsByTagName("input"));
collectie.forEach(uitpakken);
function uitpakken(antwoord) {
    if (!Array.isArray(antwoord)) {
        stad.forEach(myfunction);
        function myfunction(item) {
            if (antwoord.includes(item.value.toLowerCase())) {
                item.style.background = "green";
                a++;
            } else {
                antwoord.style.background = "red";
            }
        }
    }
    else{
        antwoord.Foreach(uitpakken);
        function uitpakken(antwoord) {
        stad.forEach(mysecondfunction);
            function mysecondfunction(item) {
                if (antwoord.includes(item.value.toLowerCase())) {
                    item.style.background = "green";
                    a++;
                } else {
                    antwoord.style.background = "red";
                }
            }
        }
    }
}
</code>```

However, i get the error: item.value is not defined.
Within the console, i see that item is a collection of inputs, and not a single input.

Why is this not working?

答:
document.getElementsByTagName does not return an array, it returns a live HTML collection, which cannot be iterated over with forEach, although you can refer to its elements by index number (https://developer.mozilla.org/en-US/docs/Web/API/document/getElementsByTagName).

In addition, you are then pushing this entire collection to the stad array as one item, which is why you see item is a collection of inputs -- that collection (of live HTML elements) is the only item in the stad array.

As another answer suggests, instead of using stad.push, simply assign a real array to stad by creating an array from the collection:

stad = Array.from(document.getElementsByTagName("input"));

Body:
I am trying to check if the answers from a user are correct. The answers of the user are stored in variable "stad". The correct options are stored in variable "collectie". However, this variable is an array with a nested array. So i first loop through the "collectie", check if the collectie element is not an array and if not, check that the submitted value is within this collectie element.

If the collectie element is an array, i have to alter a little bit the function so the variable checks whether the answer is within the nested array.

I have the following:

function nakijken() {
var collectie = ["parijs", "8", "ijsselmeer", ["Volkswagen", "Audi", "Opel", "Porsche", "BMW", "Mercedes", "Mercedes-Benz"],
["Texel", "Vlieland", "Terschelling", "Ameland", "Schiermonnikoog"]];
var stad = [];
var a = 0;
stad.push(document.getElementsByTagName("input"));
collectie.forEach(uitpakken);
function uitpakken(antwoord) {
    if (!Array.isArray(antwoord)) {
        stad.forEach(myfunction);
        function myfunction(item) {
            if (antwoord.includes(item.value.toLowerCase())) {
                item.style.background = "green";
                a++;
            } else {
                antwoord.style.background = "red";
            }
        }
    }
    else{
        antwoord.Foreach(uitpakken);
        function uitpakken(antwoord) {
        stad.forEach(mysecondfunction);
            function mysecondfunction(item) {
                if (antwoord.includes(item.value.toLowerCase())) {
                    item.style.background = "green";
                    a++;
                } else {
                    antwoord.style.background = "red";
                }
            }
        }
    }
}

However, i get the error: item.value is not defined.
Within the console, i see that item is a collection of inputs, and not a single input.

Why is this not working?