问:
delete query in databricks showing parse exception
```<code> DELETE FROM (
  select
    id,
    firstname,
    middlename,
    lastname,
    gender,
    row_number() over(
      partition by firstname,
      middlename,
      lastname,
      gender
      order by
        id
    ) as dupcount
  from
    delete_people10m
)
WHERE dupcount > 1;
</code>```

please note that inner query is working fine.

Body:
 DELETE FROM (
  select
    id,
    firstname,
    middlename,
    lastname,
    gender,
    row_number() over(
      partition by firstname,
      middlename,
      lastname,
      gender
      order by
        id
    ) as dupcount
  from
    delete_people10m
)
WHERE dupcount > 1;

please note that inner query is working fine.


来源: stackexchange

问:
VS Code gives import error but the script works
I'm writing my first script in python and VS Code marks me errors, but the script works fine.

The error are like this:

```<code>from pyautogui import screenshot
</code>```

and marks screenshot in red and pyautogui in blue and gives this error:

"screenshot" is unknown import symbolPylancereportGeneralTypeIssues

Is anything wrong since this works, or is there a way to take the warning?

I tried using the quickfix suggestion

```<code> # type: ignore # type: ignorefrom requests_html import AsyncHTMLSession, HTMLSession

</code>```

But doesn't do anything.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing my first script in python and VS Code marks me errors, but the script works fine.

The error are like this:

from pyautogui import screenshot

and marks screenshot in red and pyautogui in blue and gives this error:

"screenshot" is unknown import symbolPylancereportGeneralTypeIssues

Is anything wrong since this works, or is there a way to take the warning?

I tried using the quickfix suggestion

 # type: ignore # type: ignorefrom requests_html import AsyncHTMLSession, HTMLSession

But doesn't do anything.


问:
Change JSON Keys in Nested JSON in SQL Table
I have a table with column called tableJson which contains information of the following type:

```<code>[
  {
    "type": "TABLE",
    "content": {
                 "rows":
                        [{"Date": "2021-09-28","Monthly return": "1.44%"},
                         {"Date": "2021-11-24", "Yearly return": "0.62%"},
                         {"Date": "2021-12-03", "Monthly return": "8.57%"},
                         {},
                        ]
               }
   }
]
</code>```

I want to change "Monthly Return" to "Weekly Return" everywhere in the table column where it exists.

Thank you in advance!

I tried different approaches to Parse, read, OPENJSON, CROSS APPLY but could not make it.

Body:
I have a table with column called tableJson which contains information of the following type:

[
  {
    "type": "TABLE",
    "content": {
                 "rows":
                        [{"Date": "2021-09-28","Monthly return": "1.44%"},
                         {"Date": "2021-11-24", "Yearly return": "0.62%"},
                         {"Date": "2021-12-03", "Monthly return": "8.57%"},
                         {},
                        ]
               }
   }
]

I want to change "Monthly Return" to "Weekly Return" everywhere in the table column where it exists.

Thank you in advance!

I tried different approaches to Parse, read, OPENJSON, CROSS APPLY but could not make it.


问:
Xcode: Blue folder on colleagues machine, but grey for me
Step 1: Select the plus icon at the bottom of 'frameworks and libraries` on the general tab.

Step 2: Select add files at the bottom.

Step 3: Select the folder I'm interested in from the navigator and it appears here, as a grey folder.

When my colleague repeats the above 3 steps on his machine, the folder color is blue instead. Why?

There is no option to select 'add as group' etc, so not sure what's going on.


问:
Permission to use Client Credential Flow (2-legged OAuth)
At our company we want to have the best possible setup for analyzing data about our Linkedin ads performance.

Our data specialist needs to access the API using the Client Credential Flow (2-legged OAuth)
https://www.linkedin.com/developers/news/featured-updates/oauth-token-inspector

I created a Linkedin ticket and got the answer that I needed to ask the question here. But actually I though that Linkedin needed to grant the permission. Do any of you know how to solve this?

We tried creating a Linkedin ticket but they asked us to write here.


问:
Issues with javascript/jQuery in Application Customizer - timing issue?
I am trying to add javascript and css to my Sharepoint Online/Modern site using Application Customizer for the first time.

In my ApplicationCustomizer.ts, I try tlo load jquery and my oqn javascript from site assets using this code (I add a date/time string to avoid the page using cached javascript)

```<code> let current_date: Date = new Date();
    let date_String: string = current_date.toString();
    date_String = current_date.toISOString()
    console.log('date_string = %s', date_String);
    SPComponentLoader.loadCss('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.css?d=' + date_String);
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/jquery-3.6.3.min.js?d=' + date_String)
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.js?d=' + date_String);
</code>```

I also added the datestirng to jquery as I read it was how to force the javascript to load in the specified order.

My main javacript ((caj23.js) then uses jquery $(document).load() to run some code - however, this only works intermittently. When it fails, the console shows

caj23.js?d=Mon%20Jan%2009%202023:50 Uncaught ReferenceError: $ is not defined

which suggests jquery hadn't finished loading in time before the $(document).load() fired.

Is there any way to force the my javascript to wait until jQuery is ready?
Or some other way to fix dependencies?

Thanks!

Body:
I am trying to add javascript and css to my Sharepoint Online/Modern site using Application Customizer for the first time.

In my ApplicationCustomizer.ts, I try tlo load jquery and my oqn javascript from site assets using this code (I add a date/time string to avoid the page using cached javascript)

 let current_date: Date = new Date();
    let date_String: string = current_date.toString();
    date_String = current_date.toISOString()
    console.log('date_string = %s', date_String);
    SPComponentLoader.loadCss('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.css?d=' + date_String);
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/jquery-3.6.3.min.js?d=' + date_String)
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.js?d=' + date_String);

I also added the datestirng to jquery as I read it was how to force the javascript to load in the specified order.

My main javacript ((caj23.js) then uses jquery $(document).load() to run some code - however, this only works intermittently. When it fails, the console shows

caj23.js?d=Mon%20Jan%2009%202023:50 Uncaught ReferenceError: $ is not defined

which suggests jquery hadn't finished loading in time before the $(document).load() fired.

Is there any way to force the my javascript to wait until jQuery is ready?
Or some other way to fix dependencies?

Thanks!


问:
iOS UIDatePicker "Time" label locale / language not working
Is there any way to change the language/locale of the label with "Time" string on UIDatePicker? This is my date picker configuration:

```<code>datePicker.locale = Locale(identifier: "de_DE")
datePicker.calendar.locale = Locale(identifier: "de_DE")
datePicker.datePickerMode = .dateAndTime
datePicker.preferredDatePickerStyle = .inline
</code>```

And it is displayed as on the screenshot:

As you can see the "Time" label is still in English but I expected it to be in German. Is there any way to fix that or maybe at least hide this label?

Body:
Is there any way to change the language/locale of the label with "Time" string on UIDatePicker? This is my date picker configuration:

datePicker.locale = Locale(identifier: "de_DE")
datePicker.calendar.locale = Locale(identifier: "de_DE")
datePicker.datePickerMode = .dateAndTime
datePicker.preferredDatePickerStyle = .inline

And it is displayed as on the screenshot:

As you can see the "Time" label is still in English but I expected it to be in German. Is there any way to fix that or maybe at least hide this label?


问:
Arel subselects with ActiveRecord?
I'm using a slightly-modified version of the geocoded gem which returns this query when I call near on my model (calling Deal.near(southwest), where southwest is an array of geo coordinates):

```<code>SELECT
  deals.*,
  3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) AS distance,
  CAST(DEGREES(ATAN2( RADIANS(addresses.lng - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974))) + 360 AS decimal) % 360 AS bearing
  FROM "deals"
  INNER JOIN "companies" ON "companies"."id" = "deals"."company_id"
  INNER JOIN "addresses" ON "addresses"."addressable_id" = "companies"."id" AND "addresses"."addressable_type" = 'Company'
  WHERE (
    addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867
    AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986
  )
  GROUP BY
    deals.id,
    deals.created_at,
    deals.updated_at,
    deals.active,
    deals.company_id,
    deals.title,
    deals.limitations,
    deals.redemption_count,
    addresses.lat,
    addresses.lng
  HAVING 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) <= 20
  ORDER BY 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) ASC
</code>```

My issue is that this will return multiple Deal records if that Deal's company has multiple Addresses, which I don't want.

In MySQL, I could just omit address.lat, address.lng in the GROUP_BY clause and it will properly group the records, but I can't do this in PostgreSQL.

I know I could wrap the whole query above in another SELECT and GROUP_BY, like this:

```<code>SELECT
  id, created_at, updated_at, active, title, punches_to_complete, company_id, description, lat, lng, MIN(distance), bearing
  FROM ( ... ) AS t
  GROUP BY company_id
</code>```

... where the ellipsis is the query from above. That (I believe) should get me the desired result in both MySQL and PostgreSQL.

The only problem is that I have no idea how to write this in ARel!

I had tried the following, a la this tip from the ARel guru, but I couldn't really make it work quite right (calling to_sql as the OP had said fixed his issue escapes the quotes, which freaks PostgreSQL out).

Can anyone help me with this???

UPDATE:

I've managed to get this done with an additional scope, like so:

```<code>  scope :nearest, lambda { |coords|
    subquery = "(#{Deal.near(coords).to_sql}) AS t1"
    columns = Deal.columns.map{ |c| c.name }.join(',')
    Deal.select(columns)
      .select('MIN(distance) AS distance')
      .from(subquery)
      .group(columns)
      .order('distance ASC')
  }
</code>```

However, this totally breaks chainability, as now I cannot call something like current_user.deals.nearest(coords), since that tags on an additional WHERE deals.user_id = 1 to the query outside of the subselect. I tried compensating for this by moving this logic into a class method and blanking the wheres clause on the SelectManager manually, like this:

```<code>  def self.nearest(coords)
    subquery = "(#{Deal.near(coords).to_sql}) AS t1"
    columns = Deal.columns.map{ |c| c.name }.join(',')
    query = Deal.select(columns)
      .select('MIN(distance) AS distance')
      .from(subquery)
      .group(columns)
      .order('distance ASC')
    query.arel.ast.cores[0].wheres = []
    query
  end
</code>```

... but that doesn't seem to work either: the additional WHERE clause is still appended:

Failure/Error:
  @user.deals.nearest(southwest).first.distance.to_f.round(2).should ==
       ActiveRecord::StatementInvalid:
         Mysql2::Error: Unknown column 'deals.user_id' in 'where
  clause': SELECT  id,created_at,updated_at,user_id,company_id,
  MIN(distance) AS distance FROM (SELECT deals.*, 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(addresses.lng
  - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974)))
  + 360 AS decimal) % 360 AS bearing FROM deals INNER JOIN companies
  ON companies.id = deals.company_id INNER JOIN addresses ON
  addresses.addressable_id = companies.id AND
  addresses.addressable_type = 'Company' WHERE deals.user_id =
  26 AND (addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867
  AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986)
  GROUP BY
  deals.id,deals.created_at,deals.updated_at,deals.user_id,deals.company_id,
  addresses.lat, addresses.lng HAVING 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) <= 20 ORDER BY 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) ASC) AS t1  WHERE deals.user_id = 26 GROUP BY
  id,created_at,updated_at,user_id,company_id ORDER BY distance ASC
  LIMIT 1

