问:
How to implement caching for API get detail of objects
I have 2 services:

Service A: manage entity A (class A) (CRUD).

Service B: need to get data of instances of class A.

How to implement caching for API get detail of an object A ?

Method 1:

Service A:

Create/Delete/Update into DB, and sync to redis

API get detail of an object: read from DB

Service B: get data from redis first, if cache miss then call API get detail of A object

Method 2:

Service A:

Create/Delete/Update into DB, and sync to redis

API get detail of an object

Get from redis first

If cache miss, get from DB

Service B: always call API get detail of object A


来源: stackexchange

问:
Eclipse doesnt show output of JCWDE simulation in the console
Recently I started learning Java Card development using eclipse v4.2 and the JCDE eclipse plugins with JCDK 2.2.2. (windows 10 64x)

I am trying to run a simulation with Jcwde. however when i run the simulation, Eclipse console does not show the output that says it has established a connection nor does register any inputs as commands.

enter image description here

the console in eclipse should be looking like this:

enter image description here

If i go to the JCDK and run the Apdutool.bat after i start the simulation in eclipe. i can connect to the Virtual card; input my commands and run simple applets by sending command APDUs.

its also worth noting  that if the first command i type in the apdutool.bat is not powerup the simulation ends in Eclipse. (see next image)

enter image description here

So Eclipse clearly is registering my inputs but no displaying them in the console.

also note that when i create a simple Java application that displays on the console like System.out.println("testing console"). the console displays the message with no issues. so the problem should be with eclipse console and the cmd.

i tried eclipse 4.2.3; eclipse 4.2 64x and 32x with different JDKs but all were the same.

ContentLicense: CC BY-SA 4.0


问:
With gitlab, can you mark-as-viewed at the hunk/patch level instead of at the file level?
With gitlab, when reviewing a MR, you can set a file as viewed.

This way, it does not show up in the Changes tab, until a new change appears in that file.

However, it applies at the file level. That is to say, if

you have reviewed 3 independant modifications in 3 different places in the file

then you have marked the file as viewed

a commit is pushed with a modification in a 4th location in the file

then the file will appear again in the Changes tab, and all 4 modifications will be displayed again for review.

I would like to know if there is a setting (or maybe a plugin?) to enable mark-as-viewed at the patch level, in order to avoid reviewing again all modifications of a file when only one new modification actually has to be reviewed.


问:
OIDC challenge is the browser history for ASP.Net Core client
I use IdentityServer (aka Duende) ver. 6 and ASP.Net Core client as a BFF provider for the frontend with standard .Net Core Microsoft OIDC  middleware .AddOpenIdConnect for the Authorization Code flow. Everything works nice except one small thing: browser history entry for the OIDC challenge which looks like https://myserver/connect/authorize/callback?client_id... It must be the same for any OIDC provider because this call must be done in a browser and cannot be replaced by AJAX.

It's just looking untidy with long URL and no page title in the history. If user hits back in a browser, it leads to the error because the challenge code is not valid anymore. The problem was precisely explained here and the solution history.replace was even implemented for the IdentityServer's JS client as a config parameter but I can't find anything similar for the .Net Core.

The solution for the browser back button is implemented on the IdentityServer side in their "QuickStart" sample and I also handle an error on the client but still this long untidy URL in the browser offends my eye. I would prefer replacing history instead.

The idea is to handle some event from the OIDC middleware and inject javascript with history.replace to the http context there. Maybe someone already has ready-to-go solution?


问:
how to install xmla package in 3.10?
I'd like to install xmla in Python 3.10 to access an SSAS db but I get the following error:

```<code>pip install xmla
ImportError: cannot import name 'MutableMapping' from 'collections' (C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\collections\__init__.py)
</code>```

Any help welcome

Title: how to install xmla package in 3.10?

Body:
I'd like to install xmla in Python 3.10 to access an SSAS db but I get the following error:

pip install xmla
ImportError: cannot import name 'MutableMapping' from 'collections' (C:\Users\xx\AppData\Local\Programs\Python\Python310\lib\collections\__init__.py)

Any help welcome


问:
Error Calculation for Hierarchical Time Series Forecasting
I have hierarchical time series data and I generate forecasts at the lowest level in the hierarchy. I am looking for a method to calculate the error of time series forecasts on each level in the hierarchy.
Let's assume that the hierarchy is as follows:

City - Region - Country - Continent

I have forecasts for each city and I calculate MAE of my forecasts on this level. How should I calculate the error on the Region level? Should take the weighted average of the MAEs calculated on city level or should I calculate the forecasts on Region level first(by summing up the forecasts on city level) and then calculate the MAE?

I hope my question is understandable. Thank you


问:
How to switch back to parent browser tab from popout tab using javascript in firefox
I create popout tab as follow -:

```<code>window.name = 'someName'
window.open('someUrl', '_blank');
</code>```

Now i want to switch back to parent tab.
In Chrome i am able to do so by -:

```<code>window.open('', window.opener.name)
</code>```

But this is not working in Firefox.  what i noticed is window.opener object is Restricted in Firefox.

Please suggest any way to do it in firefox.

Body:
I create popout tab as follow -:

window.name = 'someName'
window.open('someUrl', '_blank');

Now i want to switch back to parent tab.
In Chrome i am able to do so by -:

window.open('', window.opener.name)

But this is not working in Firefox.  what i noticed is window.opener object is Restricted in Firefox.

Please suggest any way to do it in firefox.


问:
Mongoose & MongoDB: Cast Error when adding sub schema element to array of parent schema
I am working on a practice project and I'm getting an error I haven't been able to solve. In my backend, I have a blog controller and a blog model as well, as a comment model and a comment controller. When I try to add a comment I get the following error message:

```<code>CastError: Cast to [ObjectId] failed for value "[{"commentText":"Cool","authorName":"David"}]" (type string) at path "comments.0"
    at model.Query.exec (/Users/david/Documents/Coding/codingChallenge/react-blog-server/node_modules/mongoose/lib/query.js:4498:21)
    at model.Query.Query.then (/Users/david/Documents/Coding/codingChallenge/react-blog-server/node_modules/mongoose/lib/query.js:4592:15)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
</code>```

In my controller, I'm hitting the addComment Request where I select the specific BlogPost document, and then add a comment to the comment array.

```<code>import { Request, Response } from 'express';
import BaseController from '../baseController';
import { BlogPostSchema } from '../../repository/blogPost';

export default class BlogPostController extends BaseController {
  constructor() {
    super();
  }

  public async test(req: Request, res: Response) {
    res.status(200).send('test worked');
  }

  public async addComment(req: Request, res: Response) {
    const newComment = req.body;
    const updatedBlogPost = await BlogPostSchema.findByIdAndUpdate(
      { _id: req.params.id },
      { $push: { comments: newComment } },
      { new: true }
    );
    res.status(200).send(updatedBlogPost);
  }
}
</code>```

That request uses the Blog model/schema

```<code>import {
  createSchema,
  ExtractDoc,
  ExtractProps,
  Type,
  typedModel
} from 'ts-mongoose';
import { commentSchema } from './comment';

export const blogPostSchema = createSchema(
  {
    authorName: Type.string({ trim: true }),
    blogText: Type.string({ trim: true }),
    category: Type.string({
      default: '',
      trim: true,
      enum: ['gaming', 'lifestyle', 'cooking', 'baking']
    }),
    comments: Type.array().of(
      Type.ref(Type.objectId()).to('comment', commentSchema)
    )
  },
  {
    versionKey: false,
    timestamps: true
  }
);

export const BlogPostSchema = typedModel('blogPost', blogPostSchema);
export type BlogPost = ExtractProps<typeof blogPostSchema>;
export type BlogPostDoc = ExtractDoc<typeof blogPostSchema>;
</code>```

The BlogPostSchema then uses the Comment Schema

```<code>import {
  createSchema,
  ExtractDoc,
  ExtractProps,
  Type,
  typedModel
} from 'ts-mongoose';

export const commentSchema = createSchema(
  {
    commentText: Type.string({ trim: true }),
    authorName: Type.string({ trim: true })
  },
  {
    versionKey: false,
    timestamps: true
  }
);

export const CommentModel = typedModel('comment', commentSchema);
export type Comment = ExtractProps<typeof commentSchema>;
export type CommentDoc = ExtractDoc<typeof commentSchema>;
</code>```

What should be my next steps in problem solving, or a potential solution to this problem?

edit: I have also tried this for the addComment request, and it has not worked either.

```<code>public async addComment(req: Request, res: Response) {
    const newComment = await BlogPostSchema.create(req.body);
    const updatedBlogPost = await BlogPostSchema.findByIdAndUpdate(
      { _id: req.params.id },
      { $push: { comments: newComment } },
      { new: true }
    );
    res.status(200).send(updatedBlogPost);
  }
</code>```

Body:
I am working on a practice project and I'm getting an error I haven't been able to solve. In my backend, I have a blog controller and a blog model as well, as a comment model and a comment controller. When I try to add a comment I get the following error message:

CastError: Cast to [ObjectId] failed for value "[{"commentText":"Cool","authorName":"David"}]" (type string) at path "comments.0"
    at model.Query.exec (/Users/david/Documents/Coding/codingChallenge/react-blog-server/node_modules/mongoose/lib/query.js:4498:21)
    at model.Query.Query.then (/Users/david/Documents/Coding/codingChallenge/react-blog-server/node_modules/mongoose/lib/query.js:4592:15)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

In my controller, I'm hitting the addComment Request where I select the specific BlogPost document, and then add a comment to the comment array.

import { Request, Response } from 'express';
import BaseController from '../baseController';
import { BlogPostSchema } from '../../repository/blogPost';

export default class BlogPostController extends BaseController {
  constructor() {
    super();
  }

  public async test(req: Request, res: Response) {
    res.status(200).send('test worked');
  }

  public async addComment(req: Request, res: Response) {
    const newComment = req.body;
    const updatedBlogPost = await BlogPostSchema.findByIdAndUpdate(
      { _id: req.params.id },
      { $push: { comments: newComment } },
      { new: true }
    );
    res.status(200).send(updatedBlogPost);
  }
}

That request uses the Blog model/schema

import {
  createSchema,
  ExtractDoc,
  ExtractProps,
  Type,
  typedModel
} from 'ts-mongoose';
import { commentSchema } from './comment';

