问:
Sharp image folder compression and convertion
How to configure Sharp so that all jpg & png files in 'src/images' folder convert to webp & avif in the same folder, replacing jpg & png? The svg icons should be only compressed, without conversion. Would be nice to have a separate script in package.json specifically for these tasks.

When building, it should compress the converted images and copy them in dist/images.

I tried to do it for webp only and I received an error: 'EISDIR: illegal operation on a directory, read'

```<code>import fs from 'fs';
import sharp from 'sharp';

const files = fs.readdirSync('images');

const convert = (dir, name) => {
  const fullname = dir + '/' + name;
  const i = sharp(fs.readFileSync(fullname));
  i.toFormat('webp', { quality: 75 });
  return i
    .toFile('images/' + name + '.webp')
    .then(() => console.log('Converted', fullname))
    .catch((e) => console.log('Failed converting', fullname, e, 'skipping...'));
};

const promises = files.map((name) => convert('images/', name));

Promise.all(promises)
  .then(() => console.log('Done'))
  .catch((e) => console.error(e));

</code>```

Body:
How to configure Sharp so that all jpg & png files in 'src/images' folder convert to webp & avif in the same folder, replacing jpg & png? The svg icons should be only compressed, without conversion. Would be nice to have a separate script in package.json specifically for these tasks.

When building, it should compress the converted images and copy them in dist/images.

I tried to do it for webp only and I received an error: 'EISDIR: illegal operation on a directory, read'

import fs from 'fs';
import sharp from 'sharp';

const files = fs.readdirSync('images');

const convert = (dir, name) => {
  const fullname = dir + '/' + name;
  const i = sharp(fs.readFileSync(fullname));
  i.toFormat('webp', { quality: 75 });
  return i
    .toFile('images/' + name + '.webp')
    .then(() => console.log('Converted', fullname))
    .catch((e) => console.log('Failed converting', fullname, e, 'skipping...'));
};

const promises = files.map((name) => convert('images/', name));

Promise.all(promises)
  .then(() => console.log('Done'))
  .catch((e) => console.error(e));


来源: stackexchange

问:
Add Chevron Image to Tab on Mobile Size
I am trying to make a 3-tab layout using CSS that is responsive. I have two issues. The first is the third tab won't line up with the box. It's just a tad bit off.

The second issue is I would like to show chevron images on mobile screens (up to close, down to expand). I am not sure how to do this.

Here is my HTML.

```<code><section class="tabs-wrapper">
            <div class="tabs-container">
                <div class="tabs-block">
                    <div class="tabs">
                        <input type="radio" name="tabs" id="tab1" checked="checked" />
                        <label class="label1" for="tab1"><!--<span class="material-icons">favorite_border</span>-->
                            QuickBooks for
                            Manufacturing & Distribution</label>
                        <div class="tab">
                            <!-- <h2>Angular</h2> -->
                            <div class="flex-container">
                                <div class="tab-list-item-left">
                                    <ul>
                                        <li>Monitor and track inventory.</li>
                                        <li>Create bills of material and work orders.</li>
                                        <li>Set up accurate COGS and inventory costing system.</li>
                                        <li>Assist in inventory assembly setup and implementation.</li>
                                    </ul>
                                </div>
                                <div class="tab-list-item-right">
                                    <ul>
                                        <li>Capture indirect and direct costs.</li>
                                        <li>Build sales order reports.</li>
                                        <li>Track profit and loss.</li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        <input type="radio" name="tabs" id="tab2" />
                        <label class="label2" for="tab2"><!-- <span class="material-icons">face</span>--> QuickBooks for
                            Professional
                            Services</label>
                        <div class="tab tab-2">
                            <!-- <h2>React</h2> -->
                            <div class="flex-container">
                                <div class="tab-list-item-left">
                                    <ul>
                                        <li>Track time and expenses.</li>
                                        <li>Set up separate billing rates and customized invoices.</li>
                                    </ul>
                                </div>
                                <div class="tab-list-item-right">
                                    <ul>
                                        <li>Analyze profitability by project or client.</li>
                                        <li>Process payroll.</li>
                                    </ul>
                                </div>
                            </div>
                        </div>

                        <input type="radio" name="tabs" id="tab3" />
                        <label class="label3" for="tab3"><!--<span class="material-icons">lightbulb</span>--> QuickBooks
                            for
                            E-Commerce</label>
                        <div class="tab tab-3">
                            <!-- <h2>Vue</h2> -->
                            <div class="flex-container">
                                <div class="tab-list-item-left">
                                    <ul>
                                        <li>Set up client-specific reports to track financial data.</li>
                                        <li>Bill clients.</li>
                                    </ul>
                                </div>
                                <div class="tab-list-item-right">
                                    <ul>
                                        <li>Manage inventory.</li>
                                        <li>Create profit and loss reports.</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
</code>```

Now, here is my CSS.

```<code>/**
 * Reset
 */
*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  font-family: sans-serif;
  line-height: 1.15;
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
}

body {
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  background-color: #e5e5e5;
  color: #1a1a1a;
  font-family: "Source Sans Pro", sans-serif;
  font-size: 1rem;
  line-height: 1.6;
}

p,
ol,
ul,
li,
dl,
dt,
dd,
blockquote,
figure,
fieldset,
form,
legend,
textarea,
pre,
iframe,
hr,
h1,
h2,
h3,
h4,
h5,
h6 {
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
}

/**
 * Global Rules
 */
h1,
h2,
h3,
h4,
h5,
h6 {
  color: #0d0d0d;
  font-family: Roboto, sans-serif;
  line-height: 1.2;
}

h1 {
  font-size: 40px;
}

h2 {
  font-size: 35px;
}

a,
a:visited {
  background-color: transparent;
  color: #0067b8;
  text-decoration: none;
  border-bottom: 1px dotted;
}

a:hover,
a:active {
  border-bottom: none;
  outline: 0;
}

a:focus {
  border-bottom: none;
  outline: thin dotted;
}

a img {
  border: 0;
}

/**
 * Tabs Container
 */
.tabs-container {
  padding: 0.5rem;
}

/**
 * Tabs Block
 */
.tabs-block {
  display: flex;
  align-items: center;
  justify-content: center;
}

/**
 * Tabs
 */
.tabs {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.tabs label {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 1.5rem;
  margin-right: 0.079rem;
  cursor: pointer;
  /*background-color: #000;*/
  color: #000;
  font-family: Roboto, sans-serif;
  font-size: 0.75rem;
  font-weight: 700;
  transition: background-color ease 0.3s;
  border: 1px solid black;
}

.label1 {
  background-color: #fff;
}

.label2 {
  background-color: #ededed;
}

.tabs .label3 {
  background-color: #cecece;
  padding-left: 51px;
  padding-right: 41px;
}

.tabs label .material-icons {
  margin-right: 0.3rem;
}

.tabs .tab {
  flex-grow: 1;
  width: 100%;
  height: 100%;
  display: none;
  padding: 1rem 2rem 1rem 2rem;
  /*color: #000;*/
  background-color: #fff;
  /*box-shadow: 0 10px 10px rgba(0, 0, 0, 0.4);*/
  border: 1px solid black;
  border-top: none;
}

.tabs .tab-2 {
  background-color: #ededed;
}

.tabs .tab-3 {
  background-color: #cecece;
}

.tabs .tab > *:not(:last-child) {
  margin-bottom: 0.8rem;
}

.tabs [type="radio"] {
  display: none;
}

.tabs [type="radio"]:checked + label {
  /*background-color: #fff;*/
  color: #283841;
  /*border-top: 4px solid #0067b8; */
  /*box-shadow: 0 10px 10px rgba(0, 0, 0, 0.4);*/
}

.tabs [type="radio"]:checked + label + .tab {
  display: block;
}
@media (min-width: 770px) {
  body {
    font-size: 1.125rem;
  }

  .tabs-container {
    padding: 4rem 4rem;
  }

  .tabs label {
    order: 1;
    width: auto;
  }

  .tabs .tab {
    order: 9;
  }

  .tabs [type="radio"]:checked + label {
    border-bottom: none;
  }
}
@media (min-width: 992px) {
  .tabs {
    width: 800px;
  }
}

ul {
  list-style-image: url("https://wordpress-833610-3044148.cloudwaysapps.com/wp-content/uploads/2022/12/Icons-87-18x16-1.png");
}

li {
  padding: 0.5em;
  margin: 1px;
}

.flex-container {
  display: flex;
  flex-direction: row;
}

.tab-list-item-left {
  padding: 3px;
  flex: 50%;
}

.tab-list-item-right {
  padding: 3px;
  flex: 50%;
}
</code>```

Can someone walk me through how to add the chevron images when viewing on a mobile screen?

ContentLicense: CC BY-SA 4.0

Title: Add Chevron Image to Tab on Mobile Size

Body:
I am trying to make a 3-tab layout using CSS that is responsive. I have two issues. The first is the third tab won't line up with the box. It's just a tad bit off.

The second issue is I would like to show chevron images on mobile screens (up to close, down to expand). I am not sure how to do this.

Here is my HTML.

                        <input type="radio" name="tabs" id="tab1" checked="checked" />

                            QuickBooks for
                            Manufacturing & Distribution

Monitor and track inventory.

Create bills of material and work orders.

Set up accurate COGS and inventory costing system.

Assist in inventory assembly setup and implementation.

Capture indirect and direct costs.

Build sales order reports.

Track profit and loss.

                        <input type="radio" name="tabs" id="tab2" />
                         QuickBooks for
                            Professional
                            Services

Track time and expenses.

Set up separate billing rates and customized invoices.

Analyze profitability by project or client.

Process payroll.

                        <input type="radio" name="tabs" id="tab3" />
                         QuickBooks
                            for
                            E-Commerce

Set up client-specific reports to track financial data.

Bill clients.

Manage inventory.

Create profit and loss reports.

Now, here is my CSS.

/**
 * Reset
 */
*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  font-family: sans-serif;
  line-height: 1.15;
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
}

body {
  -webkit-text-size-adjust: 100%;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  background-color: #e5e5e5;
  color: #1a1a1a;
  font-family: "Source Sans Pro", sans-serif;
  font-size: 1rem;
  line-height: 1.6;
}

p,
ol,
ul,
li,
dl,
dt,
dd,
blockquote,
figure,
fieldset,
form,
legend,
textarea,
pre,
iframe,
hr,
h1,
h2,
h3,
h4,
h5,
h6 {
  padding: 0;
  margin: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
}

/**
 * Global Rules
 */
h1,
h2,
h3,
h4,
h5,
h6 {
  color: #0d0d0d;
  font-family: Roboto, sans-serif;
  line-height: 1.2;
}

h1 {
  font-size: 40px;
}