Is what I'm trying to do even possible with ARel? The additional scopes above feel really dirty to me (parsing the subquery to raw SQL? I thought ARel was supposed to make it so I never did that!)

Related question: Can ARel formulate cross-db queries for CTEs (Common Table Expressions)?

ContentLicense: CC BY-SA 3.0

Title: Arel subselects with ActiveRecord?

Body:
I'm using a slightly-modified version of the geocoded gem which returns this query when I call near on my model (calling Deal.near(southwest), where southwest is an array of geo coordinates):

SELECT
  deals.*,
  3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) AS distance,
  CAST(DEGREES(ATAN2( RADIANS(addresses.lng - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974))) + 360 AS decimal) % 360 AS bearing
  FROM "deals"
  INNER JOIN "companies" ON "companies"."id" = "deals"."company_id"
  INNER JOIN "addresses" ON "addresses"."addressable_id" = "companies"."id" AND "addresses"."addressable_type" = 'Company'
  WHERE (
    addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867
    AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986
  )
  GROUP BY
    deals.id,
    deals.created_at,
    deals.updated_at,
    deals.active,
    deals.company_id,
    deals.title,
    deals.limitations,
    deals.redemption_count,
    addresses.lat,
    addresses.lng
  HAVING 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) <= 20
  ORDER BY 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180 / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat * PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() / 180 / 2), 2) )) ASC

My issue is that this will return multiple Deal records if that Deal's company has multiple Addresses, which I don't want.

In MySQL, I could just omit address.lat, address.lng in the GROUP_BY clause and it will properly group the records, but I can't do this in PostgreSQL.

I know I could wrap the whole query above in another SELECT and GROUP_BY, like this:

SELECT
  id, created_at, updated_at, active, title, punches_to_complete, company_id, description, lat, lng, MIN(distance), bearing
  FROM ( ... ) AS t
  GROUP BY company_id

... where the ellipsis is the query from above. That (I believe) should get me the desired result in both MySQL and PostgreSQL.

The only problem is that I have no idea how to write this in ARel!

I had tried the following, a la this tip from the ARel guru, but I couldn't really make it work quite right (calling to_sql as the OP had said fixed his issue escapes the quotes, which freaks PostgreSQL out).

Can anyone help me with this???

UPDATE:

I've managed to get this done with an additional scope, like so:

  scope :nearest, lambda { |coords|
    subquery = "(#{Deal.near(coords).to_sql}) AS t1"
    columns = Deal.columns.map{ |c| c.name }.join(',')
    Deal.select(columns)
      .select('MIN(distance) AS distance')
      .from(subquery)
      .group(columns)
      .order('distance ASC')
  }

However, this totally breaks chainability, as now I cannot call something like current_user.deals.nearest(coords), since that tags on an additional WHERE deals.user_id = 1 to the query outside of the subselect. I tried compensating for this by moving this logic into a class method and blanking the wheres clause on the SelectManager manually, like this:

  def self.nearest(coords)
    subquery = "(#{Deal.near(coords).to_sql}) AS t1"
    columns = Deal.columns.map{ |c| c.name }.join(',')
    query = Deal.select(columns)
      .select('MIN(distance) AS distance')
      .from(subquery)
      .group(columns)
      .order('distance ASC')
    query.arel.ast.cores[0].wheres = []
    query
  end

... but that doesn't seem to work either: the additional WHERE clause is still appended:

Failure/Error:
  @user.deals.nearest(southwest).first.distance.to_f.round(2).should ==
       ActiveRecord::StatementInvalid:
         Mysql2::Error: Unknown column 'deals.user_id' in 'where
  clause': SELECT  id,created_at,updated_at,user_id,company_id,
  MIN(distance) AS distance FROM (SELECT deals.*, 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(addresses.lng
  - -122.42336332798004), RADIANS(addresses.lat - 37.772476604436974)))
  + 360 AS decimal) % 360 AS bearing FROM deals INNER JOIN companies
  ON companies.id = deals.company_id INNER JOIN addresses ON
  addresses.addressable_id = companies.id AND
  addresses.addressable_type = 'Company' WHERE deals.user_id =
  26 AND (addresses.lat BETWEEN 37.483013038215276 AND 38.06194017065867
  AND addresses.lng BETWEEN -122.78956461309022 AND -122.05716204286986)
  GROUP BY
  deals.id,deals.created_at,deals.updated_at,deals.user_id,deals.company_id,
  addresses.lat, addresses.lng HAVING 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) <= 20 ORDER BY 3958.755864232 * 2 *
  ASIN(SQRT(POWER(SIN((37.772476604436974 - addresses.lat) * PI() / 180
  / 2), 2) + COS(37.772476604436974 * PI() / 180) * COS(addresses.lat *
  PI() / 180) * POWER(SIN((-122.42336332798004 - addresses.lng) * PI() /
  180 / 2), 2) )) ASC) AS t1  WHERE deals.user_id = 26 GROUP BY
  id,created_at,updated_at,user_id,company_id ORDER BY distance ASC
  LIMIT 1

Is what I'm trying to do even possible with ARel? The additional scopes above feel really dirty to me (parsing the subquery to raw SQL? I thought ARel was supposed to make it so I never did that!)

Related question: Can ARel formulate cross-db queries for CTEs (Common Table Expressions)?


问:
MacOS can't display an open3d window from remote server，GLX_ARB_create_context_profile is unavailable

Problem

The remote server can't forward open3d window to my Mac

the codes are as follows:

import copy
import numpy as np
import open3d as o3d

if __name__ == "__main__":

    print("Testing mesh in open3d ...")
    mesh = o3d.io.read_triangle_mesh("a.obj")
    print(mesh)
    print(np.asarray(mesh.vertices))
    print(np.asarray(mesh.triangles))
    verts = np.asarray(mesh.vertices)

    mesh.vertices = o3d.utility.Vector3dVector(verts)
    mesh.compute_vertex_normals()
    mesh.paint_uniform_color([0.6, 0.1, 0.5])

    cords = o3d.geometry.TriangleMesh.create_coordinate_frame()
    o3d.visualization.draw_geometries([mesh])
```
<p>note that <code>a.obj</code> is a testfile for helping test X11 Forwarding</p>
<p>the raised error is:</p>
```libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
[Open3D WARNING] GLFW Error: GLX: Forward compatibility requested but GLX_ARB_create_context_profile is unavailable
[Open3D WARNING] Failed to create window
[Open3D WARNING] [DrawGeometries] Failed creating OpenGL window.
```
<h2>Background</h2>
<p>I have added the following two lines in my ssh configuration file on Mac</p>
```ForwardX11 yes
ForwardX11Trusted yes
```
<p>and added the following command in my <code>.bashrc</code> file on Mac</p>
```export DISPLAY=:0
```

I'm using XQuartz 2.8.4 to receive remote GUI, and I can display the clock on my Mac by using xclock on the remote server terminal normally

Mac config: MacBook Pro 2021 Apple Silicon 13.0.1 (22A400)

What I Want

I asked others, I know that mobaxterm can display open3d window normally, but it's a windows software, and Mac can only use XQuartz to display GUI of the remote server.

so how can I display the open3d window on Mac by XQuartz?

Body:
Problem

The remote server can't forward open3d window to my Mac

the codes are as follows:

import copy
import numpy as np
import open3d as o3d

if __name__ == "__main__":

    print("Testing mesh in open3d ...")
    mesh = o3d.io.read_triangle_mesh("a.obj")
    print(mesh)
    print(np.asarray(mesh.vertices))
    print(np.asarray(mesh.triangles))
    verts = np.asarray(mesh.vertices)

    mesh.vertices = o3d.utility.Vector3dVector(verts)
    mesh.compute_vertex_normals()
    mesh.paint_uniform_color([0.6, 0.1, 0.5])

    cords = o3d.geometry.TriangleMesh.create_coordinate_frame()
    o3d.visualization.draw_geometries([mesh])

note that a.obj is a testfile for helping test X11 Forwarding

the raised error is:

libGL error: No matching fbConfigs or visuals found
libGL error: failed to load driver: swrast
[Open3D WARNING] GLFW Error: GLX: Forward compatibility requested but GLX_ARB_create_context_profile is unavailable
[Open3D WARNING] Failed to create window
[Open3D WARNING] [DrawGeometries] Failed creating OpenGL window.

Background

I have added the following two lines in my ssh configuration file on Mac

ForwardX11 yes
ForwardX11Trusted yes

and added the following command in my .bashrc file on Mac

export DISPLAY=:0

I'm using XQuartz 2.8.4 to receive remote GUI, and I can display the clock on my Mac by using xclock on the remote server terminal normally

Mac config: MacBook Pro 2021 Apple Silicon 13.0.1 (22A400)

What I Want

I asked others, I know that mobaxterm can display open3d window normally, but it's a windows software, and Mac can only use XQuartz to display GUI of the remote server.

so how can I display the open3d window on Mac by XQuartz?


问:
Tests are falling in the headless Chromedriver, Selenium, C#
When running tests in headless chromedriver, the tests fail with errors like "Element not interactable", "element click intercepted" (in the same places). But when I run normal chromedriver the tests pass. I identify elements by XPath.
Why is this happening and how can it be fixed?

Examples of my Chromedriver settings:

Headless:

```<code>var options = new ChromeOptions();
options.AddArguments("headless");
driver = new ChromeDriver(options);
</code>```

Normal:

```<code>driver = new OpenQA.Selenium.Chrome.ChromeDriver();