export const blogPostSchema = createSchema(
  {
    authorName: Type.string({ trim: true }),
    blogText: Type.string({ trim: true }),
    category: Type.string({
      default: '',
      trim: true,
      enum: ['gaming', 'lifestyle', 'cooking', 'baking']
    }),
    comments: Type.array().of(
      Type.ref(Type.objectId()).to('comment', commentSchema)
    )
  },
  {
    versionKey: false,
    timestamps: true
  }
);

export const BlogPostSchema = typedModel('blogPost', blogPostSchema);
export type BlogPost = ExtractProps<typeof blogPostSchema>;
export type BlogPostDoc = ExtractDoc<typeof blogPostSchema>;

The BlogPostSchema then uses the Comment Schema

import {
  createSchema,
  ExtractDoc,
  ExtractProps,
  Type,
  typedModel
} from 'ts-mongoose';

export const commentSchema = createSchema(
  {
    commentText: Type.string({ trim: true }),
    authorName: Type.string({ trim: true })
  },
  {
    versionKey: false,
    timestamps: true
  }
);

export const CommentModel = typedModel('comment', commentSchema);
export type Comment = ExtractProps<typeof commentSchema>;
export type CommentDoc = ExtractDoc<typeof commentSchema>;

What should be my next steps in problem solving, or a potential solution to this problem?

edit: I have also tried this for the addComment request, and it has not worked either.

public async addComment(req: Request, res: Response) {
    const newComment = await BlogPostSchema.create(req.body);
    const updatedBlogPost = await BlogPostSchema.findByIdAndUpdate(
      { _id: req.params.id },
      { $push: { comments: newComment } },
      { new: true }
    );
    res.status(200).send(updatedBlogPost);
  }


Title: python pandas normalize json

Body:
I am looking to normalize a flat file that has json format and store in snowflake.  The issue is whenever the data is loaded the object projected_annual_contributions stores the values in scientific notation ie. 8000.0 shows in snowflake as 8.000000000000000e+03,1.010000000000000e+04.  I want to list the entire below json data in 1 column in snowflake.