h2 {
  font-size: 35px;
}

a,
a:visited {
  background-color: transparent;
  color: #0067b8;
  text-decoration: none;
  border-bottom: 1px dotted;
}

a:hover,
a:active {
  border-bottom: none;
  outline: 0;
}

a:focus {
  border-bottom: none;
  outline: thin dotted;
}

a img {
  border: 0;
}

/**
 * Tabs Container
 */
.tabs-container {
  padding: 0.5rem;
}

/**
 * Tabs Block
 */
.tabs-block {
  display: flex;
  align-items: center;
  justify-content: center;
}

/**
 * Tabs
 */
.tabs {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.tabs label {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 1.5rem;
  margin-right: 0.079rem;
  cursor: pointer;
  /*background-color: #000;*/
  color: #000;
  font-family: Roboto, sans-serif;
  font-size: 0.75rem;
  font-weight: 700;
  transition: background-color ease 0.3s;
  border: 1px solid black;
}

.label1 {
  background-color: #fff;
}

.label2 {
  background-color: #ededed;
}

.tabs .label3 {
  background-color: #cecece;
  padding-left: 51px;
  padding-right: 41px;
}

.tabs label .material-icons {
  margin-right: 0.3rem;
}

.tabs .tab {
  flex-grow: 1;
  width: 100%;
  height: 100%;
  display: none;
  padding: 1rem 2rem 1rem 2rem;
  /*color: #000;*/
  background-color: #fff;
  /*box-shadow: 0 10px 10px rgba(0, 0, 0, 0.4);*/
  border: 1px solid black;
  border-top: none;
}

.tabs .tab-2 {
  background-color: #ededed;
}

.tabs .tab-3 {
  background-color: #cecece;
}

.tabs .tab > *:not(:last-child) {
  margin-bottom: 0.8rem;
}

.tabs [type="radio"] {
  display: none;
}

.tabs [type="radio"]:checked + label {
  /*background-color: #fff;*/
  color: #283841;
  /*border-top: 4px solid #0067b8; */
  /*box-shadow: 0 10px 10px rgba(0, 0, 0, 0.4);*/
}

.tabs [type="radio"]:checked + label + .tab {
  display: block;
}
@media (min-width: 770px) {
  body {
    font-size: 1.125rem;
  }

  .tabs-container {
    padding: 4rem 4rem;
  }

  .tabs label {
    order: 1;
    width: auto;
  }

  .tabs .tab {
    order: 9;
  }

  .tabs [type="radio"]:checked + label {
    border-bottom: none;
  }
}
@media (min-width: 992px) {
  .tabs {
    width: 800px;
  }
}

ul {
  list-style-image: url("https://wordpress-833610-3044148.cloudwaysapps.com/wp-content/uploads/2022/12/Icons-87-18x16-1.png");
}

li {
  padding: 0.5em;
  margin: 1px;
}

.flex-container {
  display: flex;
  flex-direction: row;
}

.tab-list-item-left {
  padding: 3px;
  flex: 50%;
}

.tab-list-item-right {
  padding: 3px;
  flex: 50%;
}

Can someone walk me through how to add the chevron images when viewing on a mobile screen?


问:
How to read an array inside an array in JSON using python
I am trying to read the "transcript" from my json file and i just can't get inside it. I can access the main JSON but not the specific part of it.

My JSON file

```<code>    "results": [ {
      "alternatives": [ {
        "confidence": 0.90822744,
        "transcript":"bunch of words" ,
        "words": [ {
          "endTime": "1.400s",
          "startTime": "0s",
          "word": "bunch"
        },...
</code>```

My Code snippet

```<code>f =  open('C:\\Users\\Kerem\\Desktop\\YeniGoogleapi\\MugeAnliileTatliSert7Kasim.json', encoding="utf8")
data = json.load(f)

for i in data['results']:
  print(i)
</code>```

Body:
I am trying to read the "transcript" from my json file and i just can't get inside it. I can access the main JSON but not the specific part of it.

My JSON file

    "results": [ {
      "alternatives": [ {
        "confidence": 0.90822744,
        "transcript":"bunch of words" ,
        "words": [ {
          "endTime": "1.400s",
          "startTime": "0s",
          "word": "bunch"
        },...

My Code snippet

f =  open('C:\\Users\\Kerem\\Desktop\\YeniGoogleapi\\MugeAnliileTatliSert7Kasim.json', encoding="utf8")
data = json.load(f)

for i in data['results']:
  print(i)


问:
My keyboard doesn't hover over elements when I tap on a text field in my nativescript app
I am working on creating an application with the Nativescript framework. In my registration page (Clavier.vue), I used the TabView template (from my App.vue) and I put a FlexboxLayout with a height and width of 100% each. Inside I put the text fields and a save button. Problem: When I click on a text field to fill it, the keyboard automatically pops out and the elements at the bottom of my FlexboxLayout move up to be visible. I would like the elements to remain hidden by the android keyboard and only the text field of the form in question to be visible, because my form can include many text fields. Here is the code for the Clavier.vue page: Clavier.vue

Screenshot Keyboard.vue Default Keyboard.vue Here you see that the 3 icons (buttons) of the tabview and the button of the form go up to land at the top of the android keyboard.


问:
How can I apply a ProseMirror (tiptap) transaction to data persisted on the server?
I'm using TipTap to build a document editor. On the server side (node), I've got a postgres db storing tiptap's output as json. My issue is that I'm expecting the content of the editor to get big, and so posting the entire content to the server on each save isn't going to work.

What I'd like to do is take the transactions from tiptap and send them to the server, load the persisted version, apply the transactions, and then persist the result. Does anyone know how I would go about doing this?

It seems that tiptap depends on there being a DOM, so I'm not sure it's possible to load it in node. And even if it was, I'm unclear on how I could apply those transactions, although prosemirror does have the apply and prosemirror-transform commands, which seem promising.

It seems like people would have run into this issue before-any thoughts?

Thanks!


问:
Show copilot inline suggestion together with "regular" auto completion list in vscode
Case1: with inline no autocompletion list

Case2: with autocompletion list no lineline

As in the images, when Vscode triggers "regular" auto suggestion list, it disables the copilot's inline suggestion. Any way we can keep both?

Btw, Nvim has both


问:
Google Sign-in can't call onsuccess function
I want to use Google Sign on my nodejs project. The Google account selection screen is shown and I select my account. But after that console.log is still empty.

What can I do? The codes are below.

```<code><div class="g-signin2" data-onsuccess="onSignIn"></div>
<a href="#" onclick="signOut();">Sign out</a>

<script>

function onSignIn(googleUser) {
    console.log("furkan deneme");
    var profile = googleUser.getBasicProfile();
    console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
    console.log('Name: ' + profile.getName());
    console.log('Image URL: ' + profile.getImageUrl());
    console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    console.log("furkan deneme2");
}
function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function() {
        console.log('User signed out.');
    });
}

</script>
</code>```

head;

```<code>  <meta name="google-signin-scope" content="profile email">
  <meta name="google-signin-client_id" content="xxxxx.apps.googleusercontent.com">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
</code>```

finally, i can not trigger this onsuccess method. and i can not see 'furkan deneme' message on my console

Body:
I want to use Google Sign on my nodejs project. The Google account selection screen is shown and I select my account. But after that console.log is still empty.

What can I do? The codes are below.

Sign out

head;

  <meta name="google-signin-scope" content="profile email">
  <meta name="google-signin-client_id" content="xxxxx.apps.googleusercontent.com">

finally, i can not trigger this onsuccess method. and i can not see 'furkan deneme' message on my console


问:
How do I set laravel 9 to dev after uploading to production?
I've put my fledgeling Laravel/Vue/Axios application into production, but now I can't get my local copy back into dev mode - my changes aren't being applied.

As far as I can remember (after a few trials), to prepare my app for prod, I did the following:

removed 'vendor' and 'public/build' from .gitignore

ran 'php artisan view:cache' and 'php artisan config:cache'

ran 'npm run build' (or were these in the opposite order?)

pushed the project to my server repository and tweaked stuff on the prod version

Now I've been struggling for a couple of days to have any change reflected in the local copy. I've followed the advice I find everywhere (including https://tinkerwell.app/blog/laravel-caches-and-all-ways-to-clear-them)

ran 'php artisan cache:clear'

ran 'php artisan view:clear'

ran 'php artisan config:clear'

checked that my .env has:

APP_ENV=local

APP_DEBUG=true

LOG_LEVEL=debug

ran 'npm run dev' (mistake because I'm using Vue in this project)

ran 'npm run watch'

If I update my browser too soon after making a change, I see the usual 'Vite manifest not found' error, so the 'npm run watch' part is definitely working.

What else do I need to do to have my changes reflected properly?


问:
Nuxt input formula input key value pair
Is there a way to get hashmaps from a form in nuxt?

I'm using nuxt and have a form where I want to receive a hash map where the user is entering a key-value pair that will be parsed to an API.

<template>

</template>

```

If I try to use KEY as the key value and VALUE as the value value

it returns "mapKey": "KEY", "mapValue": "VALUE"

is it possible to change it so it returns "KEY":"VALUE"?

Title: Nuxt input formula input key value pair

Body:
Is there a way to get hashmaps from a form in nuxt?

I'm using nuxt and have a form where I want to receive a hash map where the user is entering a key-value pair that will be parsed to an API.

<template>

</template>

If I try to use KEY as the key value and VALUE as the value value

it returns "mapKey": "KEY", "mapValue": "VALUE"

is it possible to change it so it returns "KEY":"VALUE"?


问:
Refresh whole site after login Woocommerce
In Woocommerce, if a customer is a guest and is NOT logged in and visits a couple of product pages.
He does not see the prices and add to cart button. That is correct. This is like this because of this plugin: https://wordpress.org/plugins/hide-cart-functions/

Now the customer clicks on the account page and loges in.
Then he goes straight back to the product pages he already visited.
The problem is that he now still sees No prices and add to cart button.
The browser has saved the not logged in version of the pages and shows these to the customer after he is logged in.

The client must manually press the F5 button himself, and only then the page will reload and the prices etc. will be shown.

The only plugins I have activated are : WooCommerce, Wordfence Security and Hide Cart Functions
It does not matter which theme I use.
It does not matter if I use a plugin like Hide Cart Functions or another. They all have the same problem.
There is no other cache plugin active on the server.
There is no custom CSS.

Does anyone have any experience with this problem?
Does anyone know a way/code to automatically refresh the whole site AFTER a customer loges in?
Woocommerce does not help.


问:
Places api returns claimed places
i am trying to get a excel file back with all unclaimed GMB profile near me but it returns only a few GMB profiles that are already claimed I can't find anything in the documentation
and this is the only think I have been able to do so far is there a data point I am missing or is it just not a think the API can do</p>
```<code>import googlemaps
import openpyxl
import os

# Google Maps API key
API_KEY = 'API_KEY'

# radius to search for GMB accounts in meters
RADIUS = 5000

# latitude and longitude of search area
LATITUDE = 61.313999
LONGITUDE = 45.432400

# Create a Google Maps client
gmaps = googlemaps.Client(key=API_KEY)

# Search for GMB accounts in radius
places = gmaps.places_nearby(
    location=(LATITUDE, LONGITUDE), radius=RADIUS, type='establishment'
)

# new Excel workbook
workbook = openpyxl.Workbook()
sheet = workbook.active

# Adds the headers to the spreadsheet
sheet.cell(row=1, column=1).value = 'Name'
sheet.cell(row=1, column=2).value = 'Phone Number'
sheet.cell(row=1, column=3).value = 'Place ID'
sheet.cell(row=1, column=4).value = 'Website'
sheet.cell(row=1, column=5).value = 'Claim URL'

# Loops through the GMB accounts
for i, place in enumerate(places['results']):
  # Check if the account is unclaimed
  if 'website' not in place:
    # Add the information to the spreadsheet
    sheet.cell(row=i+2, column=1).value = place['name']
    sheet.cell(row=i+2, column=3).value = place['place_id']
    sheet.cell(row=i+2, column=5).value = f'https://business.google.com/manage/#/details/{place["place_id"]}/claim'

# Save the workbook to the current directory
workbook.save(os.path.join(os.getcwd(), 'unclaimed_gmb_accounts.xlsx'))
</code>```

Title: Places api returns claimed places

Body:
i am trying to get a excel file back with all unclaimed GMB profile near me but it returns only a few GMB profiles that are already claimed I can't find anything in the documentation
and this is the only think I have been able to do so far is there a data point I am missing or is it just not a think the API can do

import googlemaps
import openpyxl
import os

# Google Maps API key
API_KEY = 'API_KEY'

# radius to search for GMB accounts in meters
RADIUS = 5000

# latitude and longitude of search area
LATITUDE = 61.313999
LONGITUDE = 45.432400

# Create a Google Maps client
gmaps = googlemaps.Client(key=API_KEY)

# Search for GMB accounts in radius
places = gmaps.places_nearby(
    location=(LATITUDE, LONGITUDE), radius=RADIUS, type='establishment'
)

# new Excel workbook
workbook = openpyxl.Workbook()
sheet = workbook.active

# Adds the headers to the spreadsheet
sheet.cell(row=1, column=1).value = 'Name'
sheet.cell(row=1, column=2).value = 'Phone Number'
sheet.cell(row=1, column=3).value = 'Place ID'
sheet.cell(row=1, column=4).value = 'Website'
sheet.cell(row=1, column=5).value = 'Claim URL'

# Loops through the GMB accounts
for i, place in enumerate(places['results']):
  # Check if the account is unclaimed
  if 'website' not in place:
    # Add the information to the spreadsheet
    sheet.cell(row=i+2, column=1).value = place['name']
    sheet.cell(row=i+2, column=3).value = place['place_id']
    sheet.cell(row=i+2, column=5).value = f'https://business.google.com/manage/#/details/{place["place_id"]}/claim'

# Save the workbook to the current directory
workbook.save(os.path.join(os.getcwd(), 'unclaimed_gmb_accounts.xlsx'))


问:
Which test strategy to use mock data or context autowired in spring boot
I am in confusion about selecting JUnit testing strategy as I can use both

Mockito to use mock objects

Use Spring context load and @Autowired to test(integration too)

if I would be given both option then which one to use in what scenario

eg:

mock way

```<code> @SpringBootTest
 class AccountFormDelegateTest {
     @Autowired
     private AccountFormDelegate accountFormDelegate;
     @Test
     final void testExecute() {
         try {
             accountFormDelegate.execute(execution);
             verify(execution, times(1)).getVariable("orderReference");
         } catch (Exception e) {
             e.printStackTrace();
             fail();
         }
     }
 }
</code>```

spring context load way

```<code>        @ExtendWith(MockitoExtension.class)
        class AccountFormDelegateTest {
            @InjectMocks
            private AccountFormDelegate accountFormDelegate;
            @Mock
            private AddressDetails postalAddress;
            @Test
            final void testExecute() {
                try {
                    List<AddlAttributes> addAttribute = new ArrayList<AddlAttributes>();
                    when(postalAddress.getAddlOrderAttribute(customerOrder.getSiteOrders().get(0))).thenReturn(addAttribute);
                    accountFormDelegate.execute(execution);
                    verify(execution, times(1)).getVariable("orderReference");
                } catch (Exception e) {
                    e.printStackTrace();
                    fail();
                }
            }
        }
</code>```

need suggestion

Body:
I am in confusion about selecting JUnit testing strategy as I can use both

Mockito to use mock objects

Use Spring context load and @Autowired to test(integration too)

if I would be given both option then which one to use in what scenario

eg:

mock way

 @SpringBootTest
 class AccountFormDelegateTest {
     @Autowired
     private AccountFormDelegate accountFormDelegate;
     @Test
     final void testExecute() {
         try {
             accountFormDelegate.execute(execution);
             verify(execution, times(1)).getVariable("orderReference");
         } catch (Exception e) {
             e.printStackTrace();
             fail();
         }
     }
 }

spring context load way

        @ExtendWith(MockitoExtension.class)
        class AccountFormDelegateTest {
            @InjectMocks
            private AccountFormDelegate accountFormDelegate;
            @Mock
            private AddressDetails postalAddress;
            @Test
            final void testExecute() {
                try {
                    List<AddlAttributes> addAttribute = new ArrayList<AddlAttributes>();
                    when(postalAddress.getAddlOrderAttribute(customerOrder.getSiteOrders().get(0))).thenReturn(addAttribute);
                    accountFormDelegate.execute(execution);
                    verify(execution, times(1)).getVariable("orderReference");
                } catch (Exception e) {
                    e.printStackTrace();
                    fail();
                }
            }
        }

need suggestion


问:
Integrating google Speech Listener on Samsung Galaxy 4
We developed an app that needs to work on all smartwatches with wearOS. The app is installed on Ticwatch and it works perfectly well.

In the same app, with the same wearOS version, we are facing an issue on Samsung smartwatch Galaxy 4 with a speech listener.
We get the following error:

```<code>E/SpeechRecognizer: no selected voice recognition service
</code>```

(The smartwatch is properly installed with all the latest versions)

does anyone have an idea, of what can it be or what we need to do in order to make it work on Samsung Galaxy 4 and 5?

Body:
We developed an app that needs to work on all smartwatches with wearOS. The app is installed on Ticwatch and it works perfectly well.

In the same app, with the same wearOS version, we are facing an issue on Samsung smartwatch Galaxy 4 with a speech listener.
We get the following error:

E/SpeechRecognizer: no selected voice recognition service

(The smartwatch is properly installed with all the latest versions)

does anyone have an idea, of what can it be or what we need to do in order to make it work on Samsung Galaxy 4 and 5?


问:
How to get the height and width of chrome devtools?

Is there any way to know the height and width of Chromedevtool when it docked to the bottom?

when it's docked to left or right , I can use window.outerWidth - window.innerWidth to get the width of it,sothat I can use some script to move devtoolpanel to right or left only by keyboard(not use a mouse). but when it's docked to bottom, How to get the size of it?


问:
Importing JS modules into TS app: d.ts is not a module error
I'm new to Typescript and am trying to migrate an existing JS application into it. I'm trying to follow instructions from https://www.typescriptlang.org/docs/handbook/modules.html to import JS files without having to convert them to TS (yet).

In the following file (index.tsx) I'm trying to import a JS module (sugg.js) - I don't want to convert this to TS yet, so have set up a declaration file for it (sugg.d.ts):

```<code>/// <reference path="../utils/sugg.d.ts"/>
import { populateSugg} from '../utils/sugg.ts';
</code>```

However I get the following errors on this:

```<code>File '/utils/sugg.d.ts' is not a module.ts(2306)
</code>```

I've set up the declaration file as below:

```<code>//sugg.d.ts
declare module sugg {
    export function populateSugg} (
        scope: string,
        value: string,
        property?: string
    ): string;
}
</code>```

'sugg.js' contains the following function (among others):

```<code>const populateSugg = (scope, value, property) => {
    //Do things
    return updatedVal;
}

...

export {
    ...
    populateSugg
}
</code>```

Can anyone suggest where I'm going wrong?

Body:
I'm new to Typescript and am trying to migrate an existing JS application into it. I'm trying to follow instructions from https://www.typescriptlang.org/docs/handbook/modules.html to import JS files without having to convert them to TS (yet).

In the following file (index.tsx) I'm trying to import a JS module (sugg.js) - I don't want to convert this to TS yet, so have set up a declaration file for it (sugg.d.ts):

/// <reference path="../utils/sugg.d.ts"/>
import { populateSugg} from '../utils/sugg.ts';

However I get the following errors on this:

File '/utils/sugg.d.ts' is not a module.ts(2306)

I've set up the declaration file as below:

//sugg.d.ts
declare module sugg {
    export function populateSugg} (
        scope: string,
        value: string,
        property?: string
    ): string;
}

'sugg.js' contains the following function (among others):

const populateSugg = (scope, value, property) => {
    //Do things
    return updatedVal;
}

...

export {
    ...
    populateSugg
}

Can anyone suggest where I'm going wrong?


问:
Data appear in Chrome but not in Cypress test runner
My problem is that when im opening website on my computer by chorme everything works fine. But when im using Cypress cy.visit() to reach this endpoint by Cypress test runner, the data not appear..

in runner i always get Null response and have no idea why.

ill try to wait for page to load but its not working. click for module im interested, post and get endpoint. nothing works, table in test runner still opens empty


问:
Pandas - Calculate lookback period based on threshold condition
I have the following inefficient loop that I'd like to clean up.  We lookback over the data while a condition is true and count the number of times a threshold condition is met.

Input variables are x and a, the desired/correct output is countA.

x
a
countA

1.00
0
0

1.00
4
0

0.75
8
1

1.00
0
1

0.75
1
1

0.75
9
2

0.75
4
2

0.50
1
1

0.75
0
2

0.75
0
2

1.00
2
0

0.75
3
2

0.75
0
2

1.00
0
0

0.75
1
2

0.75
6
3

0.50
5
2

```<code>import pandas as pd
import numpy as np

df = pd.read_csv('input.csv')

lb = 0.25
thres = 5
df['countA'] = np.nan

for i in reversed(df.index):
    j = 0
    countA = 0

    while abs(df['x'][i] - df['x'][i - j]) <= lb:
        if i <= j:
            break
        if df['a'][i - j] >= thres:
            countA+=1
        j+=1

    df['countA'][i] = countA
</code>```

Body:
I have the following inefficient loop that I'd like to clean up.  We lookback over the data while a condition is true and count the number of times a threshold condition is met.

Input variables are x and a, the desired/correct output is countA.

x
a
countA

1.00
0
0

1.00
4
0

0.75
8
1

1.00
0
1

0.75
1
1

0.75
9
2

0.75
4
2

0.50
1
1

0.75
0
2

0.75
0
2

1.00
2
0

0.75
3
2

0.75
0
2

1.00
0
0

0.75
1
2

0.75
6
3

0.50
5
2

import pandas as pd
import numpy as np

df = pd.read_csv('input.csv')

lb = 0.25
thres = 5
df['countA'] = np.nan

for i in reversed(df.index):
    j = 0
    countA = 0

    while abs(df['x'][i] - df['x'][i - j]) <= lb:
        if i <= j:
            break
        if df['a'][i - j] >= thres:
            countA+=1
        j+=1

    df['countA'][i] = countA


问:
how to reference an already filtered table in jquery
I'm filtering an html table using jquery, I have a filter for every column and it works just fine, but right now if I filter the second column after filtering the first one (example), it refilters the entire table and I want it to filter the already filtered table.

Here is the table.

```<code> while($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td class='table-row'>" . $row["conditions"] . "</td>
                    <td class='table-row'>" . $row["modelYears"] . "</td>
                    <td class='table-row'>" . $row["makes"] . "</td>
                    <td class='table-row'>" . $row["models"] . "</td>
                    <td class='table-row'>" . $row["contactNumbers"] . "</td>
                    <td class='table-row'>" . $row["supplierName"] . "</td>
                    <td class='table-row'>" . $row["supplierAddress"] . "</td>
                    <td class='table-row'>" . $row["supplierFullAddress"] . "</td>
                    <td class='table-row'>" . $row["supplierComment"] . "</td>
                </tr>";
        }
</code>```

Here are 3 examples of the input fields in thead.

```<code> <th><input id="con" type="text" placeholder="condition"></th>
 <th><input id="cyears" type="text" placeholder="modelyears"></th>
 <th><input id="cmakes" type="text" placeholder="makes"></th>
</code>```

Here are two examples of the script I'm using to filter each column.

```<code>$(document).ready(function() {
                $("#con").on("keyup", function() {
                    var value = $(this).val().toLowerCase();
                    $("#geeks tr").filter(function() {
                        $(this).toggle($(this.children[0]).text()
                        .toLowerCase().indexOf(value) > -1)
                    });
                });
            });
            $(document).ready(function() {
                $("#cyears").on("keyup", function() {
                    var value = $(this).val().toLowerCase();
                    $("#geeks tr").filter(function() {
                        $(this).toggle($(this.children[1]).text()
                        .toLowerCase().indexOf(value) > -1)
                    });
                });
            });
</code>```

is there a way I can reference the already filtered table?

Body:
I'm filtering an html table using jquery, I have a filter for every column and it works just fine, but right now if I filter the second column after filtering the first one (example), it refilters the entire table and I want it to filter the already filtered table.

Here is the table.

 while($row = $result->fetch_assoc()) {
            echo "

                    " . $row["conditions"] . "
                    " . $row["modelYears"] . "
                    " . $row["makes"] . "
                    " . $row["models"] . "
                    " . $row["contactNumbers"] . "
                    " . $row["supplierName"] . "
                    " . $row["supplierAddress"] . "
                    " . $row["supplierFullAddress"] . "
                    " . $row["supplierComment"] . "

";
        }

Here are 3 examples of the input fields in thead.

 <input id="con" type="text" placeholder="condition">
 <input id="cyears" type="text" placeholder="modelyears">
 <input id="cmakes" type="text" placeholder="makes">

Here are two examples of the script I'm using to filter each column.

$(document).ready(function() {
                $("#con").on("keyup", function() {
                    var value = $(this).val().toLowerCase();
                    $("#geeks tr").filter(function() {
                        $(this).toggle($(this.children[0]).text()
                        .toLowerCase().indexOf(value) > -1)
                    });
                });
            });
            $(document).ready(function() {
                $("#cyears").on("keyup", function() {
                    var value = $(this).val().toLowerCase();
                    $("#geeks tr").filter(function() {
                        $(this).toggle($(this.children[1]).text()
                        .toLowerCase().indexOf(value) > -1)
                    });
                });
            });

is there a way I can reference the already filtered table?


问:
Is it possible to write a generic trigger for all tables in Postgres?
I want to listen to every transaction that is recorded in the database And I noticed that there is a concept in Postgres under the title LISTEN and NOTIFY (Of course, I am not sure that this is the right way)

Now I want to write a trigger that sends a notification to the channel when any operation occurs in any table

Is it possible?

My way is right?

thanks

Postgres TRIGGER to call NOTIFY with a JSON payload


问:
Unable to import MySQL Connector using PyCharm
```<code>import mysql.connector
</code>```

I was trying to make a database using python. I used the code shown below after the installation of MySQL-connector-python to the python interpreter, but the following output shows in the terminal:

```<code>Traceback (most recent call last):
  File "F:\coding\sql-course-materials\SQL Course Materials\mysql.py", line 1, in <module>
    import mysql.connector
  File "F:\coding\sql-course-materials\SQL Course Materials\mysql.py", line 1, in <module>
    import mysql.connector
ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package
</code>```

Body:
import mysql.connector

I was trying to make a database using python. I used the code shown below after the installation of MySQL-connector-python to the python interpreter, but the following output shows in the terminal:

Traceback (most recent call last):
  File "F:\coding\sql-course-materials\SQL Course Materials\mysql.py", line 1, in <module>
    import mysql.connector
  File "F:\coding\sql-course-materials\SQL Course Materials\mysql.py", line 1, in <module>
    import mysql.connector
ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package


问:
Python <Response [503]> ms grap api: how to retry upload after 503 error when uploading file to OneDrive?
I am uploading home-drive files pro-grammatically to One-drive business using the ms graph API. I'm uploading large files in chunks and a chunk upload fails after running the script almost 6 to 7 hours returning the code 503 at this point:
below are the code error......

```<code><Response [503]>
uploading large files /abc\abc (2)\dwnlds\controllermagazin_052017.pdf.....
Traceback (most recent call last):
  File "c:\Users\abc\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\abc\Downloads\MigrationOfHomedriveToOnedrive\MigrationOfHomedriveToOnedrive\main.py", line 195, in <module>
    HomeDriveMove()
  File "C:\Users\abc\Downloads\MigrationOfHomedriveToOnedrive\MigrationOfHomedriveToOnedrive\main.py", line 173, in HomeDriveMove
    print(chunk_data_upload.json())
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

How to solve this issue?? any help would be highly appreciated.

Body:
I am uploading home-drive files pro-grammatically to One-drive business using the ms graph API. I'm uploading large files in chunks and a chunk upload fails after running the script almost 6 to 7 hours returning the code 503 at this point:
below are the code error......

<Response [503]>
uploading large files /abc\abc (2)\dwnlds\controllermagazin_052017.pdf.....
Traceback (most recent call last):
  File "c:\Users\abc\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\abc\Downloads\MigrationOfHomedriveToOnedrive\MigrationOfHomedriveToOnedrive\main.py", line 195, in <module>
    HomeDriveMove()
  File "C:\Users\abc\Downloads\MigrationOfHomedriveToOnedrive\MigrationOfHomedriveToOnedrive\main.py", line 173, in HomeDriveMove
    print(chunk_data_upload.json())
  File "C:\Users\abc\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How to solve this issue?? any help would be highly appreciated.


问:
.NET MAUI: How to add an XAML page as the content of a Syncfusion sfTabItem
I'm using Syncfusion's sfTabView for my MAUI app and I have the content of all my tabs set as Pages from seperate files to avoid my main page being 1000+ lines long.

The problem is that sfTabItems do not directly support Pages as content so I have them wrapped in a grid, which works in debug mode, but crashes on start if I run it not in debug mode. Is there a workaround for this?

```<code>xmlns:views="clr-namespace:MyProject.Views"
xmlns:tabView="clr-namespace:Syncfusion.Maui.TabView;assembly=Syncfusion.Maui.TabView"

<tabView:SfTabView>
    <tabView:SfTabView.Items>
        <tabView:SfTabItem>
            <tabView:SfTabItem.Content> <!-- content does not directly support ContentPages -->
                <Grid>
                    <views:HomePage /> <!-- allowed (in debug) when wrapped in a grid -->
                </Grid>
            </tabView:SfTabItem.Content>
        </tabView:SfTabItem>
    </tabView:SfTabView.Items>
</tabView:SfTabView>
</code>```

The first error in my device log is as follows:

```<code>Time    Device Name Type    PID Tag Message
12-20 11:32:44.439  pixel_5_-_api_29    Error   4343        * Assertion: should not be reached at /__w/1/s/src/mono/mono/mini/mini-exceptions.c:456
</code>```

Followed by:

```<code>Time    Device Name Type    PID Tag Message
12-20 11:32:44.439  pixel_5_-_api_29    Error   4343    libc    Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 4343 (.myproject), pid 4343 (.myproject)
</code>```

Body:
I'm using Syncfusion's sfTabView for my MAUI app and I have the content of all my tabs set as Pages from seperate files to avoid my main page being 1000+ lines long.

The problem is that sfTabItems do not directly support Pages as content so I have them wrapped in a grid, which works in debug mode, but crashes on start if I run it not in debug mode. Is there a workaround for this?

xmlns:views="clr-namespace:MyProject.Views"
xmlns:tabView="clr-namespace:Syncfusion.Maui.TabView;assembly=Syncfusion.Maui.TabView"

<tabView:SfTabView>
    <tabView:SfTabView.Items>
        <tabView:SfTabItem>
            <tabView:SfTabItem.Content>
                <Grid>
                    <views:HomePage />
                </Grid>
            </tabView:SfTabItem.Content>
        </tabView:SfTabItem>
    </tabView:SfTabView.Items>
</tabView:SfTabView>

The first error in my device log is as follows:

Time    Device Name Type    PID Tag Message
12-20 11:32:44.439  pixel_5_-_api_29    Error   4343        * Assertion: should not be reached at /__w/1/s/src/mono/mono/mini/mini-exceptions.c:456

Followed by:

Time    Device Name Type    PID Tag Message
12-20 11:32:44.439  pixel_5_-_api_29    Error   4343    libc    Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 4343 (.myproject), pid 4343 (.myproject)


问:
Create empty directories with cloud_init
I am trying to configure an user account using one cloud-init yaml file that include a call to write_files module, like this:

write_files:
#passwd file for vncserver
- path: /home/ubuntu/.vnc/passwd
  owner: ubuntu:ubuntu
  permissions: '0600'
  defer: true
  encoding: b64
  content: bmtzZGN1eQo=
```
<p>The file is created as expected, but the problem is that the parent directory is owned by root, and not by ubuntu user.</p>
```$ ls -la .vnc/
total 12
drwxr-xr-x 2 root   root   4096 Dec 20 16:24 .
drwxr-x--- 5 ubuntu ubuntu 4096 Dec 20 16:24 ..
-rw------- 1 ubuntu ubuntu    8 Dec 20 16:24 passwd
```
<p>I tried to manually create the /home/ubuntu/.vnc/ directory prior to create the passwd file to be able to set the ownership of the directory, just to find that documentation of write_files does not explain how to create (empty) directories.</p>
<p>I know that I could do this using <code>runcmd</code> module to insert a command like this:</p>
<pre class="lang-yaml prettyprint-override"><code>runcmd:
  - mkdir --mode 0600 --parents /home/ubuntu/.vnc
  - echo bmtzZGN1eQo | base64 -d > /home/ubuntu/.vnc/passwd
  - chmod 0600 /home/ubuntu/.vnc/passwd
</code>```

but this seems to be too complex to do such small task.

It is possible to use write_files module to create directories or change ownership/permission of existing directories?

Body:
I am trying to configure an user account using one cloud-init yaml file that include a call to write_files module, like this:

write_files:
#passwd file for vncserver
- path: /home/ubuntu/.vnc/passwd
  owner: ubuntu:ubuntu
  permissions: '0600'
  defer: true
  encoding: b64
  content: bmtzZGN1eQo=

The file is created as expected, but the problem is that the parent directory is owned by root, and not by ubuntu user.

$ ls -la .vnc/
total 12
drwxr-xr-x 2 root   root   4096 Dec 20 16:24 .
drwxr-x--- 5 ubuntu ubuntu 4096 Dec 20 16:24 ..
-rw------- 1 ubuntu ubuntu    8 Dec 20 16:24 passwd

I tried to manually create the /home/ubuntu/.vnc/ directory prior to create the passwd file to be able to set the ownership of the directory, just to find that documentation of write_files does not explain how to create (empty) directories.

I know that I could do this using runcmd module to insert a command like this:

runcmd:
  - mkdir --mode 0600 --parents /home/ubuntu/.vnc
  - echo bmtzZGN1eQo | base64 -d > /home/ubuntu/.vnc/passwd
  - chmod 0600 /home/ubuntu/.vnc/passwd

but this seems to be too complex to do such small task.

It is possible to use write_files module to create directories or change ownership/permission of existing directories?


问:
When reload the page all data disappears in the page in ReactJS
Uncaught TypeError: Cannot read properties of null (reading 'imageLink')

The above error occurred in the <ProductMoreDetails> component:

This Products page Display all the products in the database. When I click on any product card it will redirects to the more details page of that product. First time it loads without any issue and when I refresh the page or backward the page it will disappear all the content in the page.

ProductMoreDetails.js

```<code>import Navbar from "../components/Navbar";
import { useProductsContext } from "../hooks/useProductsContext";
import { useParams } from "react-router-dom";
import { useEffect } from "react";

//setproducts
const ProductMoreDetails = () => {
    const {products,dispatch} = useProductsContext();
    const {id} = useParams();

    useEffect(() => {
        const  fetchProducts = async () => {
            const response = await fetch(`/api/products/${id}`)
            const json = await response.json()

            if (response.ok) {
                dispatch({type: 'SET_PRODUCTS', payload: json})
            }
        }
        fetchProducts()
    },[dispatch,id])

    return (
        <div className="moredetails">
            <Navbar/>
            <br /><br />

            <div className="details">
                <img className="productImage" src={products.imageLink} alt="productImage" />
                <div className="details-section"></div>
                <div className="row section1">
                    <div className="col-lg-8">
                    </div>
                    <div className="col-lg-2">
                        <button className="btn btn-primary addnew">Add to Cart</button>
                    </div>

                </div>
                <div className="row section1">
                    <div className="col-lg-8">
                        <h1>{products.productName}</h1>
                    </div>
                    <div className="col-lg-2">
                        <h1>Rs. {products.price}</h1>
                    </div>

                </div>

                <div className="section1">
                <hr />

                    <h1>Product Details</h1>
                    <br />
                <div className="row">
                    <div className="col-lg-6">
                        <div className="row">
                            <div className="col-lg-6">
                                <h6>Category</h6>
                            </div>
                            <div className="col-lg-6">
                                <p>{products.category}</p>
                            </div>
                        </div>
                    </div>
                    <div className="col-lg-6">
                        <div className="row">
                            <div className="col-lg-6">
                                <h6>Brand</h6>
                            </div>
                            <div className="col-lg-6">
                                <p>{products.brand}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <br />

                <div className="row">
                    <div className="col-lg-6">
                        <div className="row">
                            <div className="col-lg-6">
                                <h6>Model</h6>
                            </div>
                            <div className="col-lg-6">
                                <p>{products.model}</p>
                            </div>
                        </div>
                    </div>
                    <div className="col-lg-6">
                        <div className="row">
                            <div className="col-lg-6">
                                <h6>Year</h6>
                            </div>
                            <div className="col-lg-6">
                                <p>{products.year}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <br />
                <div className="row">
                    <div className="col-lg-6">
                        <div className="row">
                            <div className="col-lg-6">
                                <h6>Features</h6>
                            </div>
                            <div className="col-lg-6">
                                <p>{products.features}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <hr />
                <div className="section2">
                    <h1>Product Description</h1>
                </div>
                    <p>
                        {products.description}
                    </p>
                </div>
            </div>

        </div>

    )
}

export default ProductMoreDetails;
</code>```

ProductContext.js

```<code>import { createContext } from "react";
import { useReducer } from "react";

export const ProductsContext = createContext();

export const productsReducer = (state, action) => {
    switch (action.type) {
        // set products
        case "SET_PRODUCTS":
            return {
                ...state,
                products: action.payload,
            }
        //set a single product
        case "SET_PRODUCT":
            return {
                ...state,
                products: action.payload,
            }

        case 'CREATE_PRODUCT':
            return {
                products: [action.payload, ...state.products]
            }
        case 'DELETE_PRODUCT':
            return {
                products: state.products.filter((product) => product._id !== action.payload._id)
            }
        case 'UPDATE_PRODUCT':
            return {
                products: state.products.map((product) => product._id === action.payload._id ? action.payload : product)
            }
        default:
            return state;
    }
}

export const ProductsContextProvider = ({ children }) => {
    const [state, dispatch] = useReducer(productsReducer, {
        products: null
    })

    return (
        <ProductsContext.Provider value={{...state, dispatch}}>
            { children }
        </ProductsContext.Provider>
    )
}

</code>```

Body:
Uncaught TypeError: Cannot read properties of null (reading 'imageLink')

The above error occurred in the <ProductMoreDetails> component:

This Products page Display all the products in the database. When I click on any product card it will redirects to the more details page of that product. First time it loads without any issue and when I refresh the page or backward the page it will disappear all the content in the page.

ProductMoreDetails.js

import Navbar from "../components/Navbar";
import { useProductsContext } from "../hooks/useProductsContext";
import { useParams } from "react-router-dom";
import { useEffect } from "react";

//setproducts
const ProductMoreDetails = () => {
    const {products,dispatch} = useProductsContext();
    const {id} = useParams();

    useEffect(() => {
        const  fetchProducts = async () => {
            const response = await fetch(`/api/products/${id}`)
            const json = await response.json()

            if (response.ok) {
                dispatch({type: 'SET_PRODUCTS', payload: json})
            }
        }
        fetchProducts()
    },[dispatch,id])

    return (

            <Navbar/>

                        <button className="btn btn-primary addnew">Add to Cart</button>

{products.productName}

Rs. {products.price}

Product Details

Category

{products.category}

Brand

{products.brand}

Model

{products.model}

Year

{products.year}

Features

{products.features}

Product Description

                        {products.description}

    )
}

export default ProductMoreDetails;

ProductContext.js

import { createContext } from "react";
import { useReducer } from "react";

export const ProductsContext = createContext();

export const productsReducer = (state, action) => {
    switch (action.type) {
        // set products
        case "SET_PRODUCTS":
            return {
                ...state,
                products: action.payload,
            }
        //set a single product
        case "SET_PRODUCT":
            return {
                ...state,
                products: action.payload,
            }

        case 'CREATE_PRODUCT':
            return {
                products: [action.payload, ...state.products]
            }
        case 'DELETE_PRODUCT':
            return {
                products: state.products.filter((product) => product._id !== action.payload._id)
            }
        case 'UPDATE_PRODUCT':
            return {
                products: state.products.map((product) => product._id === action.payload._id ? action.payload : product)
            }
        default:
            return state;
    }
}

export const ProductsContextProvider = ({ children }) => {
    const [state, dispatch] = useReducer(productsReducer, {
        products: null
    })

    return (
        <ProductsContext.Provider value={{...state, dispatch}}>
            { children }
        </ProductsContext.Provider>
    )
}


问:
MariaDb Begin End in a multi-value Insert
Im using MariaDb and Im trying to execute a multi-value insert query using Begin End and I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END' at line 1  0.000 sec

```<code>BEGIN;
INSERT INTO Client (Id, Name, Total)
VALUES
(1, 'John', 1000),
(2, 'Mary', 3000),
(3, 'Mike', 14000),
(4, 'George', 15000);
END;
</code>```

Can I use Begin, End with a multi-value insert and if yes what is the correct syntax here?

I have millions of data to insert. the above is just a small sample of my dataset

Body:
Im using MariaDb and Im trying to execute a multi-value insert query using Begin End and I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END' at line 1  0.000 sec

BEGIN;
INSERT INTO Client (Id, Name, Total)
VALUES
(1, 'John', 1000),
(2, 'Mary', 3000),
(3, 'Mike', 14000),
(4, 'George', 15000);
END;

Can I use Begin, End with a multi-value insert and if yes what is the correct syntax here?

I have millions of data to insert. the above is just a small sample of my dataset


问:
Spark : dataframe - how to properly parallelize the execution
I have a Spark Streaming application that reads from Kafka with a batch interval of 5 minutes

My application stores the input in a DataFrame, and is configured to execute aggregation queries on the dataframe (~ 1000 queries)

Current solution: from the driver I execute a "for loop" on the list of 1000 queries and execute them.

Problem: I have a hundred queries to execute and it takes a huge amount of time for my application.

Is there a way to make this process more faster ?

```<code>        SparkConf sparkConf = new SparkConf();

        messagesFromKafka.foreachRDD((VoidFunction2<JavaRDD<String>, Time>) (rdd, time) -> {

            //...
            SparkSession spark = JavaSparkSessionSingleton.getInstance(sparkConf);

            // Convert RDD[String]
            JavaRDD<Bean> rddRow = rdd.map((Function<String, Bean>) line -> {

               Bean row = new Bean();

               row.setFiled1(line.split(";")[0]);
               row.setFiled2(line.split(";")[1]);
               //..
               return row;

            });

            // ...
            Dataset<Bean> ds = spark.createDataFrame(rddRow, Bean.class);

            // Prepare List of query ...
            List<String> listQuery = new ArrayList<>();
            listQuery.add("select sum(..)  group by filed1...");
            listQuery.add("select avg (..) group by field2...");

            // perform aggregation with key query
            for (String query : listQuery) {
                Dataset<Bean> dsResult = spark.sql(query);
            }

        }
</code>```

Body:
I have a Spark Streaming application that reads from Kafka with a batch interval of 5 minutes

My application stores the input in a DataFrame, and is configured to execute aggregation queries on the dataframe (~ 1000 queries)

Current solution: from the driver I execute a "for loop" on the list of 1000 queries and execute them.

Problem: I have a hundred queries to execute and it takes a huge amount of time for my application.

Is there a way to make this process more faster ?

        SparkConf sparkConf = new SparkConf();

        messagesFromKafka.foreachRDD((VoidFunction2<JavaRDD<String>, Time>) (rdd, time) -> {

            //...
            SparkSession spark = JavaSparkSessionSingleton.getInstance(sparkConf);

            // Convert RDD[String]
            JavaRDD<Bean> rddRow = rdd.map((Function<String, Bean>) line -> {

               Bean row = new Bean();

               row.setFiled1(line.split(";")[0]);
               row.setFiled2(line.split(";")[1]);
               //..
               return row;

            });

            // ...
            Dataset<Bean> ds = spark.createDataFrame(rddRow, Bean.class);

            // Prepare List of query ...
            List<String> listQuery = new ArrayList<>();
            listQuery.add("select sum(..)  group by filed1...");
            listQuery.add("select avg (..) group by field2...");

            // perform aggregation with key query
            for (String query : listQuery) {
                Dataset<Bean> dsResult = spark.sql(query);
            }

        }


问:
Vue: How to test function within another function with Vitest
So I have this function inside my Vue Component:

```<code>function openLink(event: Event, url: string, type: string) {
  switch (type) {
    case 'onetype':
    case 'twotype':
      event.preventDefault()
      openURLInBrowser(url, '_blank');
      break
  }
}
</code>```

I am writing my unit test with Vitest. I can easily test, if openLink have been called:

```<code>const wrapper = shallowMount(MyLinks, {
    propsData: {
       myLinks: linkDataStructure
    }
})

const a = wrapper.find('a');
const openLink= vi.spyOn(wrapper.vm, 'openLink')

await a.trigger('click');
expect(openLink).toHaveBeenCalled()
</code>```

This works great. Now I need to test the case, if type is onetype, the method openURLInBrowser is called. So basically the switchcase inside the openLink function.

If I use following, I get: openURLInBrowser does not exist.

```<code>const openLink= vi.spyOn(wrapper.vm, 'openURLInBrowser')
</code>```

How can I access this method inside the function to test it?

Note: The function openURLInBrowser is imported from a openURLInBrowser.ts-File.

Body:
So I have this function inside my Vue Component:

function openLink(event: Event, url: string, type: string) {
  switch (type) {
    case 'onetype':
    case 'twotype':
      event.preventDefault()
      openURLInBrowser(url, '_blank');
      break
  }
}

I am writing my unit test with Vitest. I can easily test, if openLink have been called:

const wrapper = shallowMount(MyLinks, {
    propsData: {
       myLinks: linkDataStructure
    }
})

const a = wrapper.find('a');
const openLink= vi.spyOn(wrapper.vm, 'openLink')

await a.trigger('click');
expect(openLink).toHaveBeenCalled()

This works great. Now I need to test the case, if type is onetype, the method openURLInBrowser is called. So basically the switchcase inside the openLink function.

If I use following, I get: openURLInBrowser does not exist.

const openLink= vi.spyOn(wrapper.vm, 'openURLInBrowser')

How can I access this method inside the function to test it?

Note: The function openURLInBrowser is imported from a openURLInBrowser.ts-File.


问:
mat-table: checking selection length by value change
I would like to have a function where I can check the length of selected checkboxes every time it changes.

like this:

```<code>this.selection.selected.length.valueChanges
.subscribe(
    () => ...
)
</code>```

https://stackblitz.com/edit/angular-mat-table-with-selection-checkbox?file=app/table-selection-example.html

Body:
I would like to have a function where I can check the length of selected checkboxes every time it changes.

like this:

this.selection.selected.length.valueChanges
.subscribe(
    () => ...
)

https://stackblitz.com/edit/angular-mat-table-with-selection-checkbox?file=app/table-selection-example.html


问:
How to mock and test date-fns submodule with Jest
I'm trying to write a test for a utility function in our project, which uses the formatDuration module from date-fns/formatDuration. Can anyone help me creating a mock for this module with Jest and be able to test if formatDuration was called with expected arguments?

This is my current setup:

// ../utilites/date.ts
import formatDuration from "date-fns/formatDuration";
import subSeconds from "date-fns/subSeconds";
import intervalToDuration from "date-fns/intervalToDuration";

export const createDurationFromSeconds = (seconds: number) => {
  const end = new Date();

  const start = subSeconds(end, seconds);
  return intervalToDuration({ start, end });
};

type FunctionArgs = Parameters<typeof formatDuration>;

export const formatDurationHelper = (
  duration: FunctionArgs[0],
  options?: FunctionArgs[1]
) => {
  //...do something with options.format

  return formatDuration(duration, options);
};
```
<pre class="lang-ts prettyprint-override"><code>// ../utilites/date.test.ts
import formatDuration from "date-fns/formatDuration";
import { formatDurationHelper, createDurationFromSeconds } from "./date";

jest.mock("date-fns/formatDuration", () => {
  return {
    __esModule: true,
    default: jest.fn()
  };
});

describe("formatDurationWithLocale", () => {
  it("created mocked formatDuration", () => {
    expect(jest.isMockFunction(formatDuration)).toBe(true);  // <- this test is successful
  });

  it("does something with options.format", () => {
    const duration = createDurationFromSeconds(1);
    formatDurationHelper(duration, {
      format: ["seconds"]
    });

    expect(formatDuration).toHaveBeenCalled();  // <- this test is unsuccessful
    expect(formatDuration).toHaveBeenCalledWith(duration, {   // <- this test is unsuccessful
      format: ["seconds"]
    });
  });
});
</code>```

expect(jest.isMockFunction(formatDuration)).toBe(true) is successful, but the others fail...

Thanks in advance!

Body:
I'm trying to write a test for a utility function in our project, which uses the formatDuration module from date-fns/formatDuration. Can anyone help me creating a mock for this module with Jest and be able to test if formatDuration was called with expected arguments?

This is my current setup:

// ../utilites/date.ts
import formatDuration from "date-fns/formatDuration";
import subSeconds from "date-fns/subSeconds";
import intervalToDuration from "date-fns/intervalToDuration";

export const createDurationFromSeconds = (seconds: number) => {
  const end = new Date();

  const start = subSeconds(end, seconds);
  return intervalToDuration({ start, end });
};

type FunctionArgs = Parameters<typeof formatDuration>;

export const formatDurationHelper = (
  duration: FunctionArgs[0],
  options?: FunctionArgs[1]
) => {
  //...do something with options.format

  return formatDuration(duration, options);
};

// ../utilites/date.test.ts
import formatDuration from "date-fns/formatDuration";
import { formatDurationHelper, createDurationFromSeconds } from "./date";

jest.mock("date-fns/formatDuration", () => {
  return {
    __esModule: true,
    default: jest.fn()
  };
});

describe("formatDurationWithLocale", () => {
  it("created mocked formatDuration", () => {
    expect(jest.isMockFunction(formatDuration)).toBe(true);  // <- this test is successful
  });

  it("does something with options.format", () => {
    const duration = createDurationFromSeconds(1);
    formatDurationHelper(duration, {
      format: ["seconds"]
    });

    expect(formatDuration).toHaveBeenCalled();  // <- this test is unsuccessful
    expect(formatDuration).toHaveBeenCalledWith(duration, {   // <- this test is unsuccessful
      format: ["seconds"]
    });
  });
});

expect(jest.isMockFunction(formatDuration)).toBe(true) is successful, but the others fail...

Thanks in advance!


问:
How to get the configured fallback locale as a string from Vue-i18n?
I'm using vue-i18n for my Vue 3 app. The app is configured like so

```<code>const i18n = createI18n({
  legacy: false,
  locale: "en",
  fallbackLocale: "en",
});
</code>```

Inside my component I'm using

```<code>import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();
</code>```

where locale.value returns a string, but fallbackLocale.value returns a custom type. https://vue-i18n.intlify.dev/guide/essentials/fallback.html#fallbacking shows that there might be multiple locales.

Since I could check against each fallback locale I need to find a way to iterate fallbackLocale. Currently I wasn't able to figure out how, a for...in loop didn't work for me, it says

TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'FallbackLocales '.

My usecase:

An external API returns a Record of locales and their messages. Based on my settings I want to read the translated message from it:

```<code>import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();

const myRecord: Record<string /* locale */, string /* text */> = { "en": "title", "de": "titel" };

function getContent(): string {
    if (locale.value in myRecord) {
      return myRecord[locale.value];
    }

    // try the fallback locales before throwing an error...

    throw new Error('missing translation...');
}
</code>```

Body:
I'm using vue-i18n for my Vue 3 app. The app is configured like so

const i18n = createI18n({
  legacy: false,
  locale: "en",
  fallbackLocale: "en",
});

Inside my component I'm using

import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();

where locale.value returns a string, but fallbackLocale.value returns a custom type. https://vue-i18n.intlify.dev/guide/essentials/fallback.html#fallbacking shows that there might be multiple locales.

Since I could check against each fallback locale I need to find a way to iterate fallbackLocale. Currently I wasn't able to figure out how, a for...in loop didn't work for me, it says

TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'FallbackLocales '.

My usecase:

An external API returns a Record of locales and their messages. Based on my settings I want to read the translated message from it:

import { useI18n } from "vue-i18n";

const { locale, fallbackLocale } = useI18n();

const myRecord: Record<string /* locale */, string /* text */> = { "en": "title", "de": "titel" };

function getContent(): string {
    if (locale.value in myRecord) {
      return myRecord[locale.value];
    }

    // try the fallback locales before throwing an error...

    throw new Error('missing translation...');
}


问:
AI categorical prediction for time variant data
I'm currently trying to use a sensor to measure a process's consistency. The sensor output varies wildly in its actual reading but displays features that are statistically different across three categories [dark, appropriate, light], with dark and light being out of control items. For example, one output could read approximately 0V, the process repeats and the sensor then reads 0.6V. Both the 0V reading and the 0.6V reading could represent an in control process. There is a consistent difference for sensor readings for out of control items vs in control items. An example set of an in control item can be found here and an example set of two out of control items can be found here. Because of the wildness of the sensor and characteristic shapes of each category's data, I think the best way to assess the readings is to process them with an AI model. This is my first foray into creating a model that creates a categorical prediction given a time series window. I haven't been able to find anything on the internet with my searches (I'm possibly looking for the wrong thing). I'm certain that what I'm attempting is feasible and has a strong case for an AI model, I'm just not certain what the optimal way to make it is. One idea that I had was to treat the data similarly to how an image is treated by an object detection model, with the readings as the input array and the category as the output, but I'm not certain that this is the best way to go about solving the problem. If anyone can help point me in the right direction or give me a resource, I would greatly appreciate it. Thanks for reading my post!</p>


问:
How would I get the IP address of a remote server without URL or IP address available
I use an application the makes calls to apps reunning on other servers. I would like to get the IP address of one of those servers and the source page doesn't reference either the called URL or IP address.
My idea is to ping the currect page to get the server IP address.</p>


问:
Object properties is undefined even with value after copy the object
i got a object that have 2 of the properties returning undefined even with a value inside of them, when i access them directly like "modelForm.action" it gives the right value but if a just do console.log(modelForm) returns the name undefined

```<code> this.modelForm = Object.assign({}, this.formSelected)
 console.log(this.modelForm)
 console.log(this.modelForm.action)
</code>```

//First Log

action: undefined  company_id: 1  created_at: "2022-12-19 19:13:21"  deleted_at: null  description: "ewef"  html: null  id: 7  name: "Form 3"  status: undefined  updated_at: "2022-12-19 19:45:34"

//Second Log

default

```<code></code>```

Body:
i got a object that have 2 of the properties returning undefined even with a value inside of them, when i access them directly like "modelForm.action" it gives the right value but if a just do console.log(modelForm) returns the name undefined

 this.modelForm = Object.assign({}, this.formSelected)
 console.log(this.modelForm)
 console.log(this.modelForm.action)

//First Log

action: undefined  company_id: 1  created_at: "2022-12-19 19:13:21"  deleted_at: null  description: "ewef"  html: null  id: 7  name: "Form 3"  status: undefined  updated_at: "2022-12-19 19:45:34"

//Second Log

default


问:
Error: Error in dimnames(x) <- dn : length of 'dimnames' [2] not equal to array extent
I have the following dataset about the choices of different car brands and their attributes. I would like to create a matrix based on each attribute of the cars.

```<code> RespNum Task Concept Make Exterior.Design Interior.design
    1 100086500    1       1    3               2               3
    2 100086500    1       2    1               3               2
    3 100086500    1       3    4               1               1
    4 100086500    1       4    0               0               0
    5 100086500    2       1    1               3               2
    6 100086500    2       2    5               1               3
      Driving.performance Driving.attributes Comfort Practibility Safety
    1                   1                  1       1            3      3
    2                   3                  3       3            2      1
    3                   2                  2       2            1      2
    4                   0                  0       0            0      0
    5                   3                  2       1            1      3
    6                   1                  3       3            3      2
      Quality Equipment Sustainability Economy Price Response
    1       2         1              1       3     1        0
    2       1         3              3       1     3        0
    3       3         2              2       2     2        1
    4       0         0              0       0     0        0
    5       3         2              1       1     4        0
    6       1         3              3       3     8        0
</code>```

I am using the function:

```<code>Make = attribcoding(6,4,'Other')
</code>```

The first input (6) is the number of levels, the second (4) is the column position in the dataset, and the last ('Other') is the name of the outside option. However, I get the following error message:

```<code>Error in dimnames(x) <- dn :
  length of 'dimnames' [2] not equal to array extent
</code>```

Body:
I have the following dataset about the choices of different car brands and their attributes. I would like to create a matrix based on each attribute of the cars.

 RespNum Task Concept Make Exterior.Design Interior.design
    1 100086500    1       1    3               2               3
    2 100086500    1       2    1               3               2
    3 100086500    1       3    4               1               1
    4 100086500    1       4    0               0               0
    5 100086500    2       1    1               3               2
    6 100086500    2       2    5               1               3
      Driving.performance Driving.attributes Comfort Practibility Safety
    1                   1                  1       1            3      3
    2                   3                  3       3            2      1
    3                   2                  2       2            1      2
    4                   0                  0       0            0      0
    5                   3                  2       1            1      3
    6                   1                  3       3            3      2
      Quality Equipment Sustainability Economy Price Response
    1       2         1              1       3     1        0
    2       1         3              3       1     3        0
    3       3         2              2       2     2        1
    4       0         0              0       0     0        0
    5       3         2              1       1     4        0
    6       1         3              3       3     8        0

I am using the function:

Make = attribcoding(6,4,'Other')

The first input (6) is the number of levels, the second (4) is the column position in the dataset, and the last ('Other') is the name of the outside option. However, I get the following error message:

Error in dimnames(x) <- dn :
  length of 'dimnames' [2] not equal to array extent


问:
Scaffolded password-reset page breaks user passwords
I am having issues with logging in after resetting a password, with scaffolded Identitity pages (forgot password, reset password, login).

I scaffolded the ForgotPassword and PasswordReset pages because I wanted admins to be able to reset users' passwords for them. Additionally, I am using a custom IdentityUser class that inherits IdentityUser. Everything else works (including logins, logouts, etc.).

The password reset doesn't work. In tracing the flow - the password reset token is generated correctly. The user receives it, goes to the correct page, it gets decoded correctly. The issue seems to be happening when the new password gets hashed - I don't know what algorithm it's using, but the resultant hash is obviously different than the initial. I did a test where I typed down a password, copy-and-pasted it into both the reset field and the login field, and got a credential error!!!

Out of curiosity I called the following function which I assumed should've given me the same hash as on the SQL server, and compared it to the hash stored there (my local test DB of course)

```<code>var test = _signInManager.UserManager.PasswordHasher.HashPassword(
    await _signInManager.UserManager.FindByEmailAsync(Input.Email),
    Input.Password);
</code>```

Here are the results:

Password:

ABCDEFG12345

Password hasher in ResetPassword:

AQAAAAEAACcQAAAAEBhYZXqCx2Y43vqlB9bQ0Cf6AjgcyckVYDQSm+D+t8Zmv8V9Mx/E6/w5LyFzGOqIFQ==

Sql DB hash for that user:

AQAAAAEAACcQAAAAEItXHv1WYksR5AU6KUYHrF4Xrlnlzi2EM+LzecmUqrcz1Zx2JiUVLkHMk7ZSgqfiXw==

Password hasher in Login:

AQAAAAEAACcQAAAAEGUvKsoSmQ5RFQWLysQqAv6BZtgMEup1bPEYZSlJ7MzzhMVQ+20qhKapzcX+ISOLOg==

What gives? Where's the issue? Has anyone experienced this or has ways to troubleshoot this further? Am I using the wrong password hashing function to compare what gets put in the server? Is it a localhost vs. deployed issue?

For what it's worth, I checked and the DB hash does change after each password reset, so it's not as if the code isn't doing anything. It seems like the left and right hands aren't talking to each other.

Body:
I am having issues with logging in after resetting a password, with scaffolded Identitity pages (forgot password, reset password, login).

I scaffolded the ForgotPassword and PasswordReset pages because I wanted admins to be able to reset users' passwords for them. Additionally, I am using a custom IdentityUser class that inherits IdentityUser. Everything else works (including logins, logouts, etc.).

The password reset doesn't work. In tracing the flow - the password reset token is generated correctly. The user receives it, goes to the correct page, it gets decoded correctly. The issue seems to be happening when the new password gets hashed - I don't know what algorithm it's using, but the resultant hash is obviously different than the initial. I did a test where I typed down a password, copy-and-pasted it into both the reset field and the login field, and got a credential error!!!

Out of curiosity I called the following function which I assumed should've given me the same hash as on the SQL server, and compared it to the hash stored there (my local test DB of course)

var test = _signInManager.UserManager.PasswordHasher.HashPassword(
    await _signInManager.UserManager.FindByEmailAsync(Input.Email),
    Input.Password);

Here are the results:

Password:

ABCDEFG12345

Password hasher in ResetPassword:

AQAAAAEAACcQAAAAEBhYZXqCx2Y43vqlB9bQ0Cf6AjgcyckVYDQSm+D+t8Zmv8V9Mx/E6/w5LyFzGOqIFQ==

Sql DB hash for that user:

AQAAAAEAACcQAAAAEItXHv1WYksR5AU6KUYHrF4Xrlnlzi2EM+LzecmUqrcz1Zx2JiUVLkHMk7ZSgqfiXw==

Password hasher in Login:

AQAAAAEAACcQAAAAEGUvKsoSmQ5RFQWLysQqAv6BZtgMEup1bPEYZSlJ7MzzhMVQ+20qhKapzcX+ISOLOg==

What gives? Where's the issue? Has anyone experienced this or has ways to troubleshoot this further? Am I using the wrong password hashing function to compare what gets put in the server? Is it a localhost vs. deployed issue?

For what it's worth, I checked and the DB hash does change after each password reset, so it's not as if the code isn't doing anything. It seems like the left and right hands aren't talking to each other.


问:
How to get data in a server side rendered module federated webapp
I looked at module federation in webpack. We work with micro-frontends and we render our frontend server side. I looked at the following example https://github.com/module-federation/module-federation-examples/tree/master/server-side-rendering and was wondering where we should get the data for microservice remote1.

I put some example code in: https://github.com/joris77/module-federation-101

My changes for getting data work like this:

Remote1 also exposes a module with the name: <lower case component name>Server.js"
remote1/src/contentServer.js which has a function to get the data.

```<code>export const getServerSideProps = async ctx => ({
    name: 'joris'
})
</code>```

This module can be fetched and executed just before rendering a page by the shell
shell/server/render.js - line 10 - 12

The preloadedState will be put in the page
shell/server/render.js - line 29

```<code>import React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import {Helmet} from 'react-helmet';
import App from '../src/components/App';

export default async (req, res, next) => {
    const helmet = Helmet.renderStatic();
    let didError = false;

    const {getServerSideProps} = await import('remote1/contentServer')

    const preloadedState = await getServerSideProps({req, res})

    const stream = renderToPipeableStream(<App {...preloadedState} />, {
        onAllReady() {
            res.statusCode = didError ? 500 : 200;
            res.setHeader('Content-type', 'text/html');
            res.write(`<!DOCTYPE html`);
            res.write(`<html ${helmet.htmlAttributes.toString()}>
      <head>
        ${helmet.title.toString()}
        ${helmet.meta.toString()}
        ${helmet.link.toString()}
      </head>
      <body>`);
            res.write(`<div id="root">`);
            stream.pipe(res);
            res.write(`</div>`);
            res.write(`<script>window.pageState = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')}</script>`)
            res.write(`<script async data-chunk="main" src="http://localhost:3000/static/main.js"></script>`);
            res.write(`</body></html>`);
        },
        onShellError() {
            res.statusCode = 500;
            res.send(`<h1>An error occurred</h1>`)
        },
        onError(err) {
            didError = true;
            console.error(err);
        }
    })
};
</code>```

The preloadedState is used for hydration on the client
shell/src/bootstrap.js- line 7-8

```<code>import React from 'react';
import * as ReactDOMClient from 'react-dom/client';
import App from './components/App';

const render = App => {
  const root = document.getElementById('root');
  const state = window.pageState
  ReactDOMClient.hydrateRoot(root, <App {...state} />);
};

render(App);
</code>```

The preloadedState is rendered
shell/src/components/App.js - line 21

```<code>import React from 'react';
import {Helmet} from "react-helmet";

const Remote1Content = React.lazy(() => import('remote1/Content'));

export default (preloadedState) => (
    <div>
        <Helmet>
            <title>SSR MF Example</title>
        </Helmet>
        <div style={{
            backgroundColor: 'black',
            color: 'lightgrey',
            padding: '1rem'
        }} onClick={() => alert('shell is interactive')}>
            <h1>Module Federation Example: Server Side Rendering</h1>
            <h2>This is the shell application.</h2>
        </div>
        <React.Suspense fallback={<h1>Loading....</h1>}>
            <Remote1Content {...preloadedState}/>
        </React.Suspense>
    </div>
);
</code>```

remote1/src/Content.jsx - line 10

```<code>import React from "react";
const Image = React.lazy(() => import("remote2/Image"));

export default ({name}) => (
    <div style={{
      backgroundColor: 'green',
      color: 'lightgrey',
      padding: '1rem'
    }}>
      <h2>Remote 1: Hello {name}</h2>
      <p>This is the content from remote 1, which will include an image component exposed by remote2. This demonstrates nested federated modules being rendered server-side.</p>
      <React.Suspense fallback={<h1>Loading...</h1>}>
        <Image />
      </React.Suspense>
    </div>
  );
</code>```

This code is a very naive way of doing this, does not look nice and we could of course improve it a lot.

My main question is: how valid is this concept for a production situation?

Body:
I looked at module federation in webpack. We work with micro-frontends and we render our frontend server side. I looked at the following example https://github.com/module-federation/module-federation-examples/tree/master/server-side-rendering and was wondering where we should get the data for microservice remote1.

I put some example code in: https://github.com/joris77/module-federation-101

My changes for getting data work like this:

Remote1 also exposes a module with the name: <lower case component name>Server.js"
remote1/src/contentServer.js which has a function to get the data.

export const getServerSideProps = async ctx => ({
    name: 'joris'
})

This module can be fetched and executed just before rendering a page by the shell
shell/server/render.js - line 10 - 12

The preloadedState will be put in the page
shell/server/render.js - line 29

import React from 'react';
import {renderToPipeableStream} from 'react-dom/server';
import {Helmet} from 'react-helmet';
import App from '../src/components/App';

export default async (req, res, next) => {
    const helmet = Helmet.renderStatic();
    let didError = false;

    const {getServerSideProps} = await import('remote1/contentServer')

    const preloadedState = await getServerSideProps({req, res})

    const stream = renderToPipeableStream(<App {...preloadedState} />, {
        onAllReady() {
            res.statusCode = didError ? 500 : 200;
            res.setHeader('Content-type', 'text/html');
            res.write(`<!DOCTYPE html`);
            res.write(`

        ${helmet.title.toString()}
        ${helmet.meta.toString()}
        ${helmet.link.toString()}

      `);
            res.write(`<div id="root">`);
            stream.pipe(res);
            res.write(`</div>`);
            res.write(`<script>window.pageState = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')}</script>`)
            res.write(`<script async data-chunk="main" src="http://localhost:3000/static/main.js"></script>`);
            res.write(`</body></html>`);
        },
        onShellError() {
            res.statusCode = 500;
            res.send(`<h1>An error occurred</h1>`)
        },
        onError(err) {
            didError = true;
            console.error(err);
        }
    })
};

The preloadedState is used for hydration on the client
shell/src/bootstrap.js- line 7-8

import React from 'react';
import * as ReactDOMClient from 'react-dom/client';
import App from './components/App';

const render = App => {
  const root = document.getElementById('root');
  const state = window.pageState
  ReactDOMClient.hydrateRoot(root, <App {...state} />);
};

render(App);

The preloadedState is rendered
shell/src/components/App.js - line 21

import React from 'react';
import {Helmet} from "react-helmet";

const Remote1Content = React.lazy(() => import('remote1/Content'));

export default (preloadedState) => (

        <Helmet>
            <title>SSR MF Example</title>
        </Helmet>

 alert('shell is interactive')}>

Module Federation Example: Server Side Rendering

This is the shell application.

        <React.Suspense fallback={
Loading....
}>
            <Remote1Content {...preloadedState}/>
        </React.Suspense>

);

