问:
Timezone problem, server uses Central Time but frontend and backend are using UTC
I need assistance regarding best practices for the date/time handling of my web application.

Please excuse my lack of understanding.

This is my setup:
-Server OS: Linux server, it hosts backend and frontend
-Backend: NodeJS and express.js and moment.js
-Frontend: React and moment.js
-Database: phpMyAdmin

The web application is always opened in browsers with a central time, but I noticed that from 18h to the end of day, if I sent a moment.js date object from the client/browser, it would reach the backend with a date of the day after (with an offset of 6 hours later).

So I went to my Linux server, typed date in the terminal and it returned precisely the 6h+ date, which I knew was UTC. For me, and probably in my ignorance, it was obvious that I had to change the server's timezone in order to sync it with the clients that are going to make requests to it. So I did exactly that by issuing these commands in the linux terminal:

I needed this timezone:

```<code>timedatectl set-timezone America/Mexico_City
</code>```

So now typing date in the server returns Central time. I thought that was all but it actually didn't help. The frontend kept sending the dates with what appeared to be universal time (6 hours + from central time) after this change.

Then I read that making the previous change was not going to be permanent, that it would be switched back to default upon rebooting, and that I should use this instead to make the timezone persist:

```<code>ln -sf /usr/share/zoneinfo/America/Mexico_City /etc/localtime
</code>```

So I issued that command too, rebooted the server and checked the server date again, it returned Central time. The server is fully using Central Time now.

So I tested the web application again, and the frontend kept sending UTC instead of Central Time. Now, I'm confused because, as I mentioned, I type date in my linux terminal and it returns Central time. But when the frontend sends the date, it sends UTC (6h+).

So then I decided to test my backend, I created a little route to just check what time it was working with, this time I didn't use moment like I did before. Now I was using the javascript object like so: const currentTime = new Date();. And it returns UTC, again, not using Central time, which is the time at which the server is supposed to be working with.

So, up to this point, when I ask the date in my linux server, it returns Central Time. When I ask the backend or the frontend, it returns UTC (6h+). Out of desperation, I even went ahead and checked what time my database was using, fully knowing that my backend's time-checking route was not actually hitting the database, and ran a simple SELECT NOW(); in phpmyadmin. It returned Central Time.

So I have the feeling that NodeJS is the one responsible for this timezone discrepancy. My question here is, what is the best practice? If I know my date objects are going to be sent frontend to backend and backend to frontend in UTC (6h+), do I change my dates to be sent (6h-) so they're in sync? What do I do to the server date?

Thanks for any input.

Body:
I need assistance regarding best practices for the date/time handling of my web application.

Please excuse my lack of understanding.

This is my setup:
-Server OS: Linux server, it hosts backend and frontend
-Backend: NodeJS and express.js and moment.js
-Frontend: React and moment.js
-Database: phpMyAdmin

The web application is always opened in browsers with a central time, but I noticed that from 18h to the end of day, if I sent a moment.js date object from the client/browser, it would reach the backend with a date of the day after (with an offset of 6 hours later).

So I went to my Linux server, typed date in the terminal and it returned precisely the 6h+ date, which I knew was UTC. For me, and probably in my ignorance, it was obvious that I had to change the server's timezone in order to sync it with the clients that are going to make requests to it. So I did exactly that by issuing these commands in the linux terminal:

I needed this timezone:

timedatectl set-timezone America/Mexico_City

So now typing date in the server returns Central time. I thought that was all but it actually didn't help. The frontend kept sending the dates with what appeared to be universal time (6 hours + from central time) after this change.

Then I read that making the previous change was not going to be permanent, that it would be switched back to default upon rebooting, and that I should use this instead to make the timezone persist:

ln -sf /usr/share/zoneinfo/America/Mexico_City /etc/localtime

So I issued that command too, rebooted the server and checked the server date again, it returned Central time. The server is fully using Central Time now.

So I tested the web application again, and the frontend kept sending UTC instead of Central Time. Now, I'm confused because, as I mentioned, I type date in my linux terminal and it returns Central time. But when the frontend sends the date, it sends UTC (6h+).

So then I decided to test my backend, I created a little route to just check what time it was working with, this time I didn't use moment like I did before. Now I was using the javascript object like so: const currentTime = new Date();. And it returns UTC, again, not using Central time, which is the time at which the server is supposed to be working with.

So, up to this point, when I ask the date in my linux server, it returns Central Time. When I ask the backend or the frontend, it returns UTC (6h+). Out of desperation, I even went ahead and checked what time my database was using, fully knowing that my backend's time-checking route was not actually hitting the database, and ran a simple SELECT NOW(); in phpmyadmin. It returned Central Time.

So I have the feeling that NodeJS is the one responsible for this timezone discrepancy. My question here is, what is the best practice? If I know my date objects are going to be sent frontend to backend and backend to frontend in UTC (6h+), do I change my dates to be sent (6h-) so they're in sync? What do I do to the server date?

Thanks for any input.


来源: stackexchange

问:
Got error "AttributeError: 'TimestepEmbedSequential' object has no attribute '__globals__'" while torch.jit.script()
While trying to script Stable Diffusion model using torch.jit.script(), I got this following error:

```<code>AttributeError: 'TimestepEmbedSequential' object has no attribute '__globals__'
</code>```

I'm trying to export this model to ONNX and found out that running torch.onnx.export() will torch.jit.trace the models, which unrolls every loops, so I'm trying to use script first.

When I follow the traceback, the error occurs in this function while reading fn.__globals__ in _jit_internal.py from torch

```<code>def get_closure(fn):
    """
    Get a dictionary of closed over variables from a function
    """
    captures = {}
    captures.update(fn.__globals__)

    for index, captured_name in enumerate(fn.__code__.co_freevars):
        captures[captured_name] = fn.__closure__[index].cell_contents

    return captures
</code>```

code for scripting is as follows:

stablediffusion_wrapper = StableDiffusionWrapper(model, sampler, opt)
scripted_module = torch.jit.script(stablediffusion_wrapper, example_inputs=[(token_dummy, img_dummy)])
```
<p>and <code>TimestepEmbedSequential</code> module:</p>
```class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
    """
    A sequential module that passes timestep embeddings to the children that
    support it as an extra input.
    """

    def forward(self, x, emb, context=None):
        for layer in self:
            if isinstance(layer, TimestepBlock):
                x = layer(x, emb)
            elif isinstance(layer, SpatialTransformer):
                x = layer(x, context)
            else:
                x = layer(x)
        return x
```

Any suggestions how can I figure it out?

I tried to set @torch.jit.export decorator to the parent class TimestepBlock, but showed no effect. Actually, I have no idea what to look for this problem. I would appreciate any suggestions. Thank you

ContentLicense: CC BY-SA 4.0

Body:
While trying to script Stable Diffusion model using torch.jit.script(), I got this following error:

AttributeError: 'TimestepEmbedSequential' object has no attribute '__globals__'

I'm trying to export this model to ONNX and found out that running torch.onnx.export() will torch.jit.trace the models, which unrolls every loops, so I'm trying to use script first.

When I follow the traceback, the error occurs in this function while reading fn.__globals__ in _jit_internal.py from torch

def get_closure(fn):
    """
    Get a dictionary of closed over variables from a function
    """
    captures = {}
    captures.update(fn.__globals__)

    for index, captured_name in enumerate(fn.__code__.co_freevars):
        captures[captured_name] = fn.__closure__[index].cell_contents

    return captures

code for scripting is as follows:

stablediffusion_wrapper = StableDiffusionWrapper(model, sampler, opt)
scripted_module = torch.jit.script(stablediffusion_wrapper, example_inputs=[(token_dummy, img_dummy)])

and TimestepEmbedSequential module:

class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
    """
    A sequential module that passes timestep embeddings to the children that
    support it as an extra input.
    """

    def forward(self, x, emb, context=None):
        for layer in self:
            if isinstance(layer, TimestepBlock):
                x = layer(x, emb)
            elif isinstance(layer, SpatialTransformer):
                x = layer(x, context)
            else:
                x = layer(x)
        return x

Any suggestions how can I figure it out?

I tried to set @torch.jit.export decorator to the parent class TimestepBlock, but showed no effect. Actually, I have no idea what to look for this problem. I would appreciate any suggestions. Thank you


问:
Cannot summarize the qty in SQL Server
I currently make a query DB to summary the Qty based on ShipNo, but it could not be summarized- due to the different date are exists. I have tried to convert the date  format using yyyy-mm-dd but It does not solve it. Did I miss something ?

Here is the code that I used.

```<code>SELECT DISTINCT  T1.ShipNo
            ,    CONVERT(VARCHAR,T1.EndDt,23) EndDt
            ,    SUM(T2.ShipQty) AS ShipQty