</code>```

Body:
When running tests in headless chromedriver, the tests fail with errors like "Element not interactable", "element click intercepted" (in the same places). But when I run normal chromedriver the tests pass. I identify elements by XPath.
Why is this happening and how can it be fixed?

Examples of my Chromedriver settings:

Headless:

var options = new ChromeOptions();
options.AddArguments("headless");
driver = new ChromeDriver(options);

Normal:

driver = new OpenQA.Selenium.Chrome.ChromeDriver();


问:
How to control concurrent sessions per user in Apache Presto?
I'm wondering how to control/limit max concurrent sessions per user querying "Apache Presto" that is installed on a distributed mode?

Thanks!

Is there a management console that we can use in Apache Presto to control max number of concurrent queries per logged-in users?


问:
How to specify region for functions using Angular Fire Module?
I'm using @angular/fire" AKA AngularFireModule v6.1.5 and want to know how to actually pass region information so that I could use functions on other regions.

This didn't work:

```<code>import { REGION } from '@angular/fire/functions';

export class Region {
  public static get getRegion() {
    const storageService = new StorageService();
    const runtimeConfig = storageService.secureStorage.getItem("runtimeConfig");
    console.log(runtimeConfig); // { "functionsRegion": "us-east4" }
    const value = runtimeConfig?.["functionsRegion"] ?? "us-central1"; // "us-east4"
    console.log("getRegion: ", value) // us-east4
    return value;
  }
}

@NgModule({
  providers: [
    { provide: REGION, useValue: Region.getRegion }
  ]
})
</code>```

I'm receiving and storing Runtime Config correctly, but functions calls are still using us-central1.

Works now after these changes:

1- Forgot to add AngularFireFunctionsModule to imports.

2- Function calls were done using the firebase library instead of Angular Fire:

This didn't work:

```<code>import firebase from "firebase";

firebase.functions().httpsCallable("helloWorld")(); // us-central1
</code>```

This however worked:

```<code>// constructor
private fns: AngularFireFunctions

//function
const callable = this.fns.httpsCallable('helloWorld'); // us-east1

//call
callable(null).subscribe(res => console.log({ res }));

</code>```

Body:
I'm using @angular/fire" AKA AngularFireModule v6.1.5 and want to know how to actually pass region information so that I could use functions on other regions.

This didn't work:

import { REGION } from '@angular/fire/functions';

export class Region {
  public static get getRegion() {
    const storageService = new StorageService();
    const runtimeConfig = storageService.secureStorage.getItem("runtimeConfig");
    console.log(runtimeConfig); // { "functionsRegion": "us-east4" }
    const value = runtimeConfig?.["functionsRegion"] ?? "us-central1"; // "us-east4"
    console.log("getRegion: ", value) // us-east4
    return value;
  }
}

@NgModule({
  providers: [
    { provide: REGION, useValue: Region.getRegion }
  ]
})

I'm receiving and storing Runtime Config correctly, but functions calls are still using us-central1.

Works now after these changes:

1- Forgot to add AngularFireFunctionsModule to imports.

2- Function calls were done using the firebase library instead of Angular Fire:

This didn't work:

import firebase from "firebase";

firebase.functions().httpsCallable("helloWorld")(); // us-central1

This however worked:

// constructor
private fns: AngularFireFunctions

//function
const callable = this.fns.httpsCallable('helloWorld'); // us-east1

//call
callable(null).subscribe(res => console.log({ res }));


问:
QML Tumbler looses vertical mouse focus
When I create a tumbler widget in QML, I can grab it, and change the contents. As soon as I leave the widget with my mouse in vertical direction, the tumbler stops changing its contents. It works fine if I leave the widget to the left or right. In that case, I can operate the tumbler even when the mouse leaves the QML window.
Is there anything I missed?

Example code:

```<code>import QtQuick 2.5
import QtQuick.Controls 2.5

Rectangle {
    width: 1000
    height: 600
    Tumbler {
        anchors.centerIn: parent
        model: 24
        width: 30
        height: 100
    }
}
</code>```

I'm using QT 6.2.1 and tried it on Kubuntu 20.04 and Yocto Dunfell.
I tried the same thing with a QML Dial. Herewith I can leave the widget in all directions, and it still reacts to my mouse movement.

Title: QML Tumbler looses vertical mouse focus

Body:
When I create a tumbler widget in QML, I can grab it, and change the contents. As soon as I leave the widget with my mouse in vertical direction, the tumbler stops changing its contents. It works fine if I leave the widget to the left or right. In that case, I can operate the tumbler even when the mouse leaves the QML window.
Is there anything I missed?

Example code:

import QtQuick 2.5
import QtQuick.Controls 2.5

Rectangle {
    width: 1000
    height: 600
    Tumbler {
        anchors.centerIn: parent
        model: 24
        width: 30
        height: 100
    }
}

I'm using QT 6.2.1 and tried it on Kubuntu 20.04 and Yocto Dunfell.
I tried the same thing with a QML Dial. Herewith I can leave the widget in all directions, and it still reacts to my mouse movement.


问:
How to configure automatic clearCache in Strapi Cache Middlware with Strapi v3?
I have a problem related with the cache middleware in strapi v3. I have two models that are not related each other but when loading the first one I am calling the second one. So my problem is:

I have the clearRelatedCache attribute enable so when something change from one of each model, it refresh the cache. Everything works fine if we call each route individually. The problem is with the first model (settings) retrieving an array from the second-one (events). If I call settings and something is changed from events it does not refresh the cache of settings

My question is, is there any magic attribute that related settings with events only in the configuration cache so every time I change something from the events the cache from settings refresh itself?

Things that I tried: I know it can work relating each other on Strapi but I cannot do that. I know it also works configuring its afterXXX method on the model but I want do find a elegant solution.


问:
How to verify response of below type where the value has multiple dynamic value using karate framework
How to verify response of below type which has dynamic value and need to be validated against test data in Examples section of scenario outline

Original response:(This is one of the key and value of the response, actual response has multiple key value. I am stuck at this point)

"NAVIGATION_KEY": "{"m_Schema":"Schema_DE_TEST","m_TableName":"PTR_DETAIL","m_KeyValues":[{"m_KeyName":"CTRY_CODE","m_KeyValue":"US"},{"m_KeyName":"CMP_CODE","m_KeyValue":"TEST"},{"m_KeyName":"PTNR_SEQ_NUM","m_KeyValue":"5648545"},{"m_KeyName":"TNS_ID","m_KeyValue":"845421"},{"m_KeyName":"TNS_TYPE","m_KeyValue":"SO"}]}",

Below is how i have parameterized, but it is not working. It is not replacing with the test data from Examples.

"NAVIGATION_KEY": "{"m_Schema":"Schema_DE_#(expectedOrg)","m_TableName":"PTR_DETAIL","m_KeyValues":[{"m_KeyName":"CTRY_CODE","m_KeyValue":"US"},{"m_KeyName":"CMP_CODE","m_KeyValue":"#(expectedOrg)"},{"m_KeyName":"PTNR_SEQ_NUM","m_KeyValue":"#notnull"},{"m_KeyName":"TNS_ID","m_KeyValue":"#notnull"},{"m_KeyName":"TNS_TYPE","m_KeyValue":"#(expectedType)"}]}",


问:
Low-Level Mouse Hook - WM_MOUSEWHEEL event data
I've implemented low level mouse hook as described in https://learn.microsoft.com/en-us/archive/blogs/toub/low-level-mouse-hook-in-c

It works fine. The only question is for WM_MOUSEWHEEL event - how to detect wheel rotation direction (forward or backward).
The system provides additional data in mouseData field only. In my tests mouseData = 7864320 for forward rotation and mouseData=4287102976 for backward rotation always.

So question: how to parse mouseData to detect the wheel rotation direction and possibly additional data related to the event?

mouseData comes from lParam

The hook provides lParam which is parsed as:

```<code>public struct MSLLHOOKSTRUCT
{
    public POINT pt;
    public uint mouseData;
    public uint flags;
    public uint time;
    public IntPtr dwExtraInfo;
}
</code>```

Body:
I've implemented low level mouse hook as described in https://learn.microsoft.com/en-us/archive/blogs/toub/low-level-mouse-hook-in-c

It works fine. The only question is for WM_MOUSEWHEEL event - how to detect wheel rotation direction (forward or backward).
The system provides additional data in mouseData field only. In my tests mouseData = 7864320 for forward rotation and mouseData=4287102976 for backward rotation always.

So question: how to parse mouseData to detect the wheel rotation direction and possibly additional data related to the event?

mouseData comes from lParam

The hook provides lParam which is parsed as:

public struct MSLLHOOKSTRUCT
{
    public POINT pt;
    public uint mouseData;
    public uint flags;
    public uint time;
    public IntPtr dwExtraInfo;
}


问:
Condition Based Result In another Column
I want to give condition in column B based on Column A data.
Example ColA have data Score i.e 80,90,40,50,60,70
and I want Column B should come If ColA=80 then "Good",90 then "Excellent",60 then Average

I am trying on it but output is not coming ok


问:
copy multiple files from yesterday to specific folder powershell script
I am trying to copy all files changed/created yesterday from a certain folder to another certain folder. It writes errors and also does not paste the files into the folder.

Here is the script:

```<code>$DestinationFolder = "D:\Dropbox\Public\Download\New folder"
  If(!(test-path $DestinationFolder))
  {
        New-Item -ItemType Directory -Force -Path $DestinationFolder
  }
  $EarliestModifiedTime = (Get-date).AddDays(-1).ToString("MM/dd/yyyy")

  $Files = Get-ChildItem "C:\Users\Harel Gordon\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\" -File

  foreach ($File in $Files)
  {
      if ($File.LastWriteTime.ToString("MM/dd/yyyy") -eq $EarliestModifiedTime)
      {
          Copy-Item $File -Destination $DestinationFolder
          Write-Host "Copying $File"
      }
      else
      {
          Write-Host "Not copying $File"
      }
  }