2022-11-06 00:18:52.675 goe_matrix_component - INFO - {'goe_request_id': '0d933x1d-46ef-4fd0-b3a2-adf873ed2313', 'age': 40, 'retirement_age': 79, 'planning_age': 95,  'projected_annual_contributions': [8000.0, 10100.0, 12241.2, 14424.214, 16649.66416, 18918.1809018, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 19906.1303489, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}

Below is sample of code:

import pandas as pd
d = json.loads(y)
df1 = pd.json_normalize(d,max_level=0)
write_pandas(table_name = raw_table_name,conn = snowflake_conn(), df = df1)


问:
How to modify Apache Nifi node adresses while deploying in Kubernetes?
In Kubernetes I would like to deploy Apache Nifi Cluster in StatefulSet with 3 nodes.
Problem is I would like to modify node adresses recursively in an init container in my yaml file.
I have to modify these parameters for each nodes in Kubernetes:

```<code>'nifi.remote.input.host'
'nifi.cluster.node.address'
</code>```

I need to have these FQDN added recursively in Nifi properties:

```<code>nifi-0.nifi.NAMESPACENAME.svc.cluster.local
nifi-1.nifi.NAMESPACENAME.svc.cluster.local
nifi-2.nifi.NAMESPACENAME.svc.cluster.local
</code>```

I have to modify the properties before deploying so I tried the following init container but doesn't work :

```<code>initContainers:
      - name: modify-nifi-properties
        image: busybox:v01
        command:
        - sh
        - -c
        - |
          # Modify nifi.properties to use the correct hostname for each node
          for i in {1..3}; do
            sed -i "s/nifi-$((i-1))/nifi-$((i-1)).nifinamespace.nifi.svc.cluster.local/g" /opt/nifi/conf/nifi.properties
          done
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
          limits:
            cpu: 100m
            memory: 100Mi
</code>```

How can I do it ?

Body:
In Kubernetes I would like to deploy Apache Nifi Cluster in StatefulSet with 3 nodes.
Problem is I would like to modify node adresses recursively in an init container in my yaml file.
I have to modify these parameters for each nodes in Kubernetes:

'nifi.remote.input.host'
'nifi.cluster.node.address'

I need to have these FQDN added recursively in Nifi properties:

nifi-0.nifi.NAMESPACENAME.svc.cluster.local
nifi-1.nifi.NAMESPACENAME.svc.cluster.local
nifi-2.nifi.NAMESPACENAME.svc.cluster.local

I have to modify the properties before deploying so I tried the following init container but doesn't work :

initContainers:
      - name: modify-nifi-properties
        image: busybox:v01
        command:
        - sh
        - -c
        - |
          # Modify nifi.properties to use the correct hostname for each node
          for i in {1..3}; do
            sed -i "s/nifi-$((i-1))/nifi-$((i-1)).nifinamespace.nifi.svc.cluster.local/g" /opt/nifi/conf/nifi.properties
          done
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
          limits:
            cpu: 100m
            memory: 100Mi

How can I do it ?


问:
Can't able launch Node Red App in IBM Cloud
I had Created a resource element in IBM Cloud for NODE RED post loading it show dull.

I tried with different browsers and cleaned my cache, tried to delete resource and add another it didn't helped


问:
Why is setting a method to have a side_effect causing construction of that method's class to throw?
I'm trying to create an MVCE for another problem I'm having. But I ran into an intermediate problem. You should be able to see and run an MVCE here, but here it is laid out:

B is just a class that you can call go() on, which in turn just prints that it happened.

```<code># module_b.py

class B:
  def __init__(self) -> None:
    self.x = True
    print("B constructed OK")
  def go(self):
    print("called B.go()")
</code>```

A is a class that holds an instance of B. It also has a go() method, which calls the B instance's go() method.

```<code># module_a.py

from module_b import B

class A:
  def __init__(self) -> None:
    try:
      self.b = B()
      print("A constructed OK")
    except Exception as e:
      print("A's constructor threw an exception: " + repr(e))
  def go(self):
    try:
      self.b.go()
    except Exception as e:
      print("a.go() threw an exception: " + repr(e))
</code>```

And here's the test code:

```<code># main.py

from module_a import A
from module_b import B
from unittest import mock

@mock.patch("module_a.B")
@mock.patch("module_a.B.go")
def test_b_method_go_throws_1(
    mock_b: mock.Mock,
    mock_b_go: mock.Mock
    ):
  mock_b.return_value = mock.Mock()
  mock_b_go.side_effect = Exception("test") # <-- This line seems to cause the issue.
  a = A()
  a.go()

print("-- test_b_method_go_throws_1() --")
test_b_method_go_throws_1()
print("")
</code>```

Finally, here's the output:

-- test_b_method_go_throws_1() --
A's constructor threw an exception: Exception('test')
a.go() threw an exception: AttributeError("'A' object has no attribute 'b'")
```

Originally I was trying to patch an instance's method to throw an error—I'm pretty sure I wasn't doing that right. But here I'm trying to understand why setting mock_b_go.side_effect is causing the construction of B to throw an exception.

Body:
I'm trying to create an MVCE for another problem I'm having. But I ran into an intermediate problem. You should be able to see and run an MVCE here, but here it is laid out:

B is just a class that you can call go() on, which in turn just prints that it happened.

# module_b.py

class B:
  def __init__(self) -> None:
    self.x = True
    print("B constructed OK")
  def go(self):
    print("called B.go()")

A is a class that holds an instance of B. It also has a go() method, which calls the B instance's go() method.

# module_a.py

from module_b import B

class A:
  def __init__(self) -> None:
    try:
      self.b = B()
      print("A constructed OK")
    except Exception as e:
      print("A's constructor threw an exception: " + repr(e))
  def go(self):
    try:
      self.b.go()
    except Exception as e:
      print("a.go() threw an exception: " + repr(e))

And here's the test code:

# main.py

from module_a import A
from module_b import B
from unittest import mock

@mock.patch("module_a.B")
@mock.patch("module_a.B.go")
def test_b_method_go_throws_1(
    mock_b: mock.Mock,
    mock_b_go: mock.Mock
    ):
  mock_b.return_value = mock.Mock()
  mock_b_go.side_effect = Exception("test") # <-- This line seems to cause the issue.
  a = A()
  a.go()

print("-- test_b_method_go_throws_1() --")
test_b_method_go_throws_1()
print("")

Finally, here's the output:

-- test_b_method_go_throws_1() --
A's constructor threw an exception: Exception('test')
a.go() threw an exception: AttributeError("'A' object has no attribute 'b'")

Originally I was trying to patch an instance's method to throw an error—I'm pretty sure I wasn't doing that right. But here I'm trying to understand why setting mock_b_go.side_effect is causing the construction of B to throw an exception.


问:
Restart user application after update on multiuser system
We do an update of our application, which consists of a system service and a UI application. The UI application is running under each user logged in to the system. It is implemented by placing a .lnk shortcut under the C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup folder.

The sequence of update is:

stop service & UI app for all users

update binary files

restart the service and UI app

The question is, how to properly restart the UI application if the update was performed in the context of the SYSTEM account (session 0) and the system has a couple of logged-in users?

Windows starts the UI application on each user login, but if it was terminated, the next restart will be on the next user login.

Does Windows have some functionality like restart startup application?


问:
Running Service Worker cause an error responding to the control function (NET HELPMSG 2186)
I am developing a .net Service Worker. When I publish it, I can run the Worker and it works normally. But when I going to make it as a Windows Service, it doesn't run and causes error by message:

The service is not responding to the control function.
More help is available by typing NET HELPMSG 2186.

I thought it was because of and exception in the program. But I simplified it to a tiny Worker and see the same error.

The commands in the Administrator CMD:

```<code>sc.exe create "MyWorkerService" binpath="D:\Projects\MyWorker.exe"
net start MyWorkerService

</code>```

.Net version : 6
Windows : 10

I want to run the Service (Worker) and I want to make it running until I stop it by myself.

Body:
I am developing a .net Service Worker. When I publish it, I can run the Worker and it works normally. But when I going to make it as a Windows Service, it doesn't run and causes error by message:

The service is not responding to the control function.
More help is available by typing NET HELPMSG 2186.

I thought it was because of and exception in the program. But I simplified it to a tiny Worker and see the same error.

The commands in the Administrator CMD:

sc.exe create "MyWorkerService" binpath="D:\Projects\MyWorker.exe"
net start MyWorkerService

.Net version : 6
Windows : 10

I want to run the Service (Worker) and I want to make it running until I stop it by myself.


问:
Not able to use SMOTETomek or SMOTEENN - Import Module error
I am trying to import the following libraries:

```<code>from imblearn.combine import SMOTEENN
from imblearn.combine import SMOTETomek
</code>```

Unfortunately I am getting an error that says:

```<code>ModuleNotFoundError: No module named 'scipy.special.cython_special'
</code>```

I have also checked on the following link :https://imbalanced-learn.org/stable/install.html and looks like almost every dependency is installed in my environment.

I am also getting the same error while I am importing Random forest classifier

```<code>from sklearn.ensemble import RandomForestClassifier
</code>```

What could be the issue here?

Body:
I am trying to import the following libraries:

from imblearn.combine import SMOTEENN
from imblearn.combine import SMOTETomek

Unfortunately I am getting an error that says:

ModuleNotFoundError: No module named 'scipy.special.cython_special'

I have also checked on the following link :https://imbalanced-learn.org/stable/install.html and looks like almost every dependency is installed in my environment.

I am also getting the same error while I am importing Random forest classifier

from sklearn.ensemble import RandomForestClassifier

What could be the issue here?


问:
LSTM inputs, different sequences with different lengths
I'm building a Recurrent Auto-encoder to make feature extraction on some time series sequences. All this sequences have different lengths and looking at different tutorials it seems that LSTM input layer accept only data in a format like (nb_sequence, nb_timestep, nb_feature) with the same timestep for all the sequences.

My model look like this:

```<code>encoder=Sequential([
    LSTM(128,activation="relu",input_shape=(timesteps,n_features),return_sequences=True),
    LSTM(64,activation="relu",return_sequences=False)
],name="Encoder")

decoder=Sequential([
    RepeatVector(timesteps,input_shape=[64]),
    LSTM(64,activation="relu",return_sequences=True),
    LSTM(128,activation="relu",return_sequences=True),
    TimeDistributed(Dense(n_features))
],name="Decoder")

autoencoder=Sequential([encoder,decoder])
</code>```

Is it possible to train my model with different sequences with different lengths ? If yes, how have to proceed ?

Body:
I'm building a Recurrent Auto-encoder to make feature extraction on some time series sequences. All this sequences have different lengths and looking at different tutorials it seems that LSTM input layer accept only data in a format like (nb_sequence, nb_timestep, nb_feature) with the same timestep for all the sequences.

My model look like this:

encoder=Sequential([
    LSTM(128,activation="relu",input_shape=(timesteps,n_features),return_sequences=True),
    LSTM(64,activation="relu",return_sequences=False)
],name="Encoder")

decoder=Sequential([
    RepeatVector(timesteps,input_shape=[64]),
    LSTM(64,activation="relu",return_sequences=True),
    LSTM(128,activation="relu",return_sequences=True),
    TimeDistributed(Dense(n_features))
],name="Decoder")

autoencoder=Sequential([encoder,decoder])

Is it possible to train my model with different sequences with different lengths ? If yes, how have to proceed ?


问:
How do I use new AWS Amplify Authenticator flow with React Context?
The last time I looked at Authentication in AWS Amplify each authentication step had a request and response.  I stored the responses in a authentication global react context.

Now it appears there is a WYSIWYG widget that handles everything -- Authenticator
(https://ui.docs.amplify.aws/react/connected-components/authenticator/configuration).

The documentation focuses on UI customization but does not deep dive into the responses.  For example, when someone signs up I want to set their account to "pending" until they enter the email authentication code sent to their email address.  obviously if they leave the signup process mid cycle I need to age the account and remove it after x days if it is not completed.

How do I capture the flow response stage in order to do this?

ie., SIGNUP --> "add signing up to global context" --> CODE SENT --> "add pending to account" --> CODE ENTERED --> "activate account"

I tried figuring out how to catch the responses from aws authenticator with no luck.


问:
I have a problem with es_extended when i try to buy ammo and it did not save after restart
So whenever i buy ammo in shop for pistol for example, when i rejoin it just reset the ammo back

I tried downloading different script for weapon shop but it didnt work at all


问:
How to dispatch data that came by emitting event in socket in every subscribed to this event user?
I have application with client-side on React and ReduxToolkit and server-side on NodeJS and Socket.io, with page of adding posts form and page for output posts, but I dont know how to dispatch posts to reduxtk store in every user

I'm trying on every adding of post, emit event to all users and they got this new post without additional fetch, and I did it, but I cant understand how to dispatch this new post to reduxtoolkit store in every user that are subscribed to this event, not only the one who added this post

```<code> useEffect(() => {
    async function fetchPost(){
        const posts = await postService.getPosts()
        dispatch(setPosts(posts))
    }
    fetchPost()
    socket.on("connect",()=>{
      socket.send(`${user.userInfo.username} connected.`)
    })
    socket.on("updatePosts",async data=>{
      const { createdPost } = data
      dispatch(updatePosts(createdPost))
    })
    return () => {
     socket.off("updatePosts")
    }
  }, [])
</code>```

Body:
I have application with client-side on React and ReduxToolkit and server-side on NodeJS and Socket.io, with page of adding posts form and page for output posts, but I dont know how to dispatch posts to reduxtk store in every user

I'm trying on every adding of post, emit event to all users and they got this new post without additional fetch, and I did it, but I cant understand how to dispatch this new post to reduxtoolkit store in every user that are subscribed to this event, not only the one who added this post

 useEffect(() => {
    async function fetchPost(){
        const posts = await postService.getPosts()
        dispatch(setPosts(posts))
    }
    fetchPost()
    socket.on("connect",()=>{
      socket.send(`${user.userInfo.username} connected.`)
    })
    socket.on("updatePosts",async data=>{
      const { createdPost } = data
      dispatch(updatePosts(createdPost))
    })
    return () => {
     socket.off("updatePosts")
    }
  }, [])


问:
Send/Publish message from with Service Bus to RabbitMQ?
I knwo that's possible to send messages from RabbitMQ to Azure Service Bus, documentation in Microsoft Azure.

From my use case, I look to do the inverse : send message from Azure Service Bus to RabbitMQ and be consume.
Is it possible? Thank you.


问:
C# HelixToolkit: ObjReader reading from stream returns transparent model
I wanna load .obj/.mtl models in C# using the HelixToolkit.ObjReader. The Read(string path) method works fine but the Read(Stream objStream, Stream[] mtlStreams) method sometimes returns a transparent model. But i need to use the stream reading as my final models will come in a stream.

I got a Tree and a Appartment model:

And the two Read methods of this code..

```<code>    ObjReader objReader = new()
    {
        IsSmoothingDefault = true,
        SkipTransparencyValues = true,
        IgnoreErrors = false,
        SwitchYZ = false,
    };

    Model3DGroup modelGroup;

    //Read(path)
    modelGroup = objReader.Read(path);

    // Read(objStream, mtlStreams)
    string mtlPath = Path.ChangeExtension(path, "mtl");
    modelGroup = objReader.Read(
        new FileStream(path, FileMode.Open),
        new Stream[] { new FileStream(mtlPath, FileMode.Open) });
</code>```

.. produce these two different results:

Read(path): Everything looks fine.

Read(objStream, mtlStreams) : The appartmant has no materials and is transparent.

I am expecting both methods to behave the same, especially as the second method explicitely obtains the path to the .mtl file. Why is the model transparent?

Body:
I wanna load .obj/.mtl models in C# using the HelixToolkit.ObjReader. The Read(string path) method works fine but the Read(Stream objStream, Stream[] mtlStreams) method sometimes returns a transparent model. But i need to use the stream reading as my final models will come in a stream.

I got a Tree and a Appartment model:

And the two Read methods of this code..

    ObjReader objReader = new()
    {
        IsSmoothingDefault = true,
        SkipTransparencyValues = true,
        IgnoreErrors = false,
        SwitchYZ = false,
    };

    Model3DGroup modelGroup;

    //Read(path)
    modelGroup = objReader.Read(path);

    // Read(objStream, mtlStreams)
    string mtlPath = Path.ChangeExtension(path, "mtl");
    modelGroup = objReader.Read(
        new FileStream(path, FileMode.Open),
        new Stream[] { new FileStream(mtlPath, FileMode.Open) });

.. produce these two different results:

Read(path): Everything looks fine.

Read(objStream, mtlStreams) : The appartmant has no materials and is transparent.

I am expecting both methods to behave the same, especially as the second method explicitely obtains the path to the .mtl file. Why is the model transparent?


问:
NHibernate Cache throwing "Cannot access disposed object" exception
I am trying to use the NHibernate Cache RtMemoryCache in my .NET core web API.
I am using NHibernate 5.2.0, and the version of .NET Core is 3.1

The caching does not work properly when I cache a query on an entity and want to access the results of the query.
I get a "Cannot access disposed object" exception with this error message :

```<code>Cannot access a disposed object.
Object name: 'AsyncReaderWriterLock'.
</code>```

StackTrace :

```<code>   at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder)
   at NHibernate.Loader.Loader.ListUsingQueryCache(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces)
   at NHibernate.Loader.Criteria.CriteriaLoaderExtensions.LoadAllToList[T](IList`1 loaders, ISessionImplementor session)
   at NHibernate.Impl.SessionImpl.List[T](CriteriaImpl criteria)
   at NHibernate.Impl.CriteriaImpl.List[T]()
</code>```

I have setup my Cache in my Nhibernate loader class by adding it to the XML definition:

```<code>// Configuration cfg setup //
cfg.Cache((cacheProperties) => {
                cacheProperties.UseQueryCache = true;
                cacheProperties.DefaultExpiration = 300;
                });
            cfg.CreateIndexesForForeignKeys();
            cfg.SetProperty("cache.use_second_level_cache", "true");
            cfg.SetProperty("cache.provider_class", "NHibernate.Caches.RtMemoryCache.RtMemoryCacheProvider, NHibernate.Caches.RtMemoryCache");
</code>```

I have no clue about why this AsyncReaderWriterLock causes an issue. Could anyone help me with this?
Thank you!

Body:
I am trying to use the NHibernate Cache RtMemoryCache in my .NET core web API.
I am using NHibernate 5.2.0, and the version of .NET Core is 3.1

The caching does not work properly when I cache a query on an entity and want to access the results of the query.
I get a "Cannot access disposed object" exception with this error message :

Cannot access a disposed object.
Object name: 'AsyncReaderWriterLock'.

StackTrace :

   at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder)
   at NHibernate.Loader.Loader.ListUsingQueryCache(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces)
   at NHibernate.Loader.Criteria.CriteriaLoaderExtensions.LoadAllToList[T](IList`1 loaders, ISessionImplementor session)
   at NHibernate.Impl.SessionImpl.List[T](CriteriaImpl criteria)
   at NHibernate.Impl.CriteriaImpl.List[T]()

I have setup my Cache in my Nhibernate loader class by adding it to the XML definition:

// Configuration cfg setup //
cfg.Cache((cacheProperties) => {
                cacheProperties.UseQueryCache = true;
                cacheProperties.DefaultExpiration = 300;
                });
            cfg.CreateIndexesForForeignKeys();
            cfg.SetProperty("cache.use_second_level_cache", "true");
            cfg.SetProperty("cache.provider_class", "NHibernate.Caches.RtMemoryCache.RtMemoryCacheProvider, NHibernate.Caches.RtMemoryCache");

I have no clue about why this AsyncReaderWriterLock causes an issue. Could anyone help me with this?
Thank you!


问:
print markdown table when creating word doc using quarto
In my notebook I have some R code like this taken from here:

```<code>#| echo: false

data.frame(Function = "`read_delim()`",
           Formula = "$\\leftarrow$",
           Break = "this continues on a<br>new line",
           Link = "[Google](www.google.com)") |>
  kbl(format = "markdown")
</code>```

This produces output as Markdown but it is also Markdown in the final word document I create like this:

```<code>quarto render SomeNB.ipynb --to docx --execute
</code>```

How can I create a code generated table in this use case?

PS:

The current output in the word doc looks like this:

Body:
In my notebook I have some R code like this taken from here:

#| echo: false

data.frame(Function = "`read_delim()`",
           Formula = "$\\leftarrow$",
           Break = "this continues on a
new line",
           Link = "[Google](www.google.com)") |>
  kbl(format = "markdown")

This produces output as Markdown but it is also Markdown in the final word document I create like this:

quarto render SomeNB.ipynb --to docx --execute

How can I create a code generated table in this use case?

PS:

The current output in the word doc looks like this:


问:
Why do I not get a symmetric matrix
expected symmetric matrix

Why is the resulting matrix not symmetrical?
Jim

Hand multiplication gives a matrix that is not symmetrical

Title: Why do I not get a symmetric matrix


问:
/php_intl.h:33:10: fatal error: 'unicode/ubrk.h' file not found
I'm trying to install intl on Mac os Ventura 13.0.1 with XAMPP 8.1.12 with pecl with this command:

```<code>sudo /Applications/XAMPP/xamppfiles/bin/pecl install intl
</code>```

i cannot use directly pecl because i've also other installed php version.

Obviously i've already installed icu4c with command:

```<code>brew install icu4c
</code>```

Here's result of brew list icu4c

```<code>/opt/homebrew/Cellar/icu4c/71.1/bin/derb
/opt/homebrew/Cellar/icu4c/71.1/bin/genbrk
/opt/homebrew/Cellar/icu4c/71.1/bin/gencfu
/opt/homebrew/Cellar/icu4c/71.1/bin/gencnval
/opt/homebrew/Cellar/icu4c/71.1/bin/gendict
/opt/homebrew/Cellar/icu4c/71.1/bin/genrb
/opt/homebrew/Cellar/icu4c/71.1/bin/icu-config
/opt/homebrew/Cellar/icu4c/71.1/bin/icuexportdata
/opt/homebrew/Cellar/icu4c/71.1/bin/icuinfo
/opt/homebrew/Cellar/icu4c/71.1/bin/makeconv
/opt/homebrew/Cellar/icu4c/71.1/bin/pkgdata
/opt/homebrew/Cellar/icu4c/71.1/bin/uconv
/opt/homebrew/Cellar/icu4c/71.1/include/unicode/ (189 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/libicudata.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicui18n.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicuio.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicutest.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicutu.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicuuc.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/icu/ (4 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/pkgconfig/ (3 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/ (18 other files)
/opt/homebrew/Cellar/icu4c/71.1/sbin/escapesrc
/opt/homebrew/Cellar/icu4c/71.1/sbin/genccode
/opt/homebrew/Cellar/icu4c/71.1/sbin/gencmn
/opt/homebrew/Cellar/icu4c/71.1/sbin/gennorm2
/opt/homebrew/Cellar/icu4c/71.1/sbin/gensprep
/opt/homebrew/Cellar/icu4c/71.1/sbin/icupkg
/opt/homebrew/Cellar/icu4c/71.1/share/icu/ (4 files)
/opt/homebrew/Cellar/icu4c/71.1/share/man/ (15 files)
</code>```

Now once i try to install intl with pecl i got this error:

```<code> cc -I. -I/private/var/tmp/pear/temp/intl -I/private/var/tmp/pear/temp/pear-build-rootQBIGcB/intl-3.0.0/include -I/private/var/tmp/pear/temp/pear-build-rootQBIGcB/intl-3.0.0/main -I/private/var/tmp/pear/temp/intl -I/Applications/XAMPP/xamppfiles/include/php -I/Applications/XAMPP/xamppfiles/include/php/main -I/Applications/XAMPP/xamppfiles/include/php/TSRM -I/Applications/XAMPP/xamppfiles/include/php/Zend -I/Applications/XAMPP/xamppfiles/include/php/ext -I/Applications/XAMPP/xamppfiles/include/php/ext/date/lib -I/include -DHAVE_CONFIG_H -g -O2 -Wno-write-strings -DZEND_COMPILE_DL_EXT=1 -c /private/var/tmp/pear/temp/intl/php_intl.c -MMD -MF php_intl.dep -MT php_intl.lo  -fno-common -DPIC -o .libs/php_intl.o
In file included from /private/var/tmp/pear/temp/intl/php_intl.c:25:
In file included from /private/var/tmp/pear/temp/intl/php_intl.h:32:
/private/var/tmp/pear/temp/intl/collator/collator_sort.h:23:76: error: expected ')'
typedef int (*collator_compare_func_t)( zval *result, zval *op1, zval *op2 TSRMLS_DC );
                                                                           ^
/private/var/tmp/pear/temp/intl/collator/collator_sort.h:23:39: note: to match this '('
typedef int (*collator_compare_func_t)( zval *result, zval *op1, zval *op2 TSRMLS_DC );
                                      ^
In file included from /private/var/tmp/pear/temp/intl/php_intl.c:25:
/private/var/tmp/pear/temp/intl/php_intl.h:33:10: fatal error: 'unicode/ubrk.h' file not found
#include <unicode/ubrk.h>
         ^~~~~~~~~~~~~~~~
2 errors generated.
make: *** [php_intl.lo] Error 1
ERROR: `make' failed
</code>```

Once i start the install intl the script ask me:

Specify where ICU libraries and headers can be found [DEFAULT] :

i simple hint enter and got same error but i've also tried to use:

```<code>/opt/homebrew/Cellar/icu4c/71.1/include/unicode/
</code>```

but same error appear

I'm loosing my mind with this problem!!

Body:
I'm trying to install intl on Mac os Ventura 13.0.1 with XAMPP 8.1.12 with pecl with this command:

sudo /Applications/XAMPP/xamppfiles/bin/pecl install intl

i cannot use directly pecl because i've also other installed php version.

Obviously i've already installed icu4c with command:

brew install icu4c

Here's result of brew list icu4c

/opt/homebrew/Cellar/icu4c/71.1/bin/derb
/opt/homebrew/Cellar/icu4c/71.1/bin/genbrk
/opt/homebrew/Cellar/icu4c/71.1/bin/gencfu
/opt/homebrew/Cellar/icu4c/71.1/bin/gencnval
/opt/homebrew/Cellar/icu4c/71.1/bin/gendict
/opt/homebrew/Cellar/icu4c/71.1/bin/genrb
/opt/homebrew/Cellar/icu4c/71.1/bin/icu-config
/opt/homebrew/Cellar/icu4c/71.1/bin/icuexportdata
/opt/homebrew/Cellar/icu4c/71.1/bin/icuinfo
/opt/homebrew/Cellar/icu4c/71.1/bin/makeconv
/opt/homebrew/Cellar/icu4c/71.1/bin/pkgdata
/opt/homebrew/Cellar/icu4c/71.1/bin/uconv
/opt/homebrew/Cellar/icu4c/71.1/include/unicode/ (189 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/libicudata.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicui18n.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicuio.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicutest.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicutu.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/libicuuc.71.1.dylib
/opt/homebrew/Cellar/icu4c/71.1/lib/icu/ (4 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/pkgconfig/ (3 files)
/opt/homebrew/Cellar/icu4c/71.1/lib/ (18 other files)
/opt/homebrew/Cellar/icu4c/71.1/sbin/escapesrc
/opt/homebrew/Cellar/icu4c/71.1/sbin/genccode
/opt/homebrew/Cellar/icu4c/71.1/sbin/gencmn
/opt/homebrew/Cellar/icu4c/71.1/sbin/gennorm2
/opt/homebrew/Cellar/icu4c/71.1/sbin/gensprep
/opt/homebrew/Cellar/icu4c/71.1/sbin/icupkg
/opt/homebrew/Cellar/icu4c/71.1/share/icu/ (4 files)
/opt/homebrew/Cellar/icu4c/71.1/share/man/ (15 files)

Now once i try to install intl with pecl i got this error:

 cc -I. -I/private/var/tmp/pear/temp/intl -I/private/var/tmp/pear/temp/pear-build-rootQBIGcB/intl-3.0.0/include -I/private/var/tmp/pear/temp/pear-build-rootQBIGcB/intl-3.0.0/main -I/private/var/tmp/pear/temp/intl -I/Applications/XAMPP/xamppfiles/include/php -I/Applications/XAMPP/xamppfiles/include/php/main -I/Applications/XAMPP/xamppfiles/include/php/TSRM -I/Applications/XAMPP/xamppfiles/include/php/Zend -I/Applications/XAMPP/xamppfiles/include/php/ext -I/Applications/XAMPP/xamppfiles/include/php/ext/date/lib -I/include -DHAVE_CONFIG_H -g -O2 -Wno-write-strings -DZEND_COMPILE_DL_EXT=1 -c /private/var/tmp/pear/temp/intl/php_intl.c -MMD -MF php_intl.dep -MT php_intl.lo  -fno-common -DPIC -o .libs/php_intl.o
In file included from /private/var/tmp/pear/temp/intl/php_intl.c:25:
In file included from /private/var/tmp/pear/temp/intl/php_intl.h:32:
/private/var/tmp/pear/temp/intl/collator/collator_sort.h:23:76: error: expected ')'
typedef int (*collator_compare_func_t)( zval *result, zval *op1, zval *op2 TSRMLS_DC );
                                                                           ^
/private/var/tmp/pear/temp/intl/collator/collator_sort.h:23:39: note: to match this '('
typedef int (*collator_compare_func_t)( zval *result, zval *op1, zval *op2 TSRMLS_DC );
                                      ^
In file included from /private/var/tmp/pear/temp/intl/php_intl.c:25:
/private/var/tmp/pear/temp/intl/php_intl.h:33:10: fatal error: 'unicode/ubrk.h' file not found
#include <unicode/ubrk.h>
         ^~~~~~~~~~~~~~~~
2 errors generated.
make: *** [php_intl.lo] Error 1
ERROR: `make' failed

Once i start the install intl the script ask me:

Specify where ICU libraries and headers can be found [DEFAULT] :

i simple hint enter and got same error but i've also tried to use:

/opt/homebrew/Cellar/icu4c/71.1/include/unicode/

but same error appear

I'm loosing my mind with this problem!!


问:
Strange behaviour with FILTER on dynamic array in MS Excel
On an Excel sheet, please put these functions into the cells indicated:

A1:  =RANDARRAY(10,3,1,20,TRUE)

E1:  =FILTER(A1#,$B$1:$B$10>12)

I1: =FILTER(INDEX(A1#,SEQUENCE(ROWS(A1#)),{1,3}),$B$1:$B$10>12)

L1: =INDEX(A1#,SEQUENCE(ROWS(A1#)),{1,3})

Now hit your Function-9 key to generate new random numbers in the dynamic array anchored to cell A1.  Most of the time everything works as expected, but now and then you get a #SPILL error in E1 or in I1 or in both (never in L1).  The error message that appears when you hover over the little yellow triangle beside the #SPILL error says 'We can't tell how many rows and columns to spill into.'

What is causing this bizarre behaviour, and can I make it go away?
I’m using Excel version 2210 (Build 15726.20262)


问:
Is it possible to use missMDA for imputating values for MCA with FactoMineR and still get a modality names containing underlying variable names?
I use the missMDA and the factomineR package to create an object for my mca analysis. It works fine except for the names of the modalities. When I create a mca object without imputation, the names of the modalities are a combination of the underlying variable name and the factor level (like they should). But when I use the missMDA package and create the mca object based on the imputation, the modality names in the resulting mca object are named only after the factor levels.

An example:

```<code>library(tidyverse)
library(FactoMineR)
library(factoextra)
library(missMDA)
</code>```

I have data about preferences for oranges and apples, containing missings.

```<code>x <- data.frame("oranges" = sample(c("like", "dislike", NA), size = rownr, replace = TRUE),
                "apples" = sample(c("like", "dislike", NA), size = rownr, replace = TRUE)) %>%
  mutate(oranges = as.factor(oranges)) %>%
  mutate(apples = as.factor(apples))
</code>```

Creating the mca object without imputation results in meaningful modality names:
mca_no_imp <- MCA(x, graph = FALSE)

```<code>rownames(mca_no_imp$var$coord)
[1] "oranges.NA"      "oranges_dislike" "oranges_like"    "apples.NA"       "apples_dislike"  "apples_like"
</code>```

However, creating the mca object with imputation results in these modality names:

```<code>tab.disj <- imputeMCA(x, ncp = 1)$tab.disj
mca_w_imp <- MCA(x, tab.disj = tab.disj, graph = FALSE)
rownames(mca_w_imp$var$coord)
[1] "dislike" "like"    "dislike" "like"
</code>```

I already have a workaround for this problem: I create one mca object with imputation and one without and transfer the rownames. It works but it is cumbersome and prone to error. Has anyone an idea how to avoid the problem in the first place?

Thanks in advance!

Body:
I use the missMDA and the factomineR package to create an object for my mca analysis. It works fine except for the names of the modalities. When I create a mca object without imputation, the names of the modalities are a combination of the underlying variable name and the factor level (like they should). But when I use the missMDA package and create the mca object based on the imputation, the modality names in the resulting mca object are named only after the factor levels.

An example:

library(tidyverse)
library(FactoMineR)
library(factoextra)
library(missMDA)

I have data about preferences for oranges and apples, containing missings.

x <- data.frame("oranges" = sample(c("like", "dislike", NA), size = rownr, replace = TRUE),
                "apples" = sample(c("like", "dislike", NA), size = rownr, replace = TRUE)) %>%
  mutate(oranges = as.factor(oranges)) %>%
  mutate(apples = as.factor(apples))

Creating the mca object without imputation results in meaningful modality names:
mca_no_imp <- MCA(x, graph = FALSE)

rownames(mca_no_imp$var$coord)
[1] "oranges.NA"      "oranges_dislike" "oranges_like"    "apples.NA"       "apples_dislike"  "apples_like"

However, creating the mca object with imputation results in these modality names:

tab.disj <- imputeMCA(x, ncp = 1)$tab.disj
mca_w_imp <- MCA(x, tab.disj = tab.disj, graph = FALSE)
rownames(mca_w_imp$var$coord)
[1] "dislike" "like"    "dislike" "like"

I already have a workaround for this problem: I create one mca object with imputation and one without and transfer the rownames. It works but it is cumbersome and prone to error. Has anyone an idea how to avoid the problem in the first place?

Thanks in advance!


问:
Download file in android studio with the original file name
How to write the code to download file in android studio with the original file name?

I am trying to create a very simple webview mobile android application as I am a beginner in this field. I am almost done but I am stuck at a problem. It is working perfectly with .pdf but it is saving .lrc files with .txt extension.

My code is:

MainActivity.java

```<code>webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String fileExtenstion, long contentLength) {

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                MimeTypeMap.getFileExtensionFromUrl(url);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie",cookies);
                request.addRequestHeader("User-Agent",userAgent);
                request.setDescription("Downloading file....");
                request.setTitle(URLUtil.guessFileName(url,contentDisposition,fileExtenstion));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, fileExtenstion));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(),"Downloading File",Toast.LENGTH_SHORT).show();

            }
        });  ```

**AndroidManiFest.xml**

```