FROM WNTPRD.ASSY_2022.dbo.T_MetalShip AS T1
INNER JOIN WNTPRD.ASSY_2022.dbo.T_MetalShip_Lot AS T2 ON T1.MetalShipID = T2.MetalShipID
WHERE 0=0
AND T1.ShipNo = 'TIC1P03Q00010'
GROUP BY T1.ShipNo, T1.EndDt
</code>```

And here is the result of the query above;

enter image description here

Title: Cannot summarize the qty in SQL Server

Body:
I currently make a query DB to summary the Qty based on ShipNo, but it could not be summarized- due to the different date are exists. I have tried to convert the date  format using yyyy-mm-dd but It does not solve it. Did I miss something ?

Here is the code that I used.

SELECT DISTINCT  T1.ShipNo
            ,    CONVERT(VARCHAR,T1.EndDt,23) EndDt
            ,    SUM(T2.ShipQty) AS ShipQty
FROM WNTPRD.ASSY_2022.dbo.T_MetalShip AS T1
INNER JOIN WNTPRD.ASSY_2022.dbo.T_MetalShip_Lot AS T2 ON T1.MetalShipID = T2.MetalShipID
WHERE 0=0
AND T1.ShipNo = 'TIC1P03Q00010'
GROUP BY T1.ShipNo, T1.EndDt

And here is the result of the query above;

enter image description here


问:
Getting N + 1 query while working with Active Storage attachments
Here is my code that is giving me N + 1 query.

```<code>class User < ApplicationRecord
  has_many_attached :resumes, dependent: :destroy
  has_many_attached :cover_letters, dependent: :destroy
end

class ResumesController < ApplicationController
  def new
    @user = User.includes(resumes_attachments: :blob).find(params[:user_id])
  end

  def create
    @user = User.includes(resumes_attachments: :blob).find(params[:user_id])

    if @user.resumes.attach(params[:user][:resume])
      redirect_to new_user_resume_path(@user)
    else
      render :new
    end
  end
end
</code>```

I have commented out everything in a view to make sure nothing is happening there. Bullet gem is only complaining when create action fails and render :new is triggered. For success create action bullet gem is not giving any error.

But when I check server log ActiveStorage::Blob is being called so many times. What am I missing ?. I am using Rails 6.

UPDATE:

Below is my log.

```<code>    ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "13e9e539-8c45-473f-b849-9e459646a1a1"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.3ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "2581e71d-98e3-4edc-afb8-310e699dde00"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "59ad2a58-dafe-4983-83d0-ce27ba37ff01"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "6f3431c2-8bb7-4348-a9d9-d36a4e8ea6bb"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.5ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "ac925113-8f42-4d12-aa04-842a812e57ab"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "bd753376-408b-497b-b4f9-8cdd4c85c23e"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "d48b3658-bb81-472b-b9b9-8da341a55ab6"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "e098a866-e14d-4477-8f4d-bd48389d0831"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
</code>```

UPDATE 2

I also tried User.with_attached_resumes.find(id) but still same problem

UPDATE 3

Below is my code from new.html.erb page

```<code><%= form_with model: @user, url: user_resumes_path(@user), method: :post, local: true do |f| %>
        <div class='row'>
          <div class='col-md-12 col-sm-12'>
            <div class='statistic-item'>
              <%= f.file_field :resume, class: 'form-control file-field' %>
            </div>
          </div>
        </div>
        <div class='row mrg-top-30'>
          <div class='col-md-12 col-sm-12'>
            <div class='form-group text-center'>
              <%= f.submit 'Upload Resume', class: 'btn btn-primary theme-bg' %>
            </div>
          </div>
        </div>
<% end %>
</code>```

Solution

I managed to solve the issue but I don't know why it works. Basically I have to include cover_letters as well and then N + 1 query is solved. This is very strange that I have to include cover_letters when I am trying to attach just resume. Below is my working code for create action

```<code>@user = User.includes(resumes_attachments: :blob, cover_letters_attachments: :blob).find(params[:user_id])
</code>```

OR

```<code>@user = User.with_attached_resumes.with_attached_cover_letters.find(params[:user_id])
</code>```

If anyone have explanation for this behavior then please let me know. Thanks

Body:
Here is my code that is giving me N + 1 query.

class User < ApplicationRecord
  has_many_attached :resumes, dependent: :destroy
  has_many_attached :cover_letters, dependent: :destroy
end

class ResumesController < ApplicationController
  def new
    @user = User.includes(resumes_attachments: :blob).find(params[:user_id])
  end

  def create
    @user = User.includes(resumes_attachments: :blob).find(params[:user_id])

    if @user.resumes.attach(params[:user][:resume])
      redirect_to new_user_resume_path(@user)
    else
      render :new
    end
  end
end

I have commented out everything in a view to make sure nothing is happening there. Bullet gem is only complaining when create action fails and render :new is triggered. For success create action bullet gem is not giving any error.

But when I check server log ActiveStorage::Blob is being called so many times. What am I missing ?. I am using Rails 6.

UPDATE:

Below is my log.

    ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "13e9e539-8c45-473f-b849-9e459646a1a1"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.3ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "2581e71d-98e3-4edc-afb8-310e699dde00"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "59ad2a58-dafe-4983-83d0-ce27ba37ff01"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "6f3431c2-8bb7-4348-a9d9-d36a4e8ea6bb"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.5ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "ac925113-8f42-4d12-aa04-842a812e57ab"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "bd753376-408b-497b-b4f9-8cdd4c85c23e"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "d48b3658-bb81-472b-b9b9-8da341a55ab6"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'
  ActiveStorage::Blob Load (0.2ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", "e098a866-e14d-4477-8f4d-bd48389d0831"], ["LIMIT", 1]]
  ↳ app/controllers/resumes_controller.rb:17:in `create'

UPDATE 2

I also tried User.with_attached_resumes.find(id) but still same problem

UPDATE 3

Below is my code from new.html.erb page

<%= form_with model: @user, url: user_resumes_path(@user), method: :post, local: true do |f| %>

              <%= f.file_field :resume, class: 'form-control file-field' %>

              <%= f.submit 'Upload Resume', class: 'btn btn-primary theme-bg' %>

<% end %>

Solution

I managed to solve the issue but I don't know why it works. Basically I have to include cover_letters as well and then N + 1 query is solved. This is very strange that I have to include cover_letters when I am trying to attach just resume. Below is my working code for create action

@user = User.includes(resumes_attachments: :blob, cover_letters_attachments: :blob).find(params[:user_id])

OR

@user = User.with_attached_resumes.with_attached_cover_letters.find(params[:user_id])

If anyone have explanation for this behavior then please let me know. Thanks


问:
TypeScript: .mts file extension does not work as expected (tsc emits commonJS code instead)
This page says:

In turn, TypeScript supports two new source file extensions: .mts and .cts. When TypeScript emits these to JavaScript files, it will emit them to .mjs and .cjs respectively.

(emphasis mine)

I'm aware that it only says that it'll emit .mts files to .mjs files but I do expect that it will adhere to the module system chosen by the file extension.

What do I mean?

When I setup a blank project with npm install --save-dev typescript and a single file example.mts with the following contents:

import path from "path"

console.log(
    path.resolve("./")
)
```
<p>I expect that <code>./node_modules/.bin/tsc example.mts</code> results in (at the <strong>very</strong> least) a file created <code>example.mjs</code> with the following contents:</p>
<pre class="lang-js prettyprint-override"><code>import path from "path"

console.log(
    path.resolve("./")
)
</code>```

But instead, tsc decides to output:

"use strict";
exports.__esModule = true;
var path_1 = require("path");
console.log(path_1["default"].resolve("./"));
```

Why is that?

Edit: filed a bug report on github.

Body:
This page says:

In turn, TypeScript supports two new source file extensions: .mts and .cts. When TypeScript emits these to JavaScript files, it will emit them to .mjs and .cjs respectively.

(emphasis mine)

I'm aware that it only says that it'll emit .mts files to .mjs files but I do expect that it will adhere to the module system chosen by the file extension.

What do I mean?

When I setup a blank project with npm install --save-dev typescript and a single file example.mts with the following contents:

import path from "path"

console.log(
    path.resolve("./")
)

I expect that ./node_modules/.bin/tsc example.mts results in (at the very least) a file created example.mjs with the following contents:

import path from "path"

console.log(
    path.resolve("./")
)

But instead, tsc decides to output:

"use strict";
exports.__esModule = true;
var path_1 = require("path");
console.log(path_1["default"].resolve("./"));

Why is that?

Edit: filed a bug report on github.


问:
Emmet overwriting the text next to it
In vs code in html, Emmet is overwriting or replacing text. For example,
(p)My name is Prakash.(p)

Now in the above line I want to make the word "Prakash" in bold. For that I put the cursor before the word "P". Then I type (b and Emmet suggestions show up. I choose "bold" from the suggestions. Now the problem happens. The bold tag instead of pushing the word "Prakash" to the right, overwrites on the word "Prakash".

Help me solve the problem. (Note:- Understand the brackets as angular brackets.I couldnt find angular brackets on my mobile to type here)

I have described the problem in the best way possible. Your help would be appreciated.

Title: Emmet overwriting the text next to it


问:
How to stop double render in react-native-tab-view using React Hooks
I am using  react-native-tab-view for creating swipe tabs but when I swipe from one tab to another I got my us effect of each component called every time when I swipe it.

My problem is similar as like https://github.com/satya164/react-native-tab-view/issues/750

**Current behaviour

When use 'switch render' scene inside of the hooks function - I get two renders (when we just start app)**

`

