问:
Why can't I capture a MetaInspector::TimeoutError inside an Async block in Ruby 3 with Async 2.3.0 and MetaInspector 5.13.0?
I am using Ruby 3.0.0, MetaInspector 5.13.0, and socketry's Async 2.3.0 to scrape the meta from a list of urls. I set the connection and read timeouts as per the documentation for MetaInspector and test with httpbin's delay endpoint. MetaInspector's documentation notes I should be able to capture a MetaInspector::Timeout error but instead the Async block errors out uncaptured, even if I capture all errors. Here is my test script called timeout_error.rb:

```<code>require 'async'
require 'metainspector'

urls = ["https://httpbin.org/delay/15", "https://www.google.com"]

Async do

  urls.each do |url|

    Async do

      begin
        page = MetaInspector.new(url, connection_timeout: 10, read_timeout: 5, allow_non_html_content: true)
      rescue MetaInspector::TimeoutError
        puts "rescued MetaInspector's TimeoutError"
      rescue => e
        puts "rescued everything else, type: #{e.class}, message: #{e.message}"
      end

      puts "made it to the end of the nested Async block with #{url}"
    end
  end
end
</code>```

Here is my output from the shell:

```<code>meta_collector git:(master) ✗ ruby -v
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin21]
meta_collector git:(master) ✗ ruby bin/timeout_error.rb
made it to the end of the nested Async block with https://www.google.com
.../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `select': execution expired (Timeout::Error)
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `run_once'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:232:in `run'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/kernel/async.rb:32:in `Async'
    from bin/timeout_error.rb:6:in `<main>'
</code>```

I expect to see once the "rescued everything else..." alongside two "made it to the end of the nested.." output, but I never do. Anyone have any insights here?

Body:
I am using Ruby 3.0.0, MetaInspector 5.13.0, and socketry's Async 2.3.0 to scrape the meta from a list of urls. I set the connection and read timeouts as per the documentation for MetaInspector and test with httpbin's delay endpoint. MetaInspector's documentation notes I should be able to capture a MetaInspector::Timeout error but instead the Async block errors out uncaptured, even if I capture all errors. Here is my test script called timeout_error.rb:

require 'async'
require 'metainspector'

urls = ["https://httpbin.org/delay/15", "https://www.google.com"]

Async do

  urls.each do |url|

    Async do

      begin
        page = MetaInspector.new(url, connection_timeout: 10, read_timeout: 5, allow_non_html_content: true)
      rescue MetaInspector::TimeoutError
        puts "rescued MetaInspector's TimeoutError"
      rescue => e
        puts "rescued everything else, type: #{e.class}, message: #{e.message}"
      end

      puts "made it to the end of the nested Async block with #{url}"
    end
  end
end

Here is my output from the shell:

meta_collector git:(master) ✗ ruby -v
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin21]
meta_collector git:(master) ✗ ruby bin/timeout_error.rb
made it to the end of the nested Async block with https://www.google.com
.../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `select': execution expired (Timeout::Error)
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:213:in `run_once'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/async/scheduler.rb:232:in `run'
    from .../.rvm/gems/ruby-3.0.0/gems/async-2.3.0/lib/kernel/async.rb:32:in `Async'
    from bin/timeout_error.rb:6:in `'

I expect to see once the "rescued everything else..." alongside two "made it to the end of the nested.." output, but I never do. Anyone have any insights here?


来源: stackexchange

问:
Obtaining a value from an attribute without quotation marks with lxml and XPATH
I'm working with XML docs that have structures similar to the following:

```<code><root>

<tok lemma="A" xpos="AQ0MS00">sobredit</tok>
<tok lemma="B" xpos="Fc"> this </tok>
<tok lemma="something" xpos="AQ0MS00">something</tok>
<tok lemma="X" xpos="Fc"> that </tok>
<tok>del
  <dtok form="de" lemma="de" xpos="SPC00"/>
  <dtok form="el" lemma="el" xpos="DA0MS0"/>
</tok>
<tok lemma="sobredit" xpos="AQ0MS00">sobredit </tok>
<tok lemma="X" xpos="Fc"> sometinelse </tok>

</root>
</code>```

I use the following code (Python and LXML) to get the values of the attribute 'lemma' whenever a 'tok' element has value starting with 'AQ' for the attribute 'xpos'.

```<code>   for el in root_element.xpath('//tok[starts-with(@xpos, "AQ")]')

        if el.xpath('preceding::tok[1]/dtok'):

            prec_lem = el.xpath('preceding::tok[1]/dtok[last()]/@lemma')

        elif el.xpath('preceding::tok[1]'):

            prec_lem = el.xpath('preceding::tok[1]')[0].get('lemma')

        else:

            prec_lem = 'None'
</code>```

With the valuable help of stackoverflow contributor Martin Honnen I managed to get through some problems but now I'm stuck with the following silly problem. When the first condition is met, what I get as a value is an element of a list which appears as ['DA0MS0'], whereas what I get when the second condition is met is just the string for value. I could get rid of the quotation marks using regex or in some other inelegant, brute force way but I would prefer to do this right.

If I do:

```<code>prec_lem = el.xpath('preceding::tok[1]/dtok[last()]).get('lemma')
</code>```

I get the error message: AttributeError: 'list' object has no attribute 'get'

I understand what the error message tells me but I don't understand why I'm getting a list element from one XPATH statement but not from the other. The internal structure of the  elements and that of the  elements is very similar. Why cannot I get the attribute values of these two elements in the same way?

After a lot of searches and consultation of the XPATH documentation I give up. I've seen mentions of string(), text() and I've tried those but nothing seems to work. I'm very new to this and there is obviously something very basic about XPATH I'm not understanding.

How does one get the value of the attribute without the quotation marks?

ContentLicense: CC BY-SA 4.0

Body:
I'm working with XML docs that have structures similar to the following:

<root>

<tok lemma="A" xpos="AQ0MS00">sobredit</tok>
<tok lemma="B" xpos="Fc"> this </tok>
<tok lemma="something" xpos="AQ0MS00">something</tok>
<tok lemma="X" xpos="Fc"> that </tok>
<tok>del
  <dtok form="de" lemma="de" xpos="SPC00"/>
  <dtok form="el" lemma="el" xpos="DA0MS0"/>
</tok>
<tok lemma="sobredit" xpos="AQ0MS00">sobredit </tok>
<tok lemma="X" xpos="Fc"> sometinelse </tok>

</root>

I use the following code (Python and LXML) to get the values of the attribute 'lemma' whenever a 'tok' element has value starting with 'AQ' for the attribute 'xpos'.

   for el in root_element.xpath('//tok[starts-with(@xpos, "AQ")]')

        if el.xpath('preceding::tok[1]/dtok'):

            prec_lem = el.xpath('preceding::tok[1]/dtok[last()]/@lemma')

        elif el.xpath('preceding::tok[1]'):

            prec_lem = el.xpath('preceding::tok[1]')[0].get('lemma')

        else:

            prec_lem = 'None'

With the valuable help of stackoverflow contributor Martin Honnen I managed to get through some problems but now I'm stuck with the following silly problem. When the first condition is met, what I get as a value is an element of a list which appears as ['DA0MS0'], whereas what I get when the second condition is met is just the string for value. I could get rid of the quotation marks using regex or in some other inelegant, brute force way but I would prefer to do this right.

If I do:

prec_lem = el.xpath('preceding::tok[1]/dtok[last()]).get('lemma')

I get the error message: AttributeError: 'list' object has no attribute 'get'

I understand what the error message tells me but I don't understand why I'm getting a list element from one XPATH statement but not from the other. The internal structure of the  elements and that of the  elements is very similar. Why cannot I get the attribute values of these two elements in the same way?

After a lot of searches and consultation of the XPATH documentation I give up. I've seen mentions of string(), text() and I've tried those but nothing seems to work. I'm very new to this and there is obviously something very basic about XPATH I'm not understanding.

How does one get the value of the attribute without the quotation marks?


问:
Same CIGaussianBlur effect archives two highly different results depending on the background
I am trying to achieve a the same gaussian blur as Photoshop does but it's seems the CIFilter in Core Image is very biased on the background of the image. I am not talking about the blurred edges, please look closer at the blue intensity between white and dark background of the CIFilter blurred version and Photoshop.

Input images:

Core Image result:

Photoshop result:

You can clearly see CIGaussianBlur outputs a very different image.

This is the code used to generate the images on iOS:

let imageURL = Bundle.main.url(forResource: "1", withExtension: "png")!
let ciImage = CIImage(contentsOf: imageURL)!
let extent = CGRect(origin: .zero, size: ciImage.extent.size)
let blurredImage = CIFilter.gaussianBlur()
blurredImage.radius = 64
blurredImage.inputImage = ciImage

let outputURL = try! FileService.shared.getNewFileURL(type: "jpeg")
let context = CIContext()
try! context.writeJPEGRepresentation(of: blurredImage.outputImage!.cropped(to: extent), to: outputURL, colorSpace: colorSpace)
```


问:
Nest, serverless: ENOENT: no such file or directory, open
My project has above project structure

```<code>   src
     ---- Clone(empty folder)
     ---- app.module.ts
     ---- app.service.ts
</code>```

serverless

```<code>  functions:
    main:
      timeout: 60
      handler: src/main.handler
      events:
      - schedule: cron(40 22 ? * MON *)
</code>```

service trigger s3 bucket at the scheduler time and a data CSV file should be pushed to GitHub. When GitHub clones, it always clones into the src/clone folder. when running locally serverless it works properly but when deploying the "No such file or directory" an error comes. I can't see the clone folder after unzipping the sls package zip file. any one can help me solve this problem

Body:
My project has above project structure

   src
     ---- Clone(empty folder)
     ---- app.module.ts
     ---- app.service.ts

serverless

  functions:
    main:
      timeout: 60
      handler: src/main.handler
      events:
      - schedule: cron(40 22 ? * MON *)

service trigger s3 bucket at the scheduler time and a data CSV file should be pushed to GitHub. When GitHub clones, it always clones into the src/clone folder. when running locally serverless it works properly but when deploying the "No such file or directory" an error comes. I can't see the clone folder after unzipping the sls package zip file. any one can help me solve this problem


问:
Setting starting DOM in TinyMCE
When I run init() and create an tinymce instance, I want to have some wrapping divs for styling purposes.

For example, imagine this is the initial DOM inside TinyMCE's iframe when the page starts up:

```<code><html>
<body>
  <div class="myWrapper">
    <div class="myWrapperContainer">

--> User input area <--

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

Then when I get the user input content:

```<code>var userContent = tinymce.get("myTextarea").getContent();
</code>```

I don't want the wrapper divs to be included in userContent. I just want the HTML inside the wrapper divs

How should I go about this?

Title: Setting starting DOM in TinyMCE

Body:
When I run init() and create an tinymce instance, I want to have some wrapping divs for styling purposes.

For example, imagine this is the initial DOM inside TinyMCE's iframe when the page starts up:

--> User input area <--

Then when I get the user input content:

var userContent = tinymce.get("myTextarea").getContent();

I don't want the wrapper divs to be included in userContent. I just want the HTML inside the wrapper divs

How should I go about this?


问:
Property 'canActivate' in type 'AuthorizationGuard' is not assignable to the same property in base type 'CanActivate'
I upgraded my Angular application to Angular 14 and when I tried to run "ng build," I came across this error:

"Property 'canActivate' in type 'AuthorizationGuard' is not assignable to the same property in base type 'CanActivate'."

This is the function:

```<code>  public canActivate(): Observable<boolean> {
    return new Observable<boolean>(obs => {
      combineLatest([this.appService.getAppsForUserByRoleObservable(),
        this.userservice.getUserInfoObservable(), this.contentService.getContentObservable()]).subscribe(context => {
        const userAppIds = context[0].map(entry => entry.apps.map(app => app.appId))
        .reduce((acc, val) => acc.concat(val), []);
        if (userAppIds.length > 0 && (userAppIds.indexOf(this.appInfoService.getAppInfo().appId) > -1)) {
          this.helpService.getHelpMenuLinks();
          obs.next(true);
        } else {
          this.auditService.registerEvent(AuditEventEnum.AUDIT_EVENT_002);
          obs.next(false);
        }
      }, () => {
        this.auditService.registerEvent(AuditEventEnum.AUDIT_EVENT_002);
        obs.next(false);
      });
    });

  }
</code>```

I found a similar SO question here: TS2416: Property 'canActivate' in type 'MyGuard' is not assignable to the same property in base type 'CanActivate'

But according that person, removing "the return type (Observable | Promise | boolean ) from canActivate" made the problem go away, but I tried doing the same thing (removing Observable) and it did not work.
Images:
the function
the error in terminal

Body:
I upgraded my Angular application to Angular 14 and when I tried to run "ng build," I came across this error:

"Property 'canActivate' in type 'AuthorizationGuard' is not assignable to the same property in base type 'CanActivate'."

This is the function:

  public canActivate(): Observable<boolean> {
    return new Observable<boolean>(obs => {
      combineLatest([this.appService.getAppsForUserByRoleObservable(),
        this.userservice.getUserInfoObservable(), this.contentService.getContentObservable()]).subscribe(context => {
        const userAppIds = context[0].map(entry => entry.apps.map(app => app.appId))
        .reduce((acc, val) => acc.concat(val), []);
        if (userAppIds.length > 0 && (userAppIds.indexOf(this.appInfoService.getAppInfo().appId) > -1)) {
          this.helpService.getHelpMenuLinks();
          obs.next(true);
        } else {
          this.auditService.registerEvent(AuditEventEnum.AUDIT_EVENT_002);
          obs.next(false);
        }
      }, () => {
        this.auditService.registerEvent(AuditEventEnum.AUDIT_EVENT_002);
        obs.next(false);
      });
    });

  }

I found a similar SO question here: TS2416: Property 'canActivate' in type 'MyGuard' is not assignable to the same property in base type 'CanActivate'

But according that person, removing "the return type (Observable | Promise | boolean ) from canActivate" made the problem go away, but I tried doing the same thing (removing Observable) and it did not work.
Images:
the function
the error in terminal


问:
How to filter an HTTP request with the get method?
My request returns a json with more than 700k lines, like

```<code>{
   id: 1,
   nr: 77,
   project_name: batata,
   ...
  }
  {
   id: 2,
   nr: 435
  ...
  }
</code>```

This is taking a long time and I only need the project_name values

How can i filter it so it only returns the project_names ?

Body:
My request returns a json with more than 700k lines, like

{
   id: 1,
   nr: 77,
   project_name: batata,
   ...
  }
  {
   id: 2,
   nr: 435
  ...
  }

This is taking a long time and I only need the project_name values

How can i filter it so it only returns the project_names ?


问:
Non-blocking Python window only displaying a constantly updating image
I want to develop an application that uses multiple threads to read user input from the keyboard and translate that to an image on the screen, very quickly so that it can be updated quickly enough itll look like a smooth animation.  The image generation will sometimes include algorithmic further processing so i need the program to update the image on the screen while at the same time retrieving input from the terminal.

All I need is a window with an image that updates itself based on user input and algorithms while the user is using the command line spawning other windows like a video playback window(opencv) while running image processing routines and database access in the background.

inputThread
imageGeneratorThread

while Running:
    if inputThread.inputEntered:
       userInput = inputThread.getUserInput()
       img = generateImage(userInput)
       imageGeneratorThread.updateImage(img)
```

I need this loop running continuously while the worker threads gather input and output results from it.  There'll be any number of windows and associated threads running, turned on and off from the command line, with its own keyboard listener thread running.

Thank you for reading

I Tried:

I used pynput for the keyboard thread and it works great, its always on collecting keystrokes even if another window has focus.

Initially I tried pygame for the keyboard and graphic animations which should've worked great, but updating the screens with the keystrokes was too slow to be usuable, not sure why my other pygame project was great but I think the font subsystem on it is to blame.

The pillow library was my next goto, but its just not good for smooth animations, best I could get was another window every frame, not good enough

Then I tried the opencv imshow function which is great for displaying video files and rapidly updating images, but hangs miserably when its waiting for an input so I keep getting window not responding when the image ceases to change

Im starting to see that windows on Python needs to be on the main thread and blocking.  Is there another GUI API thats thread safe and fast?  Is there some lower level python library I can use in its own thread?

Body:
I want to develop an application that uses multiple threads to read user input from the keyboard and translate that to an image on the screen, very quickly so that it can be updated quickly enough itll look like a smooth animation.  The image generation will sometimes include algorithmic further processing so i need the program to update the image on the screen while at the same time retrieving input from the terminal.

All I need is a window with an image that updates itself based on user input and algorithms while the user is using the command line spawning other windows like a video playback window(opencv) while running image processing routines and database access in the background.

inputThread
imageGeneratorThread

while Running:
    if inputThread.inputEntered:
       userInput = inputThread.getUserInput()
       img = generateImage(userInput)
       imageGeneratorThread.updateImage(img)

I need this loop running continuously while the worker threads gather input and output results from it.  There'll be any number of windows and associated threads running, turned on and off from the command line, with its own keyboard listener thread running.

Thank you for reading

I Tried:

I used pynput for the keyboard thread and it works great, its always on collecting keystrokes even if another window has focus.

Initially I tried pygame for the keyboard and graphic animations which should've worked great, but updating the screens with the keystrokes was too slow to be usuable, not sure why my other pygame project was great but I think the font subsystem on it is to blame.

The pillow library was my next goto, but its just not good for smooth animations, best I could get was another window every frame, not good enough

Then I tried the opencv imshow function which is great for displaying video files and rapidly updating images, but hangs miserably when its waiting for an input so I keep getting window not responding when the image ceases to change

Im starting to see that windows on Python needs to be on the main thread and blocking.  Is there another GUI API thats thread safe and fast?  Is there some lower level python library I can use in its own thread?


问:
Archiving zip files from Jenkins Pipeline
I have a Jenkins pipeline which runs a bunch of postman collections using newman.

newman run \"collections/${npm_config_collection}.postman_collection.json\" --color off -e \"environments/TEST.postman_environment.json\" --reporters cli,junitfull,htmlextra --reporter-junitfull-export newman/${npm_config_collection}.xml --env-var access_token=$TOKENSERVICE
```
<p>Since this produces a lot of html files (because of the htmlextra reporter) that cannot be viewed by clicking the links in artifacts, because of som Jenkins settings. To ease this, I added a post action which zips all the html (as well as the junit xml) files generated, to enable easier download, and proper viewing. BUT. Jenkins apparently shows all the html files, which is not what I want.<br />
Can I add something to <code>archiveArtifacts</code> to avoid Jenkins expanding the zip file?<br />
<img src="https://i.stack.imgur.com/8k0TO.png" alt="links on main job page" />
<img src="https://i.stack.imgur.com/nufBu.png" alt="clicked on Last Successful Artifacts" /></p>
```post {
        always {
            echo ' * *  Publishing JUnit results'
            junit testResults: 'newman/*.xml', skipPublishingChecks: true, allowEmptyResults: true
            echo ' * *  Zipping HTMLExtra results'
            script {
                sh script: " zip newman/\$(date +'%Y-%m-%d_%H-%M-%S')_htmlreports.zip newman/*.html"
                sh script: " zip newman/\$(date +'%Y-%m-%d_%H-%M-%S')_junitreports.zip newman/*.xml"
            }
            echo ' * *  Publishing results as Zip file(s)'
            archiveArtifacts artifacts: 'newman/*.zip', allowEmptyArchive: true
        }
    }
```

Body:
I have a Jenkins pipeline which runs a bunch of postman collections using newman.

newman run \"collections/${npm_config_collection}.postman_collection.json\" --color off -e \"environments/TEST.postman_environment.json\" --reporters cli,junitfull,htmlextra --reporter-junitfull-export newman/${npm_config_collection}.xml --env-var access_token=$TOKENSERVICE

Since this produces a lot of html files (because of the htmlextra reporter) that cannot be viewed by clicking the links in artifacts, because of som Jenkins settings. To ease this, I added a post action which zips all the html (as well as the junit xml) files generated, to enable easier download, and proper viewing. BUT. Jenkins apparently shows all the html files, which is not what I want.

Can I add something to archiveArtifacts to avoid Jenkins expanding the zip file?

post {
        always {
            echo ' * *  Publishing JUnit results'
            junit testResults: 'newman/*.xml', skipPublishingChecks: true, allowEmptyResults: true
            echo ' * *  Zipping HTMLExtra results'
            script {
                sh script: " zip newman/\$(date +'%Y-%m-%d_%H-%M-%S')_htmlreports.zip newman/*.html"
                sh script: " zip newman/\$(date +'%Y-%m-%d_%H-%M-%S')_junitreports.zip newman/*.xml"
            }
            echo ' * *  Publishing results as Zip file(s)'
            archiveArtifacts artifacts: 'newman/*.zip', allowEmptyArchive: true
        }
    }


问:
Error connecting to the database (MongoDB)
I have cloned a website from github and I am trying to connect my database (MongoDB) with website but its giving an error

My database file:
db.js

```<code>
const mongoose = require("mongoose");
try {
  mongoose.connect("mongodb+srv://AhmedHassan:Knight007@cluster0.ofzz68w.mongodb.net/TestDB?retryWrites=true&w=majority", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  });
  console.log("Database Connected Successfully");
} catch (err) {
  console.log("Database Not Connected");
}
</code>```

My app file:
app.js

```<code>const express = require("express");
const app = express();
require("dotenv").config();
const mongoose = require("mongoose");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const cors = require("cors");

// Import Router
const authRouter = require("./routes/auth");
const categoryRouter = require("./routes/categories");
const productRouter = require("./routes/products");
const brainTreeRouter = require("./routes/braintree");
const orderRouter = require("./routes/orders");
const usersRouter = require("./routes/users");
const customizeRouter = require("./routes/customize");
// Import Auth middleware for check user login or not~
const { loginCheck } = require("./middleware/auth");
const CreateAllFolder = require("./config/uploadFolderCreateScript");

/* Create All Uploads Folder if not exists | For Uploading Images */
CreateAllFolder();

// Database Connection
mongoose
  .connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() =>
    console.log(
      "==============Mongodb Database Connected Successfully=============="
    )
  )
  .catch((err) => console.log("Database Not Connected !!!"));

// Middleware
app.use(morgan("dev"));
app.use(cookieParser());
app.use(cors());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Routes
app.use("/api", authRouter);
app.use("/api/user", usersRouter);
app.use("/api/category", categoryRouter);
app.use("/api/product", productRouter);
app.use("/api", brainTreeRouter);
app.use("/api/order", orderRouter);
app.use("/api/customize", customizeRouter);

// Run Server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log("Server is running on ", PORT);
});
</code>```

Here are pictures:

01_ After Running the server from terminal i.e, "npm run start:dev"
When Server Starts

02_ After Registering a user from front-end:
After registering a user i.e sending data to Database

Body:
I have cloned a website from github and I am trying to connect my database (MongoDB) with website but its giving an error

My database file:
db.js

const mongoose = require("mongoose");
try {
  mongoose.connect("mongodb+srv://AhmedHassan:Knight007@cluster0.ofzz68w.mongodb.net/TestDB?retryWrites=true&w=majority", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  });
  console.log("Database Connected Successfully");
} catch (err) {
  console.log("Database Not Connected");
}