```

Can you guys help me to make it right please.

Body:
How to write the code to download file in android studio with the original file name?

I am trying to create a very simple webview mobile android application as I am a beginner in this field. I am almost done but I am stuck at a problem. It is working perfectly with .pdf but it is saving .lrc files with .txt extension.

My code is:

MainActivity.java

webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String fileExtenstion, long contentLength) {

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                MimeTypeMap.getFileExtensionFromUrl(url);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie",cookies);
                request.addRequestHeader("User-Agent",userAgent);
                request.setDescription("Downloading file....");
                request.setTitle(URLUtil.guessFileName(url,contentDisposition,fileExtenstion));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, fileExtenstion));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(),"Downloading File",Toast.LENGTH_SHORT).show();

            }
        });  ```

**AndroidManiFest.xml**

</code></pre>

```

Can you guys help me to make it right please.


问:
POSIX Shell Conventions: Is it given that lowercase names are reserved for binaries and uppercase names are intended for variables?

Background

I'm writing some scripts for standing up WSL instances with regularity, due to accidentally ruining a previous install, and the painful process of getting it back to a workable state. As part of this, I'm learning a lot about how Unix is managed, since it differs greatly from Windows.

Question

Is there a convention for avoiding name collisions between built-ins/binaries and variables?

This question came to mind because of certain common words for binaries, like groups and file, and I was having to be careful in situations like for file in ~/.ssh.

My Current Understanding

In some cases, it looks like all-lowercase names are the norm for binaries, sometimes kebab-case, and obviously you can't write kebab-case variables. I also don't normally see uppercase names used outside of things like $PATH or $HOME. That said, while those can be considered variables, they also follow the C convention of all-caps for runtime constants, since they are largely static. You can add things to $PATH, but it usually handled by a start-up process, like ~/.bashrc.

Example Code

# User Setup
## Perform setup for each user account provisioned (should only be one)
for USERHOME in /home/*; do
    USER="$(basename "$USERHOME")"

    # make directory for SSH keys
    mkdir -p "$USERHOME/.ssh"
    # make development directories
    mkdir -p "$USERHOME/bitbucket" "$USERHOME/github" "$USERHOME/gitlab"

    # Copy SSH keys from host machine into each user
    for fp in /mnt/c/Users/some_user/.ssh/*; do
        f="$USERHOME/.ssh/$(basename "$fp")"

        # If the SSH file isn't found in the current user's $HOME/.ssh
        if ! test -e "$f"; then
            # Copy from host machine
            cp "$fp" "$f"
        fi

        # test if no extension, which is common for private SSH keys
        # The test compares target file with a substitution that returns everything after a period (commonly the extension)
        # Note: Problem occurs due to directory (~/.ssh) containing period.
        fname = $(basename "$f")
        if test -f "$f" && test "$fname" = "${fname#*.}"; then
            # Private keys shouldn't be available to other users
            chmod 600 "$f"
        else
            # Other files (like public keys) can be read-only to all users
            chmod 644 "$f"
        fi
    done

    # Add ssh-agent start command, and add SSH keys
    if ! grep -q "ssh-agent" "$USERHOME/.bashrc"; then
        tee -a "$USERHOME/.bashrc" <<- EOF > /dev/null
            # Note: ssh-agent process count will include grep scan. Check for only one for not-started
            if test \$(ps -ef | grep -c "ssh-agent") -eq 1; then
                eval "\$(ssh-agent -s)"
            elif test -z $SSH_AGENT_PID; then
                export SSH_AUTH_SOCK=$(ls -1 /tmp/ssh-*/agent.* | head -n1)
                export SSH_AGENT_PID="${SSH_AUTH_SOCK#*.}"
            fi

            if test \$(ls ~/.ssh/*_ed25519 2>/dev/null); then
                ssh-add ~/.ssh/*_ed25519
            fi

            if test \$(ls ~/.ssh/*_rsa 2>/dev/null); then
                ssh-add ~/.ssh/*_rsa
            fi
        EOF
    fi

    # Add current user to Docker permissions group
    if test $(groups $USER | grep -c "docker") -eq 0; then
        usermod -aG docker "$USER"
    fi

  if test -d /root/.cargo; then
    cp /root/.cargo "$USERHOME"
    echo '. "$HOME/.cargo/env"' >> "$USERHOME/.bashrc"
  fi

    # Switch ownership of the user's HOME to current user (defaults to root)
    chown -fR "$USER" "$USERHOME"
done
```