```<code> const _renderScene = ({ route }) => {
    switch (route.key) {
      case 'login':
        return <FirstRoute />;
      case 'sign_up':
        return <SecondRoute />;
      default:
        return null;
    }
  };
</code>```

`

`

```<code>index.js:17  FirstRoute
index.js:28 SecondRoute
index.js:17 FirstRoute
index.js:28 SecondRoute
</code>```

`

When switch between tabs - also received two render - every time!

`

```<code>index.js:17 FirstRoute
index.js:28 SecondRoute
</code>```

`

**Expected behaviour

When use the same code but with this method**

`

```<code>  const _renderScene = SceneMap({
    login: FirstRoute,
    sign_up: SecondRoute,
  });
</code>```

`

Code sample

`

```<code>import React, { useState } from 'react';
import {
  Text,
  View,
  Keyboard,
} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import { TabView, TabBar, SceneMap } from 'react-native-tab-view';

import { DEVICE_WIDTH } from 'config/constants';

import styles from './styles';

const FirstRoute = () => {
  console.log('FirstRoute');
  return (
    <View>
      <Text>
        Lorem ipsum dolor sit amet
      </Text>
    </View>
  );
};

const SecondRoute = () => {
  console.log('SecondRoute');
  return (
    <View>
      <Text>
        Lorem ipsum dolor sit amet
      </Text>
    </View>
  );
};

const INITIAL_STATE = {
  index: 0,
  routes: [
    {
      key: 'login',
      title: 'Login',
      icon: '',
      accessibilityLabel: 'Login',
      testID: 'loginTab',
    },
    {
      key: 'sign_up',
      title: 'Register',
      icon: '',
      accessibilityLabel: 'SignIn',
      testID: 'signInTab',
    },
  ],
};

const LoginScreen = () => {
  const [state, setState] = useState(INITIAL_STATE);

  const _renderScene = SceneMap({
    login: FirstRoute,
    sign_up: SecondRoute,
  });

  // const _renderScene = ({ route }) => {
  //   switch (route.key) {
  //     case 'login':
  //       return <FirstRoute />;
  //     case 'sign_up':
  //       return <SecondRoute stings={[]} />;
  //     default:
  //       return null;
  //   }
  // };

  const _handleIndexChange = (index) => {
    Keyboard.dismiss();
    setState({ ...INITIAL_STATE, index });
  };

  const _renderTabBar = props => (
    <TabBar
      {...props}
      activeColor={EStyleSheet.value('$primaryColor')}
      inactiveColor="black"
      style={styles.tabBar}
      indicatorStyle={styles.indicatorStyle}
    />
  );

  return (
    <View style={styles.container}>
      <TabView
        // lazy
        navigationState={state}
        renderScene={_renderScene}
        renderTabBar={_renderTabBar}
        onIndexChange={_handleIndexChange}
        // swipeEnabled={false}
        initialLayout={{
          height: 0,
          width: DEVICE_WIDTH,
        }}
      />
    </View>
  );
};

export default LoginScreen;

</code>```

`

 I tried below solutions too but all in vain. Pease help.Used useCallBack:

const _renderScene = useCallback(SceneMap({
login: FirstRoute,
sign_up: SecondRoute
}));

also used useMemo but got below error :

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

const firstRoute = useMemo(() => (), []);

or

const LoginUser = React.memo(() => ());

Please help.

Expected behaviour

When use the same code but with this method

const _renderScene = SceneMap({ login: FirstRoute, sign_up: SecondRoute, });
All as expected (when we just start app)
 index.js:17 FirstRoute index.js:28 SecondRoute

Body:
I am using  react-native-tab-view for creating swipe tabs but when I swipe from one tab to another I got my us effect of each component called every time when I swipe it.

My problem is similar as like https://github.com/satya164/react-native-tab-view/issues/750

**Current behaviour

When use 'switch render' scene inside of the hooks function - I get two renders (when we just start app)**

`

 const _renderScene = ({ route }) => {
    switch (route.key) {
      case 'login':
        return <FirstRoute />;
      case 'sign_up':
        return <SecondRoute />;
      default:
        return null;
    }
  };

`

`

index.js:17  FirstRoute
index.js:28 SecondRoute
index.js:17 FirstRoute
index.js:28 SecondRoute

`

When switch between tabs - also received two render - every time!

`

index.js:17 FirstRoute
index.js:28 SecondRoute

`

**Expected behaviour

When use the same code but with this method**

`

  const _renderScene = SceneMap({
    login: FirstRoute,
    sign_up: SecondRoute,
  });

`

Code sample

`

import React, { useState } from 'react';
import {
  Text,
  View,
  Keyboard,
} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import { TabView, TabBar, SceneMap } from 'react-native-tab-view';

import { DEVICE_WIDTH } from 'config/constants';

import styles from './styles';

const FirstRoute = () => {
  console.log('FirstRoute');
  return (
    <View>
      <Text>
        Lorem ipsum dolor sit amet
      </Text>
    </View>
  );
};

const SecondRoute = () => {
  console.log('SecondRoute');
  return (
    <View>
      <Text>
        Lorem ipsum dolor sit amet
      </Text>
    </View>
  );
};

const INITIAL_STATE = {
  index: 0,
  routes: [
    {
      key: 'login',
      title: 'Login',
      icon: '',
      accessibilityLabel: 'Login',
      testID: 'loginTab',
    },
    {
      key: 'sign_up',
      title: 'Register',
      icon: '',
      accessibilityLabel: 'SignIn',
      testID: 'signInTab',
    },
  ],
};

const LoginScreen = () => {
  const [state, setState] = useState(INITIAL_STATE);

  const _renderScene = SceneMap({
    login: FirstRoute,
    sign_up: SecondRoute,
  });

  // const _renderScene = ({ route }) => {
  //   switch (route.key) {
  //     case 'login':
  //       return <FirstRoute />;
  //     case 'sign_up':
  //       return <SecondRoute stings={[]} />;
  //     default:
  //       return null;
  //   }
  // };

  const _handleIndexChange = (index) => {
    Keyboard.dismiss();
    setState({ ...INITIAL_STATE, index });
  };

  const _renderTabBar = props => (
    <TabBar
      {...props}
      activeColor={EStyleSheet.value('$primaryColor')}
      inactiveColor="black"
      style={styles.tabBar}
      indicatorStyle={styles.indicatorStyle}
    />
  );

  return (
    <View style={styles.container}>
      <TabView
        // lazy
        navigationState={state}
        renderScene={_renderScene}
        renderTabBar={_renderTabBar}
        onIndexChange={_handleIndexChange}
        // swipeEnabled={false}
        initialLayout={{
          height: 0,
          width: DEVICE_WIDTH,
        }}
      />
    </View>
  );
};

export default LoginScreen;