Read-Host -Prompt "Press Enter to exit"
</code>```

These are the errors:

enter image description here

It worked for a while then stopped. do not know why

Body:
I am trying to copy all files changed/created yesterday from a certain folder to another certain folder. It writes errors and also does not paste the files into the folder.

Here is the script:

$DestinationFolder = "D:\Dropbox\Public\Download\New folder"
  If(!(test-path $DestinationFolder))
  {
        New-Item -ItemType Directory -Force -Path $DestinationFolder
  }
  $EarliestModifiedTime = (Get-date).AddDays(-1).ToString("MM/dd/yyyy")

  $Files = Get-ChildItem "C:\Users\Harel Gordon\AppData\Local\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets\" -File

  foreach ($File in $Files)
  {
      if ($File.LastWriteTime.ToString("MM/dd/yyyy") -eq $EarliestModifiedTime)
      {
          Copy-Item $File -Destination $DestinationFolder
          Write-Host "Copying $File"
      }
      else
      {
          Write-Host "Not copying $File"
      }
  }

Read-Host -Prompt "Press Enter to exit"

These are the errors:

enter image description here

It worked for a while then stopped. do not know why


问:
Issue while pushing branch into remote (jgit)
Hi i created a branch and added some files on that and checked out that branch after that if I try pushing the branch it is not pushed to remote only inital commit gets pushed each and everytime

Here is the code

```<code>
    private void remotePush(GitDto gitDto, CredentialsProvider credential, File destination)
    {
        try (Repository repository = repositoryBuilder(destination)) {
            try (Git git = Git.open(destination)) {
                git.checkout().setName(gitDto.getBranchName()).call(); git.commit().setAll(true).setMessage(gitDto.getCommitMessage()).call();
                git.push().setRemote("origin").setCredentialsProvider(credential)
                   .setRefSpecs(new RefSpec(gitDto.getBranchName() + ":" + gitDto.getBranchName()))
                    .call();
            } catch (RefNotFoundException e)
            {
                throw new RuntimeException(e);
            }
            catch (RefAlreadyExistsException e)
            {
                throw new RuntimeException(e);
            }
            catch (InvalidRefNameException e)
            {
                throw new RuntimeException(e);
            }
            catch (CheckoutConflictException e)
            {
                throw new RuntimeException(e);
            }
            catch (GitAPIException e) { throw new RuntimeException(e); }
        } catch (IOException e) { throw new RuntimeException(e); }
    }
</code>```

Thanks in advance

Body:
Hi i created a branch and added some files on that and checked out that branch after that if I try pushing the branch it is not pushed to remote only inital commit gets pushed each and everytime

Here is the code

    private void remotePush(GitDto gitDto, CredentialsProvider credential, File destination)
    {
        try (Repository repository = repositoryBuilder(destination)) {
            try (Git git = Git.open(destination)) {
                git.checkout().setName(gitDto.getBranchName()).call(); git.commit().setAll(true).setMessage(gitDto.getCommitMessage()).call();
                git.push().setRemote("origin").setCredentialsProvider(credential)
                   .setRefSpecs(new RefSpec(gitDto.getBranchName() + ":" + gitDto.getBranchName()))
                    .call();
            } catch (RefNotFoundException e)
            {
                throw new RuntimeException(e);
            }
            catch (RefAlreadyExistsException e)
            {
                throw new RuntimeException(e);
            }
            catch (InvalidRefNameException e)
            {
                throw new RuntimeException(e);
            }
            catch (CheckoutConflictException e)
            {
                throw new RuntimeException(e);
            }
            catch (GitAPIException e) { throw new RuntimeException(e); }
        } catch (IOException e) { throw new RuntimeException(e); }
    }

Thanks in advance


问:
How to incorporate Api into Android Studio
I am using Android Studio with Kotlin language.
I have created my front end.
I have the DB linked in this app but my API is done in a different App.

I am battling to figure out how to put my API into my App and have them communicate.
How would I incorporate the API so that my App uses the API to check, validate, read and write data into the database?

The API was created using .js and .json files.

Any assistance will be greatly appreciated.
Thank you


问:
Why is a particular file's tag surrounding the <App> tag in index.js rather than being in App.js file?
I am learning React and while creating the project the mentor used the products_context.js and added some reducers to it, but then he surrounded the  tag with this component's tag. I am trying to understand why did he do that in the main index.js and not in App.js file?

products_context.js

```<code>import axios from 'axios'
import React, { useContext, useEffect, useReducer } from 'react'
import reducer from '../reducers/products_reducer'
import { products_url as url } from '../utils/constants'
import {
  SIDEBAR_OPEN,
  SIDEBAR_CLOSE,
  GET_PRODUCTS_BEGIN,
  GET_PRODUCTS_SUCCESS,
  GET_PRODUCTS_ERROR,
  GET_SINGLE_PRODUCT_BEGIN,
  GET_SINGLE_PRODUCT_SUCCESS,
  GET_SINGLE_PRODUCT_ERROR,
} from '../actions'

const initialState = {
  isSidebarOpen: false,
}

const ProductsContext = React.createContext()

export const ProductsProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState)

  const openSidebar = () => {
    dispatch({ type: SIDEBAR_OPEN })
  }

  const closeSidebar = () => {
    dispatch({ type: SIDEBAR_CLOSE })
  }

  return (
    <ProductsContext.Provider value='products context'>
      {children}
    </ProductsContext.Provider>
  )
}
// make sure use
export const useProductsContext = () => {
  return useContext(ProductsContext)
}

</code>```

index.js

```<code>import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'

import { ProductsProvider } from './context/products_context'
import { FilterProvider } from './context/filter_context'
import { CartProvider } from './context/cart_context'
import { UserProvider } from './context/user_context'
import { Auth0Provider } from '@auth0/auth0-react'

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(
  <ProductsProvider>
    <App />
  </ProductsProvider>
)

</code>```

App.js

```<code>import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { Navbar, Sidebar, Footer } from './components'
import {
  Home,
  Products,
  SingleProduct,
  About,
  Cart,
  Checkout,
  Error,
  AuthWrapper,
  PrivateRoute,
} from './pages'

function App() {
  return (
    <Router>
      <Navbar />
      <Sidebar />
      <Switch>
        <Route exact path='/'>
          <Home />
        </Route>
        <Route exact path='/about'>
          <About />
        </Route>
        <Route exact path='/cart'>
          <Cart />
        </Route>
        <Route exact path='/products'>
          <Products />
        </Route>
        <Route exact path='/products/:id' children={<SingleProduct />} />
        <Route exact path='/checkout'>
          <Checkout />
        </Route>
        <Route exact path='*'>
          <Error />
        </Route>
      </Switch>
      <Footer />
    </Router>
  )
}

export default App

</code>```

I am just trying to uderstand the reason for this code structure.

Body:
I am learning React and while creating the project the mentor used the products_context.js and added some reducers to it, but then he surrounded the  tag with this component's tag. I am trying to understand why did he do that in the main index.js and not in App.js file?

products_context.js

import axios from 'axios'
import React, { useContext, useEffect, useReducer } from 'react'
import reducer from '../reducers/products_reducer'
import { products_url as url } from '../utils/constants'
import {
  SIDEBAR_OPEN,
  SIDEBAR_CLOSE,
  GET_PRODUCTS_BEGIN,
  GET_PRODUCTS_SUCCESS,
  GET_PRODUCTS_ERROR,
  GET_SINGLE_PRODUCT_BEGIN,
  GET_SINGLE_PRODUCT_SUCCESS,
  GET_SINGLE_PRODUCT_ERROR,
} from '../actions'

const initialState = {
  isSidebarOpen: false,
}

const ProductsContext = React.createContext()

export const ProductsProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState)

  const openSidebar = () => {
    dispatch({ type: SIDEBAR_OPEN })
  }

  const closeSidebar = () => {
    dispatch({ type: SIDEBAR_CLOSE })
  }

  return (
    <ProductsContext.Provider value='products context'>
      {children}
    </ProductsContext.Provider>
  )
}
// make sure use
export const useProductsContext = () => {
  return useContext(ProductsContext)
}

index.js

import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'

import { ProductsProvider } from './context/products_context'
import { FilterProvider } from './context/filter_context'
import { CartProvider } from './context/cart_context'
import { UserProvider } from './context/user_context'
import { Auth0Provider } from '@auth0/auth0-react'

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(
  <ProductsProvider>
    <App />
  </ProductsProvider>
)

App.js

import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { Navbar, Sidebar, Footer } from './components'
import {
  Home,
  Products,
  SingleProduct,
  About,
  Cart,
  Checkout,
  Error,
  AuthWrapper,
  PrivateRoute,
} from './pages'

function App() {
  return (
    <Router>
      <Navbar />
      <Sidebar />
      <Switch>
        <Route exact path='/'>
          <Home />
        </Route>
        <Route exact path='/about'>
          <About />
        </Route>
        <Route exact path='/cart'>
          <Cart />
        </Route>
        <Route exact path='/products'>
          <Products />
        </Route>
        <Route exact path='/products/:id' children={<SingleProduct />} />
        <Route exact path='/checkout'>
          <Checkout />
        </Route>
        <Route exact path='*'>
          <Error />
        </Route>
      </Switch>

    </Router>
  )
}

export default App

I am just trying to uderstand the reason for this code structure.


问:
Oracle OJDBC MERGE Statement and Generated Keys
Does Oracle ~>12 support generated keys using a Merge statement? Some sudo code..

```<code>MERGE INTO TARGET_TABLE TRG
USING (SELECT CAST(? AS NUMBER) AS ID FROM DUAL) SRC
ON (TRG.ID = SRC.ID)
WHEN MATCHED THEN UPDATE SET....
WHEN NOT MATCHED THEN
    INSERT(ID....)
    VALUES(MYSEQ.NEXTVAL...)