My app file:
app.js

const express = require("express");
const app = express();
require("dotenv").config();
const mongoose = require("mongoose");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const cors = require("cors");

// Import Router
const authRouter = require("./routes/auth");
const categoryRouter = require("./routes/categories");
const productRouter = require("./routes/products");
const brainTreeRouter = require("./routes/braintree");
const orderRouter = require("./routes/orders");
const usersRouter = require("./routes/users");
const customizeRouter = require("./routes/customize");
// Import Auth middleware for check user login or not~
const { loginCheck } = require("./middleware/auth");
const CreateAllFolder = require("./config/uploadFolderCreateScript");

/* Create All Uploads Folder if not exists | For Uploading Images */
CreateAllFolder();

// Database Connection
mongoose
  .connect(process.env.DATABASE, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() =>
    console.log(
      "==============Mongodb Database Connected Successfully=============="
    )
  )
  .catch((err) => console.log("Database Not Connected !!!"));

// Middleware
app.use(morgan("dev"));
app.use(cookieParser());
app.use(cors());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Routes
app.use("/api", authRouter);
app.use("/api/user", usersRouter);
app.use("/api/category", categoryRouter);
app.use("/api/product", productRouter);
app.use("/api", brainTreeRouter);
app.use("/api/order", orderRouter);
app.use("/api/customize", customizeRouter);

// Run Server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log("Server is running on ", PORT);
});

Here are pictures:

01_ After Running the server from terminal i.e, "npm run start:dev"
When Server Starts

02_ After Registering a user from front-end:
After registering a user i.e sending data to Database


问:
How do I update .env variables in the middle of a program?
I'm running a script that is grabbing data from a .env file. I am trying to update the .env variable in the middle of the script and then use that new value. It's an encryption script, so I need to have the .env value to decrypt, update the value, and then use the new value to encrypt it again. What's happening instead is it is decrypting, reencrypting, and then updating. It seems like that's just how .env files work, but I was hoping there was a way to make the variable update mid-script. Here's the code that I'm running:</p>
```<code>def changeSecret(slices, envvars, num):
    key = sign(slices) #function I wrote decrypting several slices of data and putting them together
    dotenv_file = dotenv.find_dotenv()
    dotenv.load_dotenv(dotenv_file)
    dotenv.set_key(dotenv_file, 'secret', str(num)) #this ends up updating the .env variable only when the program finishes
    slices = encrypt(key) #the 'encrypt' function uses os.getenv('secret'), so I want it to have updated already
    updateenv(slices, envvars) #this updates other variables.
</code>```

Body:
I'm running a script that is grabbing data from a .env file. I am trying to update the .env variable in the middle of the script and then use that new value. It's an encryption script, so I need to have the .env value to decrypt, update the value, and then use the new value to encrypt it again. What's happening instead is it is decrypting, reencrypting, and then updating. It seems like that's just how .env files work, but I was hoping there was a way to make the variable update mid-script. Here's the code that I'm running:

def changeSecret(slices, envvars, num):
    key = sign(slices) #function I wrote decrypting several slices of data and putting them together
    dotenv_file = dotenv.find_dotenv()
    dotenv.load_dotenv(dotenv_file)
    dotenv.set_key(dotenv_file, 'secret', str(num)) #this ends up updating the .env variable only when the program finishes
    slices = encrypt(key) #the 'encrypt' function uses os.getenv('secret'), so I want it to have updated already
    updateenv(slices, envvars) #this updates other variables.


问:
Run selenium webdriver over adb
I'm just getting started with the Selenium Python bindings and can successfully perform basic functionality using my computer's browser.  I'd now like to use the Chrome browser on an Android phone which I'm connected to via adb.

I've looked online and have seen references to remote web drivers and Selenium grid.  However, I don't know if this is what I need or, if so, what is needed to set this up.

Is there some web driver equivalent of gdb-server?

Title: Run selenium webdriver over adb


问:
Thing Connects fine to AWS IoT Core but does not when using AWS Device Advisor
I have a custom device running FreeRTOS and Mbed-TLS. The device connects fine to the production IoT core endpoint and I can pub/sub to my hearts content; however, when I try to connect to the endpoint provided by the device advisor with a MQTT Connect testcase, it wont complete the TLS handshake. The log has two entries in it, the client hello and then a close-notify alert from the server. I tried using a little C# test application I wrote to connect to the same end point and that seems to work. I use the same method for both, the only difference is the device. I did decode the client hello my device is sending and I do not see anything obviously wrong.

At the point of pulling my hair out, any tips?