`

 I tried below solutions too but all in vain. Pease help.Used useCallBack:

const _renderScene = useCallback(SceneMap({
login: FirstRoute,
sign_up: SecondRoute
}));

also used useMemo but got below error :

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

const firstRoute = useMemo(() => (), []);

or

const LoginUser = React.memo(() => ());

Please help.

Expected behaviour

When use the same code but with this method

const _renderScene = SceneMap({ login: FirstRoute, sign_up: SecondRoute, });
All as expected (when we just start app)
 index.js:17 FirstRoute index.js:28 SecondRoute


问:
AWS GovCloud: The AWS Access Key Id you provided does not exist in our records
I'm trying to create an AMI on AWS GovCloud with the AWS EC2 API

```<code>ec2-import-volume --region us-gov-east-1 -f vmdk -b <bucket_name> -z us-gov-east-1a -o <aws_access_key_id> -w <aws_secret_access_key> -U https://ec2.us-gov-east-1.amazonaws.com -O <aws_access_key_id> -W <aws_secret_access_key>  local_file.vmdk -v
</code>```
```<code>ERROR: Cannot access/create bucket: bucketname : org.jets3t.service.S3ServiceException: S3 Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error><Code>InvalidAccessKeyId</Code><Message>The AWS Access Key Id you provided does not exist in our records.</Message>
</code>```

The error is due to the api requesting to the standard AWS S3 endpoint

```<code>[main] DEBUG org.apache.http.wire  - >> "Host: s3.amazonaws.com:443[\r][\n]"
</code>```

Providing the flags --region us-gov-east-1 or -U https://ec2.us-gov-east-1.amazonaws.com doesn't seem to do the trick either.

Is there a way to enable EC2 API to request to GovCloud endpoints?

Body:
I'm trying to create an AMI on AWS GovCloud with the AWS EC2 API

ec2-import-volume --region us-gov-east-1 -f vmdk -b <bucket_name> -z us-gov-east-1a -o <aws_access_key_id> -w <aws_secret_access_key> -U https://ec2.us-gov-east-1.amazonaws.com -O <aws_access_key_id> -W <aws_secret_access_key>  local_file.vmdk -v

ERROR: Cannot access/create bucket: bucketname : org.jets3t.service.S3ServiceException: S3 Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error>InvalidAccessKeyId<Message>The AWS Access Key Id you provided does not exist in our records.</Message>

The error is due to the api requesting to the standard AWS S3 endpoint

[main] DEBUG org.apache.http.wire  - >> "Host: s3.amazonaws.com:443[\r][\n]"

Providing the flags --region us-gov-east-1 or -U https://ec2.us-gov-east-1.amazonaws.com doesn't seem to do the trick either.

Is there a way to enable EC2 API to request to GovCloud endpoints?


问:
How to compare string of list with a string of list in presto SQL?
My column is String(), I tried:

WHEN column = '[1]'
```
<p>it didn't work as the desired rows with column equals to '[1]' didn't get returned, but then I tried:</p>
<pre class="lang-sql prettyprint-override"><code>WHEN column = CAST('[1]' AS VARCHAR)
</code>```

it worked... I'd really like to know if the latter one is indeed the right way to do this..

Body:
My column is String(), I tried:

WHEN column = '[1]'

it didn't work as the desired rows with column equals to '[1]' didn't get returned, but then I tried:

WHEN column = CAST('[1]' AS VARCHAR)

it worked... I'd really like to know if the latter one is indeed the right way to do this..


问:
How to GET Field URL of Project Board from Github using GraphQL/REST API
I'm new at using GraphQL and REST API. Basically, what I'm trying to do is to get the item's URL/URI address in my Project Board in Github

Here's my project to do list from github.

I was able to get the title, the status and the assignee in my code but not the uri/url of the fields as I don't really know how to do it.

Here's what I have so far:

```<code>gh api graphql -f query='
  query{
    node(id: "PVT_kwDOBzffic4AJwzx") {
        ... on ProjectV2 {
          items(first: 20) {
            nodes{
              id
              fieldValues(first: 20) {
                nodes{
                  ... on ProjectV2ItemFieldTextValue {
                    text
                    field {
                      ... on ProjectV2FieldCommon {
                        name
                      }
                    }
                  }

                  ... on ProjectV2ItemFieldSingleSelectValue {
                    name
                    field {
                      ... on ProjectV2FieldCommon {
                        name
                      }
                    }
                  }
                }
              }
              content{

                ...on Issue {
                  title
                  assignees(first: 20) {
                    nodes{
                      login
                    }
                  }
                }

              }
            }
          }
        }
      }
    }'
</code>```

Can you recommend something that I should include in my code to get the field's URI/URL?

Thanks.

Body:
I'm new at using GraphQL and REST API. Basically, what I'm trying to do is to get the item's URL/URI address in my Project Board in Github

Here's my project to do list from github.

I was able to get the title, the status and the assignee in my code but not the uri/url of the fields as I don't really know how to do it.

Here's what I have so far:

gh api graphql -f query='
  query{
    node(id: "PVT_kwDOBzffic4AJwzx") {
        ... on ProjectV2 {
          items(first: 20) {
            nodes{
              id
              fieldValues(first: 20) {
                nodes{
                  ... on ProjectV2ItemFieldTextValue {
                    text
                    field {
                      ... on ProjectV2FieldCommon {
                        name
                      }
                    }
                  }

                  ... on ProjectV2ItemFieldSingleSelectValue {
                    name
                    field {
                      ... on ProjectV2FieldCommon {
                        name
                      }
                    }
                  }
                }
              }
              content{

                ...on Issue {
                  title
                  assignees(first: 20) {
                    nodes{
                      login
                    }
                  }
                }

              }
            }
          }
        }
      }
    }'

Can you recommend something that I should include in my code to get the field's URI/URL?

Thanks.


问:
C++ | How to remove rounding after point with precision?
I wrote this code:
Code
for example for test
2 3
it should output 0.66666666 but it outputs 0.66666667
So how can i treat that rounding in the end of my double value?</p>


问:
Is there a way to avoid reloading vs code window for changes to python modules to be reflected in other files?
Say I have a Python module with an init file like this:

```<code># pages/__init__.py
from ..utils.page import Page
from .main_page import MainPage
from typing import Dict, Type

PAGE_MAP: Dict[str, Type[Page]] = {
}

__all__ = ['PAGE_MAP']
</code>```

In the same module I have another file called main_page.py, which holds a Page class that will be put into the PAGE_MAP later.
In my main file, I have want to use this PAGE_MAP, like this:

```<code># main.py
from src.pages import PAGE_MAP

def main():
    current_page = 'MainPage'
    PAGE_MAP[current_page]().write()
</code>```

Now, obviously I will have squiggles under the PAGE_MAP call, since the PAGE_MAP is empty, so I cannot access current_page, instantiate the class and call the write method.
Now I update the PAGE_MAPE to contain the 'MainPage':

```<code># Update to pages/__init__.py
PAGE_MAP: Dict[str, Type[Page]] = {
    "MainPage": MainPage
}
</code>```

Going back to the main file, why does the squiggles not disappear automatically in vs code? I have to reload the window before the squiggles disappear, or wait an absurd amount of time before it updates. Since it does in fact update after a long time, is there a way to make it update on save, or shorten the time between updates? Or maybe other ways to handle this issue?

I tried searching online, but I can't seem to find other similar problems or possible solutions.

EDIT: as JarroVGIT pointed out, I failed to mention my os. I am using WSL2 Ubuntu on my Windows 11 system. There are other similar issues with WSL in vs code, for example the source control and file explorer needs manual reload by pressing the reload buttons. My issue is likely WSL related, but if anyone has a fix, i'm all ears.

Body:
Say I have a Python module with an init file like this:

# pages/__init__.py
from ..utils.page import Page
from .main_page import MainPage
from typing import Dict, Type

PAGE_MAP: Dict[str, Type[Page]] = {
}

__all__ = ['PAGE_MAP']

In the same module I have another file called main_page.py, which holds a Page class that will be put into the PAGE_MAP later.
In my main file, I have want to use this PAGE_MAP, like this:

# main.py
from src.pages import PAGE_MAP

def main():
    current_page = 'MainPage'
    PAGE_MAP[current_page]().write()

Now, obviously I will have squiggles under the PAGE_MAP call, since the PAGE_MAP is empty, so I cannot access current_page, instantiate the class and call the write method.
Now I update the PAGE_MAPE to contain the 'MainPage':

# Update to pages/__init__.py
PAGE_MAP: Dict[str, Type[Page]] = {
    "MainPage": MainPage
}

Going back to the main file, why does the squiggles not disappear automatically in vs code? I have to reload the window before the squiggles disappear, or wait an absurd amount of time before it updates. Since it does in fact update after a long time, is there a way to make it update on save, or shorten the time between updates? Or maybe other ways to handle this issue?

I tried searching online, but I can't seem to find other similar problems or possible solutions.

EDIT: as JarroVGIT pointed out, I failed to mention my os. I am using WSL2 Ubuntu on my Windows 11 system. There are other similar issues with WSL in vs code, for example the source control and file explorer needs manual reload by pressing the reload buttons. My issue is likely WSL related, but if anyone has a fix, i'm all ears.


问:
I've had problem when i want install extensions in the VSCODE on windows 10
for about a week that I install windows 10 on my PC. after that i installed VSCODE on that but when I want to try install extensions in VSCODE the following error occured and couldnot fix it so far, and my search on the internet didn't answer. I have had two windows on my PC ,windows 7 and windows 10. VSCODE properly work on windows 7 but in windows 10 doesnot. both windows are used the same internet connection. I've also set my proxy to auto but i didn't work.

The content error is:
'the editor could not be opend due to unexpected error:XHR timeout:undefinedms'

I googled my problem to solve that but didn't answer. I manipulate proxy setting but i cant fix it.


问:
Angular Material MatSnackBar panelClass not working
Since the update to Material 15 I have problems with the panelClass Property. It didn't work since update.
My styles.scss like:

```<code>::ng-deep .success-dialog-snackbar {
  color: white !important;
  background-color: green !important;
}