</code>```

The prepared statement is set up;

```<code>try (PreparedStatement pstmt =
              connection.prepareStatement(
                  loadStatement(sqlName, connection, getClass()), new String[] {ID})) {
...
int inserted = pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();

List<Long> keys = new ArrayList<>(inserted);
while (rs.next) {
    rs.getLong(1);
}
return keys;
...

</code>```

I have in-memory tests where the connection uses the H2 driver running the very same SQL and PreparedStatment and that returns the generated key just fine, but Oracle does not.

Reviewing the docs it would suggest it does not?

Thanks!

Body:
Does Oracle ~>12 support generated keys using a Merge statement? Some sudo code..

MERGE INTO TARGET_TABLE TRG
USING (SELECT CAST(? AS NUMBER) AS ID FROM DUAL) SRC
ON (TRG.ID = SRC.ID)
WHEN MATCHED THEN UPDATE SET....
WHEN NOT MATCHED THEN
    INSERT(ID....)
    VALUES(MYSEQ.NEXTVAL...)

The prepared statement is set up;

try (PreparedStatement pstmt =
              connection.prepareStatement(
                  loadStatement(sqlName, connection, getClass()), new String[] {ID})) {
...
int inserted = pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();

List<Long> keys = new ArrayList<>(inserted);
while (rs.next) {
    rs.getLong(1);
}
return keys;
...

I have in-memory tests where the connection uses the H2 driver running the very same SQL and PreparedStatment and that returns the generated key just fine, but Oracle does not.

Reviewing the docs it would suggest it does not?

Thanks!


问:
material UI with nextjs dark mode bug
I have set up a test next js app.

TLDR: Here is the repo code and also code sandbox. Clone and then npm run dev and then Switch to dark mode and refresh the page. You will see inconsistency in styles.

I did everything that was mentioned in mui example for next js. I tried adding both dark mode and light mode support for static site generation but couldn't make it work properly. The code inside pages/_document.js and src/createEmotionCache.js are the same as the code in the example. in pages/_app.js I simply get the initialPaletteMode from localStorage and send it to src/Layout.js. Inside Layout, I set paletteMode (default is light) based on initialPaletteMode and will set new theme if the user has clicked on the toggle button. On first page load everything works fine. But if you toggle to dark mode and then refresh the page, since the server rendered html differs from that of client (light mode on server and dark mode on client), you will see body color in light mode and other styles in dark mode. Isn't there an official way to fix this issue? I'm looking for a good example to support both dark mode and light mode without flickers and using static site generation. Thanks in advance

pages/_document.js

```<code>import * as React from "react"
import Document, { Html, Head, Main, NextScript } from "next/document"
import createEmotionServer from "@emotion/server/create-instance"
import createEmotionCache from "../src/createEmotionCache"

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <link rel="shortcut icon" href="/favicon.ico" />
          <meta name="emotion-insertion-point" content="" />
          {this.props.emotionStyleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static-site generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
  // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render

  const originalRenderPage = ctx.renderPage

  // You can consider sharing the same Emotion cache between all the SSR requests to speed up performance.
  // However, be aware that it can have global side effects.
  const cache = createEmotionCache()
  const { extractCriticalToChunks } = createEmotionServer(cache)

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return (
            <App emotionCache={cache} initialPaletteMode="unset" {...props} />
          )
        }
    })

  const initialProps = await Document.getInitialProps(ctx)
  // This is important. It prevents Emotion to render invalid HTML.
  // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
  const emotionStyles = extractCriticalToChunks(initialProps.html)
  const emotionStyleTags = emotionStyles.styles.map((style) => (
    <style
      data-emotion={`${style.key} ${style.ids.join(" ")}`}
      key={style.key}
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{ __html: style.css }}
    />
  ))

  return {
    ...initialProps,
    emotionStyleTags
  }
}
</code>```

pages/_app.js

```<code>import * as React from "react"
import PropTypes from "prop-types"
import Head from "next/head"
import { CacheProvider } from "@emotion/react"
import createEmotionCache from "../src/createEmotionCache"
import Layout from "../src/Layout"

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache()

let clientPaletteMode
if (typeof window !== "undefined") {
  clientPaletteMode = localStorage.getItem("mode") || "unset"
}

export default function MyApp(props) {
  const {
    Component,
    emotionCache = clientSideEmotionCache,
    initialPaletteMode = clientPaletteMode,
    pageProps
  } = props

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <Layout initialPaletteMode={initialPaletteMode}>
        <Component {...pageProps} />
      </Layout>
    </CacheProvider>
  )
}

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  emotionCache: PropTypes.object,
  pageProps: PropTypes.object.isRequired
}
</code>```

pages/index.js

```<code>import * as React from "react"
import Typography from "@mui/material/Typography"
import { useTheme } from "@mui/material"

export default function Index() {
  const theme = useTheme()
  return (
    <Typography variant="h1" color="primary.main" mb={4}>
      {theme.palette.mode} mode
    </Typography>
  )
}

export const getStaticProps = async () => {
  return {
    props: {}
  }
}
</code>```

src/createEmotionCache.js

```<code>import createCache from "@emotion/cache"

const isBrowser = typeof document !== "undefined"

// On the client side, Create a meta tag at the top of the <head> and set it as insertionPoint.
// This assures that MUI styles are loaded first.
// It allows developers to easily override MUI styles with other styling solutions, like CSS modules.
export default function createEmotionCache() {
  let insertionPoint

  if (isBrowser) {
    const emotionInsertionPoint = document.querySelector(
      'meta[name="emotion-insertion-point"]'
    )
    insertionPoint = emotionInsertionPoint ?? undefined
  }

  return createCache({ key: "mui-style", insertionPoint })
}
</code>```

src/Layout.js

```<code>import React from "react"
import { Button, CssBaseline, ThemeProvider } from "@mui/material"
import { useEffect, useState } from "react"
import themes from "./theme"

const getInitialPaletteMode = (initialPaletteMode) => {
  if (initialPaletteMode === "unset") {
    return "light"
  } else {
    return initialPaletteMode
  }
}

const Layout = ({ children, initialPaletteMode }) => {
  const [paletteMode, setPaletteMode] = useState(
    getInitialPaletteMode(initialPaletteMode)
  )
  const [theme, setTheme] = useState(themes[paletteMode])

  useEffect(() => {
    localStorage.setItem("mode", paletteMode)
    setTheme(themes[paletteMode])
  }, [paletteMode])

  const toggleTheme = () => {
    setPaletteMode(paletteMode === "dark" ? "light" : "dark")
  }

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {children}
      <Button onClick={toggleTheme}>Toggle theme</Button>
    </ThemeProvider>
  )
}

export default Layout
</code>```

src/theme.js

```<code>import { blue, red } from "@mui/material/colors"
import { createTheme } from "@mui/material/styles"

// Create a theme instance.
const lightTheme = createTheme({
  palette: {
    mode: "light",
    primary: red
  }
})

const darkTheme = createTheme({
  palette: {
    mode: "dark",
    primary: blue
  }
})

const themes = {
  dark: darkTheme,
  light: lightTheme
}

export default themes
</code>```

Title: material UI with nextjs dark mode bug

Body:
I have set up a test next js app.

TLDR: Here is the repo code and also code sandbox. Clone and then npm run dev and then Switch to dark mode and refresh the page. You will see inconsistency in styles.

I did everything that was mentioned in mui example for next js. I tried adding both dark mode and light mode support for static site generation but couldn't make it work properly. The code inside pages/_document.js and src/createEmotionCache.js are the same as the code in the example. in pages/_app.js I simply get the initialPaletteMode from localStorage and send it to src/Layout.js. Inside Layout, I set paletteMode (default is light) based on initialPaletteMode and will set new theme if the user has clicked on the toggle button. On first page load everything works fine. But if you toggle to dark mode and then refresh the page, since the server rendered html differs from that of client (light mode on server and dark mode on client), you will see body color in light mode and other styles in dark mode. Isn't there an official way to fix this issue? I'm looking for a good example to support both dark mode and light mode without flickers and using static site generation. Thanks in advance

pages/_document.js

import * as React from "react"
import Document, { Html, Head, Main, NextScript } from "next/document"
import createEmotionServer from "@emotion/server/create-instance"
import createEmotionCache from "../src/createEmotionCache"

export default class MyDocument extends Document {
  render() {
    return (

          <link rel="shortcut icon" href="/favicon.ico" />
          <meta name="emotion-insertion-point" content="" />
          {this.props.emotionStyleTags}

          <NextScript />

    )
  }
}

// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static-site generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
  // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render

  const originalRenderPage = ctx.renderPage

  // You can consider sharing the same Emotion cache between all the SSR requests to speed up performance.
  // However, be aware that it can have global side effects.
  const cache = createEmotionCache()
  const { extractCriticalToChunks } = createEmotionServer(cache)

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) =>
        function EnhanceApp(props) {
          return (
            <App emotionCache={cache} initialPaletteMode="unset" {...props} />
          )
        }
    })

  const initialProps = await Document.getInitialProps(ctx)
  // This is important. It prevents Emotion to render invalid HTML.
  // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
  const emotionStyles = extractCriticalToChunks(initialProps.html)
  const emotionStyleTags = emotionStyles.styles.map((style) => (


问:
How can i append twig templates inside a loop?
Here i am iterating through a loop and rendering different twig templates inside a div with id {{ divId }} on the action of click. But when i am doing this, the html is rendering separately instead of rendering inside the div. Here i am attaching the code and image to further explain the issue.

```<code><script id="template_{{ field_id }}" type="text/html">

                {% set scriptSeperatorId = 'separator_' ~ field_id ~ "-" ~ '{section_id}' %}
                <span class="sepRater" id="{{ scriptSeperatorId }}"></span>
                {% set divId = field_id ~ '-{section_id}' %}
                <div id="{{ divId }}">
                    {% for multi_input_template_field_key, multi_input_template_field_details in multi_input_template_fields %}
                        {% set multi_input_template_field_id = field_id ~ '-' ~ '{section_id}' ~ '-' ~ multi_input_template_field_key %}
                        {% set multi_input_template_field_name = field_name ~ ':' ~ '{section_id}' ~ ':' ~ multi_input_template_field_key %}
                        {% set multi_input_template_field_value = '' %}

                        {% if multi_input_template_field_details[default] is defined %}
                            {% set multi_input_template_field_value = multi_input_template_field_details.default %}
                        {% endif %}

                        {% set view_data = {} %}
                        {% set view_data = view_data|merge({'field_id': (multi_input_template_field_id)}) %}
                        {% set view_data = view_data|merge({'field_name': (multi_input_template_field_name)}) %}
                        {% set view_data = view_data|merge({'field_value': (multi_input_template_field_value)}) %}
                        {% set view_data = view_data|merge({'field_details': (multi_input_template_field_details)}) %}

                        {% set data = {} %}
                        {% set data = data|merge({'view_data': (view_data)}) %}
                        {% set data = data|merge({'field_details': (multi_input_template_field_details)}) %}
                        {% set data = data|merge({'categories': (categories)}) %}

                        {% include "field-type-render.html.twig" with data %}
                    {% endfor %}

                    <div class="form-box">
                        <label class="pure-material-textfield-outlined smBtnArea">
                            <button type="button" class=" btn btn-info btn-ad  removeBtn"  id="remove_multiinput_section_{{ field_id }}-{section_id}">Remove</button>
                            <span style="color:red;display:none;" class="spancantremove{{ field_id }}-{section_id}">You can't remove the last element </span>
                        </label>
                    </div>
                </div>
            </script>
</code>```

The type of output i am supposed to get is:

The output i am getting:

Body:
Here i am iterating through a loop and rendering different twig templates inside a div with id {{ divId }} on the action of click. But when i am doing this, the html is rendering separately instead of rendering inside the div. Here i am attaching the code and image to further explain the issue.

The type of output i am supposed to get is:

The output i am getting:


问:
AMQ222082: error on connection failure check: java.lang.OutOfMemoryError: unable to create new native thread
I have an application deployed on WildFly, and I use the domain mode.  The VM used for deployment is full saturation when I checked the log I found the size of the server log file so big (approximately 25G). When I checked the log I found this warning is repeated:

```<code>2023-01-05 09:55:15,693 WARN  [org.apache.activemq.artemis.core.server] (activemq-failure-check-thread) AMQ222082: error on connection failure check: java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:717)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:957)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1378)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.onAddedTaskIfNotRunning(ProcessorBase.java:205)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.task(ProcessorBase.java:193)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.execute(OrderedExecutor.java:54)
    at org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl$FailureCheckAndFlushThread.run(RemotingServiceImpl.java:709)