问:
How can I increase the throughput in Android using COC? I cant find a way to change MTU
Throughput of coc android was low. How can I increase it?

I can't find a way change the MTU in android coc api. I know using GATT there is a way to request for MTU negotiation..
The throughput I received was lower than using Gatt..how can i increase the mtu?
Thanks


问:
set and image for a canvas when user clicks and when we have multiple canvases on tkinter
I have a code that makes multiple canvases on Python tkinter (9 canvas). With this function (I destroy all item on window with destroy function at start):

```<code>def show_board(self):
    self.destroy_start()
    canvas_list = []
    for i in range(9):
        dist = {
            f"canvas{i + 1}": Canvas(height=150, width=150, bg=BOARD_COLOR),
        }
        canvas_list.append(dist)
    for n in range(len(canvas_list)):
        canvas_dict = canvas_list[n]
        for (key, val) in canvas_dict.items():
            if n == 0 or n <= 2:
                row = 0
                if n == 0:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 1:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 2:
                    col = 2
                    val.grid(row=row, column=col)
            elif 2 < n <= 5:
                row = 1
                if n == 3:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 4:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 5:
                    col = 2
                    val.grid(row=row, column=col)
            elif n > 5:
                row = 2
                if n == 6:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 7:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 8:
                    col = 2
                    val.grid(row=row, column=col)
    # loop in canvas and get x and y of the click and set the image when user click
    for item in canvas_list:
        for (key, val) in item.items():
            canvas_x, canvas_y = val.winfo_rootx(), val.winfo_rooty()
            print(canvas_x, canvas_y)
            self.check_click(can=val)

    self.pl1_score_label.grid(column=0, row=3, padx=(100, 0))
    self.pl2_score_label.grid(column=2, row=3)
</code>```