::ng-deep .error-dialog-snackbar {
  color: white !important;
  background-color: darkred !important;
</code>```

MatSnackBar calling:

```<code>  success(message: string) {
    this.snackBar.open(message, '', {
      duration: 5000,
      panelClass: ['success-dialog-snackbar']
    });
  }

  error(message: string) {
    this.snackBar.open(message, '', {
      duration: 5000,
      panelClass: ['error-dialog-snackbar']
    });
  }
</code>```

The MatSnackBar calling is in a Angular Service which get an call from an Error Interceptor

Has something changed in Material 15?

I have tried to leave ::ng-deep but also still not working

Body:
Since the update to Material 15 I have problems with the panelClass Property. It didn't work since update.
My styles.scss like:

::ng-deep .success-dialog-snackbar {
  color: white !important;
  background-color: green !important;
}

::ng-deep .error-dialog-snackbar {
  color: white !important;
  background-color: darkred !important;

MatSnackBar calling:

  success(message: string) {
    this.snackBar.open(message, '', {
      duration: 5000,
      panelClass: ['success-dialog-snackbar']
    });
  }

  error(message: string) {
    this.snackBar.open(message, '', {
      duration: 5000,
      panelClass: ['error-dialog-snackbar']
    });
  }

The MatSnackBar calling is in a Angular Service which get an call from an Error Interceptor

Has something changed in Material 15?

I have tried to leave ::ng-deep but also still not working


问:
Twig files inside subfolder is not recognized in symfony 4.4
I am migrating from Symfony 3.4 to 4.4 and encounter 1 issue in render twig files. My controller:

```<code>src/UserBundle/Controller/UserController.php
</code>```

this files is going to render login twig like this:

```<code>$this->render('@App\UserBundle:Auth:login.html.twig', []));
</code>```

the twig file is located in:

```<code>src/UserBundle/Resources/views/Auth/login.html.twig
</code>```

but it not read Auth folder correctly, it give this error:

```<code>Unable to find template "@App/UserBundle:Auth/login.html.twig" (looked into: /Users/myname/Sites/projectFs/src/AppBundle/Resources/views).
</code>```

I can't understand why Auth folder is not recognized? I want to keep using this structure, not move the template in its own folder, is there a way to fix this?

Body:
I am migrating from Symfony 3.4 to 4.4 and encounter 1 issue in render twig files. My controller:

src/UserBundle/Controller/UserController.php

this files is going to render login twig like this:

$this->render('@App\UserBundle:Auth:login.html.twig', []));

the twig file is located in:

src/UserBundle/Resources/views/Auth/login.html.twig

but it not read Auth folder correctly, it give this error:

Unable to find template "@App/UserBundle:Auth/login.html.twig" (looked into: /Users/myname/Sites/projectFs/src/AppBundle/Resources/views).

I can't understand why Auth folder is not recognized? I want to keep using this structure, not move the template in its own folder, is there a way to fix this?


问:
Getting SAXParseException while trying to parse xml with &
I am trying to parse XML response into Java object. Here is the sample xml response

Response

```<code>        <SavedSearch>
            <Id>8</Id>
            <Name>My Outstanding & Overdue mail</Name>
        <SavedSearch>
</code>```

Here is my Java Pojo object where i am trying to map response

JavaResponse.java

```<code>    @XmlRootElement(name = "SavedSearch")
    public class MailSavedSearchRO {
    private String id;
    private String name;
    @XmlElement(name = "Id")
    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    @XmlElement(name = "Name")
    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }
</code>```

But I am getting org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.I went through some solutions online but it was suggested that "&" should be replaced with ampersand. But the xml response is external entity and cant be modified from my end. Can anyone suggest how i can parse xml containing "&" without modifying xml response.

Body:
I am trying to parse XML response into Java object. Here is the sample xml response

Response

        <SavedSearch>
            <Id>8</Id>
            <Name>My Outstanding & Overdue mail</Name>
        <SavedSearch>

Here is my Java Pojo object where i am trying to map response

JavaResponse.java

    @XmlRootElement(name = "SavedSearch")
    public class MailSavedSearchRO {
    private String id;
    private String name;
    @XmlElement(name = "Id")
    public String getId() {
      return id;
    }

    public void setId(String id) {
      this.id = id;
    }

    @XmlElement(name = "Name")
    public String getName() {
      return name;
    }

    public void setName(String name) {
      this.name = name;
    }

But I am getting org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.I went through some solutions online but it was suggested that "&" should be replaced with ampersand. But the xml response is external entity and cant be modified from my end. Can anyone suggest how i can parse xml containing "&" without modifying xml response.


问:
How to stop first row from vertical scroll and can scroll horizantly
I want to stop the first row from scrolling vertically, but it can scroll horizontally. I have given my adapter and xml layout. Someone please help me. I tried many ways but no luck. Now all rows and columns are scrolling vertically as well as horizontally.

I am trying to resolve this issue for last two days.

My adapter

```<code>public class BillwiseOutstandingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final List<BillwiseOutstandingModel> retrievedResponses;
    private final Context context;
    private final int TYPE_HEADER = 0;
    private final int TYPE_ITEMS = 1;

    public BillwiseOutstandingAdapter(List<BillwiseOutstandingModel> retrievedResponses, Context context) {
        this.retrievedResponses = retrievedResponses;
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        if (viewType == TYPE_HEADER) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.billwiseoutstanding_header, parent, false);
            return new VHHeader(v);

        } else if (viewType == TYPE_ITEMS) {
            View view = LayoutInflater.from(context).inflate(R.layout.billwiseoutstanding_adapter, parent, false);
            return new VHItem(view);

        }
        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        setFadeAnimation(holder.itemView);

        if (holder instanceof VHItem) {
            VHItem vhItems = (VHItem) holder;
            vhItems.invtypeTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvtype()));
            vhItems.invnoTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvno()));
            vhItems.invdateTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvdate()));
            vhItems.supinvnoTv.setText(String.valueOf(retrievedResponses.get(position-1).getsupinvno()));
            vhItems.supinvdateTv.setText(String.valueOf(retrievedResponses.get(position-1).getsupinvdate()));
            vhItems.billamtTv.setText(String.valueOf(retrievedResponses.get(position-1).getbillamt()));
            vhItems.paidamtTv.setText(String.valueOf(retrievedResponses.get(position-1).getpaidamt()));
            vhItems.balanceTv.setText(String.valueOf(retrievedResponses.get(position-1).getbalance()));
            vhItems.crdrTv.setText(String.valueOf(retrievedResponses.get(position-1).getcrdr()));
            vhItems.daysdiffTv.setText(String.valueOf(retrievedResponses.get(position-1).getdaysdiff()));

            if(String.valueOf(retrievedResponses.get(position-1).getslno()).equals("0"))
            {
                holder.itemView.setBackgroundColor(Color.parseColor("#ADD8E6"));
                //  holder.imageView.setBackgroundColor(Color.parseColor("#FFFFFF"));
            }
            holder.setIsRecyclable(false);
        }
    }

    static class VHHeader extends RecyclerView.ViewHolder {
        public VHHeader(View view) {
            super(view);
        }
    }

    static class VHItem extends RecyclerView.ViewHolder{
        TextView invtypeTv,invnoTv,invdateTv,supinvnoTv,supinvdateTv,billamtTv,paidamtTv,balanceTv,crdrTv,daysdiffTv;
        public VHItem(View itemView) {
            super(itemView);
            this.invtypeTv = itemView.findViewById(R.id.invtypeTv);
            this.invnoTv = itemView.findViewById(R.id.invnoTv);
            this.invdateTv = itemView.findViewById(R.id.invdateTv);
            this.supinvnoTv = itemView.findViewById(R.id.supinvnoTv);
            this.supinvdateTv = itemView.findViewById(R.id.supinvdateTv);
            this.billamtTv = itemView.findViewById(R.id.billamtTv);
            this.paidamtTv = itemView.findViewById(R.id.paidamtTv);
            this.balanceTv = itemView.findViewById(R.id.balanceTv);
            this.crdrTv = itemView.findViewById(R.id.crdrTv);
            this.daysdiffTv = itemView.findViewById(R.id.daysdiffTv);
        }
    }

    @Override
    public int getItemCount() {
        return retrievedResponses.size()+1;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    public void setFadeAnimation(View view) {
        AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(500);
        view.startAnimation(anim);
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position)) {

            return TYPE_HEADER;
        }

        return TYPE_ITEMS;

    }
}
</code>```

My adapter xml

```<code><?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/customborder2"
        android:fillViewport="true">

        <TextView
            android:id="@+id/invtypeTv"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invtype"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/invnoTv"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invno"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/invdateTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invdate"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/supinvnoTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/supinvno"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/supinvdateTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/supinvdate"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/billamtTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/billamt"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/paidamtTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/paidamt"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/balanceTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/balance"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/crdrTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/crdr"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/daysdiffTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/daysdiff"
            android:textColor="@color/gray" />

    </LinearLayout>