`

```<code>TLS Record Sender CLIENT ContentType HANDSHAKE Length 149 Timestamp 2022-12-19T18:08:58Z
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 16 03 03 00 90 01 00 00 8c 03 03 76 9d 1d 5a 67 |...........v..Zg|
|00000010| e2 db 3f 45 13 41 2d 7e 28 77 00 87 e6 35 0e 32 |..?E.A-~(w...5.2|
|00000020| c2 24 bd 23 ee 69 72 77 f3 e1 69 00 00 04 c0 2b |.$.#.irw..i....+|
|00000030| 00 ff 01 00 00 5f 00 00 00 3d 00 3b 00 00 38 74 |....._...=.;..8t|
|00000040| 33 6e 78 35 69 7a 39 76 37 73 69 6a 73 2e 64 65 |3nx5iz9v7sijs.de|
|00000050| 76 69 63 65 61 64 76 69 73 6f 72 2e 69 6f 74 2e |viceadvisor.iot.|
|00000060| 75 73 2d 65 61 73 74 2d 31 2e 61 6d 61 7a 6f 6e |us-east-1.amazon|
|00000070| 61 77 73 2e 63 6f 6d 00 0d 00 06 00 04 04 03 04 |aws.com.........|
|00000080| 01 00 0a 00 0a 00 08 00 1d 00 17 00 18 00 19 00 |................|
|00000090| 0b 00 02 01 00                                  |.....           |
+--------+-------------------------------------------------+----------------+
</code>```

`

`

```<code>TLS Record Sender SERVER ContentType ALERT Length 7 Timestamp 2022-12-19T18:08:58Z
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 15 03 03 00 02 01 00                            |.......         |
+--------+-------------------------------------------------+----------------+
</code>```

`

`

```<code>16 03 03 00 a4
Record Header
    16 - type is 0x16 (handshake record)
    03 03 - protocol version is 3.3 (also known as TLS 1.2)
    00 90 - 0x90 bytes of handshake message follows

01 00 00 a0
    01 - handshake message type 0x01 (client hello)
    00 00 8c - 0x8c  bytes of client hello follows
03 03
    The protocol version of "3,3" (meaning TLS 1.2) is given.

80 e3 df 37 83 02 08 84 9d b0 6f e8 86 e9 e0 12 5e 77 f9 97 c6 af 62 cf 43 c6 40 63 c0 77 3a 82
    The client provides 32 bytes of random data.

00
    Session id
    00 - length of zero (no session id is provided)

00 04
    Cipher Suites - 4 bytes of cipher suits follow
    c0 2b
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
    00 ff
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV

01 00
    01 - 0x1 (1) bytes of compression methods follows
    00 - assigned value for no compression

00 73
    00 73 - the extensions will take 0x73 (115) bytes of data

00 00
    Server Name Extension
    00 47
        71 Bytes Follow
    00 45
        69 Bytes of list entry
    00
        List entry type is 0x00 "DNS Hostname"
    00 42
        66 Bytes of host name follow
    74 34 31 31 62 39 36 32 35 37 74 33 6e 78 35 69 7a 39 76 37 73 69 6a 73 2e 64 65 76 69 63 6561 64 76 69 73 6f 72 2e 69 6f 74 2e 75 73 2d 65 61 73 74 2d 31 2e 61 6d 61 7a 6f 6e 61 77 73 2e 63 6f 6d
        Hostname - "t411b96257t3nx5iz9v7sijs.deviceadvisor.iot.us-east-1.amazonaws.com"

00 0d
    Signature Algorithms
    00 06
        6 Bytes follow
    00 04
        4 Bytes follow
    04 03
        ECDSA/SECP256r1/SHA256
    04 01
        RSA/PKCS1/SHA256

00 0a
    Supported Groups
    00 0a
        10 bytes of "supported groups" extension data follows
    00 08
        8 Bytes of data are in the curves list
    00 1d
        x25519
    00 17
        secp256r1
    00 18
        secp384r1
    00 19
        secp521r1

00 0b
    EC Point Formats
    00 02
        2 bytes of EC points format data follows
    01
        1 bytes of data are in the list
    00
        Assigned value for uncompressed formo

</code>```

`

I have tried adding the ALPN and trying both ports 8883 and 443 - No Change

I have tried a different test application which seems to work but there is nothing in the log the point as to what the difference between my device and the test device

My device connects fine to the normal endpoint and functions as expected

I would expect the device to connect to the Device Advisor endpoint.

Body:
I have a custom device running FreeRTOS and Mbed-TLS. The device connects fine to the production IoT core endpoint and I can pub/sub to my hearts content; however, when I try to connect to the endpoint provided by the device advisor with a MQTT Connect testcase, it wont complete the TLS handshake. The log has two entries in it, the client hello and then a close-notify alert from the server. I tried using a little C# test application I wrote to connect to the same end point and that seems to work. I use the same method for both, the only difference is the device. I did decode the client hello my device is sending and I do not see anything obviously wrong.

At the point of pulling my hair out, any tips?

`

TLS Record Sender CLIENT ContentType HANDSHAKE Length 149 Timestamp 2022-12-19T18:08:58Z
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 16 03 03 00 90 01 00 00 8c 03 03 76 9d 1d 5a 67 |...........v..Zg|
|00000010| e2 db 3f 45 13 41 2d 7e 28 77 00 87 e6 35 0e 32 |..?E.A-~(w...5.2|
|00000020| c2 24 bd 23 ee 69 72 77 f3 e1 69 00 00 04 c0 2b |.$.#.irw..i....+|
|00000030| 00 ff 01 00 00 5f 00 00 00 3d 00 3b 00 00 38 74 |....._...=.;..8t|
|00000040| 33 6e 78 35 69 7a 39 76 37 73 69 6a 73 2e 64 65 |3nx5iz9v7sijs.de|
|00000050| 76 69 63 65 61 64 76 69 73 6f 72 2e 69 6f 74 2e |viceadvisor.iot.|
|00000060| 75 73 2d 65 61 73 74 2d 31 2e 61 6d 61 7a 6f 6e |us-east-1.amazon|
|00000070| 61 77 73 2e 63 6f 6d 00 0d 00 06 00 04 04 03 04 |aws.com.........|
|00000080| 01 00 0a 00 0a 00 08 00 1d 00 17 00 18 00 19 00 |................|
|00000090| 0b 00 02 01 00                                  |.....           |
+--------+-------------------------------------------------+----------------+

`

`

TLS Record Sender SERVER ContentType ALERT Length 7 Timestamp 2022-12-19T18:08:58Z
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 15 03 03 00 02 01 00                            |.......         |
+--------+-------------------------------------------------+----------------+

`

`

16 03 03 00 a4
Record Header
    16 - type is 0x16 (handshake record)
    03 03 - protocol version is 3.3 (also known as TLS 1.2)
    00 90 - 0x90 bytes of handshake message follows

01 00 00 a0
    01 - handshake message type 0x01 (client hello)
    00 00 8c - 0x8c  bytes of client hello follows
03 03
    The protocol version of "3,3" (meaning TLS 1.2) is given.

80 e3 df 37 83 02 08 84 9d b0 6f e8 86 e9 e0 12 5e 77 f9 97 c6 af 62 cf 43 c6 40 63 c0 77 3a 82
    The client provides 32 bytes of random data.

00
    Session id
    00 - length of zero (no session id is provided)

00 04
    Cipher Suites - 4 bytes of cipher suits follow
    c0 2b
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
    00 ff
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV

01 00
    01 - 0x1 (1) bytes of compression methods follows
    00 - assigned value for no compression

00 73
    00 73 - the extensions will take 0x73 (115) bytes of data

00 00
    Server Name Extension
    00 47
        71 Bytes Follow
    00 45
        69 Bytes of list entry
    00
        List entry type is 0x00 "DNS Hostname"
    00 42
        66 Bytes of host name follow
    74 34 31 31 62 39 36 32 35 37 74 33 6e 78 35 69 7a 39 76 37 73 69 6a 73 2e 64 65 76 69 63 6561 64 76 69 73 6f 72 2e 69 6f 74 2e 75 73 2d 65 61 73 74 2d 31 2e 61 6d 61 7a 6f 6e 61 77 73 2e 63 6f 6d
        Hostname - "t411b96257t3nx5iz9v7sijs.deviceadvisor.iot.us-east-1.amazonaws.com"

00 0d
    Signature Algorithms
    00 06
        6 Bytes follow
    00 04
        4 Bytes follow
    04 03
        ECDSA/SECP256r1/SHA256
    04 01
        RSA/PKCS1/SHA256

00 0a
    Supported Groups
    00 0a
        10 bytes of "supported groups" extension data follows
    00 08
        8 Bytes of data are in the curves list
    00 1d
        x25519
    00 17
        secp256r1
    00 18
        secp384r1
    00 19
        secp521r1

00 0b
    EC Point Formats
    00 02
        2 bytes of EC points format data follows
    01
        1 bytes of data are in the list
    00
        Assigned value for uncompressed formo

`

I have tried adding the ALPN and trying both ports 8883 and 443 - No Change

I have tried a different test application which seems to work but there is nothing in the log the point as to what the difference between my device and the test device

My device connects fine to the normal endpoint and functions as expected

I would expect the device to connect to the Device Advisor endpoint.


问:
Terraform Unexpected EOF
I'm getting Unexpected EOF on Terraform Apply even when there is nothing wrong with code.
I tested the same Code on my Personal Laptop and it works Perfectly fine , while on my Work Laptop it fails with Above error on any random resource creation on GCP

Terraform version :

```<code>Terraform v1.0.2
on windows_amd64
+ provider registry.terraform.io/hashicorp/google v4.46.0
</code>```

I have same version on both laptops , not sure what is causing this error. Only other thing differ in my work laptop is I have to set Custom Certs for gcloud config due to security concerns .
I have set those with below command

```<code> gcloud config set core/custom_ca_certs_file
</code>```

update :

Error in Terraform :

```<code>    google_compute_health_check.autohealing[0]: Creating...
google_compute_health_check.autohealing[0]: Still creating... [10s elapsed]
google_compute_health_check.autohealing[0]: Creation complete after 11s [id=projects/terraform-101-370721/global/healthChecks/auto-health-check]
╷
│ Error: Error creating ResourcePolicy: unexpected EOF
│
│   with google_compute_resource_policy.daily_backup,
│   on instance_group.tf line 74, in resource "google_compute_resource_policy" "daily_backup":
│   74: resource "google_compute_resource_policy" "daily_backup" {
│
╵
╷
│ Error: Error creating Network: unexpected EOF
│
│   with google_compute_network.network[0],
│   on network.tf line 3, in resource "google_compute_network" "network":
│    3: resource "google_compute_network" "network" {
│
╵
</code>```

Note :
Code block :

```<code>resource "google_compute_resource_policy" "daily_backup" {
  name   = "every-day-4am"
  region = local.reg
  snapshot_schedule_policy {
    schedule {
      daily_schedule {
        days_in_cycle = 1
        start_time    = "04:00"
      }
    }
  }
}

resource "google_compute_network" "network" {
  count =  var.flip.set_ntw == true ? 1 : 0
  name                    = var.ntw.name
  auto_create_subnetworks = var.ntw.auto_create_sub
  mtu                     = var.ntw.ntw_mtu
}
</code>```

Even the error is on different resource every time I freshly run apply.

Also, same code won't give any EOF on my Personal PC

Title: Terraform Unexpected EOF

Body:
I'm getting Unexpected EOF on Terraform Apply even when there is nothing wrong with code.
I tested the same Code on my Personal Laptop and it works Perfectly fine , while on my Work Laptop it fails with Above error on any random resource creation on GCP

Terraform version :

Terraform v1.0.2
on windows_amd64
+ provider registry.terraform.io/hashicorp/google v4.46.0

I have same version on both laptops , not sure what is causing this error. Only other thing differ in my work laptop is I have to set Custom Certs for gcloud config due to security concerns .
I have set those with below command

 gcloud config set core/custom_ca_certs_file

update :

Error in Terraform :

    google_compute_health_check.autohealing[0]: Creating...
google_compute_health_check.autohealing[0]: Still creating... [10s elapsed]
google_compute_health_check.autohealing[0]: Creation complete after 11s [id=projects/terraform-101-370721/global/healthChecks/auto-health-check]
╷
│ Error: Error creating ResourcePolicy: unexpected EOF
│
│   with google_compute_resource_policy.daily_backup,
│   on instance_group.tf line 74, in resource "google_compute_resource_policy" "daily_backup":
│   74: resource "google_compute_resource_policy" "daily_backup" {
│
╵
╷
│ Error: Error creating Network: unexpected EOF
│
│   with google_compute_network.network[0],
│   on network.tf line 3, in resource "google_compute_network" "network":
│    3: resource "google_compute_network" "network" {
│
╵

Note :
Code block :

resource "google_compute_resource_policy" "daily_backup" {
  name   = "every-day-4am"
  region = local.reg
  snapshot_schedule_policy {
    schedule {
      daily_schedule {
        days_in_cycle = 1
        start_time    = "04:00"
      }
    }
  }
}

resource "google_compute_network" "network" {
  count =  var.flip.set_ntw == true ? 1 : 0
  name                    = var.ntw.name
  auto_create_subnetworks = var.ntw.auto_create_sub
  mtu                     = var.ntw.ntw_mtu
}

Even the error is on different resource every time I freshly run apply.

Also, same code won't give any EOF on my Personal PC


问:
How to join two arrays in Snaplogic, using map()?
I have the following JSON:

```<code>[
    {
        "First Name": "John",
        "Last Name": "Smith",
        "State": "California",
        "Course1": "HTML",
        "Course2": "JavaScript",
        "start_date": [
            "2018-09-01",
            "2019-06-01"
        ],
        "end_date": [
            "2019-09-01",
            "2020-09-01"
        ]
    }
]
</code>```

And I need to join the "end_date" together with "start_date" as follows(tried concat, spread operator etc, but I do get the desired output, and since I am new to this, I need help in how to build the expression). I am thinking of the map(), but not sure how to apply it correctly:

```<code>[
    {
        "First Name": "John",
        "Last Name": "Smith",
        "State": "California",
        "Course1": "HTML",
        "Course2": "JavaScript",
        "RootArray": [
        {
           "start_date": "2018-09-01",
           "end_date": "2019-06-01"

        },
       {
          "start_date": "2018-05-03",
           "end_date": "2018-08-07"

        }
    }
                    ]
]
</code>```

Body:
I have the following JSON:

[
    {
        "First Name": "John",
        "Last Name": "Smith",
        "State": "California",
        "Course1": "HTML",
        "Course2": "JavaScript",
        "start_date": [
            "2018-09-01",
            "2019-06-01"
        ],
        "end_date": [
            "2019-09-01",
            "2020-09-01"
        ]
    }
]

And I need to join the "end_date" together with "start_date" as follows(tried concat, spread operator etc, but I do get the desired output, and since I am new to this, I need help in how to build the expression). I am thinking of the map(), but not sure how to apply it correctly:

[
    {
        "First Name": "John",
        "Last Name": "Smith",
        "State": "California",
        "Course1": "HTML",
        "Course2": "JavaScript",
        "RootArray": [
        {
           "start_date": "2018-09-01",
           "end_date": "2019-06-01"

        },
       {
          "start_date": "2018-05-03",
           "end_date": "2018-08-07"

        }
    }
                    ]
]


问:
Use Modelica FMU derivatives in constraint formulation for Pyomo
As per object, I have several models developed in Modelica that I would like to use for optimal control purposes. So, I was wondering if there is any intention of coupling Pyomo with the FMI/FMU standard (in particular with Modelica generated FMU) to enable the extrapolation of derivatives from the FMU for the formulation of constraints, jacobians,etc...

I tried to look into the webpage, blog, newsletters and repository but I did not find anything related.


问:
Is it possible to use an integer discrimination value for mongodb java driver?
First of all, hope you are having a great day!!!

I have a class model with a POJO having nested document list which are an abstract type, like so:

public class ConfigDocument {
    private List<BaseActionConfig> actions;
}
```
<pre class="lang-java prettyprint-override"><code>public abstract class BaseActionConfig {
    @BsonProperty("interface") private int iface;
}

public class SwitchActionConfig extends BaseActionConfig {
    private int switchIndex;
    private boolean switchState;
}
</code>```

My configuration form MongoClient is:

public class MongoDBManager {

    private static MongoClient client = null;

    private static CodecRegistry codecRegistry()
    {
        ClassModel<ConfigDocument> configDocumentPojo =
            ClassModel.builder(ConfigDocument.class).enableDiscriminator(true).build();

        ClassModel<BaseActionConfig> baseActionConfigPojo = ClassModel.builder(BaseActionConfig.class)
                                                                .enableDiscriminator(true)
                                                                .discriminatorKey("interface")
                                                                .build();

        ClassModel<SwitchActionConfig> switchActionConfigPojo = ClassModel.builder(SwitchActionConfig.class)
                                                                    .enableDiscriminator(true)
                                                                    .discriminatorKey("interface")
                                                                    .discriminator("1")
                                                                    .build();

        PojoCodecProvider manualProvider = PojoCodecProvider.builder()
                                                .register(configDocumentPojo,
                                                          baseActionConfigPojo,
                                                          switchActionConfigPojo)
                                                .build();
        PojoCodecProvider autoProvider = PojoCodecProvider.builder().automatic(true).build();

        CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                                                            fromProviders(manualProvider, autoProvider));

        return pojoCodecRegistry;
    }

    private static MongoClient getClient()
    {
        if (client == null) {
            CodecRegistry pojoCodecRegistry = MongoDBManager.codecRegistry();

            MongoClientSettings setting = MongoClientSettings.builder()
                                                .applyConnectionString(new ConnectionString(CONN_STRING))
                                                .codecRegistry(pojoCodecRegistry)
                                                .build();

            client = MongoClients.create(setting);
        }

        return client;
    }
}
```
<p>When reading from database i have all kind of exceptions. The most recurrent one is an <code>InstantiateException</code>. After a lot of research and configuring ClassModels for using the <code>BsonDiscriminator</code> i reached the conclusion that the discriminator is not working because i am using an integer value.</p>
<p>How? I have manually replaced the type field in a document inside the database to string  and the discrimination started to work. Also, because at some time i have reached this other exception:</p>
```org.bson.codecs.configuration.CodecConfigurationException:
Failed to decode 'ConfigDocument'. Decoding 'actions' errored with: Failed to decode 'BaseActionConfig'.
Decoding errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is INT32.
```

The thing is that i cannot update the field of ALL Documents in the database and i see useless to add a new field on each document only for having this java application to work.
So, before watching me writing a custom Codec for those classes, i wanted to know if it is possible to configure a discriminator to use an integer value instead of an string one.

Reference to mongodb POJO Customization documentation

Body:
First of all, hope you are having a great day!!!

I have a class model with a POJO having nested document list which are an abstract type, like so:

public class ConfigDocument {
    private List<BaseActionConfig> actions;
}

public abstract class BaseActionConfig {
    @BsonProperty("interface") private int iface;
}

public class SwitchActionConfig extends BaseActionConfig {
    private int switchIndex;
    private boolean switchState;
}

My configuration form MongoClient is:

public class MongoDBManager {

    private static MongoClient client = null;

    private static CodecRegistry codecRegistry()
    {
        ClassModel<ConfigDocument> configDocumentPojo =
            ClassModel.builder(ConfigDocument.class).enableDiscriminator(true).build();

        ClassModel<BaseActionConfig> baseActionConfigPojo = ClassModel.builder(BaseActionConfig.class)
                                                                .enableDiscriminator(true)
                                                                .discriminatorKey("interface")
                                                                .build();

        ClassModel<SwitchActionConfig> switchActionConfigPojo = ClassModel.builder(SwitchActionConfig.class)
                                                                    .enableDiscriminator(true)
                                                                    .discriminatorKey("interface")
                                                                    .discriminator("1")
                                                                    .build();

        PojoCodecProvider manualProvider = PojoCodecProvider.builder()
                                                .register(configDocumentPojo,
                                                          baseActionConfigPojo,
                                                          switchActionConfigPojo)
                                                .build();
        PojoCodecProvider autoProvider = PojoCodecProvider.builder().automatic(true).build();

        CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                                                            fromProviders(manualProvider, autoProvider));

        return pojoCodecRegistry;
    }

    private static MongoClient getClient()
    {
        if (client == null) {
            CodecRegistry pojoCodecRegistry = MongoDBManager.codecRegistry();

            MongoClientSettings setting = MongoClientSettings.builder()
                                                .applyConnectionString(new ConnectionString(CONN_STRING))
                                                .codecRegistry(pojoCodecRegistry)
                                                .build();

            client = MongoClients.create(setting);
        }

        return client;
    }
}

When reading from database i have all kind of exceptions. The most recurrent one is an InstantiateException. After a lot of research and configuring ClassModels for using the BsonDiscriminator i reached the conclusion that the discriminator is not working because i am using an integer value.

How? I have manually replaced the type field in a document inside the database to string  and the discrimination started to work. Also, because at some time i have reached this other exception:

org.bson.codecs.configuration.CodecConfigurationException:
Failed to decode 'ConfigDocument'. Decoding 'actions' errored with: Failed to decode 'BaseActionConfig'.
Decoding errored with: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is INT32.

The thing is that i cannot update the field of ALL Documents in the database and i see useless to add a new field on each document only for having this java application to work.
So, before watching me writing a custom Codec for those classes, i wanted to know if it is possible to configure a discriminator to use an integer value instead of an string one.

Reference to mongodb POJO Customization documentation


问:
How can I cluster my snowflake table on the entirety of a VARCHAR column?
The Snowflake documentation is quite clear that only the first 5 characters of a VARCHAR are being used in clustering.

See  in "Important Notes"

I thought about using HASH() on the VARCHAR but

```<code>SHOW FUNCTIONS LIKE 'HASH';
</code>```

tells me it is not usable for Clustering (see column valid_for_clustering)

Is there another way/function I could use to cluster on my entire VARCHAR?

Body:
The Snowflake documentation is quite clear that only the first 5 characters of a VARCHAR are being used in clustering.

See  in "Important Notes"

I thought about using HASH() on the VARCHAR but

SHOW FUNCTIONS LIKE 'HASH';

tells me it is not usable for Clustering (see column valid_for_clustering)

Is there another way/function I could use to cluster on my entire VARCHAR?


问:
Wrong shape 'logits' and 'labels'
When executing the following code:

```<code># Set the input shape and number of classes
INPUT_SHAPE = (128, 128, 3)  # Assume 128x128 RGB images
NUM_CLASSES = 2  # Food or not food

# Set the batch size
BATCH_SIZE = 64

# Set the directory containing the images
image_dir = 'food_images_2'

# Create an ImageDataGenerator object
image_generator = ImageDataGenerator(rescale=1./255, validation_split=0.2)

# Use the generator to load the images from the directory
train_data_gen = image_generator.flow_from_directory(image_dir,
                                                     target_size=(128, 128),
                                                     color_mode='rgb',
                                                     class_mode='binary',
                                                     batch_size=64,
                                                     subset='training')
val_data_gen = image_generator.flow_from_directory(image_dir,
                                                   target_size=(128, 128),
                                                   color_mode='rgb',
                                                   class_mode='binary',
                                                   batch_size=64,
                                                   subset='validation')

# Get the images and labels from the generator
x_train, y_train = next(train_data_gen)
x_val, y_val = next(val_data_gen)

# Define the encoder
encoder_input = layers.Input(shape=INPUT_SHAPE)
x = layers.Conv2D(16, 3, activation='relu', padding='same')(encoder_input)
x = layers.MaxPooling2D(2, padding='same')(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
x = layers.MaxPooling2D(2, padding='same')(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
encoder_output = layers.MaxPooling2D(2, padding='same')(x)

# Define the decoder
decoder_input = encoder_output
x = layers.Conv2D(8, 3, activation='relu', padding='same')(decoder_input)
x = layers.UpSampling2D(2)(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
x = layers.UpSampling2D(2)(x)
x = layers.Conv2D(16, 3, activation='relu')(x)
x = layers.UpSampling2D(2)(x)
decoder_output = layers.Conv2D(3, 3, activation='sigmoid', padding='same')(x)

# Define the autoencoder
autoencoder = tf.keras.Model(encoder_input, decoder_output)

# Define the encoder model
encoder = tf.keras.Model(encoder_input, encoder_output)

# Compile the autoencoder with a loss function and an optimizer
autoencoder.compile(loss='binary_crossentropy', optimizer='adam')

from tensorflow.keras.callbacks import ModelCheckpoint

NUM_EPOCHS = 10

# Create a ModelCheckpoint callback
checkpoint_callback = ModelCheckpoint('autoencoder_weights.h5', save_weights_only=True, period=5)

# Fit the autoencoder to the training data, using the ModelCheckpoint callback
history = autoencoder.fit(x_train,
                          x_train,
                          epochs=NUM_EPOCHS,
                          batch_size=BATCH_SIZE,
                          validation_data=(x_val, x_val),
                          callbacks=[checkpoint_callback])
</code>```

The autoencoder.fit() function throws an error telling me:

```<code>ValueError: `logits` and `labels` must have the same shape, received ((64, 124, 124, 3) vs (64, 128, 128, 3)).
</code>```

The output of

```<code>print(x_train.shape)
print(y_train.shape)
print(x_val.shape)
print(y_val.shape)
</code>```

results in:

```<code>(64, 128, 128, 3)
(64,)
(64, 128, 128, 3)
(64,)
</code>```

And the summary of the encoder gives me the following information:

```<code>________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_17 (InputLayer)       [(None, 128, 128, 3)]     0

 conv2d_79 (Conv2D)          (None, 128, 128, 16)      448

 max_pooling2d_39 (MaxPoolin  (None, 64, 64, 16)       0
 g2D)

 conv2d_80 (Conv2D)          (None, 64, 64, 8)         1160

 max_pooling2d_40 (MaxPoolin  (None, 32, 32, 8)        0
 g2D)

 conv2d_81 (Conv2D)          (None, 32, 32, 8)         584

 max_pooling2d_41 (MaxPoolin  (None, 16, 16, 8)        0
 g2D)

 conv2d_82 (Conv2D)          (None, 16, 16, 8)         584

 up_sampling2d_30 (UpSamplin  (None, 32, 32, 8)        0
 g2D)
...
Total params: 4,963
Trainable params: 4,963
Non-trainable params: 0
</code>```

I have no clue where the (64, 124,124, 3) is coming from. I do believe this issue could be solved quite easily but i've been searching for hours and unfortunately without succes. All help is welcome!

Title: Wrong shape 'logits' and 'labels'

Body:
When executing the following code:

# Set the input shape and number of classes
INPUT_SHAPE = (128, 128, 3)  # Assume 128x128 RGB images
NUM_CLASSES = 2  # Food or not food

# Set the batch size
BATCH_SIZE = 64

# Set the directory containing the images
image_dir = 'food_images_2'

# Create an ImageDataGenerator object
image_generator = ImageDataGenerator(rescale=1./255, validation_split=0.2)

# Use the generator to load the images from the directory
train_data_gen = image_generator.flow_from_directory(image_dir,
                                                     target_size=(128, 128),
                                                     color_mode='rgb',
                                                     class_mode='binary',
                                                     batch_size=64,
                                                     subset='training')
val_data_gen = image_generator.flow_from_directory(image_dir,
                                                   target_size=(128, 128),
                                                   color_mode='rgb',
                                                   class_mode='binary',
                                                   batch_size=64,
                                                   subset='validation')

# Get the images and labels from the generator
x_train, y_train = next(train_data_gen)
x_val, y_val = next(val_data_gen)

# Define the encoder
encoder_input = layers.Input(shape=INPUT_SHAPE)
x = layers.Conv2D(16, 3, activation='relu', padding='same')(encoder_input)
x = layers.MaxPooling2D(2, padding='same')(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
x = layers.MaxPooling2D(2, padding='same')(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
encoder_output = layers.MaxPooling2D(2, padding='same')(x)

# Define the decoder
decoder_input = encoder_output
x = layers.Conv2D(8, 3, activation='relu', padding='same')(decoder_input)
x = layers.UpSampling2D(2)(x)
x = layers.Conv2D(8, 3, activation='relu', padding='same')(x)
x = layers.UpSampling2D(2)(x)
x = layers.Conv2D(16, 3, activation='relu')(x)
x = layers.UpSampling2D(2)(x)
decoder_output = layers.Conv2D(3, 3, activation='sigmoid', padding='same')(x)

# Define the autoencoder
autoencoder = tf.keras.Model(encoder_input, decoder_output)

# Define the encoder model
encoder = tf.keras.Model(encoder_input, encoder_output)

# Compile the autoencoder with a loss function and an optimizer
autoencoder.compile(loss='binary_crossentropy', optimizer='adam')

from tensorflow.keras.callbacks import ModelCheckpoint

NUM_EPOCHS = 10

# Create a ModelCheckpoint callback
checkpoint_callback = ModelCheckpoint('autoencoder_weights.h5', save_weights_only=True, period=5)

# Fit the autoencoder to the training data, using the ModelCheckpoint callback
history = autoencoder.fit(x_train,
                          x_train,
                          epochs=NUM_EPOCHS,
                          batch_size=BATCH_SIZE,
                          validation_data=(x_val, x_val),
                          callbacks=[checkpoint_callback])

The autoencoder.fit() function throws an error telling me:

ValueError: `logits` and `labels` must have the same shape, received ((64, 124, 124, 3) vs (64, 128, 128, 3)).

The output of

print(x_train.shape)
print(y_train.shape)
print(x_val.shape)
print(y_val.shape)

results in:

(64, 128, 128, 3)
(64,)
(64, 128, 128, 3)
(64,)

And the summary of the encoder gives me the following information:

________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_17 (InputLayer)       [(None, 128, 128, 3)]     0

 conv2d_79 (Conv2D)          (None, 128, 128, 16)      448

 max_pooling2d_39 (MaxPoolin  (None, 64, 64, 16)       0
 g2D)

 conv2d_80 (Conv2D)          (None, 64, 64, 8)         1160

 max_pooling2d_40 (MaxPoolin  (None, 32, 32, 8)        0
 g2D)

 conv2d_81 (Conv2D)          (None, 32, 32, 8)         584

 max_pooling2d_41 (MaxPoolin  (None, 16, 16, 8)        0
 g2D)

 conv2d_82 (Conv2D)          (None, 16, 16, 8)         584

 up_sampling2d_30 (UpSamplin  (None, 32, 32, 8)        0
 g2D)
...
Total params: 4,963
Trainable params: 4,963
Non-trainable params: 0

I have no clue where the (64, 124,124, 3) is coming from. I do believe this issue could be solved quite easily but i've been searching for hours and unfortunately without succes. All help is welcome!


问:
Retrieve GAUL country boundaries based on ISO3 string in Earth Engine
I want to retrieve the geometry of a country based on its ISO3 name (which is then used in another function). My code to get the geometry currently looks as follows (countryCodes is a table with various aliases for countries in, and filtering it manually works fine):

```<code>var FAO_GAUL = ee.FeatureCollection("FAO/GAUL/2015/level0");
var countryCodes = ee.FeatureCollection("users/tsb42/country-codes_csv");

var getGaulCode = function (iso3) {
  return countryCodes.filter(ee.Filter.eq("ISO3166-1-Alpha-3", iso3))
                  .select("GAUL").first().get("GAUL");
};

var getGaulGeom = function (iso3) {
  var gaulCode = getGaulCode(iso3);
  var countryDat = FAO_GAUL.filter(ee.Filter.eq("ADM0_CODE", gaulCode));
  return countryDat.geometry();
};
</code>```

Doing getGaulCode("GBR") returns 256, which is the expected value. However doing getGaulGeom("GBR") returns an empty geometry because countryDat is a feature collection with no elements.

Doing FAO_GAUL.filter(ee.Filter.eq("ADM0_CODE", 256)) returns a feature collection with one element and the expected geometry.

Why can I not pass the number generated by getGaulCode into a filter? I'm very stuck, any method to get country boundaries from ISO3 strings would be much appreciated!!

Body:
I want to retrieve the geometry of a country based on its ISO3 name (which is then used in another function). My code to get the geometry currently looks as follows (countryCodes is a table with various aliases for countries in, and filtering it manually works fine):

var FAO_GAUL = ee.FeatureCollection("FAO/GAUL/2015/level0");
var countryCodes = ee.FeatureCollection("users/tsb42/country-codes_csv");

var getGaulCode = function (iso3) {
  return countryCodes.filter(ee.Filter.eq("ISO3166-1-Alpha-3", iso3))
                  .select("GAUL").first().get("GAUL");
};

var getGaulGeom = function (iso3) {
  var gaulCode = getGaulCode(iso3);
  var countryDat = FAO_GAUL.filter(ee.Filter.eq("ADM0_CODE", gaulCode));
  return countryDat.geometry();
};

Doing getGaulCode("GBR") returns 256, which is the expected value. However doing getGaulGeom("GBR") returns an empty geometry because countryDat is a feature collection with no elements.

Doing FAO_GAUL.filter(ee.Filter.eq("ADM0_CODE", 256)) returns a feature collection with one element and the expected geometry.

Why can I not pass the number generated by getGaulCode into a filter? I'm very stuck, any method to get country boundaries from ISO3 strings would be much appreciated!!


问:
Nuxt 3.0.0 (no RC) file upload does not work
i tried to implement the solution which was posted here
formidable is installed and exposed/loaded via nuxtconfig file.

my index.post looks exactly like this:

import formidable from "formidable";
import fs from "fs";
import path from "path";

export default defineEventHandler(async (event) => {
  let imageUrl = "";
  let oldPath = "";
  let newPath = "";

  const form = formidable({ multiples: true });
  const data = await new Promise((resolve, reject) => {
    form.parse(event.req, (err, fields, files) => {
      if (err) {
        reject(err);
      }
      if (!files.photo) {
        resolve({
          status: "error",
          message: "Please upload a photo with name photo in the form",
        });
      }
      if (files.photo.mimetype.startsWith("image/")) {
        let imageName =
          Date.now() +
          Math.round(Math.random() * 100000) +
          files.photo.originalFilename;
        oldPath = files.photo.filepath;
        newPath = `${path.join("public", "uploads", imageName)}`;
        imageUrl = "./public/upload/" + imageName;
        fs.copyFileSync(oldPath, newPath);
        resolve({
          status: "ok",
          url: imageUrl,
        });
      } else {
        resolve({
          status: "error",
          message: "Please upload nothing but images.",
        });
      }
    });
  });
  return data;
});
```
<p>this is the frontend part:</p>
<pre class="lang-html prettyprint-override"><code><template>
  <v-col cols="12" sm="10">
    <v-sheet min-height="70vh" rounded="lg" class="pa-3">
      <input
        type="file"
        accept="image/*"
        label="Bild hochladen"
        @change="onChange"
      />
    </v-sheet>
  </v-col>
</template>

<script setup lang="ts">
const onChange = async (e: Event) => {
  const selectedFile = e.target.files[0]

  const formData = new FormData()
  formData.append('file', selectedFile)

  await useAsyncData('file', () =>
    $fetch(`/api/v1/data/images`, {
      method: 'POST',
      body: formData,
    })
  )
}
</script>
</code>```

I am getting the error:

[nitro] [dev] [uncaughtException] TypeError: Cannot read properties of undefined (reading 'mimetype')                                                               18:57:47
at file:///home/user/repo/test-store/packages/store/.nuxt/dev/index.mjs:873:23
at zalgoSafe (/home/user/repo/test-store/node_modules/dezalgo/dezalgo.js:20:10)
at f (/home/user/repo/test-store/node_modules/once/once.js:25:25)
at IncomingForm. (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:183:9)
at IncomingForm.emit (node:events:513:28)
at IncomingForm._maybeEnd (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:612:10)
at /home/user/repo/test-store/node_modules/formidable/src/Formidable.js:390:14
at Array. (/home/user/repo/test-store/node_modules/formidable/src/PersistentFile.js:77:7)
at finish (node:internal/streams/writable:745:25)
at finishMaybe (node:internal/streams/writable:733:9

I run in similar issues before. there are differences from the RC version to the final released version. any solution for this?

I have tried to implement a solution with the fs module. here I am struggling too...

export default defineEventHandler(async (event) => {
  const {imageName} = event.context.params

  const body = await readBody(event)

  await saveFile(body)

  async function saveFile(file) {
    console.log('Saving file 2')
    fs.writeFileSync(`./assets/article/images/${imageName}`, file)
    return
  }
})
```

This seems to partially work. But the generated file is corrupted.

Body:
i tried to implement the solution which was posted here
formidable is installed and exposed/loaded via nuxtconfig file.

my index.post looks exactly like this:

import formidable from "formidable";
import fs from "fs";
import path from "path";

export default defineEventHandler(async (event) => {
  let imageUrl = "";
  let oldPath = "";
  let newPath = "";

  const form = formidable({ multiples: true });
  const data = await new Promise((resolve, reject) => {
    form.parse(event.req, (err, fields, files) => {
      if (err) {
        reject(err);
      }
      if (!files.photo) {
        resolve({
          status: "error",
          message: "Please upload a photo with name photo in the form",
        });
      }
      if (files.photo.mimetype.startsWith("image/")) {
        let imageName =
          Date.now() +
          Math.round(Math.random() * 100000) +
          files.photo.originalFilename;
        oldPath = files.photo.filepath;
        newPath = `${path.join("public", "uploads", imageName)}`;
        imageUrl = "./public/upload/" + imageName;
        fs.copyFileSync(oldPath, newPath);
        resolve({
          status: "ok",
          url: imageUrl,
        });
      } else {
        resolve({
          status: "error",
          message: "Please upload nothing but images.",
        });
      }
    });
  });
  return data;
});

this is the frontend part:

<template>
  <v-col cols="12" sm="10">
    <v-sheet min-height="70vh" rounded="lg" class="pa-3">
      <input
        type="file"
        accept="image/*"
        label="Bild hochladen"
        @change="onChange"
      />
    </v-sheet>
  </v-col>
</template>

I am getting the error:

[nitro] [dev] [uncaughtException] TypeError: Cannot read properties of undefined (reading 'mimetype')                                                               18:57:47
at file:///home/user/repo/test-store/packages/store/.nuxt/dev/index.mjs:873:23
at zalgoSafe (/home/user/repo/test-store/node_modules/dezalgo/dezalgo.js:20:10)
at f (/home/user/repo/test-store/node_modules/once/once.js:25:25)
at IncomingForm. (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:183:9)
at IncomingForm.emit (node:events:513:28)
at IncomingForm._maybeEnd (/home/user/repo/test-store/node_modules/formidable/src/Formidable.js:612:10)
at /home/user/repo/test-store/node_modules/formidable/src/Formidable.js:390:14
at Array. (/home/user/repo/test-store/node_modules/formidable/src/PersistentFile.js:77:7)
at finish (node:internal/streams/writable:745:25)
at finishMaybe (node:internal/streams/writable:733:9

I run in similar issues before. there are differences from the RC version to the final released version. any solution for this?

I have tried to implement a solution with the fs module. here I am struggling too...

export default defineEventHandler(async (event) => {
  const {imageName} = event.context.params

  const body = await readBody(event)

  await saveFile(body)

  async function saveFile(file) {
    console.log('Saving file 2')
    fs.writeFileSync(`./assets/article/images/${imageName}`, file)
    return
  }
})

This seems to partially work. But the generated file is corrupted.


问:
iOS ActivityKit: Push Token Issues
iOS 16.1 brings ActivityKit that allows to show a Live Activity on Lock Screen (similar to Lock Screen widget but not quite the same).

LiveActivity can receive a limited amount of data per an update (up to 4KB). We send updates to live activity using backend server via APNs. To make backend work we need to get a pushToken from the started LiveActivity and send the token to the backend.

And here're two issues:

Issue #1 - nil token

When an activity is created, pushToken property of that activity is always nil.

```<code>        let activity = try Activity.request(
            attributes: attributes,
            contentState: contentState,
            pushType: .token
        )
        print(activity.pushToken) // always nil at this point

</code>```

So that to get an "initial" token we have to subscribe to pushTokenUpdates and wait for the first available token.

That sounds like a workaround because we expect a started activity should contain a valid token.

Question 1: Is this expected behavior that pushToken is nil right after an activity is started?

Issue #2 - Expired Token

Apple Documentation clearly says that we need to subscribe to push token updates because current token can expire:

Observe changes to an activity’s push token with pushTokenUpdates, send an updated push token to your server, and invalidate the old token on your server.

We subscribed to pushTokenUpdates in the app. But if we close the app or move it to the background, after sometime, the backend receives error 403 from APNS saying that ExpiredProviderToken.

Question 2: What's the life-time of an LiveActivity Push Token? There's no clear documentation that says how often the token refreshes, it sounds like the token can expire while the app in the background. At least this is what we see from our internal tests.
Does anyone else experience the same expiration issue with token while the app in the background?

We experience these issues on iOS 16.1 and iOS 16.2.
Seems like token always nil when activity is started, and token can expire while the app is in the background.

Title: iOS ActivityKit: Push Token Issues

Body:
iOS 16.1 brings ActivityKit that allows to show a Live Activity on Lock Screen (similar to Lock Screen widget but not quite the same).

LiveActivity can receive a limited amount of data per an update (up to 4KB). We send updates to live activity using backend server via APNs. To make backend work we need to get a pushToken from the started LiveActivity and send the token to the backend.

And here're two issues:

Issue #1 - nil token

When an activity is created, pushToken property of that activity is always nil.

        let activity = try Activity.request(
            attributes: attributes,
            contentState: contentState,
            pushType: .token
        )
        print(activity.pushToken) // always nil at this point

So that to get an "initial" token we have to subscribe to pushTokenUpdates and wait for the first available token.

That sounds like a workaround because we expect a started activity should contain a valid token.

Question 1: Is this expected behavior that pushToken is nil right after an activity is started?

Issue #2 - Expired Token

Apple Documentation clearly says that we need to subscribe to push token updates because current token can expire:

Observe changes to an activity’s push token with pushTokenUpdates, send an updated push token to your server, and invalidate the old token on your server.

We subscribed to pushTokenUpdates in the app. But if we close the app or move it to the background, after sometime, the backend receives error 403 from APNS saying that ExpiredProviderToken.

Question 2: What's the life-time of an LiveActivity Push Token? There's no clear documentation that says how often the token refreshes, it sounds like the token can expire while the app in the background. At least this is what we see from our internal tests.
Does anyone else experience the same expiration issue with token while the app in the background?

We experience these issues on iOS 16.1 and iOS 16.2.
Seems like token always nil when activity is started, and token can expire while the app is in the background.


问:
How to automatically redirect to refresh token endpoint, and then redirect to previously called endpoint?
Im using ASP.NET
I have two different application:

WEB API server on .NET Core

Client on .NET MVC with RazorPages
I have authorization with JWT + RefreshToken
I want to implement next thing:
If I call some endppoint with expired token, it should automaticaly redirect to the refrehToken endpoint and call previous called endpoint

I tried to think how to implement this. I found some stuff about interceptor but I didnt find it for RazorPages(only for Blazor)


问:
SwiftUI: Is there a difference between @StateObject initialization with closure or initializer?
To clarify in code. Is there a difference between:

```<code>struct Shim: View {
    @StateObject private var viewModel = {
        let viewModel = ContentView.ViewModel()
        //do some configuration
        return viewModel
    }()

    var body: some View {
        ContentView(viewModel: viewModel)
    }
}
</code>```

AND

```<code>struct Shim: View {
    @StateObject private var viewModel: ContentView.ViewModel

    init() {
        let viewModel = ContentView.ViewModel()
        //do some configuration
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    var body: some View {
        ContentView(viewModel: viewModel)
    }
}
</code>```

Body:
To clarify in code. Is there a difference between:

struct Shim: View {
    @StateObject private var viewModel = {
        let viewModel = ContentView.ViewModel()
        //do some configuration
        return viewModel
    }()

    var body: some View {
        ContentView(viewModel: viewModel)
    }
}

AND

struct Shim: View {
    @StateObject private var viewModel: ContentView.ViewModel

    init() {
        let viewModel = ContentView.ViewModel()
        //do some configuration
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    var body: some View {
        ContentView(viewModel: viewModel)
    }
}


问:
what is a and b in the equation below, where a and b cannot be 0 and must be a positive integer
The equation is 7a^3=11b^5. It cannot be 0 and both must be a positive integer. I have tried substitution and everything in algebra I know (not including calculus). Trial and error doesn't work because a is bigger than 40 000. I don't mean that I actually tried all till 40 000, i know the answer. I mainly just want to know how to solve it and explain how I solved it.

 a = 41503 and b = 539

Thank you in advance.


问:
Adding floating point numbers in assembly (yasm 8086)
I have to write a program that would filter text lines from the input file. Each line is divided into six columns. Columns are separated from each other by a semicolon.

I implemented 3 filters:

Second column has to contain no u or v letters.

Third column has to contain a number so that it's sum of digits is equal to 7.

Last column has to contain number that belongs to the intervar of [2.34, 4.50]

Here's input file example:

```<code>B11;one;16;0;55;2.44
C1;two;8;0;17;3.77
</code>```

First line would pass all of three filters.

My program works correctly with all of the filters. However, I have an additional task to find the sum of last columns floating point numbers but only on filtered lines.

I am not sure what would be the proper way to do it.

Here I have implemented filter function for the last column. Somehow from here I should put the filtered last column numbers into buffer and add all of them together.
Here in this function I go through each character in the line.

```<code>procBelongsToInterval
    push ax
    xor ax, ax
.first:
    mov al, [di]

    inc di
    cmp al, '-'
    je  .break
    cmp al, '2'
    je  .firstBound
    cmp al, '3'
    je  .belongs
    cmp al, '4'
    je  .secondBound
    jmp .break

.firstBound:
    mov al, [di]
    inc di
    cmp al, '.'
    je  .firstBound
    cmp al, '3'
    jb  .break
    ja  .belongs
    mov al, [di]
    cmp al, '4'
    jae .belongs
    jb  .break

.secondBound:
    mov al, [di]
    inc di
    cmp al, '.'
    je  .secondBound
    cmp al, '5'
    ja  .break
    jb  .belongs
    mov al, [di]
    cmp al, '0'
    je  .belongs
    ja  .break

.belongs:
    mov [numberBelongsToInterval], byte 1
    jmp .end

.break:
    mov [numberBelongsToInterval], byte 0
    jmp .end

.end:
    pop ax
    ret
</code>```

Body:
I have to write a program that would filter text lines from the input file. Each line is divided into six columns. Columns are separated from each other by a semicolon.

I implemented 3 filters:

Second column has to contain no u or v letters.

Third column has to contain a number so that it's sum of digits is equal to 7.

Last column has to contain number that belongs to the intervar of [2.34, 4.50]

Here's input file example:

B11;one;16;0;55;2.44
C1;two;8;0;17;3.77

First line would pass all of three filters.

My program works correctly with all of the filters. However, I have an additional task to find the sum of last columns floating point numbers but only on filtered lines.

I am not sure what would be the proper way to do it.

Here I have implemented filter function for the last column. Somehow from here I should put the filtered last column numbers into buffer and add all of them together.
Here in this function I go through each character in the line.

procBelongsToInterval
    push ax
    xor ax, ax
.first:
    mov al, [di]

    inc di
    cmp al, '-'
    je  .break
    cmp al, '2'
    je  .firstBound
    cmp al, '3'
    je  .belongs
    cmp al, '4'
    je  .secondBound
    jmp .break

.firstBound:
    mov al, [di]
    inc di
    cmp al, '.'
    je  .firstBound
    cmp al, '3'
    jb  .break
    ja  .belongs
    mov al, [di]
    cmp al, '4'
    jae .belongs
    jb  .break

.secondBound:
    mov al, [di]
    inc di
    cmp al, '.'
    je  .secondBound
    cmp al, '5'
    ja  .break
    jb  .belongs
    mov al, [di]
    cmp al, '0'
    je  .belongs
    ja  .break

.belongs:
    mov [numberBelongsToInterval], byte 1
    jmp .end

.break:
    mov [numberBelongsToInterval], byte 0
    jmp .end

.end:
    pop ax
    ret


问:
Open XML SDK when creating a document, the current html page is constantly returned
I am trying to create a word document with my own text inside using the Open XML SDK, but whatever I enter there, I always get a document in which my copied html page
enter image description here

Here is the method I use:

```<code> public IActionResult GenerateDocxBrowser()
        {

            using (MemoryStream mem  = new MemoryStream())
            {
                using (WordprocessingDocument wordDocument =
                    WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                    // Create the document structure and add some text.
                    mainPart.Document = new Document();
                    Body docBody = new Body();

                    // Add your docx content here
                    Paragraph p = new Paragraph();
                    Run r = new Run();
                    Text t = new Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent quam augue, tempus id metus in, laoreet viverra quam. Sed vulputate risus lacus, et dapibus orci porttitor non.");
                    r.Append(t);
                    p.Append(r);
                    docBody.Append(p);

                }

                var cd = new ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = "ABC.docx"
                };

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
                return File(mem.ToArray(),"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

        }
</code>```

Body:
I am trying to create a word document with my own text inside using the Open XML SDK, but whatever I enter there, I always get a document in which my copied html page
enter image description here

Here is the method I use:

 public IActionResult GenerateDocxBrowser()
        {

            using (MemoryStream mem  = new MemoryStream())
            {
                using (WordprocessingDocument wordDocument =
                    WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                    // Create the document structure and add some text.
                    mainPart.Document = new Document();
                    Body docBody = new Body();

                    // Add your docx content here
                    Paragraph p = new Paragraph();
                    Run r = new Run();
                    Text t = new Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent quam augue, tempus id metus in, laoreet viverra quam. Sed vulputate risus lacus, et dapibus orci porttitor non.");
                    r.Append(t);
                    p.Append(r);
                    docBody.Append(p);

                }

                var cd = new ContentDispositionHeaderValue("attachment")
                {
                    FileNameStar = "ABC.docx"
                };

                Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
                return File(mem.ToArray(),"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

        }


问:
How do I translate a CURL request to Python?
I am trying to translate the below CURL request to a Python request. The CURL request was provided to me by the company who owns the API.

```<code>$ export client_id="client-id"
$ read -s client_secret
$ export basic_auth="$(echo -n $client_id:$client_secret | base64)"
$ curl -XPOST https://tokenurl.com -H"Authorization: Basic $basic_auth" -d client_id="$client_id" -d grant_type=client_credentials
</code>```

Here is what I have in Python.

```<code>client_id = 'XXX'
client_secret_id = 'YYYYYYYYYYYYYY'
token_url = 'https://tokenurl.com'

basic_auth = client_id + ':'+ client_secret_id

headers = {'Authorization': f"Basic {basic_auth}"}

data = {'client_id':client_id, 'grant_type':'client_credentials'}

response = requests.post(token_url,headers=headers,json=data)
</code>```

This returns a response error [400]. Would love any help in directing me in my poor translation! Thank you in advance.

Body:
I am trying to translate the below CURL request to a Python request. The CURL request was provided to me by the company who owns the API.

$ export client_id="client-id"
$ read -s client_secret
$ export basic_auth="$(echo -n $client_id:$client_secret | base64)"
$ curl -XPOST https://tokenurl.com -H"Authorization: Basic $basic_auth" -d client_id="$client_id" -d grant_type=client_credentials

Here is what I have in Python.

client_id = 'XXX'
client_secret_id = 'YYYYYYYYYYYYYY'
token_url = 'https://tokenurl.com'

basic_auth = client_id + ':'+ client_secret_id

headers = {'Authorization': f"Basic {basic_auth}"}

data = {'client_id':client_id, 'grant_type':'client_credentials'}

response = requests.post(token_url,headers=headers,json=data)

This returns a response error [400]. Would love any help in directing me in my poor translation! Thank you in advance.


问:
Pip install error and Setuptools.command not found
I was using the guide in this link to install a package in a specific conda environment: https://github.com/alegiac95/Imaging-transcriptomics. However, I was unable to do so and had the following error. Would really appreciate the help!

Traceback (most recent call last):
File "setup.py", line 9, in
from setuptools import setup, find_packages
ImportError: No module named 'setuptools'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "setup.py", line 11, in
from distutils.core import setup, find_packages
ImportError: cannot import name 'find_packages'


问:
Extract block of text that starts with 'Block 4' until it encounters 'Block 5' from text file in Java
I have a text file that contains three messages, each message contains Block 4 content. What I want to achieve is that I want to get all the content inside Block 4. (Skipping the remaining content). Here is my code that extracts Message 1 Block 4. How do I get the Block 4 content of the remaining messages?

```<code>public static void main(String[] args) throws IOException, SQLException {
    String filePath = "C:\\Users\\abc\\Desktop\\reportTest5.txt";

    String content = null;
    try {
        // read the file
        content = readFile(filePath);

        // parse the file
        List<AlphabetSpellings> fileParsing = parseFile(content);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String readFile(String path) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
    return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}

private static List<AlphabetSpellings> parseFile(String fileContent) {

    // create list object

    String block4 = fileContent.indexOf("Block 5") == -1 ? ""
            : fileContent.substring(fileContent.indexOf("Block 4") + 8, fileContent.indexOf("Block 5"));

    // add block4 to list object

    System.out.println(block4);

    // return list as null for now
    return null;
}
</code>```

Body:
I have a text file that contains three messages, each message contains Block 4 content. What I want to achieve is that I want to get all the content inside Block 4. (Skipping the remaining content). Here is my code that extracts Message 1 Block 4. How do I get the Block 4 content of the remaining messages?

public static void main(String[] args) throws IOException, SQLException {
    String filePath = "C:\\Users\\abc\\Desktop\\reportTest5.txt";

    String content = null;
    try {
        // read the file
        content = readFile(filePath);

        // parse the file
        List<AlphabetSpellings> fileParsing = parseFile(content);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String readFile(String path) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(path)));
    return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}

private static List<AlphabetSpellings> parseFile(String fileContent) {

    // create list object

    String block4 = fileContent.indexOf("Block 5") == -1 ? ""
            : fileContent.substring(fileContent.indexOf("Block 4") + 8, fileContent.indexOf("Block 5"));

    // add block4 to list object

    System.out.println(block4);

    // return list as null for now
    return null;
}


问:
How to get File from Uri (Activity Result)?
I am trying to make a File object from Uri which I get by selecting file from file explorer. Then I need to send this File to server. I get Uri object in following way:

```<code>private val registerActivityForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    it.data?.data?.let { imageUri ->
        // handle Uri
    }
}

private val openFileExplorer: () -> Unit = {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
    }
    registerActivityForResult.launch(intent)
}
</code>```

When I try to parse Uri to File by calling Uri.toFile() method, it throws an exception:

java.lang.IllegalArgumentException: Uri lacks 'file' scheme: content://com.android.providers.media.documents/document/image%3A1000000471

What is the correct way to get a File object by selecting a file from file explorer?

Body:
I am trying to make a File object from Uri which I get by selecting file from file explorer. Then I need to send this File to server. I get Uri object in following way:

private val registerActivityForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    it.data?.data?.let { imageUri ->
        // handle Uri
    }
}

private val openFileExplorer: () -> Unit = {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "*/*"
    }
    registerActivityForResult.launch(intent)
}

When I try to parse Uri to File by calling Uri.toFile() method, it throws an exception:

java.lang.IllegalArgumentException: Uri lacks 'file' scheme: content://com.android.providers.media.documents/document/image%3A1000000471

What is the correct way to get a File object by selecting a file from file explorer?


问:
How to properly initialize and use the monaco editor tokenizer?
As the title states, I've been searching for a week now on how to get the tokenizer to work. I.e. if I do something like:

```<code>import * as monaco from "monaco-editor-core";

const code = "export const myFunc = () => console.log('hello world');"
const tokens = monaco.editor.tokenize(code, "typescript");
console.log("TOKENS ", tokens);
</code>```

I'll get the tokenized lines identified, but within each actual line you'll see that the token array is empty.

Import as you'd like here, either from monaco-editor-core or monaco-editor - you'll find the same result.

My current workaround is calling the tokenizer on the window object of monaco (I'm using React, so I could otherwise import it from the module, though I found this hack only worked with accessing window.monaco within a 1-second timeout, like so:

```<code>setTimeout(() => {
  (window as any).monaco.editor.tokenize(
    `export const dummyFunction = () => {
  console.log('hello world')
}`,
    "typescript"
  );
}, 1000);
</code>```

Only then can you successfully call monaco.editor.tokenize.

There is also an open GitHub issue about this problem.

I would be grateful if anyone can point me in a direction to get the tokenizer to work without my setTimeout hack.

Body:
As the title states, I've been searching for a week now on how to get the tokenizer to work. I.e. if I do something like:

import * as monaco from "monaco-editor-core";

const code = "export const myFunc = () => console.log('hello world');"
const tokens = monaco.editor.tokenize(code, "typescript");
console.log("TOKENS ", tokens);

I'll get the tokenized lines identified, but within each actual line you'll see that the token array is empty.

Import as you'd like here, either from monaco-editor-core or monaco-editor - you'll find the same result.

My current workaround is calling the tokenizer on the window object of monaco (I'm using React, so I could otherwise import it from the module, though I found this hack only worked with accessing window.monaco within a 1-second timeout, like so:

setTimeout(() => {
  (window as any).monaco.editor.tokenize(
    `export const dummyFunction = () => {
  console.log('hello world')
}`,
    "typescript"
  );
}, 1000);

Only then can you successfully call monaco.editor.tokenize.

There is also an open GitHub issue about this problem.

I would be grateful if anyone can point me in a direction to get the tokenizer to work without my setTimeout hack.