remote1/src/Content.jsx - line 10

import React from "react";
const Image = React.lazy(() => import("remote2/Image"));

export default ({name}) => (

Remote 1: Hello {name}

This is the content from remote 1, which will include an image component exposed by remote2. This demonstrates nested federated modules being rendered server-side.

      <React.Suspense fallback={
Loading...
}>
        <Image />
      </React.Suspense>

  );

This code is a very naive way of doing this, does not look nice and we could of course improve it a lot.

My main question is: how valid is this concept for a production situation?


问:
How to solve the issue of mismatch between docker image's arch and python3 interpreter’s arch while using Bazel on M1 mac?
I just started to use Bazel with python3 and docker on M1 mac (apple silicon). I already figured out that the python3 interpreter's arch (aarch64) doesn't match the docker image's arch (amd64).
How could I deal with this issue?
It would be appreciated if someone could provide me with any prompts or tips to move forward.</p>
```<code>% bazel run //projects/xxxx/yyyy:hhhh
...
...
...
... as bazel/projects/xxxx/yyyy:hhhh

% docker run bazel/projects/xxxx/yyyy:hhhh
Traceback (most recent call last):
  File "/app/projects/xxxx/yyyy.binary", line 392, in <module>
    Main()
  File "/app/projects/xxxx/yyyy.binary", line 382, in Main
    os.execv(args[0], args)
OSError: [Errno 8] Exec format error: '/app/projects/xxxx/yyyy.binary.runfiles/py3_aarch64-apple-darwin/bin/python3'

% bazel --version
bazel 5.2.0
% python --version
python 3.10.2
</code>```