</code>```

Can anyone here helps with this problem? I don't know I think that is due to the heap memory, but here I'm in the prod profile so what do you think?

Body:
I have an application deployed on WildFly, and I use the domain mode.  The VM used for deployment is full saturation when I checked the log I found the size of the server log file so big (approximately 25G). When I checked the log I found this warning is repeated:

2023-01-05 09:55:15,693 WARN  [org.apache.activemq.artemis.core.server] (activemq-failure-check-thread) AMQ222082: error on connection failure check: java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:717)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:957)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1378)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.onAddedTaskIfNotRunning(ProcessorBase.java:205)
    at org.apache.activemq.artemis.utils.actors.ProcessorBase.task(ProcessorBase.java:193)
    at org.apache.activemq.artemis.utils.actors.OrderedExecutor.execute(OrderedExecutor.java:54)
    at org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl$FailureCheckAndFlushThread.run(RemotingServiceImpl.java:709)

Can anyone here helps with this problem? I don't know I think that is due to the heap memory, but here I'm in the prod profile so what do you think?


问:
Replacement of LdapURL class in java 11
I was using LdapURL class like below using Java 8, now I have upgraded to java 11 so I need replacement of this class.

```<code>LdapURL ldapURL = new LdapURL(ldapDomain);
if (!ldapURL.useSsl()) {
    profiles.add("non-secure-LDAP");
} else {
    profiles.add("secure-LDAP");
}
</code>```

Could someone help.

Title: Replacement of LdapURL class in java 11

Body:
I was using LdapURL class like below using Java 8, now I have upgraded to java 11 so I need replacement of this class.

LdapURL ldapURL = new LdapURL(ldapDomain);
if (!ldapURL.useSsl()) {
    profiles.add("non-secure-LDAP");
} else {
    profiles.add("secure-LDAP");
}

Could someone help.


问:
The treeview border got hidden after applying this style
I have applied this style to tkinter treeview but the data separator line got vanished

```<code>style_def = ttk.Style(frametree)
style_def.configure("Treeview",
    background="#FFDEAD",fieldbackground="#FFDEAD", foreground="Black",
    font=(None, 14), sheight=14, rowheight=30)
style_def.configure("Treeview.Heading",font=(None, 12))
</code>```

I have tried without the style it works fine but when I merge it with the app which already has treeview, all the treeview gets the same style .So I changed the styling method and now I used the following.

```<code>style_defect = ttk.Style()
        style_defect.configure("fordefect.Treeview", background="#FFDEAD", foreground="black", fieldbackground="#FFDEAD",font=(None, 14), sheight=14, rowheight=30)
        style_defect.configure('fordefect.Treeview.Heading', background="white", font=('calibre', 14,"bold"))
        style_defect.map('fordefect.Treeview', background=[('selected', '#1E90FF')], foreground=[('selected', 'white')])
        self.tree = ttk.Treeview(frametree,height=26,style="fordefect.Treeview")
</code>```

But now the border/item separator line has gone

Body:
I have applied this style to tkinter treeview but the data separator line got vanished

style_def = ttk.Style(frametree)
style_def.configure("Treeview",
    background="#FFDEAD",fieldbackground="#FFDEAD", foreground="Black",
    font=(None, 14), sheight=14, rowheight=30)
style_def.configure("Treeview.Heading",font=(None, 12))

I have tried without the style it works fine but when I merge it with the app which already has treeview, all the treeview gets the same style .So I changed the styling method and now I used the following.

style_defect = ttk.Style()
        style_defect.configure("fordefect.Treeview", background="#FFDEAD", foreground="black", fieldbackground="#FFDEAD",font=(None, 14), sheight=14, rowheight=30)
        style_defect.configure('fordefect.Treeview.Heading', background="white", font=('calibre', 14,"bold"))
        style_defect.map('fordefect.Treeview', background=[('selected', '#1E90FF')], foreground=[('selected', 'white')])
        self.tree = ttk.Treeview(frametree,height=26,style="fordefect.Treeview")

But now the border/item separator line has gone


问:
Download TikTok video without watermark using Python and TiktokApi
I am trying to download a TikTok video without the watermark based on the link, and I am using the TiktokApi package for this, but I am getting some exceptions when trying 2 different versions :

```<code>from TikTokApi import TikTokApi

api = TikTokApi()
url = 'TIKTOK_URL_HERE'
video_bytes = api.get_video_no_watermark(url)

with open("nature.mp4", 'wb') as output:
    output.write(video_bytes)
</code>```

With 5.2.2/Latest version I got :

```<code>AttributeError: 'TikTokApi' object has no attribute 'get_video_no_watermark'
</code>```

And when downgrading to 4.1.0, it tells that the method is deprecated :

```<code>Exception: Deprecated method, TikTok fixed this.
</code>```

I already run this install :

```<code>python -m playwright install
</code>```

If anyone has a solution for this, or maybe another package that will do the job?

Body:
I am trying to download a TikTok video without the watermark based on the link, and I am using the TiktokApi package for this, but I am getting some exceptions when trying 2 different versions :

from TikTokApi import TikTokApi

api = TikTokApi()
url = 'TIKTOK_URL_HERE'
video_bytes = api.get_video_no_watermark(url)

with open("nature.mp4", 'wb') as output:
    output.write(video_bytes)

With 5.2.2/Latest version I got :

AttributeError: 'TikTokApi' object has no attribute 'get_video_no_watermark'

And when downgrading to 4.1.0, it tells that the method is deprecated :

Exception: Deprecated method, TikTok fixed this.

I already run this install :

python -m playwright install

If anyone has a solution for this, or maybe another package that will do the job?


问:
PHP/Dokan/WooCommerce. Change input type="text" to input="checkbox"
We have a WordPress site using Dokan.
I'd like to add a checkbox where the user can check whether the product should be a donation.
I got this snippet that I'm trying to modify. My PHP is a bit too basic. Please help.

```<code>/*
* Adding extra field on New product popup/without popup form
*/

add_action( 'dokan_new_product_after_product_tags','new_product_field',10 );

function new_product_field(){ ?>

     <div class="dokan-form-group">

              <input type="text" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">
        </div>

   <?php
}

/*
* Saving product field data for edit and update
*/

 add_action( 'dokan_new_product_added','save_add_product_meta', 10, 2 );
 add_action( 'dokan_product_updated', 'save_add_product_meta', 10, 2 );

function save_add_product_meta($product_id, $postdata){

    if ( ! dokan_is_user_seller( get_current_user_id() ) ) {
            return;
        }

        if ( ! empty( $postdata['new_field'] ) ) {
            update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
        }
}

/*
* Showing field data on product edit page
*/

add_action('dokan_product_edit_after_product_tags','show_on_edit_page',99,2);

function show_on_edit_page($post, $post_id){
$new_field         = get_post_meta( $post_id, 'new_field', true );
?>
   <div class="dokan-form-group">
        <input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
        <label for="new_field" class="form-label"><?php esc_html_e( 'Product Code', 'dokan-lite' ); ?></label>
        <?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>
        <div class="dokan-product-title-alert dokan-hide">
         <?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>
        </div>
     </div> <?php

    }

// showing on single product page
add_action('woocommerce_single_product_summary','show_product_code',13);

function show_product_code(){
      global $product;

        if ( empty( $product ) ) {
            return;
        }
 $new_field = get_post_meta( $product->get_id(), 'new_field', true );

        if ( ! empty( $new_field ) ) {
            ?>
                  <span class="details"><?php echo esc_attr__( 'Product Code:', 'dokan-lite' ); ?> <strong><?php echo esc_attr( $new_field ); ?></strong></span>
            <?php
        }
}
</code>```

This is how far I got:

```<code>/*
* Adding extra field on New product popup/without popup form
*/

add_action( 'dokan_new_product_after_product_tags','new_product_field',10 );

function new_product_field(){ ?>

     <div class="dokan-form-group">

              <input type="checkbox" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">
        </div>

   <?php
}

/*
* Saving product field data for edit and update
*/

 add_action( 'dokan_new_product_added','save_add_product_meta', 10, 2 );
 add_action( 'dokan_product_updated', 'save_add_product_meta', 10, 2 );

function save_add_product_meta($product_id, $postdata){

    if ( ! dokan_is_user_seller( get_current_user_id() ) ) {
            return;
        }

        if ( ! empty( $postdata['new_field'] ) ) {
            update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
        }
}

/*
* Showing field data on product edit page
*/

add_action('dokan_product_edit_after_product_tags','show_on_edit_page',99,2);

function show_on_edit_page($post, $post_id){
$new_field         = get_post_meta( $post_id, 'new_field', true );
?>
   <div class="dokan-form-group">
        <input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
        <label for="new_field" class="form-label"><?php esc_html_e( 'Product Code', 'dokan-lite' ); ?></label>
        <?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>
        <div class="dokan-product-title-alert dokan-hide">
         <?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>
        </div>
     </div> <?php

    }

// showing on single product page
add_action('woocommerce_single_product_summary','show_product_code',13);