</HorizontalScrollView>
</code>```

Body:
I want to stop the first row from scrolling vertically, but it can scroll horizontally. I have given my adapter and xml layout. Someone please help me. I tried many ways but no luck. Now all rows and columns are scrolling vertically as well as horizontally.

I am trying to resolve this issue for last two days.

My adapter

public class BillwiseOutstandingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final List<BillwiseOutstandingModel> retrievedResponses;
    private final Context context;
    private final int TYPE_HEADER = 0;
    private final int TYPE_ITEMS = 1;

    public BillwiseOutstandingAdapter(List<BillwiseOutstandingModel> retrievedResponses, Context context) {
        this.retrievedResponses = retrievedResponses;
        this.context = context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        if (viewType == TYPE_HEADER) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.billwiseoutstanding_header, parent, false);
            return new VHHeader(v);

        } else if (viewType == TYPE_ITEMS) {
            View view = LayoutInflater.from(context).inflate(R.layout.billwiseoutstanding_adapter, parent, false);
            return new VHItem(view);

        }
        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        setFadeAnimation(holder.itemView);

        if (holder instanceof VHItem) {
            VHItem vhItems = (VHItem) holder;
            vhItems.invtypeTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvtype()));
            vhItems.invnoTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvno()));
            vhItems.invdateTv.setText(String.valueOf(retrievedResponses.get(position-1).getinvdate()));
            vhItems.supinvnoTv.setText(String.valueOf(retrievedResponses.get(position-1).getsupinvno()));
            vhItems.supinvdateTv.setText(String.valueOf(retrievedResponses.get(position-1).getsupinvdate()));
            vhItems.billamtTv.setText(String.valueOf(retrievedResponses.get(position-1).getbillamt()));
            vhItems.paidamtTv.setText(String.valueOf(retrievedResponses.get(position-1).getpaidamt()));
            vhItems.balanceTv.setText(String.valueOf(retrievedResponses.get(position-1).getbalance()));
            vhItems.crdrTv.setText(String.valueOf(retrievedResponses.get(position-1).getcrdr()));
            vhItems.daysdiffTv.setText(String.valueOf(retrievedResponses.get(position-1).getdaysdiff()));

            if(String.valueOf(retrievedResponses.get(position-1).getslno()).equals("0"))
            {
                holder.itemView.setBackgroundColor(Color.parseColor("#ADD8E6"));
                //  holder.imageView.setBackgroundColor(Color.parseColor("#FFFFFF"));
            }
            holder.setIsRecyclable(false);
        }
    }

    static class VHHeader extends RecyclerView.ViewHolder {
        public VHHeader(View view) {
            super(view);
        }
    }

    static class VHItem extends RecyclerView.ViewHolder{
        TextView invtypeTv,invnoTv,invdateTv,supinvnoTv,supinvdateTv,billamtTv,paidamtTv,balanceTv,crdrTv,daysdiffTv;
        public VHItem(View itemView) {
            super(itemView);
            this.invtypeTv = itemView.findViewById(R.id.invtypeTv);
            this.invnoTv = itemView.findViewById(R.id.invnoTv);
            this.invdateTv = itemView.findViewById(R.id.invdateTv);
            this.supinvnoTv = itemView.findViewById(R.id.supinvnoTv);
            this.supinvdateTv = itemView.findViewById(R.id.supinvdateTv);
            this.billamtTv = itemView.findViewById(R.id.billamtTv);
            this.paidamtTv = itemView.findViewById(R.id.paidamtTv);
            this.balanceTv = itemView.findViewById(R.id.balanceTv);
            this.crdrTv = itemView.findViewById(R.id.crdrTv);
            this.daysdiffTv = itemView.findViewById(R.id.daysdiffTv);
        }
    }

    @Override
    public int getItemCount() {
        return retrievedResponses.size()+1;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

    public void setFadeAnimation(View view) {
        AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(500);
        view.startAnimation(anim);
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position)) {

            return TYPE_HEADER;
        }

        return TYPE_ITEMS;

    }
}

My adapter xml

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/customborder2"
        android:fillViewport="true">

        <TextView
            android:id="@+id/invtypeTv"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invtype"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/invnoTv"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invno"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/invdateTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/invdate"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/supinvnoTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/supinvno"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/supinvdateTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/supinvdate"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/billamtTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/billamt"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/paidamtTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/paidamt"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/balanceTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/balance"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/crdrTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/crdr"
            android:textColor="@color/gray" />

        <TextView
            android:id="@+id/daysdiffTv"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/nunitoblack"
            android:layout_gravity="center"
            android:textSize="14sp"
            android:padding="8dp"
            android:text="@string/daysdiff"
            android:textColor="@color/gray" />

    </LinearLayout>

</HorizontalScrollView>


问:
Getting a SSL/TLS certificate for GRPC services from AWS
I wrote a GRPC service. This is my server code:

```<code>type GrpcServer[TServer any] func(*Handler) TServer

type GrpcRegistrar[TServer any] func(grpc.ServiceRegistrar, TServer)

type GrpcService[TServer any] struct {
    handler         *Handler
    inner           GrpcServer[TServer]
    registrar       GrpcRegistrar[TServer]
    certificateFile string
    certificateKey  string
    addr            string
    clientAddr      string
    gatewayAddr     string
}

func (service *GrpcService[TServer]) runGRPC(lis net.Listener, opts ...grpc.ServerOption) (*grpc.Server, error) {

    creds, err := credentials.NewServerTLSFromFile(service.certificateFile, service.certificateKey)
    if err != nil {
        return nil, service.handler.Logger.Error(err, "Failed to setup TLS")
    }

    opts = append([]grpc.ServerOption{grpc.Creds(creds)}, opts...)
    server := grpc.NewServer(opts...)

    service.registrar(server, service.inner(service.handler))

    service.handler.Logger.Log("GRPC listening on %s", service.addr)
    if err := server.Serve(lis); err != nil {
        return nil, service.handler.Logger.Error(err, "GRPC server failed unrecoverably")
    }

    return server, nil
}
</code>```

The issue I'm having is that this service expects a certificate file and certificate key. I understand I can create a public certificate using AWS credential manager and download it using the AWS CLI. However, this only gives me the certificate value; I need a key file in addition. Is there a way I can get a certificate from AWS for use as GRPC server credentials?

Body:
I wrote a GRPC service. This is my server code:

type GrpcServer[TServer any] func(*Handler) TServer

type GrpcRegistrar[TServer any] func(grpc.ServiceRegistrar, TServer)

type GrpcService[TServer any] struct {
    handler         *Handler
    inner           GrpcServer[TServer]
    registrar       GrpcRegistrar[TServer]
    certificateFile string
    certificateKey  string
    addr            string
    clientAddr      string
    gatewayAddr     string
}

func (service *GrpcService[TServer]) runGRPC(lis net.Listener, opts ...grpc.ServerOption) (*grpc.Server, error) {

    creds, err := credentials.NewServerTLSFromFile(service.certificateFile, service.certificateKey)
    if err != nil {
        return nil, service.handler.Logger.Error(err, "Failed to setup TLS")
    }

    opts = append([]grpc.ServerOption{grpc.Creds(creds)}, opts...)
    server := grpc.NewServer(opts...)

    service.registrar(server, service.inner(service.handler))

    service.handler.Logger.Log("GRPC listening on %s", service.addr)
    if err := server.Serve(lis); err != nil {
        return nil, service.handler.Logger.Error(err, "GRPC server failed unrecoverably")
    }

    return server, nil
}

The issue I'm having is that this service expects a certificate file and certificate key. I understand I can create a public certificate using AWS credential manager and download it using the AWS CLI. However, this only gives me the certificate value; I need a key file in addition. Is there a way I can get a certificate from AWS for use as GRPC server credentials?


问:
xml.parser.fromstring({text: xmlcontent}); is returning null value, though the xml is a valid one
I am trying to parse an xmlcontent to xmldocument but it gives me null response. My code is below

```<code>xmlDoc = xml.Parser.fromString({text: xmlContent});

log.debug('xmldoc',xmlDoc);
</code>```

I can see the below response in the log.

```<code>{"name":"#document","type":"DOCUMENT_NODE","value":null,"textContent":null}
</code>```

I am trying to parse an xmlcontent to xmldocument but it gives me null response. My code is below

```<code>xmlDoc = xml.Parser.fromString({text: xmlContent});

log.debug('xmldoc',xmlDoc);
</code>```

I can see the below response in the log.

```<code>{"name":"#document","type":"DOCUMENT_NODE","value":null,"textContent":null}
</code>```

Body:
I am trying to parse an xmlcontent to xmldocument but it gives me null response. My code is below

xmlDoc = xml.Parser.fromString({text: xmlContent});

log.debug('xmldoc',xmlDoc);

I can see the below response in the log.

{"name":"#document","type":"DOCUMENT_NODE","value":null,"textContent":null}

I am trying to parse an xmlcontent to xmldocument but it gives me null response. My code is below

xmlDoc = xml.Parser.fromString({text: xmlContent});

log.debug('xmldoc',xmlDoc);

I can see the below response in the log.

{"name":"#document","type":"DOCUMENT_NODE","value":null,"textContent":null}


问:
Microsoft.Extensions.Logging.ILogger - Custom formatting of logging properties
Without creating a brand new customer ILogger type, is it possible to somehow register "formatters" for different parameter types?

Example:

double someVar = 10.3;
/*snip*/

logger.LogDebug("Look at this property {MyProp}", someVar);
```

Can I somehow change how the someVar in this case is formatted by the logger?
AFAIK, it just defaults to ToString() on each of the provided property values.

In my specific case, I want to change how protobuf messages are logged in properties.
So I would like to intercept the formatting of any IMessage object, and apply custom formatting to those. using any existing logger that is.
Is that possible?

Body:
Without creating a brand new customer ILogger type, is it possible to somehow register "formatters" for different parameter types?

Example:

double someVar = 10.3;
/*snip*/

logger.LogDebug("Look at this property {MyProp}", someVar);

Can I somehow change how the someVar in this case is formatted by the logger?
AFAIK, it just defaults to ToString() on each of the provided property values.

In my specific case, I want to change how protobuf messages are logged in properties.
So I would like to intercept the formatting of any IMessage object, and apply custom formatting to those. using any existing logger that is.
Is that possible?