Body:
I just started to use Bazel with python3 and docker on M1 mac (apple silicon). I already figured out that the python3 interpreter's arch (aarch64) doesn't match the docker image's arch (amd64).
How could I deal with this issue?
It would be appreciated if someone could provide me with any prompts or tips to move forward.

% bazel run //projects/xxxx/yyyy:hhhh
...
...
...
... as bazel/projects/xxxx/yyyy:hhhh

% docker run bazel/projects/xxxx/yyyy:hhhh
Traceback (most recent call last):
  File "/app/projects/xxxx/yyyy.binary", line 392, in <module>
    Main()
  File "/app/projects/xxxx/yyyy.binary", line 382, in Main
    os.execv(args[0], args)
OSError: [Errno 8] Exec format error: '/app/projects/xxxx/yyyy.binary.runfiles/py3_aarch64-apple-darwin/bin/python3'

% bazel --version
bazel 5.2.0
% python --version
python 3.10.2


问:
how can I create on my own a auto-self created datetime column?
i have a datetime dataframe
assume it is the following

```<code>    Datetime
0   2022-09-06 12:33:40
1   2022-09-06 12:33:50
2   2022-09-06 12:34:00
3   2022-09-06 12:34:10
4   2022-09-06 12:34:20

</code>```

2022 - 09 - 06 (09-06 is 9th june)