function show_product_code(){
      global $product;

        if ( empty( $product ) ) {
            return;
        }
 $new_field = get_post_meta( $product->get_id(), 'new_field', true );

        if ( ! empty( $new_field ) ) {
            ?>
                  <span class="details"><?php echo esc_attr__( 'Donation Product', 'dokan-lite' ); ?> <strong><?php echo esc_attr( $new_field ); ?></strong></span>
            <?php
        }
}
</code>```

The rest I'm struggling with. Many thanks for any help on this.

Body:
We have a WordPress site using Dokan.
I'd like to add a checkbox where the user can check whether the product should be a donation.
I got this snippet that I'm trying to modify. My PHP is a bit too basic. Please help.

/*
* Adding extra field on New product popup/without popup form
*/

add_action( 'dokan_new_product_after_product_tags','new_product_field',10 );

function new_product_field(){ ?>

              <input type="text" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">

   <?php
}

/*
* Saving product field data for edit and update
*/

 add_action( 'dokan_new_product_added','save_add_product_meta', 10, 2 );
 add_action( 'dokan_product_updated', 'save_add_product_meta', 10, 2 );

function save_add_product_meta($product_id, $postdata){

    if ( ! dokan_is_user_seller( get_current_user_id() ) ) {
            return;
        }

        if ( ! empty( $postdata['new_field'] ) ) {
            update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
        }
}

/*
* Showing field data on product edit page
*/

add_action('dokan_product_edit_after_product_tags','show_on_edit_page',99,2);

function show_on_edit_page($post, $post_id){
$new_field         = get_post_meta( $post_id, 'new_field', true );
?>

        <input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
        <?php esc_html_e( 'Product Code', 'dokan-lite' ); ?>
        <?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>

         <?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>

 <?php

    }

// showing on single product page
add_action('woocommerce_single_product_summary','show_product_code',13);

function show_product_code(){
      global $product;

        if ( empty( $product ) ) {
            return;
        }
 $new_field = get_post_meta( $product->get_id(), 'new_field', true );

        if ( ! empty( $new_field ) ) {
            ?>
                  <?php echo esc_attr__( 'Product Code:', 'dokan-lite' ); ?> <?php echo esc_attr( $new_field ); ?>
            <?php
        }
}

This is how far I got:

/*
* Adding extra field on New product popup/without popup form
*/

add_action( 'dokan_new_product_after_product_tags','new_product_field',10 );

function new_product_field(){ ?>

              <input type="checkbox" class="dokan-form-control" name="new_field" placeholder="<?php esc_attr_e( 'Product Code', 'dokan-lite' ); ?>">

   <?php
}

/*
* Saving product field data for edit and update
*/

 add_action( 'dokan_new_product_added','save_add_product_meta', 10, 2 );
 add_action( 'dokan_product_updated', 'save_add_product_meta', 10, 2 );

function save_add_product_meta($product_id, $postdata){

    if ( ! dokan_is_user_seller( get_current_user_id() ) ) {
            return;
        }

        if ( ! empty( $postdata['new_field'] ) ) {
            update_post_meta( $product_id, 'new_field', $postdata['new_field'] );
        }
}

/*
* Showing field data on product edit page
*/

add_action('dokan_product_edit_after_product_tags','show_on_edit_page',99,2);

function show_on_edit_page($post, $post_id){
$new_field         = get_post_meta( $post_id, 'new_field', true );
?>

        <input type="hidden" name="new_field" id="dokan-edit-product-id" value="<?php echo esc_attr( $post_id ); ?>"/>
        <?php esc_html_e( 'Product Code', 'dokan-lite' ); ?>
        <?php dokan_post_input_box( $post_id, 'new_field', array( 'placeholder' => __( 'product code', 'dokan-lite' ), 'value' => $new_field ) ); ?>

         <?php esc_html_e( 'Please enter product code!', 'dokan-lite' ); ?>

 <?php

    }

// showing on single product page
add_action('woocommerce_single_product_summary','show_product_code',13);

function show_product_code(){
      global $product;

        if ( empty( $product ) ) {
            return;
        }
 $new_field = get_post_meta( $product->get_id(), 'new_field', true );

        if ( ! empty( $new_field ) ) {
            ?>
                  <?php echo esc_attr__( 'Donation Product', 'dokan-lite' ); ?> <?php echo esc_attr( $new_field ); ?>
            <?php
        }
}

The rest I'm struggling with. Many thanks for any help on this.


问:
RTK Query vs CreateAysncThunk updating state
I built a project a little while ago using Redux Toolkit and CreateAsyncThunk. I am now working on a new project using RTK Query.

In the documentation for RTK Query:

Currently,  is specifically importing useSelector,
useDispatch, and useEffect, reading posts data and loading state from
the store, and dispatching the fetchPosts() thunk on mount to trigger
the data fetch. The useGetPostsQueryHook replaces all of that!

Now previously, I sometimes changed the global state directly in a CreateAsyncThunk.fulfilled

```<code>let user = sessionStorage.getItem("user");

const initialState: AuthState = {
  user: user ? user : null,
  message: "",
  isError: false,
  isLoading: false,
  isSuccess: false,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(Signin.pending, (state) => {
        state.isLoading = true;
        state.isError = false;
        state.isSuccess = false;
      })
      .addCase(Signin.fulfilled, (state, action) => {
        //updating the state of user as soon as creatAsyncThunk finishes no additional dispatch
        state.user = action.payload.RefreshToken;
        state.isLoading = false;
        state.isError = false;
        state.isSuccess = true;
      })
      .addCase(Signin.rejected, (state) => {
        state.isLoading = false;
        state.isError = true;
        state.isSuccess = false;
      });
  },
});
</code>```

Where I need clarification is in an auth example for RTK query they use RTK query with dispatch, they just dispatch the result, is there no way and or is it just bad practice to change the global state from an RTK Query. (comments are my own)

```<code> <Button
          isFullWidth
          onClick={async () => {
            try {
              //call use query
              const user = await login(formState).unwrap()
              //additional dispatch if you want to actually change the state in store
              dispatch(setCredentials(user))
              navigate('/')
            } catch (err) {
              toast({
                status: 'error',
                title: 'Error',
                description: 'Oh no, there was an error!',
                isClosable: true,
              })
            }
          }}
          colorScheme="green"
          isLoading={isLoading}
        >
</code>```

Is the normal flow going to be dispatching the results of an RTK query and is there no way to have the RTK query itself change/update the state from the Query so that you are really getting rid of the use Dispatches like how I am understanding the original quote in the documentation? Maybe you where never supposed to do it the way I was with creatAsyncThunk in the first place?

EDIT:
On the issue of can you, I suppose you can just dispatch from a transferResponse in a query or mutation after its finished and then only have to call the function, and this to me seemed like the way you would be expected to use RTK Query, but no examples showed this or at least I did not see it in the docs, and maybe its best practice to keep fetching and state logic totally separate?

Body:
I built a project a little while ago using Redux Toolkit and CreateAsyncThunk. I am now working on a new project using RTK Query.

In the documentation for RTK Query:

Currently,  is specifically importing useSelector,
useDispatch, and useEffect, reading posts data and loading state from
the store, and dispatching the fetchPosts() thunk on mount to trigger
the data fetch. The useGetPostsQueryHook replaces all of that!

Now previously, I sometimes changed the global state directly in a CreateAsyncThunk.fulfilled

let user = sessionStorage.getItem("user");

const initialState: AuthState = {
  user: user ? user : null,
  message: "",
  isError: false,
  isLoading: false,
  isSuccess: false,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(Signin.pending, (state) => {
        state.isLoading = true;
        state.isError = false;
        state.isSuccess = false;
      })
      .addCase(Signin.fulfilled, (state, action) => {
        //updating the state of user as soon as creatAsyncThunk finishes no additional dispatch
        state.user = action.payload.RefreshToken;
        state.isLoading = false;
        state.isError = false;
        state.isSuccess = true;
      })
      .addCase(Signin.rejected, (state) => {
        state.isLoading = false;
        state.isError = true;
        state.isSuccess = false;
      });
  },
});

Where I need clarification is in an auth example for RTK query they use RTK query with dispatch, they just dispatch the result, is there no way and or is it just bad practice to change the global state from an RTK Query. (comments are my own)

 <Button
          isFullWidth
          onClick={async () => {
            try {
              //call use query
              const user = await login(formState).unwrap()
              //additional dispatch if you want to actually change the state in store
              dispatch(setCredentials(user))
              navigate('/')
            } catch (err) {
              toast({
                status: 'error',
                title: 'Error',
                description: 'Oh no, there was an error!',
                isClosable: true,
              })
            }
          }}
          colorScheme="green"
          isLoading={isLoading}
        >

Is the normal flow going to be dispatching the results of an RTK query and is there no way to have the RTK query itself change/update the state from the Query so that you are really getting rid of the use Dispatches like how I am understanding the original quote in the documentation? Maybe you where never supposed to do it the way I was with creatAsyncThunk in the first place?

EDIT:
On the issue of can you, I suppose you can just dispatch from a transferResponse in a query or mutation after its finished and then only have to call the function, and this to me seemed like the way you would be expected to use RTK Query, but no examples showed this or at least I did not see it in the docs, and maybe its best practice to keep fetching and state logic totally separate?


问:
Who doesn't show VSCode connections, why?

Question

I realized who command in Ubuntu 18.04 does not show VS Code connections.
But I can see VS Code connections at ss and ssh ports are in use.

Do you know why?

What have been done so far

sudo who

```<code>ubuntu   pts/0        2023-01-09 14:27 (${local_ip_1})
</code>```

ss

```<code>tcp    ESTAB    0         0        ${server_ip}:ssh        ${local_ip_1}:${port_1}
tcp    ESTAB    0         0        ${server_ip}:ssh        ${local_ip_2}:${port_2}
</code>```

What is Expected

```<code>$ sudo who
ubuntu   pts/0        2023-01-09 14:27 (${local_ip_1})
foo      pts/1        2023-01-09 14:27 (${local_ip_2})

</code>```

Body:
Question

I realized who command in Ubuntu 18.04 does not show VS Code connections.
But I can see VS Code connections at ss and ssh ports are in use.

Do you know why?

What have been done so far

sudo who

ubuntu   pts/0        2023-01-09 14:27 (${local_ip_1})

ss

tcp    ESTAB    0         0        ${server_ip}:ssh        ${local_ip_1}:${port_1}
tcp    ESTAB    0         0        ${server_ip}:ssh        ${local_ip_2}:${port_2}

What is Expected

$ sudo who
ubuntu   pts/0        2023-01-09 14:27 (${local_ip_1})
foo      pts/1        2023-01-09 14:27 (${local_ip_2})


问:
What is the advantage of using jsDelivr?
The getbootstrap.com docs include jsDelivr, stating:

Skip the download with jsDelivr to deliver cached version of Bootstrap’s compiled CSS and JS to your project.

According to https://www.jsdelivr.com/about :

jsDelivr is a public, open-source CDN (Content Delivery Network) developed by Dmitriy Akulov and Prospect One, focused on performance, reliability, and security. It is free to use for everyone, with no bandwidth limits.

I don't really understand what this means or how it compares to say, simply downloading with npm. Can anyone explain?


问:
How to integrate Stripe in a headless Bigcommerce checkout?
I used the Bigcommerce API docs (https://developer.bigcommerce.com/api-reference/d8c2da0790a85-checkouts) to create a headless checkout. Currently I can place an order via a test credit card. Now, in addition to credit card payments, I also want to accept iDeal/Giropay payments via Stripe. I can't find any documents on which agency to send to the process payment API for this and how to initiate a non-credit card Stripe payment.

I have tried to change the payment body to match with Stripe values, but this didn't work.
Working credit card example:
"payment": { "instrument": { "type": "card", "number": "4111111111111111", "cardholder_name": "John Doe", "expiry_month": 12, "expiry_year": 2027, "verification_value": "123" }, "payment_method_id": "stripeupe.card", amount: 12563, currency_code: "EUR" }


问:
Merging video and Audio using FFmpegKit in Flutter
I'm trying to merge video with audio using FFmpegKit.

I have given the command,
String command =
"-y -i ${file.path} -i ${result!.files.single.path} -map 0:v:0  -map 1:a:0 -c:v copy "
"-shortest ${appDirectory!.path}/output.mp4";
and it is working on only a specific mp3 available in my local. I don't know why it is not working with the other audios/mp3 files.
It would be a great assistance if you could.


问:
Copy text list to html table
I have a table on a form that is formatted like this:

```<code> <table id='leaderTable'>
      <tbody>
            <tr>
                <td> Name1</td><td> item1</td><td> item2</td> <td> item3</td><td> item4</td><td> item5</td>
    </tr>
            <tr>
                <td> Name2</td> <td> item1</td> <td> item2</td><td> item3</td><td> item4</td><td> item5</td>
    </tr>
    <tr>
        <td> Name3</td>

   -- etc. --