问:
How to implement the 4th order Runge-Kutta method with a constraint on a derivative?
I am trying to solve a set of two 2nd order differential equations using the 4th order Runge-Kutta method. For this purpose, I have rewritten the two 2nd order equations into four 1st order equations, so that the problem gets reduced to solving four 1st order equations. I am writing the code in C language. The two variables in the problem are the radial coordinate (r) and the zenith angle (theta). I expect to obtain a curve like the following:

The expected plot

One can observe from the above plot that the derivative of theta changes at the turning points, but the derivative of r never changes its sign because the particle is always moving inwards towards the origin. So, the constraint is: the derivative of r is always positive.

I have written the following code where I find that soon after the derivative of theta changes sign, the derivative of r also changes sign and the particle starts to move in the outside direction, and I couldn't implement the constraint in the code. The plot that I obtained is:

The plot that I obtained

The code that I have written is the following:

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

// ***********************************************************************************************

// The integrand for dr/dt

double integrand1(double R)
{
    return R;
}

// The integrand for dtheta/dt

double integrand2(double T)
{
    return T;
}

// The integrand for dR/dt

double integrand3(double r, double theta, double T)
{
    double rnot, a=0.8, l=2.68, r1=3.5, term1, term2, term3, term4, term5, integrand3;
    rnot = fabs(pow(a,0.125));
    term1 = (r*T*T);
    term2 = (1/((r-rnot)*(r-rnot)));
    term3 = ((l*l)/(2*r*r*r*sin(theta)*sin(theta)));
    term4 = ((3*(r-2)*l*l)/(2*r*r*r*r*sin(theta)*sin(theta)));
    term5 = ((3*r1*a*l)/(r*r*r*r));
    integrand3 = term1 - term2 - term3 + term4 + term5;
    return integrand3;
}

// The integrand for dT/dt

double integrand4(double r, double theta, double R, double T)
{
    double l=2.68, term1, term2, integrand4;
    term1 = ((r-2)*l*l*cos(theta))/(r*r*r*r*r*sin(theta)*sin(theta)*sin(theta));
    term2 = ((2*R*T)/r);
    integrand4 = term1 - term2;
    return integrand4;
}

// -------------------- THE RUNGE-KUTTA ALGORITHM ----------------------------

double rk4(double t0, double r0, double theta0, double R0, double T0, double t, double h, double arr[])
{
    int n = (int)(fabs((t-t0)/h));
    double k1,k2,k3,k4,l1,l2,l3,l4,m1,m2,m3,m4,n1,n2,n3,n4;

    double r = r0;
    double theta = theta0;
    double R = R0;
    double T = T0;

    for (int i=1; i<=n; i++)
        {
        k1 = h*integrand1(R);
        l1 = h*integrand2(T);
        m1 = h*integrand3(r, theta, T);
        n1 = h*integrand4(r, theta, R, T);

        k2 = h*integrand1(R + 0.5*m1);
        l2 = h*integrand2(T + 0.5*n1);
        m2 = h*integrand3(r + 0.5*k1, theta + 0.5*l1, T + 0.5*n1);
        n2 = h*integrand4(r + 0.5*k1, theta + 0.5*l1, R + 0.5*m1, T + 0.5*n1);

        k3 = h*integrand1(R + 0.5*m2);
        l3 = h*integrand2(T + 0.5*n2);
        m3 = h*integrand3(r + 0.5*k2, theta + 0.5*l2, T + 0.5*n2);
        n3 = h*integrand4(r + 0.5*k2, theta + 0.5*l2, R + 0.5*m2, T + 0.5*n2);

        k4 = h*integrand1(R + m3);
        l4 = h*integrand2(T + n3);
        m4 = h*integrand3(r + k3, theta + l3, T + n3);
        n4 = h*integrand4(r + k3, theta + l3, R + m3, T + n3);

        r = r + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);
        theta = theta + (1.0/6.0)*(l1 + 2*l2 + 2*l3 + l4);
        R = R + (1.0/6.0)*(m1 + 2*m2 + 2*m3 + m4);
        T = T + (1.0/6.0)*(n1 + 2*n2 + 2*n3 + n4);

        arr[0] = r;
        arr[1] = theta;
        arr[2] = R;
        arr[3] = T;

//      t0 = t0 + h;
    } return 0;
}

// ------------------------------------------------------------------------------------

// ------------------
// The main function
//-------------------

int main()
{
    double t0=500.0,r0=50.0,theta0=1.0467,R0=0.0,T0=0.0,t,r,theta,R,T,a,h=-0.001,x,z,arr[4],i,test;

    FILE *fp1=NULL;
    fp1=fopen("rthetaplot.txt","w");

    // Integration

    for(t=499.0;t>=0.0;t-=0.5)
    {
        rk4(t0,r0,theta0,R0,T0,t,h,arr);

        r = arr[0];
        theta = arr[1];
        R = arr[2];
        T = arr[3];
        x = r*sin(theta);
        z = r*cos(theta);

        t0 = t;
        r0 = r;
        theta0 = theta;
        R0 = R;
        T0 = T;

        fprintf(fp1,"%f \t %f \t %f \t %f \t %f \t %f \t %f \n", t,r,theta,R,T,x,z);

    }

    fclose(fp1);
}
</code>```

In the code, I have defined the 1st derivative of r and theta as R and T respectively. So, I have four 1st order differential equations for r, theta, R and T. I started to integrate from a point (r,theta,R,T)=(50,pi/3,0,0) and used a negative step-size.

So, can anyone please suggest how to incorporate the constraint that the derivative of r is always positive so that the particle continues to move inwards after crossing the turning points?

Body:
I am trying to solve a set of two 2nd order differential equations using the 4th order Runge-Kutta method. For this purpose, I have rewritten the two 2nd order equations into four 1st order equations, so that the problem gets reduced to solving four 1st order equations. I am writing the code in C language. The two variables in the problem are the radial coordinate (r) and the zenith angle (theta). I expect to obtain a curve like the following:

The expected plot

One can observe from the above plot that the derivative of theta changes at the turning points, but the derivative of r never changes its sign because the particle is always moving inwards towards the origin. So, the constraint is: the derivative of r is always positive.

I have written the following code where I find that soon after the derivative of theta changes sign, the derivative of r also changes sign and the particle starts to move in the outside direction, and I couldn't implement the constraint in the code. The plot that I obtained is:

The plot that I obtained

The code that I have written is the following:

#include<stdio.h>
#include <math.h>

// ***********************************************************************************************

// The integrand for dr/dt

double integrand1(double R)
{
    return R;
}

// The integrand for dtheta/dt

double integrand2(double T)
{
    return T;
}

// The integrand for dR/dt

double integrand3(double r, double theta, double T)
{
    double rnot, a=0.8, l=2.68, r1=3.5, term1, term2, term3, term4, term5, integrand3;
    rnot = fabs(pow(a,0.125));
    term1 = (r*T*T);
    term2 = (1/((r-rnot)*(r-rnot)));
    term3 = ((l*l)/(2*r*r*r*sin(theta)*sin(theta)));
    term4 = ((3*(r-2)*l*l)/(2*r*r*r*r*sin(theta)*sin(theta)));
    term5 = ((3*r1*a*l)/(r*r*r*r));
    integrand3 = term1 - term2 - term3 + term4 + term5;
    return integrand3;
}

// The integrand for dT/dt

double integrand4(double r, double theta, double R, double T)
{
    double l=2.68, term1, term2, integrand4;
    term1 = ((r-2)*l*l*cos(theta))/(r*r*r*r*r*sin(theta)*sin(theta)*sin(theta));
    term2 = ((2*R*T)/r);
    integrand4 = term1 - term2;
    return integrand4;
}

// -------------------- THE RUNGE-KUTTA ALGORITHM ----------------------------

double rk4(double t0, double r0, double theta0, double R0, double T0, double t, double h, double arr[])
{
    int n = (int)(fabs((t-t0)/h));
    double k1,k2,k3,k4,l1,l2,l3,l4,m1,m2,m3,m4,n1,n2,n3,n4;

    double r = r0;
    double theta = theta0;
    double R = R0;
    double T = T0;

    for (int i=1; i<=n; i++)
        {
        k1 = h*integrand1(R);
        l1 = h*integrand2(T);
        m1 = h*integrand3(r, theta, T);
        n1 = h*integrand4(r, theta, R, T);

        k2 = h*integrand1(R + 0.5*m1);
        l2 = h*integrand2(T + 0.5*n1);
        m2 = h*integrand3(r + 0.5*k1, theta + 0.5*l1, T + 0.5*n1);
        n2 = h*integrand4(r + 0.5*k1, theta + 0.5*l1, R + 0.5*m1, T + 0.5*n1);

        k3 = h*integrand1(R + 0.5*m2);
        l3 = h*integrand2(T + 0.5*n2);
        m3 = h*integrand3(r + 0.5*k2, theta + 0.5*l2, T + 0.5*n2);
        n3 = h*integrand4(r + 0.5*k2, theta + 0.5*l2, R + 0.5*m2, T + 0.5*n2);

        k4 = h*integrand1(R + m3);
        l4 = h*integrand2(T + n3);
        m4 = h*integrand3(r + k3, theta + l3, T + n3);
        n4 = h*integrand4(r + k3, theta + l3, R + m3, T + n3);

        r = r + (1.0/6.0)*(k1 + 2*k2 + 2*k3 + k4);
        theta = theta + (1.0/6.0)*(l1 + 2*l2 + 2*l3 + l4);
        R = R + (1.0/6.0)*(m1 + 2*m2 + 2*m3 + m4);
        T = T + (1.0/6.0)*(n1 + 2*n2 + 2*n3 + n4);

        arr[0] = r;
        arr[1] = theta;
        arr[2] = R;
        arr[3] = T;

//      t0 = t0 + h;
    } return 0;
}

// ------------------------------------------------------------------------------------

// ------------------
// The main function
//-------------------

int main()
{
    double t0=500.0,r0=50.0,theta0=1.0467,R0=0.0,T0=0.0,t,r,theta,R,T,a,h=-0.001,x,z,arr[4],i,test;

    FILE *fp1=NULL;
    fp1=fopen("rthetaplot.txt","w");

    // Integration

    for(t=499.0;t>=0.0;t-=0.5)
    {
        rk4(t0,r0,theta0,R0,T0,t,h,arr);

        r = arr[0];
        theta = arr[1];
        R = arr[2];
        T = arr[3];
        x = r*sin(theta);
        z = r*cos(theta);

        t0 = t;
        r0 = r;
        theta0 = theta;
        R0 = R;
        T0 = T;

        fprintf(fp1,"%f \t %f \t %f \t %f \t %f \t %f \t %f \n", t,r,theta,R,T,x,z);

    }

    fclose(fp1);
}

In the code, I have defined the 1st derivative of r and theta as R and T respectively. So, I have four 1st order differential equations for r, theta, R and T. I started to integrate from a point (r,theta,R,T)=(50,pi/3,0,0) and used a negative step-size.

So, can anyone please suggest how to incorporate the constraint that the derivative of r is always positive so that the particle continues to move inwards after crossing the turning points?


问:
Nextjs : why the browser tab freezes when I use router.push()?

"next": "12.3.0",
```
<p>To be more precise this does not happen all the time, let's say in 85% it works fine but sometimes the browser tap freezes and I can't click on anything, all I can do is to close it.</p>
<p>No errors in the browser console neither in the terminal and the app works fine.</p>
<p>I have a button that calls an API and after reciving the data I want to  <code>router.push()</code> to the same page. and as I montioned it is not happening all the time so it should not be a problem with my code.</p>
<pre class="lang-js prettyprint-override"><code><Button
onClick={async() => {
 await axios
   .patch('url', updateTrackDto)
   .then((res) => {
       router.push(`/tracks`); // this is the path of the same page
  }).catch((error) => {
       console.log(error);
  });
}>update</Button>
</code>```

getServerSideProps :

```<code>export async function getServerSideProps(context) {
  const trackId = context.params.trackId;
  const track = await axios.get(`http://127.0.0.1:5000/track/get/${trackId}`);
  return {
    props: {
      track: track.data,
    },
  };
}
</code>```

I checked, there are no infinite renders or infinite loops or anything not working as expected, the stricMode is enabled. Can it be a problem with getServerSideProps() getting called many times ? because when I keep clicking on the button this is happening on the 8-9th click/getServerSideProps call

Body:
"next": "12.3.0",

To be more precise this does not happen all the time, let's say in 85% it works fine but sometimes the browser tap freezes and I can't click on anything, all I can do is to close it.

No errors in the browser console neither in the terminal and the app works fine.

I have a button that calls an API and after reciving the data I want to  router.push() to the same page. and as I montioned it is not happening all the time so it should not be a problem with my code.

<Button
onClick={async() => {
 await axios
   .patch('url', updateTrackDto)
   .then((res) => {
       router.push(`/tracks`); // this is the path of the same page
  }).catch((error) => {
       console.log(error);
  });
}>update</Button>

getServerSideProps :

export async function getServerSideProps(context) {
  const trackId = context.params.trackId;
  const track = await axios.get(`http://127.0.0.1:5000/track/get/${trackId}`);
  return {
    props: {
      track: track.data,
    },
  };
}