and I want to when user clicks on window on one of these canvases for the canvas to create an image (just than canvas)
I try to do this with last loop in upper function

```<code>def display_mouse_pos(self, event):
    self.window.update()
    x = event.x
    y = event.y
    print(x, y)

def check_click(self, can):
    self.window.bind("<Button-1>", self.display_mouse_pos)
    can.create_image(100, 100, image=self.x_image)
    self.window.update()`
</code>```

but I get that image on all canvas I know problem is my function and for loop I can't find the way to check if screen get clicked or not and if its get clicked which canvas get clicked and who can I make a picture in that canvas

Body:
I have a code that makes multiple canvases on Python tkinter (9 canvas). With this function (I destroy all item on window with destroy function at start):

def show_board(self):
    self.destroy_start()
    canvas_list = []
    for i in range(9):
        dist = {
            f"canvas{i + 1}": Canvas(height=150, width=150, bg=BOARD_COLOR),
        }
        canvas_list.append(dist)
    for n in range(len(canvas_list)):
        canvas_dict = canvas_list[n]
        for (key, val) in canvas_dict.items():
            if n == 0 or n <= 2:
                row = 0
                if n == 0:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 1:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 2:
                    col = 2
                    val.grid(row=row, column=col)
            elif 2 < n <= 5:
                row = 1
                if n == 3:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 4:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 5:
                    col = 2
                    val.grid(row=row, column=col)
            elif n > 5:
                row = 2
                if n == 6:
                    col = 0
                    val.grid(row=row, column=col, padx=(125, 0))
                elif n == 7:
                    col = 1
                    val.grid(row=row, column=col)
                elif n == 8:
                    col = 2
                    val.grid(row=row, column=col)
    # loop in canvas and get x and y of the click and set the image when user click
    for item in canvas_list:
        for (key, val) in item.items():
            canvas_x, canvas_y = val.winfo_rootx(), val.winfo_rooty()
            print(canvas_x, canvas_y)
            self.check_click(can=val)

    self.pl1_score_label.grid(column=0, row=3, padx=(100, 0))
    self.pl2_score_label.grid(column=2, row=3)

and I want to when user clicks on window on one of these canvases for the canvas to create an image (just than canvas)
I try to do this with last loop in upper function

def display_mouse_pos(self, event):
    self.window.update()
    x = event.x
    y = event.y
    print(x, y)

def check_click(self, can):
    self.window.bind("<Button-1>", self.display_mouse_pos)
    can.create_image(100, 100, image=self.x_image)
    self.window.update()`

but I get that image on all canvas I know problem is my function and for loop I can't find the way to check if screen get clicked or not and if its get clicked which canvas get clicked and who can I make a picture in that canvas


问:
Spark session is Started but not executing the Next cells in synapse notebook?
I have started the Cluster in azure synapse and the spark session has been started in 2 to 3 minutes but rather than moving to next cell for executing all the cells the execution is still happening in first cell only. what can be the issue which is causing this problem? i am attaching a SS which will show that session is started but the cell is still executing

What we can do to resolve this issue?


问:
Turn off JSON deserialization of results from spanner
We pull many large-ish payloads from Spanner, and the current performance bottleneck is deserializing the result from Spanner into objects in memory. We don't need these objects, as the result is just going to pass through to another application. I haven't seen anything in the SDK documentation about this, but I'm sure there is a way to provide a custom deserialization, or to turn it off altogether. We currently use the Javascript and Java SDKs, so any advice on either is appreciated. Thanks!</p>


问:
Cloud hosted jupyter-style notebook with user authentication against a REST API
I am interested in setting up a site hosting a cloud-hosted jupyter-style notebook, which users can provide their credentials to. The credentials are used for authenticated access to a REST API which can then be called from the notebook to retrieve data which users can then perform data-science type investigations on, e.g. similar to a kaggle notebook, but for a specific REST API.

Ideally the kernal would be hosted on the client's machine or elsewhere, so as to avoid having to provide server-side resources (storage and compute power) to run user's code.

I've been looking at jupyterlite and google colab as possible solutions.

Any suggestions for how to approach this would be much appreciated.


问:
How to encode binary file inside JavaScript in HTML
I want to use a HTML webpage that uses a .bin file with JavaScript.

I have found out that browsers don't support opening files from JS with anything BUT a protocol.
Console in Google Chrome throws the "origin 'null' has been blocked by CORS policy"

HOWEVER, could I paste the binary file's base64 value (e.g. data URI or JSON) inside the .HTML instead of asking it to open the file?

```<code>  ...
  var filename = "recipes_0_" + cut_cost + "_" + stack_cost + (singleLayerIsRaw?"r":"") + ".bin";
  load_binary_resource( filename );
}

function onPageLoad() {
  document.getElementById("code").disabled = true;
  //load_binary_resource("[base64 value]");

</code>```

instead of

```<code>  document.getElementById("code").disabled = true;
  //load_binary_resource("myfile.bin");
</code>```

Body:
I want to use a HTML webpage that uses a .bin file with JavaScript.

I have found out that browsers don't support opening files from JS with anything BUT a protocol.
Console in Google Chrome throws the "origin 'null' has been blocked by CORS policy"

HOWEVER, could I paste the binary file's base64 value (e.g. data URI or JSON) inside the .HTML instead of asking it to open the file?

  ...
  var filename = "recipes_0_" + cut_cost + "_" + stack_cost + (singleLayerIsRaw?"r":"") + ".bin";
  load_binary_resource( filename );
}