</code>```

I search for and find a given Name in col-1 of this table, extract the data from cells to the right of that found Name, and copy them to a list in a textArea (id=leaderInfoArea).

Then I want to edit this text and copy it back to the original table, replacing the old data.

I've got the first part working and can extract the data to the textArea, but now I'm stuck and I don't know how to get it back to the table.

Here's how I'm extracting each record from the html table.

```<code>function getLeaderData() { // match the Pod Leader's entered name on the form (leaderName) against each cell in col-1 of leaderTable
    let leaderInfoArea = document.getElementById('leaderInfoArea') ;
    let leaderName = document.getElementById('leaderName').value.trim();
    leaderName = leaderName.toLowerCase();
    leaderName = leaderName.replace( '.' , ' ').replace(/  +/g, ' ');

    let tab = document.getElementById('leaderTable');
        let tabRows = tab.rows;
        for (let i = 0; i < tabRows.length; i++) {
        let leaderNameCell = tabRows[i].cells[0];
        let nextLeaderName = leaderNameCell.innerText.trim();
        nextLeaderName = nextLeaderName.toLowerCase();
        nextLeaderName = nextLeaderName.replace.( '.' , ' ').replace(/  +/g, ' ');
        if (leaderName === nextLeaderName) {  //  if the names match, copy the data for this Pod Leader into leaderInfoArea, and exit
            leaderInfoArea.value = "";
            for (let j = 0; j < tabRows[i].cells.length;  j++) {
                leaderInfoArea.value += tabRows[i].cells[j].innerText + "\r";
    }
    return;
        }
    }
}
</code>```

leaderInfoArea now contains a list 6 lines high, although I can't get this editor to show that.

Name2
item1
item2
item3
item4
item5

Could someone please suggest how I can get this list back into the html table?

Title: Copy text list to html table

Body:
I have a table on a form that is formatted like this:

                 Name1	 item1	 item2	  item3	 item4	 item5

                 Name2	  item1	  item2	 item3	 item4	 item5

         Name3

   -- etc. --

I search for and find a given Name in col-1 of this table, extract the data from cells to the right of that found Name, and copy them to a list in a textArea (id=leaderInfoArea).

Then I want to edit this text and copy it back to the original table, replacing the old data.

I've got the first part working and can extract the data to the textArea, but now I'm stuck and I don't know how to get it back to the table.

Here's how I'm extracting each record from the html table.

function getLeaderData() { // match the Pod Leader's entered name on the form (leaderName) against each cell in col-1 of leaderTable
    let leaderInfoArea = document.getElementById('leaderInfoArea') ;
    let leaderName = document.getElementById('leaderName').value.trim();
    leaderName = leaderName.toLowerCase();
    leaderName = leaderName.replace( '.' , ' ').replace(/  +/g, ' ');

    let tab = document.getElementById('leaderTable');
        let tabRows = tab.rows;
        for (let i = 0; i < tabRows.length; i++) {
        let leaderNameCell = tabRows[i].cells[0];
        let nextLeaderName = leaderNameCell.innerText.trim();
        nextLeaderName = nextLeaderName.toLowerCase();
        nextLeaderName = nextLeaderName.replace.( '.' , ' ').replace(/  +/g, ' ');
        if (leaderName === nextLeaderName) {  //  if the names match, copy the data for this Pod Leader into leaderInfoArea, and exit
            leaderInfoArea.value = "";
            for (let j = 0; j < tabRows[i].cells.length;  j++) {
                leaderInfoArea.value += tabRows[i].cells[j].innerText + "\r";
    }
    return;
        }
    }
}

leaderInfoArea now contains a list 6 lines high, although I can't get this editor to show that.

Name2
item1
item2
item3
item4
item5

Could someone please suggest how I can get this list back into the html table?


问:
How do I get realtime audio from android
I am trying to analyze internal audio from android system to know wave amplitude of the sound that is being played at the moment. I start playing the audio on the device and after more or less four seconds the apps gets the sound that was playing. I think that the problem could start with the priority of my app on the system that cannot get audio on real time or closer to it.

I am using the AudioRecord from android

```<code>      internalRecorder = AudioRecord.Builder()
        .setAudioFormat(audioFormat)
        .setBufferSizeInBytes(124800)
        .setAudioPlaybackCaptureConfig(config)
        .build()
</code>```

and the config:

```<code>val config = AudioPlaybackCaptureConfiguration.Builder(mediaProjection!!)
        .addMatchingUsage(AudioAttributes.USAGE_MEDIA)
        .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
        .addMatchingUsage(AudioAttributes.USAGE_GAME)
        .build()
</code>```

I have tried to make an accessibility service but this not improve the performance. The audio buffer is having seconds of delay.

Body:
I am trying to analyze internal audio from android system to know wave amplitude of the sound that is being played at the moment. I start playing the audio on the device and after more or less four seconds the apps gets the sound that was playing. I think that the problem could start with the priority of my app on the system that cannot get audio on real time or closer to it.

I am using the AudioRecord from android

      internalRecorder = AudioRecord.Builder()
        .setAudioFormat(audioFormat)
        .setBufferSizeInBytes(124800)
        .setAudioPlaybackCaptureConfig(config)
        .build()

and the config:

val config = AudioPlaybackCaptureConfiguration.Builder(mediaProjection!!)
        .addMatchingUsage(AudioAttributes.USAGE_MEDIA)
        .addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
        .addMatchingUsage(AudioAttributes.USAGE_GAME)
        .build()

I have tried to make an accessibility service but this not improve the performance. The audio buffer is having seconds of delay.


问:
Getting FileAttribute error for files stored on my Mac
I am trying to show a list of files from my computer using a server app that uses the IP address and you can look for a file from the phone.

I am fetching files successfully, but I have a problem with showing the size and creation date of files. This works fine on the iOS simulator!!! but on the real device, I am getting this error for each file:

FileAttribute error: Error Domain=NSCocoaErrorDomain Code=260 "The
file “office-decor.jpg” couldn’t be opened because there is no such
file."
UserInfo={NSFilePath=/Users/username/Desktop/My%20office%20stuff/office-decor.jpg,
NSUnderlyingError=0x281e279c0 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}

I have created an URL extension to show date, size:

```<code>extension URL {
    var attributes: [FileAttributeKey : Any]? {
        do {
            return try FileManager.default.attributesOfItem(atPath: path)
        } catch let error as NSError {
            print("FileAttribute error: \(error)")
        }
        return nil
    }

    var fileSize: UInt64 {
        return attributes?[.size] as? UInt64 ?? UInt64(0)
    }

    var fileSizeString: String {
        return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
    }

    var creationDate: Date? {
        return attributes?[.creationDate] as? Date
    }
}
</code>```

my file path is something like this:

```<code>Users/username/Desktop/xxx.jpg
</code>```

and trying to get the file path using URL like this to get the file size:

```<code>private var fileSize: String {
        guard let url = URL(string: path.addURLEncoding()) else { return "-" }
        return url.fileSizeString
    }

extension String {
    func addURLEncoding() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    }
}
</code>```

I also tried file:// and URL(filePath...), URL(fileURLWithPath  but still get that error on the device, which is working totally fine on simulator. Any idea how to fix that?

Body:
I am trying to show a list of files from my computer using a server app that uses the IP address and you can look for a file from the phone.

I am fetching files successfully, but I have a problem with showing the size and creation date of files. This works fine on the iOS simulator!!! but on the real device, I am getting this error for each file:

FileAttribute error: Error Domain=NSCocoaErrorDomain Code=260 "The
file “office-decor.jpg” couldn’t be opened because there is no such
file."
UserInfo={NSFilePath=/Users/username/Desktop/My%20office%20stuff/office-decor.jpg,
NSUnderlyingError=0x281e279c0 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}

I have created an URL extension to show date, size:

extension URL {
    var attributes: [FileAttributeKey : Any]? {
        do {
            return try FileManager.default.attributesOfItem(atPath: path)
        } catch let error as NSError {
            print("FileAttribute error: \(error)")
        }
        return nil
    }

    var fileSize: UInt64 {
        return attributes?[.size] as? UInt64 ?? UInt64(0)
    }

    var fileSizeString: String {
        return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)
    }

    var creationDate: Date? {
        return attributes?[.creationDate] as? Date
    }
}

my file path is something like this:

Users/username/Desktop/xxx.jpg

and trying to get the file path using URL like this to get the file size:

private var fileSize: String {
        guard let url = URL(string: path.addURLEncoding()) else { return "-" }
        return url.fileSizeString
    }

extension String {
    func addURLEncoding() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
    }
}

I also tried file:// and URL(filePath...), URL(fileURLWithPath  but still get that error on the device, which is working totally fine on simulator. Any idea how to fix that?


问:
Creating an audio visualizer in Flutter for web
I'm currently trying to create an audioplayer in Flutter Web, which is also able to visualize the bytefrequencydata. I already built this app in Angular but i just don't know how to access the data via audiocontext like in js.
I searched many libraries but none seems to provide the option to create an analyser node,

There is the standard dart:web_audio lib, but I can't use that in Flutter.
I am getting really desperate since there is also not a single tutorial to find which shows how to build such an app for flutter web, or at least I can't seem to find one.
The app only needs to run for flutter web.

A little help to get me on the right tracks would be much appreciated.