I checked, there are no infinite renders or infinite loops or anything not working as expected, the stricMode is enabled. Can it be a problem with getServerSideProps() getting called many times ? because when I keep clicking on the button this is happening on the 8-9th click/getServerSideProps call


问:
ElasticSearch "request [/gn-records/_search] contains unrecognized parameters"
I'm using ElasticSearch 7.2.0 and sending cURL GET requests through PHP. I'm trying to get to get the resourceTitleObject and the link fields from _source, but it tells me that the includes parameter doesn't exist for _source.
I get this when I var_dump the error:

```<code>array(2) {
   ["error"]=> array(3) {
      ["root_cause"]=> array(1) {
         [0]=> array(2) {
            ["type"]=> string(26) "illegal_argument_exception"
            ["reason"]=> string(252) "request [/gn-records/_search] contains unrecognized parameters: [_source[includes][0]] -> did you mean any of [_source_includes, _source_excludes]?, [_source[includes][1]] -> did you mean any of [_source_includes, _source_excludes]?, [query[term][_id]]"
         }
      }
      ["type"]=> string(26) "illegal_argument_exception"
      ["reason"]=> string(252) "request [/gn-records/_search] contains unrecognized parameters: [_source[includes][0]] -> did you mean any of [_source_includes, _source_excludes]?, [_source[includes][1]] -> did you mean any of [_source_includes, _source_excludes]?, [query[term][_id]]"
   }
   ["status"]=> int(400)
}
</code>```

Here's the body of my request :

```<code>{
    "_source": {
        "includes": [ "resourceTitleObject", "link" ]
    },
    "query": {
        "term": {
            "_id": "8826b05232abbd7bc0981436c8c5d3aa63136eda"
        }
    }
}
</code>```

I looked up the doc for ElasticSearch 7.2.0 and it tells me to do it like this.

Body:
I'm using ElasticSearch 7.2.0 and sending cURL GET requests through PHP. I'm trying to get to get the resourceTitleObject and the link fields from _source, but it tells me that the includes parameter doesn't exist for _source.
I get this when I var_dump the error:

array(2) {
   ["error"]=> array(3) {
      ["root_cause"]=> array(1) {
         [0]=> array(2) {
            ["type"]=> string(26) "illegal_argument_exception"
            ["reason"]=> string(252) "request [/gn-records/_search] contains unrecognized parameters: [_source[includes][0]] -> did you mean any of [_source_includes, _source_excludes]?, [_source[includes][1]] -> did you mean any of [_source_includes, _source_excludes]?, [query[term][_id]]"
         }
      }
      ["type"]=> string(26) "illegal_argument_exception"
      ["reason"]=> string(252) "request [/gn-records/_search] contains unrecognized parameters: [_source[includes][0]] -> did you mean any of [_source_includes, _source_excludes]?, [_source[includes][1]] -> did you mean any of [_source_includes, _source_excludes]?, [query[term][_id]]"
   }
   ["status"]=> int(400)
}

Here's the body of my request :

{
    "_source": {
        "includes": [ "resourceTitleObject", "link" ]
    },
    "query": {
        "term": {
            "_id": "8826b05232abbd7bc0981436c8c5d3aa63136eda"
        }
    }
}

I looked up the doc for ElasticSearch 7.2.0 and it tells me to do it like this.


问:
Installing USB Webcam on jackal robot
I am working on jackal robot I am trying to do some computer vision work using webcam and jackal UGV. I want to install webcam, . How I can access it and how i can its topic get published.

Thanks in Advance.

i plugged the webcam in Jackal but i am not able to access it and also its topic is not being published.

I have written simple code.

import cv2
vid = cv2.VideoCapture(0)
while(True):
    _, frame = vid.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
vid.release()
cv2.destroyAllWindows()
```
<p>And getting below output which shows no frame at input I guess.</p>
```[ WARN:0@0.005] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
Traceback (most recent call last):
  File "jcv2.py", line 5, in <module>
    cv2.imshow('frame', frame)
cv2.error: OpenCV(4.6.0) /io/opencv/modules/highgui/src/window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'`
```

Title: Installing USB Webcam on jackal robot

Body:
I am working on jackal robot I am trying to do some computer vision work using webcam and jackal UGV. I want to install webcam, . How I can access it and how i can its topic get published.

Thanks in Advance.

i plugged the webcam in Jackal but i am not able to access it and also its topic is not being published.

I have written simple code.

import cv2
vid = cv2.VideoCapture(0)
while(True):
    _, frame = vid.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
vid.release()
cv2.destroyAllWindows()

And getting below output which shows no frame at input I guess.

[ WARN:0@0.005] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video0): can't open camera by index
Traceback (most recent call last):
  File "jcv2.py", line 5, in <module>
    cv2.imshow('frame', frame)
cv2.error: OpenCV(4.6.0) /io/opencv/modules/highgui/src/window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'`