function onPageLoad() {
  document.getElementById("code").disabled = true;
  //load_binary_resource("[base64 value]");

instead of

  document.getElementById("code").disabled = true;
  //load_binary_resource("myfile.bin");


问:
kernel development, physical addresses and virtual addresses
I'm writing an operating system (kernel) as a hobby and I have a problem with the "boot boot" bootloader:

When my kernel's main() is loaded I retrieve screen pointers to display text on the screen.

When I enable paging in my kernel the physical addresses are no longer visible, of course, because paging has been enabled.
I created a macro that allows me to transform addresses from physical to virtual and vice versa.

The question is how can I make the physical address pointing to the screen (fb on bootboot) when the paging is enabled ?


问:
How to define custom parameters in Stimulsoft report and send value from webfrom application
I want to generate and show printable reports to my client using Stimulsoft report and ASP.NET web application in C#.

I already designed a MRT file by generating custom columns from data from dataset.datatable corresponding to a stored procedure result.

Here my columns are those from executing the stored procedure and all of the report columns are the same.

```<code>|deviceId|,|deviceName|,|deviceDesc|,|deviceTypeName|,|priceValue|
</code>```

And I set all of the types of columns in the report as string.

Here is my stored procedure:

```<code>ALTER PROCEDURE [dbo].[DeviceAllLastPrice]
    @userName BIGINT
AS
BEGIN
    SELECT
        D.deviceId, d.deviceName, d.deviceDesc, d.deviceImg,
        dt.deviceTypeId, dt.deviceTypeName,
        p.priceId, p.priceValue, p.PriceDateTime
    FROM
        Device d
    INNER JOIN
        DeviceType dt ON d.deviceTypeId = dt.deviceTypeId
    OUTER APPLY
        (SELECT TOP 1
             dp.priceId, dp.priceValue,dp.PriceDateTime
         FROM
             DevicePrice dp
         WHERE
             dp.deviceId = d.deviceId
             AND dp.userName = @userName
         ORDER BY
             dp.priceId DESC) p
    WHERE
        p.priceValue IS NOT NULL
END
</code>```

All of the columns in the report file are in DataSource1 and I add another extra parameter called SolarDate as a string, outside the stored procedure.

Now here is the problem: when I load the data from the database using Entity Framework and bound them with the report everything is ok, except my custom parameter SolarDate which I gave it a value in page load, won't show in the report.

Here is my C# code in page load:

```<code>protected void Page_Load(object sender, EventArgs e)
{
        using (var db = new DbModel())
        {
            var data = db.DeviceAllLastPrice(1).ToList();

            StiReport report = new StiReport();
            report.RegData("myReport", data);
            report.Load(Server.MapPath("~/Reports/Report.mrt"));
            report.Compile();

            report["SolarDate"] = clsEasy.makeDateToPersian(DateTime.Now);
            report.Render();
            StiWebViewer1.Report = report;
        }
}
</code>```

Body:
I want to generate and show printable reports to my client using Stimulsoft report and ASP.NET web application in C#.

I already designed a MRT file by generating custom columns from data from dataset.datatable corresponding to a stored procedure result.

Here my columns are those from executing the stored procedure and all of the report columns are the same.

|deviceId|,|deviceName|,|deviceDesc|,|deviceTypeName|,|priceValue|

And I set all of the types of columns in the report as string.

Here is my stored procedure:

ALTER PROCEDURE [dbo].[DeviceAllLastPrice]
    @userName BIGINT
AS
BEGIN
    SELECT
        D.deviceId, d.deviceName, d.deviceDesc, d.deviceImg,
        dt.deviceTypeId, dt.deviceTypeName,
        p.priceId, p.priceValue, p.PriceDateTime
    FROM
        Device d
    INNER JOIN
        DeviceType dt ON d.deviceTypeId = dt.deviceTypeId
    OUTER APPLY
        (SELECT TOP 1
             dp.priceId, dp.priceValue,dp.PriceDateTime
         FROM
             DevicePrice dp
         WHERE
             dp.deviceId = d.deviceId
             AND dp.userName = @userName
         ORDER BY
             dp.priceId DESC) p
    WHERE
        p.priceValue IS NOT NULL
END

All of the columns in the report file are in DataSource1 and I add another extra parameter called SolarDate as a string, outside the stored procedure.

Now here is the problem: when I load the data from the database using Entity Framework and bound them with the report everything is ok, except my custom parameter SolarDate which I gave it a value in page load, won't show in the report.

Here is my C# code in page load:

protected void Page_Load(object sender, EventArgs e)
{
        using (var db = new DbModel())
        {
            var data = db.DeviceAllLastPrice(1).ToList();

            StiReport report = new StiReport();
            report.RegData("myReport", data);
            report.Load(Server.MapPath("~/Reports/Report.mrt"));
            report.Compile();

            report["SolarDate"] = clsEasy.makeDateToPersian(DateTime.Now);
            report.Render();
            StiWebViewer1.Report = report;
        }
}


问:
Flutter_Switch state on PageView widget
I am using the package Flutter_Switch to create a switch button on a PageView.

When i turn the switch 'ON' and move to the new page within my PageView the state of the switch on is already 'ON', like it's inherited the state from the previous page.

Is there a way to control this switch per PageView page?

Link to code snippet of my PageView widget
Code Snip

Title: Flutter_Switch state on PageView widget


问:
exportAllData property not working for material table react
I have below default options set for the material table

```<code>const defaultOptions = {
    filtering: false,
    search: false,
    exportButton: true,
    exportAllData: true,
    pageSize: 10,
    pageSizeOptions: [10, 50, 100],
    actionsColumnIndex: -1,
    padding: 'dense',
    showTitle: true,
    exportCsv: (columns,data ) => {
      const columnTitles = columns
          .map(columnDef => columnDef.title);
      const csvData = data.map(rowData =>
            columns.map(columnDef =>  {
                return rowData[columnDef.field] ;
            } ),
          );
      const builder = new CsvBuilder(`sampledata.csv`)
            .setColumns(columnTitles)
            .addRows(csvData)
            .exportFile();
      return builder;
    }
  };
</code>```

But when I am trying to export , its still showing data for the first 10 rows even if the total rows are 50. I have set exportAllData: true in the default options.
I want to export all 50 rows in the CSV file.

Body:
I have below default options set for the material table

const defaultOptions = {
    filtering: false,
    search: false,
    exportButton: true,
    exportAllData: true,
    pageSize: 10,
    pageSizeOptions: [10, 50, 100],
    actionsColumnIndex: -1,
    padding: 'dense',
    showTitle: true,
    exportCsv: (columns,data ) => {
      const columnTitles = columns
          .map(columnDef => columnDef.title);
      const csvData = data.map(rowData =>
            columns.map(columnDef =>  {
                return rowData[columnDef.field] ;
            } ),
          );
      const builder = new CsvBuilder(`sampledata.csv`)
            .setColumns(columnTitles)
            .addRows(csvData)
            .exportFile();
      return builder;
    }
  };

But when I am trying to export , its still showing data for the first 10 rows even if the total rows are 50. I have set exportAllData: true in the default options.
I want to export all 50 rows in the CSV file.


问:
How stream the data between particular client to server in websocket?
I'm trying to make individual connection, but it was not working in node js.</p>
```<code>let wss = new WebSocketServer({ port: 2217 });

wss.on('connection', async function connection(ws, request) {
        try {
            let ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;

            ws.id = request.headers.uniqekey;

            ws.on('message', async function incoming(message) {

            let customObj = {regno:123,
                             name:'peter'}
            ws.send(JSON.stringify(customObj));

            })
      }catch(error){

      }
})
</code>```

Body:
I'm trying to make individual connection, but it was not working in node js.

let wss = new WebSocketServer({ port: 2217 });

wss.on('connection', async function connection(ws, request) {
        try {
            let ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;

            ws.id = request.headers.uniqekey;

            ws.on('message', async function incoming(message) {

            let customObj = {regno:123,
                             name:'peter'}
            ws.send(JSON.stringify(customObj));

            })
      }catch(error){

      }
})


问:
Placing multiple texts and photos together in Flutter
I want to receive a text from the database, for example the text below
"Lorem ipsum dolor sit amet, consectetur {IMAG01.PNGG} adipiscing elit, sed do eiusmod tempor {IMAG02.PNG} incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
And wherever the {} sign is checked, whether the string inside the image is there or not, if it is, it will place the image from the memory, otherwise the text will be displayed.
Set the scroll size to the size of the page text.

I did it in Visual Basic by these codes

`Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
Activity.LoadLayout("l_contents_image")
Sql2.Initialize(File.DirInternal , "database.db" ,True)
curcit = Sql2.ExecQuery("SELECT * From TableContentsImage")
curcit.Position =  Main.listid_cit
sv.Initialize(0)

```<code>curset = Sql2.ExecQuery("SELECT * From TableSetting")
curset.Position = 0

sv.Color = Colors.White
Activity.AddView(sv,0,0,100%x,100%y)
Private text As String = curcit.GetString("text")
Dim part(3) As Int
part = Array As Int(0,0,0)
For i = 0 To text.Length - 1
    If text.CharAt(i) = "{" Then
        part(1) = i
        If text.SubString2(part(0),part(1)) <> "" Then
            setLabel(text.SubString2(part(0),part(1)))
        End If
    End If
    If text.CharAt(i) = "}" Then
        part(2) = i
        setImage(text.SubString2(part(1) + 1,part(2)))
        part(0) = part(2) + 1
    End If
Next

sv.Panel.Height = offsetY + 3%y
</code>```

End Sub`

Sub setLabel(value As String) Private lbl As Label lbl.Initialize("") lbl.TextColor = Colors.Black lbl.TextSize = 20 lbl.Text = value lbl.Gravity = Gravity.CENTER 'lbl.Typeface = Typeface.LoadFromAssets("arabic.ttf") sv.Panel.AddView(lbl,1%x,offsetY,98%x,5%y) Dim stu As StringUtils lbl.Height = stu.MeasureMultilineTextHeight(lbl,lbl.Text) offsetY = stu.MeasureMultilineTextHeight(lbl,lbl.Text) + lbl.Top + 1%y End Sub

Sub setImage(value As String) If(value.EndsWith(".jpg") Or value.EndsWith(".png")) Then Private img As ImageView img.Initialize("") img.Gravity = Gravity.FILL sv.Panel.AddView(img,33%x,offsetY,33%x,33%y) Dim b As BitmapDrawable b.Initialize(LoadBitmapSample(File.DirAssets,value,img.Width,img.Height)) img.Bitmap = b.Bitmap offsetY = img.Top + img.Height +1%y End If End Sub
Now I want to do this in Flutter.

Body:
I want to receive a text from the database, for example the text below
"Lorem ipsum dolor sit amet, consectetur {IMAG01.PNGG} adipiscing elit, sed do eiusmod tempor {IMAG02.PNG} incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
And wherever the {} sign is checked, whether the string inside the image is there or not, if it is, it will place the image from the memory, otherwise the text will be displayed.
Set the scroll size to the size of the page text.

I did it in Visual Basic by these codes

`Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
Activity.LoadLayout("l_contents_image")
Sql2.Initialize(File.DirInternal , "database.db" ,True)
curcit = Sql2.ExecQuery("SELECT * From TableContentsImage")
curcit.Position =  Main.listid_cit
sv.Initialize(0)

curset = Sql2.ExecQuery("SELECT * From TableSetting")
curset.Position = 0

sv.Color = Colors.White
Activity.AddView(sv,0,0,100%x,100%y)
Private text As String = curcit.GetString("text")
Dim part(3) As Int
part = Array As Int(0,0,0)
For i = 0 To text.Length - 1
    If text.CharAt(i) = "{" Then
        part(1) = i
        If text.SubString2(part(0),part(1)) <> "" Then
            setLabel(text.SubString2(part(0),part(1)))
        End If
    End If
    If text.CharAt(i) = "}" Then
        part(2) = i
        setImage(text.SubString2(part(1) + 1,part(2)))
        part(0) = part(2) + 1
    End If
Next

sv.Panel.Height = offsetY + 3%y

End Sub`

Sub setLabel(value As String) Private lbl As Label lbl.Initialize("") lbl.TextColor = Colors.Black lbl.TextSize = 20 lbl.Text = value lbl.Gravity = Gravity.CENTER 'lbl.Typeface = Typeface.LoadFromAssets("arabic.ttf") sv.Panel.AddView(lbl,1%x,offsetY,98%x,5%y) Dim stu As StringUtils lbl.Height = stu.MeasureMultilineTextHeight(lbl,lbl.Text) offsetY = stu.MeasureMultilineTextHeight(lbl,lbl.Text) + lbl.Top + 1%y End Sub

Sub setImage(value As String) If(value.EndsWith(".jpg") Or value.EndsWith(".png")) Then Private img As ImageView img.Initialize("") img.Gravity = Gravity.FILL sv.Panel.AddView(img,33%x,offsetY,33%x,33%y) Dim b As BitmapDrawable b.Initialize(LoadBitmapSample(File.DirAssets,value,img.Width,img.Height)) img.Bitmap = b.Bitmap offsetY = img.Top + img.Height +1%y End If End Sub
Now I want to do this in Flutter.


问:
How i can make this relations on prisma
this is my schema prisma i have error.

```<code>model Deliveries {
    id             String @id   @default(uuid())
    id_client      String
    client         Clients  @relation(fields: [id_client], references: [id])
    id_deliveryman String
    deliveryman    DeliveryMan  @relation(fields: [id_client], references: [id])

    item_name   String
    created_at  DateTime @default(now())
    end_at      DateTime @default(now())
}
</code>```

and i have error

Error parsing attribute "@relation": The given constraint name Deliveries_id_client_fkey has to be unique in the following namespace: on model Deliveries for primary key, indexes, unique constraints and foreign keys. Please provide a different name using the map argument.

Error validating field deliveryman in model Deliveries: The relation field deliveryman on Model Deliveries is missing an opposite relation field on the model DeliveryMan. Either run prisma format or add it manually"

Title: How i can make this relations on prisma

Body:
this is my schema prisma i have error.

model Deliveries {
    id             String @id   @default(uuid())
    id_client      String
    client         Clients  @relation(fields: [id_client], references: [id])
    id_deliveryman String
    deliveryman    DeliveryMan  @relation(fields: [id_client], references: [id])

    item_name   String
    created_at  DateTime @default(now())
    end_at      DateTime @default(now())
}

and i have error

Error parsing attribute "@relation": The given constraint name Deliveries_id_client_fkey has to be unique in the following namespace: on model Deliveries for primary key, indexes, unique constraints and foreign keys. Please provide a different name using the map argument.

Error validating field deliveryman in model Deliveries: The relation field deliveryman on Model Deliveries is missing an opposite relation field on the model DeliveryMan. Either run prisma format or add it manually"


问:
Run macro(XLSB) using python
I am facing the below error using python to call a macro from my macro workbook that contains all my macros and it's in XLSB extension
Error:
FileNotFoundError: No such file:

Python code:

```<code>import xlwings as xw
wb = xw.Book(r'C:\1.Work\Automation\Personal All MAcro codes.xlsb')
your_macro = wb.macro('Iwebsite')
your_macro(1, 2)
</code>```

Title: Run macro(XLSB) using python

Body:
I am facing the below error using python to call a macro from my macro workbook that contains all my macros and it's in XLSB extension
Error:
FileNotFoundError: No such file:

Python code:

import xlwings as xw
wb = xw.Book(r'C:\1.Work\Automation\Personal All MAcro codes.xlsb')
your_macro = wb.macro('Iwebsite')
your_macro(1, 2)


问:
NestJS Dependency Injection with Constructor Parameters
I have a custom NewLogger class that implements LoggerService and has so far worked perfectly without Dependency Injection. It wraps around log4js's Logger class and leverages it for logging. So far, I have avoided DI since I use the logger outside injectable service layer, such as configuration files, and other loose functions that sit outside Module scopes. And since it had simple dependencies, it was never necessary.

```<code>export class NewLogger implements LoggerService {
  private readonly constants: GlobalConstants = new GlobalConstants();

  //@Inject(CACHE_MANAGER) private cacheManager: Cache

  private LOGGER: Logger;

  constructor(name: string) {
    const log4js: Log4js = getConfiguredLog4js();
    this.LOGGER = log4js.getLogger(name);
  }

  log(message, ...optionalParams: any[]) {
    this.LOGGER.info(`${message}`, ...optionalParams);
  }
</code>```

However, I now need to use caching in this same Logger, which according to documentation, requires the injection of the CACHE_MANAGER token into the Cache object. This currently does not work in the NewLogger since it itself is not Injectable.

I need to pick a route to progress here and see two options:

I somehow leverage caching without using the DI method documented, but I have not found any way to do this yet as it seems to be dependent on the CACHE_MANAGER token and implementation. How can I use caching without DI?

I make NewLogger Injectable() and inject it in cases where I need to leverage caching. This would be fine, but the problem with this approach is then I lose the ability to pass dynamic constructor parameters, which means that the log messages will no longer display the name of the class that executed the log message, which I definitely also need. How can I pass in dynamic constructor parameters (the name String) whenever injecting NewLogger?

Which of the two options is best and how would I implement it? Are there other options?

Any help will be highly appreciated, let me know if any extra information is needed.

Body:
I have a custom NewLogger class that implements LoggerService and has so far worked perfectly without Dependency Injection. It wraps around log4js's Logger class and leverages it for logging. So far, I have avoided DI since I use the logger outside injectable service layer, such as configuration files, and other loose functions that sit outside Module scopes. And since it had simple dependencies, it was never necessary.

export class NewLogger implements LoggerService {
  private readonly constants: GlobalConstants = new GlobalConstants();

  //@Inject(CACHE_MANAGER) private cacheManager: Cache

  private LOGGER: Logger;

  constructor(name: string) {
    const log4js: Log4js = getConfiguredLog4js();
    this.LOGGER = log4js.getLogger(name);
  }

  log(message, ...optionalParams: any[]) {
    this.LOGGER.info(`${message}`, ...optionalParams);
  }

However, I now need to use caching in this same Logger, which according to documentation, requires the injection of the CACHE_MANAGER token into the Cache object. This currently does not work in the NewLogger since it itself is not Injectable.

I need to pick a route to progress here and see two options:

I somehow leverage caching without using the DI method documented, but I have not found any way to do this yet as it seems to be dependent on the CACHE_MANAGER token and implementation. How can I use caching without DI?

I make NewLogger Injectable() and inject it in cases where I need to leverage caching. This would be fine, but the problem with this approach is then I lose the ability to pass dynamic constructor parameters, which means that the log messages will no longer display the name of the class that executed the log message, which I definitely also need. How can I pass in dynamic constructor parameters (the name String) whenever injecting NewLogger?

Which of the two options is best and how would I implement it? Are there other options?

Any help will be highly appreciated, let me know if any extra information is needed.


问:
Flask blueprint: Template not showing
I have a Flask app with the following blueprint:

folder: fabu

init.py

```<code>from .views import fabu
</code>```

views.py

```<code>fabu = Blueprint("fabu", __name__)

@fabu.route('/', methods=['GET', 'POST'])
def index():
...
  return render_template('index.html')
</code>```

Two html templates in the fabu folder.

Then in app.py I register the blueprints.

```<code>from .fabu import fabu

DEFAULT_BLUEPRINTS = (
frontend,
settings,
tasks,
fabu)

def create_app(config=None, app_name=None, blueprints=None):
...
configure_blueprints(app, blueprints)
</code>```

```<code>def configure_blueprints(app, blueprints):
# Configure blueprints in views

for blueprint in blueprints:
    app.register_blueprint(blueprint)
</code>```

Folder: templates/dashboard

dashboard.html:

```<code>{

% block body %}

  <div class="container">
    <div class="row mt-5">
      <div class="col-6 offset-3">
        {{ url_for('fabu.index')}}
      </div>
    </div>
  </div>

{% endblock %}
</code>```

With the above code dashboard.html shows '/' instead of the content of my fabu templates embedded in dashboard.html.
I'm probably missing something simple?

Title: Flask blueprint: Template not showing

Body:
I have a Flask app with the following blueprint:

folder: fabu

init.py

from .views import fabu

views.py

fabu = Blueprint("fabu", __name__)

@fabu.route('/', methods=['GET', 'POST'])
def index():
...
  return render_template('index.html')

Two html templates in the fabu folder.

Then in app.py I register the blueprints.

from .fabu import fabu

DEFAULT_BLUEPRINTS = (
frontend,
settings,
tasks,
fabu)

def create_app(config=None, app_name=None, blueprints=None):
...
configure_blueprints(app, blueprints)

def configure_blueprints(app, blueprints):
# Configure blueprints in views

for blueprint in blueprints:
    app.register_blueprint(blueprint)

Folder: templates/dashboard

dashboard.html:

{

% block body %}

        {{ url_for('fabu.index')}}

{% endblock %}

With the above code dashboard.html shows '/' instead of the content of my fabu templates embedded in dashboard.html.
I'm probably missing something simple?


问:
Query similar entity on different DB schema JpaRepository
I'm developing a Java-Spring application that has 2 modules, with a database schema for each one, and I'm using Hibernate.

Let's say I have one entity in schema named A which looks like this:

```<code>@Entity
public class entityInSchemaA {

    private String field1;

    private boolean boolean1;

    private Integer integer1;

    ...Other fields specific to this class...

}
</code>```

And another entity in schema named B, that shares just some fields with the entity above, and it looks like this:

```<code>@Entity
public class entityInSchemaB {

    private String field1;

    private boolean boolean1;

    private Integer integer1;

    ...Other fields specific to this class...

}
</code>```

I was wondering if there is a conventional/correct/clean way to do something like:

From the application module related to schema B, from entityInSchemaBRepository, query schema A and fill the attributes in entityInSchemaB that are also in entityInSchemaA (In this case: field1, boolean1 and integer1).

If I wasn't clear on something, or if information is missing, please ask me, I know it's a bit confusing.

Thanks in advance

Body:
I'm developing a Java-Spring application that has 2 modules, with a database schema for each one, and I'm using Hibernate.

Let's say I have one entity in schema named A which looks like this:

@Entity
public class entityInSchemaA {

    private String field1;

    private boolean boolean1;

    private Integer integer1;

    ...Other fields specific to this class...

}

And another entity in schema named B, that shares just some fields with the entity above, and it looks like this:

@Entity
public class entityInSchemaB {

    private String field1;

    private boolean boolean1;

    private Integer integer1;

    ...Other fields specific to this class...

}

I was wondering if there is a conventional/correct/clean way to do something like:

From the application module related to schema B, from entityInSchemaBRepository, query schema A and fill the attributes in entityInSchemaB that are also in entityInSchemaA (In this case: field1, boolean1 and integer1).

If I wasn't clear on something, or if information is missing, please ask me, I know it's a bit confusing.

Thanks in advance


问:
Rewrite a user profile URL
Sorry if my title isn't very clear, I don't know how to word it.
For example I want to rewrite this URL:
https://website.com/profile.php?uid=2 to something like:
https://website.com/user/username

My NGINX config is as follows:

```<code>server {
        listen 80;
        server_name website.com hiddenservice.onion;
        root /var/www/website;

        # Add index.php to the list if you are using PHP
        index index.php;

        add_header Onion-Location http://hiddenservice.onion$request_uri;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;

                # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/run/php/php8.1-fpm.sock;
                # With php-cgi (or other tcp sockets):
        #       fastcgi_pass website.com;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}
</code>```

Title: Rewrite a user profile URL

Body:
Sorry if my title isn't very clear, I don't know how to word it.
For example I want to rewrite this URL:
https://website.com/profile.php?uid=2 to something like:
https://website.com/user/username

My NGINX config is as follows:

server {
        listen 80;
        server_name website.com hiddenservice.onion;
        root /var/www/website;

        # Add index.php to the list if you are using PHP
        index index.php;

        add_header Onion-Location http://hiddenservice.onion$request_uri;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;

                # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/run/php/php8.1-fpm.sock;
                # With php-cgi (or other tcp sockets):
        #       fastcgi_pass website.com;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}