```<code>Datetime
</code>```

40490   2022-06-14 05:02:00
40491   2022-06-14 05:02:10
40492   2022-06-14 05:02:20
40493   2022-06-14 05:02:30
.
.
Datetime
301492  2022-02-10 10:05:40
301493  2022-02-10 10:05:50
301494  2022-02-10 10:06:00
301495  2022-02-10 10:06:10
301496  2022-02-10 10:06:20

this DateTime dataframe contains 1.000.000 rows until the 2022-5-10 ( 5th octomber) with the step of 10 seconds

the problem is that many dates follow the formation year-month-day and other dates in the dataframe follow the formation od year - day - month

how couldd the datetime changes on its own ?
what I mean is that I have an initial datetime  2022-09-06 12:33:40 and I want to make a code that after a x number of seconds will change the day and after of y number of seconds will change the month creating a new column that follows this pattern
2022-month-day hour-minutes-seconds
does anybody know how can I fix my problem?

Body:
i have a datetime dataframe
assume it is the following

    Datetime
0   2022-09-06 12:33:40
1   2022-09-06 12:33:50
2   2022-09-06 12:34:00
3   2022-09-06 12:34:10
4   2022-09-06 12:34:20

2022 - 09 - 06 (09-06 is 9th june)

Datetime

40490   2022-06-14 05:02:00
40491   2022-06-14 05:02:10
40492   2022-06-14 05:02:20
40493   2022-06-14 05:02:30
.
.
Datetime
301492  2022-02-10 10:05:40
301493  2022-02-10 10:05:50
301494  2022-02-10 10:06:00
301495  2022-02-10 10:06:10
301496  2022-02-10 10:06:20

this DateTime dataframe contains 1.000.000 rows until the 2022-5-10 ( 5th octomber) with the step of 10 seconds

the problem is that many dates follow the formation year-month-day and other dates in the dataframe follow the formation od year - day - month

how couldd the datetime changes on its own ?
what I mean is that I have an initial datetime  2022-09-06 12:33:40 and I want to make a code that after a x number of seconds will change the day and after of y number of seconds will change the month creating a new column that follows this pattern
2022-month-day hour-minutes-seconds
does anybody know how can I fix my problem?